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.

perf(audio): a piece of music is made in less than half the time - a note's sample loop asked for an exponential and a sine again every sample and read each pitch, loudness and filter corner through a curve; what does not change is worked out before the loop, a decay is a product kept up sample by sample and a ringing mode a point carried round a circle: a minute of music in 2.4 s where it took 5.3, two samples in five million off by one step of sixteen bits

yhhebd6b11d89aa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 476ff3e3f..af61215db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,7 +28,7 @@ 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 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 minute of music after 4 s, the first time only (the music is made at about twenty times the speed it plays). 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
diff --git a/sdk/src/sound/index.ts b/sdk/src/sound/index.ts
index 8954c0b2d..60823a218 100644
--- a/sdk/src/sound/index.ts
+++ b/sdk/src/sound/index.ts
@@ -23,7 +23,7 @@ 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';
+export const SOUND_RENDER_REVISION = '2';
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. */
diff --git a/sdk/src/sound/soundRender.ts b/sdk/src/sound/soundRender.ts
index 5161a9a5a..8e0794376 100644
--- a/sdk/src/sound/soundRender.ts
+++ b/sdk/src/sound/soundRender.ts
@@ -166,69 +166,125 @@ function recordingBody(recording: SoundRecording, count: number, rate: number, s
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 }));
+ const kind = layer.source;
// 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 [attack, release] = [layer.attack ?? (kind === '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;
+ const noise = kind === 'noise' ? noiseBody(layer, count, rate, seed, pitch)
+ : kind === '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];
+ const spike = kind === 'impulse' ? (layer.width ?? 0.0002) * rate : 0;
+
+ // This loop is all the time a piece of music takes to make: a note is one pass of it for each layer of its instrument. So what
+ // does not change from one sample to the next is worked out before it. A pitch, a loudness or a corner written as one number
+ // is one number; a decay is a product kept up sample by sample, and a ringing mode a point carried round a circle, where each
+ // was an exponential and a sine asked for again every sample.
+ const freq = layer.freq, gain = layer.gain;
+ const freqMoves = typeof freq === 'object', gainMoves = typeof gain === 'object';
+ const hzStill = (freqMoves ? 440 : freq ?? 440) * pitch;
+ const levelStill = gainMoves ? 1 : gain ?? 1;
+ const vibrato = layer.vibrato, tremolo = layer.tremolo, fm = layer.fm, tail = layer.tail;
+ const stepStill = Math.min(0.49, hzStill / rate);
+ const fmIndex = fm?.index;
+ const fmMoves = typeof fmIndex === 'object';
+ const fmStill = fmMoves ? 0 : fmIndex ?? 0;
+ const width = layer.width ?? 0.5;
+
+ const filters = layer.filters ?? [];
+ const corners = filters.length;
+ const runs: Biquad[] = [];
+ const moving: boolean[] = [];
+ for (const f of filters) {
+ const run = new Biquad(f.type, f.q ?? 0.7, rate, f.gain ?? 0);
+ const moves = typeof f.freq === 'object';
+ // A noise struck at another pitch has no pitch of its own to move, so its filters move instead.
+ if (!moves) run.tune((f.freq as number | undefined ?? 1000) * (noise ? pitch : 1));
+ runs.push(run);
+ moving.push(moves);
+ }
+
+ // exp(-t / decay) at this sample, and what takes it to the next.
+ const decays = !!layer.decay;
+ const fastBy = decays ? Math.exp(-1 / (layer.decay! * rate)) : 1;
+ const slowBy = decays && tail ? Math.exp(-1 / (tail.decay * rate)) : 1;
+ let fast = 1, slow = 1;
+ // A mode: how loud it is now, the point on the circle its sine is read from, and the turn and the fading a sample makes.
+ let modes = 0;
+ let modeLoud: Float64Array | null = null, modeFade: Float64Array | null = null;
+ let modeCos: Float64Array | null = null, modeSin: Float64Array | null = null, turnCos: Float64Array | null = null, turnSin: Float64Array | null = null;
+ if (kind === 'modes') {
+ const heard = layer.modes!.filter(([hz]) => hz * pitch < rate * 0.48);
+ modes = heard.length;
+ modeLoud = new Float64Array(modes); modeFade = new Float64Array(modes);
+ modeCos = new Float64Array(modes); modeSin = new Float64Array(modes);
+ turnCos = new Float64Array(modes); turnSin = new Float64Array(modes);
+ heard.forEach(([hz, loud, dies], i) => {
+ const turn = (TAU * hz * pitch) / rate;
+ modeLoud![i] = loud; modeFade![i] = Math.exp(-1 / (dies * rate));
+ modeCos![i] = 1; modeSin![i] = 0;
+ turnCos![i] = Math.cos(turn); turnSin![i] = Math.sin(turn);
+ });
+ }
+
+ 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') {
+ else if (kind === 'impulse') {
const b = n / spike;
v = b < 10 ? (1 - b) * Math.exp(-b) : 0;
- } else if (layer.source === 'modes') {
+ } else if (kind === '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);
+ for (let i = 0; i < modes; i++) {
+ const c = modeCos![i]!, s = modeSin![i]!;
+ v += modeLoud![i]! * s;
+ modeLoud![i] = modeLoud![i]! * modeFade![i]!;
+ modeCos![i] = c * turnCos![i]! - s * turnSin![i]!;
+ modeSin![i] = s * turnCos![i]! + c * turnSin![i]!;
}
} 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);
+ let step = stepStill;
+ if (freqMoves || vibrato) {
+ let hz = freqMoves ? curveAt(freq, t, 440, true) * pitch : hzStill;
+ if (vibrato) hz *= Math.pow(2, (vibrato.depth * Math.sin(TAU * vibrato.rate * t)) / 12);
+ 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 (fm) {
+ bend += step * fm.ratio;
if (bend >= 1) bend -= Math.floor(bend);
- at = phase + (curveAt(layer.fm.index, t, 0, false) * Math.sin(TAU * bend)) / TAU;
+ at = phase + ((fmMoves ? curveAt(fmIndex, t, 0, false) : fmStill) * 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);
- }
+ if (kind === 'sine') v = Math.sin(TAU * at);
+ else if (kind === 'triangle') v = 1 - 4 * Math.abs(at - 0.5);
+ else if (kind === 'saw') v = 2 * at - 1 - (fm ? 0 : polyBlep(at, step));
+ else {
+ v = at < width ? 1 : -1;
+ if (!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);
+ for (let i = 0; i < corners; i++) {
+ const run = runs[i]!;
+ // A corner that moves is read every 16 samples: often enough for a sweep, seldom enough to cost little.
+ if (moving[i] && (n & 15) === 0) run.tune(curveAt(filters[i]!.freq, t, 1000, true) * (noise ? pitch : 1));
+ v = 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;
+ let level = gainMoves ? curveAt(gain, t, 1, false) : levelStill;
+ if (decays) {
+ level *= tail ? fast * (1 - tail.mix) + slow * tail.mix : fast;
+ fast *= fastBy;
+ slow *= slowBy;
}
- if (layer.tremolo) level *= 1 - layer.tremolo.depth * (0.5 + 0.5 * Math.sin(TAU * layer.tremolo.rate * t));
+ if (tremolo) level *= 1 - tremolo.depth * (0.5 + 0.5 * Math.sin(TAU * 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);
diff --git a/sdk/src/sound/soundWorkerBundle.generated.ts b/sdk/src/sound/soundWorkerBundle.generated.ts
index 961510ee2..249ebcabe 100644
--- a/sdk/src/sound/soundWorkerBundle.generated.ts
+++ b/sdk/src/sound/soundWorkerBundle.generated.ts
@@ -2,4 +2,4 @@
// 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})({});";
+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.source,[l,u]=[e.attack??(c===`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=c===`noise`?ee(e,o,n,i,r):c===`sample`?te(a,o,n,(e.speed??1)*r,e.from??0):null,h=c===`impulse`?(e.width??2e-4)*n:0,g=e.freq,_=e.gain,v=typeof g==`object`,y=typeof _==`object`,b=(v?440:g??440)*r,x=y?1:_??1,S=e.vibrato,C=e.tremolo,w=e.fm,T=e.tail,E=Math.min(.49,b/n),D=w?.index,O=typeof D==`object`,k=O?0:D??0,A=e.width??.5,j=e.filters??[],M=j.length,N=[],P=[];for(let e of j){let t=new V(e.type,e.q??.7,n,e.gain??0),i=typeof e.freq==`object`;i||t.tune((e.freq??1e3)*(m?r:1)),N.push(t),P.push(i)}let F=!!e.decay,L=F?Math.exp(-1/(e.decay*n)):1,z=F&&T?Math.exp(-1/(T.decay*n)):1,H=1,U=1,W=0,G=null,K=null,q=null,J=null,Y=null,X=null;if(c===`modes`){let t=e.modes.filter(([e])=>e*r<n*.48);W=t.length,G=new Float64Array(W),K=new Float64Array(W),q=new Float64Array(W),J=new Float64Array(W),Y=new Float64Array(W),X=new Float64Array(W),t.forEach(([e,t,i],a)=>{let o=I*e*r/n;G[a]=t,K[a]=Math.exp(-1/(i*n)),q[a]=1,J[a]=0,Y[a]=Math.cos(o),X[a]=Math.sin(o)})}let[Z,Q]=[0,0];for(let e=0;e<o;e++){let i=e/n,a;if(m)a=m[e];else if(c===`impulse`){let t=e/h;a=t<10?(1-t)*Math.exp(-t):0}else if(c===`modes`){a=0;for(let e=0;e<W;e++){let t=q[e],n=J[e];a+=G[e]*n,G[e]=G[e]*K[e],q[e]=t*Y[e]-n*X[e],J[e]=n*Y[e]+t*X[e]}}else{let e=E;if(v||S){let t=v?R(g,i,440,!0)*r:b;S&&(t*=2**(S.depth*Math.sin(I*S.rate*i)/12)),e=Math.min(.49,t/n)}Z+=e,Z>=1&&(Z-=Math.floor(Z));let t=Z;w&&(Q+=e*w.ratio,Q>=1&&(Q-=Math.floor(Q)),t=Z+(O?R(D,i,0,!1):k)*Math.sin(I*Q)/I,t-=Math.floor(t)),c===`sine`?a=Math.sin(I*t):c===`triangle`?a=1-4*Math.abs(t-.5):c===`saw`?a=2*t-1-(w?0:B(t,e)):(a=t<A?1:-1,w||(a+=B(t,e)-B((t-A+1)%1,e)))}for(let t=0;t<M;t++){let n=N[t];P[t]&&!(e&15)&&n.tune(R(j[t].freq,i,1e3,!0)*(m?r:1)),a=n.run(a)}d>0&&(a=Math.tanh(a*f)/p);let o=y?R(_,i,1,!1):x;F&&(o*=T?H*(1-T.mix)+U*T.mix:H,H*=L,U*=z),C&&(o*=1-C.depth*(.5+.5*Math.sin(I*C.rate*i))),l>0&&i<l&&(o*=i/l);let V=t-i;u>0&&V<u&&(o*=Math.max(0,V/u)),s[e]=a*o}return s}function W(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 G(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 K(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 q(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=K(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=K(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=W(n,G(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 J(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 Y(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 X(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 Y(a,u)}let Z=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`],Q=e=>`${Z[(e%12+12)%12]}${Math.floor(e/12)-1}`;function ne(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 re(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=ne(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 ie(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=>ie(e,t))):e.length??t;return(e.start??0)+n+r}function ae(e,t,n,r=0){return e.source===`group`?{...e,layers:e.layers.map(e=>ae(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 oe={soft:-1,normal:0,loud:1};function se(e,t,n,r){let i=e.samples,a=e=>oe[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 ce(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)$(e,`lowpass`,c.cutoff,a);return x}function le(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 $(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 ue(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 de(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 fe(e,t={}){let n=re(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=ce(e,n,o,i.midi,u,r,t,l),c.set(d,f)),!f){let e=n.release??.08,t=n.layers.map(t=>ae(t,u,e,l));f=q({duration:Math.min(8,Math.max(.02,...t.map(t=>ie(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=se(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&&$(e,`highpass`,n.lowcut,r),n.highcut&&$(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=>de(G(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=ue(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&&$(t,`lowshelf`,110,r,e.master.low),e.master.high&&$(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=le(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 pe=e=>/\\.esmusic(\\?|$)/i.test(e);function me(e){let t;try{t=JSON.parse(e.source)}catch{throw Error(`${e.path} is not JSON`)}return pe(e.path)?{music:P(t)}:{sound:m(t)}}function he(e,t){let n=me({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 ge(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=X(new Uint8Array(r));t[n]={rate:i.rate,channels:i.channels}}let n=me(e),r=`sound`in n?q(n.sound,0,{given:t}):fe(n.music,t),i=J({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=ge(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=ge,e.soundNeeds=he,e})({});";
diff --git a/sdk/tests/audio-recipe.test.ts b/sdk/tests/audio-recipe.test.ts
index 6cada9d15..db1e4be99 100644
--- a/sdk/tests/audio-recipe.test.ts
+++ b/sdk/tests/audio-recipe.test.ts
@@ -93,7 +93,7 @@ describe('an audio recipe', () => {
{
"bytes": 35324,
"digest": "4083f3064656b38c",
- "revision": "1",
+ "revision": "2",
}
`);
});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index af1c5369e..e361fb56c 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4762,4 +4762,6 @@ export const NOTED = {
{"note": "A sound or a piece of music can ship as its recipe."},
"feat(audio): a sound made in the editor is named by its source - sound_write answers the .essound as ref (the .wav is wavRef) and music_write adds recipeRef beside the .wav, with what each costs; the edit realm and the Play realm import esengine/sound, so a clip named by its source plays in the editor as it does in a package":
{"note": "A sound or a piece of music can ship as its recipe."},
+ "perf(audio): a piece of music is made in less than half the time - a note's sample loop asked for an exponential and a sine again every sample and read each pitch, loudness and filter corner through a curve; what does not change is worked out before the loop, a decay is a product kept up sample by sample and a ringing mode a point carried round a circle: a minute of music in 2.4 s where it took 5.3, two samples in five million off by one step of sixteen bits":
+ {"note": "A sound or a piece of music can ship as its recipe."},
};