Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(audio): a sound or a piece of music can ship as its recipe - an .essound or .esmusic named where a clip goes is carried as its source and made on the device when it loads, by the synthesis the editor bakes it with, on a worker and kept in the content cache; a game of five clips packaged 1.7 MB lighter

yhh0c7ecd0e9f18
diff --git a/CHANGELOG.md b/CHANGELOG.md
index da0ad5ef4..476ff3e3f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,9 +28,13 @@ published separately; it ships inside the editor.
- **A joint that gives way.** Every 3D joint takes a `breakForce` (N) and `breakTorque` (N m): held with more than either over a step, it is taken out of the world, its `enabled` lowered, and the break told in `Physics3DEvents.jointBreaks`, so a chandelier comes down when its mount is pulled harder than it holds. A 2 kg weight hanging on a rope pulls on it with 19.62 N in both worlds; in the editor a rope rated at 15 N gave way and its weight fell to the floor while one rated at 30 N held.
- **A character that runs into something says so.** `Physics3DEvents.characterHits` tells what a 3D character ran into that it was not already touching, once a meeting, with how fast it closed, the mass they met with and the impulse, as a contact between bodies does; a `Breakable` a character runs into is struck with it, so a dive through a window breaks it and a lean on it does not. A character dropped 2.1 m onto a floor told it once, at 6.38 m/s against the 6.42 the fall gives and with its own 70 kg, and walking into a 30 kg crate at 3 m/s met it with 21 kg, in both worlds.
- **Telling the parts of a character apart.** `Hitboxes` puts a box on each bone of a skinned character, the size its ragdoll would give it, that follows the animation: a kinematic sensor that nothing walks into or is pushed by and that a ray meets, so a shot names the bone it struck and `hitPartOf` says whose. While the ragdoll is limp its own bodies stand in. In the editor a character from the character-rig example given `Hitboxes` had a sensor box on each of its bones, a ray at one of them met that character's bone by name, and three quarters of a second of animation later a ray where the bone had gone still met it.
+- **A sound or a piece of music can ship as its recipe.** A package shipped every sample of every clip, compressed. An `.essound` or an `.esmusic` (the source the sound and music tools write, which until now only the editor read) named where a clip goes is carried as it is and made on the device when it loads, by the same synthesis the editor bakes it with: `AudioSource.clip`, `Audio.playSFX` and `Audio.playBGM` take the path of the source. It is made on a worker thread, a piece of music on one and sound effects on another so a step is never made behind a theme, and kept in the content cache, so a later run reads it back. Importing `esengine/sound` installs the maker, and an export adds it when a shipped asset is one. A game of four effects and a minute of music packaged 1.7 MB lighter; on a desktop its effects were ready 2.5 s after the page opened and its music after 7.6 s, the first time only. A sound with variants is made as its first, and a backend that plays from an address and not from bytes cannot play one yet.
+- **A picture made in the editor is named by its recipe.** `image_write` answered the `.png` it had drawn, and the material it wrote named its maps as `.png` files, so a game built from what the tool answered shipped pixels although the engine could draw them from a few hundred bytes. It answers the `.esimage` as `ref` and as the texture of `meshRenderer` now, the material it writes names its maps as recipes, and the drawn file is `pngRef`. The game the editor plays draws recipes as the edit view does.
### Fixed
+- **A package that ships texture recipes draws them.** An export carried its `.esimage` files and drew its ground and its walls with no texture, saying only in the console that nothing there draws recipes. The call that installs the drawer had ended up in a part of the built SDK that was not marked as having an effect, and the bundler dropped it; and a playable ad, whose entry is the whole SDK, never imported the drawer at all. Both are put right, and a check now bundles a game that imports it and looks for it.
+- **A cleared asset field no longer stops a game.** An empty string in an asset field of an engine component (a material cleared to nothing) was taken for a path to load, came back from the load still a string, was written back as one and asked for again, without end: a field of plants put it on every cell it grew, and the packaged game stopped answering half a minute in. An empty string is no asset now, and a path nothing resolves keeps its placeholder.
- **A Jolt hinge or slider whose motor is switched on in play keeps its limit.** Made with its motor off, a joint in the Jolt world took the solver's own motor settings when the motor was turned on later, which push without bound, so a door with a `maxMotorTorque` of 10 opened as if it had none, where the PhysX world held it to 10. Both now hold every motor to its limit from the start: switched on with a limit of nothing, a door turns nothing in either.
## [0.104.1] - 2026-11-13
diff --git a/pipeline/src/assets/addressableManifest.ts b/pipeline/src/assets/addressableManifest.ts
index 3cbc4ed72..03bfece24 100644
--- a/pipeline/src/assets/addressableManifest.ts
+++ b/pipeline/src/assets/addressableManifest.ts
@@ -39,6 +39,8 @@ interface FlatManifest {
const ADDRESSABLE_TYPE: Record<string, string> = {
// A picture's source ships as a texture that is drawn where it loads (a recipe): an image to whatever loads it, never one to the cook.
texture: 'texture', imageSource: 'texture', material: 'material', audio: 'audio', 'bitmap-font': 'bitmap-font',
+ // A sound's source ships as a clip that is made where it loads, as a picture's ships as a texture.
+ soundSource: 'audio', musicSource: 'audio',
prefab: 'prefab', spine: 'spine',
scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', 'sound-event': 'json', 'world-rules': 'json', 'terrain-layer': 'json', 'terrain-tiles': 'json', shader: 'text',
};
diff --git a/pipeline/src/assets/assetDb.ts b/pipeline/src/assets/assetDb.ts
index a38e28698..c89c67e12 100644
--- a/pipeline/src/assets/assetDb.ts
+++ b/pipeline/src/assets/assetDb.ts
@@ -240,6 +240,8 @@ const JSON_REF_TYPES = new Set([
]);
const isTextureRecipe = (e: { type: string; path: string }): boolean => e.type === 'imageSource' && e.path.toLowerCase().endsWith('.esimage');
+/** A clip that is a recipe names the recordings it plays (a sampled instrument's notes, a sample layer's file). */
+const isAudioRecipe = (e: { type: string }): boolean => e.type === 'soundSource' || e.type === 'musicSource';
/**
* Collect every asset reference in a JSON document:
@@ -378,7 +380,7 @@ async function computeDeps(
const uuids = new Set(entries.map((e) => e.uuid));
const refEntries = (targets ?? entries).filter(
// A texture that is a recipe names what it is drawn from: the pictures it lays in, its font files, the picture it is a map of.
- (e) => JSON_REF_TYPES.has(e.type) || e.type === BITMAP_FONT || e.type === 'mesh' || isTextureRecipe(e)
+ (e) => JSON_REF_TYPES.has(e.type) || e.type === BITMAP_FONT || e.type === 'mesh' || isTextureRecipe(e) || isAudioRecipe(e)
|| SKELETAL_ATLAS_TYPES.has(getEditorType(e.path)),
);
type DepResult = { uuid: string; refs: string[] } | { warning: string };
diff --git a/pipeline/src/bundle/engineInstalls.ts b/pipeline/src/bundle/engineInstalls.ts
index 64e64e48e..9340bc5c2 100644
--- a/pipeline/src/bundle/engineInstalls.ts
+++ b/pipeline/src/bundle/engineInstalls.ts
@@ -26,6 +26,9 @@ const ASSET_SUBPATH: Readonly<Record<string, string>> = {
'.esgraph': 'esengine/logic',
// A picture's source that ships is a texture drawn on the device (sdk asset/textureRecipe.ts).
'.esimage': 'esengine/image',
+ // A clip named by its source is made where it loads, as a texture named by its recipe is drawn.
+ '.essound': 'esengine/sound',
+ '.esmusic': 'esengine/sound',
'.esanimator': 'esengine/skeletal-animation',
'.esavatar': 'esengine/skeletal-animation',
'.estimeline': 'esengine/timeline',
diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.ts
index aaaadf02e..ff5fd48dc 100644
--- a/pipeline/src/bundle/engineSubpaths.ts
+++ b/pipeline/src/bundle/engineSubpaths.ts
@@ -23,6 +23,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {
'esengine/water': 'water/index.js',
'esengine/spline': 'spline/index.js',
'esengine/image': 'image/index.js',
+ 'esengine/sound': 'sound/index.js',
'esengine/voxel': 'voxel/index.js',
'esengine/rig2d': 'rig2d/index.js',
'esengine/imported-scene': 'imported-scene/index.js',
diff --git a/pipeline/src/music/musicRender.ts b/pipeline/src/music/musicRender.ts
index 89163fedb..2e79773ba 100644
--- a/pipeline/src/music/musicRender.ts
+++ b/pipeline/src/music/musicRender.ts
@@ -1,659 +1,4 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file musicRender.ts — a music source worked out into the notes it plays, and the notes into samples.
- *
- * Two steps, and the first is worth having on its own: `compileMusic` turns patterns of steps into notes with a
- * time, a length and a pitch, which is what a picture of the piece is drawn from and what can be checked without
- * hearing anything. `renderMusic` then strikes each instrument's layers once for every note (soundRender.ts) and
- * sums them, each instrument on its own bus so the buses can be written out apart.
- *
- * A piece that loops is not faded into itself: what rings past its end is added to its start, which is what
- * would be heard had it been playing round already.
- */
-import { fft } from '../sound/soundPicture';
-import { placeResponse, renderSound } from '../sound/soundRender';
-import type { SoundLayer } from '../sound/soundSource';
-import { midiOf, musicSeconds, parseTrack, SCALES, tonicOf, type MusicInstrument, type MusicSource } from './musicSource';
-
-/** A recording as samples: what an instrument made of recordings plays from. */
-export interface SampleData { rate: number; channels: readonly Float32Array[] }
-
-export interface MusicEvent {
- instrument: string;
- /** Seconds from the start of the piece, and how long it is held. */
- at: number;
- seconds: number;
- /** The note, 60 being middle C; null for an instrument struck at its own pitch. */
- midi: number | null;
- loud: number;
- /** Which part of the song it is in. */
- part: number;
- /** Written with # or b: outside the key. */
- outside: boolean;
- /** Softer (-1) or louder (1) than the rest by its mark and by where it lies in the dynamics; 0 for neither. */
- mark: -1 | 0 | 1;
- /** How loud it is written, by its mark and the dynamics, before the hand's unevenness. */
- hard: number;
- /** How long it sounds, where that is longer than it is written: held on by the pedal to the end of its bar. */
- sounds?: number;
- /** It comes in under the note before it and is not struck afresh. */
- slur?: boolean;
- /** The note after it comes in under it, and it stays a moment longer for that. */
- tied?: boolean;
-}
-
-export interface CompiledMusic {
- seconds: number;
- barSeconds: number;
- events: MusicEvent[];
- parts: { pattern: string; at: number; bars: number }[];
- notes: string[];
-}
-
-export interface RenderedMusic extends CompiledMusic {
- rate: number;
- /** Left, right. */
- channels: Float32Array[];
- peak: number;
- rms: number;
- /** For a loop with an introduction: seconds into the file that it comes back to. 0 where the whole of it goes round. */
- loopStart: number;
- /** For a piece that ends: seconds it rings on after its last bar, which the file is longer by. */
- tailSeconds: number;
- /** For a loop: what sounds in its last bar and in its first, and how loud each is, in decibels beside the whole. Null for a piece that ends. */
- join: { ends: string[]; begins: string[]; endDb: number; startDb: number } | null;
- /** Each instrument alone, when the source asks for stems: they add up to `channels`. */
- stems: Record<string, Float32Array[]> | null;
- /** What each instrument played, and how loud it is beside the whole, in decibels. */
- instruments: Record<string, { notes: number; low?: string; high?: string; levelDb: number }>;
-}
-
-const NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
-export const noteName = (midi: number): string => `${NOTE_NAMES[((midi % 12) + 12) % 12]}${Math.floor(midi / 12) - 1}`;
-
-function randomOf(seed: number): () => number {
- let s = (seed * 2654435761 + 0x9e3779b9) >>> 0;
- return () => {
- s = (s + 0x6d2b79f5) >>> 0;
- let t = s;
- t = Math.imul(t ^ (t >>> 15), t | 1);
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
- return ((t ^ (t >>> 14)) >>> 0) / 2147483648 - 1;
- };
-}
-
-/** The notes a validated source plays, in the order they begin. */
-export function compileMusic(source: MusicSource): CompiledMusic {
- const beats = source.beats ?? 4;
- const barSeconds = (beats * 60) / source.tempo;
- const scale = SCALES[source.scale ?? 'minor'];
- const tonic = tonicOf(source.key);
- const human = source.humanize ?? 0.15;
- const random = randomOf(source.seed ?? 1);
- const events: MusicEvent[] = [];
- const parts: CompiledMusic['parts'] = [];
- const notes: string[] = [];
- const said = new Set<string>();
- const say = (text: string): void => { if (!said.has(text)) { said.add(text); notes.push(text); } };
- const played = new Set<string>();
- const used = new Set<string>();
- let at = 0;
-
- source.song.forEach((part, p) => {
- const name = typeof part === 'string' ? part : part.pattern;
- const pattern = source.patterns[name]!;
- used.add(name);
- parts.push({ pattern: name, at, bars: pattern.bars });
- const div = pattern.div ?? 4;
- const stepsToBar = beats * div;
- const step = barSeconds / stepsToBar;
- const before = events.length;
- for (const [track, line] of Object.entries(pattern.tracks)) {
- if (typeof part !== 'string' && (part.without?.includes(track) || (part.only && !part.only.includes(track)))) continue;
- const instrument = source.instruments[track]!;
- if (instrument.follow && !pattern.chords) say(`"${track}" follows the chords, and pattern "${name}" has none: it plays every bar on chord 1`);
- const steps = parseTrack(line, pattern.bars, stepsToBar, `pattern "${name}", track "${track}"`, SCALES[instrument.scale ?? source.scale ?? 'minor'].length);
- // Time that gives: late at the start of the phrase, made up through its middle, late again toward its end,
- // and back where it was on the last bar line, so the pattern is as long as it was written.
- const phrase = pattern.bars * barSeconds;
- const give = ((source.rubato ?? 0) * 0.08 * phrase) / (2 * Math.PI);
- const timed = (t: number): number => t + give * Math.sin((2 * Math.PI * t) / phrase);
- // How loud the line is at each step: between the number its bar begins on and the next bar's.
- const levels = pattern.dynamics?.[track] ?? pattern.dynamics?.all;
- const levelAt = (i: number): number => {
- if (!levels) return 1;
- const bar = i / stepsToBar;
- const [a, b] = [levels[Math.min(Math.floor(bar), levels.length - 1)]!, levels[Math.min(Math.floor(bar) + 1, levels.length - 1)]!];
- return a + (b - a) * (bar - Math.floor(bar));
- };
- // The last single note of this line, and the step it ends on: what a note that follows straight on is slurred from.
- let before: { end: number; event: MusicEvent } | null = null;
- for (let i = 0; i < steps.length; i++) {
- const s = steps[i]!;
- if (s.kind === 'hold' && (i === 0 || steps[i - 1]!.kind === 'rest')) say(`pattern "${name}", track "${track}": a "-" at step ${(i % stepsToBar) + 1} of bar ${Math.floor(i / stepsToBar) + 1} has no note before it to hold, and is silent`);
- if (s.kind !== 'hit' && s.kind !== 'notes') continue;
- let held = 1;
- while (i + held < steps.length && steps[i + held]!.kind === 'hold') held++;
- // Every second step late, which is what makes a line swing.
- const late = div % 2 === 0 && i % 2 === 1 ? (source.swing ?? 0) * step : 0;
- const when = Math.max(0, at + timed(i * step + late) + human * 0.012 * random());
- const written = timed((i + held) * step) - timed(i * step);
- const hard = s.loud * levelAt(i);
- const loud = hard * (1 + human * 0.25 * random());
- const mark = hard > 1.15 ? 1 : hard < 0.8 ? -1 : 0;
- // The pedal is down to the end of the bar: the note rings on to there.
- const toBarEnd = timed((Math.floor(i / stepsToBar) + 1) * stepsToBar * step) - timed(i * step);
- const sounds = instrument.pedal && toBarEnd > written + 1e-9 ? { sounds: toBarEnd } : {};
- played.add(track);
- if (s.kind === 'hit') {
- events.push({ instrument: track, at: when, seconds: written, midi: null, loud, part: p, outside: false, mark, hard, ...sounds });
- before = null;
- continue;
- }
- // One note running straight on from one note, and not struck harder: in the same breath.
- const slurred = !!instrument.legato && s.notes.length === 1 && before !== null && before.end === i && s.loud <= 1;
- if (slurred) before!.event.tied = true;
- const chord = instrument.follow && pattern.chords ? pattern.chords[Math.floor(i / stepsToBar) % pattern.chords.length]! : 1;
- // A root in the upper part of the scale (5, 6 or 7 of seven; 4 or 5 of five) is taken below the tonic, so the
- // chords lie round it and a bass does not climb away.
- // The instrument's own scale where it has one: the same tonic, other notes.
- const own = instrument.scale ? SCALES[instrument.scale] : scale;
- const size = own.length;
- const drop = chord > size / 2 + 1 ? -size : 0;
- for (const n of s.notes) {
- const index = n.degree - 1 + chord - 1 + drop + size;
- const midi = 60 + tonic + own[index % size]! + 12 * (Math.floor(index / size) - 1 + n.octave + (instrument.octave ?? 0)) + n.alter;
- events.push({ instrument: track, at: when, seconds: written, midi, loud, part: p, outside: n.alter !== 0, mark, hard, ...sounds, ...(slurred ? { slur: true } : {}) });
- }
- before = s.notes.length === 1 ? { end: i + held, event: events.at(-1)! } : null;
- }
- }
- if (events.length === before) notes.push(`part ${p + 1} of the song ("${name}") plays nothing`);
- at += pattern.bars * barSeconds;
- });
-
- for (const name of Object.keys(source.instruments)) if (!played.has(name)) notes.push(`instrument "${name}" is never played`);
- for (const name of Object.keys(source.patterns)) if (!used.has(name)) notes.push(`pattern "${name}" is not in the song`);
-
- // What can be said of the notes without hearing them.
- const pitched = new Map<string, MusicEvent[]>();
- for (const e of events) if (e.midi !== null) pitched.set(e.instrument, [...(pitched.get(e.instrument) ?? []), e]);
- const middle = new Map<string, number>();
- for (const [name, list] of pitched) {
- const sorted = list.map((e) => e.midi!).sort((a, b) => a - b);
- middle.set(name, sorted[Math.floor(sorted.length / 2)]!);
- if (sorted[0]! < 24) notes.push(`"${name}" goes down to ${noteName(sorted[0]!)}, below where a pitch can be told: raise its octave`);
- if (sorted.at(-1)! > 100) notes.push(`"${name}" goes up to ${noteName(sorted.at(-1)!)}, which is a whistle: lower its octave`);
- const outside = list.filter((e) => e.outside).length;
- if (outside > 0) notes.push(`"${name}" plays ${outside} note${outside === 1 ? '' : 's'} outside the key`);
- }
- const names = [...pitched.keys()];
- for (let a = 0; a < names.length; a++) for (let b = a + 1; b < names.length; b++) {
- const [x, y] = [pitched.get(names[a]!)!, pitched.get(names[b]!)!];
- if (Math.abs(middle.get(names[a]!)! - middle.get(names[b]!)!) > 4) continue;
- // How much of the time the less busy of the two sounds, the other is sounding too.
- const length = (list: MusicEvent[]): number => list.reduce((sum, e) => sum + e.seconds, 0);
- let both = 0;
- for (const e of x) for (const f of y) both += Math.max(0, Math.min(e.at + e.seconds, f.at + f.seconds) - Math.max(e.at, f.at));
- if (both > 0.5 * Math.min(length(x), length(y))) notes.push(`"${names[a]}" and "${names[b]}" sound together in the same octave, round ${noteName(middle.get(names[a]!)!)}, and will blur into one: move one of them an octave`);
- }
-
- events.sort((a, b) => a.at - b.at);
- return { seconds: musicSeconds(source), barSeconds, events, parts, notes };
-}
-
-/** How far past its own start a layer can still be sounding, when a held note lasts @p held seconds. */
-function reach(layer: SoundLayer, held: number): number {
- const again = layer.scatter ? layer.scatter.over : layer.repeat ? (layer.repeat.count - 1) * layer.repeat.every : 0;
- const own = layer.source === 'group' ? Math.max(0, ...layer.layers!.map((l) => reach(l, held))) : layer.length ?? held;
- return (layer.start ?? 0) + again + own;
-}
-
-/** A layer with no length of its own lasts as long as the note, and dies over the instrument's release. */
-function forNote(layer: SoundLayer, held: number, release: number, slur = 0): SoundLayer {
- if (layer.source === 'group') return { ...layer, layers: layer.layers!.map((l) => forNote(l, held, release, slur)) };
- // A layer with a length of its own is the knock at the front of a note, which a slurred note has none of.
- if (layer.length !== undefined) return slur > 0 ? { ...layer, mute: true } : layer;
- return { ...layer, length: Math.max(0.01, held + release - (layer.start ?? 0)), release: layer.release ?? release, ...(slur > 0 ? { attack: Math.max(layer.attack ?? 0, slur) } : {}) };
-}
-
-/**
- * One note of an instrument made of recordings: the recording nearest the note, played faster to be higher or slower
- * to be lower, let go over the release. A recording an octave from its note is another instrument, which is why there
- * are several; within three semitones the ear takes it for the same one.
- */
-const HARDNESS = { soft: -1, normal: 0, loud: 1 } as const;
-
-/**
- * Which of an instrument's recordings plays a note. First by how hard: the recordings made as hard as the note is
- * marked, or failing those the nearest in hardness. Then by pitch: the ones whose range holds the note, or failing
- * those the nearest. And where several are left that are the same note, they take turns, so the same key struck
- * four times is not one recording four times.
- */
-export function sampleZone(instrument: MusicInstrument, midi: number | null, mark: number, turn: number): { index: number; matched: boolean } {
- const zones = instrument.samples!;
- const hard = (i: number): number => HARDNESS[zones[i]!.dynamic ?? 'normal'];
- let left = zones.map((_, i) => i);
- const nearest = Math.min(...left.map((i) => Math.abs(hard(i) - mark)));
- left = left.filter((i) => Math.abs(hard(i) - mark) === nearest);
- const matched = nearest === 0 && mark !== 0;
- if (midi !== null) {
- const ranged = left.filter((i) => (zones[i]!.low !== undefined || zones[i]!.high !== undefined) && midi >= (midiOf(zones[i]!.low) ?? 0) && midi <= (midiOf(zones[i]!.high) ?? 127));
- if (ranged.length) left = ranged;
- const far = Math.min(...left.map((i) => Math.abs(midiOf(zones[i]!.note)! - midi)));
- left = left.filter((i) => Math.abs(midiOf(zones[i]!.note)! - midi) === far);
- // Of two as near, one above and one below, the turn must not swap them: only recordings of one note take turns.
- left = left.filter((i) => midiOf(zones[i]!.note) === midiOf(zones[left[0]!]!.note));
- } else left = [left[0]!];
- return { index: left[turn % left.length]!, matched };
-}
-
-function sampleNote(name: string, instrument: MusicInstrument, index: number, midi: number | null, held: number, rate: number, given: Readonly<Record<string, SampleData>>, slur = 0): Float32Array[] {
- const zone = instrument.samples![index]!;
- const data = given[zone.file];
- if (!data) throw new Error(`instrument "${name}": the recording ${zone.file} was not found`);
- const frames = data.channels[0]!.length;
- const step = (midi === null ? 1 : Math.pow(2, (midi - midiOf(zone.note)! - (zone.tune ?? 0) / 100) / 12)) * (data.rate / rate);
- // Slurred, it is not the start of the recording that is wanted, which is the bow biting or the breath beginning,
- // but what comes after; and it comes in over the time the note before takes to go.
- const skip = slur > 0 ? Math.min(0.12 * data.rate, frames * 0.25) : 0;
- const [attack, release] = [slur > 0 ? slur : instrument.attack ?? 0.003, instrument.release ?? 0.08];
- // Round its steady middle, or the seconds given, with the end of each turn faded into the start of the next.
- let [from, to] = [0, 0];
- if (zone.loop) {
- [from, to] = zone.loop === true ? [frames * 0.4, frames * 0.85] : [zone.loop[0] * data.rate, Math.min(frames - 2, zone.loop[1] * data.rate)];
- }
- const round = to - from;
- const fade = round > 0 ? Math.min(0.12 * data.rate, round / 3, from) : 0;
- const count = Math.max(1, Math.round(Math.min(held + release, round > 0 ? 30 : (frames - 2 - skip) / step / rate) * rate));
- const at = (channel: Float32Array, p: number): number => {
- // Through four points, so a note played slower is not a staircase.
- const i = Math.floor(p), t = p - i;
- const [a, b, c, d] = [channel[i - 1] ?? channel[i]!, channel[i]!, channel[i + 1] ?? 0, channel[i + 2] ?? 0];
- return b + 0.5 * t * (c - a + t * (2 * a - 5 * b + 4 * c - d + t * (3 * (b - c) + d - a)));
- };
- const out = data.channels.slice(0, 2).map(() => new Float32Array(count));
- const letGo = Math.round(held * rate);
- const ending = Math.min(count, Math.round(0.005 * rate));
- for (let n = 0; n < count; n++) {
- let p = skip + n * step;
- let blend = 0;
- if (round > 0 && p >= to - fade) {
- p = from + ((p - from) % round);
- if (fade > 0 && p >= to - fade) blend = (p - (to - fade)) / fade;
- }
- let level = n < attack * rate ? n / (attack * rate) : 1;
- if (n > letGo) level *= Math.max(0, 1 - (n - letGo) / Math.max(1, release * rate));
- if (count - n < ending) level *= (count - n) / ending;
- for (let c = 0; c < out.length; c++) {
- const channel = data.channels[c]!;
- out[c]![n] = (blend > 0 ? at(channel, p) * (1 - blend) + at(channel, p - round) * blend : at(channel, p)) * level * (zone.gain ?? 1);
- }
- }
- // Duller than it was recorded, where the sample says so: at a fixed place, whatever the note.
- if (zone.cutoff && zone.cutoff < rate * 0.45) for (const channel of out) filtered(channel, 'lowpass', zone.cutoff, rate);
- return out;
-}
-
-/**
- * The pitch heard in a recording, in Hz, looked for within two octaves of @p near; null where it has none that can be
- * told (a drum, a noise). It is found by how far the wave has to be slid to lie on itself again. A wave lies on itself
- * at twice its period too, so the shortest slide that fits nearly as well as the best is taken: that is what tells a
- * recording named an octave from what it is, which libraries that count octaves from another C are throughout.
- */
-export function samplePitch(data: SampleData, near: number): number | null {
- const samples = data.channels[0]!;
- const longest = Math.ceil(data.rate / (near / 2.1));
- const start = Math.floor(samples.length * 0.25);
- const size = Math.min(16384, samples.length - start - longest);
- if (size < longest * 2) return null;
- const scores: [number, number][] = [];
- for (let lag = Math.max(8, Math.floor(data.rate / (near * 4.2))); lag <= longest; lag++) {
- let sum = 0, a = 0, b = 0;
- for (let n = 0; n < size; n += 2) { const x = samples[start + n]!, y = samples[start + n + lag]!; sum += x * y; a += x * x; b += y * y; }
- scores.push([lag, sum / Math.sqrt(a * b + 1e-12)]);
- }
- const top = Math.max(...scores.map((score) => score[1]));
- if (!(top > 0.6)) return null;
- let at = scores.findIndex((score) => score[1] >= top * 0.92);
- while (at + 1 < scores.length && scores[at + 1]![1] > scores[at]![1]) at++;
- // A high note in a recording made at a low rate has a period of a dozen samples and a half: no whole slide fits
- // it, and twice the period, which is whole, fits better. So a half and a third of the slide found are tried too,
- // between the samples, and the shortest that fits nearly as well is the pitch.
- const fits = (lag: number): number => {
- let sum = 0, a = 0, b = 0;
- const whole = Math.floor(lag), part = lag - whole;
- for (let n = 0; n < size; n += 2) {
- const x = samples[start + n]!, y = samples[start + n + whole]! * (1 - part) + samples[start + n + whole + 1]! * part;
- sum += x * y; a += x * x; b += y * y;
- }
- return sum / Math.sqrt(a * b + 1e-12);
- };
- let lag = scores[at]![0];
- // Just off the whole number, a little either side, where the fit is best.
- const best = (centre: number): [number, number] => { let found: [number, number] = [centre, -1]; for (let d = -0.5; d <= 0.5; d += 0.05) { const f = fits(centre + d); if (f > found[1]) found = [centre + d, f]; } return found;
- };
- let [fine, fit] = best(lag);
- for (const part of [3, 2]) {
- if (lag / part < 4 || data.rate / (lag / part) > near * 4.2) continue;
- const [shorter, shorterFit] = best(lag / part);
- if (shorterFit >= fit * 0.9) { [fine, fit] = [shorter, shorterFit]; break; }
- }
- lag = fine;
- return data.rate / lag;
-}
-
-type Shape = 'lowpass' | 'highpass' | 'lowshelf' | 'highshelf';
-
-/** A two-pole filter run over @p channel where it lies: a cut above or below @p hz, or a shelf of @p db there. */
-function filtered(channel: Float32Array, shape: Shape, hz: number, rate: number, db = 0): void {
- const w = (2 * Math.PI * Math.min(hz, rate * 0.45)) / rate;
- const [cos, sin] = [Math.cos(w), Math.sin(w)];
- let b0: number, b1: number, b2: number, a0: number, a1: number, a2: number;
- if (shape === 'lowpass' || shape === 'highpass') {
- const alpha = sin / (2 * Math.SQRT1_2);
- [b0, b1, b2] = shape === 'lowpass' ? [(1 - cos) / 2, 1 - cos, (1 - cos) / 2] : [(1 + cos) / 2, -(1 + cos), (1 + cos) / 2];
- [a0, a1, a2] = [1 + alpha, -2 * cos, 1 - alpha];
- } else {
- const A = Math.pow(10, db / 40);
- const beta = 2 * Math.sqrt(A) * (sin / 2) * Math.SQRT2;
- const sign = shape === 'lowshelf' ? 1 : -1;
- b0 = A * (A + 1 - sign * (A - 1) * cos + beta);
- b1 = sign * 2 * A * (A - 1 - sign * (A + 1) * cos);
- b2 = A * (A + 1 - sign * (A - 1) * cos - beta);
- a0 = A + 1 + sign * (A - 1) * cos + beta;
- a1 = -sign * 2 * (A - 1 + sign * (A + 1) * cos);
- a2 = A + 1 + sign * (A - 1) * cos - beta;
- }
- let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
- for (let n = 0; n < channel.length; n++) {
- const x = channel[n]!;
- const y = (b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2) / a0;
- x2 = x1; x1 = x; y2 = y1; y1 = y;
- channel[n] = y;
- }
-}
-
-/**
- * How much each moment of a mix is to be held down: 1 where it is quiet, less where it is loud. The loudness is
- * followed quickly up and slowly down, as an ear follows it, and what is over the line is let through at a share of
- * what it is over by. Worked out from the whole and laid on every instrument alike, so they still add up to it.
- */
-function compression(channels: readonly Float32Array[], rate: number, amount: number, round: boolean): Float32Array {
- const frames = channels[0]!.length;
- let peak = 0;
- for (const c of channels) for (const v of c) if (Math.abs(v) > peak) peak = Math.abs(v);
- const gains = new Float32Array(frames).fill(1);
- if (!(peak > 1e-6) || amount <= 0) return gains;
- const line = peak * Math.pow(10, -(6 + 14 * amount) / 20);
- const ratio = 1.5 + 2.5 * amount;
- const [up, down] = [Math.exp(-1 / (0.005 * rate)), Math.exp(-1 / (0.14 * rate))];
- let follow = 0;
- const step = (n: number): void => {
- let loud = 0;
- for (const c of channels) loud = Math.max(loud, Math.abs(c[n]!));
- follow = loud > follow ? loud + (follow - loud) * up : loud + (follow - loud) * down;
- };
- // A piece that goes round arrives at its start from its end, so the following starts from there.
- if (round) for (let n = Math.max(0, frames - rate); n < frames; n++) step(n);
- for (let n = 0; n < frames; n++) {
- step(n);
- if (follow > line) gains[n] = (line * Math.pow(follow / line, 1 / ratio)) / follow;
- }
- // The following is always a little behind the sound, so the front of every loud note would get through whole and
- // the peak of the piece would be where it was. So the holding down begins before the note: going backward, the
- // gain may rise only so fast, which is a hand already on the fader as the note arrives.
- const rise = 1 / (0.006 * rate);
- for (let n = frames - 2; n >= 0; n--) gains[n] = Math.min(gains[n]!, gains[n + 1]! + rise);
- if (round) gains[frames - 1] = Math.min(gains[frames - 1]!, gains[0]! + rise);
- return gains;
-}
-
-const TAIL_SECONDS = 4;
-
-/**
- * A long sound in a place: the same sum a single transform of the whole would give, taken a stretch at a time, each
- * stretch answered by the place and laid where it belongs. A piece of music is a hundred times as long as the room's
- * answer, and one transform of all of it costs several times what these do.
- */
-function inPlace(response: Float32Array): (signal: Float32Array) => Float32Array {
- let size = 1;
- while (size < response.length * 2) size <<= 1;
- const block = size - response.length;
- const [hr, hi] = [new Float64Array(size), new Float64Array(size)];
- hr.set(response);
- fft(hr, hi);
- const [xr, xi] = [new Float64Array(size), new Float64Array(size)];
- return (signal) => {
- const out = new Float32Array(signal.length);
- for (let from = 0; from < signal.length; from += block) {
- xr.fill(0); xi.fill(0);
- let any = false;
- for (let n = 0; n < block && from + n < signal.length; n++) { const v = signal[from + n]!; xr[n] = v; if (v !== 0) any = true; }
- if (!any) continue;
- fft(xr, xi);
- for (let k = 0; k < size; k++) {
- const re = xr[k]! * hr[k]! - xi[k]! * hi[k]!, im = xr[k]! * hi[k]! + xi[k]! * hr[k]!;
- // Back the same way: the transform of the conjugate, shared out.
- xr[k] = re; xi[k] = -im;
- }
- fft(xr, xi);
- for (let n = 0; n < size && from + n < signal.length; n++) out[from + n]! += xr[n]! / size;
- }
- return out;
- };
-}
-
-/** The samples a validated source makes. @p given holds the recordings its instruments play, by the path each is named by. */
-export function renderMusic(source: MusicSource, given: Readonly<Record<string, SampleData>> = {}): RenderedMusic {
- const compiled = compileMusic(source);
- const rate = source.rate ?? 44100;
- const count = Math.max(1, Math.round(compiled.seconds * rate));
- const work = count + Math.round(TAIL_SECONDS * rate);
- const names = Object.keys(source.instruments);
- const buses = new Map(names.map((name) => [name, [new Float32Array(work), new Float32Array(work)]] as const));
-
- const cache = new Map<string, Float32Array[]>();
- const noteOf = (name: string, instrument: MusicInstrument, e: MusicEvent, turn: number, zone: number): Float32Array[] => {
- // The same note is made a few times over and no more: enough that a hat is not one sample struck again.
- const legato = instrument.legato === true ? 0.07 : instrument.legato || 0;
- const slur = e.slur ? legato : 0;
- // As long as it sounds: as written, or on to the bar line under the pedal, and a moment more where the next
- // note comes in under it.
- const held = (e.sounds ?? e.seconds) + (e.tied ? legato : 0);
- const key = `${name}|${e.midi}|${Math.round(held * 1000)}|${slur}|${instrument.samples ? `z${zone}` : turn % 3}`;
- let made = cache.get(key);
- if (!made && instrument.samples) {
- made = sampleNote(name, instrument, zone, e.midi, held, rate, given, slur);
- cache.set(key, made);
- }
- if (!made) {
- const release = instrument.release ?? 0.08;
- const layers = instrument.layers!.map((l) => forNote(l, held, release, slur));
- const duration = Math.min(8, Math.max(0.02, ...layers.map((l) => reach(l, held + release))));
- made = renderSound({ duration, rate, layers, normalize: false }, 0, { pitch: e.midi === null ? 1 : Math.pow(2, (e.midi - 69) / 12), seed: (turn % 3) * 7919, raw: true }).channels;
- cache.set(key, made);
- }
- return made;
- };
-
- const turns = new Map<string, number>();
- for (const e of compiled.events) {
- const instrument = source.instruments[e.instrument]!;
- const turn = turns.get(e.instrument) ?? 0;
- turns.set(e.instrument, turn + 1);
- // Which recording, for an instrument of them: recordings of one note take turns, counted for each note apart.
- let zone = { index: 0, matched: false };
- if (instrument.samples) {
- const of = `${e.instrument}|${e.midi}|${e.mark}`;
- const again = turns.get(of) ?? 0;
- turns.set(of, again + 1);
- zone = sampleZone(instrument, e.midi, e.mark, again);
- }
- const note = noteOf(e.instrument, instrument, e, turn, zone.index);
- const [l, r] = [note[0]!, note[1] ?? note[0]!];
- const pan = instrument.pan ?? 0;
- // Equal power, and full in the middle. A recording made as hard as the note is marked is already that loud:
- // the mark is not counted twice.
- const loud = (zone.matched ? e.loud / e.hard : e.loud) * (instrument.gain ?? 1) * Math.SQRT2;
- const [gl, gr] = [Math.cos(((pan + 1) * Math.PI) / 4) * loud, Math.sin(((pan + 1) * Math.PI) / 4) * loud];
- const [left, right] = buses.get(e.instrument)!;
- const from = Math.round(e.at * rate);
- for (let n = 0; n < l.length && from + n < work; n++) {
- left[from + n]! += l[n]! * gl;
- right[from + n]! += r[n]! * gr;
- }
- }
-
- // What each instrument has no need of, taken off before the room hears it.
- for (const name of names) {
- const instrument = source.instruments[name]!;
- for (const channel of buses.get(name)!) {
- if (instrument.lowcut) filtered(channel, 'highpass', instrument.lowcut, rate);
- if (instrument.highcut) filtered(channel, 'lowpass', instrument.highcut, rate);
- }
- }
-
- // The room. One for everything; or, when the instruments are to be written apart, one each, so they still add up.
- const room = [new Float32Array(work), new Float32Array(work)];
- if (source.reverb) {
- const [size, mix] = [source.reverb.size ?? 0.4, (source.reverb.mix ?? 0.2) * 3];
- const answers = [0, 1].map((side) => inPlace(placeResponse(rate, size, 'room', side)));
- const sendOf = (name: string): number => source.instruments[name]!.reverb ?? 0.3;
- if (source.stems) {
- for (const name of names) {
- if (sendOf(name) === 0) continue;
- buses.get(name)!.forEach((channel, c) => {
- const wet = answers[c]!(channel);
- for (let n = 0; n < work; n++) channel[n]! += wet[n]! * mix * sendOf(name);
- });
- }
- } else {
- for (const c of [0, 1]) {
- const send = new Float32Array(work);
- for (const name of names) { const [bus, share] = [buses.get(name)![c]!, sendOf(name)]; if (share > 0) for (let n = 0; n < work; n++) send[n]! += bus[n]! * share; }
- const wet = answers[c]!(send);
- for (let n = 0; n < work; n++) room[c]![n] = wet[n]! * mix;
- }
- }
- }
-
- const loop = source.loop !== false;
- // Where the round begins: the start, or the end of an introduction that is heard once.
- const loopStart = loop && source.intro ? compiled.parts[source.intro]!.at : 0;
- const roundFrom = Math.round(loopStart * rate);
- // A piece that ends rings out: the file runs on past its last bar until what is left cannot be heard. One that fades
- // out is at nothing by the end of the bar, and has nothing to ring.
- let total = count;
- if (!loop && !source.fadeOut) {
- let last = count;
- for (const channel of [...room, ...names.flatMap((name) => buses.get(name)!)]) for (let n = work - 1; n > last; n--) if (Math.abs(channel[n]!) > 2e-4) { last = n; break; }
- total = Math.min(work, last + (last > count ? Math.round(0.05 * rate) : 0));
- }
- const finish = (channel: Float32Array): Float32Array => {
- const out = channel.slice(0, total);
- // What rings past the end is heard as the round begins again, which is where it is put.
- if (loop) for (let n = count; n < work; n++) out[roundFrom + ((n - count) % (count - roundFrom))]! += channel[n]!;
- else {
- if (source.fadeIn) { const rise = Math.round(source.fadeIn * rate); for (let n = 0; n < rise && n < total; n++) out[n]! *= (n / rise) ** 2; }
- // Let down over the seconds asked, or over the last fiftieth of one so that it does not stop on a step.
- const fall = Math.min(total, Math.round((source.fadeOut ?? 0.02) * rate));
- for (let n = 0; n < fall; n++) out[total - 1 - n]! *= source.fadeOut ? (n / fall) ** 2 : n / fall;
- }
- return out;
- };
- const stems: Record<string, Float32Array[]> = {};
- for (const name of names) stems[name] = buses.get(name)!.map(finish);
- const channels = [0, 1].map((c) => {
- const sum = finish(room[c]!);
- for (const name of names) { const stem = stems[name]![c]!; for (let n = 0; n < total; n++) sum[n]! += stem[n]!; }
- return sum;
- });
-
- // The whole, once summed: held together, and tilted. Done to the sum and to each instrument alike.
- if (source.master) {
- const every = [channels, ...Object.values(stems)];
- if (source.master.compress) {
- const gains = compression(channels, rate, source.master.compress, loop);
- for (const list of every) for (const channel of list) for (let n = 0; n < total; n++) channel[n]! *= gains[n]!;
- }
- for (const list of every) for (const channel of list) {
- if (source.master.low) filtered(channel, 'lowshelf', 110, rate, source.master.low);
- if (source.master.high) filtered(channel, 'highshelf', 7000, rate, source.master.high);
- }
- }
-
- let peak = 0;
- for (const channel of channels) for (const v of channel) if (Math.abs(v) > peak) peak = Math.abs(v);
- const notes = [...compiled.notes];
- // A recording called a note it is not puts every note played from it out of tune, and nothing in the notes shows it.
- for (const name of names) {
- const wrong: { file: string; said: number; is: number }[] = [];
- // A drum is struck as it was recorded, at no note: whatever pitch is found in it, it is not out of tune with anything.
- const zones = compiled.events.some((e) => e.instrument === name && e.midi !== null) ? source.instruments[name]!.samples ?? [] : [];
- const heard = new Set<string>();
- for (const zone of zones) {
- const data = given[zone.file];
- // A recording used for several ranges is listened to once.
- if (!data || heard.has(`${zone.file}|${zone.note}`)) continue;
- heard.add(`${zone.file}|${zone.note}`);
- const said = midiOf(zone.note)!;
- // Where it is said to be sharp or flat of its note, that is where it is listened for.
- const hz = 440 * Math.pow(2, (said + (zone.tune ?? 0) / 100 - 69) / 12);
- const found = samplePitch(data, hz);
- const off = found === null ? 0 : 12 * Math.log2(found / hz);
- if (Math.abs(off) >= 0.7) wrong.push({ file: zone.file, said, is: Math.round(said + off) });
- }
- if (wrong.length === 0) continue;
- const by = (w: { said: number; is: number }): number => w.is - w.said;
- const semitones = (n: number): string => `${Math.abs(n)} semitone${Math.abs(n) === 1 ? '' : 's'} ${n > 0 ? 'higher' : 'lower'}`;
- // A whole library out by the same amount is one thing to say, and nearly always an octave: it counts its octaves from another C.
- if (wrong.length === heard.size && wrong.length > 1 && wrong.every((w) => by(w) === by(wrong[0]!))) {
- notes.push(`"${name}": every one of its ${heard.size} recordings sounds ${semitones(by(wrong[0]!))} than the note it is said to be (${wrong[0]!.file} is said to be ${noteName(wrong[0]!.said)} and sounds as ${noteName(wrong[0]!.is)})${Math.abs(by(wrong[0]!)) === 12 ? ', as a library does that counts its octaves from another C' : ''}: the instrument plays that much out. Move each \`note\` by that much`);
- } else {
- for (const w of wrong) notes.push(`"${name}": ${w.file} is said to be ${noteName(w.said)} and sounds as ${noteName(w.is)}: every note played from it is ${semitones(by(w))} than written. Set its note to "${noteName(w.is)}"`);
- }
- }
- const target = source.gain ?? 0.9;
- const scale = peak > 1e-6 ? target / peak : 1;
- if (peak <= 1e-6) notes.push('the piece is silent: nothing in it reaches a level that can be heard');
- for (const list of [channels, ...Object.values(stems)]) for (const channel of list) for (let n = 0; n < total; n++) channel[n]! *= scale;
- const rmsOf = (list: Float32Array[], from = 0, to = count): number => { let s = 0; for (const channel of list) for (let n = from; n < to; n++) s += channel[n]! * channel[n]!; return Math.sqrt(s / (Math.max(1, to - from) * list.length)); };
- const rms = rmsOf(channels);
-
- // Where a loop meets itself. The samples join without a step whatever is written; what the ear hears as a join is
- // the music changing at once, a full last bar running into a first bar with two instruments in it.
- let join: RenderedMusic['join'] = null;
- if (loop) {
- const bar = Math.min(count, Math.round(compiled.barSeconds * rate));
- const sounding = (from: number, to: number): string[] => {
- // In the bar for more than a twentieth of it: a note let go on the bar line, a few thousandths late, is not in the next bar.
- const least = compiled.barSeconds * 0.05;
- return names.filter((name) => compiled.events.some((e) => e.instrument === name && Math.min(to, e.at + e.seconds) - Math.max(from, e.at) > least));
- };
- const db = (level: number): number => (level > 0 && rms > 0 ? Math.round(20 * Math.log10(level / rms) * 10) / 10 : -120);
- join = {
- // The first bar of the round, which with an introduction is not the first bar of the file.
- ends: sounding(compiled.seconds - compiled.barSeconds, compiled.seconds), begins: sounding(loopStart, loopStart + compiled.barSeconds),
- endDb: db(rmsOf(channels, count - bar, count)), startDb: db(rmsOf(channels, roundFrom, Math.min(count, roundFrom + bar))),
- };
- const [gone, come] = [join.ends.filter((n) => !join!.begins.includes(n)), join.begins.filter((n) => !join!.ends.includes(n))];
- if (count - roundFrom > bar * 2 && (Math.abs(join.endDb - join.startDb) > 6 || gone.length + come.length > Math.max(1, names.length / 3))) {
- notes.push(`where the loop meets itself the music changes at once: its last bar has ${join.ends.join(', ') || 'nothing'} at ${join.endDb} dB and its first has ${join.begins.join(', ') || 'nothing'} at ${join.startDb} dB${gone.length ? `, so ${gone.join(', ')} stop${gone.length === 1 ? 's' : ''} dead` : ''}. A loop is heard as one piece when its end is as full as its start: end on a part like the one it comes back to (thin the last part with \`without\`, or begin as full as it ends), and put a build that happens once in an introduction with \`intro\``);
- }
- }
-
- const instruments: RenderedMusic['instruments'] = {};
- for (const name of names) {
- const mine = compiled.events.filter((e) => e.instrument === name);
- const pitches = mine.filter((e) => e.midi !== null).map((e) => e.midi!);
- const level = rmsOf(stems[name]!);
- instruments[name] = {
- notes: mine.length,
- ...(pitches.length ? { low: noteName(Math.min(...pitches)), high: noteName(Math.max(...pitches)) } : {}),
- levelDb: level > 0 && rms > 0 ? Math.round(20 * Math.log10(level / rms) * 10) / 10 : -120,
- };
- }
- return { ...compiled, notes, rate, channels, peak: peak > 1e-6 ? target : 0, rms, loopStart, tailSeconds: (total - count) / rate, join, stems: source.stems ? stems : null, instruments };
-}
+// The synthesis is the engine's (sdk/src/sound): a package that ships a sound as its source makes it with the same code the editor bakes it with.
+export * from '../../../sdk/src/sound/musicRender';
diff --git a/pipeline/src/music/musicSource.ts b/pipeline/src/music/musicSource.ts
index 636123c82..ed8da448d 100644
--- a/pipeline/src/music/musicSource.ts
+++ b/pipeline/src/music/musicSource.ts
@@ -1,466 +1,4 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file musicSource.ts — a piece of music as what it is made of: instruments, the patterns they play, and the order
- * the patterns come in.
- *
- * An instrument is the layers of a sound (soundSource.ts), written as it sounds at A above middle C; a note
- * strikes it at another pitch for as long as the note lasts. A pattern is a few bars, each track a line of
- * steps. A step is a degree of the key and not a pitch in Hz, so a line written without accidentals cannot
- * leave the key, and a track that follows the bar's chord cannot leave the chord's scale either. What is saved
- * is this description; the `.wav` a game plays is made from it.
- *
- * Layers make sounds that are plainly made. An instrument that has to pass for a real one is recordings of it:
- * a few notes of a piano or a section of strings, each played back faster or slower for the notes round it.
- */
-import { validateSoundSource, type SoundLayer } from '../sound/soundSource';
-
-export const MUSIC_SOURCE_EXT = '.esmusic';
-export const MUSIC_SOURCE_VERSION = 1;
-export const MAX_MUSIC_SECONDS = 240;
-
-/**
- * Semitones above the tonic of each of a scale's degrees. Most have seven. The five-note scales have five, and a line
- * written in one of them cannot touch the two notes it leaves out, which is the whole of their sound: `pentatonic`
- * and `pentatonicMinor` by their Western names, and the five Chinese modes, each the same five notes begun from
- * another of them, gong (do), shang (re), jue (mi), zhi (sol) and yu (la).
- */
-export const SCALES = {
- pentatonic: [0, 2, 4, 7, 9],
- pentatonicMinor: [0, 3, 5, 7, 10],
- gong: [0, 2, 4, 7, 9],
- shang: [0, 2, 5, 7, 10],
- jue: [0, 3, 5, 8, 10],
- zhi: [0, 2, 5, 7, 9],
- yu: [0, 3, 5, 7, 10],
- major: [0, 2, 4, 5, 7, 9, 11],
- minor: [0, 2, 3, 5, 7, 8, 10],
- dorian: [0, 2, 3, 5, 7, 9, 10],
- phrygian: [0, 1, 3, 5, 7, 8, 10],
- lydian: [0, 2, 4, 6, 7, 9, 11],
- mixolydian: [0, 2, 4, 5, 7, 9, 10],
- harmonic: [0, 2, 3, 5, 7, 8, 11],
-} as const;
-export type ScaleName = keyof typeof SCALES;
-
-const TONICS: Record<string, number> = { C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, F: 5, 'F#': 6, Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11 };
-
-/** One recording of an instrument playing one note. */
-export interface MusicSample {
- /** A project path to the recording. */
- file: string;
- /** The note it is a recording of: "C4" is middle C, "F#3", "Bb2"; or its number, 60 being middle C. */
- note: string | number;
- /** The notes it plays, lowest to highest. Left out, each note is played by the recording nearest it. */
- low?: string | number;
- high?: string | number;
- /** For a note held longer than the recording: true goes round its steady middle, [from, to] round those seconds of it. A piano dies of itself and has none. */
- loop?: boolean | readonly [number, number];
- /**
- * How hard it was played. A step marked `?` is played from a "soft" recording and one marked `!` from a "loud"
- * one, where the instrument has them: a piano struck hard is brighter, not only louder, and turning a soft
- * recording up does not make it so. Left out, it is "normal".
- */
- dynamic?: (typeof DYNAMICS)[number];
- /** Hundredths of a semitone the recording is sharp (above 0) or flat of its note, -100..100, which is taken out as it is played. */
- tune?: number;
- /** How loud this recording is played beside the instrument's others, 1 being as it is: what evens one recording against the next. */
- gain?: number;
- /** Nothing of it above this many Hz: a bright recording played mellow, which is how one recording serves soft notes and loud. */
- cutoff?: number;
-}
-
-export const DYNAMICS = ['soft', 'normal', 'loud'] as const;
-
-export interface MusicInstrument {
- /** The layers of its sound at A above middle C (440 Hz): a sine at 440 is its fundamental, one at 880 the octave over it. A layer with no `length` lasts as long as the note; one with a `length` (the knock at the front of a pluck, a drum) keeps its own. */
- layers?: readonly SoundLayer[];
- /** In place of layers: recordings of the instrument, each played faster or slower for the notes round it. The further a note is from its recording the less it is the instrument, so a recording every three or four semitones. */
- samples?: readonly MusicSample[];
- /** Samples: seconds a note takes to come in. Default 0.003. */
- attack?: number;
- /** Loudness against the other instruments. Default 1. */
- gain?: number;
- /** -1 is left, 1 is right. Default 0. */
- pan?: number;
- /** Octaves up or down from where its notes are written: a bass is -2. Default 0. */
- octave?: number;
- /** Its degrees count from the root of the bar's chord: 1 is the root, 3 the third, 5 the fifth, whatever the chord. A bass or a pad that follows is written once and moves with the chords. */
- follow?: boolean;
- /**
- * A scale of its own, on the piece's tonic, that its line is written in: a tune in the five notes of `yu` over a
- * piece in `minor`, whose chords and bass have all seven. That is how the style is made, a tune that cannot
- * touch the two notes the harmony under it is free to use. Not for an instrument that follows the chords, whose
- * degrees are counted from them.
- */
- scale?: ScaleName;
- /** Seconds a held note takes to die after it is let go. Default 0.08. */
- release?: number;
- /**
- * Nothing of it below this many Hz. Every instrument but the bass and the kick has a bottom it does not need,
- * the thump of a piano's frame, the rumble under a string section, and all of them together are the mud a mix
- * drowns in: 120 to 200 for what plays in the middle, 300 and up for what plays high.
- */
- lowcut?: number;
- /** Nothing of it above this many Hz: what should sit behind the rest is duller than what is in front. */
- highcut?: number;
- /**
- * A line played in one breath. Where one note of its line runs straight into the next, with no silence between
- * and the next not marked `!`, the next is not struck afresh: it comes in under the one before over this many
- * seconds (true is 0.07) while that one goes out, and a recording is taken from past its attack. This is a bow
- * that does not leave the string and a breath that is not taken again; without it every note of a violin or a
- * flute begins from nothing and a tune is a row of separate notes. Chords are struck as they were.
- */
- legato?: boolean | number;
- /**
- * The sustaining pedal, held down through each bar and changed on the bar line: every note rings on to the end
- * of its bar however short it is written, so the notes of a broken chord pile up into the chord and one bar
- * runs into the next. A piano without it is dry and its chords are apart.
- */
- pedal?: boolean;
- /** How much of it goes to the room, 0..1. Default 0.3; a bass or a kick wants 0. */
- reverb?: number;
-}
-
-export interface MusicPattern {
- bars: number;
- /** Steps to a beat. Default 4, which is sixteenths; 3 is triplets; 2 is eighths. */
- div?: number;
- /** The chord of each bar, as the degree its root is on: [1, 6, 3, 7]. Fewer than the bars come round again. Only instruments that `follow` hear them. */
- chords?: readonly number[];
- /**
- * How loud each bar begins, for an instrument or for `all` of them, 1 being as written: `{ lead: [0.6, 0.8, 1,
- * 0.7] }`. Between one bar's number and the next the loudness moves evenly, which is a crescendo or a
- * diminuendo; one number more than there are bars is where the last bar ends. A phrase that is all one loudness
- * is not heard as a phrase.
- */
- dynamics?: Readonly<Record<string, readonly number[]>>;
- /**
- * A line of steps for each instrument that plays, separated by spaces, bars by `|`. A step is: `.` silence; `-` the
- * note before, still held; a degree 1..7 with `'` for each octave up and `,` for each down, `#` or `b` before it to
- * leave the key by a semitone; `[1 3 5]` several at once; `x` the instrument at its own pitch, for a drum. `!` after
- * a step makes it louder and `?` softer.
- */
- tracks: Readonly<Record<string, string>>;
-}
-
-export type SongPart = string | { pattern: string; without?: readonly string[]; only?: readonly string[] };
-
-export interface MusicSource {
- version?: number;
- /** Beats a minute. */
- tempo: number;
- /** Beats to a bar. Default 4. */
- beats?: number;
- /** The tonic: C, F#, Bb. */
- key: string;
- /** Default minor. */
- scale?: ScaleName;
- /** Every second step comes late by this share of a step, 0..0.6. 0.33 is a shuffle. */
- swing?: number;
- /** How unlike a machine: timing and loudness off by a little at random, 0..1. Default 0.15. */
- humanize?: number;
- seed?: number;
- instruments: Readonly<Record<string, MusicInstrument>>;
- patterns: Readonly<Record<string, MusicPattern>>;
- /** The patterns in the order they come, each whole, or with some instruments left out or only some kept. */
- song: readonly SongPart[];
- /**
- * What rings past the end comes in at the start, so the piece runs into itself. Default true. False is a piece
- * with an end: its last notes and the room ring out after the last bar, and the file is that much longer.
- */
- loop?: boolean;
- /**
- * How many of the song's first parts are an introduction: heard once, after which the rest goes round. The file
- * is still one file; what rings past its end comes in where the introduction ends, and the reply gives that place
- * as `loopStart`, which the game hands to playBGM or sets on the AudioSource. This is where a build belongs
- * that a loop cannot hold: two instruments growing to all of them, once.
- */
- intro?: number;
- /** Seconds over which it comes up from nothing at its start. A loop comes round to its start again and again, so only a piece that ends has one; a game fades a loop in as it starts it. */
- fadeIn?: number;
- /** Seconds before the end of the last bar over which it goes down to nothing, for a piece that ends and has no ending written. */
- fadeOut?: number;
- /** Also a file for each instrument, which add up to the whole: a game brings them in and out. */
- stems?: boolean;
- /** The room it is all in: `size` 0..1, `mix` 0..1. */
- reverb?: { size?: number; mix?: number };
- /**
- * Time that gives: each pattern is a phrase that begins a little held back, moves on through its middle and
- * eases off to its end, by up to this share of 8% of the tempo, 0..1. Every instrument moves together and a
- * pattern is as long as it was. 0.3 is a player breathing; 1 is a romantic one. Not for what is danced to.
- */
- rubato?: number;
- /**
- * What is done to the whole once it is summed. `compress` 0..1 holds the loud moments down so the quiet ones
- * come up and the instruments are heard as one thing and not several (0.3 to 0.5 for most pieces); `low` and
- * `high` are decibels more or less below 110 Hz and above 7 kHz, -12..12.
- */
- master?: { compress?: number; low?: number; high?: number };
- /** How loud the loudest moment is, 1 being full. Default 0.9. */
- gain?: number;
- rate?: number;
-}
-
-/** One sounding in a step: a degree, or the instrument's own pitch. */
-export interface StepNote { degree: number; alter: number; octave: number }
-export type Step =
- | { kind: 'rest' }
- | { kind: 'hold' }
- | { kind: 'hit'; loud: number }
- | { kind: 'notes'; loud: number; notes: StepNote[] };
-
-const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
-const between = (v: unknown, lo: number, hi: number): boolean => isNum(v) && v >= lo && v <= hi;
-const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
-const NAME = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
-
-export const tonicOf = (key: string): number => TONICS[key]!;
-
-/** "C4" as its number, 60; a number as itself. Null for what is neither. */
-export function midiOf(note: unknown): number | null {
- if (typeof note === 'number') return Number.isInteger(note) && note >= 0 && note <= 127 ? note : null;
- const m = typeof note === 'string' ? /^([A-G](?:#|b)?)(-?\d)$/.exec(note) : null;
- if (!m || TONICS[m[1]!] === undefined) return null;
- const midi = TONICS[m[1]!]! + 12 * (Number(m[2]) + 1);
- return midi >= 0 && midi <= 127 ? midi : null;
-}
-
-/** The recordings a source plays, each once. */
-export function musicSampleFiles(source: MusicSource): string[] {
- return [...new Set(Object.values(source.instruments).flatMap((i) => (i.samples ?? []).map((s) => s.file)))];
-}
-
-const loudOf = (mark: string): number => (mark === '!' ? 1.3 : mark === '?' ? 0.6 : 1);
-
-function noteOf(text: string): StepNote | null {
- const m = /^([#b]?)([1-7])([',]*)$/.exec(text);
- if (!m) return null;
- let octave = 0;
- for (const c of m[3]!) octave += c === "'" ? 1 : -1;
- return { degree: Number(m[2]), alter: m[1] === '#' ? 1 : m[1] === 'b' ? -1 : 0, octave };
-}
-
-/** A track's line as steps, bar by bar. Throws saying which bar is wrong and why. */
-export function parseTrack(text: string, bars: number, stepsToBar: number, where: string, degrees = 7): Step[] {
- const out: Step[] = [];
- const written = text.split('|').map((b) => b.trim());
- if (written.at(-1) === '') written.pop();
- if (written.length !== bars) throw new Error(`${where} has ${written.length} bar${written.length === 1 ? '' : 's'} between its | marks; the pattern is ${bars}`);
- written.forEach((bar, b) => {
- // A chord's notes are kept together through the split on spaces.
- const tokens = bar.replace(/\[([^\]]*)\]/g, (_, inner: string) => `[${inner.trim().split(/\s+/).join('+')}]`).split(/\s+/).filter((t) => t !== '');
- if (tokens.length !== stepsToBar) throw new Error(`${where}, bar ${b + 1} has ${tokens.length} steps; a bar here is ${stepsToBar}. Write "." for a silent step and "-" for one that holds the note before`);
- for (const token of tokens) {
- const mark = token.endsWith('!') || token.endsWith('?') ? token.slice(-1) : '';
- const body = mark ? token.slice(0, -1) : token;
- if (body === '.') out.push({ kind: 'rest' });
- else if (body === '-') out.push({ kind: 'hold' });
- else if (body === 'x') out.push({ kind: 'hit', loud: loudOf(mark) });
- else {
- const parts = body.startsWith('[') && body.endsWith(']') ? body.slice(1, -1).split('+') : [body];
- const notes = parts.map(noteOf);
- if (notes.length === 0 || notes.length > 6 || notes.some((n) => n === null)) {
- throw new Error(`${where}, bar ${b + 1}: "${token.replace(/\+/g, ' ')}" is not a step. A step is . (silence), - (hold), x (a drum), a degree 1..7 with ' or , for octaves and # or b before it, or [1 3 5] for up to six at once`);
- }
- const past = (notes as StepNote[]).find((n) => n.degree > degrees);
- if (past) throw new Error(`${where}, bar ${b + 1}: degree ${past.degree} is not in this scale, which has ${degrees} notes: its degrees are 1..${degrees}, and the next octave begins again at 1'`);
- out.push({ kind: 'notes', loud: loudOf(mark), notes: notes as StepNote[] });
- }
- }
- });
- return out;
-}
-
-const SOURCE_FIELDS = ['version', 'tempo', 'beats', 'key', 'scale', 'swing', 'humanize', 'seed', 'instruments', 'patterns', 'song', 'loop', 'intro', 'fadeIn', 'fadeOut', 'stems', 'reverb', 'rubato', 'master', 'gain', 'rate'];
-const INSTRUMENT_FIELDS = ['layers', 'samples', 'attack', 'gain', 'pan', 'octave', 'follow', 'release', 'reverb', 'legato', 'pedal', 'lowcut', 'highcut', 'scale'];
-const RECORDING = /\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i;
-
-function checkSamples(samples: unknown, where: string): void {
- if (!Array.isArray(samples) || samples.length === 0 || samples.length > 256) throw new Error(`${where}: samples must be 1..256 of { file, note }`);
- samples.forEach((sample: unknown, i) => {
- const at = `${where}, sample ${i + 1}`;
- if (!isObj(sample)) throw new Error(`${at} must be { file, note }`);
- for (const key of Object.keys(sample)) if (!['file', 'note', 'low', 'high', 'loop', 'dynamic', 'tune', 'gain', 'cutoff'].includes(key)) throw new Error(`${at} has unknown "${key}"; a sample has file, note, low, high, loop, dynamic, tune, gain, cutoff`);
- if (sample.gain !== undefined && !between(sample.gain, 0.01, 4)) throw new Error(`${at}: gain must be 0.01..4, 1 being the recording as it is`);
- if (sample.cutoff !== undefined && !between(sample.cutoff, 200, 20000)) throw new Error(`${at}: cutoff must be Hz, 200..20000`);
- if (sample.dynamic !== undefined && !DYNAMICS.includes(sample.dynamic as never)) throw new Error(`${at}: dynamic must be one of ${DYNAMICS.join(', ')}`);
- if (sample.tune !== undefined && !between(sample.tune, -100, 100)) throw new Error(`${at}: tune must be hundredths of a semitone, -100..100`);
- if (typeof sample.file !== 'string' || !RECORDING.test(sample.file)) throw new Error(`${at}: file must be a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)`);
- if (midiOf(sample.note) === null) throw new Error(`${at}: note must be the note recorded, as "C4", "F#3" or "Bb2" (C4 is middle C), or its number 0..127`);
- for (const key of ['low', 'high']) if (sample[key] !== undefined && midiOf(sample[key]) === null) throw new Error(`${at}: ${key} must be a note, as "C4"`);
- if (sample.low !== undefined && sample.high !== undefined && midiOf(sample.low)! > midiOf(sample.high)!) throw new Error(`${at}: low is above high`);
- const loop = sample.loop;
- if (loop !== undefined && typeof loop !== 'boolean' && !(Array.isArray(loop) && loop.length === 2 && isNum(loop[0]) && isNum(loop[1]) && loop[0] >= 0 && loop[1] > loop[0] + 0.0005)) {
- throw new Error(`${at}: loop must be true, or [from, to] in seconds with to past from`);
- }
- });
-}
-const PATTERN_FIELDS = ['bars', 'div', 'chords', 'dynamics', 'tracks'];
-
-/** Seconds the song lasts, before anything that rings past its end. */
-export function musicSeconds(source: MusicSource): number {
- const bar = ((source.beats ?? 4) * 60) / source.tempo;
- return source.song.reduce((sum, part) => sum + source.patterns[typeof part === 'string' ? part : part.pattern]!.bars * bar, 0);
-}
-
-/** The source if it is well formed; otherwise throws, naming the instrument, the pattern, the track and the bar. */
-export function validateMusicSource(raw: unknown): MusicSource {
- if (!isObj(raw)) throw new Error('a music source must be { tempo, key, instruments, patterns, song }');
- const s = raw;
- for (const key of Object.keys(s)) if (!SOURCE_FIELDS.includes(key)) throw new Error(`unknown field "${key}"; music has ${SOURCE_FIELDS.join(', ')}`);
- if (s.version !== undefined && s.version !== MUSIC_SOURCE_VERSION) throw new Error(`version ${String(s.version)} is not one this editor reads (${MUSIC_SOURCE_VERSION})`);
- if (!between(s.tempo, 30, 300)) throw new Error('tempo must be beats a minute, 30..300');
- if (s.beats !== undefined && !(Number.isInteger(s.beats) && between(s.beats, 2, 12))) throw new Error('beats must be a whole number to the bar, 2..12');
- if (typeof s.key !== 'string' || TONICS[s.key] === undefined) throw new Error(`key must be a tonic: ${Object.keys(TONICS).join(', ')}`);
- if (s.scale !== undefined && !(typeof s.scale === 'string' && s.scale in SCALES)) throw new Error(`scale must be one of ${Object.keys(SCALES).join(', ')}`);
- if (s.swing !== undefined && !between(s.swing, 0, 0.6)) throw new Error('swing must be 0..0.6');
- if (s.humanize !== undefined && !between(s.humanize, 0, 1)) throw new Error('humanize must be 0..1');
- if (s.seed !== undefined && !Number.isInteger(s.seed)) throw new Error('seed must be a whole number');
- if (s.gain !== undefined && !between(s.gain, 0, 1)) throw new Error('gain must be 0..1');
- if (s.rate !== undefined && ![22050, 44100, 48000].includes(s.rate as number)) throw new Error('rate must be one of 22050, 44100, 48000');
- for (const key of ['loop', 'stems']) if (s[key] !== undefined && typeof s[key] !== 'boolean') throw new Error(`${key} must be true or false`);
- if (s.reverb !== undefined) {
- if (!isObj(s.reverb)) throw new Error('reverb must be { size?, mix? }');
- for (const key of Object.keys(s.reverb)) if (!['size', 'mix'].includes(key)) throw new Error(`reverb has unknown "${key}"; it takes size, mix`);
- if (s.reverb.size !== undefined && !between(s.reverb.size, 0, 1)) throw new Error('reverb.size must be 0..1');
- if (s.reverb.mix !== undefined && !between(s.reverb.mix, 0, 1)) throw new Error('reverb.mix must be 0..1');
- }
-
- if (s.rubato !== undefined && !between(s.rubato, 0, 1)) throw new Error('rubato must be 0..1');
- if (s.master !== undefined) {
- if (!isObj(s.master)) throw new Error('master must be { compress?, low?, high? }');
- for (const key of Object.keys(s.master)) if (!['compress', 'low', 'high'].includes(key)) throw new Error(`master has unknown "${key}"; it takes compress, low, high`);
- if (s.master.compress !== undefined && !between(s.master.compress, 0, 1)) throw new Error('master.compress must be 0..1');
- for (const key of ['low', 'high']) if (s.master[key] !== undefined && !between(s.master[key], -12, 12)) throw new Error(`master.${key} must be decibels, -12..12`);
- }
- if (!isObj(s.instruments) || Object.keys(s.instruments).length === 0) throw new Error('instruments must be { name: { layers: [...] } }, at least one');
- if (Object.keys(s.instruments).length > 16) throw new Error('at most 16 instruments');
- for (const [name, value] of Object.entries(s.instruments)) {
- const where = `instrument "${name}"`;
- if (!NAME.test(name)) throw new Error(`${where}: a name is a letter, then letters, digits, _ or -`);
- if (!isObj(value)) throw new Error(`${where} must be { layers: [...] }`);
- for (const key of Object.keys(value)) if (!INSTRUMENT_FIELDS.includes(key)) throw new Error(`${where} has unknown "${key}"; an instrument has ${INSTRUMENT_FIELDS.join(', ')}`);
- if ((value.layers === undefined) === (value.samples === undefined)) throw new Error(`${where} needs layers (a made sound) or samples (recordings), one of the two`);
- if (value.samples !== undefined) checkSamples(value.samples, where);
- else {
- try {
- // Its layers are a sound's layers, and are wrong in the same ways.
- validateSoundSource({ duration: 8, layers: value.layers });
- } catch (e) {
- throw new Error(`${where}: ${(e as Error).message}`);
- }
- }
- if (value.attack !== undefined && !(value.samples !== undefined && between(value.attack, 0, 2))) throw new Error(`${where}: attack is for samples, seconds 0..2; layers have their own`);
- if (value.gain !== undefined && !between(value.gain, 0, 4)) throw new Error(`${where}: gain must be 0..4`);
- if (value.pan !== undefined && !between(value.pan, -1, 1)) throw new Error(`${where}: pan must be -1..1`);
- if (value.octave !== undefined && !(Number.isInteger(value.octave) && between(value.octave, -4, 4))) throw new Error(`${where}: octave must be a whole number, -4..4`);
- if (value.follow !== undefined && typeof value.follow !== 'boolean') throw new Error(`${where}: follow must be true or false`);
- if (value.release !== undefined && !between(value.release, 0, 4)) throw new Error(`${where}: release must be seconds, 0..4`);
- if (value.reverb !== undefined && !between(value.reverb, 0, 1)) throw new Error(`${where}: reverb must be 0..1`);
- if (value.legato !== undefined && typeof value.legato !== 'boolean' && !between(value.legato, 0.01, 0.5)) throw new Error(`${where}: legato must be true, or the seconds one note takes to come in under the last, 0.01..0.5`);
- if (value.pedal !== undefined && typeof value.pedal !== 'boolean') throw new Error(`${where}: pedal must be true or false`);
- if (value.scale !== undefined) {
- if (!(typeof value.scale === 'string' && value.scale in SCALES)) throw new Error(`${where}: scale must be one of ${Object.keys(SCALES).join(', ')}`);
- if (value.follow) throw new Error(`${where}: an instrument that follows the chords counts its degrees from them, in the piece's scale; a scale of its own is for a line that does not follow`);
- }
- if (value.lowcut !== undefined && !between(value.lowcut, 20, 2000)) throw new Error(`${where}: lowcut must be Hz, 20..2000`);
- if (value.highcut !== undefined && !between(value.highcut, 500, 20000)) throw new Error(`${where}: highcut must be Hz, 500..20000`);
- }
-
- const beats = (s.beats as number | undefined) ?? 4;
- const degrees = SCALES[(s.scale as ScaleName | undefined) ?? 'minor'].length;
- if (!isObj(s.patterns) || Object.keys(s.patterns).length === 0) throw new Error('patterns must be { name: { bars, tracks: { instrument: "steps" } } }, at least one');
- for (const [name, value] of Object.entries(s.patterns)) {
- const where = `pattern "${name}"`;
- if (!NAME.test(name)) throw new Error(`${where}: a name is a letter, then letters, digits, _ or -`);
- if (!isObj(value)) throw new Error(`${where} must be { bars, tracks }`);
- for (const key of Object.keys(value)) if (!PATTERN_FIELDS.includes(key)) throw new Error(`${where} has unknown "${key}"; a pattern has ${PATTERN_FIELDS.join(', ')}`);
- if (!(Number.isInteger(value.bars) && between(value.bars, 1, 32))) throw new Error(`${where}: bars must be a whole number, 1..32`);
- if (value.div !== undefined && !(Number.isInteger(value.div) && between(value.div, 1, 8))) throw new Error(`${where}: div must be whole steps to a beat, 1..8`);
- if (value.chords !== undefined) {
- if (!Array.isArray(value.chords) || value.chords.length === 0 || value.chords.length > (value.bars as number) || value.chords.some((c) => !(Number.isInteger(c) && c >= 1 && c <= degrees))) {
- throw new Error(`${where}: chords must be the degree of each bar's root, 1..${degrees}, no more of them than bars`);
- }
- }
- if (value.dynamics !== undefined) {
- if (!isObj(value.dynamics)) throw new Error(`${where}: dynamics must be { instrument or "all": [how loud each bar begins] }`);
- for (const [who, levels] of Object.entries(value.dynamics)) {
- if (who !== 'all' && !(who in s.instruments)) throw new Error(`${where}: dynamics for "${who}", which is not an instrument; the instruments are ${Object.keys(s.instruments).join(', ')}, or "all"`);
- if (!Array.isArray(levels) || levels.length === 0 || levels.length > (value.bars as number) + 1 || levels.some((v) => !between(v, 0.1, 2))) {
- throw new Error(`${where}: dynamics for "${who}" must be how loud each bar begins, 0.1..2 with 1 as written, one for each of its ${String(value.bars)} bars and at most one more for where the last ends`);
- }
- }
- }
- if (!isObj(value.tracks) || Object.keys(value.tracks).length === 0) throw new Error(`${where}: tracks must be { instrument: "steps" }, at least one`);
- for (const [track, line] of Object.entries(value.tracks)) {
- if (!(track in s.instruments)) throw new Error(`${where} has a track for "${track}", which is not an instrument; the instruments are ${Object.keys(s.instruments).join(', ')}`);
- if (typeof line !== 'string') throw new Error(`${where}, track "${track}" must be a line of steps`);
- parseTrack(line, value.bars as number, beats * ((value.div as number | undefined) ?? 4), `${where}, track "${track}"`, SCALES[((s.instruments as Record<string, MusicInstrument>)[track]!.scale ?? (s.scale as ScaleName | undefined) ?? 'minor')].length);
- }
- }
-
- if (!Array.isArray(s.song) || s.song.length === 0 || s.song.length > 64) throw new Error('song must be the patterns in order, 1..64 of them');
- s.song.forEach((part, i) => {
- const name = typeof part === 'string' ? part : isObj(part) ? part.pattern : undefined;
- if (typeof name !== 'string' || !(name in (s.patterns as object))) throw new Error(`song part ${i + 1}: "${String(name)}" is not a pattern; the patterns are ${Object.keys(s.patterns as object).join(', ')}`);
- if (isObj(part)) {
- for (const key of Object.keys(part)) if (!['pattern', 'without', 'only'].includes(key)) throw new Error(`song part ${i + 1} has unknown "${key}"; it takes pattern, without, only`);
- if (part.without !== undefined && part.only !== undefined) throw new Error(`song part ${i + 1}: give without or only, not both`);
- for (const key of ['without', 'only']) {
- const list = part[key];
- if (list === undefined) continue;
- if (!Array.isArray(list) || list.some((n) => typeof n !== 'string' || !(n in (s.instruments as object)))) throw new Error(`song part ${i + 1}: ${key} must be a list of instruments (${Object.keys(s.instruments as object).join(', ')})`);
- }
- }
- });
- const source = s as unknown as MusicSource;
- const seconds = musicSeconds(source);
- if (s.intro !== undefined) {
- if (s.loop === false) throw new Error('intro is the part of a loop that is heard once; a piece with loop false is heard once whole and has none');
- if (!(Number.isInteger(s.intro) && (s.intro as number) >= 1 && (s.intro as number) < s.song.length)) throw new Error(`intro must be how many of the song's first parts are heard once: a whole number from 1, leaving at least one part to go round (the song has ${s.song.length})`);
- }
- for (const key of ['fadeIn', 'fadeOut'] as const) {
- if (s[key] === undefined) continue;
- if (s.loop !== false) throw new Error(`${key} is for a piece that ends (loop: false). A loop comes round to its start with no gap, and a fade written into it would be heard every time round: the game fades it, playBGM(url, { fadeIn }) to start it and stopBGM(seconds) to end it`);
- if (!(isNum(s[key]) && (s[key] as number) > 0 && (s[key] as number) <= seconds)) throw new Error(`${key} must be seconds, above 0 and no longer than the piece (${Math.round(seconds * 10) / 10} s)`);
- }
- if (seconds > MAX_MUSIC_SECONDS) throw new Error(`the song lasts ${Math.round(seconds)} s; at most ${MAX_MUSIC_SECONDS}`);
- return source;
-}
-
-export type MusicEdit =
- | { op: 'instrument'; name: string; value: MusicInstrument | null }
- | { op: 'pattern'; name: string; value: MusicPattern | null }
- | { op: 'track'; pattern: string; track: string; steps: string | null }
- | { op: 'settings'; fields: Record<string, unknown> };
-
-/** The source with @p edits made in order, checked as a whole. A bad edit changes nothing. */
-export function applyMusicEdits(source: MusicSource, edits: readonly MusicEdit[]): MusicSource {
- const next = JSON.parse(JSON.stringify(source)) as Record<string, unknown> & { instruments: Record<string, unknown>; patterns: Record<string, { tracks: Record<string, string> }> };
- edits.forEach((edit, i) => {
- const where = `edit ${i + 1}`;
- if (!isObj(edit)) throw new Error(`${where} must be { op, ... }`);
- if (edit.op === 'instrument' || edit.op === 'pattern') {
- const into = edit.op === 'instrument' ? next.instruments : next.patterns;
- if (typeof edit.name !== 'string') throw new Error(`${where}: name the ${edit.op}`);
- if (edit.value === null) {
- if (!(edit.name in into)) throw new Error(`${where}: there is no ${edit.op} "${edit.name}"; there are ${Object.keys(into).join(', ')}`);
- delete into[edit.name];
- } else (into as Record<string, unknown>)[edit.name] = edit.value;
- } else if (edit.op === 'track') {
- const pattern = next.patterns[edit.pattern];
- if (!pattern) throw new Error(`${where}: there is no pattern "${edit.pattern}"; there are ${Object.keys(next.patterns).join(', ')}`);
- if (edit.steps === null) delete pattern.tracks[edit.track];
- else pattern.tracks[edit.track] = edit.steps;
- } else if (edit.op === 'settings') {
- if (!isObj(edit.fields)) throw new Error(`${where}: settings needs fields`);
- for (const [key, value] of Object.entries(edit.fields)) {
- if (['instruments', 'patterns'].includes(key)) throw new Error(`${where}: change ${key} with the ${key.slice(0, -1)} op`);
- if (value === null) delete next[key];
- else next[key] = value;
- }
- } else throw new Error(`${where}: op must be instrument, pattern, track or settings`);
- });
- return validateMusicSource(next);
-}
+// The synthesis is the engine's (sdk/src/sound): a package that ships a sound as its source makes it with the same code the editor bakes it with.
+export * from '../../../sdk/src/sound/musicSource';
diff --git a/pipeline/src/sound/soundPicture.ts b/pipeline/src/sound/soundPicture.ts
index 9fc5ac5ec..2d4add12c 100644
--- a/pipeline/src/sound/soundPicture.ts
+++ b/pipeline/src/sound/soundPicture.ts
@@ -10,35 +10,12 @@
* Faint lines mark 100 Hz, 1 kHz and 10 kHz, and tenths of a second, or whole seconds on a long sound.
*/
import type { RenderedSound } from './soundRender';
+import { fft } from '../../../sdk/src/sound/fft';
export interface SoundPicture { width: number; height: number; rgba: Uint8Array }
-/** In place: the transform of @p re + i @p im, their length a power of two. */
-export function fft(re: Float64Array, im: Float64Array): void {
- const n = re.length;
- for (let i = 1, j = 0; i < n; i++) {
- let bit = n >> 1;
- for (; j & bit; bit >>= 1) j ^= bit;
- j ^= bit;
- if (i < j) { const r = re[i]!; re[i] = re[j]!; re[j] = r; const m = im[i]!; im[i] = im[j]!; im[j] = m; }
- }
- for (let size = 2; size <= n; size <<= 1) {
- const angle = (-2 * Math.PI) / size;
- const wr = Math.cos(angle), wi = Math.sin(angle), half = size >> 1;
- // Plain locals throughout: this loop is all the time a long convolution takes.
- for (let start = 0; start < n; start += size) {
- let cr = 1, ci = 0;
- for (let k = 0; k < half; k++) {
- const a = start + k, b = a + half;
- const tr = re[b]! * cr - im[b]! * ci, ti = re[b]! * ci + im[b]! * cr;
- re[b] = re[a]! - tr; im[b] = im[a]! - ti;
- re[a] = re[a]! + tr; im[a] = im[a]! + ti;
- const next = cr * wr - ci * wi;
- ci = cr * wi + ci * wr; cr = next;
- }
- }
- }
-}
+// The transform is the engine's, where the synthesis that uses it now lives.
+export { fft } from '../../../sdk/src/sound/fft';
const LOW = 40;
const HIGH = 20000;
diff --git a/pipeline/src/sound/soundRender.ts b/pipeline/src/sound/soundRender.ts
index 40947ca52..5b4762ba8 100644
--- a/pipeline/src/sound/soundRender.ts
+++ b/pipeline/src/sound/soundRender.ts
@@ -1,618 +1,4 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file soundRender.ts — a sound source worked out into samples, and the samples as a `.wav`.
- *
- * Every layer is rendered on its own, placed in time, and summed; then what the source says of the whole (a
- * filter, an echo, a place, a level) is applied to the sum. Nothing depends on the machine: no random number is
- * drawn that is not seeded, and the arithmetic is plain doubles.
- *
- * What makes a made sound pass for a real one is mostly here, and it is not more kinds of wave. A bang is several
- * bands of noise that die at different rates, the high ones first, behind a spike a fifth of a millisecond wide;
- * a breaking thing is hundreds of small rings scattered in time and pitch; a place is a wash whose top dies before
- * its bottom, after a handful of distinct first echoes. A layer of noise through one filter with one decay has
- * none of that and is heard at once as a machine.
- */
-import { fft } from './soundPicture';
-import type { SoundCurve, SoundFilter, SoundLayer, SoundSource } from './soundSource';
-
-export interface RenderedSound {
- rate: number;
- /** One for a sound with nothing off-centre, two otherwise: left, right. */
- channels: Float32Array[];
- seconds: number;
- /** The loudest moment, 0..1, after everything. */
- peak: number;
- /** The level over the whole, as the square root of the mean square. */
- rms: number;
- /** Where each layer sounds and how loud it is on its own, before the sum. */
- layers: { id?: string; source: string; from: number; to: number; peak: number; strikes?: number }[];
- notes: string[];
-}
-
-const TAU = Math.PI * 2;
-/** The level white noise has here, which a band of it is brought back to. */
-const NOISE_LEVEL = 1 / Math.sqrt(3);
-
-/** A curve read at @p t seconds: straight between its points, or along the ratio between them for a pitch. */
-function curveAt(curve: SoundCurve | undefined, t: number, fallback: number, ratio: boolean): number {
- if (curve === undefined) return fallback;
- if (typeof curve === 'number') return curve;
- if (t <= curve[0]![0]) return curve[0]![1];
- for (let i = 1; i < curve.length; i++) {
- const [t1, v1] = curve[i]!;
- if (t > t1) continue;
- const [t0, v0] = curve[i - 1]!;
- const w = (t - t0) / (t1 - t0);
- // A pitch glides by ratio: halfway from 200 to 800 Hz is 400, as the ear has it.
- return ratio && v0 > 0 && v1 > 0 ? v0 * Math.pow(v1 / v0, w) : v0 + (v1 - v0) * w;
- }
- return curve.at(-1)![1];
-}
-
-/** The same numbers for the same seed, -1..1. */
-function noiseOf(seed: number): () => number {
- let s = (seed * 2654435761 + 0x9e3779b9) >>> 0;
- return () => {
- s = (s + 0x6d2b79f5) >>> 0;
- let t = s;
- t = Math.imul(t ^ (t >>> 15), t | 1);
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
- return ((t ^ (t >>> 14)) >>> 0) / 2147483648 - 1;
- };
-}
-
-/** What a sharp step would alias as, taken out of the two samples beside it. */
-function polyBlep(phase: number, step: number): number {
- if (phase < step) { const t = phase / step; return t + t - t * t - 1; }
- if (phase > 1 - step) { const t = (phase - 1) / step; return t * t + t + t + 1; }
- return 0;
-}
-
-/** A two-pole filter whose corner may move: the coefficients are worked out again as it does. */
-class Biquad {
- private x1 = 0; private x2 = 0; private y1 = 0; private y2 = 0;
- private b0 = 1; private b1 = 0; private b2 = 0; private a1 = 0; private a2 = 0;
- private last = -1;
- constructor(private readonly type: SoundFilter['type'], private readonly q: number, private readonly rate: number, private readonly gainDb = 0) {}
-
- tune(freq: number): void {
- const f = Math.max(20, Math.min(this.rate * 0.45, freq));
- if (Math.abs(f - this.last) < 0.01) return;
- this.last = f;
- const w = (TAU * f) / this.rate;
- const [cos, alpha] = [Math.cos(w), Math.sin(w) / (2 * this.q)];
- let a0 = 1 + alpha, a1 = -2 * cos, a2 = 1 - alpha;
- let b0: number, b1: number, b2: number;
- switch (this.type) {
- case 'lowpass': [b0, b1, b2] = [(1 - cos) / 2, 1 - cos, (1 - cos) / 2]; break;
- case 'highpass': [b0, b1, b2] = [(1 + cos) / 2, -(1 + cos), (1 + cos) / 2]; break;
- case 'bandpass': [b0, b1, b2] = [alpha, 0, -alpha]; break;
- case 'peak': {
- const lift = Math.pow(10, this.gainDb / 40);
- [b0, b1, b2] = [1 + alpha * lift, -2 * cos, 1 - alpha * lift];
- [a0, a1, a2] = [1 + alpha / lift, -2 * cos, 1 - alpha / lift];
- break;
- }
- default: [b0, b1, b2] = [1, -2 * cos, 1];
- }
- [this.b0, this.b1, this.b2, this.a1, this.a2] = [b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0];
- }
-
- run(x: number): number {
- const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2;
- [this.x2, this.x1, this.y2, this.y1] = [this.x1, x, this.y1, y];
- return y;
- }
-}
-
-const rmsOf = (a: Float32Array): number => { let s = 0; for (const v of a) s += v * v; return Math.sqrt(s / Math.max(1, a.length)); };
-
-/** @p count samples of a noise layer's own sound, before its loudness is shaped: its colour, and its band at the level of the whole. */
-function noiseBody(layer: SoundLayer, count: number, rate: number, seed: number, pitch: number): Float32Array {
- const random = noiseOf(seed);
- const out = new Float32Array(count);
- // Pink and brown are white put through a few poles; these are their memories.
- let [p0, p1, p2, brown] = [0, 0, 0, 0];
- for (let n = 0; n < count; n++) {
- const white = random();
- if (layer.color === 'pink') {
- p0 = 0.99765 * p0 + white * 0.099046;
- p1 = 0.963 * p1 + white * 0.2965164;
- p2 = 0.57 * p2 + white * 1.0526913;
- out[n] = (p0 + p1 + p2 + white * 0.1848) * 0.25;
- } else if (layer.color === 'brown') {
- brown = (brown + white * 0.02) / 1.02;
- out[n] = brown * 3.5;
- } else out[n] = white;
- }
- if (layer.band) {
- // Cut to the band, then brought back up: what is left of noise after two filters is faint, and a band that
- // had to be turned up by guess would never balance against the others.
- const [high, low] = [new Biquad('highpass', 0.7, rate), new Biquad('lowpass', 0.7, rate)];
- high.tune(layer.band[0] * pitch);
- low.tune(layer.band[1] * pitch);
- // Run in a little first, so the filters are not still starting when the sound is.
- for (let n = 0; n < 64; n++) low.run(high.run(random()));
- for (let n = 0; n < count; n++) out[n] = low.run(high.run(out[n]!));
- const level = rmsOf(out);
- if (level > 1e-9) for (let n = 0; n < count; n++) out[n]! *= NOISE_LEVEL / level;
- }
- return out;
-}
-
-/** A recording a layer plays: its samples and the rate they were made at. */
-export interface SoundRecording { rate: number; channels: readonly Float32Array[] }
-
-/** @p count samples of a recording, its two sides as one, played at @p speed from @p from seconds in. Past its end is silence. */
-function recordingBody(recording: SoundRecording, count: number, rate: number, speed: number, from: number): Float32Array {
- const out = new Float32Array(count);
- const [l, r] = [recording.channels[0]!, recording.channels[1] ?? recording.channels[0]!];
- const step = (speed * recording.rate) / rate;
- const start = from * recording.rate;
- for (let n = 0; n < count; n++) {
- const p = start + n * step;
- const i = Math.floor(p);
- if (i + 1 >= l.length) break;
- const t = p - i;
- out[n] = ((l[i]! + r[i]!) * (1 - t) + (l[i + 1]! + r[i + 1]!) * t) / 2;
- }
- return out;
-}
-
-/** One striking of a layer: its samples from its own start, at @p pitch times its written pitch. */
-function strike(layer: SoundLayer, seconds: number, rate: number, pitch: number, seed: number, recording: SoundRecording | null = null): Float32Array {
- const count = Math.max(1, Math.round(seconds * rate));
- const out = new Float32Array(count);
- const filters = (layer.filters ?? []).map((f) => ({ run: new Biquad(f.type, f.q ?? 0.7, rate, f.gain ?? 0), freq: f.freq }));
- // The fades that only stop a click are never most of a short layer: a strike two milliseconds long keeps its front.
- const [attack, release] = [layer.attack ?? (layer.source === 'impulse' ? 0 : Math.min(0.002, seconds * 0.1)), layer.release ?? Math.min(0.01, seconds * 0.25)];
- const drive = layer.drive ?? 0;
- const push = 1 + drive * 14;
- const pushed = Math.tanh(push);
- // What is made ahead of the loop: a noise, or a recording played at its speed.
- const noise = layer.source === 'noise' ? noiseBody(layer, count, rate, seed, pitch)
- : layer.source === 'sample' ? recordingBody(recording!, count, rate, (layer.speed ?? 1) * pitch, layer.from ?? 0) : null;
- // A spike: up in one sample and down over its width, as the air does in front of a bang.
- const spike = layer.source === 'impulse' ? (layer.width ?? 0.0002) * rate : 0;
- let [phase, bend] = [0, 0];
-
- for (let n = 0; n < count; n++) {
- const t = n / rate;
- let v: number;
- if (noise) v = noise[n]!;
- else if (layer.source === 'impulse') {
- const b = n / spike;
- v = b < 10 ? (1 - b) * Math.exp(-b) : 0;
- } else if (layer.source === 'modes') {
- v = 0;
- for (const [hz, loud, dies] of layer.modes!) {
- const f = hz * pitch;
- if (f < rate * 0.48) v += loud * Math.exp(-t / dies) * Math.sin(TAU * f * t);
- }
- } else {
- let hz = curveAt(layer.freq, t, 440, true) * pitch;
- if (layer.vibrato) hz *= Math.pow(2, (layer.vibrato.depth * Math.sin(TAU * layer.vibrato.rate * t)) / 12);
- const step = Math.min(0.49, hz / rate);
- phase += step;
- if (phase >= 1) phase -= Math.floor(phase);
- let at = phase;
- if (layer.fm) {
- bend += step * layer.fm.ratio;
- if (bend >= 1) bend -= Math.floor(bend);
- at = phase + (curveAt(layer.fm.index, t, 0, false) * Math.sin(TAU * bend)) / TAU;
- at -= Math.floor(at);
- }
- switch (layer.source) {
- case 'sine': v = Math.sin(TAU * at); break;
- case 'triangle': v = 1 - 4 * Math.abs(at - 0.5); break;
- case 'saw': v = 2 * at - 1 - (layer.fm ? 0 : polyBlep(at, step)); break;
- default: {
- const width = layer.width ?? 0.5;
- v = at < width ? 1 : -1;
- if (!layer.fm) v += polyBlep(at, step) - polyBlep((at - width + 1) % 1, step);
- }
- }
- }
- for (const f of filters) {
- // The corner is read every 16 samples: often enough for a sweep, seldom enough to cost little. A noise struck
- // at another pitch has no pitch of its own to move, so its filters move instead.
- if ((n & 15) === 0) f.run.tune(curveAt(f.freq, t, 1000, true) * (noise ? pitch : 1));
- v = f.run.run(v);
- }
- if (drive > 0) v = Math.tanh(v * push) / pushed;
- let level = curveAt(layer.gain, t, 1, false);
- if (layer.decay) {
- const fast = Math.exp(-t / layer.decay);
- level *= layer.tail ? fast * (1 - layer.tail.mix) + Math.exp(-t / layer.tail.decay) * layer.tail.mix : fast;
- }
- if (layer.tremolo) level *= 1 - layer.tremolo.depth * (0.5 + 0.5 * Math.sin(TAU * layer.tremolo.rate * t));
- if (attack > 0 && t < attack) level *= t / attack;
- const left = seconds - t;
- if (release > 0 && left < release) level *= Math.max(0, left / release);
- out[n] = v * level;
- }
- return out;
-}
-
-/** @p a and @p b laid over one another at every offset: what a sound becomes in a place whose answer to a click is @p b. */
-export function convolve(a: Float32Array, b: Float32Array, keep: number): Float32Array {
- let size = 1;
- while (size < a.length + b.length) size <<= 1;
- const [ar, ai, br, bi] = [new Float64Array(size), new Float64Array(size), new Float64Array(size), new Float64Array(size)];
- ar.set(a); br.set(b);
- fft(ar, ai); fft(br, bi);
- for (let k = 0; k < size; k++) {
- const [re, im] = [ar[k]! * br[k]! - ai[k]! * bi[k]!, ar[k]! * bi[k]! + ai[k]! * br[k]!];
- // Back the same way: the transform of the conjugate, conjugated and shared out.
- ar[k] = re; ai[k] = -im;
- }
- fft(ar, ai);
- const out = new Float32Array(keep);
- for (let n = 0; n < keep; n++) out[n] = ar[n]! / size;
- return out;
-}
-
-/**
- * What a place answers to one click, for one ear. A room: noise in three bands that each die at their own rate, the
- * top in half the time of the bottom, coming up over a hundredth of a second, with thirty-odd distinct first echoes
- * ahead of it. Open ground: a few slaps off far walls, each duller than the last, and a long faint tail.
- */
-export function placeResponse(rate: number, size: number, kind: 'room' | 'open', side: number): Float32Array {
- const random = noiseOf(kind === 'room' ? 6923 + side * 977 : 32324 + side * 977);
- const unit = (): number => random() * 0.5 + 0.5;
- const seconds = kind === 'room' ? 0.35 + size * 2.4 : 0.6 + size * 2.6;
- const count = Math.floor(rate * seconds);
- const out = new Float32Array(count);
- const banded = (low: number | null, high: number | null): Float32Array => {
- const buf = new Float32Array(count);
- const [hp, lp] = [low ? new Biquad('highpass', 0.6, rate) : null, high ? new Biquad('lowpass', 0.6, rate) : null];
- hp?.tune(low!); lp?.tune(high!);
- for (let n = 0; n < count; n++) { let v = random(); if (hp) v = hp.run(v); if (lp) v = lp.run(v); buf[n] = v; }
- const level = rmsOf(buf) || 1;
- for (let n = 0; n < count; n++) buf[n]! /= level;
- return buf;
- };
- if (kind === 'room') {
- // Seconds for each band to fall by sixty decibels.
- const long = 0.25 + size * 1.5;
- const bands: [Float32Array, number, number][] = [[banded(null, 420), 0.45, long], [banded(420, 3000), 1, long * 0.8], [banded(3000, null), 1.6, long * 0.4]];
- for (let n = 0; n < count; n++) {
- const t = n / rate;
- const rise = 1 - Math.exp(-t / 0.014);
- let v = 0;
- for (const [buf, loud, falls] of bands) v += buf[n]! * loud * Math.pow(10, (-3 * t) / falls);
- out[n] = v * rise;
- }
- const wash = rmsOf(out) * Math.sqrt(count);
- const first = new Float32Array(count);
- for (let e = 0; e < 34; e++) {
- const t = (0.0048 + 0.088 * Math.pow((e + unit()) / 34, 1.5)) * (0.45 + size) * (side ? 1.07 : 1);
- const at = Math.floor(t * rate);
- const loud = (random() < 0 ? -1 : 1) * Math.exp(-t / 0.034) * (0.55 + 0.45 * unit());
- // Later echoes have travelled further and are smeared wider.
- const width = 1 + Math.floor(t * 60);
- for (let n = 0; n < width && at + n < count; n++) first[at + n]! += (loud * (1 - n / width)) / Math.sqrt(width);
- }
- const firstLevel = rmsOf(first) * Math.sqrt(count) || 1;
- for (let n = 0; n < count; n++) out[n]! += first[n]! * ((0.78 * wash) / firstLevel);
- } else {
- for (const [t, loud, milliseconds, top] of [[0.094, 0.5, 5, 5200], [0.151, 0.4, 8, 3800], [0.212, 0.31, 12, 2700], [0.289, 0.24, 16, 2000]] as const) {
- const length = Math.floor((rate * milliseconds * 4) / 1000);
- const [lp, hp] = [new Biquad('lowpass', 0.6, rate), new Biquad('highpass', 0.6, rate)];
- lp.tune(top); hp.tune(180);
- const slap = new Float32Array(length);
- for (let n = 0; n < length; n++) slap[n] = hp.run(lp.run(random())) * Math.exp(-n / ((rate * milliseconds) / 1000)) * (1 - Math.exp(-n / (rate * 0.0006)));
- const level = rmsOf(slap) * Math.sqrt(length) || 1;
- const at = Math.floor(rate * t * (0.5 + size) * (1 + 0.1 * random() * 0.5));
- const share = (loud * (0.45 + 0.55 * (side ? 1 - unit() : unit()))) / level;
- for (let n = 0; n < length && at + n < count; n++) out[at + n]! += slap[n]! * share;
- }
- const slaps = rmsOf(out) * Math.sqrt(count) || 1;
- const tail = banded(320, 2300);
- const falls = 1 + size * 2;
- let tailSquares = 0;
- for (let n = 0; n < count; n++) {
- const t = n / rate;
- tail[n] = tail[n]! * Math.pow(10, (-3 * t) / falls) * (1 - Math.exp(-t / 0.11));
- tailSquares += tail[n]! * tail[n]!;
- }
- const tailLevel = Math.sqrt(tailSquares) || 1;
- for (let n = 0; n < count; n++) out[n]! += tail[n]! * ((0.5 * slaps) / tailLevel);
- }
- // Let down at its end, and of one energy whatever its size: `mix` then means the same in a closet and a hall.
- const fade = Math.floor(count * 0.08);
- for (let n = 0; n < fade; n++) out[count - 1 - n]! *= n / fade;
- const energy = rmsOf(out) * Math.sqrt(count) || 1;
- for (let n = 0; n < count; n++) out[n]! /= energy;
- return out;
-}
-
-interface Strike { at: number; pitch: number; loud: number; pan: number; seed: number }
-
-/** When a layer is struck, and how: once, again by `repeat`, or many times at random by `scatter`. */
-function strikesOf(layer: SoundLayer, start: number, seed: number): Strike[] {
- const pan = layer.pan ?? 0;
- if (layer.scatter) {
- const c = layer.scatter;
- const random = noiseOf(seed + 4409);
- const unit = (): number => random() * 0.5 + 0.5;
- const [p0, p1] = c.pitch ?? [1, 1];
- const [g0, g1] = c.gain ?? [1, 1];
- return Array.from({ length: c.count }, (_, k) => {
- const when = Math.pow(unit(), c.early ?? 1);
- return {
- at: start + c.over * when,
- // Between two pitches by ratio, so there are as many strikes in each octave of the range.
- pitch: p0 * Math.pow(p1 / p0, unit()),
- loud: (g0 + (g1 - g0) * unit()) * (1 - (c.fade ?? 0) * when),
- pan: Math.max(-1, Math.min(1, pan + (c.pan ?? 0) * random())),
- seed: seed + k * 131,
- };
- }).sort((a, b) => a.at - b.at);
- }
- const r = layer.repeat;
- const jitter = noiseOf(seed + 7919);
- const out: Strike[] = [];
- let [at, gap] = [start, r?.every ?? 0];
- for (let k = 0; k < (r?.count ?? 1); k++) {
- out.push({ at: at + (k > 0 && r?.jitter ? jitter() * r.jitter : 0), pitch: Math.pow(r?.pitch ?? 1, k), loud: Math.pow(r?.gain ?? 1, k), pan, seed: seed + k * 131 });
- at += gap;
- // A thing bouncing to rest: each gap shorter than the last.
- gap *= r?.faster ?? 1;
- }
- return out;
-}
-
-/** Where and how an event is struck: what a group hands down to the layers in it. */
-interface Placement { offset: number; pitch: number; loud: number; pan: number; seed: number }
-
-/** How a variant of a layer strays from the layer as written. */
-interface Stray { pitch: number; loud: number; decay: number; late: number; seed: number }
-
-/**
- * The samples a validated source makes. @p variant 0 is the sound as written; another is the same sound a little
- * unlike it, as a second shot from the same gun is: other noise, and each layer's pitch, loudness, decay and timing
- * off by up to the source's `vary`.
- *
- * @p at is for a sound played as a note: `pitch` times its written pitch, with `seed` for other noise, and `raw`
- * leaving its level as the layers sum to, so that many notes keep their balance against one another.
- */
-export function renderSound(source: SoundSource, variant = 0, at: { pitch?: number; seed?: number; raw?: boolean; given?: Readonly<Record<string, SoundRecording>> } = {}): RenderedSound {
- const rate = source.rate ?? 44100;
- const count = Math.max(1, Math.round(source.duration * rate));
- // A loop is rendered a little long and its extra folded back over its start, so the end runs into the beginning.
- const fold = source.loop ? Math.min(Math.round(0.08 * rate), Math.floor(count / 2)) : 0;
- const total = count + fold;
- const [left, right] = [new Float32Array(total), new Float32Array(total)];
- const notes: string[] = [];
- const reports: RenderedSound['layers'] = [];
- let stereo = source.reverb !== undefined;
-
- const vary = variant > 0 ? source.vary ?? 0.06 : 0;
- const strayRandom = noiseOf(variant * 7717 + 13);
- const strays = new Map<SoundLayer, Stray>();
- const strayOf = (layer: SoundLayer): Stray => {
- let s = strays.get(layer);
- if (!s) {
- s = vary > 0
- ? { pitch: 1 + vary * strayRandom(), loud: 1 + vary * 2 * strayRandom(), decay: 1 + vary * 1.5 * strayRandom(), late: 1 + vary * strayRandom(), seed: variant * 1009 }
- : { pitch: 1, loud: 1, decay: 1, late: 1, seed: 0 };
- strays.set(layer, s);
- }
- return s;
- };
-
- /** One layer, or a group of them, struck where @p place says. Answers how loud it was and when it ended. */
- const play = (layer: SoundLayer, index: number, where: string, place: Placement, top: boolean): { peak: number; last: number; heard: number; strikes: number } => {
- const stray = strayOf(layer);
- // A layer that comes after the start of its event comes a little sooner or later in another variant.
- const start = place.offset + (layer.start ?? 0) * stray.late;
- const seed = (layer.seed ?? index + 1) + place.seed + stray.seed;
- if (layer.source === 'group') {
- const strikes = strikesOf(layer, start, seed);
- const loud = (typeof layer.gain === 'number' ? layer.gain : 1) * stray.loud;
- let [peak, last, heard] = [0, start, 0];
- for (const s of strikes) {
- if (s.at * rate >= total) continue;
- heard++;
- layer.layers!.forEach((child, j) => {
- if (child.mute) return;
- const made = play(child, j, `${where} > layer ${j}${child.id ? ` "${child.id}"` : ''}`,
- { offset: s.at, pitch: place.pitch * s.pitch, loud: place.loud * s.loud * loud, pan: Math.max(-1, Math.min(1, place.pan + s.pan)), seed: s.seed + j * 977 }, false);
- peak = Math.max(peak, made.peak);
- last = Math.max(last, made.last);
- });
- }
- return { peak, last, heard, strikes: strikes.length };
- }
- const space = total / rate - start;
- const recording = layer.source === 'sample' ? at.given?.[layer.file!] ?? null : null;
- if (layer.source === 'sample' && !recording) throw new Error(`${where}: the recording ${layer.file} was not found`);
- // A recording lasts as long as it lasts, at the speed it is played.
- const whole = recording ? Math.max(0.001, (recording.channels[0]!.length / recording.rate - (layer.from ?? 0)) / ((layer.speed ?? 1) * place.pitch * stray.pitch)) : space;
- const seconds = Math.min(layer.length ?? whole, space);
- if (!(seconds > 0)) {
- if (top) notes.push(`${where} starts at the end of the sound and is not heard`);
- return { peak: 0, last: start, heard: 0, strikes: 0 };
- }
- if (top && layer.length !== undefined && layer.length > space + 1e-6 && !layer.repeat && !layer.scatter) notes.push(`${where} is cut short: it runs ${layer.length} s from ${Math.round(start * 1000) / 1000} s in a sound of ${source.duration} s`);
- const wide = layer.source === 'noise' ? layer.wide ?? 0 : 0;
- // The variant's own layer: the same in everything but how long it rings.
- const made = stray.decay !== 1 && layer.decay
- ? { ...layer, decay: layer.decay * stray.decay, ...(layer.tail ? { tail: { ...layer.tail, decay: layer.tail.decay * stray.decay } } : {}) }
- : layer;
- const strikes = strikesOf(layer, start, seed);
- if (wide > 0 || place.pan !== 0 || strikes.some((s) => s.pan !== 0)) stereo = true;
- let [peak, last, heard] = [0, start, 0];
- for (const s of strikes) {
- const from = Math.round(Math.max(0, s.at) * rate);
- if (from >= total) continue;
- heard++;
- const length = Math.min(seconds, (total - from) / rate);
- const pitch = s.pitch * place.pitch * stray.pitch;
- const loud = s.loud * place.loud * stray.loud;
- // Each striking has its own noise, as no two footsteps are the same grit.
- const hit = strike(made, length, rate, pitch, s.seed, recording);
- // The other ear's noise is another noise, by as much as the layer is wide.
- const other = wide > 0 ? strike(made, length, rate, pitch, s.seed + 50021) : null;
- // Equal power: a sound sent to one side is as loud as one in the middle.
- const pan = Math.max(-1, Math.min(1, s.pan + place.pan));
- const [gl, gr] = [Math.cos(((pan + 1) * Math.PI) / 4), Math.sin(((pan + 1) * Math.PI) / 4)];
- for (let n = 0; n < hit.length && from + n < total; n++) {
- const v = hit[n]! * loud;
- left[from + n]! += v * gl;
- right[from + n]! += (other ? v * (1 - wide) + other[n]! * loud * wide : v) * gr;
- if (Math.abs(v) > peak) peak = Math.abs(v);
- }
- last = Math.max(last, Math.min(total / rate, s.at + hit.length / rate));
- }
- return { peak, last, heard, strikes: strikes.length };
- };
-
- source.layers.forEach((layer, index) => {
- if (layer.mute) return;
- const where = `layer ${index}${layer.id ? ` "${layer.id}"` : ''}`;
- const made = play(layer, index, where, { offset: 0, pitch: at.pitch ?? 1, loud: 1, pan: 0, seed: at.seed ?? 0 }, true);
- const start = layer.start ?? 0;
- reports.push({
- ...(layer.id ? { id: layer.id } : {}), source: layer.source, from: Math.round(start * 1000) / 1000, to: Math.round(made.last * 1000) / 1000,
- peak: Math.round(made.peak * 1000) / 1000, ...(made.strikes > 1 ? { strikes: made.heard } : {}),
- });
- if (made.heard < made.strikes) notes.push(`${where}: ${made.strikes - made.heard} of its ${made.strikes} strikes fall past the end of the sound and are not heard`);
- if (made.strikes > 0 && made.peak < 1e-4) notes.push(`${where} makes no sound: its level is nothing throughout`);
- });
-
- const channels = stereo ? [left, right] : [left.map((v, i) => (v + right[i]!) * Math.SQRT1_2)];
- for (const [c, channel] of channels.entries()) {
- for (const [key, type] of [['highpass', 'highpass'], ['lowpass', 'lowpass']] as const) {
- if (source[key] === undefined) continue;
- const filter = new Biquad(type, 0.7, rate);
- filter.tune(source[key]!);
- for (let n = 0; n < total; n++) channel[n] = filter.run(channel[n]!);
- }
- if (source.echo) {
- const delay = Math.max(1, Math.round(source.echo.time * rate));
- const [feedback, mix] = [source.echo.feedback ?? 0.35, source.echo.mix ?? 0.3];
- const line = new Float32Array(delay);
- for (let n = 0; n < total; n++) {
- const heard = line[n % delay]!;
- line[n % delay] = channel[n]! + heard * feedback;
- channel[n] = channel[n]! + heard * mix;
- }
- }
- if (source.reverb) {
- // The two ears are answered a little differently, which is what makes a place wide.
- const wet = convolve(channel, placeResponse(rate, source.reverb.size ?? 0.5, source.reverb.kind ?? 'room', c), total);
- const mix = source.reverb.mix ?? 0.25;
- for (let n = 0; n < total; n++) channel[n] = channel[n]! + wet[n]! * mix * 3;
- }
- }
-
- const out = channels.map((channel) => {
- const kept = channel.subarray(0, count).slice();
- if (fold > 0) {
- for (let n = 0; n < fold; n++) {
- const w = n / fold;
- kept[n] = kept[n]! * w + channel[count + n]! * (1 - w);
- }
- } else {
- // A sound that stops on a sample that is not nothing clicks: the last three milliseconds are let down.
- const tail = Math.min(count, Math.round(0.003 * rate));
- for (let n = 0; n < tail; n++) kept[count - 1 - n]! *= n / tail;
- }
- return kept;
- });
-
- let peak = 0;
- for (const channel of out) for (const v of channel) if (Math.abs(v) > peak) peak = Math.abs(v);
- const target = source.gain ?? 0.9;
- if (at.raw) {
- // Left as it sums: whoever plays it as a note sets the level of the whole.
- } else if (source.normalize !== false) {
- if (peak > 1e-6) for (const channel of out) for (let n = 0; n < count; n++) channel[n]! *= target / peak;
- else notes.push('the sound is silent: nothing in it reaches a level that can be heard');
- peak = peak > 1e-6 ? target : 0;
- } else {
- for (const channel of out) for (let n = 0; n < count; n++) channel[n]! *= target / 0.9;
- peak *= target / 0.9;
- if (peak > 1) {
- notes.push(`the layers sum to ${peak.toFixed(2)} times full, and what is past full is cut off flat: lower their gain, or leave normalize on`);
- for (const channel of out) for (let n = 0; n < count; n++) channel[n] = Math.max(-1, Math.min(1, channel[n]!));
- peak = 1;
- }
- }
- let squares = 0;
- for (const channel of out) for (const v of channel) squares += v * v;
- return { rate, channels: out, seconds: count / rate, peak, rms: Math.sqrt(squares / (count * out.length)), layers: reports, notes };
-}
-
-/** The samples as a 16-bit PCM `.wav`, which every platform the engine runs on plays. */
-export function encodeWav(sound: { rate: number; channels: readonly Float32Array[] }): Uint8Array {
- const [channels, frames] = [sound.channels.length, sound.channels[0]!.length];
- const bytes = new Uint8Array(44 + frames * channels * 2);
- const view = new DataView(bytes.buffer);
- const text = (at: number, s: string): void => { for (let i = 0; i < s.length; i++) bytes[at + i] = s.charCodeAt(i); };
- text(0, 'RIFF'); view.setUint32(4, 36 + frames * channels * 2, true); text(8, 'WAVE');
- text(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, channels, true);
- view.setUint32(24, sound.rate, true); view.setUint32(28, sound.rate * channels * 2, true); view.setUint16(32, channels * 2, true); view.setUint16(34, 16, true);
- text(36, 'data'); view.setUint32(40, frames * channels * 2, true);
- for (let n = 0; n < frames; n++) {
- for (let c = 0; c < channels; c++) {
- const v = Math.max(-1, Math.min(1, sound.channels[c]![n]!));
- view.setInt16(44 + (n * channels + c) * 2, Math.round(v * 32767), true);
- }
- }
- return bytes;
-}
-
-/** Every variant a source asks for, the first being the sound as written. */
-export function renderSoundVariants(source: SoundSource, given: Readonly<Record<string, SoundRecording>> = {}): RenderedSound[] {
- return Array.from({ length: source.variants ?? 1 }, (_, k) => renderSound(source, k, { given }));
-}
-
-/** A recording as this file's sounds are held, so it can be drawn and measured as they are. */
-export function soundFromSamples(rate: number, channels: readonly Float32Array[]): RenderedSound {
- const kept = channels.slice(0, 2).map((c) => Float32Array.from(c));
- let [peak, squares] = [0, 0];
- for (const channel of kept) for (const v of channel) { if (Math.abs(v) > peak) peak = Math.abs(v); squares += v * v; }
- const frames = kept[0]?.length ?? 0;
- return { rate, channels: kept, seconds: frames / rate, peak, rms: Math.sqrt(squares / Math.max(1, frames * kept.length)), layers: [], notes: [] };
-}
-
-/** A `.wav` read: PCM of 8, 16, 24 or 32 bits, or 32-bit floats. Throws on anything else, saying what it found. */
-export function decodeWav(bytes: Uint8Array): RenderedSound {
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- const tag = (at: number): string => String.fromCharCode(bytes[at]!, bytes[at + 1]!, bytes[at + 2]!, bytes[at + 3]!);
- if (bytes.length < 44 || tag(0) !== 'RIFF' || tag(8) !== 'WAVE') throw new Error('not a .wav: it does not begin RIFF....WAVE');
- let [format, channels, rate, bits] = [0, 0, 0, 0];
- let data: { at: number; size: number } | null = null;
- for (let at = 12; at + 8 <= bytes.length;) {
- const size = view.getUint32(at + 4, true);
- if (tag(at) === 'fmt ') {
- format = view.getUint16(at + 8, true);
- channels = view.getUint16(at + 10, true);
- rate = view.getUint32(at + 12, true);
- bits = view.getUint16(at + 22, true);
- // An extensible header says its real format further in.
- if (format === 0xfffe && size >= 26) format = view.getUint16(at + 32, true);
- } else if (tag(at) === 'data') data = { at: at + 8, size: Math.min(size, bytes.length - at - 8) };
- at += 8 + size + (size & 1);
- }
- if (!data || !channels || !rate) throw new Error('a .wav with no format or no samples in it');
- if (!((format === 1 && [8, 16, 24, 32].includes(bits)) || (format === 3 && bits === 32))) throw new Error(`a .wav of a kind not read here (format ${format}, ${bits} bits); PCM of 8 to 32 bits and 32-bit floats are`);
- const step = bits / 8;
- const frames = Math.floor(data.size / (step * channels));
- const out = Array.from({ length: channels }, () => new Float32Array(frames));
- for (let n = 0; n < frames; n++) {
- for (let c = 0; c < channels; c++) {
- const at = data.at + (n * channels + c) * step;
- out[c]![n] = format === 3 ? view.getFloat32(at, true)
- : bits === 8 ? (bytes[at]! - 128) / 128
- : bits === 16 ? view.getInt16(at, true) / 32768
- : bits === 24 ? ((bytes[at]! | (bytes[at + 1]! << 8) | (view.getInt8(at + 2) << 16))) / 8388608
- : view.getInt32(at, true) / 2147483648;
- }
- }
- return soundFromSamples(rate, out);
-}
+// The synthesis is the engine's (sdk/src/sound): a package that ships a sound as its source makes it with the same code the editor bakes it with.
+export * from '../../../sdk/src/sound/soundRender';
diff --git a/pipeline/src/sound/soundSource.ts b/pipeline/src/sound/soundSource.ts
index bc01c453f..ed6da1462 100644
--- a/pipeline/src/sound/soundSource.ts
+++ b/pipeline/src/sound/soundSource.ts
@@ -1,401 +1,4 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file soundSource.ts — `.essound`: a sound as the layers that make it, what a model writes and edits, and what is wrong with one.
- *
- * A picture is layers of shapes and a model is steps; a sound effect is layers too. A gunshot is a crack of
- * noise, a thump under it and a tail; a footstep is a thud and a scrape; a glass is a handful of ringing tones.
- * Each layer is one source (a tone, a noise, or a struck body's ringing), shaped in time by an envelope and in
- * colour by filters, and the layers are summed. What is saved is this description, and the `.wav` a game plays is
- * made from it, so a sound is changed by changing a number and never by recording again.
- *
- * Nothing here is random that is not seeded: the same source is the same samples on every machine.
- */
-
-export const SOUND_SOURCE_EXT = '.essound';
-export const SOUND_SOURCE_VERSION = 1;
-export const MAX_SOUND_SECONDS = 30;
-export const SOUND_RATES = [22050, 44100, 48000] as const;
-
-/** One value for the whole of a layer, or [[seconds, value], ...] from the layer's start: a pitch that falls, a filter that opens. */
-export type SoundCurve = number | readonly (readonly [number, number])[];
-
-export const SOUND_SOURCES = ['sine', 'triangle', 'saw', 'square', 'noise', 'modes', 'impulse', 'sample', 'group'] as const;
-export const MAX_SOUND_VARIANTS = 8;
-export type SoundSourceKind = (typeof SOUND_SOURCES)[number];
-export const SOUND_FILTERS = ['lowpass', 'highpass', 'bandpass', 'notch', 'peak'] as const;
-export const REVERB_KINDS = ['room', 'open'] as const;
-export const NOISE_COLORS = ['white', 'pink', 'brown'] as const;
-
-export interface SoundFilter {
- type: (typeof SOUND_FILTERS)[number];
- /** Hz, 20..20000. */
- freq: SoundCurve;
- /** How narrow: 0.7 is plain, 5 rings, 20 whistles. Default 0.7. */
- q?: number;
- /** peak: dB it lifts (or with a minus, cuts) round `freq`, -24..24: the note a barrel, a box or a room adds. */
- gain?: number;
-}
-
-export interface SoundLayer {
- id?: string;
- source: SoundSourceKind;
- /**
- * group: the layers that make one event, struck together. A footstep is a thud, a scrape and two clicks, and four
- * footsteps are that one group with `repeat`, each striking with its own grit, in place of the layers written out
- * four times. The group's `start`, `gain`, `pan`, `repeat` and `scatter` are the event's; each layer in it keeps its
- * own start, counted from the event's.
- */
- layers?: readonly SoundLayer[];
- /** A tone's pitch in Hz; a curve glides between its points as the ear hears pitch. */
- freq?: SoundCurve;
- /** square: the share of each cycle it is high, 0.05..0.95. Default 0.5. impulse: seconds its one spike lasts, 0.00002..0.02; a shot's is 0.0002. */
- width?: number;
- /**
- * noise: only what lies between these two Hz, brought back to the level of the whole. A real bang is several bands
- * of noise that die at different rates, the high ones first, and this is one of them.
- */
- band?: readonly [number, number];
- /** noise: how unlike its two sides are, 0..1. It makes the file stereo, and a wide crack fills the head where a narrow one sits in the middle. */
- wide?: number;
- /** noise: white is hiss, pink is rain, brown is a rumble. Default white. */
- color?: (typeof NOISE_COLORS)[number];
- /**
- * sample: a recording in the project, by its path, played as a layer among the made ones: the real crack of a
- * branch under made leaves, a voice, the one sound that will not come out of waves and noise. Everything a layer
- * has shapes it as it shapes the rest: an envelope, filters, a drive, repeats, a scatter.
- */
- file?: string;
- /** sample: how fast it is played, 0.25..4; 2 is an octave up and half as long. Default 1. */
- speed?: number;
- /** sample: seconds into the recording that it starts from. Default 0. */
- from?: number;
- /** modes: each [Hz, loudness, seconds to die away], the tones a struck thing rings with. */
- modes?: readonly (readonly [number, number, number])[];
- seed?: number;
- /** Seconds into the sound that it begins. Default 0. */
- start?: number;
- /** Seconds it lasts. Default: to the end of the sound. */
- length?: number;
- /** Loudness, 1 being full; a curve shapes it over the layer. Default 1. */
- gain?: SoundCurve;
- /** Seconds to rise from nothing, and to fall to nothing at its end. Defaults 0.002 and 0.01, which only stop a click. */
- attack?: number;
- release?: number;
- /** Dies away of itself: seconds to fall to about a third. A hit, a pluck, a drop. */
- decay?: number;
- /** With `decay`: a share `mix` of it dies more slowly, in `decay` seconds of its own. The body of a bang goes at once and its ring lingers. */
- tail?: { decay: number; mix: number };
- /** Wavers in pitch: `rate` times a second, `depth` semitones each way. */
- vibrato?: { rate: number; depth: number };
- /** Wavers in loudness: `rate` times a second, by `depth` 0..1. */
- tremolo?: { rate: number; depth: number };
- /** A second tone bending this one: at `ratio` times its pitch, by `index` (0 is none, 2 is brassy, 8 is a clang). Metal, bells, lasers. */
- fm?: { ratio: number; index: SoundCurve };
- /** In order, each working on what the one before left. */
- filters?: readonly SoundFilter[];
- /** Pushed into distortion, 0..1: grit, fuzz, a speaker torn. */
- drive?: number;
- /** -1 is left, 1 is right. Default 0. */
- pan?: number;
- /** The layer struck again: `count` times in all, `every` seconds apart, each `gain` times as loud and `pitch` times as high as the last, off the beat by up to `jitter` seconds. */
- repeat?: { count: number; every: number; gain?: number; pitch?: number; jitter?: number; faster?: number };
- /**
- * The layer struck many times at random: `count` strikes within `over` seconds, crowded toward the start by
- * `early` (1 is even, 2.3 is a crash), each at a pitch between the two of `pitch` times its own, as loud as between
- * the two of `gain`, thrown to either side by up to `pan`, the later ones quieter by `fade`. Breaking glass is four
- * hundred short rings scattered like this; so are gravel, rain, sparks and applause.
- */
- scatter?: { count: number; over: number; early?: number; pitch?: readonly [number, number]; gain?: readonly [number, number]; pan?: number; fade?: number };
- /** Left out of the sound, kept in the source. */
- mute?: boolean;
-}
-
-export interface SoundSource {
- version?: number;
- /** Seconds. */
- duration: number;
- /** Samples a second. Default 44100. */
- rate?: number;
- /** Its end runs into its start with no click, for an engine, a wind, a hum. */
- loop?: boolean;
- /**
- * How many of it to make, 1..8, each a little unlike the others: other noise, and pitch, loudness, decay and timing
- * off by up to `vary`. A game that plays the same file for every shot or step is heard as a machine however good the
- * file; with variants a sound event is written beside them that plays one after another without repeating.
- */
- variants?: number;
- /** How far a variant strays, 0..0.3. Default 0.06. */
- vary?: number;
- /** A recording to make it like, by project path. It is shown above the sound in every reply, drawn the same way to the same scale, and measured the same way. Nothing is taken from it. */
- reference?: string;
- layers: readonly SoundLayer[];
- /** Over the whole sound, after the layers are summed: */
- highpass?: number;
- lowpass?: number;
- /** A repeat of the whole: `time` seconds later, `feedback` 0..0.95 of each into the next, `mix` 0..1 of it in the sound. */
- echo?: { time: number; feedback?: number; mix?: number };
- /**
- * A place round it: `size` 0..1 from a closet to a hall, `mix` 0..1 of it in the sound. `kind` "room" is walls
- * close by, with first echoes and a wash whose top dies before its bottom; "open" is a street or a yard: a few
- * distinct slaps off far walls and a long thin tail.
- */
- reverb?: { size?: number; mix?: number; kind?: (typeof REVERB_KINDS)[number] };
- /** Loudness of the whole. With `normalize` it is how loud the loudest moment is, 1 being full. Default 0.9. */
- gain?: number;
- /** false leaves the levels as the layers sum to. Default true: the loudest moment is brought to `gain`. */
- normalize?: boolean;
-}
-
-const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
-const between = (v: unknown, lo: number, hi: number): boolean => isNum(v) && v >= lo && v <= hi;
-
-function curveProblem(v: unknown, lo: number, hi: number, what: string): string | null {
- if (isNum(v)) return v >= lo && v <= hi ? null : `${what} must be ${lo}..${hi}`;
- if (!Array.isArray(v) || v.length < 2) return `${what} must be a number, or two or more [seconds, value]`;
- let last = -Infinity;
- for (const p of v) {
- if (!Array.isArray(p) || p.length !== 2 || !isNum(p[0]) || !isNum(p[1])) return `${what} must be [seconds, value] pairs`;
- if (p[0] < 0) return `${what}: a time is seconds from the layer's start, none below 0`;
- if (p[0] <= last) return `${what}: its times must rise`;
- if (p[1] < lo || p[1] > hi) return `${what}: each value must be ${lo}..${hi}`;
- last = p[0];
- }
- return null;
-}
-
-const LAYER_FIELDS = ['id', 'source', 'freq', 'width', 'band', 'wide', 'color', 'modes', 'file', 'speed', 'from', 'seed', 'start', 'length', 'gain', 'attack', 'release', 'decay', 'tail', 'vibrato', 'tremolo', 'fm', 'filters', 'drive', 'pan', 'repeat', 'scatter', 'mute'];
-
-const GROUP_FIELDS = ['id', 'source', 'layers', 'start', 'gain', 'pan', 'repeat', 'scatter', 'mute'];
-
-function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>, duration: number, depth = 0): void {
- const fail = (what: string): never => { throw new Error(`${where}: ${what}`); };
- if (typeof l !== 'object' || l === null || Array.isArray(l)) fail('must be an object');
- if (l.source === 'group') {
- for (const key of Object.keys(l)) if (!GROUP_FIELDS.includes(key)) fail(`a group takes ${GROUP_FIELDS.join(', ')}; "${key}" belongs on the layers in it`);
- if (depth >= 3) fail('groups go three deep and no further');
- if (!Array.isArray(l.layers) || l.layers.length === 0) fail('a group needs `layers`: one or more');
- if (l.gain !== undefined && !between(l.gain, 0, 4)) fail('a group\'s gain is one number, 0..4');
- } else if (l.layers !== undefined) fail('`layers` goes with source "group"');
- if (l.source !== 'group') for (const key of Object.keys(l)) if (!LAYER_FIELDS.includes(key)) fail(`unknown field "${key}"; a layer takes ${LAYER_FIELDS.join(', ')}`);
- if (l.id !== undefined) {
- if (typeof l.id !== 'string' || !l.id) fail('id must be a name');
- if (ids.has(l.id as string)) fail(`the id "${String(l.id)}" is already used`);
- ids.add(l.id as string);
- }
- if (!SOUND_SOURCES.includes(l.source as SoundSourceKind)) fail(`source ${JSON.stringify(l.source)} must be one of ${SOUND_SOURCES.join(', ')}`);
- const tone = l.source !== 'noise' && l.source !== 'modes' && l.source !== 'impulse' && l.source !== 'group' && l.source !== 'sample';
- if (l.source === 'sample') {
- if (typeof l.file !== 'string' || !/\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i.test(l.file)) fail('a sample needs file: a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)');
- if (l.speed !== undefined && !between(l.speed, 0.25, 4)) fail('speed must be 0.25..4');
- if (l.from !== undefined && !between(l.from, 0, 600)) fail('from must be seconds into the recording, 0 or more');
- } else for (const key of ['file', 'speed', 'from']) if (l[key] !== undefined) fail(`${key} goes with source "sample"`);
- if (tone) {
- if (l.freq === undefined) fail(`a ${String(l.source)} needs freq, its pitch in Hz`);
- const bad = curveProblem(l.freq, 10, 20000, 'freq');
- if (bad) fail(bad);
- } else if (l.freq !== undefined) fail(`freq is a tone's pitch; a ${String(l.source)} has none (give noise its colour with filters, and modes their own Hz)`);
- if (l.width !== undefined) {
- if (l.source === 'square') { if (!between(l.width, 0.05, 0.95)) fail('a square\'s width is the share of a cycle it is high, 0.05..0.95'); }
- else if (l.source === 'impulse') { if (!between(l.width, 0.00002, 0.02)) fail('an impulse\'s width is seconds, 0.00002..0.02'); }
- else fail('width is a square\'s or an impulse\'s');
- }
- if (l.band !== undefined) {
- const b = l.band as unknown[];
- if (l.source !== 'noise') fail('band is a noise\'s: [low Hz, high Hz]');
- if (!Array.isArray(b) || b.length !== 2 || !between(b[0], 20, 20000) || !between(b[1], 20, 20000) || (b[0] as number) >= (b[1] as number)) fail('band must be [low Hz, high Hz], 20..20000, the first below the second');
- }
- if (l.wide !== undefined && !(l.source === 'noise' && between(l.wide, 0, 1))) fail('wide is a noise\'s, 0..1');
- if (l.tail !== undefined) {
- const t = l.tail as Record<string, unknown> | null;
- if (l.decay === undefined) fail('tail is the slow part of a decay: give decay too');
- if (typeof t !== 'object' || t === null || !(isNum(t.decay) && t.decay > 0) || !between(t.mix, 0, 1) || Object.keys(t).length !== 2) fail('tail must be { decay: seconds above 0, mix: 0..1 }');
- }
- if (l.color !== undefined && !(l.source === 'noise' && NOISE_COLORS.includes(l.color as never))) fail(`color is a noise's: ${NOISE_COLORS.join(', ')}`);
- if (l.source === 'modes') {
- const modes = l.modes;
- if (!Array.isArray(modes) || modes.length === 0 || modes.length > 64) fail('modes needs `modes`: 1 to 64 of [Hz, loudness, seconds to die away]');
- for (const m of modes as unknown[]) {
- if (!Array.isArray(m) || m.length !== 3 || !between(m[0], 10, 20000) || !between(m[1], 0, 4) || !between(m[2], 0.001, MAX_SOUND_SECONDS)) fail('each mode must be [Hz 10..20000, loudness 0..4, seconds above 0]');
- }
- } else if (l.modes !== undefined) fail('`modes` goes with source "modes"');
- if (l.seed !== undefined && !Number.isInteger(l.seed)) fail('seed must be a whole number');
- if (l.start !== undefined && !between(l.start, 0, duration)) fail(`start must be 0..${duration}, inside the sound`);
- if (l.length !== undefined && !(isNum(l.length) && l.length > 0)) fail('length must be above 0');
- if (l.gain !== undefined && l.source !== 'group') { const bad = curveProblem(l.gain, 0, 4, 'gain'); if (bad) fail(bad); }
- for (const key of ['attack', 'release']) if (l[key] !== undefined && !between(l[key], 0, MAX_SOUND_SECONDS)) fail(`${key} must be seconds, 0 or more`);
- if (l.decay !== undefined && !(isNum(l.decay) && l.decay > 0)) fail('decay must be seconds above 0');
- const wobble = (key: string, deepest: number): void => {
- const w = l[key] as Record<string, unknown> | undefined;
- if (w === undefined) return;
- if (typeof w !== 'object' || w === null || !between(w.rate, 0.01, 2000) || !between(w.depth, 0, deepest) || Object.keys(w).length !== 2) fail(`${key} must be { rate: times a second, depth: 0..${deepest} }`);
- };
- wobble('vibrato', 24);
- wobble('tremolo', 1);
- if (l.fm !== undefined) {
- const fm = l.fm as Record<string, unknown> | null;
- if (!tone) fail('fm bends a tone; noise and modes have no pitch to bend');
- if (typeof fm !== 'object' || fm === null || !between(fm.ratio, 0.01, 64) || Object.keys(fm).some((k) => k !== 'ratio' && k !== 'index')) fail('fm must be { ratio: 0.01..64, index }');
- const bad = curveProblem(fm!.index, 0, 64, 'fm.index');
- if (bad) fail(bad);
- }
- if (l.filters !== undefined) {
- if (!Array.isArray(l.filters) || l.filters.length > 8) fail('filters must be a list of up to 8');
- (l.filters as Record<string, unknown>[]).forEach((f, i) => {
- if (typeof f !== 'object' || f === null) fail(`filter ${i} must be { type, freq, q? }`);
- for (const key of Object.keys(f)) if (!['type', 'freq', 'q', 'gain'].includes(key)) fail(`filter ${i} has unknown "${key}"; it takes type, freq, q, gain`);
- if (f.type === 'peak' ? !between(f.gain, -24, 24) : f.gain !== undefined) fail(`filter ${i}: gain is a peak's, in dB, -24..24`);
- if (!SOUND_FILTERS.includes(f.type as never)) fail(`filter ${i}: type must be one of ${SOUND_FILTERS.join(', ')}`);
- const bad = curveProblem(f.freq, 20, 20000, `filter ${i}: freq`);
- if (bad) fail(bad);
- if (f.q !== undefined && !between(f.q, 0.1, 40)) fail(`filter ${i}: q must be 0.1..40`);
- });
- }
- if (l.drive !== undefined && !between(l.drive, 0, 1)) fail('drive must be 0..1');
- if (l.pan !== undefined && !between(l.pan, -1, 1)) fail('pan must be -1..1');
- if (l.repeat !== undefined) {
- const r = l.repeat as Record<string, unknown> | null;
- if (typeof r !== 'object' || r === null) fail('repeat must be { count, every, gain?, pitch?, jitter? }');
- for (const key of Object.keys(r!)) if (!['count', 'every', 'gain', 'pitch', 'jitter', 'faster'].includes(key)) fail(`repeat has unknown "${key}"; it takes count, every, gain, pitch, jitter, faster`);
- if (r!.faster !== undefined && !between(r!.faster, 0.2, 1)) fail('repeat.faster is how much shorter each gap is than the last, 0.2..1: a thing bouncing to rest');
- if (l.scatter !== undefined) fail('a layer is struck by repeat or by scatter, not both');
- if (!Number.isInteger(r!.count) || (r!.count as number) < 2 || (r!.count as number) > 200) fail('repeat.count must be a whole number, 2..200');
- if (!(isNum(r!.every) && (r!.every as number) > 0)) fail('repeat.every must be seconds above 0');
- if (r!.gain !== undefined && !between(r!.gain, 0, 2)) fail('repeat.gain must be 0..2');
- if (r!.pitch !== undefined && !between(r!.pitch, 0.25, 4)) fail('repeat.pitch must be 0.25..4');
- if (r!.jitter !== undefined && !between(r!.jitter, 0, 1)) fail('repeat.jitter must be 0..1 seconds');
- }
- if (l.scatter !== undefined) {
- const c = l.scatter as Record<string, unknown> | null;
- if (typeof c !== 'object' || c === null) fail('scatter must be { count, over, early?, pitch?, gain?, pan?, fade? }');
- for (const key of Object.keys(c!)) if (!['count', 'over', 'early', 'pitch', 'gain', 'pan', 'fade'].includes(key)) fail(`scatter has unknown "${key}"; it takes count, over, early, pitch, gain, pan, fade`);
- if (!Number.isInteger(c!.count) || (c!.count as number) < 2 || (c!.count as number) > 2000) fail('scatter.count must be a whole number, 2..2000');
- if (!(isNum(c!.over) && (c!.over as number) > 0)) fail('scatter.over must be seconds above 0');
- if (c!.early !== undefined && !between(c!.early, 0.3, 6)) fail('scatter.early must be 0.3..6');
- const range = (key: string, lo: number, hi: number): void => {
- const v = c![key] as unknown[] | undefined;
- if (v === undefined) return;
- if (!Array.isArray(v) || v.length !== 2 || !between(v[0], lo, hi) || !between(v[1], lo, hi) || (v[0] as number) > (v[1] as number)) fail(`scatter.${key} must be [low, high], ${lo}..${hi}`);
- };
- range('pitch', 0.1, 10);
- range('gain', 0, 2);
- for (const key of ['pan', 'fade']) if (c![key] !== undefined && !between(c![key], 0, 1)) fail(`scatter.${key} must be 0..1`);
- }
- if (l.mute !== undefined && typeof l.mute !== 'boolean') fail('mute must be true or false');
- if (l.source === 'group') (l.layers as Record<string, unknown>[]).forEach((c, i) => checkLayer(c, `${where} > layer ${i}${c?.id ? ` "${String(c.id)}"` : ''}`, ids, duration, depth + 1));
-}
-
-const SOURCE_FIELDS = ['version', 'duration', 'rate', 'loop', 'variants', 'vary', 'reference', 'layers', 'highpass', 'lowpass', 'echo', 'reverb', 'gain', 'normalize'];
-
-/** The recordings a sound's layers play, each once. */
-export function soundSampleFiles(source: Pick<SoundSource, 'layers'>): string[] {
- const files = new Set<string>();
- const walk = (layers: readonly SoundLayer[]): void => { for (const l of layers) { if (l.source === 'sample' && l.file) files.add(l.file); if (l.layers) walk(l.layers); } };
- walk(source.layers);
- return [...files];
-}
-
-/** The source if it is well formed; otherwise throws, naming the layer and the field. */
-export function validateSoundSource(raw: unknown): SoundSource {
- if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) throw new Error('a sound source must be { duration, layers }');
- const s = raw as Record<string, unknown>;
- for (const key of Object.keys(s)) if (!SOURCE_FIELDS.includes(key)) throw new Error(`unknown field "${key}"; a sound has ${SOURCE_FIELDS.join(', ')}`);
- if (s.version !== undefined && s.version !== SOUND_SOURCE_VERSION) throw new Error(`version ${String(s.version)} is not one this editor reads (${SOUND_SOURCE_VERSION})`);
- if (!(isNum(s.duration) && s.duration > 0 && s.duration <= MAX_SOUND_SECONDS)) throw new Error(`duration must be seconds, above 0 and up to ${MAX_SOUND_SECONDS}`);
- if (s.rate !== undefined && !SOUND_RATES.includes(s.rate as never)) throw new Error(`rate must be one of ${SOUND_RATES.join(', ')}`);
- if (s.loop !== undefined && typeof s.loop !== 'boolean') throw new Error('loop must be true or false');
- if (s.variants !== undefined && !(Number.isInteger(s.variants) && (s.variants as number) >= 1 && (s.variants as number) <= MAX_SOUND_VARIANTS)) throw new Error(`variants must be a whole number, 1..${MAX_SOUND_VARIANTS}`);
- if (s.vary !== undefined && !between(s.vary, 0, 0.3)) throw new Error('vary must be 0..0.3');
- if (s.reference !== undefined && !(typeof s.reference === 'string' && /\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i.test(s.reference))) throw new Error('reference must be a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)');
- if (s.normalize !== undefined && typeof s.normalize !== 'boolean') throw new Error('normalize must be true or false');
- if (s.gain !== undefined && !between(s.gain, 0, 1)) throw new Error('gain must be 0..1');
- for (const key of ['highpass', 'lowpass']) if (s[key] !== undefined && !between(s[key], 20, 20000)) throw new Error(`${key} must be Hz, 20..20000`);
- if (s.echo !== undefined) {
- const e = s.echo as Record<string, unknown> | null;
- if (typeof e !== 'object' || e === null || !between(e.time, 0.01, 2)) throw new Error('echo must be { time: 0.01..2 seconds, feedback?, mix? }');
- for (const key of Object.keys(e)) if (!['time', 'feedback', 'mix'].includes(key)) throw new Error(`echo has unknown "${key}"; it takes time, feedback, mix`);
- if (e.feedback !== undefined && !between(e.feedback, 0, 0.95)) throw new Error('echo.feedback must be 0..0.95');
- if (e.mix !== undefined && !between(e.mix, 0, 1)) throw new Error('echo.mix must be 0..1');
- }
- if (s.reverb !== undefined) {
- const r = s.reverb as Record<string, unknown> | null;
- if (typeof r !== 'object' || r === null) throw new Error('reverb must be { size?, mix?, kind? }');
- for (const key of Object.keys(r)) if (!['size', 'mix', 'kind'].includes(key)) throw new Error(`reverb has unknown "${key}"; it takes size, mix, kind`);
- if (r.kind !== undefined && !REVERB_KINDS.includes(r.kind as never)) throw new Error(`reverb.kind must be one of ${REVERB_KINDS.join(', ')}`);
- for (const key of ['size', 'mix']) if (r[key] !== undefined && !between(r[key], 0, 1)) throw new Error(`reverb.${key} must be 0..1`);
- }
- if (!Array.isArray(s.layers) || s.layers.length === 0) throw new Error('layers must be a list of one or more');
- if (s.layers.length > 64) throw new Error('a sound has up to 64 layers');
- const ids = new Set<string>();
- (s.layers as Record<string, unknown>[]).forEach((l, i) => checkLayer(l, `layer ${i}${l?.id ? ` "${String(l.id)}"` : ''}`, ids, s.duration as number));
- return { version: SOUND_SOURCE_VERSION, ...(s as unknown as SoundSource) };
-}
-
-export type SoundEdit =
- | { op: 'set'; layer: string | number; fields: Record<string, unknown> }
- | { op: 'insert'; layer: SoundLayer; before?: string | number; after?: string | number; into?: string }
- | { op: 'remove'; layer: string | number }
- | { op: 'settings'; fields: Partial<Omit<SoundSource, 'layers' | 'version'>> };
-
-/** The source with @p edits applied, in order. A `null` field removes it. Refuses without changing anything. */
-export function applySoundEdits(source: SoundSource, edits: readonly SoundEdit[]): SoundSource {
- const next = JSON.parse(JSON.stringify(source)) as SoundSource & { layers: (SoundLayer & Record<string, unknown>)[] };
- type Row = SoundLayer & Record<string, unknown>;
- const allIds = (list: readonly Row[]): string[] => list.flatMap((l) => [...(l.id ? [l.id] : []), ...allIds((l.layers ?? []) as Row[])]);
- /** The list a layer is in and its place there: by index among the top layers, or by id anywhere, in a group too. */
- const locate = (ref: string | number): { list: Row[]; index: number } => {
- const within = (list: Row[]): { list: Row[]; index: number } | null => {
- for (let i = 0; i < list.length; i++) {
- if (list[i]!.id === ref) return { list, index: i };
- const hit = list[i]!.layers ? within(list[i]!.layers as Row[]) : null;
- if (hit) return hit;
- }
- return null;
- };
- const top = next.layers as Row[];
- const hit = typeof ref === 'number' ? (Number.isInteger(ref) && ref >= 0 && ref < top.length ? { list: top, index: ref } : null) : within(top);
- if (!hit) throw new Error(`no layer ${JSON.stringify(ref)}; ${top.length} layers, ids: ${allIds(top).join(', ') || '(none)'}`);
- return hit;
- };
- for (const edit of edits) {
- switch (edit?.op) {
- case 'set': {
- const at = locate(edit.layer);
- const layer = at.list[at.index]!;
- for (const [key, value] of Object.entries(edit.fields ?? {})) {
- if (value === null) delete layer[key];
- else layer[key] = value;
- }
- break;
- }
- case 'insert': {
- // Beside the layer named, in whichever list that is; or, with `into`, at the end of a group.
- if (edit.into !== undefined) {
- const group = locate(edit.into);
- const row = group.list[group.index]!;
- if (row.source !== 'group') throw new Error(`${JSON.stringify(edit.into)} is not a group`);
- (row.layers as Row[]).push(edit.layer as Row);
- } else if (edit.before !== undefined || edit.after !== undefined) {
- const at = locate((edit.before ?? edit.after)!);
- at.list.splice(at.index + (edit.before !== undefined ? 0 : 1), 0, edit.layer as Row);
- } else (next.layers as Row[]).push(edit.layer as Row);
- break;
- }
- case 'remove': {
- const at = locate(edit.layer);
- at.list.splice(at.index, 1);
- break;
- }
- case 'settings':
- for (const [key, value] of Object.entries(edit.fields ?? {})) {
- if (key === 'layers' || key === 'version') throw new Error(`settings does not take ${key}; use set, insert and remove for layers`);
- if (value === null) delete (next as unknown as Record<string, unknown>)[key];
- else (next as unknown as Record<string, unknown>)[key] = value;
- }
- break;
- default:
- throw new Error(`an edit has op ${JSON.stringify((edit as { op?: unknown })?.op)}; there are set, insert, remove, settings`);
- }
- }
- return validateSoundSource(next);
-}
+// The synthesis is the engine's (sdk/src/sound): a package that ships a sound as its source makes it with the same code the editor bakes it with.
+export * from '../../../sdk/src/sound/soundSource';
diff --git a/pipeline/tests/engine-installs.test.ts b/pipeline/tests/engine-installs.test.ts
index b0d1a1864..04de7ef2a 100644
--- a/pipeline/tests/engine-installs.test.ts
+++ b/pipeline/tests/engine-installs.test.ts
@@ -137,7 +137,7 @@ describe('every subpath the SDK publishes', () => {
}
// The two tables engineInstalls keeps for evidence content does not carry
// as a component — asked through it, so this cannot read a stale copy.
- for (const ext of ['.esgraph', '.esfsm', '.esbt', '.esimage']) {
+ for (const ext of ['.esgraph', '.esfsm', '.esbt', '.esimage', '.essound', '.esmusic']) {
for (const s of engineInstalls({ assetPaths: [`x${ext}`] }).subpaths) installable.add(s);
}
for (const id of ['physics', 'physics3d', 'dragonbones', 'spine:4.2']) {
@@ -259,7 +259,7 @@ describe('every module a project can refuse', () => {
);
// Detection also reads asset extensions, which is how a script graph is
// found; asked through engineInstalls so this cannot read a stale copy.
- for (const ext of ['.esgraph', '.esfsm', '.esbt', '.esimage']) {
+ for (const ext of ['.esgraph', '.esfsm', '.esbt', '.esimage', '.essound', '.esmusic']) {
for (const s of engineInstalls({ assetPaths: [`x${ext}`] }).subpaths) byComponent.add(s);
}
// …and a post-process effect group is found by the effects a volume names.
diff --git a/sdk/etc/sound.api.md b/sdk/etc/sound.api.md
new file mode 100644
index 000000000..2b3a0e961
--- /dev/null
+++ b/sdk/etc/sound.api.md
@@ -0,0 +1,458 @@
+# API surface — esengine/sound
+
+<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
+Symbols: 0 public · 0 beta · 63 experimental · 0 deprecated
+
+## CompiledMusic — interface @experimental
+```
+barSeconds: number
+events: MusicEvent[]
+notes: string[]
+parts: { pattern: string; at: number; bars: number; }[]
+seconds: number
+```
+
+## DYNAMICS — const @experimental
+```
+readonly ["soft", "normal", "loud"]
+```
+
+## MAX_MUSIC_SECONDS — const @experimental
+```
+240
+```
+
+## MAX_SOUND_SECONDS — const @experimental
+```
+30
+```
+
+## MAX_SOUND_VARIANTS — const @experimental
+```
+8
+```
+
+## MUSIC_SOURCE_EXT — const @experimental
+```
+".esmusic"
+```
+
+## MUSIC_SOURCE_VERSION — const @experimental
+```
+1
+```
+
+## MusicEdit — type @experimental
+```
+| { op: 'instrument'; name: string; value: MusicInstrument | null }
+ | { op: 'pattern'; name: string; value: MusicPattern | null }
+ | { op: 'track'; pattern: string; track: string; steps: string | null }
+ | { op: 'settings'; fields: Record<string, unknown> }
+```
+
+## MusicEvent — interface @experimental
+```
+at: number
+hard: number
+instrument: string
+loud: number
+mark: 0 | 1 | -1
+midi: number | null
+outside: boolean
+part: number
+seconds: number
+slur: boolean | undefined
+sounds: number | undefined
+tied: boolean | undefined
+```
+
+## MusicInstrument — interface @experimental
+```
+attack: number | undefined
+follow: boolean | undefined
+gain: number | undefined
+highcut: number | undefined
+layers: readonly SoundLayer[] | undefined
+legato: number | boolean | undefined
+lowcut: number | undefined
+octave: number | undefined
+pan: number | undefined
+pedal: boolean | undefined
+release: number | undefined
+reverb: number | undefined
+samples: readonly MusicSample[] | undefined
+scale: "pentatonic" | "pentatonicMinor" | "gong" | "shang" | "jue" | "zhi" | "yu" | "major" | "minor" | "dorian" | "phrygian" | "lydian" | "mixolydian" | "harmonic" | undefined
+```
+
+## MusicPattern — interface @experimental
+```
+bars: number
+chords: readonly number[] | undefined
+div: number | undefined
+dynamics: Readonly<Record<string, readonly number[]>> | undefined
+tracks: Readonly<Record<string, string>>
+```
+
+## MusicSample — interface @experimental
+```
+cutoff: number | undefined
+dynamic: "normal" | "soft" | "loud" | undefined
+file: string
+gain: number | undefined
+high: string | number | undefined
+loop: boolean | readonly [number, number] | undefined
+low: string | number | undefined
+note: string | number
+tune: number | undefined
+```
+
+## MusicSource — interface @experimental
+```
+beats: number | undefined
+fadeIn: number | undefined
+fadeOut: number | undefined
+gain: number | undefined
+humanize: number | undefined
+instruments: Readonly<Record<string, MusicInstrument>>
+intro: number | undefined
+key: string
+loop: boolean | undefined
+master: { compress?: number; low?: number; high?: number; } | undefined
+patterns: Readonly<Record<string, MusicPattern>>
+rate: number | undefined
+reverb: { size?: number; mix?: number; } | undefined
+rubato: number | undefined
+scale: "pentatonic" | "pentatonicMinor" | "gong" | "shang" | "jue" | "zhi" | "yu" | "major" | "minor" | "dorian" | "phrygian" | "lydian" | "mixolydian" | "harmonic" | undefined
+seed: number | undefined
+song: readonly SongPart[]
+stems: boolean | undefined
+swing: number | undefined
+tempo: number
+version: number | undefined
+```
+
+## NOISE_COLORS — const @experimental
+```
+readonly ["white", "pink", "brown"]
+```
+
+## REVERB_KINDS — const @experimental
+```
+readonly ["room", "open"]
+```
+
+## RenderedMusic — interface @experimental
+```
+barSeconds: number
+channels: Float32Array<ArrayBufferLike>[]
+events: MusicEvent[]
+instruments: Record<string, { notes: number; low?: string; high?: string; levelDb: number; }>
+join: { ends: string[]; begins: string[]; endDb: number; startDb: number; } | null
+loopStart: number
+notes: string[]
+parts: { pattern: string; at: number; bars: number; }[]
+peak: number
+rate: number
+rms: number
+seconds: number
+stems: Record<string, Float32Array<ArrayBufferLike>[]> | null
+tailSeconds: number
+```
+
+## RenderedSound — interface @experimental
+```
+channels: Float32Array<ArrayBufferLike>[]
+layers: { id?: string; source: string; from: number; to: number; peak: number; strikes?: number; }[]
+notes: string[]
+peak: number
+rate: number
+rms: number
+seconds: number
+```
+
+## SCALES — const @experimental
+```
+{ readonly pentatonic: readonly [0, 2, 4, 7, 9]; readonly pentatonicMinor: readonly [0, 3, 5, 7, 10]; readonly gong: readonly [0, 2, 4, 7, 9]; readonly shang: readonly [0, 2, 5, 7, 10]; readonly jue: readonly [0, 3, 5, 8, 10]; readonly zhi: readonly [0, 2, 5, 7, 9]; readonly yu: readonly [0, 3, 5, 7, 10]; readonly major: readonly [0, 2, 4, 5, 7, 9, 11]; readonly minor: readonly [0, 2, 3, 5, 7, 8, 10]; readonly dorian: readonly [0, 2, 3, 5, 7, 9, 10]; readonly phrygian: readonly [0, 1, 3, 5, 7, 8, 10]; readonly lydian: readonly [0, 2, 4, 6, 7, 9, 11]; readonly mixolydian: readonly [0, 2, 4, 5, 7, 9, 10]; readonly harmonic: readonly [0, 2, 3, 5, 7, 8, 11]; }
+```
+
+## SOUND_FILTERS — const @experimental
+```
+readonly ["lowpass", "highpass", "bandpass", "notch", "peak"]
+```
+
+## SOUND_RATES — const @experimental
+```
+readonly [22050, 44100, 48000]
+```
+
+## SOUND_RENDER_REVISION — const @experimental
+```
+"1"
+```
+
+## SOUND_SOURCES — const @experimental
+```
+readonly ["sine", "triangle", "saw", "square", "noise", "modes", "impulse", "sample", "group"]
+```
+
+## SOUND_SOURCE_EXT — const @experimental
+```
+".essound"
+```
+
+## SOUND_SOURCE_VERSION — const @experimental
+```
+1
+```
+
+## SampleData — interface @experimental
+```
+channels: readonly Float32Array<ArrayBufferLike>[]
+rate: number
+```
+
+## ScaleName — type @experimental
+```
+keyof typeof SCALES
+```
+
+## SongPart — type @experimental
+```
+string | { pattern: string; without?: readonly string[]; only?: readonly string[] }
+```
+
+## SoundCurve — type @experimental
+```
+number | readonly (readonly [number, number])[]
+```
+
+## SoundEdit — type @experimental
+```
+| { op: 'set'; layer: string | number; fields: Record<string, unknown> }
+ | { op: 'insert'; layer: SoundLayer; before?: string | number; after?: string | number; into?: string }
+ | { op: 'remove'; layer: string | number }
+ | { op: 'settings'; fields: Partial<Omit<SoundSource, 'layers' | 'version'>> }
+```
+
+## SoundFilter — interface @experimental
+```
+freq: SoundCurve
+gain: number | undefined
+q: number | undefined
+type: "lowpass" | "highpass" | "bandpass" | "notch" | "peak"
+```
+
+## SoundJob — interface @experimental
+```
+files: Record<string, ArrayBuffer>
+path: string
+source: string
+```
+
+## SoundLayer — interface @experimental
+```
+attack: number | undefined
+band: readonly [number, number] | undefined
+color: "white" | "pink" | "brown" | undefined
+decay: number | undefined
+drive: number | undefined
+file: string | undefined
+filters: readonly SoundFilter[] | undefined
+fm: { ratio: number; index: SoundCurve; } | undefined
+freq: SoundCurve | undefined
+from: number | undefined
+gain: SoundCurve | undefined
+id: string | undefined
+layers: readonly SoundLayer[] | undefined
+length: number | undefined
+modes: readonly (readonly [number, number, number])[] | undefined
+mute: boolean | undefined
+pan: number | undefined
+release: number | undefined
+repeat: { count: number; every: number; gain?: number; pitch?: number; jitter?: number; faster?: number; } | undefined
+scatter: { count: number; over: number; early?: number; pitch?: readonly [number, number]; gain?: readonly [number, number]; pan?: number; fade?: number; } | undefined
+seed: number | undefined
+source: "noise" | "square" | "group" | "sine" | "triangle" | "saw" | "modes" | "impulse" | "sample"
+speed: number | undefined
+start: number | undefined
+tail: { decay: number; mix: number; } | undefined
+tremolo: { rate: number; depth: number; } | undefined
+vibrato: { rate: number; depth: number; } | undefined
+wide: number | undefined
+width: number | undefined
+```
+
+## SoundRecording — interface @experimental
+```
+channels: readonly Float32Array<ArrayBufferLike>[]
+rate: number
+```
+
+## SoundSource — interface @experimental
+```
+duration: number
+echo: { time: number; feedback?: number; mix?: number; } | undefined
+gain: number | undefined
+highpass: number | undefined
+layers: readonly SoundLayer[]
+loop: boolean | undefined
+lowpass: number | undefined
+normalize: boolean | undefined
+rate: number | undefined
+reference: string | undefined
+reverb: { size?: number; mix?: number; kind?: (typeof REVERB_KINDS)[number]; } | undefined
+variants: number | undefined
+vary: number | undefined
+version: number | undefined
+```
+
+## SoundSourceKind — type @experimental
+```
+(typeof SOUND_SOURCES)[number]
+```
+
+## Step — type @experimental
+```
+| { kind: 'rest' }
+ | { kind: 'hold' }
+ | { kind: 'hit'; loud: number }
+ | { kind: 'notes'; loud: number; notes: StepNote[] }
+```
+
+## StepNote — interface @experimental
+```
+alter: number
+degree: number
+octave: number
+```
+
+## applyMusicEdits — function @experimental
+```
+(source: MusicSource, edits: readonly MusicEdit[]): MusicSource
+```
+
+## applySoundEdits — function @experimental
+```
+(source: SoundSource, edits: readonly SoundEdit[]): SoundSource
+```
+
+## compileMusic — function @experimental
+```
+(source: MusicSource): CompiledMusic
+```
+
+## convolve — function @experimental
+```
+(a: Float32Array, b: Float32Array, keep: number): Float32Array
+```
+
+## decodeWav — function @experimental
+```
+(bytes: Uint8Array): RenderedSound
+```
+
+## encodeWav — function @experimental
+```
+(sound: { rate: number; channels: readonly Float32Array[]; }): Uint8Array
+```
+
+## fft — function @experimental
+```
+(re: Float64Array, im: Float64Array): void
+```
+
+## installAudioRecipes — function @experimental
+```
+(): void
+```
+
+## makeSound — function @experimental
+```
+(job: SoundJob): ArrayBuffer
+```
+
+## midiOf — function @experimental
+```
+(note: unknown): number | null
+```
+
+## musicSampleFiles — function @experimental
+```
+(source: MusicSource): string[]
+```
+
+## musicSeconds — function @experimental
+```
+(source: MusicSource): number
+```
+
+## noteName — const @experimental
+```
+(midi: number) => string
+```
+
+## parseTrack — function @experimental
+```
+(text: string, bars: number, stepsToBar: number, where: string, degrees?: number): Step[]
+```
+
+## placeResponse — function @experimental
+```
+(rate: number, size: number, kind: "room" | "open", side: number): Float32Array
+```
+
+## renderMusic — function @experimental
+```
+(source: MusicSource, given?: Readonly<Record<string, SampleData>>): RenderedMusic
+```
+
+## renderSound — function @experimental
+```
+(source: SoundSource, variant?: number, at?: { pitch?: number; seed?: number; raw?: boolean; given?: Readonly<Record<string, SoundRecording>>; }): RenderedSound
+```
+
+## renderSoundVariants — function @experimental
+```
+(source: SoundSource, given?: Readonly<Record<string, SoundRecording>>): RenderedSound[]
+```
+
+## samplePitch — function @experimental
+```
+(data: SampleData, near: number): number | null
+```
+
+## sampleZone — function @experimental
+```
+(instrument: MusicInstrument, midi: number | null, mark: number, turn: number): { index: number; matched: boolean; }
+```
+
+## soundFromSamples — function @experimental
+```
+(rate: number, channels: readonly Float32Array[]): RenderedSound
+```
+
+## soundNeeds — function @experimental
+```
+(source: string, path: string): string[]
+```
+
+## soundSampleFiles — function @experimental
+```
+(source: Pick<SoundSource, "layers">): string[]
+```
+
+## tonicOf — const @experimental
+```
+(key: string) => number
+```
+
+## validateMusicSource — function @experimental
+```
+(raw: unknown): MusicSource
+```
+
+## validateSoundSource — function @experimental
+```
+(raw: unknown): SoundSource
+```
+
diff --git a/sdk/package.json b/sdk/package.json
index ea037f901..56f47c8b4 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -29,6 +29,8 @@
"./dist/spline/index.js",
"./dist/image/index.js",
"./dist/shared/image.js",
+ "./dist/sound/index.js",
+ "./dist/shared/sound.js",
"./dist/voxel/index.js",
"./dist/rig2d/index.js",
"./dist/imported-scene/index.js",
@@ -134,6 +136,10 @@
"import": "./dist/image/index.js",
"types": "./dist/image/index.d.ts"
},
+ "./sound": {
+ "import": "./dist/sound/index.js",
+ "types": "./dist/sound/index.d.ts"
+ },
"./voxel": {
"import": "./dist/voxel/index.js",
"types": "./dist/voxel/index.d.ts"
diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.js
index d38ec2917..ea4e3e56b 100644
--- a/sdk/rolldown.config.js
+++ b/sdk/rolldown.config.js
@@ -114,6 +114,7 @@ export default defineConfig([
'water/index': 'src/water/index.ts',
'spline/index': 'src/spline/index.ts',
'image/index': 'src/image/index.ts',
+ 'sound/index': 'src/sound/index.ts',
'voxel/index': 'src/voxel/index.ts',
'rig2d/index': 'src/rig2d/entry.ts',
'imported-scene/index': 'src/imported-scene/index.ts',
diff --git a/sdk/rollup.config.js b/sdk/rollup.config.js
index 1aec791e8..b11fb074f 100644
--- a/sdk/rollup.config.js
+++ b/sdk/rollup.config.js
@@ -36,6 +36,7 @@ export default [
'water/index': 'src/water/index.ts',
'spline/index': 'src/spline/index.ts',
'image/index': 'src/image/index.ts',
+ 'sound/index': 'src/sound/index.ts',
'voxel/index': 'src/voxel/index.ts',
'rig2d/index': 'src/rig2d/entry.ts',
'imported-scene/index': 'src/imported-scene/index.ts',
diff --git a/sdk/scripts/worker-source.mjs b/sdk/scripts/worker-source.mjs
index 45b28a081..365209d26 100644
--- a/sdk/scripts/worker-source.mjs
+++ b/sdk/scripts/worker-source.mjs
@@ -11,6 +11,8 @@ const WORKERS = [
doc: "The planning worker's script: what a pool of planning workers is started from." },
{ entry: 'src/image/recipeWorker.ts', out: 'src/image/recipeWorkerBundle.generated.ts', name: 'RECIPE_WORKER_SOURCE',
doc: "The recipe worker's script: what the workers that draw texture recipes are started from." },
+ { entry: 'src/sound/soundWorker.ts', out: 'src/sound/soundWorkerBundle.generated.ts', name: 'SOUND_WORKER_SOURCE',
+ doc: "The sound worker's script: what the worker that makes audio recipes is started from." },
];
async function build(worker) {
diff --git a/sdk/src/asset/audioRecipe.ts b/sdk/src/asset/audioRecipe.ts
new file mode 100644
index 000000000..9656fa9b8
--- /dev/null
+++ b/sdk/src/asset/audioRecipe.ts
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file audioRecipe.ts
+ * @brief A clip that is a recipe: a sound's or a piece of music's source (`.essound`, `.esmusic`) shipped in place of its samples and
+ * made where it is loaded.
+ *
+ * @details A package that ships a minute of music ships a megabyte of it, compressed; one that ships how the music is played ships a
+ * few kilobytes and pays for the playing once, on the device. Whoever loads a clip asks here for any path that is a recipe,
+ * and is handed the bytes of a `.wav`, which every audio backend already reads. What makes one is not in the core:
+ * importing `esengine/sound` installs it, so a game with no recipe does not carry the synthesis.
+ *
+ * A recipe may play recordings of the project (a sampled instrument, a sample layer). The maker says which, they are read
+ * here, and what was made is kept in the platform's content cache under all it was made from: the source, those files'
+ * own bytes, and the maker's revision. A change in any of them is another key. See textureRecipe.ts, which this follows.
+ */
+import { contentHashHex } from './contentHash';
+import { platformReadCacheFile, platformWriteCacheFile } from '../platform';
+import { decodeUtf8, encodeUtf8 } from '../util/utf8';
+
+/** Reads a file of the project by its project path, as the asset layer would. */
+export type AudioRecipeFileReader = (path: string) => Promise<ArrayBuffer>;
+
+/** What makes recipes. */
+export interface AudioRecipeMaker {
+ /** How it sounds, as a name: it changes whenever the same source would come out as other samples. */
+ revision: string;
+ /** The recordings a source plays, by project path. */
+ needs(source: string, path: string): readonly string[];
+ /** The clip of a source as the bytes of a `.wav`, with every recording it plays to hand. */
+ make(source: string, files: ReadonlyMap<string, ArrayBuffer>, path: string): ArrayBuffer | Promise<ArrayBuffer>;
+}
+
+/** What recipes have cost since the game began (or since the counts were last cleared). */
+export interface AudioRecipeStats {
+ /** Recipes made, and how long the making took in all, in milliseconds of the clock on the wall. */
+ made: number;
+ makeMs: number;
+ /** Recipes read back from the content cache, made by an earlier run. */
+ reused: number;
+}
+
+const RECIPE_EXTENSIONS = ['.essound', '.esmusic'] as const;
+let maker: AudioRecipeMaker | null = null;
+const stats: AudioRecipeStats = { made: 0, makeMs: 0, reused: 0 };
+
+/** Whether a clip's path names a recipe and not a recording. */
+export function isAudioRecipePath(path: string): boolean {
+ const end = path.indexOf('?');
+ const bare = (end < 0 ? path : path.slice(0, end)).toLowerCase();
+ return RECIPE_EXTENSIONS.some((ext) => bare.endsWith(ext));
+}
+
+/** Installs what makes recipes (null takes it out again). `esengine/sound` does this on import. */
+export function setAudioRecipeMaker(next: AudioRecipeMaker | null): void {
+ maker = next;
+}
+
+export function hasAudioRecipeMaker(): boolean {
+ return maker !== null;
+}
+
+/** The counts so far; `clear` starts them again. */
+export function audioRecipeStats(clear = false): AudioRecipeStats {
+ const now = { ...stats };
+ if (clear) { stats.made = 0; stats.makeMs = 0; stats.reused = 0; }
+ return now;
+}
+
+/** The content cache's key for a recipe: the maker's revision, and the hash of the source with the files it was made from. */
+export function audioRecipeCacheKey(source: string, files: ReadonlyMap<string, ArrayBuffer> = new Map(), revision = maker?.revision ?? ''): string {
+ const from = [...files.keys()].sort().map((path) => `\n${path}:${contentHashHex(new Uint8Array(files.get(path)!))}`).join('');
+ return `estella:audio-recipe:${revision}:${contentHashHex(encodeUtf8(source + from))}`;
+}
+
+/** A kept clip is read back only if it is a `.wav` at all: anything else is made again and written over. */
+function isWav(bytes: ArrayBuffer): boolean {
+ if (bytes.byteLength < 44) return false;
+ const b = new Uint8Array(bytes, 0, 12);
+ return b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x41 && b[10] === 0x56 && b[11] === 0x45;
+}
+
+/** The `.wav` of the recipe at `path`: read back where an earlier run made it, made and kept otherwise. */
+export async function renderAudioRecipe(path: string, read: AudioRecipeFileReader): Promise<ArrayBuffer> {
+ const by = maker;
+ if (!by) throw new Error(`clip "${path}" is a recipe, and nothing here makes recipes: import 'esengine/sound' where the game starts`);
+ const source = decodeUtf8(new Uint8Array(await read(path)));
+ const files = new Map<string, ArrayBuffer>();
+ for (const need of by.needs(source, path)) if (!files.has(need)) files.set(need, await read(need));
+ const key = audioRecipeCacheKey(source, files, by.revision);
+ const kept = await platformReadCacheFile(key);
+ if (kept && isWav(kept)) { stats.reused++; return kept; }
+ const began = Date.now();
+ const made = await by.make(source, files, path);
+ stats.made++;
+ stats.makeMs += Date.now() - began;
+ // Kept for the next run without holding this one up; a platform with no cache, or a full one, only means it is made again.
+ // A copy, since the caller hands the bytes to a decoder that may take them.
+ void platformWriteCacheFile(key, made.slice(0));
+ return made;
+}
diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.ts
index 3e5072611..53c02dd6c 100644
--- a/sdk/src/assetTypes.ts
+++ b/sdk/src/assetTypes.ts
@@ -39,6 +39,8 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [
{ extensions: ['ktx2'], contentType: 'binary', editorType: 'texture', addressableType: 'texture', wechatPackInclude: true, hasTransitiveDeps: false },
// A picture's source, drawn into a texture where it is loaded (asset/textureRecipe.ts).
{ extensions: ['esimage'], contentType: 'json', editorType: 'texture', addressableType: 'texture', wechatPackInclude: true, hasTransitiveDeps: false },
+ // A sound's or a piece of music's source, named where a clip goes: a clip to whatever loads it (see asset/audioRecipe.ts).
+ { extensions: ['essound', 'esmusic'], contentType: 'json', editorType: 'audio', addressableType: 'audio', wechatPackInclude: true, hasTransitiveDeps: false },
{ extensions: ['mp3', 'wav', 'ogg', 'aac', 'flac', 'm4a', 'webm'], contentType: 'audio', editorType: 'audio', addressableType: 'audio', wechatPackInclude: false, hasTransitiveDeps: false },
// Video container, streamed + decoded by the video system (HTMLVideoElement
// on web). `webm` stays with audio above to avoid the ambiguity; a .webm
diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.ts
index 3c2f29dfc..f204064c9 100644
--- a/sdk/src/audio/Audio.ts
+++ b/sdk/src/audio/Audio.ts
@@ -7,6 +7,8 @@ import { defineResource } from '../ecs/resource';
import { RuntimeConfig } from '../defaults';
import { log } from '../util/logger';
import { disposeAll } from '../util/disposeAll';
+import { isAudioRecipePath, renderAudioRecipe } from '../asset/audioRecipe';
+import { getPlatform } from '../platform/base';
/** `./a//b.mp3` and `a/b.mp3` are one clip. */
function normalizeClipPath(path: string): string {
@@ -173,6 +175,13 @@ interface LayerGroup {
inStep: boolean;
}
+/**
+ * How a clip made from a recipe is loaded: decoded whole. What was made is a plain .wav under a path that names no recording, so the
+ * length rule that plays a long file from a media element would hand it bytes with no type to go by; and a loop that is decoded
+ * comes round on the sample, which a piece of music made to loop is for.
+ */
+const RECIPE_LOAD: AudioLoadOptions = { loadType: 'decompress' };
+
export class AudioAPI {
private readonly voiceStates_ = new WeakMap<AudioHandle, SoftVoice>();
private readonly playbackStops_ = new Set<(generation: number) => void>();
@@ -528,8 +537,26 @@ export class AudioAPI {
await promise;
}
+ /**
+ * The `.wav` of a clip that is a recipe (an `.essound`, an `.esmusic`): its source read as any clip is, by the resolver that
+ * holds a package's inlined files or from where the path resolves to, and made by `esengine/sound` (see asset/audioRecipe.ts).
+ */
+ private recipeClip_(url: string, resolved: string, given?: ArrayBuffer): Promise<ArrayBuffer> {
+ return renderAudioRecipe(url, async (path) => {
+ if (path === url && given) return given;
+ const held = this.assetResolver_?.(path);
+ if (held) return held;
+ return getPlatform().readFile(path === url ? resolved : this.resolveUrl_(path));
+ });
+ }
+
async preload(url: string): Promise<void> {
if (this.disposed_ || this.bufferCache_.has(url)) return;
+ if (isAudioRecipePath(url)) {
+ // Made, then handed to the backend as the bytes of a file, which every backend that decodes already reads.
+ await this.ensureBuffer_(url, async source => this.backend_.loadBufferFromData(source, await this.recipeClip_(url, source), RECIPE_LOAD));
+ return;
+ }
if (this.assetResolver_) {
const data = this.assetResolver_(url);
if (data) {
@@ -574,6 +601,11 @@ export class AudioAPI {
* for a `url`-delivery backend is the only thing it plays.
*/
async preloadFromData(url: string, data: ArrayBuffer): Promise<void> {
+ if (isAudioRecipePath(url)) {
+ // The bytes of a recipe are its source, not a recording: handed to a decoder they are refused, and the clip was silent.
+ await this.ensureBuffer_(url, async source => this.backend_.loadBufferFromData(source, await this.recipeClip_(url, source, data), RECIPE_LOAD));
+ return;
+ }
const options = this.loadOptions_(url);
await this.ensureBuffer_(url, source => (options
? this.backend_.loadBufferFromData(source, data, options) : this.backend_.loadBufferFromData(source, data)));
diff --git a/sdk/src/platform/nativeModuleRegistry.ts b/sdk/src/platform/nativeModuleRegistry.ts
index c8ea47b35..879052802 100644
--- a/sdk/src/platform/nativeModuleRegistry.ts
+++ b/sdk/src/platform/nativeModuleRegistry.ts
@@ -34,6 +34,7 @@ import * as FoliageModule from '../foliage';
import * as WorldGenModule from '../worldgen';
import * as WaterModule from '../water';
import * as ImageModule from '../image';
+import * as SoundModule from '../sound';
import * as SplineModule from '../spline';
import * as VoxelModule from '../voxel';
import * as Rig2DModule from '../rig2d';
@@ -70,6 +71,7 @@ export const NATIVE_MODULE_NAMESPACES: Readonly<Record<string, unknown>> = {
'esengine/worldgen': WorldGenModule,
'esengine/water': WaterModule,
'esengine/image': ImageModule,
+ 'esengine/sound': SoundModule,
'esengine/spline': SplineModule,
'esengine/voxel': VoxelModule,
'esengine/rig2d': Rig2DModule,
diff --git a/sdk/src/sound/fft.ts b/sdk/src/sound/fft.ts
new file mode 100644
index 000000000..02492f2ac
--- /dev/null
+++ b/sdk/src/sound/fft.ts
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fft.ts — the fast Fourier transform a sound's rooms and its picture are worked out with.
+ */
+/** In place: the transform of @p re + i @p im, their length a power of two. */
+export function fft(re: Float64Array, im: Float64Array): void {
+ const n = re.length;
+ for (let i = 1, j = 0; i < n; i++) {
+ let bit = n >> 1;
+ for (; j & bit; bit >>= 1) j ^= bit;
+ j ^= bit;
+ if (i < j) { const r = re[i]!; re[i] = re[j]!; re[j] = r; const m = im[i]!; im[i] = im[j]!; im[j] = m; }
+ }
+ for (let size = 2; size <= n; size <<= 1) {
+ const angle = (-2 * Math.PI) / size;
+ const wr = Math.cos(angle), wi = Math.sin(angle), half = size >> 1;
+ // Plain locals throughout: this loop is all the time a long convolution takes.
+ for (let start = 0; start < n; start += size) {
+ let cr = 1, ci = 0;
+ for (let k = 0; k < half; k++) {
+ const a = start + k, b = a + half;
+ const tr = re[b]! * cr - im[b]! * ci, ti = re[b]! * ci + im[b]! * cr;
+ re[b] = re[a]! - tr; im[b] = im[a]! - ti;
+ re[a] = re[a]! + tr; im[a] = im[a]! + ti;
+ const next = cr * wr - ci * wi;
+ ci = cr * wi + ci * wr; cr = next;
+ }
+ }
+ }
+}
diff --git a/sdk/src/sound/index.ts b/sdk/src/sound/index.ts
new file mode 100644
index 000000000..8954c0b2d
--- /dev/null
+++ b/sdk/src/sound/index.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief `esengine/sound`: sounds and music made from their sources, in the editor that bakes them and on the device that plays them.
+ *
+ * @details Importing this module installs the maker of audio recipes (see asset/audioRecipe.ts): a clip named by its `.essound` or
+ * `.esmusic` is then made where it is loaded, and the package carries the source in place of the samples.
+ */
+import { makeSound, soundNeeds, type SoundJob } from './soundWorker';
+import { SOUND_WORKER_SOURCE } from './soundWorkerBundle.generated';
+import { setAudioRecipeMaker, type AudioRecipeMaker } from '../asset/audioRecipe';
+import { createJobPool, type JobPool } from '../runtime/jobs';
+
+export * from './soundSource';
+export * from './soundRender';
+export * from './musicSource';
+export * from './musicRender';
+export { fft } from './fft';
+export { makeSound, soundNeeds, type SoundJob } from './soundWorker';
+
+/**
+ * How the synthesis sounds, as a name. Bump it whenever the same source would come out as other samples: a clip made by an earlier
+ * run is kept under it, and an old one would otherwise be played for the new.
+ */
+export const SOUND_RENDER_REVISION = '1';
+
+let pool: JobPool | null | undefined;
+/** A piece of music is seconds of work and a sound a fraction of one: each has a worker, so a step is never made behind a theme. */
+const MUSIC_WORKER = 0, SOUND_WORKER = 1;
+
+// Made on a worker where the host has workers, so a game goes on drawing frames while its music is played out; in place where it has
+// none or once they have failed (a recipe is still a clip then, a slower one to load).
+const MAKER: AudioRecipeMaker = {
+ revision: SOUND_RENDER_REVISION,
+ needs: soundNeeds,
+ async make(source, files, path): Promise<ArrayBuffer> {
+ const job: SoundJob = { source, path, files: {} };
+ for (const [file, bytes] of files) job.files[file] = bytes;
+ if (pool === undefined) pool = createJobPool(SOUND_WORKER_SOURCE, 2);
+ if (pool) {
+ try {
+ return await pool.run<ArrayBuffer>(/\.esmusic(\?|$)/i.test(path) ? MUSIC_WORKER : SOUND_WORKER, { ...job });
+ } catch (err) {
+ const why = err instanceof Error ? err.message : String(err);
+ // What the source itself is refused for is the answer; only a worker that cannot do the job sends it back here.
+ if (/^(a job worker failed|the job workers have stopped|the job pool was disposed)/.test(why)) pool = null;
+ else throw err;
+ }
+ }
+ return makeSound(job);
+ },
+};
+
+/** Installs the maker of audio recipes: what importing this module does, and a way back for whoever took it out. */
+export function installAudioRecipes(): void {
+ setAudioRecipeMaker(MAKER);
+}
+
+installAudioRecipes();
diff --git a/sdk/src/sound/musicRender.ts b/sdk/src/sound/musicRender.ts
new file mode 100644
index 000000000..c21e743a3
--- /dev/null
+++ b/sdk/src/sound/musicRender.ts
@@ -0,0 +1,659 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file musicRender.ts — a music source worked out into the notes it plays, and the notes into samples.
+ *
+ * Two steps, and the first is worth having on its own: `compileMusic` turns patterns of steps into notes with a
+ * time, a length and a pitch, which is what a picture of the piece is drawn from and what can be checked without
+ * hearing anything. `renderMusic` then strikes each instrument's layers once for every note (soundRender.ts) and
+ * sums them, each instrument on its own bus so the buses can be written out apart.
+ *
+ * A piece that loops is not faded into itself: what rings past its end is added to its start, which is what
+ * would be heard had it been playing round already.
+ */
+import { fft } from './fft';
+import { placeResponse, renderSound } from './soundRender';
+import type { SoundLayer } from './soundSource';
+import { midiOf, musicSeconds, parseTrack, SCALES, tonicOf, type MusicInstrument, type MusicSource } from './musicSource';
+
+/** A recording as samples: what an instrument made of recordings plays from. */
+export interface SampleData { rate: number; channels: readonly Float32Array[] }
+
+export interface MusicEvent {
+ instrument: string;
+ /** Seconds from the start of the piece, and how long it is held. */
+ at: number;
+ seconds: number;
+ /** The note, 60 being middle C; null for an instrument struck at its own pitch. */
+ midi: number | null;
+ loud: number;
+ /** Which part of the song it is in. */
+ part: number;
+ /** Written with # or b: outside the key. */
+ outside: boolean;
+ /** Softer (-1) or louder (1) than the rest by its mark and by where it lies in the dynamics; 0 for neither. */
+ mark: -1 | 0 | 1;
+ /** How loud it is written, by its mark and the dynamics, before the hand's unevenness. */
+ hard: number;
+ /** How long it sounds, where that is longer than it is written: held on by the pedal to the end of its bar. */
+ sounds?: number;
+ /** It comes in under the note before it and is not struck afresh. */
+ slur?: boolean;
+ /** The note after it comes in under it, and it stays a moment longer for that. */
+ tied?: boolean;
+}
+
+export interface CompiledMusic {
+ seconds: number;
+ barSeconds: number;
+ events: MusicEvent[];
+ parts: { pattern: string; at: number; bars: number }[];
+ notes: string[];
+}
+
+export interface RenderedMusic extends CompiledMusic {
+ rate: number;
+ /** Left, right. */
+ channels: Float32Array[];
+ peak: number;
+ rms: number;
+ /** For a loop with an introduction: seconds into the file that it comes back to. 0 where the whole of it goes round. */
+ loopStart: number;
+ /** For a piece that ends: seconds it rings on after its last bar, which the file is longer by. */
+ tailSeconds: number;
+ /** For a loop: what sounds in its last bar and in its first, and how loud each is, in decibels beside the whole. Null for a piece that ends. */
+ join: { ends: string[]; begins: string[]; endDb: number; startDb: number } | null;
+ /** Each instrument alone, when the source asks for stems: they add up to `channels`. */
+ stems: Record<string, Float32Array[]> | null;
+ /** What each instrument played, and how loud it is beside the whole, in decibels. */
+ instruments: Record<string, { notes: number; low?: string; high?: string; levelDb: number }>;
+}
+
+const NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
+export const noteName = (midi: number): string => `${NOTE_NAMES[((midi % 12) + 12) % 12]}${Math.floor(midi / 12) - 1}`;
+
+function randomOf(seed: number): () => number {
+ let s = (seed * 2654435761 + 0x9e3779b9) >>> 0;
+ return () => {
+ s = (s + 0x6d2b79f5) >>> 0;
+ let t = s;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 2147483648 - 1;
+ };
+}
+
+/** The notes a validated source plays, in the order they begin. */
+export function compileMusic(source: MusicSource): CompiledMusic {
+ const beats = source.beats ?? 4;
+ const barSeconds = (beats * 60) / source.tempo;
+ const scale = SCALES[source.scale ?? 'minor'];
+ const tonic = tonicOf(source.key);
+ const human = source.humanize ?? 0.15;
+ const random = randomOf(source.seed ?? 1);
+ const events: MusicEvent[] = [];
+ const parts: CompiledMusic['parts'] = [];
+ const notes: string[] = [];
+ const said = new Set<string>();
+ const say = (text: string): void => { if (!said.has(text)) { said.add(text); notes.push(text); } };
+ const played = new Set<string>();
+ const used = new Set<string>();
+ let at = 0;
+
+ source.song.forEach((part, p) => {
+ const name = typeof part === 'string' ? part : part.pattern;
+ const pattern = source.patterns[name]!;
+ used.add(name);
+ parts.push({ pattern: name, at, bars: pattern.bars });
+ const div = pattern.div ?? 4;
+ const stepsToBar = beats * div;
+ const step = barSeconds / stepsToBar;
+ const before = events.length;
+ for (const [track, line] of Object.entries(pattern.tracks)) {
+ if (typeof part !== 'string' && (part.without?.includes(track) || (part.only && !part.only.includes(track)))) continue;
+ const instrument = source.instruments[track]!;
+ if (instrument.follow && !pattern.chords) say(`"${track}" follows the chords, and pattern "${name}" has none: it plays every bar on chord 1`);
+ const steps = parseTrack(line, pattern.bars, stepsToBar, `pattern "${name}", track "${track}"`, SCALES[instrument.scale ?? source.scale ?? 'minor'].length);
+ // Time that gives: late at the start of the phrase, made up through its middle, late again toward its end,
+ // and back where it was on the last bar line, so the pattern is as long as it was written.
+ const phrase = pattern.bars * barSeconds;
+ const give = ((source.rubato ?? 0) * 0.08 * phrase) / (2 * Math.PI);
+ const timed = (t: number): number => t + give * Math.sin((2 * Math.PI * t) / phrase);
+ // How loud the line is at each step: between the number its bar begins on and the next bar's.
+ const levels = pattern.dynamics?.[track] ?? pattern.dynamics?.all;
+ const levelAt = (i: number): number => {
+ if (!levels) return 1;
+ const bar = i / stepsToBar;
+ const [a, b] = [levels[Math.min(Math.floor(bar), levels.length - 1)]!, levels[Math.min(Math.floor(bar) + 1, levels.length - 1)]!];
+ return a + (b - a) * (bar - Math.floor(bar));
+ };
+ // The last single note of this line, and the step it ends on: what a note that follows straight on is slurred from.
+ let before: { end: number; event: MusicEvent } | null = null;
+ for (let i = 0; i < steps.length; i++) {
+ const s = steps[i]!;
+ if (s.kind === 'hold' && (i === 0 || steps[i - 1]!.kind === 'rest')) say(`pattern "${name}", track "${track}": a "-" at step ${(i % stepsToBar) + 1} of bar ${Math.floor(i / stepsToBar) + 1} has no note before it to hold, and is silent`);
+ if (s.kind !== 'hit' && s.kind !== 'notes') continue;
+ let held = 1;
+ while (i + held < steps.length && steps[i + held]!.kind === 'hold') held++;
+ // Every second step late, which is what makes a line swing.
+ const late = div % 2 === 0 && i % 2 === 1 ? (source.swing ?? 0) * step : 0;
+ const when = Math.max(0, at + timed(i * step + late) + human * 0.012 * random());
+ const written = timed((i + held) * step) - timed(i * step);
+ const hard = s.loud * levelAt(i);
+ const loud = hard * (1 + human * 0.25 * random());
+ const mark = hard > 1.15 ? 1 : hard < 0.8 ? -1 : 0;
+ // The pedal is down to the end of the bar: the note rings on to there.
+ const toBarEnd = timed((Math.floor(i / stepsToBar) + 1) * stepsToBar * step) - timed(i * step);
+ const sounds = instrument.pedal && toBarEnd > written + 1e-9 ? { sounds: toBarEnd } : {};
+ played.add(track);
+ if (s.kind === 'hit') {
+ events.push({ instrument: track, at: when, seconds: written, midi: null, loud, part: p, outside: false, mark, hard, ...sounds });
+ before = null;
+ continue;
+ }
+ // One note running straight on from one note, and not struck harder: in the same breath.
+ const slurred = !!instrument.legato && s.notes.length === 1 && before !== null && before.end === i && s.loud <= 1;
+ if (slurred) before!.event.tied = true;
+ const chord = instrument.follow && pattern.chords ? pattern.chords[Math.floor(i / stepsToBar) % pattern.chords.length]! : 1;
+ // A root in the upper part of the scale (5, 6 or 7 of seven; 4 or 5 of five) is taken below the tonic, so the
+ // chords lie round it and a bass does not climb away.
+ // The instrument's own scale where it has one: the same tonic, other notes.
+ const own = instrument.scale ? SCALES[instrument.scale] : scale;
+ const size = own.length;
+ const drop = chord > size / 2 + 1 ? -size : 0;
+ for (const n of s.notes) {
+ const index = n.degree - 1 + chord - 1 + drop + size;
+ const midi = 60 + tonic + own[index % size]! + 12 * (Math.floor(index / size) - 1 + n.octave + (instrument.octave ?? 0)) + n.alter;
+ events.push({ instrument: track, at: when, seconds: written, midi, loud, part: p, outside: n.alter !== 0, mark, hard, ...sounds, ...(slurred ? { slur: true } : {}) });
+ }
+ before = s.notes.length === 1 ? { end: i + held, event: events[events.length - 1]! } : null;
+ }
+ }
+ if (events.length === before) notes.push(`part ${p + 1} of the song ("${name}") plays nothing`);
+ at += pattern.bars * barSeconds;
+ });
+
+ for (const name of Object.keys(source.instruments)) if (!played.has(name)) notes.push(`instrument "${name}" is never played`);
+ for (const name of Object.keys(source.patterns)) if (!used.has(name)) notes.push(`pattern "${name}" is not in the song`);
+
+ // What can be said of the notes without hearing them.
+ const pitched = new Map<string, MusicEvent[]>();
+ for (const e of events) if (e.midi !== null) pitched.set(e.instrument, [...(pitched.get(e.instrument) ?? []), e]);
+ const middle = new Map<string, number>();
+ for (const [name, list] of pitched) {
+ const sorted = list.map((e) => e.midi!).sort((a, b) => a - b);
+ middle.set(name, sorted[Math.floor(sorted.length / 2)]!);
+ if (sorted[0]! < 24) notes.push(`"${name}" goes down to ${noteName(sorted[0]!)}, below where a pitch can be told: raise its octave`);
+ if (sorted[sorted.length - 1]! > 100) notes.push(`"${name}" goes up to ${noteName(sorted[sorted.length - 1]!)}, which is a whistle: lower its octave`);
+ const outside = list.filter((e) => e.outside).length;
+ if (outside > 0) notes.push(`"${name}" plays ${outside} note${outside === 1 ? '' : 's'} outside the key`);
+ }
+ const names = [...pitched.keys()];
+ for (let a = 0; a < names.length; a++) for (let b = a + 1; b < names.length; b++) {
+ const [x, y] = [pitched.get(names[a]!)!, pitched.get(names[b]!)!];
+ if (Math.abs(middle.get(names[a]!)! - middle.get(names[b]!)!) > 4) continue;
+ // How much of the time the less busy of the two sounds, the other is sounding too.
+ const length = (list: MusicEvent[]): number => list.reduce((sum, e) => sum + e.seconds, 0);
+ let both = 0;
+ for (const e of x) for (const f of y) both += Math.max(0, Math.min(e.at + e.seconds, f.at + f.seconds) - Math.max(e.at, f.at));
+ if (both > 0.5 * Math.min(length(x), length(y))) notes.push(`"${names[a]}" and "${names[b]}" sound together in the same octave, round ${noteName(middle.get(names[a]!)!)}, and will blur into one: move one of them an octave`);
+ }
+
+ events.sort((a, b) => a.at - b.at);
+ return { seconds: musicSeconds(source), barSeconds, events, parts, notes };
+}
+
+/** How far past its own start a layer can still be sounding, when a held note lasts @p held seconds. */
+function reach(layer: SoundLayer, held: number): number {
+ const again = layer.scatter ? layer.scatter.over : layer.repeat ? (layer.repeat.count - 1) * layer.repeat.every : 0;
+ const own = layer.source === 'group' ? Math.max(0, ...layer.layers!.map((l) => reach(l, held))) : layer.length ?? held;
+ return (layer.start ?? 0) + again + own;
+}
+
+/** A layer with no length of its own lasts as long as the note, and dies over the instrument's release. */
+function forNote(layer: SoundLayer, held: number, release: number, slur = 0): SoundLayer {
+ if (layer.source === 'group') return { ...layer, layers: layer.layers!.map((l) => forNote(l, held, release, slur)) };
+ // A layer with a length of its own is the knock at the front of a note, which a slurred note has none of.
+ if (layer.length !== undefined) return slur > 0 ? { ...layer, mute: true } : layer;
+ return { ...layer, length: Math.max(0.01, held + release - (layer.start ?? 0)), release: layer.release ?? release, ...(slur > 0 ? { attack: Math.max(layer.attack ?? 0, slur) } : {}) };
+}
+
+/**
+ * One note of an instrument made of recordings: the recording nearest the note, played faster to be higher or slower
+ * to be lower, let go over the release. A recording an octave from its note is another instrument, which is why there
+ * are several; within three semitones the ear takes it for the same one.
+ */
+const HARDNESS = { soft: -1, normal: 0, loud: 1 } as const;
+
+/**
+ * Which of an instrument's recordings plays a note. First by how hard: the recordings made as hard as the note is
+ * marked, or failing those the nearest in hardness. Then by pitch: the ones whose range holds the note, or failing
+ * those the nearest. And where several are left that are the same note, they take turns, so the same key struck
+ * four times is not one recording four times.
+ */
+export function sampleZone(instrument: MusicInstrument, midi: number | null, mark: number, turn: number): { index: number; matched: boolean } {
+ const zones = instrument.samples!;
+ const hard = (i: number): number => HARDNESS[zones[i]!.dynamic ?? 'normal'];
+ let left = zones.map((_, i) => i);
+ const nearest = Math.min(...left.map((i) => Math.abs(hard(i) - mark)));
+ left = left.filter((i) => Math.abs(hard(i) - mark) === nearest);
+ const matched = nearest === 0 && mark !== 0;
+ if (midi !== null) {
+ const ranged = left.filter((i) => (zones[i]!.low !== undefined || zones[i]!.high !== undefined) && midi >= (midiOf(zones[i]!.low) ?? 0) && midi <= (midiOf(zones[i]!.high) ?? 127));
+ if (ranged.length) left = ranged;
+ const far = Math.min(...left.map((i) => Math.abs(midiOf(zones[i]!.note)! - midi)));
+ left = left.filter((i) => Math.abs(midiOf(zones[i]!.note)! - midi) === far);
+ // Of two as near, one above and one below, the turn must not swap them: only recordings of one note take turns.
+ left = left.filter((i) => midiOf(zones[i]!.note) === midiOf(zones[left[0]!]!.note));
+ } else left = [left[0]!];
+ return { index: left[turn % left.length]!, matched };
+}
+
+function sampleNote(name: string, instrument: MusicInstrument, index: number, midi: number | null, held: number, rate: number, given: Readonly<Record<string, SampleData>>, slur = 0): Float32Array[] {
+ const zone = instrument.samples![index]!;
+ const data = given[zone.file];
+ if (!data) throw new Error(`instrument "${name}": the recording ${zone.file} was not found`);
+ const frames = data.channels[0]!.length;
+ const step = (midi === null ? 1 : Math.pow(2, (midi - midiOf(zone.note)! - (zone.tune ?? 0) / 100) / 12)) * (data.rate / rate);
+ // Slurred, it is not the start of the recording that is wanted, which is the bow biting or the breath beginning,
+ // but what comes after; and it comes in over the time the note before takes to go.
+ const skip = slur > 0 ? Math.min(0.12 * data.rate, frames * 0.25) : 0;
+ const [attack, release] = [slur > 0 ? slur : instrument.attack ?? 0.003, instrument.release ?? 0.08];
+ // Round its steady middle, or the seconds given, with the end of each turn faded into the start of the next.
+ let [from, to] = [0, 0];
+ if (zone.loop) {
+ [from, to] = zone.loop === true ? [frames * 0.4, frames * 0.85] : [zone.loop[0] * data.rate, Math.min(frames - 2, zone.loop[1] * data.rate)];
+ }
+ const round = to - from;
+ const fade = round > 0 ? Math.min(0.12 * data.rate, round / 3, from) : 0;
+ const count = Math.max(1, Math.round(Math.min(held + release, round > 0 ? 30 : (frames - 2 - skip) / step / rate) * rate));
+ const at = (channel: Float32Array, p: number): number => {
+ // Through four points, so a note played slower is not a staircase.
+ const i = Math.floor(p), t = p - i;
+ const [a, b, c, d] = [channel[i - 1] ?? channel[i]!, channel[i]!, channel[i + 1] ?? 0, channel[i + 2] ?? 0];
+ return b + 0.5 * t * (c - a + t * (2 * a - 5 * b + 4 * c - d + t * (3 * (b - c) + d - a)));
+ };
+ const out = data.channels.slice(0, 2).map(() => new Float32Array(count));
+ const letGo = Math.round(held * rate);
+ const ending = Math.min(count, Math.round(0.005 * rate));
+ for (let n = 0; n < count; n++) {
+ let p = skip + n * step;
+ let blend = 0;
+ if (round > 0 && p >= to - fade) {
+ p = from + ((p - from) % round);
+ if (fade > 0 && p >= to - fade) blend = (p - (to - fade)) / fade;
+ }
+ let level = n < attack * rate ? n / (attack * rate) : 1;
+ if (n > letGo) level *= Math.max(0, 1 - (n - letGo) / Math.max(1, release * rate));
+ if (count - n < ending) level *= (count - n) / ending;
+ for (let c = 0; c < out.length; c++) {
+ const channel = data.channels[c]!;
+ out[c]![n] = (blend > 0 ? at(channel, p) * (1 - blend) + at(channel, p - round) * blend : at(channel, p)) * level * (zone.gain ?? 1);
+ }
+ }
+ // Duller than it was recorded, where the sample says so: at a fixed place, whatever the note.
+ if (zone.cutoff && zone.cutoff < rate * 0.45) for (const channel of out) filtered(channel, 'lowpass', zone.cutoff, rate);
+ return out;
+}
+
+/**
+ * The pitch heard in a recording, in Hz, looked for within two octaves of @p near; null where it has none that can be
+ * told (a drum, a noise). It is found by how far the wave has to be slid to lie on itself again. A wave lies on itself
+ * at twice its period too, so the shortest slide that fits nearly as well as the best is taken: that is what tells a
+ * recording named an octave from what it is, which libraries that count octaves from another C are throughout.
+ */
+export function samplePitch(data: SampleData, near: number): number | null {
+ const samples = data.channels[0]!;
+ const longest = Math.ceil(data.rate / (near / 2.1));
+ const start = Math.floor(samples.length * 0.25);
+ const size = Math.min(16384, samples.length - start - longest);
+ if (size < longest * 2) return null;
+ const scores: [number, number][] = [];
+ for (let lag = Math.max(8, Math.floor(data.rate / (near * 4.2))); lag <= longest; lag++) {
+ let sum = 0, a = 0, b = 0;
+ for (let n = 0; n < size; n += 2) { const x = samples[start + n]!, y = samples[start + n + lag]!; sum += x * y; a += x * x; b += y * y; }
+ scores.push([lag, sum / Math.sqrt(a * b + 1e-12)]);
+ }
+ const top = Math.max(...scores.map((score) => score[1]));
+ if (!(top > 0.6)) return null;
+ let at = scores.findIndex((score) => score[1] >= top * 0.92);
+ while (at + 1 < scores.length && scores[at + 1]![1] > scores[at]![1]) at++;
+ // A high note in a recording made at a low rate has a period of a dozen samples and a half: no whole slide fits
+ // it, and twice the period, which is whole, fits better. So a half and a third of the slide found are tried too,
+ // between the samples, and the shortest that fits nearly as well is the pitch.
+ const fits = (lag: number): number => {
+ let sum = 0, a = 0, b = 0;
+ const whole = Math.floor(lag), part = lag - whole;
+ for (let n = 0; n < size; n += 2) {
+ const x = samples[start + n]!, y = samples[start + n + whole]! * (1 - part) + samples[start + n + whole + 1]! * part;
+ sum += x * y; a += x * x; b += y * y;
+ }
+ return sum / Math.sqrt(a * b + 1e-12);
+ };
+ let lag = scores[at]![0];
+ // Just off the whole number, a little either side, where the fit is best.
+ const best = (centre: number): [number, number] => { let found: [number, number] = [centre, -1]; for (let d = -0.5; d <= 0.5; d += 0.05) { const f = fits(centre + d); if (f > found[1]) found = [centre + d, f]; } return found;
+ };
+ let [fine, fit] = best(lag);
+ for (const part of [3, 2]) {
+ if (lag / part < 4 || data.rate / (lag / part) > near * 4.2) continue;
+ const [shorter, shorterFit] = best(lag / part);
+ if (shorterFit >= fit * 0.9) { [fine, fit] = [shorter, shorterFit]; break; }
+ }
+ lag = fine;
+ return data.rate / lag;
+}
+
+type Shape = 'lowpass' | 'highpass' | 'lowshelf' | 'highshelf';
+
+/** A two-pole filter run over @p channel where it lies: a cut above or below @p hz, or a shelf of @p db there. */
+function filtered(channel: Float32Array, shape: Shape, hz: number, rate: number, db = 0): void {
+ const w = (2 * Math.PI * Math.min(hz, rate * 0.45)) / rate;
+ const [cos, sin] = [Math.cos(w), Math.sin(w)];
+ let b0: number, b1: number, b2: number, a0: number, a1: number, a2: number;
+ if (shape === 'lowpass' || shape === 'highpass') {
+ const alpha = sin / (2 * Math.SQRT1_2);
+ [b0, b1, b2] = shape === 'lowpass' ? [(1 - cos) / 2, 1 - cos, (1 - cos) / 2] : [(1 + cos) / 2, -(1 + cos), (1 + cos) / 2];
+ [a0, a1, a2] = [1 + alpha, -2 * cos, 1 - alpha];
+ } else {
+ const A = Math.pow(10, db / 40);
+ const beta = 2 * Math.sqrt(A) * (sin / 2) * Math.SQRT2;
+ const sign = shape === 'lowshelf' ? 1 : -1;
+ b0 = A * (A + 1 - sign * (A - 1) * cos + beta);
+ b1 = sign * 2 * A * (A - 1 - sign * (A + 1) * cos);
+ b2 = A * (A + 1 - sign * (A - 1) * cos - beta);
+ a0 = A + 1 + sign * (A - 1) * cos + beta;
+ a1 = -sign * 2 * (A - 1 + sign * (A + 1) * cos);
+ a2 = A + 1 + sign * (A - 1) * cos - beta;
+ }
+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
+ for (let n = 0; n < channel.length; n++) {
+ const x = channel[n]!;
+ const y = (b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2) / a0;
+ x2 = x1; x1 = x; y2 = y1; y1 = y;
+ channel[n] = y;
+ }
+}
+
+/**
+ * How much each moment of a mix is to be held down: 1 where it is quiet, less where it is loud. The loudness is
+ * followed quickly up and slowly down, as an ear follows it, and what is over the line is let through at a share of
+ * what it is over by. Worked out from the whole and laid on every instrument alike, so they still add up to it.
+ */
+function compression(channels: readonly Float32Array[], rate: number, amount: number, round: boolean): Float32Array {
+ const frames = channels[0]!.length;
+ let peak = 0;
+ for (const c of channels) for (const v of c) if (Math.abs(v) > peak) peak = Math.abs(v);
+ const gains = new Float32Array(frames).fill(1);
+ if (!(peak > 1e-6) || amount <= 0) return gains;
+ const line = peak * Math.pow(10, -(6 + 14 * amount) / 20);
+ const ratio = 1.5 + 2.5 * amount;
+ const [up, down] = [Math.exp(-1 / (0.005 * rate)), Math.exp(-1 / (0.14 * rate))];
+ let follow = 0;
+ const step = (n: number): void => {
+ let loud = 0;
+ for (const c of channels) loud = Math.max(loud, Math.abs(c[n]!));
+ follow = loud > follow ? loud + (follow - loud) * up : loud + (follow - loud) * down;
+ };
+ // A piece that goes round arrives at its start from its end, so the following starts from there.
+ if (round) for (let n = Math.max(0, frames - rate); n < frames; n++) step(n);
+ for (let n = 0; n < frames; n++) {
+ step(n);
+ if (follow > line) gains[n] = (line * Math.pow(follow / line, 1 / ratio)) / follow;
+ }
+ // The following is always a little behind the sound, so the front of every loud note would get through whole and
+ // the peak of the piece would be where it was. So the holding down begins before the note: going backward, the
+ // gain may rise only so fast, which is a hand already on the fader as the note arrives.
+ const rise = 1 / (0.006 * rate);
+ for (let n = frames - 2; n >= 0; n--) gains[n] = Math.min(gains[n]!, gains[n + 1]! + rise);
+ if (round) gains[frames - 1] = Math.min(gains[frames - 1]!, gains[0]! + rise);
+ return gains;
+}
+
+const TAIL_SECONDS = 4;
+
+/**
+ * A long sound in a place: the same sum a single transform of the whole would give, taken a stretch at a time, each
+ * stretch answered by the place and laid where it belongs. A piece of music is a hundred times as long as the room's
+ * answer, and one transform of all of it costs several times what these do.
+ */
+function inPlace(response: Float32Array): (signal: Float32Array) => Float32Array {
+ let size = 1;
+ while (size < response.length * 2) size <<= 1;
+ const block = size - response.length;
+ const [hr, hi] = [new Float64Array(size), new Float64Array(size)];
+ hr.set(response);
+ fft(hr, hi);
+ const [xr, xi] = [new Float64Array(size), new Float64Array(size)];
+ return (signal) => {
+ const out = new Float32Array(signal.length);
+ for (let from = 0; from < signal.length; from += block) {
+ xr.fill(0); xi.fill(0);
+ let any = false;
+ for (let n = 0; n < block && from + n < signal.length; n++) { const v = signal[from + n]!; xr[n] = v; if (v !== 0) any = true; }
+ if (!any) continue;
+ fft(xr, xi);
+ for (let k = 0; k < size; k++) {
+ const re = xr[k]! * hr[k]! - xi[k]! * hi[k]!, im = xr[k]! * hi[k]! + xi[k]! * hr[k]!;
+ // Back the same way: the transform of the conjugate, shared out.
+ xr[k] = re; xi[k] = -im;
+ }
+ fft(xr, xi);
+ for (let n = 0; n < size && from + n < signal.length; n++) out[from + n]! += xr[n]! / size;
+ }
+ return out;
+ };
+}
+
+/** The samples a validated source makes. @p given holds the recordings its instruments play, by the path each is named by. */
+export function renderMusic(source: MusicSource, given: Readonly<Record<string, SampleData>> = {}): RenderedMusic {
+ const compiled = compileMusic(source);
+ const rate = source.rate ?? 44100;
+ const count = Math.max(1, Math.round(compiled.seconds * rate));
+ const work = count + Math.round(TAIL_SECONDS * rate);
+ const names = Object.keys(source.instruments);
+ const buses = new Map(names.map((name) => [name, [new Float32Array(work), new Float32Array(work)]] as const));
+
+ const cache = new Map<string, Float32Array[]>();
+ const noteOf = (name: string, instrument: MusicInstrument, e: MusicEvent, turn: number, zone: number): Float32Array[] => {
+ // The same note is made a few times over and no more: enough that a hat is not one sample struck again.
+ const legato = instrument.legato === true ? 0.07 : instrument.legato || 0;
+ const slur = e.slur ? legato : 0;
+ // As long as it sounds: as written, or on to the bar line under the pedal, and a moment more where the next
+ // note comes in under it.
+ const held = (e.sounds ?? e.seconds) + (e.tied ? legato : 0);
+ const key = `${name}|${e.midi}|${Math.round(held * 1000)}|${slur}|${instrument.samples ? `z${zone}` : turn % 3}`;
+ let made = cache.get(key);
+ if (!made && instrument.samples) {
+ made = sampleNote(name, instrument, zone, e.midi, held, rate, given, slur);
+ cache.set(key, made);
+ }
+ if (!made) {
+ const release = instrument.release ?? 0.08;
+ const layers = instrument.layers!.map((l) => forNote(l, held, release, slur));
+ const duration = Math.min(8, Math.max(0.02, ...layers.map((l) => reach(l, held + release))));
+ made = renderSound({ duration, rate, layers, normalize: false }, 0, { pitch: e.midi === null ? 1 : Math.pow(2, (e.midi - 69) / 12), seed: (turn % 3) * 7919, raw: true }).channels;
+ cache.set(key, made);
+ }
+ return made;
+ };
+
+ const turns = new Map<string, number>();
+ for (const e of compiled.events) {
+ const instrument = source.instruments[e.instrument]!;
+ const turn = turns.get(e.instrument) ?? 0;
+ turns.set(e.instrument, turn + 1);
+ // Which recording, for an instrument of them: recordings of one note take turns, counted for each note apart.
+ let zone = { index: 0, matched: false };
+ if (instrument.samples) {
+ const of = `${e.instrument}|${e.midi}|${e.mark}`;
+ const again = turns.get(of) ?? 0;
+ turns.set(of, again + 1);
+ zone = sampleZone(instrument, e.midi, e.mark, again);
+ }
+ const note = noteOf(e.instrument, instrument, e, turn, zone.index);
+ const [l, r] = [note[0]!, note[1] ?? note[0]!];
+ const pan = instrument.pan ?? 0;
+ // Equal power, and full in the middle. A recording made as hard as the note is marked is already that loud:
+ // the mark is not counted twice.
+ const loud = (zone.matched ? e.loud / e.hard : e.loud) * (instrument.gain ?? 1) * Math.SQRT2;
+ const [gl, gr] = [Math.cos(((pan + 1) * Math.PI) / 4) * loud, Math.sin(((pan + 1) * Math.PI) / 4) * loud];
+ const [left, right] = buses.get(e.instrument)!;
+ const from = Math.round(e.at * rate);
+ for (let n = 0; n < l.length && from + n < work; n++) {
+ left[from + n]! += l[n]! * gl;
+ right[from + n]! += r[n]! * gr;
+ }
+ }
+
+ // What each instrument has no need of, taken off before the room hears it.
+ for (const name of names) {
+ const instrument = source.instruments[name]!;
+ for (const channel of buses.get(name)!) {
+ if (instrument.lowcut) filtered(channel, 'highpass', instrument.lowcut, rate);
+ if (instrument.highcut) filtered(channel, 'lowpass', instrument.highcut, rate);
+ }
+ }
+
+ // The room. One for everything; or, when the instruments are to be written apart, one each, so they still add up.
+ const room = [new Float32Array(work), new Float32Array(work)];
+ if (source.reverb) {
+ const [size, mix] = [source.reverb.size ?? 0.4, (source.reverb.mix ?? 0.2) * 3];
+ const answers = [0, 1].map((side) => inPlace(placeResponse(rate, size, 'room', side)));
+ const sendOf = (name: string): number => source.instruments[name]!.reverb ?? 0.3;
+ if (source.stems) {
+ for (const name of names) {
+ if (sendOf(name) === 0) continue;
+ buses.get(name)!.forEach((channel, c) => {
+ const wet = answers[c]!(channel);
+ for (let n = 0; n < work; n++) channel[n]! += wet[n]! * mix * sendOf(name);
+ });
+ }
+ } else {
+ for (const c of [0, 1]) {
+ const send = new Float32Array(work);
+ for (const name of names) { const [bus, share] = [buses.get(name)![c]!, sendOf(name)]; if (share > 0) for (let n = 0; n < work; n++) send[n]! += bus[n]! * share; }
+ const wet = answers[c]!(send);
+ for (let n = 0; n < work; n++) room[c]![n] = wet[n]! * mix;
+ }
+ }
+ }
+
+ const loop = source.loop !== false;
+ // Where the round begins: the start, or the end of an introduction that is heard once.
+ const loopStart = loop && source.intro ? compiled.parts[source.intro]!.at : 0;
+ const roundFrom = Math.round(loopStart * rate);
+ // A piece that ends rings out: the file runs on past its last bar until what is left cannot be heard. One that fades
+ // out is at nothing by the end of the bar, and has nothing to ring.
+ let total = count;
+ if (!loop && !source.fadeOut) {
+ let last = count;
+ for (const channel of [...room, ...names.flatMap((name) => buses.get(name)!)]) for (let n = work - 1; n > last; n--) if (Math.abs(channel[n]!) > 2e-4) { last = n; break; }
+ total = Math.min(work, last + (last > count ? Math.round(0.05 * rate) : 0));
+ }
+ const finish = (channel: Float32Array): Float32Array => {
+ const out = channel.slice(0, total);
+ // What rings past the end is heard as the round begins again, which is where it is put.
+ if (loop) for (let n = count; n < work; n++) out[roundFrom + ((n - count) % (count - roundFrom))]! += channel[n]!;
+ else {
+ if (source.fadeIn) { const rise = Math.round(source.fadeIn * rate); for (let n = 0; n < rise && n < total; n++) out[n]! *= (n / rise) ** 2; }
+ // Let down over the seconds asked, or over the last fiftieth of one so that it does not stop on a step.
+ const fall = Math.min(total, Math.round((source.fadeOut ?? 0.02) * rate));
+ for (let n = 0; n < fall; n++) out[total - 1 - n]! *= source.fadeOut ? (n / fall) ** 2 : n / fall;
+ }
+ return out;
+ };
+ const stems: Record<string, Float32Array[]> = {};
+ for (const name of names) stems[name] = buses.get(name)!.map(finish);
+ const channels = [0, 1].map((c) => {
+ const sum = finish(room[c]!);
+ for (const name of names) { const stem = stems[name]![c]!; for (let n = 0; n < total; n++) sum[n]! += stem[n]!; }
+ return sum;
+ });
+
+ // The whole, once summed: held together, and tilted. Done to the sum and to each instrument alike.
+ if (source.master) {
+ const every = [channels, ...Object.values(stems)];
+ if (source.master.compress) {
+ const gains = compression(channels, rate, source.master.compress, loop);
+ for (const list of every) for (const channel of list) for (let n = 0; n < total; n++) channel[n]! *= gains[n]!;
+ }
+ for (const list of every) for (const channel of list) {
+ if (source.master.low) filtered(channel, 'lowshelf', 110, rate, source.master.low);
+ if (source.master.high) filtered(channel, 'highshelf', 7000, rate, source.master.high);
+ }
+ }
+
+ let peak = 0;
+ for (const channel of channels) for (const v of channel) if (Math.abs(v) > peak) peak = Math.abs(v);
+ const notes = [...compiled.notes];
+ // A recording called a note it is not puts every note played from it out of tune, and nothing in the notes shows it.
+ for (const name of names) {
+ const wrong: { file: string; said: number; is: number }[] = [];
+ // A drum is struck as it was recorded, at no note: whatever pitch is found in it, it is not out of tune with anything.
+ const zones = compiled.events.some((e) => e.instrument === name && e.midi !== null) ? source.instruments[name]!.samples ?? [] : [];
+ const heard = new Set<string>();
+ for (const zone of zones) {
+ const data = given[zone.file];
+ // A recording used for several ranges is listened to once.
+ if (!data || heard.has(`${zone.file}|${zone.note}`)) continue;
+ heard.add(`${zone.file}|${zone.note}`);
+ const said = midiOf(zone.note)!;
+ // Where it is said to be sharp or flat of its note, that is where it is listened for.
+ const hz = 440 * Math.pow(2, (said + (zone.tune ?? 0) / 100 - 69) / 12);
+ const found = samplePitch(data, hz);
+ const off = found === null ? 0 : 12 * Math.log2(found / hz);
+ if (Math.abs(off) >= 0.7) wrong.push({ file: zone.file, said, is: Math.round(said + off) });
+ }
+ if (wrong.length === 0) continue;
+ const by = (w: { said: number; is: number }): number => w.is - w.said;
+ const semitones = (n: number): string => `${Math.abs(n)} semitone${Math.abs(n) === 1 ? '' : 's'} ${n > 0 ? 'higher' : 'lower'}`;
+ // A whole library out by the same amount is one thing to say, and nearly always an octave: it counts its octaves from another C.
+ if (wrong.length === heard.size && wrong.length > 1 && wrong.every((w) => by(w) === by(wrong[0]!))) {
+ notes.push(`"${name}": every one of its ${heard.size} recordings sounds ${semitones(by(wrong[0]!))} than the note it is said to be (${wrong[0]!.file} is said to be ${noteName(wrong[0]!.said)} and sounds as ${noteName(wrong[0]!.is)})${Math.abs(by(wrong[0]!)) === 12 ? ', as a library does that counts its octaves from another C' : ''}: the instrument plays that much out. Move each \`note\` by that much`);
+ } else {
+ for (const w of wrong) notes.push(`"${name}": ${w.file} is said to be ${noteName(w.said)} and sounds as ${noteName(w.is)}: every note played from it is ${semitones(by(w))} than written. Set its note to "${noteName(w.is)}"`);
+ }
+ }
+ const target = source.gain ?? 0.9;
+ const scale = peak > 1e-6 ? target / peak : 1;
+ if (peak <= 1e-6) notes.push('the piece is silent: nothing in it reaches a level that can be heard');
+ for (const list of [channels, ...Object.values(stems)]) for (const channel of list) for (let n = 0; n < total; n++) channel[n]! *= scale;
+ const rmsOf = (list: Float32Array[], from = 0, to = count): number => { let s = 0; for (const channel of list) for (let n = from; n < to; n++) s += channel[n]! * channel[n]!; return Math.sqrt(s / (Math.max(1, to - from) * list.length)); };
+ const rms = rmsOf(channels);
+
+ // Where a loop meets itself. The samples join without a step whatever is written; what the ear hears as a join is
+ // the music changing at once, a full last bar running into a first bar with two instruments in it.
+ let join: RenderedMusic['join'] = null;
+ if (loop) {
+ const bar = Math.min(count, Math.round(compiled.barSeconds * rate));
+ const sounding = (from: number, to: number): string[] => {
+ // In the bar for more than a twentieth of it: a note let go on the bar line, a few thousandths late, is not in the next bar.
+ const least = compiled.barSeconds * 0.05;
+ return names.filter((name) => compiled.events.some((e) => e.instrument === name && Math.min(to, e.at + e.seconds) - Math.max(from, e.at) > least));
+ };
+ const db = (level: number): number => (level > 0 && rms > 0 ? Math.round(20 * Math.log10(level / rms) * 10) / 10 : -120);
+ join = {
+ // The first bar of the round, which with an introduction is not the first bar of the file.
+ ends: sounding(compiled.seconds - compiled.barSeconds, compiled.seconds), begins: sounding(loopStart, loopStart + compiled.barSeconds),
+ endDb: db(rmsOf(channels, count - bar, count)), startDb: db(rmsOf(channels, roundFrom, Math.min(count, roundFrom + bar))),
+ };
+ const [gone, come] = [join.ends.filter((n) => !join!.begins.includes(n)), join.begins.filter((n) => !join!.ends.includes(n))];
+ if (count - roundFrom > bar * 2 && (Math.abs(join.endDb - join.startDb) > 6 || gone.length + come.length > Math.max(1, names.length / 3))) {
+ notes.push(`where the loop meets itself the music changes at once: its last bar has ${join.ends.join(', ') || 'nothing'} at ${join.endDb} dB and its first has ${join.begins.join(', ') || 'nothing'} at ${join.startDb} dB${gone.length ? `, so ${gone.join(', ')} stop${gone.length === 1 ? 's' : ''} dead` : ''}. A loop is heard as one piece when its end is as full as its start: end on a part like the one it comes back to (thin the last part with \`without\`, or begin as full as it ends), and put a build that happens once in an introduction with \`intro\``);
+ }
+ }
+
+ const instruments: RenderedMusic['instruments'] = {};
+ for (const name of names) {
+ const mine = compiled.events.filter((e) => e.instrument === name);
+ const pitches = mine.filter((e) => e.midi !== null).map((e) => e.midi!);
+ const level = rmsOf(stems[name]!);
+ instruments[name] = {
+ notes: mine.length,
+ ...(pitches.length ? { low: noteName(Math.min(...pitches)), high: noteName(Math.max(...pitches)) } : {}),
+ levelDb: level > 0 && rms > 0 ? Math.round(20 * Math.log10(level / rms) * 10) / 10 : -120,
+ };
+ }
+ return { ...compiled, notes, rate, channels, peak: peak > 1e-6 ? target : 0, rms, loopStart, tailSeconds: (total - count) / rate, join, stems: source.stems ? stems : null, instruments };
+}
diff --git a/sdk/src/sound/musicSource.ts b/sdk/src/sound/musicSource.ts
new file mode 100644
index 000000000..e2bbeb51e
--- /dev/null
+++ b/sdk/src/sound/musicSource.ts
@@ -0,0 +1,466 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file musicSource.ts — a piece of music as what it is made of: instruments, the patterns they play, and the order
+ * the patterns come in.
+ *
+ * An instrument is the layers of a sound (soundSource.ts), written as it sounds at A above middle C; a note
+ * strikes it at another pitch for as long as the note lasts. A pattern is a few bars, each track a line of
+ * steps. A step is a degree of the key and not a pitch in Hz, so a line written without accidentals cannot
+ * leave the key, and a track that follows the bar's chord cannot leave the chord's scale either. What is saved
+ * is this description; the `.wav` a game plays is made from it.
+ *
+ * Layers make sounds that are plainly made. An instrument that has to pass for a real one is recordings of it:
+ * a few notes of a piano or a section of strings, each played back faster or slower for the notes round it.
+ */
+import { validateSoundSource, type SoundLayer } from './soundSource';
+
+export const MUSIC_SOURCE_EXT = '.esmusic';
+export const MUSIC_SOURCE_VERSION = 1;
+export const MAX_MUSIC_SECONDS = 240;
+
+/**
+ * Semitones above the tonic of each of a scale's degrees. Most have seven. The five-note scales have five, and a line
+ * written in one of them cannot touch the two notes it leaves out, which is the whole of their sound: `pentatonic`
+ * and `pentatonicMinor` by their Western names, and the five Chinese modes, each the same five notes begun from
+ * another of them, gong (do), shang (re), jue (mi), zhi (sol) and yu (la).
+ */
+export const SCALES = {
+ pentatonic: [0, 2, 4, 7, 9],
+ pentatonicMinor: [0, 3, 5, 7, 10],
+ gong: [0, 2, 4, 7, 9],
+ shang: [0, 2, 5, 7, 10],
+ jue: [0, 3, 5, 8, 10],
+ zhi: [0, 2, 5, 7, 9],
+ yu: [0, 3, 5, 7, 10],
+ major: [0, 2, 4, 5, 7, 9, 11],
+ minor: [0, 2, 3, 5, 7, 8, 10],
+ dorian: [0, 2, 3, 5, 7, 9, 10],
+ phrygian: [0, 1, 3, 5, 7, 8, 10],
+ lydian: [0, 2, 4, 6, 7, 9, 11],
+ mixolydian: [0, 2, 4, 5, 7, 9, 10],
+ harmonic: [0, 2, 3, 5, 7, 8, 11],
+} as const;
+export type ScaleName = keyof typeof SCALES;
+
+const TONICS: Record<string, number> = { C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, F: 5, 'F#': 6, Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11 };
+
+/** One recording of an instrument playing one note. */
+export interface MusicSample {
+ /** A project path to the recording. */
+ file: string;
+ /** The note it is a recording of: "C4" is middle C, "F#3", "Bb2"; or its number, 60 being middle C. */
+ note: string | number;
+ /** The notes it plays, lowest to highest. Left out, each note is played by the recording nearest it. */
+ low?: string | number;
+ high?: string | number;
+ /** For a note held longer than the recording: true goes round its steady middle, [from, to] round those seconds of it. A piano dies of itself and has none. */
+ loop?: boolean | readonly [number, number];
+ /**
+ * How hard it was played. A step marked `?` is played from a "soft" recording and one marked `!` from a "loud"
+ * one, where the instrument has them: a piano struck hard is brighter, not only louder, and turning a soft
+ * recording up does not make it so. Left out, it is "normal".
+ */
+ dynamic?: (typeof DYNAMICS)[number];
+ /** Hundredths of a semitone the recording is sharp (above 0) or flat of its note, -100..100, which is taken out as it is played. */
+ tune?: number;
+ /** How loud this recording is played beside the instrument's others, 1 being as it is: what evens one recording against the next. */
+ gain?: number;
+ /** Nothing of it above this many Hz: a bright recording played mellow, which is how one recording serves soft notes and loud. */
+ cutoff?: number;
+}
+
+export const DYNAMICS = ['soft', 'normal', 'loud'] as const;
+
+export interface MusicInstrument {
+ /** The layers of its sound at A above middle C (440 Hz): a sine at 440 is its fundamental, one at 880 the octave over it. A layer with no `length` lasts as long as the note; one with a `length` (the knock at the front of a pluck, a drum) keeps its own. */
+ layers?: readonly SoundLayer[];
+ /** In place of layers: recordings of the instrument, each played faster or slower for the notes round it. The further a note is from its recording the less it is the instrument, so a recording every three or four semitones. */
+ samples?: readonly MusicSample[];
+ /** Samples: seconds a note takes to come in. Default 0.003. */
+ attack?: number;
+ /** Loudness against the other instruments. Default 1. */
+ gain?: number;
+ /** -1 is left, 1 is right. Default 0. */
+ pan?: number;
+ /** Octaves up or down from where its notes are written: a bass is -2. Default 0. */
+ octave?: number;
+ /** Its degrees count from the root of the bar's chord: 1 is the root, 3 the third, 5 the fifth, whatever the chord. A bass or a pad that follows is written once and moves with the chords. */
+ follow?: boolean;
+ /**
+ * A scale of its own, on the piece's tonic, that its line is written in: a tune in the five notes of `yu` over a
+ * piece in `minor`, whose chords and bass have all seven. That is how the style is made, a tune that cannot
+ * touch the two notes the harmony under it is free to use. Not for an instrument that follows the chords, whose
+ * degrees are counted from them.
+ */
+ scale?: ScaleName;
+ /** Seconds a held note takes to die after it is let go. Default 0.08. */
+ release?: number;
+ /**
+ * Nothing of it below this many Hz. Every instrument but the bass and the kick has a bottom it does not need,
+ * the thump of a piano's frame, the rumble under a string section, and all of them together are the mud a mix
+ * drowns in: 120 to 200 for what plays in the middle, 300 and up for what plays high.
+ */
+ lowcut?: number;
+ /** Nothing of it above this many Hz: what should sit behind the rest is duller than what is in front. */
+ highcut?: number;
+ /**
+ * A line played in one breath. Where one note of its line runs straight into the next, with no silence between
+ * and the next not marked `!`, the next is not struck afresh: it comes in under the one before over this many
+ * seconds (true is 0.07) while that one goes out, and a recording is taken from past its attack. This is a bow
+ * that does not leave the string and a breath that is not taken again; without it every note of a violin or a
+ * flute begins from nothing and a tune is a row of separate notes. Chords are struck as they were.
+ */
+ legato?: boolean | number;
+ /**
+ * The sustaining pedal, held down through each bar and changed on the bar line: every note rings on to the end
+ * of its bar however short it is written, so the notes of a broken chord pile up into the chord and one bar
+ * runs into the next. A piano without it is dry and its chords are apart.
+ */
+ pedal?: boolean;
+ /** How much of it goes to the room, 0..1. Default 0.3; a bass or a kick wants 0. */
+ reverb?: number;
+}
+
+export interface MusicPattern {
+ bars: number;
+ /** Steps to a beat. Default 4, which is sixteenths; 3 is triplets; 2 is eighths. */
+ div?: number;
+ /** The chord of each bar, as the degree its root is on: [1, 6, 3, 7]. Fewer than the bars come round again. Only instruments that `follow` hear them. */
+ chords?: readonly number[];
+ /**
+ * How loud each bar begins, for an instrument or for `all` of them, 1 being as written: `{ lead: [0.6, 0.8, 1,
+ * 0.7] }`. Between one bar's number and the next the loudness moves evenly, which is a crescendo or a
+ * diminuendo; one number more than there are bars is where the last bar ends. A phrase that is all one loudness
+ * is not heard as a phrase.
+ */
+ dynamics?: Readonly<Record<string, readonly number[]>>;
+ /**
+ * A line of steps for each instrument that plays, separated by spaces, bars by `|`. A step is: `.` silence; `-` the
+ * note before, still held; a degree 1..7 with `'` for each octave up and `,` for each down, `#` or `b` before it to
+ * leave the key by a semitone; `[1 3 5]` several at once; `x` the instrument at its own pitch, for a drum. `!` after
+ * a step makes it louder and `?` softer.
+ */
+ tracks: Readonly<Record<string, string>>;
+}
+
+export type SongPart = string | { pattern: string; without?: readonly string[]; only?: readonly string[] };
+
+export interface MusicSource {
+ version?: number;
+ /** Beats a minute. */
+ tempo: number;
+ /** Beats to a bar. Default 4. */
+ beats?: number;
+ /** The tonic: C, F#, Bb. */
+ key: string;
+ /** Default minor. */
+ scale?: ScaleName;
+ /** Every second step comes late by this share of a step, 0..0.6. 0.33 is a shuffle. */
+ swing?: number;
+ /** How unlike a machine: timing and loudness off by a little at random, 0..1. Default 0.15. */
+ humanize?: number;
+ seed?: number;
+ instruments: Readonly<Record<string, MusicInstrument>>;
+ patterns: Readonly<Record<string, MusicPattern>>;
+ /** The patterns in the order they come, each whole, or with some instruments left out or only some kept. */
+ song: readonly SongPart[];
+ /**
+ * What rings past the end comes in at the start, so the piece runs into itself. Default true. False is a piece
+ * with an end: its last notes and the room ring out after the last bar, and the file is that much longer.
+ */
+ loop?: boolean;
+ /**
+ * How many of the song's first parts are an introduction: heard once, after which the rest goes round. The file
+ * is still one file; what rings past its end comes in where the introduction ends, and the reply gives that place
+ * as `loopStart`, which the game hands to playBGM or sets on the AudioSource. This is where a build belongs
+ * that a loop cannot hold: two instruments growing to all of them, once.
+ */
+ intro?: number;
+ /** Seconds over which it comes up from nothing at its start. A loop comes round to its start again and again, so only a piece that ends has one; a game fades a loop in as it starts it. */
+ fadeIn?: number;
+ /** Seconds before the end of the last bar over which it goes down to nothing, for a piece that ends and has no ending written. */
+ fadeOut?: number;
+ /** Also a file for each instrument, which add up to the whole: a game brings them in and out. */
+ stems?: boolean;
+ /** The room it is all in: `size` 0..1, `mix` 0..1. */
+ reverb?: { size?: number; mix?: number };
+ /**
+ * Time that gives: each pattern is a phrase that begins a little held back, moves on through its middle and
+ * eases off to its end, by up to this share of 8% of the tempo, 0..1. Every instrument moves together and a
+ * pattern is as long as it was. 0.3 is a player breathing; 1 is a romantic one. Not for what is danced to.
+ */
+ rubato?: number;
+ /**
+ * What is done to the whole once it is summed. `compress` 0..1 holds the loud moments down so the quiet ones
+ * come up and the instruments are heard as one thing and not several (0.3 to 0.5 for most pieces); `low` and
+ * `high` are decibels more or less below 110 Hz and above 7 kHz, -12..12.
+ */
+ master?: { compress?: number; low?: number; high?: number };
+ /** How loud the loudest moment is, 1 being full. Default 0.9. */
+ gain?: number;
+ rate?: number;
+}
+
+/** One sounding in a step: a degree, or the instrument's own pitch. */
+export interface StepNote { degree: number; alter: number; octave: number }
+export type Step =
+ | { kind: 'rest' }
+ | { kind: 'hold' }
+ | { kind: 'hit'; loud: number }
+ | { kind: 'notes'; loud: number; notes: StepNote[] };
+
+const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
+const between = (v: unknown, lo: number, hi: number): boolean => isNum(v) && v >= lo && v <= hi;
+const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
+const NAME = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
+
+export const tonicOf = (key: string): number => TONICS[key]!;
+
+/** "C4" as its number, 60; a number as itself. Null for what is neither. */
+export function midiOf(note: unknown): number | null {
+ if (typeof note === 'number') return Number.isInteger(note) && note >= 0 && note <= 127 ? note : null;
+ const m = typeof note === 'string' ? /^([A-G](?:#|b)?)(-?\d)$/.exec(note) : null;
+ if (!m || TONICS[m[1]!] === undefined) return null;
+ const midi = TONICS[m[1]!]! + 12 * (Number(m[2]) + 1);
+ return midi >= 0 && midi <= 127 ? midi : null;
+}
+
+/** The recordings a source plays, each once. */
+export function musicSampleFiles(source: MusicSource): string[] {
+ return [...new Set(Object.values(source.instruments).flatMap((i) => (i.samples ?? []).map((s) => s.file)))];
+}
+
+const loudOf = (mark: string): number => (mark === '!' ? 1.3 : mark === '?' ? 0.6 : 1);
+
+function noteOf(text: string): StepNote | null {
+ const m = /^([#b]?)([1-7])([',]*)$/.exec(text);
+ if (!m) return null;
+ let octave = 0;
+ for (const c of m[3]!) octave += c === "'" ? 1 : -1;
+ return { degree: Number(m[2]), alter: m[1] === '#' ? 1 : m[1] === 'b' ? -1 : 0, octave };
+}
+
+/** A track's line as steps, bar by bar. Throws saying which bar is wrong and why. */
+export function parseTrack(text: string, bars: number, stepsToBar: number, where: string, degrees = 7): Step[] {
+ const out: Step[] = [];
+ const written = text.split('|').map((b) => b.trim());
+ if (written[written.length - 1] === '') written.pop();
+ if (written.length !== bars) throw new Error(`${where} has ${written.length} bar${written.length === 1 ? '' : 's'} between its | marks; the pattern is ${bars}`);
+ written.forEach((bar, b) => {
+ // A chord's notes are kept together through the split on spaces.
+ const tokens = bar.replace(/\[([^\]]*)\]/g, (_, inner: string) => `[${inner.trim().split(/\s+/).join('+')}]`).split(/\s+/).filter((t) => t !== '');
+ if (tokens.length !== stepsToBar) throw new Error(`${where}, bar ${b + 1} has ${tokens.length} steps; a bar here is ${stepsToBar}. Write "." for a silent step and "-" for one that holds the note before`);
+ for (const token of tokens) {
+ const mark = token.endsWith('!') || token.endsWith('?') ? token.slice(-1) : '';
+ const body = mark ? token.slice(0, -1) : token;
+ if (body === '.') out.push({ kind: 'rest' });
+ else if (body === '-') out.push({ kind: 'hold' });
+ else if (body === 'x') out.push({ kind: 'hit', loud: loudOf(mark) });
+ else {
+ const parts = body.startsWith('[') && body.endsWith(']') ? body.slice(1, -1).split('+') : [body];
+ const notes = parts.map(noteOf);
+ if (notes.length === 0 || notes.length > 6 || notes.some((n) => n === null)) {
+ throw new Error(`${where}, bar ${b + 1}: "${token.replace(/\+/g, ' ')}" is not a step. A step is . (silence), - (hold), x (a drum), a degree 1..7 with ' or , for octaves and # or b before it, or [1 3 5] for up to six at once`);
+ }
+ const past = (notes as StepNote[]).find((n) => n.degree > degrees);
+ if (past) throw new Error(`${where}, bar ${b + 1}: degree ${past.degree} is not in this scale, which has ${degrees} notes: its degrees are 1..${degrees}, and the next octave begins again at 1'`);
+ out.push({ kind: 'notes', loud: loudOf(mark), notes: notes as StepNote[] });
+ }
+ }
+ });
+ return out;
+}
+
+const SOURCE_FIELDS = ['version', 'tempo', 'beats', 'key', 'scale', 'swing', 'humanize', 'seed', 'instruments', 'patterns', 'song', 'loop', 'intro', 'fadeIn', 'fadeOut', 'stems', 'reverb', 'rubato', 'master', 'gain', 'rate'];
+const INSTRUMENT_FIELDS = ['layers', 'samples', 'attack', 'gain', 'pan', 'octave', 'follow', 'release', 'reverb', 'legato', 'pedal', 'lowcut', 'highcut', 'scale'];
+const RECORDING = /\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i;
+
+function checkSamples(samples: unknown, where: string): void {
+ if (!Array.isArray(samples) || samples.length === 0 || samples.length > 256) throw new Error(`${where}: samples must be 1..256 of { file, note }`);
+ samples.forEach((sample: unknown, i) => {
+ const at = `${where}, sample ${i + 1}`;
+ if (!isObj(sample)) throw new Error(`${at} must be { file, note }`);
+ for (const key of Object.keys(sample)) if (!['file', 'note', 'low', 'high', 'loop', 'dynamic', 'tune', 'gain', 'cutoff'].includes(key)) throw new Error(`${at} has unknown "${key}"; a sample has file, note, low, high, loop, dynamic, tune, gain, cutoff`);
+ if (sample.gain !== undefined && !between(sample.gain, 0.01, 4)) throw new Error(`${at}: gain must be 0.01..4, 1 being the recording as it is`);
+ if (sample.cutoff !== undefined && !between(sample.cutoff, 200, 20000)) throw new Error(`${at}: cutoff must be Hz, 200..20000`);
+ if (sample.dynamic !== undefined && !DYNAMICS.includes(sample.dynamic as never)) throw new Error(`${at}: dynamic must be one of ${DYNAMICS.join(', ')}`);
+ if (sample.tune !== undefined && !between(sample.tune, -100, 100)) throw new Error(`${at}: tune must be hundredths of a semitone, -100..100`);
+ if (typeof sample.file !== 'string' || !RECORDING.test(sample.file)) throw new Error(`${at}: file must be a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)`);
+ if (midiOf(sample.note) === null) throw new Error(`${at}: note must be the note recorded, as "C4", "F#3" or "Bb2" (C4 is middle C), or its number 0..127`);
+ for (const key of ['low', 'high']) if (sample[key] !== undefined && midiOf(sample[key]) === null) throw new Error(`${at}: ${key} must be a note, as "C4"`);
+ if (sample.low !== undefined && sample.high !== undefined && midiOf(sample.low)! > midiOf(sample.high)!) throw new Error(`${at}: low is above high`);
+ const loop = sample.loop;
+ if (loop !== undefined && typeof loop !== 'boolean' && !(Array.isArray(loop) && loop.length === 2 && isNum(loop[0]) && isNum(loop[1]) && loop[0] >= 0 && loop[1] > loop[0] + 0.0005)) {
+ throw new Error(`${at}: loop must be true, or [from, to] in seconds with to past from`);
+ }
+ });
+}
+const PATTERN_FIELDS = ['bars', 'div', 'chords', 'dynamics', 'tracks'];
+
+/** Seconds the song lasts, before anything that rings past its end. */
+export function musicSeconds(source: MusicSource): number {
+ const bar = ((source.beats ?? 4) * 60) / source.tempo;
+ return source.song.reduce((sum, part) => sum + source.patterns[typeof part === 'string' ? part : part.pattern]!.bars * bar, 0);
+}
+
+/** The source if it is well formed; otherwise throws, naming the instrument, the pattern, the track and the bar. */
+export function validateMusicSource(raw: unknown): MusicSource {
+ if (!isObj(raw)) throw new Error('a music source must be { tempo, key, instruments, patterns, song }');
+ const s = raw;
+ for (const key of Object.keys(s)) if (!SOURCE_FIELDS.includes(key)) throw new Error(`unknown field "${key}"; music has ${SOURCE_FIELDS.join(', ')}`);
+ if (s.version !== undefined && s.version !== MUSIC_SOURCE_VERSION) throw new Error(`version ${String(s.version)} is not one this editor reads (${MUSIC_SOURCE_VERSION})`);
+ if (!between(s.tempo, 30, 300)) throw new Error('tempo must be beats a minute, 30..300');
+ if (s.beats !== undefined && !(Number.isInteger(s.beats) && between(s.beats, 2, 12))) throw new Error('beats must be a whole number to the bar, 2..12');
+ if (typeof s.key !== 'string' || TONICS[s.key] === undefined) throw new Error(`key must be a tonic: ${Object.keys(TONICS).join(', ')}`);
+ if (s.scale !== undefined && !(typeof s.scale === 'string' && s.scale in SCALES)) throw new Error(`scale must be one of ${Object.keys(SCALES).join(', ')}`);
+ if (s.swing !== undefined && !between(s.swing, 0, 0.6)) throw new Error('swing must be 0..0.6');
+ if (s.humanize !== undefined && !between(s.humanize, 0, 1)) throw new Error('humanize must be 0..1');
+ if (s.seed !== undefined && !Number.isInteger(s.seed)) throw new Error('seed must be a whole number');
+ if (s.gain !== undefined && !between(s.gain, 0, 1)) throw new Error('gain must be 0..1');
+ if (s.rate !== undefined && ![22050, 44100, 48000].includes(s.rate as number)) throw new Error('rate must be one of 22050, 44100, 48000');
+ for (const key of ['loop', 'stems']) if (s[key] !== undefined && typeof s[key] !== 'boolean') throw new Error(`${key} must be true or false`);
+ if (s.reverb !== undefined) {
+ if (!isObj(s.reverb)) throw new Error('reverb must be { size?, mix? }');
+ for (const key of Object.keys(s.reverb)) if (!['size', 'mix'].includes(key)) throw new Error(`reverb has unknown "${key}"; it takes size, mix`);
+ if (s.reverb.size !== undefined && !between(s.reverb.size, 0, 1)) throw new Error('reverb.size must be 0..1');
+ if (s.reverb.mix !== undefined && !between(s.reverb.mix, 0, 1)) throw new Error('reverb.mix must be 0..1');
+ }
+
+ if (s.rubato !== undefined && !between(s.rubato, 0, 1)) throw new Error('rubato must be 0..1');
+ if (s.master !== undefined) {
+ if (!isObj(s.master)) throw new Error('master must be { compress?, low?, high? }');
+ for (const key of Object.keys(s.master)) if (!['compress', 'low', 'high'].includes(key)) throw new Error(`master has unknown "${key}"; it takes compress, low, high`);
+ if (s.master.compress !== undefined && !between(s.master.compress, 0, 1)) throw new Error('master.compress must be 0..1');
+ for (const key of ['low', 'high']) if (s.master[key] !== undefined && !between(s.master[key], -12, 12)) throw new Error(`master.${key} must be decibels, -12..12`);
+ }
+ if (!isObj(s.instruments) || Object.keys(s.instruments).length === 0) throw new Error('instruments must be { name: { layers: [...] } }, at least one');
+ if (Object.keys(s.instruments).length > 16) throw new Error('at most 16 instruments');
+ for (const [name, value] of Object.entries(s.instruments)) {
+ const where = `instrument "${name}"`;
+ if (!NAME.test(name)) throw new Error(`${where}: a name is a letter, then letters, digits, _ or -`);
+ if (!isObj(value)) throw new Error(`${where} must be { layers: [...] }`);
+ for (const key of Object.keys(value)) if (!INSTRUMENT_FIELDS.includes(key)) throw new Error(`${where} has unknown "${key}"; an instrument has ${INSTRUMENT_FIELDS.join(', ')}`);
+ if ((value.layers === undefined) === (value.samples === undefined)) throw new Error(`${where} needs layers (a made sound) or samples (recordings), one of the two`);
+ if (value.samples !== undefined) checkSamples(value.samples, where);
+ else {
+ try {
+ // Its layers are a sound's layers, and are wrong in the same ways.
+ validateSoundSource({ duration: 8, layers: value.layers });
+ } catch (e) {
+ throw new Error(`${where}: ${(e as Error).message}`);
+ }
+ }
+ if (value.attack !== undefined && !(value.samples !== undefined && between(value.attack, 0, 2))) throw new Error(`${where}: attack is for samples, seconds 0..2; layers have their own`);
+ if (value.gain !== undefined && !between(value.gain, 0, 4)) throw new Error(`${where}: gain must be 0..4`);
+ if (value.pan !== undefined && !between(value.pan, -1, 1)) throw new Error(`${where}: pan must be -1..1`);
+ if (value.octave !== undefined && !(Number.isInteger(value.octave) && between(value.octave, -4, 4))) throw new Error(`${where}: octave must be a whole number, -4..4`);
+ if (value.follow !== undefined && typeof value.follow !== 'boolean') throw new Error(`${where}: follow must be true or false`);
+ if (value.release !== undefined && !between(value.release, 0, 4)) throw new Error(`${where}: release must be seconds, 0..4`);
+ if (value.reverb !== undefined && !between(value.reverb, 0, 1)) throw new Error(`${where}: reverb must be 0..1`);
+ if (value.legato !== undefined && typeof value.legato !== 'boolean' && !between(value.legato, 0.01, 0.5)) throw new Error(`${where}: legato must be true, or the seconds one note takes to come in under the last, 0.01..0.5`);
+ if (value.pedal !== undefined && typeof value.pedal !== 'boolean') throw new Error(`${where}: pedal must be true or false`);
+ if (value.scale !== undefined) {
+ if (!(typeof value.scale === 'string' && value.scale in SCALES)) throw new Error(`${where}: scale must be one of ${Object.keys(SCALES).join(', ')}`);
+ if (value.follow) throw new Error(`${where}: an instrument that follows the chords counts its degrees from them, in the piece's scale; a scale of its own is for a line that does not follow`);
+ }
+ if (value.lowcut !== undefined && !between(value.lowcut, 20, 2000)) throw new Error(`${where}: lowcut must be Hz, 20..2000`);
+ if (value.highcut !== undefined && !between(value.highcut, 500, 20000)) throw new Error(`${where}: highcut must be Hz, 500..20000`);
+ }
+
+ const beats = (s.beats as number | undefined) ?? 4;
+ const degrees = SCALES[(s.scale as ScaleName | undefined) ?? 'minor'].length;
+ if (!isObj(s.patterns) || Object.keys(s.patterns).length === 0) throw new Error('patterns must be { name: { bars, tracks: { instrument: "steps" } } }, at least one');
+ for (const [name, value] of Object.entries(s.patterns)) {
+ const where = `pattern "${name}"`;
+ if (!NAME.test(name)) throw new Error(`${where}: a name is a letter, then letters, digits, _ or -`);
+ if (!isObj(value)) throw new Error(`${where} must be { bars, tracks }`);
+ for (const key of Object.keys(value)) if (!PATTERN_FIELDS.includes(key)) throw new Error(`${where} has unknown "${key}"; a pattern has ${PATTERN_FIELDS.join(', ')}`);
+ if (!(Number.isInteger(value.bars) && between(value.bars, 1, 32))) throw new Error(`${where}: bars must be a whole number, 1..32`);
+ if (value.div !== undefined && !(Number.isInteger(value.div) && between(value.div, 1, 8))) throw new Error(`${where}: div must be whole steps to a beat, 1..8`);
+ if (value.chords !== undefined) {
+ if (!Array.isArray(value.chords) || value.chords.length === 0 || value.chords.length > (value.bars as number) || value.chords.some((c) => !(Number.isInteger(c) && c >= 1 && c <= degrees))) {
+ throw new Error(`${where}: chords must be the degree of each bar's root, 1..${degrees}, no more of them than bars`);
+ }
+ }
+ if (value.dynamics !== undefined) {
+ if (!isObj(value.dynamics)) throw new Error(`${where}: dynamics must be { instrument or "all": [how loud each bar begins] }`);
+ for (const [who, levels] of Object.entries(value.dynamics)) {
+ if (who !== 'all' && !(who in s.instruments)) throw new Error(`${where}: dynamics for "${who}", which is not an instrument; the instruments are ${Object.keys(s.instruments).join(', ')}, or "all"`);
+ if (!Array.isArray(levels) || levels.length === 0 || levels.length > (value.bars as number) + 1 || levels.some((v) => !between(v, 0.1, 2))) {
+ throw new Error(`${where}: dynamics for "${who}" must be how loud each bar begins, 0.1..2 with 1 as written, one for each of its ${String(value.bars)} bars and at most one more for where the last ends`);
+ }
+ }
+ }
+ if (!isObj(value.tracks) || Object.keys(value.tracks).length === 0) throw new Error(`${where}: tracks must be { instrument: "steps" }, at least one`);
+ for (const [track, line] of Object.entries(value.tracks)) {
+ if (!(track in s.instruments)) throw new Error(`${where} has a track for "${track}", which is not an instrument; the instruments are ${Object.keys(s.instruments).join(', ')}`);
+ if (typeof line !== 'string') throw new Error(`${where}, track "${track}" must be a line of steps`);
+ parseTrack(line, value.bars as number, beats * ((value.div as number | undefined) ?? 4), `${where}, track "${track}"`, SCALES[((s.instruments as Record<string, MusicInstrument>)[track]!.scale ?? (s.scale as ScaleName | undefined) ?? 'minor')].length);
+ }
+ }
+
+ if (!Array.isArray(s.song) || s.song.length === 0 || s.song.length > 64) throw new Error('song must be the patterns in order, 1..64 of them');
+ s.song.forEach((part, i) => {
+ const name = typeof part === 'string' ? part : isObj(part) ? part.pattern : undefined;
+ if (typeof name !== 'string' || !(name in (s.patterns as object))) throw new Error(`song part ${i + 1}: "${String(name)}" is not a pattern; the patterns are ${Object.keys(s.patterns as object).join(', ')}`);
+ if (isObj(part)) {
+ for (const key of Object.keys(part)) if (!['pattern', 'without', 'only'].includes(key)) throw new Error(`song part ${i + 1} has unknown "${key}"; it takes pattern, without, only`);
+ if (part.without !== undefined && part.only !== undefined) throw new Error(`song part ${i + 1}: give without or only, not both`);
+ for (const key of ['without', 'only']) {
+ const list = part[key];
+ if (list === undefined) continue;
+ if (!Array.isArray(list) || list.some((n) => typeof n !== 'string' || !(n in (s.instruments as object)))) throw new Error(`song part ${i + 1}: ${key} must be a list of instruments (${Object.keys(s.instruments as object).join(', ')})`);
+ }
+ }
+ });
+ const source = s as unknown as MusicSource;
+ const seconds = musicSeconds(source);
+ if (s.intro !== undefined) {
+ if (s.loop === false) throw new Error('intro is the part of a loop that is heard once; a piece with loop false is heard once whole and has none');
+ if (!(Number.isInteger(s.intro) && (s.intro as number) >= 1 && (s.intro as number) < s.song.length)) throw new Error(`intro must be how many of the song's first parts are heard once: a whole number from 1, leaving at least one part to go round (the song has ${s.song.length})`);
+ }
+ for (const key of ['fadeIn', 'fadeOut'] as const) {
+ if (s[key] === undefined) continue;
+ if (s.loop !== false) throw new Error(`${key} is for a piece that ends (loop: false). A loop comes round to its start with no gap, and a fade written into it would be heard every time round: the game fades it, playBGM(url, { fadeIn }) to start it and stopBGM(seconds) to end it`);
+ if (!(isNum(s[key]) && (s[key] as number) > 0 && (s[key] as number) <= seconds)) throw new Error(`${key} must be seconds, above 0 and no longer than the piece (${Math.round(seconds * 10) / 10} s)`);
+ }
+ if (seconds > MAX_MUSIC_SECONDS) throw new Error(`the song lasts ${Math.round(seconds)} s; at most ${MAX_MUSIC_SECONDS}`);
+ return source;
+}
+
+export type MusicEdit =
+ | { op: 'instrument'; name: string; value: MusicInstrument | null }
+ | { op: 'pattern'; name: string; value: MusicPattern | null }
+ | { op: 'track'; pattern: string; track: string; steps: string | null }
+ | { op: 'settings'; fields: Record<string, unknown> };
+
+/** The source with @p edits made in order, checked as a whole. A bad edit changes nothing. */
+export function applyMusicEdits(source: MusicSource, edits: readonly MusicEdit[]): MusicSource {
+ const next = JSON.parse(JSON.stringify(source)) as Record<string, unknown> & { instruments: Record<string, unknown>; patterns: Record<string, { tracks: Record<string, string> }> };
+ edits.forEach((edit, i) => {
+ const where = `edit ${i + 1}`;
+ if (!isObj(edit)) throw new Error(`${where} must be { op, ... }`);
+ if (edit.op === 'instrument' || edit.op === 'pattern') {
+ const into = edit.op === 'instrument' ? next.instruments : next.patterns;
+ if (typeof edit.name !== 'string') throw new Error(`${where}: name the ${edit.op}`);
+ if (edit.value === null) {
+ if (!(edit.name in into)) throw new Error(`${where}: there is no ${edit.op} "${edit.name}"; there are ${Object.keys(into).join(', ')}`);
+ delete into[edit.name];
+ } else (into as Record<string, unknown>)[edit.name] = edit.value;
+ } else if (edit.op === 'track') {
+ const pattern = next.patterns[edit.pattern];
+ if (!pattern) throw new Error(`${where}: there is no pattern "${edit.pattern}"; there are ${Object.keys(next.patterns).join(', ')}`);
+ if (edit.steps === null) delete pattern.tracks[edit.track];
+ else pattern.tracks[edit.track] = edit.steps;
+ } else if (edit.op === 'settings') {
+ if (!isObj(edit.fields)) throw new Error(`${where}: settings needs fields`);
+ for (const [key, value] of Object.entries(edit.fields)) {
+ if (['instruments', 'patterns'].includes(key)) throw new Error(`${where}: change ${key} with the ${key.slice(0, -1)} op`);
+ if (value === null) delete next[key];
+ else next[key] = value;
+ }
+ } else throw new Error(`${where}: op must be instrument, pattern, track or settings`);
+ });
+ return validateMusicSource(next);
+}
diff --git a/sdk/src/sound/soundRender.ts b/sdk/src/sound/soundRender.ts
new file mode 100644
index 000000000..5161a9a5a
--- /dev/null
+++ b/sdk/src/sound/soundRender.ts
@@ -0,0 +1,620 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file soundRender.ts — a sound source worked out into samples, and the samples as a `.wav`.
+ *
+ * Every layer is rendered on its own, placed in time, and summed; then what the source says of the whole (a
+ * filter, an echo, a place, a level) is applied to the sum. Nothing depends on the machine: no random number is
+ * drawn that is not seeded, and the arithmetic is plain doubles.
+ *
+ * What makes a made sound pass for a real one is mostly here, and it is not more kinds of wave. A bang is several
+ * bands of noise that die at different rates, the high ones first, behind a spike a fifth of a millisecond wide;
+ * a breaking thing is hundreds of small rings scattered in time and pitch; a place is a wash whose top dies before
+ * its bottom, after a handful of distinct first echoes. A layer of noise through one filter with one decay has
+ * none of that and is heard at once as a machine.
+ */
+import { fft } from './fft';
+import type { SoundCurve, SoundFilter, SoundLayer, SoundSource } from './soundSource';
+
+export interface RenderedSound {
+ rate: number;
+ /** One for a sound with nothing off-centre, two otherwise: left, right. */
+ channels: Float32Array[];
+ seconds: number;
+ /** The loudest moment, 0..1, after everything. */
+ peak: number;
+ /** The level over the whole, as the square root of the mean square. */
+ rms: number;
+ /** Where each layer sounds and how loud it is on its own, before the sum. */
+ layers: { id?: string; source: string; from: number; to: number; peak: number; strikes?: number }[];
+ notes: string[];
+}
+
+const TAU = Math.PI * 2;
+/** The level white noise has here, which a band of it is brought back to. */
+const NOISE_LEVEL = 1 / Math.sqrt(3);
+
+/** A curve read at @p t seconds: straight between its points, or along the ratio between them for a pitch. */
+function curveAt(curve: SoundCurve | undefined, t: number, fallback: number, ratio: boolean): number {
+ if (curve === undefined) return fallback;
+ if (typeof curve === 'number') return curve;
+ if (t <= curve[0]![0]) return curve[0]![1];
+ for (let i = 1; i < curve.length; i++) {
+ const [t1, v1] = curve[i]!;
+ if (t > t1) continue;
+ const [t0, v0] = curve[i - 1]!;
+ const w = (t - t0) / (t1 - t0);
+ // A pitch glides by ratio: halfway from 200 to 800 Hz is 400, as the ear has it.
+ return ratio && v0 > 0 && v1 > 0 ? v0 * Math.pow(v1 / v0, w) : v0 + (v1 - v0) * w;
+ }
+ return curve[curve.length - 1]![1];
+}
+
+/** The same numbers for the same seed, -1..1. */
+function noiseOf(seed: number): () => number {
+ let s = (seed * 2654435761 + 0x9e3779b9) >>> 0;
+ return () => {
+ s = (s + 0x6d2b79f5) >>> 0;
+ let t = s;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 2147483648 - 1;
+ };
+}
+
+/** What a sharp step would alias as, taken out of the two samples beside it. */
+function polyBlep(phase: number, step: number): number {
+ if (phase < step) { const t = phase / step; return t + t - t * t - 1; }
+ if (phase > 1 - step) { const t = (phase - 1) / step; return t * t + t + t + 1; }
+ return 0;
+}
+
+/** A two-pole filter whose corner may move: the coefficients are worked out again as it does. */
+class Biquad {
+ private x1 = 0; private x2 = 0; private y1 = 0; private y2 = 0;
+ private b0 = 1; private b1 = 0; private b2 = 0; private a1 = 0; private a2 = 0;
+ private last = -1;
+ constructor(private readonly type: SoundFilter['type'], private readonly q: number, private readonly rate: number, private readonly gainDb = 0) {}
+
+ tune(freq: number): void {
+ const f = Math.max(20, Math.min(this.rate * 0.45, freq));
+ if (Math.abs(f - this.last) < 0.01) return;
+ this.last = f;
+ const w = (TAU * f) / this.rate;
+ const [cos, alpha] = [Math.cos(w), Math.sin(w) / (2 * this.q)];
+ let a0 = 1 + alpha, a1 = -2 * cos, a2 = 1 - alpha;
+ let b0: number, b1: number, b2: number;
+ switch (this.type) {
+ case 'lowpass': [b0, b1, b2] = [(1 - cos) / 2, 1 - cos, (1 - cos) / 2]; break;
+ case 'highpass': [b0, b1, b2] = [(1 + cos) / 2, -(1 + cos), (1 + cos) / 2]; break;
+ case 'bandpass': [b0, b1, b2] = [alpha, 0, -alpha]; break;
+ case 'peak': {
+ const lift = Math.pow(10, this.gainDb / 40);
+ [b0, b1, b2] = [1 + alpha * lift, -2 * cos, 1 - alpha * lift];
+ [a0, a1, a2] = [1 + alpha / lift, -2 * cos, 1 - alpha / lift];
+ break;
+ }
+ default: [b0, b1, b2] = [1, -2 * cos, 1];
+ }
+ [this.b0, this.b1, this.b2, this.a1, this.a2] = [b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0];
+ }
+
+ run(x: number): number {
+ const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2;
+ // Plain assignments: this runs once a sample for every filter of every note, and a list built to be taken apart again
+ // was a quarter of the time a piece of music took to make.
+ this.x2 = this.x1; this.x1 = x; this.y2 = this.y1; this.y1 = y;
+ return y;
+ }
+}
+
+const rmsOf = (a: Float32Array): number => { let s = 0; for (const v of a) s += v * v; return Math.sqrt(s / Math.max(1, a.length)); };
+
+/** @p count samples of a noise layer's own sound, before its loudness is shaped: its colour, and its band at the level of the whole. */
+function noiseBody(layer: SoundLayer, count: number, rate: number, seed: number, pitch: number): Float32Array {
+ const random = noiseOf(seed);
+ const out = new Float32Array(count);
+ // Pink and brown are white put through a few poles; these are their memories.
+ let [p0, p1, p2, brown] = [0, 0, 0, 0];
+ for (let n = 0; n < count; n++) {
+ const white = random();
+ if (layer.color === 'pink') {
+ p0 = 0.99765 * p0 + white * 0.099046;
+ p1 = 0.963 * p1 + white * 0.2965164;
+ p2 = 0.57 * p2 + white * 1.0526913;
+ out[n] = (p0 + p1 + p2 + white * 0.1848) * 0.25;
+ } else if (layer.color === 'brown') {
+ brown = (brown + white * 0.02) / 1.02;
+ out[n] = brown * 3.5;
+ } else out[n] = white;
+ }
+ if (layer.band) {
+ // Cut to the band, then brought back up: what is left of noise after two filters is faint, and a band that
+ // had to be turned up by guess would never balance against the others.
+ const [high, low] = [new Biquad('highpass', 0.7, rate), new Biquad('lowpass', 0.7, rate)];
+ high.tune(layer.band[0] * pitch);
+ low.tune(layer.band[1] * pitch);
+ // Run in a little first, so the filters are not still starting when the sound is.
+ for (let n = 0; n < 64; n++) low.run(high.run(random()));
+ for (let n = 0; n < count; n++) out[n] = low.run(high.run(out[n]!));
+ const level = rmsOf(out);
+ if (level > 1e-9) for (let n = 0; n < count; n++) out[n]! *= NOISE_LEVEL / level;
+ }
+ return out;
+}
+
+/** A recording a layer plays: its samples and the rate they were made at. */
+export interface SoundRecording { rate: number; channels: readonly Float32Array[] }
+
+/** @p count samples of a recording, its two sides as one, played at @p speed from @p from seconds in. Past its end is silence. */
+function recordingBody(recording: SoundRecording, count: number, rate: number, speed: number, from: number): Float32Array {
+ const out = new Float32Array(count);
+ const [l, r] = [recording.channels[0]!, recording.channels[1] ?? recording.channels[0]!];
+ const step = (speed * recording.rate) / rate;
+ const start = from * recording.rate;
+ for (let n = 0; n < count; n++) {
+ const p = start + n * step;
+ const i = Math.floor(p);
+ if (i + 1 >= l.length) break;
+ const t = p - i;
+ out[n] = ((l[i]! + r[i]!) * (1 - t) + (l[i + 1]! + r[i + 1]!) * t) / 2;
+ }
+ return out;
+}
+
+/** One striking of a layer: its samples from its own start, at @p pitch times its written pitch. */
+function strike(layer: SoundLayer, seconds: number, rate: number, pitch: number, seed: number, recording: SoundRecording | null = null): Float32Array {
+ const count = Math.max(1, Math.round(seconds * rate));
+ const out = new Float32Array(count);
+ const filters = (layer.filters ?? []).map((f) => ({ run: new Biquad(f.type, f.q ?? 0.7, rate, f.gain ?? 0), freq: f.freq }));
+ // The fades that only stop a click are never most of a short layer: a strike two milliseconds long keeps its front.
+ const [attack, release] = [layer.attack ?? (layer.source === 'impulse' ? 0 : Math.min(0.002, seconds * 0.1)), layer.release ?? Math.min(0.01, seconds * 0.25)];
+ const drive = layer.drive ?? 0;
+ const push = 1 + drive * 14;
+ const pushed = Math.tanh(push);
+ // What is made ahead of the loop: a noise, or a recording played at its speed.
+ const noise = layer.source === 'noise' ? noiseBody(layer, count, rate, seed, pitch)
+ : layer.source === 'sample' ? recordingBody(recording!, count, rate, (layer.speed ?? 1) * pitch, layer.from ?? 0) : null;
+ // A spike: up in one sample and down over its width, as the air does in front of a bang.
+ const spike = layer.source === 'impulse' ? (layer.width ?? 0.0002) * rate : 0;
+ let [phase, bend] = [0, 0];
+
+ for (let n = 0; n < count; n++) {
+ const t = n / rate;
+ let v: number;
+ if (noise) v = noise[n]!;
+ else if (layer.source === 'impulse') {
+ const b = n / spike;
+ v = b < 10 ? (1 - b) * Math.exp(-b) : 0;
+ } else if (layer.source === 'modes') {
+ v = 0;
+ for (const [hz, loud, dies] of layer.modes!) {
+ const f = hz * pitch;
+ if (f < rate * 0.48) v += loud * Math.exp(-t / dies) * Math.sin(TAU * f * t);
+ }
+ } else {
+ let hz = curveAt(layer.freq, t, 440, true) * pitch;
+ if (layer.vibrato) hz *= Math.pow(2, (layer.vibrato.depth * Math.sin(TAU * layer.vibrato.rate * t)) / 12);
+ const step = Math.min(0.49, hz / rate);
+ phase += step;
+ if (phase >= 1) phase -= Math.floor(phase);
+ let at = phase;
+ if (layer.fm) {
+ bend += step * layer.fm.ratio;
+ if (bend >= 1) bend -= Math.floor(bend);
+ at = phase + (curveAt(layer.fm.index, t, 0, false) * Math.sin(TAU * bend)) / TAU;
+ at -= Math.floor(at);
+ }
+ switch (layer.source) {
+ case 'sine': v = Math.sin(TAU * at); break;
+ case 'triangle': v = 1 - 4 * Math.abs(at - 0.5); break;
+ case 'saw': v = 2 * at - 1 - (layer.fm ? 0 : polyBlep(at, step)); break;
+ default: {
+ const width = layer.width ?? 0.5;
+ v = at < width ? 1 : -1;
+ if (!layer.fm) v += polyBlep(at, step) - polyBlep((at - width + 1) % 1, step);
+ }
+ }
+ }
+ for (const f of filters) {
+ // The corner is read every 16 samples: often enough for a sweep, seldom enough to cost little. A noise struck
+ // at another pitch has no pitch of its own to move, so its filters move instead.
+ if ((n & 15) === 0) f.run.tune(curveAt(f.freq, t, 1000, true) * (noise ? pitch : 1));
+ v = f.run.run(v);
+ }
+ if (drive > 0) v = Math.tanh(v * push) / pushed;
+ let level = curveAt(layer.gain, t, 1, false);
+ if (layer.decay) {
+ const fast = Math.exp(-t / layer.decay);
+ level *= layer.tail ? fast * (1 - layer.tail.mix) + Math.exp(-t / layer.tail.decay) * layer.tail.mix : fast;
+ }
+ if (layer.tremolo) level *= 1 - layer.tremolo.depth * (0.5 + 0.5 * Math.sin(TAU * layer.tremolo.rate * t));
+ if (attack > 0 && t < attack) level *= t / attack;
+ const left = seconds - t;
+ if (release > 0 && left < release) level *= Math.max(0, left / release);
+ out[n] = v * level;
+ }
+ return out;
+}
+
+/** @p a and @p b laid over one another at every offset: what a sound becomes in a place whose answer to a click is @p b. */
+export function convolve(a: Float32Array, b: Float32Array, keep: number): Float32Array {
+ let size = 1;
+ while (size < a.length + b.length) size <<= 1;
+ const [ar, ai, br, bi] = [new Float64Array(size), new Float64Array(size), new Float64Array(size), new Float64Array(size)];
+ ar.set(a); br.set(b);
+ fft(ar, ai); fft(br, bi);
+ for (let k = 0; k < size; k++) {
+ const [re, im] = [ar[k]! * br[k]! - ai[k]! * bi[k]!, ar[k]! * bi[k]! + ai[k]! * br[k]!];
+ // Back the same way: the transform of the conjugate, conjugated and shared out.
+ ar[k] = re; ai[k] = -im;
+ }
+ fft(ar, ai);
+ const out = new Float32Array(keep);
+ for (let n = 0; n < keep; n++) out[n] = ar[n]! / size;
+ return out;
+}
+
+/**
+ * What a place answers to one click, for one ear. A room: noise in three bands that each die at their own rate, the
+ * top in half the time of the bottom, coming up over a hundredth of a second, with thirty-odd distinct first echoes
+ * ahead of it. Open ground: a few slaps off far walls, each duller than the last, and a long faint tail.
+ */
+export function placeResponse(rate: number, size: number, kind: 'room' | 'open', side: number): Float32Array {
+ const random = noiseOf(kind === 'room' ? 6923 + side * 977 : 32324 + side * 977);
+ const unit = (): number => random() * 0.5 + 0.5;
+ const seconds = kind === 'room' ? 0.35 + size * 2.4 : 0.6 + size * 2.6;
+ const count = Math.floor(rate * seconds);
+ const out = new Float32Array(count);
+ const banded = (low: number | null, high: number | null): Float32Array => {
+ const buf = new Float32Array(count);
+ const [hp, lp] = [low ? new Biquad('highpass', 0.6, rate) : null, high ? new Biquad('lowpass', 0.6, rate) : null];
+ hp?.tune(low!); lp?.tune(high!);
+ for (let n = 0; n < count; n++) { let v = random(); if (hp) v = hp.run(v); if (lp) v = lp.run(v); buf[n] = v; }
+ const level = rmsOf(buf) || 1;
+ for (let n = 0; n < count; n++) buf[n]! /= level;
+ return buf;
+ };
+ if (kind === 'room') {
+ // Seconds for each band to fall by sixty decibels.
+ const long = 0.25 + size * 1.5;
+ const bands: [Float32Array, number, number][] = [[banded(null, 420), 0.45, long], [banded(420, 3000), 1, long * 0.8], [banded(3000, null), 1.6, long * 0.4]];
+ for (let n = 0; n < count; n++) {
+ const t = n / rate;
+ const rise = 1 - Math.exp(-t / 0.014);
+ let v = 0;
+ for (const [buf, loud, falls] of bands) v += buf[n]! * loud * Math.pow(10, (-3 * t) / falls);
+ out[n] = v * rise;
+ }
+ const wash = rmsOf(out) * Math.sqrt(count);
+ const first = new Float32Array(count);
+ for (let e = 0; e < 34; e++) {
+ const t = (0.0048 + 0.088 * Math.pow((e + unit()) / 34, 1.5)) * (0.45 + size) * (side ? 1.07 : 1);
+ const at = Math.floor(t * rate);
+ const loud = (random() < 0 ? -1 : 1) * Math.exp(-t / 0.034) * (0.55 + 0.45 * unit());
+ // Later echoes have travelled further and are smeared wider.
+ const width = 1 + Math.floor(t * 60);
+ for (let n = 0; n < width && at + n < count; n++) first[at + n]! += (loud * (1 - n / width)) / Math.sqrt(width);
+ }
+ const firstLevel = rmsOf(first) * Math.sqrt(count) || 1;
+ for (let n = 0; n < count; n++) out[n]! += first[n]! * ((0.78 * wash) / firstLevel);
+ } else {
+ for (const [t, loud, milliseconds, top] of [[0.094, 0.5, 5, 5200], [0.151, 0.4, 8, 3800], [0.212, 0.31, 12, 2700], [0.289, 0.24, 16, 2000]] as const) {
+ const length = Math.floor((rate * milliseconds * 4) / 1000);
+ const [lp, hp] = [new Biquad('lowpass', 0.6, rate), new Biquad('highpass', 0.6, rate)];
+ lp.tune(top); hp.tune(180);
+ const slap = new Float32Array(length);
+ for (let n = 0; n < length; n++) slap[n] = hp.run(lp.run(random())) * Math.exp(-n / ((rate * milliseconds) / 1000)) * (1 - Math.exp(-n / (rate * 0.0006)));
+ const level = rmsOf(slap) * Math.sqrt(length) || 1;
+ const at = Math.floor(rate * t * (0.5 + size) * (1 + 0.1 * random() * 0.5));
+ const share = (loud * (0.45 + 0.55 * (side ? 1 - unit() : unit()))) / level;
+ for (let n = 0; n < length && at + n < count; n++) out[at + n]! += slap[n]! * share;
+ }
+ const slaps = rmsOf(out) * Math.sqrt(count) || 1;
+ const tail = banded(320, 2300);
+ const falls = 1 + size * 2;
+ let tailSquares = 0;
+ for (let n = 0; n < count; n++) {
+ const t = n / rate;
+ tail[n] = tail[n]! * Math.pow(10, (-3 * t) / falls) * (1 - Math.exp(-t / 0.11));
+ tailSquares += tail[n]! * tail[n]!;
+ }
+ const tailLevel = Math.sqrt(tailSquares) || 1;
+ for (let n = 0; n < count; n++) out[n]! += tail[n]! * ((0.5 * slaps) / tailLevel);
+ }
+ // Let down at its end, and of one energy whatever its size: `mix` then means the same in a closet and a hall.
+ const fade = Math.floor(count * 0.08);
+ for (let n = 0; n < fade; n++) out[count - 1 - n]! *= n / fade;
+ const energy = rmsOf(out) * Math.sqrt(count) || 1;
+ for (let n = 0; n < count; n++) out[n]! /= energy;
+ return out;
+}
+
+interface Strike { at: number; pitch: number; loud: number; pan: number; seed: number }
+
+/** When a layer is struck, and how: once, again by `repeat`, or many times at random by `scatter`. */
+function strikesOf(layer: SoundLayer, start: number, seed: number): Strike[] {
+ const pan = layer.pan ?? 0;
+ if (layer.scatter) {
+ const c = layer.scatter;
+ const random = noiseOf(seed + 4409);
+ const unit = (): number => random() * 0.5 + 0.5;
+ const [p0, p1] = c.pitch ?? [1, 1];
+ const [g0, g1] = c.gain ?? [1, 1];
+ return Array.from({ length: c.count }, (_, k) => {
+ const when = Math.pow(unit(), c.early ?? 1);
+ return {
+ at: start + c.over * when,
+ // Between two pitches by ratio, so there are as many strikes in each octave of the range.
+ pitch: p0 * Math.pow(p1 / p0, unit()),
+ loud: (g0 + (g1 - g0) * unit()) * (1 - (c.fade ?? 0) * when),
+ pan: Math.max(-1, Math.min(1, pan + (c.pan ?? 0) * random())),
+ seed: seed + k * 131,
+ };
+ }).sort((a, b) => a.at - b.at);
+ }
+ const r = layer.repeat;
+ const jitter = noiseOf(seed + 7919);
+ const out: Strike[] = [];
+ let [at, gap] = [start, r?.every ?? 0];
+ for (let k = 0; k < (r?.count ?? 1); k++) {
+ out.push({ at: at + (k > 0 && r?.jitter ? jitter() * r.jitter : 0), pitch: Math.pow(r?.pitch ?? 1, k), loud: Math.pow(r?.gain ?? 1, k), pan, seed: seed + k * 131 });
+ at += gap;
+ // A thing bouncing to rest: each gap shorter than the last.
+ gap *= r?.faster ?? 1;
+ }
+ return out;
+}
+
+/** Where and how an event is struck: what a group hands down to the layers in it. */
+interface Placement { offset: number; pitch: number; loud: number; pan: number; seed: number }
+
+/** How a variant of a layer strays from the layer as written. */
+interface Stray { pitch: number; loud: number; decay: number; late: number; seed: number }
+
+/**
+ * The samples a validated source makes. @p variant 0 is the sound as written; another is the same sound a little
+ * unlike it, as a second shot from the same gun is: other noise, and each layer's pitch, loudness, decay and timing
+ * off by up to the source's `vary`.
+ *
+ * @p at is for a sound played as a note: `pitch` times its written pitch, with `seed` for other noise, and `raw`
+ * leaving its level as the layers sum to, so that many notes keep their balance against one another.
+ */
+export function renderSound(source: SoundSource, variant = 0, at: { pitch?: number; seed?: number; raw?: boolean; given?: Readonly<Record<string, SoundRecording>> } = {}): RenderedSound {
+ const rate = source.rate ?? 44100;
+ const count = Math.max(1, Math.round(source.duration * rate));
+ // A loop is rendered a little long and its extra folded back over its start, so the end runs into the beginning.
+ const fold = source.loop ? Math.min(Math.round(0.08 * rate), Math.floor(count / 2)) : 0;
+ const total = count + fold;
+ const [left, right] = [new Float32Array(total), new Float32Array(total)];
+ const notes: string[] = [];
+ const reports: RenderedSound['layers'] = [];
+ let stereo = source.reverb !== undefined;
+
+ const vary = variant > 0 ? source.vary ?? 0.06 : 0;
+ const strayRandom = noiseOf(variant * 7717 + 13);
+ const strays = new Map<SoundLayer, Stray>();
+ const strayOf = (layer: SoundLayer): Stray => {
+ let s = strays.get(layer);
+ if (!s) {
+ s = vary > 0
+ ? { pitch: 1 + vary * strayRandom(), loud: 1 + vary * 2 * strayRandom(), decay: 1 + vary * 1.5 * strayRandom(), late: 1 + vary * strayRandom(), seed: variant * 1009 }
+ : { pitch: 1, loud: 1, decay: 1, late: 1, seed: 0 };
+ strays.set(layer, s);
+ }
+ return s;
+ };
+
+ /** One layer, or a group of them, struck where @p place says. Answers how loud it was and when it ended. */
+ const play = (layer: SoundLayer, index: number, where: string, place: Placement, top: boolean): { peak: number; last: number; heard: number; strikes: number } => {
+ const stray = strayOf(layer);
+ // A layer that comes after the start of its event comes a little sooner or later in another variant.
+ const start = place.offset + (layer.start ?? 0) * stray.late;
+ const seed = (layer.seed ?? index + 1) + place.seed + stray.seed;
+ if (layer.source === 'group') {
+ const strikes = strikesOf(layer, start, seed);
+ const loud = (typeof layer.gain === 'number' ? layer.gain : 1) * stray.loud;
+ let [peak, last, heard] = [0, start, 0];
+ for (const s of strikes) {
+ if (s.at * rate >= total) continue;
+ heard++;
+ layer.layers!.forEach((child, j) => {
+ if (child.mute) return;
+ const made = play(child, j, `${where} > layer ${j}${child.id ? ` "${child.id}"` : ''}`,
+ { offset: s.at, pitch: place.pitch * s.pitch, loud: place.loud * s.loud * loud, pan: Math.max(-1, Math.min(1, place.pan + s.pan)), seed: s.seed + j * 977 }, false);
+ peak = Math.max(peak, made.peak);
+ last = Math.max(last, made.last);
+ });
+ }
+ return { peak, last, heard, strikes: strikes.length };
+ }
+ const space = total / rate - start;
+ const recording = layer.source === 'sample' ? at.given?.[layer.file!] ?? null : null;
+ if (layer.source === 'sample' && !recording) throw new Error(`${where}: the recording ${layer.file} was not found`);
+ // A recording lasts as long as it lasts, at the speed it is played.
+ const whole = recording ? Math.max(0.001, (recording.channels[0]!.length / recording.rate - (layer.from ?? 0)) / ((layer.speed ?? 1) * place.pitch * stray.pitch)) : space;
+ const seconds = Math.min(layer.length ?? whole, space);
+ if (!(seconds > 0)) {
+ if (top) notes.push(`${where} starts at the end of the sound and is not heard`);
+ return { peak: 0, last: start, heard: 0, strikes: 0 };
+ }
+ if (top && layer.length !== undefined && layer.length > space + 1e-6 && !layer.repeat && !layer.scatter) notes.push(`${where} is cut short: it runs ${layer.length} s from ${Math.round(start * 1000) / 1000} s in a sound of ${source.duration} s`);
+ const wide = layer.source === 'noise' ? layer.wide ?? 0 : 0;
+ // The variant's own layer: the same in everything but how long it rings.
+ const made = stray.decay !== 1 && layer.decay
+ ? { ...layer, decay: layer.decay * stray.decay, ...(layer.tail ? { tail: { ...layer.tail, decay: layer.tail.decay * stray.decay } } : {}) }
+ : layer;
+ const strikes = strikesOf(layer, start, seed);
+ if (wide > 0 || place.pan !== 0 || strikes.some((s) => s.pan !== 0)) stereo = true;
+ let [peak, last, heard] = [0, start, 0];
+ for (const s of strikes) {
+ const from = Math.round(Math.max(0, s.at) * rate);
+ if (from >= total) continue;
+ heard++;
+ const length = Math.min(seconds, (total - from) / rate);
+ const pitch = s.pitch * place.pitch * stray.pitch;
+ const loud = s.loud * place.loud * stray.loud;
+ // Each striking has its own noise, as no two footsteps are the same grit.
+ const hit = strike(made, length, rate, pitch, s.seed, recording);
+ // The other ear's noise is another noise, by as much as the layer is wide.
+ const other = wide > 0 ? strike(made, length, rate, pitch, s.seed + 50021) : null;
+ // Equal power: a sound sent to one side is as loud as one in the middle.
+ const pan = Math.max(-1, Math.min(1, s.pan + place.pan));
+ const [gl, gr] = [Math.cos(((pan + 1) * Math.PI) / 4), Math.sin(((pan + 1) * Math.PI) / 4)];
+ for (let n = 0; n < hit.length && from + n < total; n++) {
+ const v = hit[n]! * loud;
+ left[from + n]! += v * gl;
+ right[from + n]! += (other ? v * (1 - wide) + other[n]! * loud * wide : v) * gr;
+ if (Math.abs(v) > peak) peak = Math.abs(v);
+ }
+ last = Math.max(last, Math.min(total / rate, s.at + hit.length / rate));
+ }
+ return { peak, last, heard, strikes: strikes.length };
+ };
+
+ source.layers.forEach((layer, index) => {
+ if (layer.mute) return;
+ const where = `layer ${index}${layer.id ? ` "${layer.id}"` : ''}`;
+ const made = play(layer, index, where, { offset: 0, pitch: at.pitch ?? 1, loud: 1, pan: 0, seed: at.seed ?? 0 }, true);
+ const start = layer.start ?? 0;
+ reports.push({
+ ...(layer.id ? { id: layer.id } : {}), source: layer.source, from: Math.round(start * 1000) / 1000, to: Math.round(made.last * 1000) / 1000,
+ peak: Math.round(made.peak * 1000) / 1000, ...(made.strikes > 1 ? { strikes: made.heard } : {}),
+ });
+ if (made.heard < made.strikes) notes.push(`${where}: ${made.strikes - made.heard} of its ${made.strikes} strikes fall past the end of the sound and are not heard`);
+ if (made.strikes > 0 && made.peak < 1e-4) notes.push(`${where} makes no sound: its level is nothing throughout`);
+ });
+
+ const channels = stereo ? [left, right] : [left.map((v, i) => (v + right[i]!) * Math.SQRT1_2)];
+ for (const [c, channel] of channels.entries()) {
+ for (const [key, type] of [['highpass', 'highpass'], ['lowpass', 'lowpass']] as const) {
+ if (source[key] === undefined) continue;
+ const filter = new Biquad(type, 0.7, rate);
+ filter.tune(source[key]!);
+ for (let n = 0; n < total; n++) channel[n] = filter.run(channel[n]!);
+ }
+ if (source.echo) {
+ const delay = Math.max(1, Math.round(source.echo.time * rate));
+ const [feedback, mix] = [source.echo.feedback ?? 0.35, source.echo.mix ?? 0.3];
+ const line = new Float32Array(delay);
+ for (let n = 0; n < total; n++) {
+ const heard = line[n % delay]!;
+ line[n % delay] = channel[n]! + heard * feedback;
+ channel[n] = channel[n]! + heard * mix;
+ }
+ }
+ if (source.reverb) {
+ // The two ears are answered a little differently, which is what makes a place wide.
+ const wet = convolve(channel, placeResponse(rate, source.reverb.size ?? 0.5, source.reverb.kind ?? 'room', c), total);
+ const mix = source.reverb.mix ?? 0.25;
+ for (let n = 0; n < total; n++) channel[n] = channel[n]! + wet[n]! * mix * 3;
+ }
+ }
+
+ const out = channels.map((channel) => {
+ const kept = channel.subarray(0, count).slice();
+ if (fold > 0) {
+ for (let n = 0; n < fold; n++) {
+ const w = n / fold;
+ kept[n] = kept[n]! * w + channel[count + n]! * (1 - w);
+ }
+ } else {
+ // A sound that stops on a sample that is not nothing clicks: the last three milliseconds are let down.
+ const tail = Math.min(count, Math.round(0.003 * rate));
+ for (let n = 0; n < tail; n++) kept[count - 1 - n]! *= n / tail;
+ }
+ return kept;
+ });
+
+ let peak = 0;
+ for (const channel of out) for (const v of channel) if (Math.abs(v) > peak) peak = Math.abs(v);
+ const target = source.gain ?? 0.9;
+ if (at.raw) {
+ // Left as it sums: whoever plays it as a note sets the level of the whole.
+ } else if (source.normalize !== false) {
+ if (peak > 1e-6) for (const channel of out) for (let n = 0; n < count; n++) channel[n]! *= target / peak;
+ else notes.push('the sound is silent: nothing in it reaches a level that can be heard');
+ peak = peak > 1e-6 ? target : 0;
+ } else {
+ for (const channel of out) for (let n = 0; n < count; n++) channel[n]! *= target / 0.9;
+ peak *= target / 0.9;
+ if (peak > 1) {
+ notes.push(`the layers sum to ${peak.toFixed(2)} times full, and what is past full is cut off flat: lower their gain, or leave normalize on`);
+ for (const channel of out) for (let n = 0; n < count; n++) channel[n] = Math.max(-1, Math.min(1, channel[n]!));
+ peak = 1;
+ }
+ }
+ let squares = 0;
+ for (const channel of out) for (const v of channel) squares += v * v;
+ return { rate, channels: out, seconds: count / rate, peak, rms: Math.sqrt(squares / (count * out.length)), layers: reports, notes };
+}
+
+/** The samples as a 16-bit PCM `.wav`, which every platform the engine runs on plays. */
+export function encodeWav(sound: { rate: number; channels: readonly Float32Array[] }): Uint8Array {
+ const [channels, frames] = [sound.channels.length, sound.channels[0]!.length];
+ const bytes = new Uint8Array(44 + frames * channels * 2);
+ const view = new DataView(bytes.buffer);
+ const text = (at: number, s: string): void => { for (let i = 0; i < s.length; i++) bytes[at + i] = s.charCodeAt(i); };
+ text(0, 'RIFF'); view.setUint32(4, 36 + frames * channels * 2, true); text(8, 'WAVE');
+ text(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, channels, true);
+ view.setUint32(24, sound.rate, true); view.setUint32(28, sound.rate * channels * 2, true); view.setUint16(32, channels * 2, true); view.setUint16(34, 16, true);
+ text(36, 'data'); view.setUint32(40, frames * channels * 2, true);
+ for (let n = 0; n < frames; n++) {
+ for (let c = 0; c < channels; c++) {
+ const v = Math.max(-1, Math.min(1, sound.channels[c]![n]!));
+ view.setInt16(44 + (n * channels + c) * 2, Math.round(v * 32767), true);
+ }
+ }
+ return bytes;
+}
+
+/** Every variant a source asks for, the first being the sound as written. */
+export function renderSoundVariants(source: SoundSource, given: Readonly<Record<string, SoundRecording>> = {}): RenderedSound[] {
+ return Array.from({ length: source.variants ?? 1 }, (_, k) => renderSound(source, k, { given }));
+}
+
+/** A recording as this file's sounds are held, so it can be drawn and measured as they are. */
+export function soundFromSamples(rate: number, channels: readonly Float32Array[]): RenderedSound {
+ const kept = channels.slice(0, 2).map((c) => Float32Array.from(c));
+ let [peak, squares] = [0, 0];
+ for (const channel of kept) for (const v of channel) { if (Math.abs(v) > peak) peak = Math.abs(v); squares += v * v; }
+ const frames = kept[0]?.length ?? 0;
+ return { rate, channels: kept, seconds: frames / rate, peak, rms: Math.sqrt(squares / Math.max(1, frames * kept.length)), layers: [], notes: [] };
+}
+
+/** A `.wav` read: PCM of 8, 16, 24 or 32 bits, or 32-bit floats. Throws on anything else, saying what it found. */
+export function decodeWav(bytes: Uint8Array): RenderedSound {
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const tag = (at: number): string => String.fromCharCode(bytes[at]!, bytes[at + 1]!, bytes[at + 2]!, bytes[at + 3]!);
+ if (bytes.length < 44 || tag(0) !== 'RIFF' || tag(8) !== 'WAVE') throw new Error('not a .wav: it does not begin RIFF....WAVE');
+ let [format, channels, rate, bits] = [0, 0, 0, 0];
+ let data: { at: number; size: number } | null = null;
+ for (let at = 12; at + 8 <= bytes.length;) {
+ const size = view.getUint32(at + 4, true);
+ if (tag(at) === 'fmt ') {
+ format = view.getUint16(at + 8, true);
+ channels = view.getUint16(at + 10, true);
+ rate = view.getUint32(at + 12, true);
+ bits = view.getUint16(at + 22, true);
+ // An extensible header says its real format further in.
+ if (format === 0xfffe && size >= 26) format = view.getUint16(at + 32, true);
+ } else if (tag(at) === 'data') data = { at: at + 8, size: Math.min(size, bytes.length - at - 8) };
+ at += 8 + size + (size & 1);
+ }
+ if (!data || !channels || !rate) throw new Error('a .wav with no format or no samples in it');
+ if (!((format === 1 && [8, 16, 24, 32].includes(bits)) || (format === 3 && bits === 32))) throw new Error(`a .wav of a kind not read here (format ${format}, ${bits} bits); PCM of 8 to 32 bits and 32-bit floats are`);
+ const step = bits / 8;
+ const frames = Math.floor(data.size / (step * channels));
+ const out = Array.from({ length: channels }, () => new Float32Array(frames));
+ for (let n = 0; n < frames; n++) {
+ for (let c = 0; c < channels; c++) {
+ const at = data.at + (n * channels + c) * step;
+ out[c]![n] = format === 3 ? view.getFloat32(at, true)
+ : bits === 8 ? (bytes[at]! - 128) / 128
+ : bits === 16 ? view.getInt16(at, true) / 32768
+ : bits === 24 ? ((bytes[at]! | (bytes[at + 1]! << 8) | (view.getInt8(at + 2) << 16))) / 8388608
+ : view.getInt32(at, true) / 2147483648;
+ }
+ }
+ return soundFromSamples(rate, out);
+}
diff --git a/sdk/src/sound/soundSource.ts b/sdk/src/sound/soundSource.ts
new file mode 100644
index 000000000..bc01c453f
--- /dev/null
+++ b/sdk/src/sound/soundSource.ts
@@ -0,0 +1,401 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file soundSource.ts — `.essound`: a sound as the layers that make it, what a model writes and edits, and what is wrong with one.
+ *
+ * A picture is layers of shapes and a model is steps; a sound effect is layers too. A gunshot is a crack of
+ * noise, a thump under it and a tail; a footstep is a thud and a scrape; a glass is a handful of ringing tones.
+ * Each layer is one source (a tone, a noise, or a struck body's ringing), shaped in time by an envelope and in
+ * colour by filters, and the layers are summed. What is saved is this description, and the `.wav` a game plays is
+ * made from it, so a sound is changed by changing a number and never by recording again.
+ *
+ * Nothing here is random that is not seeded: the same source is the same samples on every machine.
+ */
+
+export const SOUND_SOURCE_EXT = '.essound';
+export const SOUND_SOURCE_VERSION = 1;
+export const MAX_SOUND_SECONDS = 30;
+export const SOUND_RATES = [22050, 44100, 48000] as const;
+
+/** One value for the whole of a layer, or [[seconds, value], ...] from the layer's start: a pitch that falls, a filter that opens. */
+export type SoundCurve = number | readonly (readonly [number, number])[];
+
+export const SOUND_SOURCES = ['sine', 'triangle', 'saw', 'square', 'noise', 'modes', 'impulse', 'sample', 'group'] as const;
+export const MAX_SOUND_VARIANTS = 8;
+export type SoundSourceKind = (typeof SOUND_SOURCES)[number];
+export const SOUND_FILTERS = ['lowpass', 'highpass', 'bandpass', 'notch', 'peak'] as const;
+export const REVERB_KINDS = ['room', 'open'] as const;
+export const NOISE_COLORS = ['white', 'pink', 'brown'] as const;
+
+export interface SoundFilter {
+ type: (typeof SOUND_FILTERS)[number];
+ /** Hz, 20..20000. */
+ freq: SoundCurve;
+ /** How narrow: 0.7 is plain, 5 rings, 20 whistles. Default 0.7. */
+ q?: number;
+ /** peak: dB it lifts (or with a minus, cuts) round `freq`, -24..24: the note a barrel, a box or a room adds. */
+ gain?: number;
+}
+
+export interface SoundLayer {
+ id?: string;
+ source: SoundSourceKind;
+ /**
+ * group: the layers that make one event, struck together. A footstep is a thud, a scrape and two clicks, and four
+ * footsteps are that one group with `repeat`, each striking with its own grit, in place of the layers written out
+ * four times. The group's `start`, `gain`, `pan`, `repeat` and `scatter` are the event's; each layer in it keeps its
+ * own start, counted from the event's.
+ */
+ layers?: readonly SoundLayer[];
+ /** A tone's pitch in Hz; a curve glides between its points as the ear hears pitch. */
+ freq?: SoundCurve;
+ /** square: the share of each cycle it is high, 0.05..0.95. Default 0.5. impulse: seconds its one spike lasts, 0.00002..0.02; a shot's is 0.0002. */
+ width?: number;
+ /**
+ * noise: only what lies between these two Hz, brought back to the level of the whole. A real bang is several bands
+ * of noise that die at different rates, the high ones first, and this is one of them.
+ */
+ band?: readonly [number, number];
+ /** noise: how unlike its two sides are, 0..1. It makes the file stereo, and a wide crack fills the head where a narrow one sits in the middle. */
+ wide?: number;
+ /** noise: white is hiss, pink is rain, brown is a rumble. Default white. */
+ color?: (typeof NOISE_COLORS)[number];
+ /**
+ * sample: a recording in the project, by its path, played as a layer among the made ones: the real crack of a
+ * branch under made leaves, a voice, the one sound that will not come out of waves and noise. Everything a layer
+ * has shapes it as it shapes the rest: an envelope, filters, a drive, repeats, a scatter.
+ */
+ file?: string;
+ /** sample: how fast it is played, 0.25..4; 2 is an octave up and half as long. Default 1. */
+ speed?: number;
+ /** sample: seconds into the recording that it starts from. Default 0. */
+ from?: number;
+ /** modes: each [Hz, loudness, seconds to die away], the tones a struck thing rings with. */
+ modes?: readonly (readonly [number, number, number])[];
+ seed?: number;
+ /** Seconds into the sound that it begins. Default 0. */
+ start?: number;
+ /** Seconds it lasts. Default: to the end of the sound. */
+ length?: number;
+ /** Loudness, 1 being full; a curve shapes it over the layer. Default 1. */
+ gain?: SoundCurve;
+ /** Seconds to rise from nothing, and to fall to nothing at its end. Defaults 0.002 and 0.01, which only stop a click. */
+ attack?: number;
+ release?: number;
+ /** Dies away of itself: seconds to fall to about a third. A hit, a pluck, a drop. */
+ decay?: number;
+ /** With `decay`: a share `mix` of it dies more slowly, in `decay` seconds of its own. The body of a bang goes at once and its ring lingers. */
+ tail?: { decay: number; mix: number };
+ /** Wavers in pitch: `rate` times a second, `depth` semitones each way. */
+ vibrato?: { rate: number; depth: number };
+ /** Wavers in loudness: `rate` times a second, by `depth` 0..1. */
+ tremolo?: { rate: number; depth: number };
+ /** A second tone bending this one: at `ratio` times its pitch, by `index` (0 is none, 2 is brassy, 8 is a clang). Metal, bells, lasers. */
+ fm?: { ratio: number; index: SoundCurve };
+ /** In order, each working on what the one before left. */
+ filters?: readonly SoundFilter[];
+ /** Pushed into distortion, 0..1: grit, fuzz, a speaker torn. */
+ drive?: number;
+ /** -1 is left, 1 is right. Default 0. */
+ pan?: number;
+ /** The layer struck again: `count` times in all, `every` seconds apart, each `gain` times as loud and `pitch` times as high as the last, off the beat by up to `jitter` seconds. */
+ repeat?: { count: number; every: number; gain?: number; pitch?: number; jitter?: number; faster?: number };
+ /**
+ * The layer struck many times at random: `count` strikes within `over` seconds, crowded toward the start by
+ * `early` (1 is even, 2.3 is a crash), each at a pitch between the two of `pitch` times its own, as loud as between
+ * the two of `gain`, thrown to either side by up to `pan`, the later ones quieter by `fade`. Breaking glass is four
+ * hundred short rings scattered like this; so are gravel, rain, sparks and applause.
+ */
+ scatter?: { count: number; over: number; early?: number; pitch?: readonly [number, number]; gain?: readonly [number, number]; pan?: number; fade?: number };
+ /** Left out of the sound, kept in the source. */
+ mute?: boolean;
+}
+
+export interface SoundSource {
+ version?: number;
+ /** Seconds. */
+ duration: number;
+ /** Samples a second. Default 44100. */
+ rate?: number;
+ /** Its end runs into its start with no click, for an engine, a wind, a hum. */
+ loop?: boolean;
+ /**
+ * How many of it to make, 1..8, each a little unlike the others: other noise, and pitch, loudness, decay and timing
+ * off by up to `vary`. A game that plays the same file for every shot or step is heard as a machine however good the
+ * file; with variants a sound event is written beside them that plays one after another without repeating.
+ */
+ variants?: number;
+ /** How far a variant strays, 0..0.3. Default 0.06. */
+ vary?: number;
+ /** A recording to make it like, by project path. It is shown above the sound in every reply, drawn the same way to the same scale, and measured the same way. Nothing is taken from it. */
+ reference?: string;
+ layers: readonly SoundLayer[];
+ /** Over the whole sound, after the layers are summed: */
+ highpass?: number;
+ lowpass?: number;
+ /** A repeat of the whole: `time` seconds later, `feedback` 0..0.95 of each into the next, `mix` 0..1 of it in the sound. */
+ echo?: { time: number; feedback?: number; mix?: number };
+ /**
+ * A place round it: `size` 0..1 from a closet to a hall, `mix` 0..1 of it in the sound. `kind` "room" is walls
+ * close by, with first echoes and a wash whose top dies before its bottom; "open" is a street or a yard: a few
+ * distinct slaps off far walls and a long thin tail.
+ */
+ reverb?: { size?: number; mix?: number; kind?: (typeof REVERB_KINDS)[number] };
+ /** Loudness of the whole. With `normalize` it is how loud the loudest moment is, 1 being full. Default 0.9. */
+ gain?: number;
+ /** false leaves the levels as the layers sum to. Default true: the loudest moment is brought to `gain`. */
+ normalize?: boolean;
+}
+
+const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
+const between = (v: unknown, lo: number, hi: number): boolean => isNum(v) && v >= lo && v <= hi;
+
+function curveProblem(v: unknown, lo: number, hi: number, what: string): string | null {
+ if (isNum(v)) return v >= lo && v <= hi ? null : `${what} must be ${lo}..${hi}`;
+ if (!Array.isArray(v) || v.length < 2) return `${what} must be a number, or two or more [seconds, value]`;
+ let last = -Infinity;
+ for (const p of v) {
+ if (!Array.isArray(p) || p.length !== 2 || !isNum(p[0]) || !isNum(p[1])) return `${what} must be [seconds, value] pairs`;
+ if (p[0] < 0) return `${what}: a time is seconds from the layer's start, none below 0`;
+ if (p[0] <= last) return `${what}: its times must rise`;
+ if (p[1] < lo || p[1] > hi) return `${what}: each value must be ${lo}..${hi}`;
+ last = p[0];
+ }
+ return null;
+}
+
+const LAYER_FIELDS = ['id', 'source', 'freq', 'width', 'band', 'wide', 'color', 'modes', 'file', 'speed', 'from', 'seed', 'start', 'length', 'gain', 'attack', 'release', 'decay', 'tail', 'vibrato', 'tremolo', 'fm', 'filters', 'drive', 'pan', 'repeat', 'scatter', 'mute'];
+
+const GROUP_FIELDS = ['id', 'source', 'layers', 'start', 'gain', 'pan', 'repeat', 'scatter', 'mute'];
+
+function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>, duration: number, depth = 0): void {
+ const fail = (what: string): never => { throw new Error(`${where}: ${what}`); };
+ if (typeof l !== 'object' || l === null || Array.isArray(l)) fail('must be an object');
+ if (l.source === 'group') {
+ for (const key of Object.keys(l)) if (!GROUP_FIELDS.includes(key)) fail(`a group takes ${GROUP_FIELDS.join(', ')}; "${key}" belongs on the layers in it`);
+ if (depth >= 3) fail('groups go three deep and no further');
+ if (!Array.isArray(l.layers) || l.layers.length === 0) fail('a group needs `layers`: one or more');
+ if (l.gain !== undefined && !between(l.gain, 0, 4)) fail('a group\'s gain is one number, 0..4');
+ } else if (l.layers !== undefined) fail('`layers` goes with source "group"');
+ if (l.source !== 'group') for (const key of Object.keys(l)) if (!LAYER_FIELDS.includes(key)) fail(`unknown field "${key}"; a layer takes ${LAYER_FIELDS.join(', ')}`);
+ if (l.id !== undefined) {
+ if (typeof l.id !== 'string' || !l.id) fail('id must be a name');
+ if (ids.has(l.id as string)) fail(`the id "${String(l.id)}" is already used`);
+ ids.add(l.id as string);
+ }
+ if (!SOUND_SOURCES.includes(l.source as SoundSourceKind)) fail(`source ${JSON.stringify(l.source)} must be one of ${SOUND_SOURCES.join(', ')}`);
+ const tone = l.source !== 'noise' && l.source !== 'modes' && l.source !== 'impulse' && l.source !== 'group' && l.source !== 'sample';
+ if (l.source === 'sample') {
+ if (typeof l.file !== 'string' || !/\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i.test(l.file)) fail('a sample needs file: a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)');
+ if (l.speed !== undefined && !between(l.speed, 0.25, 4)) fail('speed must be 0.25..4');
+ if (l.from !== undefined && !between(l.from, 0, 600)) fail('from must be seconds into the recording, 0 or more');
+ } else for (const key of ['file', 'speed', 'from']) if (l[key] !== undefined) fail(`${key} goes with source "sample"`);
+ if (tone) {
+ if (l.freq === undefined) fail(`a ${String(l.source)} needs freq, its pitch in Hz`);
+ const bad = curveProblem(l.freq, 10, 20000, 'freq');
+ if (bad) fail(bad);
+ } else if (l.freq !== undefined) fail(`freq is a tone's pitch; a ${String(l.source)} has none (give noise its colour with filters, and modes their own Hz)`);
+ if (l.width !== undefined) {
+ if (l.source === 'square') { if (!between(l.width, 0.05, 0.95)) fail('a square\'s width is the share of a cycle it is high, 0.05..0.95'); }
+ else if (l.source === 'impulse') { if (!between(l.width, 0.00002, 0.02)) fail('an impulse\'s width is seconds, 0.00002..0.02'); }
+ else fail('width is a square\'s or an impulse\'s');
+ }
+ if (l.band !== undefined) {
+ const b = l.band as unknown[];
+ if (l.source !== 'noise') fail('band is a noise\'s: [low Hz, high Hz]');
+ if (!Array.isArray(b) || b.length !== 2 || !between(b[0], 20, 20000) || !between(b[1], 20, 20000) || (b[0] as number) >= (b[1] as number)) fail('band must be [low Hz, high Hz], 20..20000, the first below the second');
+ }
+ if (l.wide !== undefined && !(l.source === 'noise' && between(l.wide, 0, 1))) fail('wide is a noise\'s, 0..1');
+ if (l.tail !== undefined) {
+ const t = l.tail as Record<string, unknown> | null;
+ if (l.decay === undefined) fail('tail is the slow part of a decay: give decay too');
+ if (typeof t !== 'object' || t === null || !(isNum(t.decay) && t.decay > 0) || !between(t.mix, 0, 1) || Object.keys(t).length !== 2) fail('tail must be { decay: seconds above 0, mix: 0..1 }');
+ }
+ if (l.color !== undefined && !(l.source === 'noise' && NOISE_COLORS.includes(l.color as never))) fail(`color is a noise's: ${NOISE_COLORS.join(', ')}`);
+ if (l.source === 'modes') {
+ const modes = l.modes;
+ if (!Array.isArray(modes) || modes.length === 0 || modes.length > 64) fail('modes needs `modes`: 1 to 64 of [Hz, loudness, seconds to die away]');
+ for (const m of modes as unknown[]) {
+ if (!Array.isArray(m) || m.length !== 3 || !between(m[0], 10, 20000) || !between(m[1], 0, 4) || !between(m[2], 0.001, MAX_SOUND_SECONDS)) fail('each mode must be [Hz 10..20000, loudness 0..4, seconds above 0]');
+ }
+ } else if (l.modes !== undefined) fail('`modes` goes with source "modes"');
+ if (l.seed !== undefined && !Number.isInteger(l.seed)) fail('seed must be a whole number');
+ if (l.start !== undefined && !between(l.start, 0, duration)) fail(`start must be 0..${duration}, inside the sound`);
+ if (l.length !== undefined && !(isNum(l.length) && l.length > 0)) fail('length must be above 0');
+ if (l.gain !== undefined && l.source !== 'group') { const bad = curveProblem(l.gain, 0, 4, 'gain'); if (bad) fail(bad); }
+ for (const key of ['attack', 'release']) if (l[key] !== undefined && !between(l[key], 0, MAX_SOUND_SECONDS)) fail(`${key} must be seconds, 0 or more`);
+ if (l.decay !== undefined && !(isNum(l.decay) && l.decay > 0)) fail('decay must be seconds above 0');
+ const wobble = (key: string, deepest: number): void => {
+ const w = l[key] as Record<string, unknown> | undefined;
+ if (w === undefined) return;
+ if (typeof w !== 'object' || w === null || !between(w.rate, 0.01, 2000) || !between(w.depth, 0, deepest) || Object.keys(w).length !== 2) fail(`${key} must be { rate: times a second, depth: 0..${deepest} }`);
+ };
+ wobble('vibrato', 24);
+ wobble('tremolo', 1);
+ if (l.fm !== undefined) {
+ const fm = l.fm as Record<string, unknown> | null;
+ if (!tone) fail('fm bends a tone; noise and modes have no pitch to bend');
+ if (typeof fm !== 'object' || fm === null || !between(fm.ratio, 0.01, 64) || Object.keys(fm).some((k) => k !== 'ratio' && k !== 'index')) fail('fm must be { ratio: 0.01..64, index }');
+ const bad = curveProblem(fm!.index, 0, 64, 'fm.index');
+ if (bad) fail(bad);
+ }
+ if (l.filters !== undefined) {
+ if (!Array.isArray(l.filters) || l.filters.length > 8) fail('filters must be a list of up to 8');
+ (l.filters as Record<string, unknown>[]).forEach((f, i) => {
+ if (typeof f !== 'object' || f === null) fail(`filter ${i} must be { type, freq, q? }`);
+ for (const key of Object.keys(f)) if (!['type', 'freq', 'q', 'gain'].includes(key)) fail(`filter ${i} has unknown "${key}"; it takes type, freq, q, gain`);
+ if (f.type === 'peak' ? !between(f.gain, -24, 24) : f.gain !== undefined) fail(`filter ${i}: gain is a peak's, in dB, -24..24`);
+ if (!SOUND_FILTERS.includes(f.type as never)) fail(`filter ${i}: type must be one of ${SOUND_FILTERS.join(', ')}`);
+ const bad = curveProblem(f.freq, 20, 20000, `filter ${i}: freq`);
+ if (bad) fail(bad);
+ if (f.q !== undefined && !between(f.q, 0.1, 40)) fail(`filter ${i}: q must be 0.1..40`);
+ });
+ }
+ if (l.drive !== undefined && !between(l.drive, 0, 1)) fail('drive must be 0..1');
+ if (l.pan !== undefined && !between(l.pan, -1, 1)) fail('pan must be -1..1');
+ if (l.repeat !== undefined) {
+ const r = l.repeat as Record<string, unknown> | null;
+ if (typeof r !== 'object' || r === null) fail('repeat must be { count, every, gain?, pitch?, jitter? }');
+ for (const key of Object.keys(r!)) if (!['count', 'every', 'gain', 'pitch', 'jitter', 'faster'].includes(key)) fail(`repeat has unknown "${key}"; it takes count, every, gain, pitch, jitter, faster`);
+ if (r!.faster !== undefined && !between(r!.faster, 0.2, 1)) fail('repeat.faster is how much shorter each gap is than the last, 0.2..1: a thing bouncing to rest');
+ if (l.scatter !== undefined) fail('a layer is struck by repeat or by scatter, not both');
+ if (!Number.isInteger(r!.count) || (r!.count as number) < 2 || (r!.count as number) > 200) fail('repeat.count must be a whole number, 2..200');
+ if (!(isNum(r!.every) && (r!.every as number) > 0)) fail('repeat.every must be seconds above 0');
+ if (r!.gain !== undefined && !between(r!.gain, 0, 2)) fail('repeat.gain must be 0..2');
+ if (r!.pitch !== undefined && !between(r!.pitch, 0.25, 4)) fail('repeat.pitch must be 0.25..4');
+ if (r!.jitter !== undefined && !between(r!.jitter, 0, 1)) fail('repeat.jitter must be 0..1 seconds');
+ }
+ if (l.scatter !== undefined) {
+ const c = l.scatter as Record<string, unknown> | null;
+ if (typeof c !== 'object' || c === null) fail('scatter must be { count, over, early?, pitch?, gain?, pan?, fade? }');
+ for (const key of Object.keys(c!)) if (!['count', 'over', 'early', 'pitch', 'gain', 'pan', 'fade'].includes(key)) fail(`scatter has unknown "${key}"; it takes count, over, early, pitch, gain, pan, fade`);
+ if (!Number.isInteger(c!.count) || (c!.count as number) < 2 || (c!.count as number) > 2000) fail('scatter.count must be a whole number, 2..2000');
+ if (!(isNum(c!.over) && (c!.over as number) > 0)) fail('scatter.over must be seconds above 0');
+ if (c!.early !== undefined && !between(c!.early, 0.3, 6)) fail('scatter.early must be 0.3..6');
+ const range = (key: string, lo: number, hi: number): void => {
+ const v = c![key] as unknown[] | undefined;
+ if (v === undefined) return;
+ if (!Array.isArray(v) || v.length !== 2 || !between(v[0], lo, hi) || !between(v[1], lo, hi) || (v[0] as number) > (v[1] as number)) fail(`scatter.${key} must be [low, high], ${lo}..${hi}`);
+ };
+ range('pitch', 0.1, 10);
+ range('gain', 0, 2);
+ for (const key of ['pan', 'fade']) if (c![key] !== undefined && !between(c![key], 0, 1)) fail(`scatter.${key} must be 0..1`);
+ }
+ if (l.mute !== undefined && typeof l.mute !== 'boolean') fail('mute must be true or false');
+ if (l.source === 'group') (l.layers as Record<string, unknown>[]).forEach((c, i) => checkLayer(c, `${where} > layer ${i}${c?.id ? ` "${String(c.id)}"` : ''}`, ids, duration, depth + 1));
+}
+
+const SOURCE_FIELDS = ['version', 'duration', 'rate', 'loop', 'variants', 'vary', 'reference', 'layers', 'highpass', 'lowpass', 'echo', 'reverb', 'gain', 'normalize'];
+
+/** The recordings a sound's layers play, each once. */
+export function soundSampleFiles(source: Pick<SoundSource, 'layers'>): string[] {
+ const files = new Set<string>();
+ const walk = (layers: readonly SoundLayer[]): void => { for (const l of layers) { if (l.source === 'sample' && l.file) files.add(l.file); if (l.layers) walk(l.layers); } };
+ walk(source.layers);
+ return [...files];
+}
+
+/** The source if it is well formed; otherwise throws, naming the layer and the field. */
+export function validateSoundSource(raw: unknown): SoundSource {
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) throw new Error('a sound source must be { duration, layers }');
+ const s = raw as Record<string, unknown>;
+ for (const key of Object.keys(s)) if (!SOURCE_FIELDS.includes(key)) throw new Error(`unknown field "${key}"; a sound has ${SOURCE_FIELDS.join(', ')}`);
+ if (s.version !== undefined && s.version !== SOUND_SOURCE_VERSION) throw new Error(`version ${String(s.version)} is not one this editor reads (${SOUND_SOURCE_VERSION})`);
+ if (!(isNum(s.duration) && s.duration > 0 && s.duration <= MAX_SOUND_SECONDS)) throw new Error(`duration must be seconds, above 0 and up to ${MAX_SOUND_SECONDS}`);
+ if (s.rate !== undefined && !SOUND_RATES.includes(s.rate as never)) throw new Error(`rate must be one of ${SOUND_RATES.join(', ')}`);
+ if (s.loop !== undefined && typeof s.loop !== 'boolean') throw new Error('loop must be true or false');
+ if (s.variants !== undefined && !(Number.isInteger(s.variants) && (s.variants as number) >= 1 && (s.variants as number) <= MAX_SOUND_VARIANTS)) throw new Error(`variants must be a whole number, 1..${MAX_SOUND_VARIANTS}`);
+ if (s.vary !== undefined && !between(s.vary, 0, 0.3)) throw new Error('vary must be 0..0.3');
+ if (s.reference !== undefined && !(typeof s.reference === 'string' && /\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i.test(s.reference))) throw new Error('reference must be a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)');
+ if (s.normalize !== undefined && typeof s.normalize !== 'boolean') throw new Error('normalize must be true or false');
+ if (s.gain !== undefined && !between(s.gain, 0, 1)) throw new Error('gain must be 0..1');
+ for (const key of ['highpass', 'lowpass']) if (s[key] !== undefined && !between(s[key], 20, 20000)) throw new Error(`${key} must be Hz, 20..20000`);
+ if (s.echo !== undefined) {
+ const e = s.echo as Record<string, unknown> | null;
+ if (typeof e !== 'object' || e === null || !between(e.time, 0.01, 2)) throw new Error('echo must be { time: 0.01..2 seconds, feedback?, mix? }');
+ for (const key of Object.keys(e)) if (!['time', 'feedback', 'mix'].includes(key)) throw new Error(`echo has unknown "${key}"; it takes time, feedback, mix`);
+ if (e.feedback !== undefined && !between(e.feedback, 0, 0.95)) throw new Error('echo.feedback must be 0..0.95');
+ if (e.mix !== undefined && !between(e.mix, 0, 1)) throw new Error('echo.mix must be 0..1');
+ }
+ if (s.reverb !== undefined) {
+ const r = s.reverb as Record<string, unknown> | null;
+ if (typeof r !== 'object' || r === null) throw new Error('reverb must be { size?, mix?, kind? }');
+ for (const key of Object.keys(r)) if (!['size', 'mix', 'kind'].includes(key)) throw new Error(`reverb has unknown "${key}"; it takes size, mix, kind`);
+ if (r.kind !== undefined && !REVERB_KINDS.includes(r.kind as never)) throw new Error(`reverb.kind must be one of ${REVERB_KINDS.join(', ')}`);
+ for (const key of ['size', 'mix']) if (r[key] !== undefined && !between(r[key], 0, 1)) throw new Error(`reverb.${key} must be 0..1`);
+ }
+ if (!Array.isArray(s.layers) || s.layers.length === 0) throw new Error('layers must be a list of one or more');
+ if (s.layers.length > 64) throw new Error('a sound has up to 64 layers');
+ const ids = new Set<string>();
+ (s.layers as Record<string, unknown>[]).forEach((l, i) => checkLayer(l, `layer ${i}${l?.id ? ` "${String(l.id)}"` : ''}`, ids, s.duration as number));
+ return { version: SOUND_SOURCE_VERSION, ...(s as unknown as SoundSource) };
+}
+
+export type SoundEdit =
+ | { op: 'set'; layer: string | number; fields: Record<string, unknown> }
+ | { op: 'insert'; layer: SoundLayer; before?: string | number; after?: string | number; into?: string }
+ | { op: 'remove'; layer: string | number }
+ | { op: 'settings'; fields: Partial<Omit<SoundSource, 'layers' | 'version'>> };
+
+/** The source with @p edits applied, in order. A `null` field removes it. Refuses without changing anything. */
+export function applySoundEdits(source: SoundSource, edits: readonly SoundEdit[]): SoundSource {
+ const next = JSON.parse(JSON.stringify(source)) as SoundSource & { layers: (SoundLayer & Record<string, unknown>)[] };
+ type Row = SoundLayer & Record<string, unknown>;
+ const allIds = (list: readonly Row[]): string[] => list.flatMap((l) => [...(l.id ? [l.id] : []), ...allIds((l.layers ?? []) as Row[])]);
+ /** The list a layer is in and its place there: by index among the top layers, or by id anywhere, in a group too. */
+ const locate = (ref: string | number): { list: Row[]; index: number } => {
+ const within = (list: Row[]): { list: Row[]; index: number } | null => {
+ for (let i = 0; i < list.length; i++) {
+ if (list[i]!.id === ref) return { list, index: i };
+ const hit = list[i]!.layers ? within(list[i]!.layers as Row[]) : null;
+ if (hit) return hit;
+ }
+ return null;
+ };
+ const top = next.layers as Row[];
+ const hit = typeof ref === 'number' ? (Number.isInteger(ref) && ref >= 0 && ref < top.length ? { list: top, index: ref } : null) : within(top);
+ if (!hit) throw new Error(`no layer ${JSON.stringify(ref)}; ${top.length} layers, ids: ${allIds(top).join(', ') || '(none)'}`);
+ return hit;
+ };
+ for (const edit of edits) {
+ switch (edit?.op) {
+ case 'set': {
+ const at = locate(edit.layer);
+ const layer = at.list[at.index]!;
+ for (const [key, value] of Object.entries(edit.fields ?? {})) {
+ if (value === null) delete layer[key];
+ else layer[key] = value;
+ }
+ break;
+ }
+ case 'insert': {
+ // Beside the layer named, in whichever list that is; or, with `into`, at the end of a group.
+ if (edit.into !== undefined) {
+ const group = locate(edit.into);
+ const row = group.list[group.index]!;
+ if (row.source !== 'group') throw new Error(`${JSON.stringify(edit.into)} is not a group`);
+ (row.layers as Row[]).push(edit.layer as Row);
+ } else if (edit.before !== undefined || edit.after !== undefined) {
+ const at = locate((edit.before ?? edit.after)!);
+ at.list.splice(at.index + (edit.before !== undefined ? 0 : 1), 0, edit.layer as Row);
+ } else (next.layers as Row[]).push(edit.layer as Row);
+ break;
+ }
+ case 'remove': {
+ const at = locate(edit.layer);
+ at.list.splice(at.index, 1);
+ break;
+ }
+ case 'settings':
+ for (const [key, value] of Object.entries(edit.fields ?? {})) {
+ if (key === 'layers' || key === 'version') throw new Error(`settings does not take ${key}; use set, insert and remove for layers`);
+ if (value === null) delete (next as unknown as Record<string, unknown>)[key];
+ else (next as unknown as Record<string, unknown>)[key] = value;
+ }
+ break;
+ default:
+ throw new Error(`an edit has op ${JSON.stringify((edit as { op?: unknown })?.op)}; there are set, insert, remove, settings`);
+ }
+ }
+ return validateSoundSource(next);
+}
diff --git a/sdk/src/sound/soundWorker.ts b/sdk/src/sound/soundWorker.ts
new file mode 100644
index 000000000..9a6277733
--- /dev/null
+++ b/sdk/src/sound/soundWorker.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file soundWorker.ts
+ * @brief A sound or a piece of music made from its source, and the thread that does it away from the game's.
+ *
+ * @details A piece of music is seconds of work for a minute of sound: made on the game's thread it is a frame that long. The same
+ * function runs here, on a job-pool worker, and in place where a host has no workers.
+ */
+import { validateMusicSource, musicSampleFiles, type MusicSource } from './musicSource';
+import { renderMusic } from './musicRender';
+import { decodeWav, encodeWav, renderSound, type SoundRecording } from './soundRender';
+import { soundSampleFiles, validateSoundSource, type SoundSource } from './soundSource';
+
+export interface SoundJob {
+ /** The text of the `.essound` or `.esmusic`. */
+ source: string;
+ /** Its project path, which says which of the two it is. */
+ path: string;
+ /** The recordings it plays, by project path, as the bytes of their files. */
+ files: Record<string, ArrayBuffer>;
+}
+
+const isMusic = (path: string): boolean => /\.esmusic(\?|$)/i.test(path);
+
+function parsed(job: Pick<SoundJob, 'source' | 'path'>): { music: MusicSource } | { sound: SoundSource } {
+ let raw: unknown;
+ try { raw = JSON.parse(job.source); } catch { throw new Error(`${job.path} is not JSON`); }
+ return isMusic(job.path) ? { music: validateMusicSource(raw) } : { sound: validateSoundSource(raw) };
+}
+
+/** The recordings a source plays, by project path: a sampled instrument's notes, a sample layer's file. */
+export function soundNeeds(source: string, path: string): string[] {
+ const made = parsed({ source, path });
+ if ('sound' in made) return soundSampleFiles(made.sound);
+ const files = new Set(musicSampleFiles(made.music));
+ for (const instrument of Object.values(made.music.instruments)) for (const file of soundSampleFiles({ layers: instrument.layers ?? [] })) files.add(file);
+ return [...files];
+}
+
+/** The clip of a source, as the bytes of a 16-bit `.wav`. A sound with variants is its first: the others are the sound event's. */
+export function makeSound(job: SoundJob): ArrayBuffer {
+ const given: Record<string, SoundRecording> = {};
+ for (const [file, bytes] of Object.entries(job.files)) {
+ if (!/\.wav$/i.test(file)) throw new Error(`${job.path} plays ${file}, and a recipe plays .wav recordings only`);
+ const read = decodeWav(new Uint8Array(bytes));
+ given[file] = { rate: read.rate, channels: read.channels };
+ }
+ const made = parsed(job);
+ const out = 'sound' in made ? renderSound(made.sound, 0, { given }) : renderMusic(made.music, given);
+ const wav = encodeWav({ rate: out.rate, channels: out.channels });
+ return (wav.byteOffset === 0 && wav.byteLength === wav.buffer.byteLength ? wav.buffer : wav.slice().buffer) as ArrayBuffer;
+}
+
+interface WorkerScope {
+ document?: unknown;
+ onmessage: ((e: { data: SoundJob & { id: number } }) => void) | null;
+ postMessage(m: unknown, transfer?: ArrayBuffer[]): void;
+}
+declare const self: WorkerScope | undefined;
+
+if (typeof self !== 'undefined' && typeof self.document === 'undefined') {
+ const scope = self;
+ scope.onmessage = (e) => {
+ const job = e.data;
+ try {
+ const wav = makeSound(job);
+ scope.postMessage({ id: job.id, result: wav }, [wav]);
+ } catch (err) {
+ scope.postMessage({ id: job.id, error: err instanceof Error ? err.message : String(err) });
+ }
+ };
+}
diff --git a/sdk/src/sound/soundWorkerBundle.generated.ts b/sdk/src/sound/soundWorkerBundle.generated.ts
new file mode 100644
index 000000000..961510ee2
--- /dev/null
+++ b/sdk/src/sound/soundWorkerBundle.generated.ts
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+// Generated by sdk/scripts/build-worker.mjs from src/sound/soundWorker.ts: do not edit.
+/** The sound worker's script: what the worker that makes audio recipes is started from. */
+export const SOUND_WORKER_SOURCE = "(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=[22050,44100,48e3],n=[`sine`,`triangle`,`saw`,`square`,`noise`,`modes`,`impulse`,`sample`,`group`],r=[`lowpass`,`highpass`,`bandpass`,`notch`,`peak`],i=[`room`,`open`],a=[`white`,`pink`,`brown`],o=e=>typeof e==`number`&&Number.isFinite(e),s=(e,t,n)=>o(e)&&e>=t&&e<=n;function c(e,t,n,r){if(o(e))return e>=t&&e<=n?null:`${r} must be ${t}..${n}`;if(!Array.isArray(e)||e.length<2)return`${r} must be a number, or two or more [seconds, value]`;let i=-1/0;for(let a of e){if(!Array.isArray(a)||a.length!==2||!o(a[0])||!o(a[1]))return`${r} must be [seconds, value] pairs`;if(a[0]<0)return`${r}: a time is seconds from the layer's start, none below 0`;if(a[0]<=i)return`${r}: its times must rise`;if(a[1]<t||a[1]>n)return`${r}: each value must be ${t}..${n}`;i=a[0]}return null}let l=`id.source.freq.width.band.wide.color.modes.file.speed.from.seed.start.length.gain.attack.release.decay.tail.vibrato.tremolo.fm.filters.drive.pan.repeat.scatter.mute`.split(`.`),u=[`id`,`source`,`layers`,`start`,`gain`,`pan`,`repeat`,`scatter`,`mute`];function d(e,t,i,f,p=0){let m=e=>{throw Error(`${t}: ${e}`)};if((typeof e!=`object`||!e||Array.isArray(e))&&m(`must be an object`),e.source===`group`){for(let t of Object.keys(e))u.includes(t)||m(`a group takes ${u.join(`, `)}; \"${t}\" belongs on the layers in it`);p>=3&&m(`groups go three deep and no further`),(!Array.isArray(e.layers)||e.layers.length===0)&&m(\"a group needs `layers`: one or more\"),e.gain!==void 0&&!s(e.gain,0,4)&&m(`a group's gain is one number, 0..4`)}else e.layers!==void 0&&m('`layers` goes with source \"group\"');if(e.source!==`group`)for(let t of Object.keys(e))l.includes(t)||m(`unknown field \"${t}\"; a layer takes ${l.join(`, `)}`);e.id!==void 0&&((typeof e.id!=`string`||!e.id)&&m(`id must be a name`),i.has(e.id)&&m(`the id \"${String(e.id)}\" is already used`),i.add(e.id)),n.includes(e.source)||m(`source ${JSON.stringify(e.source)} must be one of ${n.join(`, `)}`);let h=e.source!==`noise`&&e.source!==`modes`&&e.source!==`impulse`&&e.source!==`group`&&e.source!==`sample`;if(e.source===`sample`)(typeof e.file!=`string`||!/\\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i.test(e.file))&&m(`a sample needs file: a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)`),e.speed!==void 0&&!s(e.speed,.25,4)&&m(`speed must be 0.25..4`),e.from!==void 0&&!s(e.from,0,600)&&m(`from must be seconds into the recording, 0 or more`);else for(let t of[`file`,`speed`,`from`])e[t]!==void 0&&m(`${t} goes with source \"sample\"`);if(h){e.freq===void 0&&m(`a ${String(e.source)} needs freq, its pitch in Hz`);let t=c(e.freq,10,2e4,`freq`);t&&m(t)}else e.freq!==void 0&&m(`freq is a tone's pitch; a ${String(e.source)} has none (give noise its colour with filters, and modes their own Hz)`);if(e.width!==void 0&&(e.source===`square`?s(e.width,.05,.95)||m(`a square's width is the share of a cycle it is high, 0.05..0.95`):e.source===`impulse`?s(e.width,2e-5,.02)||m(`an impulse's width is seconds, 0.00002..0.02`):m(`width is a square's or an impulse's`)),e.band!==void 0){let t=e.band;e.source!==`noise`&&m(`band is a noise's: [low Hz, high Hz]`),(!Array.isArray(t)||t.length!==2||!s(t[0],20,2e4)||!s(t[1],20,2e4)||t[0]>=t[1])&&m(`band must be [low Hz, high Hz], 20..20000, the first below the second`)}if(e.wide!==void 0&&!(e.source===`noise`&&s(e.wide,0,1))&&m(`wide is a noise's, 0..1`),e.tail!==void 0){let t=e.tail;e.decay===void 0&&m(`tail is the slow part of a decay: give decay too`),(typeof t!=`object`||!t||!(o(t.decay)&&t.decay>0)||!s(t.mix,0,1)||Object.keys(t).length!==2)&&m(`tail must be { decay: seconds above 0, mix: 0..1 }`)}if(e.color!==void 0&&!(e.source===`noise`&&a.includes(e.color))&&m(`color is a noise's: ${a.join(`, `)}`),e.source===`modes`){let t=e.modes;(!Array.isArray(t)||t.length===0||t.length>64)&&m(\"modes needs `modes`: 1 to 64 of [Hz, loudness, seconds to die away]\");for(let e of t)(!Array.isArray(e)||e.length!==3||!s(e[0],10,2e4)||!s(e[1],0,4)||!s(e[2],.001,30))&&m(`each mode must be [Hz 10..20000, loudness 0..4, seconds above 0]`)}else e.modes!==void 0&&m('`modes` goes with source \"modes\"');if(e.seed!==void 0&&!Number.isInteger(e.seed)&&m(`seed must be a whole number`),e.start!==void 0&&!s(e.start,0,f)&&m(`start must be 0..${f}, inside the sound`),e.length!==void 0&&!(o(e.length)&&e.length>0)&&m(`length must be above 0`),e.gain!==void 0&&e.source!==`group`){let t=c(e.gain,0,4,`gain`);t&&m(t)}for(let t of[`attack`,`release`])e[t]!==void 0&&!s(e[t],0,30)&&m(`${t} must be seconds, 0 or more`);e.decay!==void 0&&!(o(e.decay)&&e.decay>0)&&m(`decay must be seconds above 0`);let g=(t,n)=>{let r=e[t];r!==void 0&&(typeof r!=`object`||!r||!s(r.rate,.01,2e3)||!s(r.depth,0,n)||Object.keys(r).length!==2)&&m(`${t} must be { rate: times a second, depth: 0..${n} }`)};if(g(`vibrato`,24),g(`tremolo`,1),e.fm!==void 0){let t=e.fm;h||m(`fm bends a tone; noise and modes have no pitch to bend`),(typeof t!=`object`||!t||!s(t.ratio,.01,64)||Object.keys(t).some(e=>e!==`ratio`&&e!==`index`))&&m(`fm must be { ratio: 0.01..64, index }`);let n=c(t.index,0,64,`fm.index`);n&&m(n)}if(e.filters!==void 0&&((!Array.isArray(e.filters)||e.filters.length>8)&&m(`filters must be a list of up to 8`),e.filters.forEach((e,t)=>{(typeof e!=`object`||!e)&&m(`filter ${t} must be { type, freq, q? }`);for(let n of Object.keys(e))[`type`,`freq`,`q`,`gain`].includes(n)||m(`filter ${t} has unknown \"${n}\"; it takes type, freq, q, gain`);(e.type===`peak`?!s(e.gain,-24,24):e.gain!==void 0)&&m(`filter ${t}: gain is a peak's, in dB, -24..24`),r.includes(e.type)||m(`filter ${t}: type must be one of ${r.join(`, `)}`);let n=c(e.freq,20,2e4,`filter ${t}: freq`);n&&m(n),e.q!==void 0&&!s(e.q,.1,40)&&m(`filter ${t}: q must be 0.1..40`)})),e.drive!==void 0&&!s(e.drive,0,1)&&m(`drive must be 0..1`),e.pan!==void 0&&!s(e.pan,-1,1)&&m(`pan must be -1..1`),e.repeat!==void 0){let t=e.repeat;(typeof t!=`object`||!t)&&m(`repeat must be { count, every, gain?, pitch?, jitter? }`);for(let e of Object.keys(t))[`count`,`every`,`gain`,`pitch`,`jitter`,`faster`].includes(e)||m(`repeat has unknown \"${e}\"; it takes count, every, gain, pitch, jitter, faster`);t.faster!==void 0&&!s(t.faster,.2,1)&&m(`repeat.faster is how much shorter each gap is than the last, 0.2..1: a thing bouncing to rest`),e.scatter!==void 0&&m(`a layer is struck by repeat or by scatter, not both`),(!Number.isInteger(t.count)||t.count<2||t.count>200)&&m(`repeat.count must be a whole number, 2..200`),o(t.every)&&t.every>0||m(`repeat.every must be seconds above 0`),t.gain!==void 0&&!s(t.gain,0,2)&&m(`repeat.gain must be 0..2`),t.pitch!==void 0&&!s(t.pitch,.25,4)&&m(`repeat.pitch must be 0.25..4`),t.jitter!==void 0&&!s(t.jitter,0,1)&&m(`repeat.jitter must be 0..1 seconds`)}if(e.scatter!==void 0){let t=e.scatter;(typeof t!=`object`||!t)&&m(`scatter must be { count, over, early?, pitch?, gain?, pan?, fade? }`);for(let e of Object.keys(t))[`count`,`over`,`early`,`pitch`,`gain`,`pan`,`fade`].includes(e)||m(`scatter has unknown \"${e}\"; it takes count, over, early, pitch, gain, pan, fade`);(!Number.isInteger(t.count)||t.count<2||t.count>2e3)&&m(`scatter.count must be a whole number, 2..2000`),o(t.over)&&t.over>0||m(`scatter.over must be seconds above 0`),t.early!==void 0&&!s(t.early,.3,6)&&m(`scatter.early must be 0.3..6`);let n=(e,n,r)=>{let i=t[e];i!==void 0&&(!Array.isArray(i)||i.length!==2||!s(i[0],n,r)||!s(i[1],n,r)||i[0]>i[1])&&m(`scatter.${e} must be [low, high], ${n}..${r}`)};n(`pitch`,.1,10),n(`gain`,0,2);for(let e of[`pan`,`fade`])t[e]!==void 0&&!s(t[e],0,1)&&m(`scatter.${e} must be 0..1`)}e.mute!==void 0&&typeof e.mute!=`boolean`&&m(`mute must be true or false`),e.source===`group`&&e.layers.forEach((e,n)=>d(e,`${t} > layer ${n}${e?.id?` \"${String(e.id)}\"`:``}`,i,f,p+1))}let f=[`version`,`duration`,`rate`,`loop`,`variants`,`vary`,`reference`,`layers`,`highpass`,`lowpass`,`echo`,`reverb`,`gain`,`normalize`];function p(e){let t=new Set,n=e=>{for(let r of e)r.source===`sample`&&r.file&&t.add(r.file),r.layers&&n(r.layers)};return n(e.layers),[...t]}function m(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`a sound source must be { duration, layers }`);let n=e;for(let e of Object.keys(n))if(!f.includes(e))throw Error(`unknown field \"${e}\"; a sound has ${f.join(`, `)}`);if(n.version!==void 0&&n.version!==1)throw Error(`version ${String(n.version)} is not one this editor reads (1)`);if(!(o(n.duration)&&n.duration>0&&n.duration<=30))throw Error(`duration must be seconds, above 0 and up to 30`);if(n.rate!==void 0&&!t.includes(n.rate))throw Error(`rate must be one of ${t.join(`, `)}`);if(n.loop!==void 0&&typeof n.loop!=`boolean`)throw Error(`loop must be true or false`);if(n.variants!==void 0&&!(Number.isInteger(n.variants)&&n.variants>=1&&n.variants<=8))throw Error(`variants must be a whole number, 1..8`);if(n.vary!==void 0&&!s(n.vary,0,.3))throw Error(`vary must be 0..0.3`);if(n.reference!==void 0&&!(typeof n.reference==`string`&&/\\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i.test(n.reference)))throw Error(`reference must be a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)`);if(n.normalize!==void 0&&typeof n.normalize!=`boolean`)throw Error(`normalize must be true or false`);if(n.gain!==void 0&&!s(n.gain,0,1))throw Error(`gain must be 0..1`);for(let e of[`highpass`,`lowpass`])if(n[e]!==void 0&&!s(n[e],20,2e4))throw Error(`${e} must be Hz, 20..20000`);if(n.echo!==void 0){let e=n.echo;if(typeof e!=`object`||!e||!s(e.time,.01,2))throw Error(`echo must be { time: 0.01..2 seconds, feedback?, mix? }`);for(let t of Object.keys(e))if(![`time`,`feedback`,`mix`].includes(t))throw Error(`echo has unknown \"${t}\"; it takes time, feedback, mix`);if(e.feedback!==void 0&&!s(e.feedback,0,.95))throw Error(`echo.feedback must be 0..0.95`);if(e.mix!==void 0&&!s(e.mix,0,1))throw Error(`echo.mix must be 0..1`)}if(n.reverb!==void 0){let e=n.reverb;if(typeof e!=`object`||!e)throw Error(`reverb must be { size?, mix?, kind? }`);for(let t of Object.keys(e))if(![`size`,`mix`,`kind`].includes(t))throw Error(`reverb has unknown \"${t}\"; it takes size, mix, kind`);if(e.kind!==void 0&&!i.includes(e.kind))throw Error(`reverb.kind must be one of ${i.join(`, `)}`);for(let t of[`size`,`mix`])if(e[t]!==void 0&&!s(e[t],0,1))throw Error(`reverb.${t} must be 0..1`)}if(!Array.isArray(n.layers)||n.layers.length===0)throw Error(`layers must be a list of one or more`);if(n.layers.length>64)throw Error(`a sound has up to 64 layers`);let r=new Set;return n.layers.forEach((e,t)=>d(e,`layer ${t}${e?.id?` \"${String(e.id)}\"`:``}`,r,n.duration)),{version:1,...n}}let h={pentatonic:[0,2,4,7,9],pentatonicMinor:[0,3,5,7,10],gong:[0,2,4,7,9],shang:[0,2,5,7,10],jue:[0,3,5,8,10],zhi:[0,2,5,7,9],yu:[0,3,5,7,10],major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],harmonic:[0,2,3,5,7,8,11]},g={C:0,\"C#\":1,Db:1,D:2,\"D#\":3,Eb:3,E:4,F:5,\"F#\":6,Gb:6,G:7,\"G#\":8,Ab:8,A:9,\"A#\":10,Bb:10,B:11},_=[`soft`,`normal`,`loud`],v=e=>typeof e==`number`&&Number.isFinite(e),y=(e,t,n)=>v(e)&&e>=t&&e<=n,b=e=>typeof e==`object`&&!!e&&!Array.isArray(e),x=/^[A-Za-z][A-Za-z0-9_-]{0,31}$/,S=e=>g[e];function C(e){if(typeof e==`number`)return Number.isInteger(e)&&e>=0&&e<=127?e:null;let t=typeof e==`string`?/^([A-G](?:#|b)?)(-?\\d)$/.exec(e):null;if(!t||g[t[1]]===void 0)return null;let n=g[t[1]]+12*(Number(t[2])+1);return n>=0&&n<=127?n:null}function w(e){return[...new Set(Object.values(e.instruments).flatMap(e=>(e.samples??[]).map(e=>e.file)))]}let T=e=>e===`!`?1.3:e===`?`?.6:1;function E(e){let t=/^([#b]?)([1-7])([',]*)$/.exec(e);if(!t)return null;let n=0;for(let e of t[3])n+=e===`'`?1:-1;return{degree:Number(t[2]),alter:t[1]===`#`?1:t[1]===`b`?-1:0,octave:n}}function D(e,t,n,r,i=7){let a=[],o=e.split(`|`).map(e=>e.trim());if(o[o.length-1]===``&&o.pop(),o.length!==t)throw Error(`${r} has ${o.length} bar${o.length===1?``:`s`} between its | marks; the pattern is ${t}`);return o.forEach((e,t)=>{let o=e.replace(/\\[([^\\]]*)\\]/g,(e,t)=>`[${t.trim().split(/\\s+/).join(`+`)}]`).split(/\\s+/).filter(e=>e!==``);if(o.length!==n)throw Error(`${r}, bar ${t+1} has ${o.length} steps; a bar here is ${n}. Write \".\" for a silent step and \"-\" for one that holds the note before`);for(let e of o){let n=e.endsWith(`!`)||e.endsWith(`?`)?e.slice(-1):``,o=n?e.slice(0,-1):e;if(o===`.`)a.push({kind:`rest`});else if(o===`-`)a.push({kind:`hold`});else if(o===`x`)a.push({kind:`hit`,loud:T(n)});else{let s=(o.startsWith(`[`)&&o.endsWith(`]`)?o.slice(1,-1).split(`+`):[o]).map(E);if(s.length===0||s.length>6||s.some(e=>e===null))throw Error(`${r}, bar ${t+1}: \"${e.replace(/\\+/g,` `)}\" is not a step. A step is . (silence), - (hold), x (a drum), a degree 1..7 with ' or , for octaves and # or b before it, or [1 3 5] for up to six at once`);let c=s.find(e=>e.degree>i);if(c)throw Error(`${r}, bar ${t+1}: degree ${c.degree} is not in this scale, which has ${i} notes: its degrees are 1..${i}, and the next octave begins again at 1'`);a.push({kind:`notes`,loud:T(n),notes:s})}}}),a}let O=[`version`,`tempo`,`beats`,`key`,`scale`,`swing`,`humanize`,`seed`,`instruments`,`patterns`,`song`,`loop`,`intro`,`fadeIn`,`fadeOut`,`stems`,`reverb`,`rubato`,`master`,`gain`,`rate`],k=[`layers`,`samples`,`attack`,`gain`,`pan`,`octave`,`follow`,`release`,`reverb`,`legato`,`pedal`,`lowcut`,`highcut`,`scale`],A=/\\.(wav|ogg|mp3|flac|m4a|aac|webm)$/i;function j(e,t){if(!Array.isArray(e)||e.length===0||e.length>256)throw Error(`${t}: samples must be 1..256 of { file, note }`);e.forEach((e,n)=>{let r=`${t}, sample ${n+1}`;if(!b(e))throw Error(`${r} must be { file, note }`);for(let t of Object.keys(e))if(![`file`,`note`,`low`,`high`,`loop`,`dynamic`,`tune`,`gain`,`cutoff`].includes(t))throw Error(`${r} has unknown \"${t}\"; a sample has file, note, low, high, loop, dynamic, tune, gain, cutoff`);if(e.gain!==void 0&&!y(e.gain,.01,4))throw Error(`${r}: gain must be 0.01..4, 1 being the recording as it is`);if(e.cutoff!==void 0&&!y(e.cutoff,200,2e4))throw Error(`${r}: cutoff must be Hz, 200..20000`);if(e.dynamic!==void 0&&!_.includes(e.dynamic))throw Error(`${r}: dynamic must be one of ${_.join(`, `)}`);if(e.tune!==void 0&&!y(e.tune,-100,100))throw Error(`${r}: tune must be hundredths of a semitone, -100..100`);if(typeof e.file!=`string`||!A.test(e.file))throw Error(`${r}: file must be a project path to a recording (.wav, .ogg, .mp3, .flac, .m4a)`);if(C(e.note)===null)throw Error(`${r}: note must be the note recorded, as \"C4\", \"F#3\" or \"Bb2\" (C4 is middle C), or its number 0..127`);for(let t of[`low`,`high`])if(e[t]!==void 0&&C(e[t])===null)throw Error(`${r}: ${t} must be a note, as \"C4\"`);if(e.low!==void 0&&e.high!==void 0&&C(e.low)>C(e.high))throw Error(`${r}: low is above high`);let i=e.loop;if(i!==void 0&&typeof i!=`boolean`&&!(Array.isArray(i)&&i.length===2&&v(i[0])&&v(i[1])&&i[0]>=0&&i[1]>i[0]+5e-4))throw Error(`${r}: loop must be true, or [from, to] in seconds with to past from`)})}let M=[`bars`,`div`,`chords`,`dynamics`,`tracks`];function N(e){let t=(e.beats??4)*60/e.tempo;return e.song.reduce((n,r)=>n+e.patterns[typeof r==`string`?r:r.pattern].bars*t,0)}function P(e){if(!b(e))throw Error(`a music source must be { tempo, key, instruments, patterns, song }`);let t=e;for(let e of Object.keys(t))if(!O.includes(e))throw Error(`unknown field \"${e}\"; music has ${O.join(`, `)}`);if(t.version!==void 0&&t.version!==1)throw Error(`version ${String(t.version)} is not one this editor reads (1)`);if(!y(t.tempo,30,300))throw Error(`tempo must be beats a minute, 30..300`);if(t.beats!==void 0&&!(Number.isInteger(t.beats)&&y(t.beats,2,12)))throw Error(`beats must be a whole number to the bar, 2..12`);if(typeof t.key!=`string`||g[t.key]===void 0)throw Error(`key must be a tonic: ${Object.keys(g).join(`, `)}`);if(t.scale!==void 0&&!(typeof t.scale==`string`&&t.scale in h))throw Error(`scale must be one of ${Object.keys(h).join(`, `)}`);if(t.swing!==void 0&&!y(t.swing,0,.6))throw Error(`swing must be 0..0.6`);if(t.humanize!==void 0&&!y(t.humanize,0,1))throw Error(`humanize must be 0..1`);if(t.seed!==void 0&&!Number.isInteger(t.seed))throw Error(`seed must be a whole number`);if(t.gain!==void 0&&!y(t.gain,0,1))throw Error(`gain must be 0..1`);if(t.rate!==void 0&&![22050,44100,48e3].includes(t.rate))throw Error(`rate must be one of 22050, 44100, 48000`);for(let e of[`loop`,`stems`])if(t[e]!==void 0&&typeof t[e]!=`boolean`)throw Error(`${e} must be true or false`);if(t.reverb!==void 0){if(!b(t.reverb))throw Error(`reverb must be { size?, mix? }`);for(let e of Object.keys(t.reverb))if(![`size`,`mix`].includes(e))throw Error(`reverb has unknown \"${e}\"; it takes size, mix`);if(t.reverb.size!==void 0&&!y(t.reverb.size,0,1))throw Error(`reverb.size must be 0..1`);if(t.reverb.mix!==void 0&&!y(t.reverb.mix,0,1))throw Error(`reverb.mix must be 0..1`)}if(t.rubato!==void 0&&!y(t.rubato,0,1))throw Error(`rubato must be 0..1`);if(t.master!==void 0){if(!b(t.master))throw Error(`master must be { compress?, low?, high? }`);for(let e of Object.keys(t.master))if(![`compress`,`low`,`high`].includes(e))throw Error(`master has unknown \"${e}\"; it takes compress, low, high`);if(t.master.compress!==void 0&&!y(t.master.compress,0,1))throw Error(`master.compress must be 0..1`);for(let e of[`low`,`high`])if(t.master[e]!==void 0&&!y(t.master[e],-12,12))throw Error(`master.${e} must be decibels, -12..12`)}if(!b(t.instruments)||Object.keys(t.instruments).length===0)throw Error(`instruments must be { name: { layers: [...] } }, at least one`);if(Object.keys(t.instruments).length>16)throw Error(`at most 16 instruments`);for(let[e,n]of Object.entries(t.instruments)){let t=`instrument \"${e}\"`;if(!x.test(e))throw Error(`${t}: a name is a letter, then letters, digits, _ or -`);if(!b(n))throw Error(`${t} must be { layers: [...] }`);for(let e of Object.keys(n))if(!k.includes(e))throw Error(`${t} has unknown \"${e}\"; an instrument has ${k.join(`, `)}`);if(n.layers===void 0==(n.samples===void 0))throw Error(`${t} needs layers (a made sound) or samples (recordings), one of the two`);if(n.samples!==void 0)j(n.samples,t);else try{m({duration:8,layers:n.layers})}catch(e){throw Error(`${t}: ${e.message}`)}if(n.attack!==void 0&&!(n.samples!==void 0&&y(n.attack,0,2)))throw Error(`${t}: attack is for samples, seconds 0..2; layers have their own`);if(n.gain!==void 0&&!y(n.gain,0,4))throw Error(`${t}: gain must be 0..4`);if(n.pan!==void 0&&!y(n.pan,-1,1))throw Error(`${t}: pan must be -1..1`);if(n.octave!==void 0&&!(Number.isInteger(n.octave)&&y(n.octave,-4,4)))throw Error(`${t}: octave must be a whole number, -4..4`);if(n.follow!==void 0&&typeof n.follow!=`boolean`)throw Error(`${t}: follow must be true or false`);if(n.release!==void 0&&!y(n.release,0,4))throw Error(`${t}: release must be seconds, 0..4`);if(n.reverb!==void 0&&!y(n.reverb,0,1))throw Error(`${t}: reverb must be 0..1`);if(n.legato!==void 0&&typeof n.legato!=`boolean`&&!y(n.legato,.01,.5))throw Error(`${t}: legato must be true, or the seconds one note takes to come in under the last, 0.01..0.5`);if(n.pedal!==void 0&&typeof n.pedal!=`boolean`)throw Error(`${t}: pedal must be true or false`);if(n.scale!==void 0){if(!(typeof n.scale==`string`&&n.scale in h))throw Error(`${t}: scale must be one of ${Object.keys(h).join(`, `)}`);if(n.follow)throw Error(`${t}: an instrument that follows the chords counts its degrees from them, in the piece's scale; a scale of its own is for a line that does not follow`)}if(n.lowcut!==void 0&&!y(n.lowcut,20,2e3))throw Error(`${t}: lowcut must be Hz, 20..2000`);if(n.highcut!==void 0&&!y(n.highcut,500,2e4))throw Error(`${t}: highcut must be Hz, 500..20000`)}let n=t.beats??4,r=h[t.scale??`minor`].length;if(!b(t.patterns)||Object.keys(t.patterns).length===0)throw Error(`patterns must be { name: { bars, tracks: { instrument: \"steps\" } } }, at least one`);for(let[e,i]of Object.entries(t.patterns)){let a=`pattern \"${e}\"`;if(!x.test(e))throw Error(`${a}: a name is a letter, then letters, digits, _ or -`);if(!b(i))throw Error(`${a} must be { bars, tracks }`);for(let e of Object.keys(i))if(!M.includes(e))throw Error(`${a} has unknown \"${e}\"; a pattern has ${M.join(`, `)}`);if(!(Number.isInteger(i.bars)&&y(i.bars,1,32)))throw Error(`${a}: bars must be a whole number, 1..32`);if(i.div!==void 0&&!(Number.isInteger(i.div)&&y(i.div,1,8)))throw Error(`${a}: div must be whole steps to a beat, 1..8`);if(i.chords!==void 0&&(!Array.isArray(i.chords)||i.chords.length===0||i.chords.length>i.bars||i.chords.some(e=>!(Number.isInteger(e)&&e>=1&&e<=r))))throw Error(`${a}: chords must be the degree of each bar's root, 1..${r}, no more of them than bars`);if(i.dynamics!==void 0){if(!b(i.dynamics))throw Error(`${a}: dynamics must be { instrument or \"all\": [how loud each bar begins] }`);for(let[e,n]of Object.entries(i.dynamics)){if(e!==`all`&&!(e in t.instruments))throw Error(`${a}: dynamics for \"${e}\", which is not an instrument; the instruments are ${Object.keys(t.instruments).join(`, `)}, or \"all\"`);if(!Array.isArray(n)||n.length===0||n.length>i.bars+1||n.some(e=>!y(e,.1,2)))throw Error(`${a}: dynamics for \"${e}\" must be how loud each bar begins, 0.1..2 with 1 as written, one for each of its ${String(i.bars)} bars and at most one more for where the last ends`)}}if(!b(i.tracks)||Object.keys(i.tracks).length===0)throw Error(`${a}: tracks must be { instrument: \"steps\" }, at least one`);for(let[e,r]of Object.entries(i.tracks)){if(!(e in t.instruments))throw Error(`${a} has a track for \"${e}\", which is not an instrument; the instruments are ${Object.keys(t.instruments).join(`, `)}`);if(typeof r!=`string`)throw Error(`${a}, track \"${e}\" must be a line of steps`);D(r,i.bars,n*(i.div??4),`${a}, track \"${e}\"`,h[t.instruments[e].scale??t.scale??`minor`].length)}}if(!Array.isArray(t.song)||t.song.length===0||t.song.length>64)throw Error(`song must be the patterns in order, 1..64 of them`);t.song.forEach((e,n)=>{let r=typeof e==`string`?e:b(e)?e.pattern:void 0;if(typeof r!=`string`||!(r in t.patterns))throw Error(`song part ${n+1}: \"${String(r)}\" is not a pattern; the patterns are ${Object.keys(t.patterns).join(`, `)}`);if(b(e)){for(let t of Object.keys(e))if(![`pattern`,`without`,`only`].includes(t))throw Error(`song part ${n+1} has unknown \"${t}\"; it takes pattern, without, only`);if(e.without!==void 0&&e.only!==void 0)throw Error(`song part ${n+1}: give without or only, not both`);for(let r of[`without`,`only`]){let i=e[r];if(i!==void 0&&(!Array.isArray(i)||i.some(e=>typeof e!=`string`||!(e in t.instruments))))throw Error(`song part ${n+1}: ${r} must be a list of instruments (${Object.keys(t.instruments).join(`, `)})`)}}});let i=t,a=N(i);if(t.intro!==void 0){if(t.loop===!1)throw Error(`intro is the part of a loop that is heard once; a piece with loop false is heard once whole and has none`);if(!(Number.isInteger(t.intro)&&t.intro>=1&&t.intro<t.song.length))throw Error(`intro must be how many of the song's first parts are heard once: a whole number from 1, leaving at least one part to go round (the song has ${t.song.length})`)}for(let e of[`fadeIn`,`fadeOut`])if(t[e]!==void 0){if(t.loop!==!1)throw Error(`${e} is for a piece that ends (loop: false). A loop comes round to its start with no gap, and a fade written into it would be heard every time round: the game fades it, playBGM(url, { fadeIn }) to start it and stopBGM(seconds) to end it`);if(!(v(t[e])&&t[e]>0&&t[e]<=a))throw Error(`${e} must be seconds, above 0 and no longer than the piece (${Math.round(a*10)/10} s)`)}if(a>240)throw Error(`the song lasts ${Math.round(a)} s; at most 240`);return i}function F(e,t){let n=e.length;for(let r=1,i=0;r<n;r++){let a=n>>1;for(;i&a;a>>=1)i^=a;if(i^=a,r<i){let n=e[r];e[r]=e[i],e[i]=n;let a=t[r];t[r]=t[i],t[i]=a}}for(let r=2;r<=n;r<<=1){let i=-2*Math.PI/r,a=Math.cos(i),o=Math.sin(i),s=r>>1;for(let i=0;i<n;i+=r){let n=1,r=0;for(let c=0;c<s;c++){let l=i+c,u=l+s,d=e[u]*n-t[u]*r,f=e[u]*r+t[u]*n;e[u]=e[l]-d,t[u]=t[l]-f,e[l]=e[l]+d,t[l]=t[l]+f;let p=n*a-r*o;r=n*o+r*a,n=p}}}}let I=Math.PI*2,L=1/Math.sqrt(3);function R(e,t,n,r){if(e===void 0)return n;if(typeof e==`number`)return e;if(t<=e[0][0])return e[0][1];for(let n=1;n<e.length;n++){let[i,a]=e[n];if(t>i)continue;let[o,s]=e[n-1],c=(t-o)/(i-o);return r&&s>0&&a>0?s*(a/s)**+c:s+(a-s)*c}return e[e.length-1][1]}function z(e){let t=e*2654435761+2654435769>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/2147483648-1}}function B(e,t){if(e<t){let n=e/t;return n+n-n*n-1}if(e>1-t){let n=(e-1)/t;return n*n+n+n+1}return 0}var V=class{constructor(e,t,n,r=0){this.type=e,this.q=t,this.rate=n,this.gainDb=r,this.x1=0,this.x2=0,this.y1=0,this.y2=0,this.b0=1,this.b1=0,this.b2=0,this.a1=0,this.a2=0,this.last=-1}tune(e){let t=Math.max(20,Math.min(this.rate*.45,e));if(Math.abs(t-this.last)<.01)return;this.last=t;let n=I*t/this.rate,[r,i]=[Math.cos(n),Math.sin(n)/(2*this.q)],a=1+i,o=-2*r,s=1-i,c,l,u;switch(this.type){case`lowpass`:[c,l,u]=[(1-r)/2,1-r,(1-r)/2];break;case`highpass`:[c,l,u]=[(1+r)/2,-(1+r),(1+r)/2];break;case`bandpass`:[c,l,u]=[i,0,-i];break;case`peak`:{let e=10**(this.gainDb/40);[c,l,u]=[1+i*e,-2*r,1-i*e],[a,o,s]=[1+i/e,-2*r,1-i/e];break}default:[c,l,u]=[1,-2*r,1]}[this.b0,this.b1,this.b2,this.a1,this.a2]=[c/a,l/a,u/a,o/a,s/a]}run(e){let t=this.b0*e+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;return this.x2=this.x1,this.x1=e,this.y2=this.y1,this.y1=t,t}};let H=e=>{let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/Math.max(1,e.length))};function ee(e,t,n,r,i){let a=z(r),o=new Float32Array(t),[s,c,l,u]=[0,0,0,0];for(let n=0;n<t;n++){let t=a();e.color===`pink`?(s=.99765*s+t*.099046,c=.963*c+t*.2965164,l=.57*l+t*1.0526913,o[n]=(s+c+l+t*.1848)*.25):e.color===`brown`?(u=(u+t*.02)/1.02,o[n]=u*3.5):o[n]=t}if(e.band){let[r,s]=[new V(`highpass`,.7,n),new V(`lowpass`,.7,n)];r.tune(e.band[0]*i),s.tune(e.band[1]*i);for(let e=0;e<64;e++)s.run(r.run(a()));for(let e=0;e<t;e++)o[e]=s.run(r.run(o[e]));let c=H(o);if(c>1e-9)for(let e=0;e<t;e++)o[e]*=L/c}return o}function te(e,t,n,r,i){let a=new Float32Array(t),[o,s]=[e.channels[0],e.channels[1]??e.channels[0]],c=r*e.rate/n,l=i*e.rate;for(let e=0;e<t;e++){let t=l+e*c,n=Math.floor(t);if(n+1>=o.length)break;let r=t-n;a[e]=((o[n]+s[n])*(1-r)+(o[n+1]+s[n+1])*r)/2}return a}function U(e,t,n,r,i,a=null){let o=Math.max(1,Math.round(t*n)),s=new Float32Array(o),c=(e.filters??[]).map(e=>({run:new V(e.type,e.q??.7,n,e.gain??0),freq:e.freq})),[l,u]=[e.attack??(e.source===`impulse`?0:Math.min(.002,t*.1)),e.release??Math.min(.01,t*.25)],d=e.drive??0,f=1+d*14,p=Math.tanh(f),m=e.source===`noise`?ee(e,o,n,i,r):e.source===`sample`?te(a,o,n,(e.speed??1)*r,e.from??0):null,h=e.source===`impulse`?(e.width??2e-4)*n:0,[g,_]=[0,0];for(let i=0;i<o;i++){let a=i/n,o;if(m)o=m[i];else if(e.source===`impulse`){let e=i/h;o=e<10?(1-e)*Math.exp(-e):0}else if(e.source===`modes`){o=0;for(let[t,i,s]of e.modes){let e=t*r;e<n*.48&&(o+=i*Math.exp(-a/s)*Math.sin(I*e*a))}}else{let t=R(e.freq,a,440,!0)*r;e.vibrato&&(t*=2**(e.vibrato.depth*Math.sin(I*e.vibrato.rate*a)/12));let i=Math.min(.49,t/n);g+=i,g>=1&&(g-=Math.floor(g));let s=g;switch(e.fm&&(_+=i*e.fm.ratio,_>=1&&(_-=Math.floor(_)),s=g+R(e.fm.index,a,0,!1)*Math.sin(I*_)/I,s-=Math.floor(s)),e.source){case`sine`:o=Math.sin(I*s);break;case`triangle`:o=1-4*Math.abs(s-.5);break;case`saw`:o=2*s-1-(e.fm?0:B(s,i));break;default:{let t=e.width??.5;o=s<t?1:-1,e.fm||(o+=B(s,i)-B((s-t+1)%1,i))}}}for(let e of c)i&15||e.run.tune(R(e.freq,a,1e3,!0)*(m?r:1)),o=e.run.run(o);d>0&&(o=Math.tanh(o*f)/p);let v=R(e.gain,a,1,!1);if(e.decay){let t=Math.exp(-a/e.decay);v*=e.tail?t*(1-e.tail.mix)+Math.exp(-a/e.tail.decay)*e.tail.mix:t}e.tremolo&&(v*=1-e.tremolo.depth*(.5+.5*Math.sin(I*e.tremolo.rate*a))),l>0&&a<l&&(v*=a/l);let y=t-a;u>0&&y<u&&(v*=Math.max(0,y/u)),s[i]=o*v}return s}function ne(e,t,n){let r=1;for(;r<e.length+t.length;)r<<=1;let[i,a,o,s]=[new Float64Array(r),new Float64Array(r),new Float64Array(r),new Float64Array(r)];i.set(e),o.set(t),F(i,a),F(o,s);for(let e=0;e<r;e++){let[t,n]=[i[e]*o[e]-a[e]*s[e],i[e]*s[e]+a[e]*o[e]];i[e]=t,a[e]=-n}F(i,a);let c=new Float32Array(n);for(let e=0;e<n;e++)c[e]=i[e]/r;return c}function W(e,t,n,r){let i=z(n===`room`?6923+r*977:32324+r*977),a=()=>i()*.5+.5,o=n===`room`?.35+t*2.4:.6+t*2.6,s=Math.floor(e*o),c=new Float32Array(s),l=(t,n)=>{let r=new Float32Array(s),[a,o]=[t?new V(`highpass`,.6,e):null,n?new V(`lowpass`,.6,e):null];a?.tune(t),o?.tune(n);for(let e=0;e<s;e++){let t=i();a&&(t=a.run(t)),o&&(t=o.run(t)),r[e]=t}let c=H(r)||1;for(let e=0;e<s;e++)r[e]/=c;return r};if(n===`room`){let n=.25+t*1.5,o=[[l(null,420),.45,n],[l(420,3e3),1,n*.8],[l(3e3,null),1.6,n*.4]];for(let t=0;t<s;t++){let n=t/e,r=1-Math.exp(-n/.014),i=0;for(let[e,r,a]of o)i+=e[t]*r*10**(-3*n/a);c[t]=i*r}let u=H(c)*Math.sqrt(s),d=new Float32Array(s);for(let n=0;n<34;n++){let o=(.0048+.088*((n+a())/34)**1.5)*(.45+t)*(r?1.07:1),c=Math.floor(o*e),l=(i()<0?-1:1)*Math.exp(-o/.034)*(.55+.45*a()),u=1+Math.floor(o*60);for(let e=0;e<u&&c+e<s;e++)d[c+e]+=l*(1-e/u)/Math.sqrt(u)}let f=H(d)*Math.sqrt(s)||1;for(let e=0;e<s;e++)c[e]+=d[e]*(.78*u/f)}else{for(let[n,o,l,u]of[[.094,.5,5,5200],[.151,.4,8,3800],[.212,.31,12,2700],[.289,.24,16,2e3]]){let d=Math.floor(e*l*4/1e3),[f,p]=[new V(`lowpass`,.6,e),new V(`highpass`,.6,e)];f.tune(u),p.tune(180);let m=new Float32Array(d);for(let t=0;t<d;t++)m[t]=p.run(f.run(i()))*Math.exp(-t/(e*l/1e3))*(1-Math.exp(-t/(e*6e-4)));let h=H(m)*Math.sqrt(d)||1,g=Math.floor(e*n*(.5+t)*(1+.1*i()*.5)),_=o*(.45+.55*(r?1-a():a()))/h;for(let e=0;e<d&&g+e<s;e++)c[g+e]+=m[e]*_}let n=H(c)*Math.sqrt(s)||1,o=l(320,2300),u=1+t*2,d=0;for(let t=0;t<s;t++){let n=t/e;o[t]=o[t]*10**(-3*n/u)*(1-Math.exp(-n/.11)),d+=o[t]*o[t]}let f=Math.sqrt(d)||1;for(let e=0;e<s;e++)c[e]+=o[e]*(.5*n/f)}let u=Math.floor(s*.08);for(let e=0;e<u;e++)c[s-1-e]*=e/u;let d=H(c)*Math.sqrt(s)||1;for(let e=0;e<s;e++)c[e]/=d;return c}function G(e,t,n){let r=e.pan??0;if(e.scatter){let i=e.scatter,a=z(n+4409),o=()=>a()*.5+.5,[s,c]=i.pitch??[1,1],[l,u]=i.gain??[1,1];return Array.from({length:i.count},(e,d)=>{let f=o()**+(i.early??1);return{at:t+i.over*f,pitch:s*(c/s)**+o(),loud:(l+(u-l)*o())*(1-(i.fade??0)*f),pan:Math.max(-1,Math.min(1,r+(i.pan??0)*a())),seed:n+d*131}}).sort((e,t)=>e.at-t.at)}let i=e.repeat,a=z(n+7919),o=[],[s,c]=[t,i?.every??0];for(let e=0;e<(i?.count??1);e++)o.push({at:s+(e>0&&i?.jitter?a()*i.jitter:0),pitch:(i?.pitch??1)**+e,loud:(i?.gain??1)**+e,pan:r,seed:n+e*131}),s+=c,c*=i?.faster??1;return o}function K(e,t=0,n={}){let r=e.rate??44100,i=Math.max(1,Math.round(e.duration*r)),a=e.loop?Math.min(Math.round(.08*r),Math.floor(i/2)):0,o=i+a,[s,c]=[new Float32Array(o),new Float32Array(o)],l=[],u=[],d=e.reverb!==void 0,f=t>0?e.vary??.06:0,p=z(t*7717+13),m=new Map,h=e=>{let n=m.get(e);return n||(n=f>0?{pitch:1+f*p(),loud:1+f*2*p(),decay:1+f*1.5*p(),late:1+f*p(),seed:t*1009}:{pitch:1,loud:1,decay:1,late:1,seed:0},m.set(e,n)),n},g=(t,i,a,u,f)=>{let p=h(t),m=u.offset+(t.start??0)*p.late,_=(t.seed??i+1)+u.seed+p.seed;if(t.source===`group`){let e=G(t,m,_),n=(typeof t.gain==`number`?t.gain:1)*p.loud,[i,s,c]=[0,m,0];for(let l of e)l.at*r>=o||(c++,t.layers.forEach((e,t)=>{if(e.mute)return;let r=g(e,t,`${a} > layer ${t}${e.id?` \"${e.id}\"`:``}`,{offset:l.at,pitch:u.pitch*l.pitch,loud:u.loud*l.loud*n,pan:Math.max(-1,Math.min(1,u.pan+l.pan)),seed:l.seed+t*977},!1);i=Math.max(i,r.peak),s=Math.max(s,r.last)}));return{peak:i,last:s,heard:c,strikes:e.length}}let v=o/r-m,y=t.source===`sample`?n.given?.[t.file]??null:null;if(t.source===`sample`&&!y)throw Error(`${a}: the recording ${t.file} was not found`);let b=y?Math.max(.001,(y.channels[0].length/y.rate-(t.from??0))/((t.speed??1)*u.pitch*p.pitch)):v,x=Math.min(t.length??b,v);if(!(x>0))return f&&l.push(`${a} starts at the end of the sound and is not heard`),{peak:0,last:m,heard:0,strikes:0};f&&t.length!==void 0&&t.length>v+1e-6&&!t.repeat&&!t.scatter&&l.push(`${a} is cut short: it runs ${t.length} s from ${Math.round(m*1e3)/1e3} s in a sound of ${e.duration} s`);let S=t.source===`noise`?t.wide??0:0,C=p.decay!==1&&t.decay?{...t,decay:t.decay*p.decay,...t.tail?{tail:{...t.tail,decay:t.tail.decay*p.decay}}:{}}:t,w=G(t,m,_);(S>0||u.pan!==0||w.some(e=>e.pan!==0))&&(d=!0);let[T,E,D]=[0,m,0];for(let e of w){let t=Math.round(Math.max(0,e.at)*r);if(t>=o)continue;D++;let n=Math.min(x,(o-t)/r),i=e.pitch*u.pitch*p.pitch,a=e.loud*u.loud*p.loud,l=U(C,n,r,i,e.seed,y),d=S>0?U(C,n,r,i,e.seed+50021):null,f=Math.max(-1,Math.min(1,e.pan+u.pan)),[m,h]=[Math.cos((f+1)*Math.PI/4),Math.sin((f+1)*Math.PI/4)];for(let e=0;e<l.length&&t+e<o;e++){let n=l[e]*a;s[t+e]+=n*m,c[t+e]+=(d?n*(1-S)+d[e]*a*S:n)*h,Math.abs(n)>T&&(T=Math.abs(n))}E=Math.max(E,Math.min(o/r,e.at+l.length/r))}return{peak:T,last:E,heard:D,strikes:w.length}};e.layers.forEach((e,t)=>{if(e.mute)return;let r=`layer ${t}${e.id?` \"${e.id}\"`:``}`,i=g(e,t,r,{offset:0,pitch:n.pitch??1,loud:1,pan:0,seed:n.seed??0},!0),a=e.start??0;u.push({...e.id?{id:e.id}:{},source:e.source,from:Math.round(a*1e3)/1e3,to:Math.round(i.last*1e3)/1e3,peak:Math.round(i.peak*1e3)/1e3,...i.strikes>1?{strikes:i.heard}:{}}),i.heard<i.strikes&&l.push(`${r}: ${i.strikes-i.heard} of its ${i.strikes} strikes fall past the end of the sound and are not heard`),i.strikes>0&&i.peak<1e-4&&l.push(`${r} makes no sound: its level is nothing throughout`)});let _=d?[s,c]:[s.map((e,t)=>(e+c[t])*Math.SQRT1_2)];for(let[t,n]of _.entries()){for(let[t,i]of[[`highpass`,`highpass`],[`lowpass`,`lowpass`]]){if(e[t]===void 0)continue;let a=new V(i,.7,r);a.tune(e[t]);for(let e=0;e<o;e++)n[e]=a.run(n[e])}if(e.echo){let t=Math.max(1,Math.round(e.echo.time*r)),[i,a]=[e.echo.feedback??.35,e.echo.mix??.3],s=new Float32Array(t);for(let e=0;e<o;e++){let r=s[e%t];s[e%t]=n[e]+r*i,n[e]=n[e]+r*a}}if(e.reverb){let i=ne(n,W(r,e.reverb.size??.5,e.reverb.kind??`room`,t),o),a=e.reverb.mix??.25;for(let e=0;e<o;e++)n[e]=n[e]+i[e]*a*3}}let v=_.map(e=>{let t=e.subarray(0,i).slice();if(a>0)for(let n=0;n<a;n++){let r=n/a;t[n]=t[n]*r+e[i+n]*(1-r)}else{let e=Math.min(i,Math.round(.003*r));for(let n=0;n<e;n++)t[i-1-n]*=n/e}return t}),y=0;for(let e of v)for(let t of e)Math.abs(t)>y&&(y=Math.abs(t));let b=e.gain??.9;if(!n.raw)if(e.normalize!==!1){if(y>1e-6)for(let e of v)for(let t=0;t<i;t++)e[t]*=b/y;else l.push(`the sound is silent: nothing in it reaches a level that can be heard`);y=y>1e-6?b:0}else{for(let e of v)for(let t=0;t<i;t++)e[t]*=b/.9;if(y*=b/.9,y>1){l.push(`the layers sum to ${y.toFixed(2)} times full, and what is past full is cut off flat: lower their gain, or leave normalize on`);for(let e of v)for(let t=0;t<i;t++)e[t]=Math.max(-1,Math.min(1,e[t]));y=1}}let x=0;for(let e of v)for(let t of e)x+=t*t;return{rate:r,channels:v,seconds:i/r,peak:y,rms:Math.sqrt(x/(i*v.length)),layers:u,notes:l}}function re(e){let[t,n]=[e.channels.length,e.channels[0].length],r=new Uint8Array(44+n*t*2),i=new DataView(r.buffer),a=(e,t)=>{for(let n=0;n<t.length;n++)r[e+n]=t.charCodeAt(n)};a(0,`RIFF`),i.setUint32(4,36+n*t*2,!0),a(8,`WAVE`),a(12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,t,!0),i.setUint32(24,e.rate,!0),i.setUint32(28,e.rate*t*2,!0),i.setUint16(32,t*2,!0),i.setUint16(34,16,!0),a(36,`data`),i.setUint32(40,n*t*2,!0);for(let r=0;r<n;r++)for(let n=0;n<t;n++){let a=Math.max(-1,Math.min(1,e.channels[n][r]));i.setInt16(44+(r*t+n)*2,Math.round(a*32767),!0)}return r}function ie(e,t){let n=t.slice(0,2).map(e=>Float32Array.from(e)),[r,i]=[0,0];for(let e of n)for(let t of e)Math.abs(t)>r&&(r=Math.abs(t)),i+=t*t;let a=n[0]?.length??0;return{rate:e,channels:n,seconds:a/e,peak:r,rms:Math.sqrt(i/Math.max(1,a*n.length)),layers:[],notes:[]}}function ae(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t=>String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3]);if(e.length<44||n(0)!==`RIFF`||n(8)!==`WAVE`)throw Error(`not a .wav: it does not begin RIFF....WAVE`);let[r,i,a,o]=[0,0,0,0],s=null;for(let c=12;c+8<=e.length;){let l=t.getUint32(c+4,!0);n(c)===`fmt `?(r=t.getUint16(c+8,!0),i=t.getUint16(c+10,!0),a=t.getUint32(c+12,!0),o=t.getUint16(c+22,!0),r===65534&&l>=26&&(r=t.getUint16(c+32,!0))):n(c)===`data`&&(s={at:c+8,size:Math.min(l,e.length-c-8)}),c+=8+l+(l&1)}if(!s||!i||!a)throw Error(`a .wav with no format or no samples in it`);if(!(r===1&&[8,16,24,32].includes(o)||r===3&&o===32))throw Error(`a .wav of a kind not read here (format ${r}, ${o} bits); PCM of 8 to 32 bits and 32-bit floats are`);let c=o/8,l=Math.floor(s.size/(c*i)),u=Array.from({length:i},()=>new Float32Array(l));for(let n=0;n<l;n++)for(let a=0;a<i;a++){let l=s.at+(n*i+a)*c;u[a][n]=r===3?t.getFloat32(l,!0):o===8?(e[l]-128)/128:o===16?t.getInt16(l,!0)/32768:o===24?(e[l]|e[l+1]<<8|t.getInt8(l+2)<<16)/8388608:t.getInt32(l,!0)/2147483648}return ie(a,u)}let oe=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`],q=e=>`${oe[(e%12+12)%12]}${Math.floor(e/12)-1}`;function se(e){let t=e*2654435761+2654435769>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/2147483648-1}}function ce(e){let t=e.beats??4,n=t*60/e.tempo,r=h[e.scale??`minor`],i=S(e.key),a=e.humanize??.15,o=se(e.seed??1),s=[],c=[],l=[],u=new Set,d=e=>{u.has(e)||(u.add(e),l.push(e))},f=new Set,p=new Set,m=0;e.song.forEach((u,g)=>{let _=typeof u==`string`?u:u.pattern,v=e.patterns[_];p.add(_),c.push({pattern:_,at:m,bars:v.bars});let y=v.div??4,b=t*y,x=n/b,S=s.length;for(let[t,c]of Object.entries(v.tracks)){if(typeof u!=`string`&&(u.without?.includes(t)||u.only&&!u.only.includes(t)))continue;let l=e.instruments[t];l.follow&&!v.chords&&d(`\"${t}\" follows the chords, and pattern \"${_}\" has none: it plays every bar on chord 1`);let p=D(c,v.bars,b,`pattern \"${_}\", track \"${t}\"`,h[l.scale??e.scale??`minor`].length),S=v.bars*n,C=(e.rubato??0)*.08*S/(2*Math.PI),w=e=>e+C*Math.sin(2*Math.PI*e/S),T=v.dynamics?.[t]??v.dynamics?.all,E=e=>{if(!T)return 1;let t=e/b,[n,r]=[T[Math.min(Math.floor(t),T.length-1)],T[Math.min(Math.floor(t)+1,T.length-1)]];return n+(r-n)*(t-Math.floor(t))},O=null;for(let n=0;n<p.length;n++){let c=p[n];if(c.kind===`hold`&&(n===0||p[n-1].kind===`rest`)&&d(`pattern \"${_}\", track \"${t}\": a \"-\" at step ${n%b+1} of bar ${Math.floor(n/b)+1} has no note before it to hold, and is silent`),c.kind!==`hit`&&c.kind!==`notes`)continue;let u=1;for(;n+u<p.length&&p[n+u].kind===`hold`;)u++;let S=y%2==0&&n%2==1?(e.swing??0)*x:0,C=Math.max(0,m+w(n*x+S)+a*.012*o()),T=w((n+u)*x)-w(n*x),D=c.loud*E(n),k=D*(1+a*.25*o()),A=D>1.15?1:D<.8?-1:0,j=w((Math.floor(n/b)+1)*b*x)-w(n*x),M=l.pedal&&j>T+1e-9?{sounds:j}:{};if(f.add(t),c.kind===`hit`){s.push({instrument:t,at:C,seconds:T,midi:null,loud:k,part:g,outside:!1,mark:A,hard:D,...M}),O=null;continue}let N=!!l.legato&&c.notes.length===1&&O!==null&&O.end===n&&c.loud<=1;N&&(O.event.tied=!0);let P=l.follow&&v.chords?v.chords[Math.floor(n/b)%v.chords.length]:1,F=l.scale?h[l.scale]:r,I=F.length,L=P>I/2+1?-I:0;for(let e of c.notes){let n=e.degree-1+P-1+L+I,r=60+i+F[n%I]+12*(Math.floor(n/I)-1+e.octave+(l.octave??0))+e.alter;s.push({instrument:t,at:C,seconds:T,midi:r,loud:k,part:g,outside:e.alter!==0,mark:A,hard:D,...M,...N?{slur:!0}:{}})}O=c.notes.length===1?{end:n+u,event:s[s.length-1]}:null}}s.length===S&&l.push(`part ${g+1} of the song (\"${_}\") plays nothing`),m+=v.bars*n});for(let t of Object.keys(e.instruments))f.has(t)||l.push(`instrument \"${t}\" is never played`);for(let t of Object.keys(e.patterns))p.has(t)||l.push(`pattern \"${t}\" is not in the song`);let g=new Map;for(let e of s)e.midi!==null&&g.set(e.instrument,[...g.get(e.instrument)??[],e]);let _=new Map;for(let[e,t]of g){let n=t.map(e=>e.midi).sort((e,t)=>e-t);_.set(e,n[Math.floor(n.length/2)]),n[0]<24&&l.push(`\"${e}\" goes down to ${q(n[0])}, below where a pitch can be told: raise its octave`),n[n.length-1]>100&&l.push(`\"${e}\" goes up to ${q(n[n.length-1])}, which is a whistle: lower its octave`);let r=t.filter(e=>e.outside).length;r>0&&l.push(`\"${e}\" plays ${r} note${r===1?``:`s`} outside the key`)}let v=[...g.keys()];for(let e=0;e<v.length;e++)for(let t=e+1;t<v.length;t++){let[n,r]=[g.get(v[e]),g.get(v[t])];if(Math.abs(_.get(v[e])-_.get(v[t]))>4)continue;let i=e=>e.reduce((e,t)=>e+t.seconds,0),a=0;for(let e of n)for(let t of r)a+=Math.max(0,Math.min(e.at+e.seconds,t.at+t.seconds)-Math.max(e.at,t.at));a>.5*Math.min(i(n),i(r))&&l.push(`\"${v[e]}\" and \"${v[t]}\" sound together in the same octave, round ${q(_.get(v[e]))}, and will blur into one: move one of them an octave`)}return s.sort((e,t)=>e.at-t.at),{seconds:N(e),barSeconds:n,events:s,parts:c,notes:l}}function J(e,t){let n=e.scatter?e.scatter.over:e.repeat?(e.repeat.count-1)*e.repeat.every:0,r=e.source===`group`?Math.max(0,...e.layers.map(e=>J(e,t))):e.length??t;return(e.start??0)+n+r}function Y(e,t,n,r=0){return e.source===`group`?{...e,layers:e.layers.map(e=>Y(e,t,n,r))}:e.length===void 0?{...e,length:Math.max(.01,t+n-(e.start??0)),release:e.release??n,...r>0?{attack:Math.max(e.attack??0,r)}:{}}:r>0?{...e,mute:!0}:e}let le={soft:-1,normal:0,loud:1};function ue(e,t,n,r){let i=e.samples,a=e=>le[i[e].dynamic??`normal`],o=i.map((e,t)=>t),s=Math.min(...o.map(e=>Math.abs(a(e)-n)));o=o.filter(e=>Math.abs(a(e)-n)===s);let c=s===0&&n!==0;if(t!==null){let e=o.filter(e=>(i[e].low!==void 0||i[e].high!==void 0)&&t>=(C(i[e].low)??0)&&t<=(C(i[e].high)??127));e.length&&(o=e);let n=Math.min(...o.map(e=>Math.abs(C(i[e].note)-t)));o=o.filter(e=>Math.abs(C(i[e].note)-t)===n),o=o.filter(e=>C(i[e].note)===C(i[o[0]].note))}else o=[o[0]];return{index:o[r%o.length],matched:c}}function de(e,t,n,r,i,a,o,s=0){let c=t.samples[n],l=o[c.file];if(!l)throw Error(`instrument \"${e}\": the recording ${c.file} was not found`);let u=l.channels[0].length,d=(r===null?1:2**((r-C(c.note)-(c.tune??0)/100)/12))*(l.rate/a),f=s>0?Math.min(.12*l.rate,u*.25):0,[p,m]=[s>0?s:t.attack??.003,t.release??.08],[h,g]=[0,0];c.loop&&([h,g]=c.loop===!0?[u*.4,u*.85]:[c.loop[0]*l.rate,Math.min(u-2,c.loop[1]*l.rate)]);let _=g-h,v=_>0?Math.min(.12*l.rate,_/3,h):0,y=Math.max(1,Math.round(Math.min(i+m,_>0?30:(u-2-f)/d/a)*a)),b=(e,t)=>{let n=Math.floor(t),r=t-n,[i,a,o,s]=[e[n-1]??e[n],e[n],e[n+1]??0,e[n+2]??0];return a+.5*r*(o-i+r*(2*i-5*a+4*o-s+r*(3*(a-o)+s-i)))},x=l.channels.slice(0,2).map(()=>new Float32Array(y)),S=Math.round(i*a),w=Math.min(y,Math.round(.005*a));for(let e=0;e<y;e++){let t=f+e*d,n=0;_>0&&t>=g-v&&(t=h+(t-h)%_,v>0&&t>=g-v&&(n=(t-(g-v))/v));let r=e<p*a?e/(p*a):1;e>S&&(r*=Math.max(0,1-(e-S)/Math.max(1,m*a))),y-e<w&&(r*=(y-e)/w);for(let i=0;i<x.length;i++){let a=l.channels[i];x[i][e]=(n>0?b(a,t)*(1-n)+b(a,t-_)*n:b(a,t))*r*(c.gain??1)}}if(c.cutoff&&c.cutoff<a*.45)for(let e of x)X(e,`lowpass`,c.cutoff,a);return x}function fe(e,t){let n=e.channels[0],r=Math.ceil(e.rate/(t/2.1)),i=Math.floor(n.length*.25),a=Math.min(16384,n.length-i-r);if(a<r*2)return null;let o=[];for(let s=Math.max(8,Math.floor(e.rate/(t*4.2)));s<=r;s++){let e=0,t=0,r=0;for(let o=0;o<a;o+=2){let a=n[i+o],c=n[i+o+s];e+=a*c,t+=a*a,r+=c*c}o.push([s,e/Math.sqrt(t*r+1e-12)])}let s=Math.max(...o.map(e=>e[1]));if(!(s>.6))return null;let c=o.findIndex(e=>e[1]>=s*.92);for(;c+1<o.length&&o[c+1][1]>o[c][1];)c++;let l=e=>{let t=0,r=0,o=0,s=Math.floor(e),c=e-s;for(let e=0;e<a;e+=2){let a=n[i+e],l=n[i+e+s]*(1-c)+n[i+e+s+1]*c;t+=a*l,r+=a*a,o+=l*l}return t/Math.sqrt(r*o+1e-12)},u=o[c][0],d=e=>{let t=[e,-1];for(let n=-.5;n<=.5;n+=.05){let r=l(e+n);r>t[1]&&(t=[e+n,r])}return t},[f,p]=d(u);for(let n of[3,2]){if(u/n<4||e.rate/(u/n)>t*4.2)continue;let[r,i]=d(u/n);if(i>=p*.9){[f,p]=[r,i];break}}return u=f,e.rate/u}function X(e,t,n,r,i=0){let a=2*Math.PI*Math.min(n,r*.45)/r,[o,s]=[Math.cos(a),Math.sin(a)],c,l,u,d,f,p;if(t===`lowpass`||t===`highpass`){let e=s/(2*Math.SQRT1_2);[c,l,u]=t===`lowpass`?[(1-o)/2,1-o,(1-o)/2]:[(1+o)/2,-(1+o),(1+o)/2],[d,f,p]=[1+e,-2*o,1-e]}else{let e=10**(i/40),n=2*Math.sqrt(e)*(s/2)*Math.SQRT2,r=t===`lowshelf`?1:-1;c=e*(e+1-r*(e-1)*o+n),l=r*2*e*(e-1-r*(e+1)*o),u=e*(e+1-r*(e-1)*o-n),d=e+1+r*(e-1)*o+n,f=-r*2*(e-1+r*(e+1)*o),p=e+1+r*(e-1)*o-n}let m=0,h=0,g=0,_=0;for(let t=0;t<e.length;t++){let n=e[t],r=(c*n+l*m+u*h-f*g-p*_)/d;h=m,m=n,_=g,g=r,e[t]=r}}function pe(e,t,n,r){let i=e[0].length,a=0;for(let t of e)for(let e of t)Math.abs(e)>a&&(a=Math.abs(e));let o=new Float32Array(i).fill(1);if(!(a>1e-6)||n<=0)return o;let s=a*10**(-(6+14*n)/20),c=1.5+2.5*n,[l,u]=[Math.exp(-1/(.005*t)),Math.exp(-1/(.14*t))],d=0,f=t=>{let n=0;for(let r of e)n=Math.max(n,Math.abs(r[t]));d=n>d?n+(d-n)*l:n+(d-n)*u};if(r)for(let e=Math.max(0,i-t);e<i;e++)f(e);for(let e=0;e<i;e++)f(e),d>s&&(o[e]=s*(d/s)**(1/c)/d);let p=1/(.006*t);for(let e=i-2;e>=0;e--)o[e]=Math.min(o[e],o[e+1]+p);return r&&(o[i-1]=Math.min(o[i-1],o[0]+p)),o}function Z(e){let t=1;for(;t<e.length*2;)t<<=1;let n=t-e.length,[r,i]=[new Float64Array(t),new Float64Array(t)];r.set(e),F(r,i);let[a,o]=[new Float64Array(t),new Float64Array(t)];return e=>{let s=new Float32Array(e.length);for(let c=0;c<e.length;c+=n){a.fill(0),o.fill(0);let l=!1;for(let t=0;t<n&&c+t<e.length;t++){let n=e[c+t];a[t]=n,n!==0&&(l=!0)}if(l){F(a,o);for(let e=0;e<t;e++){let t=a[e]*r[e]-o[e]*i[e],n=a[e]*i[e]+o[e]*r[e];a[e]=t,o[e]=-n}F(a,o);for(let n=0;n<t&&c+n<e.length;n++)s[c+n]+=a[n]/t}}return s}}function me(e,t={}){let n=ce(e),r=e.rate??44100,i=Math.max(1,Math.round(n.seconds*r)),a=i+Math.round(4*r),o=Object.keys(e.instruments),s=new Map(o.map(e=>[e,[new Float32Array(a),new Float32Array(a)]])),c=new Map,l=(e,n,i,a,o)=>{let s=n.legato===!0?.07:n.legato||0,l=i.slur?s:0,u=(i.sounds??i.seconds)+(i.tied?s:0),d=`${e}|${i.midi}|${Math.round(u*1e3)}|${l}|${n.samples?`z${o}`:a%3}`,f=c.get(d);if(!f&&n.samples&&(f=de(e,n,o,i.midi,u,r,t,l),c.set(d,f)),!f){let e=n.release??.08,t=n.layers.map(t=>Y(t,u,e,l));f=K({duration:Math.min(8,Math.max(.02,...t.map(t=>J(t,u+e)))),rate:r,layers:t,normalize:!1},0,{pitch:i.midi===null?1:2**((i.midi-69)/12),seed:a%3*7919,raw:!0}).channels,c.set(d,f)}return f},u=new Map;for(let t of n.events){let n=e.instruments[t.instrument],i=u.get(t.instrument)??0;u.set(t.instrument,i+1);let o={index:0,matched:!1};if(n.samples){let e=`${t.instrument}|${t.midi}|${t.mark}`,r=u.get(e)??0;u.set(e,r+1),o=ue(n,t.midi,t.mark,r)}let c=l(t.instrument,n,t,i,o.index),[d,f]=[c[0],c[1]??c[0]],p=n.pan??0,m=(o.matched?t.loud/t.hard:t.loud)*(n.gain??1)*Math.SQRT2,[h,g]=[Math.cos((p+1)*Math.PI/4)*m,Math.sin((p+1)*Math.PI/4)*m],[_,v]=s.get(t.instrument),y=Math.round(t.at*r);for(let e=0;e<d.length&&y+e<a;e++)_[y+e]+=d[e]*h,v[y+e]+=f[e]*g}for(let t of o){let n=e.instruments[t];for(let e of s.get(t))n.lowcut&&X(e,`highpass`,n.lowcut,r),n.highcut&&X(e,`lowpass`,n.highcut,r)}let d=[new Float32Array(a),new Float32Array(a)];if(e.reverb){let[t,n]=[e.reverb.size??.4,(e.reverb.mix??.2)*3],i=[0,1].map(e=>Z(W(r,t,`room`,e))),c=t=>e.instruments[t].reverb??.3;if(e.stems)for(let e of o)c(e)!==0&&s.get(e).forEach((t,r)=>{let o=i[r](t);for(let r=0;r<a;r++)t[r]+=o[r]*n*c(e)});else for(let e of[0,1]){let t=new Float32Array(a);for(let n of o){let[r,i]=[s.get(n)[e],c(n)];if(i>0)for(let e=0;e<a;e++)t[e]+=r[e]*i}let r=i[e](t);for(let t=0;t<a;t++)d[e][t]=r[t]*n}}let f=e.loop!==!1,p=f&&e.intro?n.parts[e.intro].at:0,m=Math.round(p*r),h=i;if(!f&&!e.fadeOut){let e=i;for(let t of[...d,...o.flatMap(e=>s.get(e))])for(let n=a-1;n>e;n--)if(Math.abs(t[n])>2e-4){e=n;break}h=Math.min(a,e+(e>i?Math.round(.05*r):0))}let g=t=>{let n=t.slice(0,h);if(f)for(let e=i;e<a;e++)n[m+(e-i)%(i-m)]+=t[e];else{if(e.fadeIn){let t=Math.round(e.fadeIn*r);for(let e=0;e<t&&e<h;e++)n[e]*=(e/t)**2}let t=Math.min(h,Math.round((e.fadeOut??.02)*r));for(let r=0;r<t;r++)n[h-1-r]*=e.fadeOut?(r/t)**2:r/t}return n},_={};for(let e of o)_[e]=s.get(e).map(g);let v=[0,1].map(e=>{let t=g(d[e]);for(let n of o){let r=_[n][e];for(let e=0;e<h;e++)t[e]+=r[e]}return t});if(e.master){let t=[v,...Object.values(_)];if(e.master.compress){let n=pe(v,r,e.master.compress,f);for(let e of t)for(let t of e)for(let e=0;e<h;e++)t[e]*=n[e]}for(let n of t)for(let t of n)e.master.low&&X(t,`lowshelf`,110,r,e.master.low),e.master.high&&X(t,`highshelf`,7e3,r,e.master.high)}let y=0;for(let e of v)for(let t of e)Math.abs(t)>y&&(y=Math.abs(t));let b=[...n.notes];for(let r of o){let i=[],a=n.events.some(e=>e.instrument===r&&e.midi!==null)?e.instruments[r].samples??[]:[],o=new Set;for(let e of a){let n=t[e.file];if(!n||o.has(`${e.file}|${e.note}`))continue;o.add(`${e.file}|${e.note}`);let r=C(e.note),a=440*2**((r+(e.tune??0)/100-69)/12),s=fe(n,a),c=s===null?0:12*Math.log2(s/a);Math.abs(c)>=.7&&i.push({file:e.file,said:r,is:Math.round(r+c)})}if(i.length===0)continue;let s=e=>e.is-e.said,c=e=>`${Math.abs(e)} semitone${Math.abs(e)===1?``:`s`} ${e>0?`higher`:`lower`}`;if(i.length===o.size&&i.length>1&&i.every(e=>s(e)===s(i[0])))b.push(`\"${r}\": every one of its ${o.size} recordings sounds ${c(s(i[0]))} than the note it is said to be (${i[0].file} is said to be ${q(i[0].said)} and sounds as ${q(i[0].is)})${Math.abs(s(i[0]))===12?`, as a library does that counts its octaves from another C`:``}: the instrument plays that much out. Move each \\`note\\` by that much`);else for(let e of i)b.push(`\"${r}\": ${e.file} is said to be ${q(e.said)} and sounds as ${q(e.is)}: every note played from it is ${c(s(e))} than written. Set its note to \"${q(e.is)}\"`)}let x=e.gain??.9,S=y>1e-6?x/y:1;y<=1e-6&&b.push(`the piece is silent: nothing in it reaches a level that can be heard`);for(let e of[v,...Object.values(_)])for(let t of e)for(let e=0;e<h;e++)t[e]*=S;let w=(e,t=0,n=i)=>{let r=0;for(let i of e)for(let e=t;e<n;e++)r+=i[e]*i[e];return Math.sqrt(r/(Math.max(1,n-t)*e.length))},T=w(v),E=null;if(f){let e=Math.min(i,Math.round(n.barSeconds*r)),t=(e,t)=>{let r=n.barSeconds*.05;return o.filter(i=>n.events.some(n=>n.instrument===i&&Math.min(t,n.at+n.seconds)-Math.max(e,n.at)>r))},a=e=>e>0&&T>0?Math.round(20*Math.log10(e/T)*10)/10:-120;E={ends:t(n.seconds-n.barSeconds,n.seconds),begins:t(p,p+n.barSeconds),endDb:a(w(v,i-e,i)),startDb:a(w(v,m,Math.min(i,m+e)))};let[s,c]=[E.ends.filter(e=>!E.begins.includes(e)),E.begins.filter(e=>!E.ends.includes(e))];i-m>e*2&&(Math.abs(E.endDb-E.startDb)>6||s.length+c.length>Math.max(1,o.length/3))&&b.push(`where the loop meets itself the music changes at once: its last bar has ${E.ends.join(`, `)||`nothing`} at ${E.endDb} dB and its first has ${E.begins.join(`, `)||`nothing`} at ${E.startDb} dB${s.length?`, so ${s.join(`, `)} stop${s.length===1?`s`:``} dead`:``}. A loop is heard as one piece when its end is as full as its start: end on a part like the one it comes back to (thin the last part with \\`without\\`, or begin as full as it ends), and put a build that happens once in an introduction with \\`intro\\``)}let D={};for(let e of o){let t=n.events.filter(t=>t.instrument===e),r=t.filter(e=>e.midi!==null).map(e=>e.midi),i=w(_[e]);D[e]={notes:t.length,...r.length?{low:q(Math.min(...r)),high:q(Math.max(...r))}:{},levelDb:i>0&&T>0?Math.round(20*Math.log10(i/T)*10)/10:-120}}return{...n,notes:b,rate:r,channels:v,peak:y>1e-6?x:0,rms:T,loopStart:p,tailSeconds:(h-i)/r,join:E,stems:e.stems?_:null,instruments:D}}let he=e=>/\\.esmusic(\\?|$)/i.test(e);function Q(e){let t;try{t=JSON.parse(e.source)}catch{throw Error(`${e.path} is not JSON`)}return he(e.path)?{music:P(t)}:{sound:m(t)}}function ge(e,t){let n=Q({source:e,path:t});if(`sound`in n)return p(n.sound);let r=new Set(w(n.music));for(let e of Object.values(n.music.instruments))for(let t of p({layers:e.layers??[]}))r.add(t);return[...r]}function $(e){let t={};for(let[n,r]of Object.entries(e.files)){if(!/\\.wav$/i.test(n))throw Error(`${e.path} plays ${n}, and a recipe plays .wav recordings only`);let i=ae(new Uint8Array(r));t[n]={rate:i.rate,channels:i.channels}}let n=Q(e),r=`sound`in n?K(n.sound,0,{given:t}):me(n.music,t),i=re({rate:r.rate,channels:r.channels});return i.byteOffset===0&&i.byteLength===i.buffer.byteLength?i.buffer:i.slice().buffer}if(typeof self<`u`&&self.document===void 0){let e=self;e.onmessage=t=>{let n=t.data;try{let t=$(n);e.postMessage({id:n.id,result:t},[t])}catch(t){e.postMessage({id:n.id,error:t instanceof Error?t.message:String(t)})}}}return e.makeSound=$,e.soundNeeds=ge,e})({});";
diff --git a/sdk/tests/audio-recipe.test.ts b/sdk/tests/audio-recipe.test.ts
new file mode 100644
index 000000000..6cada9d15
--- /dev/null
+++ b/sdk/tests/audio-recipe.test.ts
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file audio-recipe.test.ts
+ * @brief A clip that is a recipe: which paths are one, what makes them, that what is made is the sound its source bakes to, and
+ * that the audio layer hands it to its backend as a file.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ audioRecipeCacheKey, audioRecipeStats, hasAudioRecipeMaker, isAudioRecipePath, renderAudioRecipe, setAudioRecipeMaker,
+ type AudioRecipeFileReader,
+} from '../src/asset/audioRecipe';
+import { contentHashHex } from '../src/asset/contentHash';
+import { AudioAPI } from '../src/audio/Audio';
+import type { PlatformAudioBackend } from '../src/audio/PlatformAudioBackend';
+import { getAddressableType } from '../src/assetTypes';
+import { setPlatform } from '../src/platform/base';
+import type { PlatformAdapter } from '../src/platform/types';
+import { SOUND_RENDER_REVISION, decodeWav, encodeWav, installAudioRecipes, renderMusic, renderSound, validateMusicSource, validateSoundSource } from '../src/sound';
+import { encodeUtf8 } from '../src/util/utf8';
+
+afterEach(() => { setAudioRecipeMaker(null); audioRecipeStats(true); });
+
+/** A project that is a few files by path. */
+const project = (files: Record<string, unknown>): AudioRecipeFileReader => async (path) => {
+ if (!(path in files)) throw new Error(`there is no file at ${path}`);
+ const file = files[path];
+ const bytes = file instanceof Uint8Array ? file : encodeUtf8(typeof file === 'string' ? file : JSON.stringify(file));
+ return bytes.slice().buffer as ArrayBuffer;
+};
+
+const CHIME = { duration: 0.2, layers: [{ source: 'sine', freq: 880, decay: 0.05 }, { source: 'sine', freq: 1320, start: 0.05, decay: 0.05, pan: 0.4 }] };
+const TUNE = {
+ tempo: 120, key: 'A', scale: 'minor', loop: false,
+ instruments: { lead: { layers: [{ source: 'triangle', freq: 440, decay: 0.2 }] } },
+ patterns: { a: { bars: 1, div: 2, tracks: { lead: '1 . 3 . 5 . 1\' .' } } },
+ song: ['a'],
+};
+
+describe('an audio recipe', () => {
+ it('is a path that ends in .essound or .esmusic, whatever its case or its query', () => {
+ expect(isAudioRecipePath('assets/audio/step.essound')).toBe(true);
+ expect(isAudioRecipePath('assets/audio/Theme.ESMUSIC?v=3')).toBe(true);
+ expect(isAudioRecipePath('assets/audio/step.wav')).toBe(false);
+ expect(isAudioRecipePath('assets/audio/step.essound.wav')).toBe(false);
+ // And a clip to whatever loads it.
+ expect(getAddressableType('assets/audio/step.essound')).toBe('audio');
+ expect(getAddressableType('assets/audio/theme.esmusic')).toBe('audio');
+ });
+
+ it('is refused, saying what to import, where nothing makes recipes', async () => {
+ expect(hasAudioRecipeMaker()).toBe(false);
+ await expect(renderAudioRecipe('a.essound', project({ 'a.essound': CHIME }))).rejects.toThrow(/import 'esengine\/sound'/);
+ });
+
+ it('is made into the .wav its source bakes to', async () => {
+ installAudioRecipes();
+ const wav = await renderAudioRecipe('assets/chime.essound', project({ 'assets/chime.essound': CHIME }));
+ const baked = encodeWav(renderSound(validateSoundSource(CHIME)));
+ expect(new Uint8Array(wav)).toEqual(baked);
+ const read = decodeWav(new Uint8Array(wav));
+ expect(read.rate).toBe(44100);
+ expect(read.channels.length).toBe(2);
+ expect(read.seconds).toBeCloseTo(0.2, 2);
+ expect(audioRecipeStats().made).toBe(1);
+ });
+
+ it('is a piece of music as much as a sound', async () => {
+ installAudioRecipes();
+ const wav = await renderAudioRecipe('assets/tune.esmusic', project({ 'assets/tune.esmusic': TUNE }));
+ const baked = renderMusic(validateMusicSource(TUNE));
+ expect(new Uint8Array(wav)).toEqual(encodeWav({ rate: baked.rate, channels: baked.channels }));
+ });
+
+ it('reads the recordings its source plays, and is another clip when one of them changes', async () => {
+ installAudioRecipes();
+ const tick = encodeWav(renderSound(validateSoundSource({ duration: 0.05, layers: [{ source: 'impulse', width: 0.001 }] })));
+ const source = { duration: 0.2, layers: [{ source: 'sample', file: 'assets/tick.wav' }] };
+ const wav = await renderAudioRecipe('assets/played.essound', project({ 'assets/played.essound': source, 'assets/tick.wav': tick }));
+ expect(decodeWav(new Uint8Array(wav)).peak).toBeGreaterThan(0.1);
+ const text = JSON.stringify(source);
+ const one = audioRecipeCacheKey(text, new Map([['assets/tick.wav', tick.slice().buffer as ArrayBuffer]]));
+ const other = audioRecipeCacheKey(text, new Map([['assets/tick.wav', new Uint8Array([1, 2, 3]).buffer as ArrayBuffer]]));
+ expect(one).not.toBe(other);
+ expect(one.startsWith(`estella:audio-recipe:${SOUND_RENDER_REVISION}:`)).toBe(true);
+ });
+
+ // A clip made by an earlier run is kept under the revision: if the same source comes out as other samples, the revision has
+ // to change with it, or the old clip is played for the new. This is the same source, held to the samples it makes today.
+ it('comes out as the same samples until SOUND_RENDER_REVISION says otherwise', () => {
+ const wav = encodeWav(renderSound(validateSoundSource(CHIME)));
+ expect({ revision: SOUND_RENDER_REVISION, bytes: wav.byteLength, digest: contentHashHex(wav) }).toMatchInlineSnapshot(`
+ {
+ "bytes": 35324,
+ "digest": "4083f3064656b38c",
+ "revision": "1",
+ }
+ `);
+ });
+});
+
+describe('the audio layer', () => {
+ it('hands a clip that is a recipe to its backend as the bytes of a .wav', async () => {
+ installAudioRecipes();
+ const loaded: { src: string; bytes: Uint8Array }[] = [];
+ const backend = {
+ name: 'test', delivery: 'bytes',
+ initialize: async () => {}, ensureResumed: async () => {},
+ loadBuffer: vi.fn(async () => { throw new Error('a recipe is not fetched as a recording'); }),
+ loadBufferFromData: vi.fn(async (src: string, data: ArrayBuffer) => { loaded.push({ src, bytes: new Uint8Array(data.slice(0)) }); return { id: 1, duration: 0.2 }; }),
+ unloadBuffer: () => {}, play: () => ({ id: 1 }), suspend: () => {}, resume: () => {}, dispose: () => {},
+ } as unknown as PlatformAudioBackend;
+ const files: Record<string, Uint8Array> = { 'assets/chime.essound': encodeUtf8(JSON.stringify(CHIME)) };
+ setPlatform({ readFile: async (path: string) => {
+ const file = files[path];
+ if (!file) throw new Error(`there is no file at ${path}`);
+ return file.slice().buffer as ArrayBuffer;
+ } } as unknown as PlatformAdapter);
+ const audio = new AudioAPI(backend);
+ await audio.preload('assets/chime.essound');
+ expect(backend.loadBuffer).not.toHaveBeenCalled();
+ expect(loaded.length).toBe(1);
+ expect(loaded[0]!.bytes).toEqual(encodeWav(renderSound(validateSoundSource(CHIME))));
+ expect(audio.getBufferHandle('assets/chime.essound')).toBeTruthy();
+ });
+});
diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjs
index 68cf7b489..436027e1b 100644
--- a/tools/apiSubsystems.mjs
+++ b/tools/apiSubsystems.mjs
@@ -356,6 +356,16 @@ export const SUBSYSTEMS = [
whyZh: '配方在设备上画出来的像素与烘焙好的图片逐像素一致,已在无头游戏里检查过;它在工作线程上画一次,之后从内容缓存读取,已在浏览器里两次打开检查过,文字、人物、铺入的图片和表面贴图都在内;但没有在手机上计过时,不指定字体文件时文字跟随设备字体,地形把配方当图层读只有测试检查过、没在游戏里检查过',
entry: ['renderImage', 'validateImageSource'],
},
+ {
+ id: 'sound',
+ title: 'Audio recipes',
+ titleZh: '音频配方',
+ source: ['sound'],
+ tier: 'experimental',
+ why: 'a clip named by its source is made on the device by the code the editor bakes it with, on a worker, and read from the content cache after; checked in a headless game for a sound and a piece of music, and heard by nobody yet on a phone or in a mini-game',
+ whyZh: '以源文件命名的音频片段在设备上用编辑器烘焙时的同一份代码生成,在工作线程上完成,之后从内容缓存读取;已在无头游戏里对一个音效和一段音乐做过检查,还没有人在手机或小游戏里听过',
+ entry: ['renderSound', 'renderMusic'],
+ },
{
id: 'rig2d',
title: '2D rigs',
diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.js
index 9fff5cd4e..0b52c9c5d 100644
--- a/tools/assetMetaTable.js
+++ b/tools/assetMetaTable.js
@@ -35,6 +35,8 @@ export const EXT_TO_TYPE = Object.freeze({
'.ktx2': 'texture',
// A picture's source, drawn into a texture where it is loaded (sdk asset/textureRecipe.ts).
'.esimage': 'imageSource',
+ '.essound': 'soundSource',
+ '.esmusic': 'musicSource',
// Audio
'.wav': 'audio',
'.mp3': 'audio',
diff --git a/tools/check-entry-boots.mjs b/tools/check-entry-boots.mjs
index 84eeaedb5..253ae546d 100644
--- a/tools/check-entry-boots.mjs
+++ b/tools/check-entry-boots.mjs
@@ -156,6 +156,9 @@ const RECIPE_DRAWER = 'has no canvas to draw text on';
for (const c of [
{ name: 'lean', imports: [], installed: false },
{ name: 'lean+image', imports: ['esengine/image'], installed: true },
+ // The same for a clip made from its source: esengine/sound, whose words these are.
+ { name: 'lean+sound', imports: ['esengine/sound'], installed: true, words: 'a recipe plays .wav recordings only', what: 'maker of audio recipes' },
+ { name: 'lean without sound', imports: [], installed: false, words: 'a recipe plays .wav recordings only', what: 'maker of audio recipes' },
]) {
const src = path.join(work, `recipes-${c.name.replace(/\W+/g, '-')}.mjs`);
const out = `${src}.bundle.mjs`;
@@ -164,11 +167,11 @@ for (const c of [
entryPoints: [src], outfile: out, bundle: true, format: 'esm', platform: 'node', logLevel: 'silent',
alias: { 'esengine/lean': path.join(SDK, 'dist/index.lean.js') },
});
- const carried = readFileSync(out, 'utf8').includes(RECIPE_DRAWER);
+ const carried = readFileSync(out, 'utf8').includes(c.words ?? RECIPE_DRAWER);
if (carried !== c.installed) {
- fail(`${c.name}: the drawer of texture recipes ${c.installed ? 'should be installed' : 'should be absent'}, `
+ fail(`${c.name}: the ${c.what ?? 'drawer of texture recipes'} ${c.installed ? 'should be installed' : 'should be absent'}, `
+ `but the bundle ${carried ? 'carries' : 'lacks'} it.`
- + '\n\nesengine/image installs it with a call at the end of image/index.ts, which the build puts in a shared chunk:'
+ + '\n\nThe subpath installs it with a call at the end of its index.ts, which the build puts in a shared chunk:'
+ ' list that chunk in sdk/package.json "sideEffects".');
}
results.push(`${c.name} recipes → ${c.installed ? 'installed' : 'absent'}`);
diff --git a/tools/lib/sdkProgram.mjs b/tools/lib/sdkProgram.mjs
index d36c6fdd4..ddf4062c5 100644
--- a/tools/lib/sdkProgram.mjs
+++ b/tools/lib/sdkProgram.mjs
@@ -70,6 +70,7 @@ export const ENTRIES = {
'water': 'src/water/index.ts',
'spline': 'src/spline/index.ts',
'image': 'src/image/index.ts',
+ 'sound': 'src/sound/index.ts',
'voxel': 'src/voxel/index.ts',
'rig2d': 'src/rig2d/entry.ts',
'imported-scene': 'src/imported-scene/index.ts',
diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.js
index 298649463..a4db39474 100644
--- a/tools/nativeScriptModules.js
+++ b/tools/nativeScriptModules.js
@@ -75,6 +75,7 @@ export const MODULES = {
'esengine/worldgen': { disposition: 'native-subpath' },
'esengine/water': { disposition: 'native-subpath' },
'esengine/image': { disposition: 'native-subpath' },
+ 'esengine/sound': { disposition: 'native-subpath' },
'esengine/spline': { disposition: 'native-subpath' },
'esengine/voxel': { disposition: 'native-subpath' },
'esengine/rig2d': { disposition: 'native-subpath' },
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index e86078692..e35e476b9 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4750,4 +4750,14 @@ export const NOTED = {
{"note": "A shot through cover."},
"feat(editor): the shooting-physics check aims at an animated character's bones, shoots through a wall and hangs two weights on ropes rated either side of their load":
{"note": "Telling the parts of a character apart."},
+ "fix(assets): an empty asset path is no asset, and is asked for by nobody - an empty string in a handle field went to the resolver, came back still a string, was written back as one and asked for the same load again without end; a field of plants whose material had been cleared put it on every cell it grew and the packaged game stopped answering; a path nothing resolves keeps its placeholder":
+ {"note": "A cleared asset field no longer stops a game."},
+ "fix(image): a package that ships texture recipes can draw them - esengine/image installs its drawer with a call that the build puts in a chunk the native entry shares, the chunk was not listed as having side effects, and a bundler dropped the whole of it: an export drew its ground and its walls with no texture; the chunk is listed, and the boot check bundles a consumer that imports the subpath and looks for the drawer":
+ {"note": "A package that ships texture recipes draws them."},
+ "fix(playable): a playable imports the module an asset needs and its entry does not carry - the whole entry installs what a scene can name and not esengine/image, which only a texture recipe asks for, so a playable shipped its recipes and drew none of them; the modules its cooked assets name are imported before the host, and one with no recipe carries no drawer":
+ {"note": "A package that ships texture recipes draws them."},
+ "feat(image): a picture made in the editor is named by its recipe - image_write answers the .esimage as ref and as the texture of meshRenderer, and the material it writes names its maps as recipes, so a game ships layers and not pixels (a project of six textures packaged 2.4 MB lighter); the .png is pngRef. The Play realm imports esengine/image, as the edit realm does: a scene naming a recipe played with no texture":
+ {"note": "A picture made in the editor is named by its recipe."},
+ "feat(audio): a sound or a piece of music can ship as its recipe - an .essound or .esmusic named where a clip goes is carried as its source and made on the device when it loads, by the synthesis the editor bakes it with, on a worker and kept in the content cache; a game of five clips packaged 1.7 MB lighter":
+ {"note": "A sound or a piece of music can ship as its recipe."},
};