Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.
TypeScript agent-skillsanimationcanvasclaude-codeclaude-pluginclaude-skillscodex-plugincreative-codecreative-codingcreative-toolsdeterministicgenerative-arthand-drawnillustrationlaunch-videomotion-designmotion-graphicspluginprocedural-generationskill
sound effects: version 2 defaults, physical models, new typing and notification
Alex Greenshpun6ea095fbcb20
diff --git a/skills/anidoodle/engine/SFX_VERSIONING.md b/skills/anidoodle/engine/SFX_VERSIONING.mdnew file mode 100644index 0000000..f4f0af6--- /dev/null+++ b/skills/anidoodle/engine/SFX_VERSIONING.md@@ -0,0 +1,7 @@+# Sound effect versions++Unversioned plans use the original shipped renderer for original kinds. For new plans, set `sfxVersion: 2` on the `SfxPlan` object in the example in `../references/music/sound-design.md`, or on a `renderSfx` call. A cue can override its plan version.++Version 2 selects physical models for toggle-on, toggle-off, whoosh-short, whoosh-long and impact. Click, pop, pop-in, dark-riser, cut-hit and sub-drop retain their original models. Notification defaults to `drop` and typing to `real`. The `bar` and `glass` notification variants and `mech`, `laptop` and `soft` typing variants remain available; `typing:old` selects the legacy key tick.++`legacy: true` selects the original renderer and `legacy: false` selects physical models where available. The `old` and `new` variants select the original and physical models for supported kinds.diff --git a/skills/anidoodle/engine/package.json b/skills/anidoodle/engine/package.jsonindex b28d952..fb66575 100644--- a/skills/anidoodle/engine/package.json+++ b/skills/anidoodle/engine/package.json@@ -9,7 +9,7 @@"gate": "node tools/gate.mjs","emit": "node tools/emit.mjs","render": "node tools/render.mjs",- "test": "node tools/test.mjs"+ "test": "node tools/test.mjs && node tools/sfx-audit-unit.mjs && node tools/sfx-physics-unit.mjs && node tools/sfx-models-unit.mjs && node tools/sfx-typing-real-unit.mjs && node tools/sfx-legacy-unit.mjs"},"dependencies": {"esbuild": "0.25.12",diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfx.ts b/skills/anidoodle/engine/src/canvas-core/music/sfx.tsindex cb24977..7ada391 100644--- a/skills/anidoodle/engine/src/canvas-core/music/sfx.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/sfx.ts@@ -3,3 +3,5 @@export { SFX, SFX_KINDS, sfxVariants, sfxInfo, sfxDuckDb, renderSfx, validateSfx, sfxNeeds, parseKey, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";export { placeSfx, sfxDuck, sfxAudibility, sfxHarshness, SFX_HARSH_CAPS, mixSfx, assertSfxAudible, filmSfx, validateSfxPlan, resolveSfxPlan, type SfxCue, type SfxPlan, type SfxSnap, type PlacedCue, type SfxAudibility, type SfxHarshOptions, type SfxHarshness, type SfxMix } from "./sfxMix";export { type SfxStereo } from "./sfxCore";+export { auditSfx, hasRisingGlide, type SfxAudit } from "./sfxAudit";+export { kWeight, winLufs } from "./sfxCore";diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxAudit.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxAudit.tsnew file mode 100644index 0000000..22711ea--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxAudit.ts@@ -0,0 +1,79 @@+// Sample-level checks for a raw take. Run before any fade or trimming can hide a cut.+export type SfxAudit = { ok: boolean; failures: string[]; peak: number };+export const rerollTake = <T>(seed: number, render: (seed: number) => T, audit: (take: T) => SfxAudit): T => {+ let failures: string[] = [];+ for (let attempt = 0; attempt <= 3; attempt++) {+ const take = render((seed + 1000 * attempt) >>> 0), result = audit(take);+ if (result.ok) return take;+ failures = result.failures;+ }+ throw new Error(`sfx: failed audit after 4 takes: ${failures.join(", ")}`);+};++/** Detect coherent rising tones over 50 ms; noisy air does not have a stable period. */+export const hasRisingGlide = (samples: ArrayLike<number>, sr: number): boolean => {+ const hop = Math.max(1, Math.round(sr * 0.01)), size = Math.max(2, Math.round(sr * 0.02)), freqs: number[] = [];+ for (let start = 0; start + size <= samples.length; start += hop) {+ let best = 0, lagBest = 0, previous = -1, previousLag = 0, rising = false;+ for (let lag = Math.max(2, Math.floor(sr / 3500)); lag <= Math.min(Math.floor(sr / 100), size >> 1); lag++) {+ let ab = 0, aa = 0, bb = 0;+ for (let i = 0; i < size - lag; i += 2) { const a = samples[start + i], b = samples[start + i + lag]; ab += a * b; aa += a * a; bb += b * b; }+ const corr = ab / Math.sqrt(Math.max(aa * bb, 1e-30));+ if (rising && corr < previous && previous > 0.8) { best = previous; lagBest = previousLag; break; }+ rising = corr > previous; previous = corr; previousLag = lag;+ }+ freqs.push(best > 0.8 ? sr / lagBest : 0);+ }+ for (let i = 0; i + 5 < freqs.length; i++) {+ const part = freqs.slice(i, i + 6);+ if (part.every((f, j) => f > 0 && (!j || f >= part[j - 1] * 0.98)) && part[5] / part[0] > Math.pow(2, 4 / 12)) return true;+ }+ return false;+};++export const auditSfx = (channels: readonly ArrayLike<number>[], sr: number, whip = false): SfxAudit => {+ if (!Number.isFinite(sr) || sr <= 0 || !channels.length || !channels[0].length || channels.some(c => c.length !== channels[0].length))+ throw new Error("sfx audit: expected equal, nonempty channels and a positive sample rate");+ const n = channels[0].length, failures: string[] = [];+ let peak = 0, invalid = false;+ for (const c of channels) for (let i = 0; i < n; i++) {+ if (!Number.isFinite(c[i])) invalid = true;+ else peak = Math.max(peak, Math.abs(c[i]));+ }+ if (invalid) failures.push("non-finite samples");+ if (whip && hasRisingGlide(channels[0], sr)) failures.push("rising glide");+ if (peak < 0.001) failures.push("silence"); // -60 dBFS+ if (!peak) return { ok: false, failures, peak };+ const edgeLimit = peak * 0.01; // -40 dB relative to peak+ if (channels.some(c => Math.abs(c[0]) > edgeLimit || Math.abs(c[n - 1]) > edgeLimit)) failures.push("edge");+ if (channels.some(c => { let sum = 0; for (let i = 0; i < n; i++) sum += c[i]; return Math.abs(sum / n) > edgeLimit; })) failures.push("dc");+ // Compare each second difference to its local 10 ms RMS, excluding the sample under test.+ // This catches an isolated discontinuity without treating a high-frequency tone as a click.+ const radius = Math.max(2, Math.round(sr * 0.005));+ let click = false;+ for (const c of channels) {+ const prefix = new Float64Array(n + 1);+ for (let i = 1; i < n - 1; i++) { const d = c[i + 1] - 2 * c[i] + c[i - 1]; prefix[i + 1] = d * d; }+ for (let i = 1; i <= n; i++) prefix[i] += prefix[i - 1];+ for (let i = 1; i < n - 1 && !click; i++) {+ const d = c[i + 1] - 2 * c[i] + c[i - 1], a = Math.max(1, i - radius), b = Math.min(n - 1, i + radius + 1);+ const rms = Math.sqrt(Math.max(0, prefix[b] - prefix[a] - d * d) / Math.max(1, b - a - 1));+ // Very brief physical contacts have a legitimate broadband onset. Require a+ // large sample excursion as well as an unusual second derivative.+ if (Math.abs(c[i]) > peak * 0.5 && Math.abs(d) > peak * 0.5 && Math.abs(d) > rms * Math.pow(10, 18 / 20)) click = true;+ }+ }+ if (click) failures.push("second-difference click");+ const tail = Math.max(1, Math.round(sr * 0.005));+ let tailPeak = 0;+ for (const c of channels) for (let i = Math.max(0, n - tail); i < n; i++) tailPeak = Math.max(tailPeak, Math.abs(c[i]));+ if (tailPeak > peak * Math.pow(10, -45 / 20)) failures.push("truncated tail");+ let first = n, last = -1;+ for (let i = 0; i < n; i++) if (channels.some(c => c[i] !== 0)) { first = Math.min(first, i); last = i; }+ let gap = 0; const gapLimit = Math.max(1, Math.ceil(sr * 0.002));+ for (let i = first; i <= last; i++) {+ gap = channels.every(c => c[i] === 0) ? gap + 1 : 0;+ if (gap >= gapLimit) { failures.push("digital silence gap"); break; }+ }+ return { ok: failures.length === 0, failures, peak };+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxKit.tsindex b62e963..cc168c4 100644--- a/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts@@ -7,6 +7,9 @@ import { pcOf } from "./theory";import { clamp, db, type Rng } from "./dsp";import { Bus, modal, chirp, burst, white, pink, filt, sweep, shape, ad, smooth, finish, secs, buf, kWeight, winLufs, speakingWindow, type Mode, type SfxStereo } from "./sfxCore";import { smallRoom } from "./roomSmall";+import { makePhysics, type PhysicsKind } from "./sfxPhysics";+import { typingModels, typingReal, notificationModels } from "./sfxModels";+import { auditSfx, rerollTake } from "./sfxAudit";/*** The space every sound sits in: a diffused small room (roomSmall.ts: dense early reflections and a@@ -38,6 +41,10 @@ const punch = (b: Bus, amt: number) => {export type SfxOpts = {/** per-hit variation: same seed, same samples; a different seed, a different (but same-family) hit. */seed?: number; variant?: string;+ /** Select the original renderer for existing sounds and archived films. */+ legacy?: boolean;+ /** Version 2 selects per-kind models; omitted keeps shipped sounds. */+ sfxVersion?: 2;/** transpose in semitones (-24..24). */pitch?: number;/** length for sustained kinds (scratch, riser, whoosh, paper, thread); riser may use beats instead. */@@ -50,6 +57,10 @@ export type SfxOpts = {gainDb?: number;};export type SfxSound = { L: Float32Array; R: Float32Array; sr: number; kind: SfxKind; variant: string; seed: number;+ /** The model produced non-finite samples before output conditioning. */+ rawInvalid?: boolean;+ /** Level before the deliberate end gate, relative to the model peak. */+ fadeStartDb?: number;/** sample index of the sync point (the hit, the pass-by, the end of a riser): this lands on the cue frame. */hit: number;/** [a, b) samples where the sound speaks (used for ducking and the audibility check). */@@ -534,9 +545,16 @@ const tap: Def = {},};-export const SFX = { tick, press, pop, ink, scratch, paper, whoosh, swish, riser, impact, chime, bubble, brick, thread, tap } as const;+const physicalDef = (kind: PhysicsKind, level = -16): Def => ({ variants: kind === "typing" ? ["default", "mech", "laptop", "soft", "real", "old", "new"] : kind === "notification" ? ["default", "bar", "glass", "drop", "old", "new"] : ["default", "old", "new"], level, duckDb: 0, use: `Physical ${kind}`, make(c, v) {+ if (kind === "typing" && v === "real") return typingReal(c.o.seed ?? 1, c.o.lengthS ?? 1.3, c.sr);+ if (kind === "typing" && ["mech", "laptop", "soft"].includes(v)) return typingModels(v, c.o.seed ?? 1, c.o.lengthS ?? 1.3, c.sr);+ if (kind === "notification" && ["bar", "glass", "drop"].includes(v)) return notificationModels(v, c.o.seed ?? 1, (c.key ? keyHz(c, 5) : 659.255) * Math.pow(2, (c.o.pitch ?? 0) / 12), c.sr);+ return makePhysics(kind, { seed: c.o.seed, lengthS: c.o.lengthS, pitch: c.o.pitch, keyHz: c.key ? keyHz(c, 1) : undefined, dir: c.o.dir }, c.sr);+} });+export const SFX = { tick, press, pop, ink, scratch, paper, whoosh, swish, riser, impact, chime, bubble, brick, thread, tap,+ click: physicalDef("click"), "pop-in": physicalDef("pop-in"), "whoosh-short": physicalDef("whoosh-short"), "whoosh-long": physicalDef("whoosh-long"), "dark-riser": physicalDef("dark-riser"), "cut-hit": physicalDef("cut-hit"), "sub-drop": physicalDef("sub-drop"), typing: physicalDef("typing"), notification: physicalDef("notification"), "toggle-on": physicalDef("toggle-on"), "toggle-off": physicalDef("toggle-off") } as const;/** Per-variant level (LUFS over the speaking window) where a kind's variants differ a lot in weight. */-const VARIANT_LEVEL: Partial<Record<string, number>> = { "tap:tickHi": -22, "tap:tock": -18, "tap:thump": -14, "tap:impact": -10 };+const VARIANT_LEVEL: Partial<Record<string, number>> = { "tap:tickHi": -22, "tap:tock": -18, "tap:thump": -14, "tap:impact": -10, "typing:laptop": -19 };const VARIANT_DUCK: Partial<Record<string, number>> = { "tap:thump": 1.5, "tap:impact": 6 };export type SfxKind = keyof typeof SFX;export const SFX_KINDS = Object.keys(SFX) as SfxKind[];@@ -557,8 +575,10 @@ const checkRange = (name: string, x: unknown, lo: number, hi: number) => { if (xexport const validateSfx = (kind: string, o: SfxOpts = {}) => {if (!(kind in SFX)) throw new Error(`sfx: unknown kind "${kind}" (kinds: ${SFX_KINDS.join(", ")})`);const d = SFX[kind as SfxKind];- if (o.variant !== undefined && !d.variants.includes(o.variant)) throw new Error(`sfx: ${kind} has no variant "${o.variant}" (variants: ${d.variants.join(", ")})`);+ if (o.variant !== undefined && !d.variants.includes(o.variant) && !(["pop", "whoosh", "riser", "impact"].includes(kind) && (o.variant === "old" || o.variant === "new"))) throw new Error(`sfx: ${kind} has no variant "${o.variant}" (variants: ${d.variants.join(", ")})`);if (o.seed !== undefined) checkSeed(o.seed);+ if (o.legacy !== undefined && typeof o.legacy !== "boolean") throw new Error("sfx: legacy must be boolean");+ if (o.sfxVersion !== undefined && o.sfxVersion !== 2) throw new Error("sfx: sfxVersion must be 2");checkRange("pitch", o.pitch, -24, 24); checkRange("lengthS", o.lengthS, 0.05, 30); checkRange("beats", o.beats, 0.25, 64); checkRange("bpm", o.bpm, 20, 300); checkRange("gainDb", o.gainDb, -60, 24);if (o.dir !== undefined && o.dir !== 1 && o.dir !== -1) throw new Error(`sfx: dir must be 1 or -1, got ${String(o.dir)}`);if (o.key !== undefined) parseKey(o.key);@@ -576,7 +596,7 @@ export const sfxNeeds = (kind: SfxKind, variant: string, o: SfxOpts = {}) => ({* Render one sound. Pure in (kind, opts, sr). The level is calibrated: the kind's target loudness* over its speaking window, +-1 dB of per-seed variation, + opts.gainDb; sample peak capped at -1 dBFS.*/-export const renderSfx = (kind: SfxKind, o: SfxOpts = {}, sr = 48000): SfxSound => {+const renderOnce = (kind: SfxKind, o: SfxOpts = {}, sr = 48000): SfxSound => {validateSfx(kind, o);if (!Number.isSafeInteger(sr) || sr < 22050 || sr > 192000) throw new Error(`sfx: sample rate must be an integer 22050..192000, got ${sr}`);const d = SFX[kind], variant = o.variant ?? d.variants[0], seed = o.seed ?? 1, r = mkRng((seed ^ 0x5f3759df) >>> 0);@@ -585,13 +605,56 @@ export const renderSfx = (kind: SfxKind, o: SfxOpts = {}, sr = 48000): SfxSoundif (need.bpm && o.bpm === undefined) throw new Error(`sfx: ${kind}:${variant} is tempo-synced and needs a bpm (opts.bpm, or in a plan: plan.bpm or plan.score); there is no default tempo`);const wobble = need.key ? 1 : 1 + (r() * 2 - 1) * 0.03; // +-3 % per trigger: a repeat never clones (never on a tuned sound)const c: Ctx = { sr, r, P: Math.pow(2, (o.pitch ?? 0) / 12) * wobble, o, dir: o.dir ?? 1, key: o.key === undefined ? null : parseKey(o.key), bpm: o.bpm ?? NaN, j: (x, amt) => x * (1 + (r() * 2 - 1) * amt) };- const made = d.make(c, variant), [L, R] = finish(made.bus, made.hit);+ const mapping: Partial<Record<SfxKind, PhysicsKind>> = { pop: "pop", whoosh: variant === "fast" ? "whoosh-short" : "whoosh-long", riser: "dark-riser", impact: "impact" };+ const selected = o.legacy === false || (o.legacy !== true && o.sfxVersion === 2 && kind === "impact");+ const physical = selected && mapping[kind];+ const made = physical ? makePhysics(physical, { seed, lengthS: kind === "riser" ? (o.lengthS ?? ((o.beats ?? 4) * 60) / c.bpm) : o.lengthS, pitch: o.pitch, keyHz: c.key ? keyHz(c, 1) : undefined, dir: o.dir }, sr) : d.make(c, variant);+ const rawInvalid = [made.bus.L, made.bus.R].some(channel => channel.some(sample => !Number.isFinite(sample)));+ let [L, R] = finish(made.bus, made.hit);+ if ((kind === "typing" && ["mech", "laptop", "soft", "real"].includes(variant)) || (kind === "notification" && ["bar", "glass", "drop"].includes(variant))) {+ const size = secs(sr, kind === "typing" ? (o.lengthS ?? 1.3) : 0.7);+ const left = new Float32Array(size), right = new Float32Array(size);+ left.set(L.subarray(0, size)); right.set(R.subarray(0, size)); L = left; R = right;+ }+ if (selected && (kind === "whoosh" || kind === "whoosh-short" || kind === "whoosh-long")) {+ const w = Math.round(sr * 0.005); let sum = 0, best = 0, pos = made.hit;+ for (let i = 0; i < L.length; i++) { sum += L[i] ** 2 + R[i] ** 2; if (i >= w) sum -= L[i - w] ** 2 + R[i - w] ** 2; if (sum > best) { best = sum; pos = i - Math.floor(w / 2); } }+ made.hit = pos;+ }const kL = kWeight(L, sr), kR = kWeight(R, sr), window = speakingWindow(kL, kR, sr), now = winLufs(kL, kR, window[0], window[1]);let g = (VARIANT_LEVEL[`${kind}:${variant}`] ?? d.level) + (r() * 2 - 1) + (o.gainDb ?? 0) - now;let peak = 0; for (let i = 0; i < L.length; i++) peak = Math.max(peak, Math.abs(L[i]), Math.abs(R[i]));g = Math.min(g, -1 - 20 * Math.log10(Math.max(peak, 1e-9)));const G = db(g); for (let i = 0; i < L.length; i++) { L[i] *= G; R[i] *= G; }- return { L, R, sr, kind, variant, seed, hit: Math.min(made.hit, L.length - 1), window, lufs: now + g };+ return { L, R, sr, kind, variant, seed, hit: Math.min(made.hit, L.length - 1), window, lufs: now + g, ...(rawInvalid ? { rawInvalid } : {}), ...("fadeStartDb" in made ? { fadeStartDb: made.fadeStartDb as number } : {}) };+};++/** Original takes remain available exactly; physical takes are audited and re-rolled deterministically. */+export const renderSfx = (kind: SfxKind, o: SfxOpts = {}, sr = 48000): SfxSound => {+ if ((o.variant === "old" || o.variant === "new") && ["pop", "whoosh", "riser", "impact"].includes(kind)) {+ const variant = o.variant;+ const sound = renderSfx(kind, { ...o, variant: undefined, legacy: variant === "old" }, sr);+ return { ...sound, variant };+ }+ validateSfx(kind, o);+ const added = ["click", "pop-in", "whoosh-short", "whoosh-long", "dark-riser", "cut-hit", "sub-drop", "typing", "notification", "toggle-on", "toggle-off"];+ const old: Partial<Record<SfxKind, [SfxKind, string]>> = { click: ["tick", "ui"], "pop-in": ["pop", "cork"], "whoosh-short": ["whoosh", "fast"], "whoosh-long": ["whoosh", "soft"], "dark-riser": ["riser", "soft"], "cut-hit": ["tap", "impact"], "sub-drop": ["impact", "soft"], typing: ["tick", "key"], notification: ["chime", "bell"], "toggle-on": ["press", "soft"], "toggle-off": ["press", "soft"] };+ const defaultPhysical = ["whoosh-short", "whoosh-long", "toggle-on", "toggle-off"];+ if (added.includes(kind) && (o.variant === "old" || (o.variant === undefined || o.variant === "default") && (o.legacy === true || (o.legacy !== false && (!o.sfxVersion || !defaultPhysical.includes(kind)) && kind !== "typing" && kind !== "notification")))) {+ const [k, v] = old[kind]!;+ return renderSfx(k, { ...o, variant: v, legacy: true }, sr);+ }+ if (o.sfxVersion === 2 && o.legacy === undefined && (o.variant === undefined || o.variant === "default") && kind === "notification") o = { ...o, variant: "drop" };+ if (o.sfxVersion === 2 && o.legacy === undefined && (o.variant === undefined || o.variant === "default") && kind === "typing") o = { ...o, variant: "real" };+ const physical = added.includes(kind) || ((o.legacy === false || (o.legacy !== true && o.sfxVersion === 2 && kind === "impact")) && ["pop", "whoosh", "riser", "impact"].includes(kind));+ if (!physical) return renderOnce(kind, o, sr);+ return rerollTake(o.seed ?? 1, seed => renderOnce(kind, { ...o, seed }, sr), take => {+ const result = auditSfx([take.L, take.R], sr, kind === "whoosh-short" || (kind === "whoosh" && variantIsWhip(o.variant)));+ if (take.rawInvalid) result.failures.push("non-finite model samples");+ if (!["riser", "dark-riser"].includes(kind) && take.fadeStartDb !== undefined && take.fadeStartDb > -12) result.failures.push("truncated before gate");+ result.ok = result.failures.length === 0; return result;+ });};+const variantIsWhip = (variant?: string) => variant === "fast";export type { SfxStereo };diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxMix.tsindex 5270ab2..015197b 100644--- a/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts@@ -26,6 +26,10 @@ export type SfxCue = SfxOpts & {};export type SfxPlan = {fps: number; frames: number; cues: SfxCue[];+ /** Keep archived plans on the original effect models. */+ legacy?: boolean;+ /** Set on newly authored plans to select version 2 effects. */+ sfxVersion?: 2;/** seeds every cue that has no seed of its own; per-cue seeds depend on (kind, frame), not on list order. */seed?: number;/** tempo grid: bpm, the time of beat 1 in seconds (beatZeroS), beats per bar. */@@ -85,6 +89,8 @@ export const validateSfxPlan = (plan: SfxPlan) => {const p = resolveSfxPlan(plan);if (!Number.isSafeInteger(p.fps) || p.fps <= 0) throw new Error(`sfx plan: fps must be a positive integer, got ${String(p.fps)}`);if (!Number.isSafeInteger(p.frames) || p.frames <= 0) throw new Error(`sfx plan: frames must be a positive integer, got ${String(p.frames)}`);+ if (p.legacy !== undefined && typeof p.legacy !== "boolean") throw new Error("sfx plan: legacy must be boolean");+ if (p.sfxVersion !== undefined && p.sfxVersion !== 2) throw new Error("sfx plan: sfxVersion must be 2");if (p.seed !== undefined && (!Number.isSafeInteger(p.seed) || p.seed < 0 || p.seed > 0xffffffff)) throw new Error(`sfx plan: seed must be an integer 0..4294967295, got ${String(p.seed)}`);if (p.bpm !== undefined && (!Number.isFinite(p.bpm) || p.bpm < 20 || p.bpm > 300)) throw new Error(`sfx plan: bpm must be 20..300, got ${String(p.bpm)}`);if (p.minDb !== undefined && !Number.isFinite(p.minDb)) throw new Error("sfx plan: minDb must be a finite number");@@ -106,7 +112,7 @@ export const validateSfxPlan = (plan: SfxPlan) => {if (need.bpm && o.bpm === undefined) throw new Error(`sfx plan: ${name(c, i)} is tempo-synced: set plan.bpm, cue.bpm, or plan.score (the film's piece); there is no default tempo`);});};-const optsOf = (p: SfxPlan, c: SfxCue, seed: number): SfxOpts => ({ seed: c.seed ?? seed, variant: c.variant, pitch: c.pitch, lengthS: c.lengthS, beats: c.beats, bpm: c.bpm ?? p.bpm, key: c.key ?? p.key, dir: c.dir, gainDb: c.gainDb });+const optsOf = (p: SfxPlan, c: SfxCue, seed: number): SfxOpts => ({ seed: c.seed ?? seed, legacy: c.legacy ?? p.legacy, sfxVersion: c.sfxVersion ?? p.sfxVersion, variant: c.variant, pitch: c.pitch, lengthS: c.lengthS, beats: c.beats, bpm: c.bpm ?? p.bpm, key: c.key ?? p.key, dir: c.dir, gainDb: c.gainDb });/** Render and place every cue. Throws if a cue's pre-roll (whoosh approach, riser build) would start before 0. */export const placeSfx = (plan: SfxPlan, sr: number): PlacedCue[] => {diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxModels.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxModels.tsnew file mode 100644index 0000000..02f0cf0--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxModels.ts@@ -0,0 +1,87 @@+import { rng } from '../core';+import { Biquad } from './dsp';+import { Bus, buf, filt, secs, white } from './sfxCore';+import { smallRoom } from './roomSmall';++const tau = 2 * Math.PI;+/** Stable physical properties for each key, independent of take seed. */+export const keyProperties = (key: number) => {+ const r = rng((key + 1) * 739391);+ return { bands: [180, 420, 900, 2200].map(f => f * (0.93 + 0.14 * r())), gain: Math.pow(10, (r() * 4 - 2) / 20) };+};+/** Low-profile key: a short contact and damped case, followed by a lighter release. */+export const typingReal = (seed: number, length: number, sr: number) => {+ const r = rng(seed), bus = new Bus(sr, secs(sr, length + .2));+ let at = .015, count = 0;+ while (at < Math.max(.016, length - .16)) {+ const space = count % (4 + Math.floor(r() * 5)) === 3;+ const velocity = Math.pow(10, (r() * 20 - 10) / 20), pan = (r() - .5) * .16;+ const hit = (time: number, gain: number, decay: number) => {+ const a = white(r, secs(sr, .2));+ filt(a, sr, { hp: 120, lp: 4800 });+ for (let i = 0; i < a.length; i++) a[i] *= (Math.exp(-i / sr / decay) + .04 * Math.exp(-i / sr / .033)) * Math.min(1, i / (sr * .002));+ bus.add(a, secs(sr, time), gain * velocity, pan);+ };+ hit(at, space ? .8 : 1, .006 + r() * .003);+ hit(at + .045 + r() * .055, .28 + r() * .18, .003 + r() * .003);+ at += (space ? .20 : .09) + r() * (space ? .14 : .12) + (count % 13 === 12 ? .2 + r() * .2 : 0);+ count++;+ }+ const ambience = white(r, bus.n);+ filt(ambience, sr, { hp: 200, lp: 6000 });+ bus.add(ambience, 0, .0012);+ if (length <= .176) for (const c of [bus.L, bus.R]) {+ const end = secs(sr, length), fade = secs(sr, Math.min(.035, length / 2));+ for (let i = Math.max(0, end - fade); i < c.length; i++) c[i] *= i >= end ? 0 : Math.pow(.5 + .5 * Math.cos(Math.PI * (i - (end - fade)) / fade), 3);+ }+ return {bus, hit: 0};+};+export const typingModels = (variant: string, seed: number, length: number, sr: number) => {+ const r = rng(seed), n = secs(sr, length + .2), bus = new Bus(sr, n), laptop = variant === 'laptop', soft = variant === 'soft';+ let at = 0, count = 0, word = 3 + Math.floor(r() * 6), pos = 0;+ while (at < Math.max(.001, length - .15)) {+ const space = pos === word, key = space ? 29 : Math.floor(r() * 29), props = keyProperties(key), pan = space ? 0 : ((key % 10) / 9 - .5) * .3;+ const velocity = Math.pow(10, ((r() * 6 - 3) + (pos === 0 ? 1 : 0)) / 20) * props.gain * (laptop ? .708 : 1);+ const event = (when: number, bright: number, gain: number, decayScale: number) => {+ const size = secs(sr, .16), source = white(r, size), sig = buf(size);+ for (let j = 0; j < 4; j++) {+ const b = source.slice(), f = props.bands[j] * (space ? .7 : 1) * (soft ? .85 : 1) * (laptop ? 1.5 : 1) * bright;+ filt(b, sr, { bp: f, q: 3 });+ const decay = (space ? .045 : laptop ? [.015,.013,.010,.008][j] : [.035,.028,.021,.015][j]) * decayScale;+ for (let i = 0; i < size; i++) sig[i] += b[i] * Math.exp(-i / sr / decay) * [650,30,2,.25][j];+ }+ bus.add(sig, secs(sr, when), gain * velocity, pan);+ return sig;+ };+ const bottom = at + (soft ? 0 : .003);+ const body = event(bottom, 1, 1, 1);+ if (!soft) { const c = white(r, secs(sr, .004)); filt(c, sr, { hp: 2000, lp: 5000 }); let ce=0,be=0; for (let i=0;i<c.length;i++) { c[i] *= Math.sin(Math.PI*i/c.length); ce+=c[i]*c[i]; be+=body[i]*body[i]; } bus.add(c, secs(sr, at), Math.sqrt(be/Math.max(ce,1e-30))*.2*velocity, pan); }+ if (!laptop) event(bottom + .055 + .065*r(), 1.45, .32, .4);+ if (space) { event(bottom+.007, 1.4, .08, .25); event(bottom+.015, 1.4, .07, .25); }+ count++; pos++;+ let gap: number;+ if (space) { gap = .18 + .14*r(); pos=0; word=3+Math.floor(r()*6); }+ else { const z = Math.sqrt(-2*Math.log(Math.max(r(),1e-8))) * Math.cos(tau*r()); gap = Math.max(.07,Math.min(.19,.115*Math.exp(.28*z))); }+ at += count % 12 === 0 ? .4 + .3*r() : gap;+ }+ for (const c of [bus.L,bus.R]) { const hp=Biquad.make(sr,'hp',70,.707), lp=Biquad.make(sr,'lp',9000,.707); for(let i=0;i<n;i++) c[i]=lp.tick(hp.tick(c[i])); }+ const l=bus.L.slice(), rr=bus.R.slice(), delay=secs(sr,.004); for(let i=delay;i<n;i++){bus.L[i]+=l[i-delay]*.158;bus.R[i]+=rr[i-delay]*.158;}+ const wet=smallRoom(l,rr,sr,{rt60:.12,size:.4,er:.4,late:.4,predelay:.004,hp:200,lp:9000,damp:6500,seed}); bus.add2(wet[0],wet[1],0,.063);+ for (const c of [bus.L, bus.R]) {+ const end = secs(sr, length), fade = secs(sr, Math.min(.035, length / 2));+ for (let i = Math.max(0, end - fade); i < n; i++) c[i] *= i >= end ? 0 : Math.pow(.5 + .5 * Math.cos(Math.PI * (i - (end - fade)) / fade), 3);+ }+ return {bus,hit:0};+};+export const notificationModels = (variant: string, seed: number, root: number, sr: number) => {+ const r=rng(seed), n=secs(sr,.7), bus=new Bus(sr,n), a=buf(n);+ const note=(start:number,f:number,gain:number, ratios:number[], decay:number, attack:number) => {+ for(let i=secs(sr,start);i<n;i++){const t=i/sr-start, rise=Math.min(1,t/attack), env=(.5-.5*Math.cos(Math.PI*rise))*Math.exp(-t/decay); for(let j=0;j<ratios.length;j++) a[i]+=gain*env*Math.sin(tau*f*ratios[j]*t)/(1+j*2)*Math.exp(-t*(variant==='bar' && j ? 3 : j/.8)/decay);}+ };+ if(variant==='bar'){note(0,root,1,[1,3.9,9.2],.035,.005);note(.075,root*1.25,.794,[1,3.9,9.2],.035,.005);}+ else if(variant==='glass'){note(0,root-.4,.5,[1,2.32,4.25,6.63],.5,.0015);note(0,root+.4,.5,[1],.5,.0015);const tap=white(r,secs(sr,.0015));filt(tap,sr,{bp:4000,q:2});for(let i=0;i<tap.length;i++) a[i]+=tap[i]*3*Math.sin(Math.PI*i/tap.length);}+ else {let phase=0;for(let i=0;i<secs(sr,.06);i++){const t=i/sr;phase+=tau*root*(1+.6*t/.06)/sr;a[i]+=Math.sin(phase)*Math.sin(Math.PI*Math.min(1,t/.003)/2)*Math.exp(-t/.012);} const tick=white(r,secs(sr,.001));for(let i=0;i<tick.length;i++)a[i]+=tick[i]*.05*Math.sin(Math.PI*i/tick.length);}+ // End the finite render smoothly after the model has decayed.+ for(let i=0;i<n;i++){const t=i/sr; a[i]*=Math.min(1,Math.max(0,(.7-t)/.1));}+ bus.add(a); return {bus,hit:0};+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxPhysics.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxPhysics.tsnew file mode 100644index 0000000..c910529--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxPhysics.ts@@ -0,0 +1,101 @@+import { rng } from "../core";+import { SVF, Biquad } from "./dsp";+import { Bus, buf, secs, filt, pink, white } from "./sfxCore";+import { smallRoom } from "./roomSmall";++export type PhysicsKind = "click" | "pop" | "pop-in" | "whoosh-short" | "whoosh-long" | "dark-riser" | "impact" | "cut-hit" | "sub-drop" | "typing" | "notification" | "toggle-on" | "toggle-off";+export const PHYSICS_KINDS: PhysicsKind[] = ["click", "pop", "pop-in", "whoosh-short", "whoosh-long", "dark-riser", "impact", "cut-hit", "sub-drop", "typing", "notification", "toggle-on", "toggle-off"];+export type PhysicsOptions = { seed?: number; lengthS?: number; pitch?: number; keyHz?: number; dir?: 1 | -1 };+const tau = Math.PI * 2;+const env = (t: number, attack: number, hold: number, decay: number) => t < 0 ? 0 : t < attack ? (1 - Math.cos(Math.PI * t / attack)) / 2 : t < attack + hold ? 1 : Math.exp(-(t - attack - hold) / decay);+// Raised-cosine contact force drives second-order damped resonators.+const strike = (sr: number, n: number, f: number, ratios: number[], decay: number, contact: number, r: () => number) => {+ const out = buf(n), count = Math.max(2, secs(sr, contact));+ for (let k = 0; k < ratios.length; k++) {+ const freq = f * ratios[k] * (1 + (r() - 0.5) * 0.006), rad = Math.exp(-1 / (sr * decay / Math.sqrt(ratios[k]))), a = 2 * rad * Math.cos(tau * freq / sr), b = rad * rad;+ let y1 = 0, y2 = 0;+ for (let i = 0; i < n; i++) { const force = i < count ? (1 - Math.cos(tau * i / count)) / count : 0; const y = a * y1 - b * y2 + force; y2 = y1; y1 = y; out[i] += y / (1 + k * 0.9); }+ }+ return out;+};+const room = (bus: Bus, input: Float64Array, seed: number, mix = 0.08) => {+ const [l, r] = smallRoom(input, input, bus.sr, { rt60: 0.22, size: 0.4, er: 0.55, late: 0.55, predelay: 0.004, hp: 600, lp: 9500, damp: 6500, seed });+ bus.add2(l, r, 0, mix);+};+const click = (bus: Bus, at: number, sr: number, r: () => number, freq = 2200, gain = 1) => {+ const n = secs(sr, 0.065), snap = white(r, n), grit = white(r, n);+ filt(snap, sr, { hp: 2500, lp: 11000 }); filt(grit, sr, { bp: 4600, q: 0.8 });+ for (let i = 0; i < n; i++) { const t = i / sr; snap[i] *= env(t, 0.0002, 0, 0.0006); grit[i] *= env(t, 0.0003, 0, 0.002); }+ const tink = strike(sr, n, freq, [1, 1.62, 2.16], 0.005, 0.0003, r), body = strike(sr, n, 550, [1, 1.7], 0.009, 0.001, r);+ const transient = buf(n); for (let i = 0; i < n; i++) transient[i] = snap[i] * 0.4 + grit[i] * 0.1;+ bus.add(transient, at, gain); bus.add(tink, at, gain * 0.5); bus.add(body, at, gain * 0.1);+ return transient;+};+export const makePhysics = (kind: PhysicsKind, options: PhysicsOptions, sr: number) => {+ const seed = options.seed ?? 1, r = rng(seed), pitch = Math.pow(2, (options.pitch ?? 0) / 12), length = options.lengthS ?? (kind === "whoosh-short" ? 0.55 : kind === "whoosh-long" ? 1.2 : kind === "dark-riser" ? 2 : kind === "typing" ? 1.3 : kind === "impact" ? 3.8 : kind === "sub-drop" ? 1.5 : kind === "pop" ? 0.16 : 0.3);+ const n = secs(sr, length + (kind.startsWith("whoosh") ? 0.45 : kind === "typing" ? 0.2 : 0)); const bus = new Bus(sr, n); let hit = 0;+ if (kind === "click" || kind.startsWith("toggle")) {+ const t = click(bus, 0, sr, r); room(bus, t, seed);+ if (kind.startsWith("toggle")) click(bus, secs(sr, 0.052), sr, r, 2200 * (kind === "toggle-on" ? 1.15 : 1 / 1.15), 0.7);+ for (const channel of [bus.L, bus.R]) { const hp = Biquad.make(sr, "hp", 200, 0.707), dip = Biquad.make(sr, "peak", 3200, 1, -3); for (let i = 0; i < n; i++) channel[i] = dip.tick(hp.tick(channel[i])); }+ } else if (kind === "typing") {+ let at = 0, previous = -1;+ while (at < length - 0.14) { let key = Math.floor(r() * 12); if (key === previous) key = (key + 1) % 12; previous = key;+ click(bus, secs(sr, at), sr, r, 1800 + key * 105, 0.65 + r() * 0.25);+ bus.add(strike(sr, secs(sr, 0.055), 1050 + key * 37, [1, 1.23, 1.57, 1.93, 2.35, 2.82, 3.34], 0.0045, 0.000076, r), secs(sr, at), 0.13);+ bus.add(strike(sr, secs(sr, 0.09), 120 + key * 9, [1, 1.8], 0.018, 0.000076, r), secs(sr, at + 0.02), 0.15);+ bus.add(strike(sr, secs(sr, 0.06), 9000, [1], 0.001, 0.000076, r), secs(sr, at + 0.003), 0.008);+ click(bus, secs(sr, at + 0.07 + r() * 0.04), sr, r, 2900 + key * 70, 0.12); at += 0.062 + r() * 0.086;+ }+ const floor = pink(r, n); for (let i = 0; i < n; i++) floor[i] *= 0.0006 * Math.min(1, i / (sr * 0.005)); bus.add(floor);+ } else if (kind === "pop" || kind === "pop-in") {+ const a = buf(n), breath = pink(r, n); let phase = 0;+ filt(breath, sr, { bp: kind === "pop" ? 620 : 1800, q: 0.8 });+ // A 30 ms lead gives the UI cue its measured onset while hit still marks picture sync.+ if (kind === "pop") hit = secs(sr, 0.033);+ for (let i = 0; i < n; i++) { const t = i / sr - (kind === "pop" ? 0.03 : 0); if (t < 0) continue; const e = env(t, kind === "pop" ? 0.024 : 0.004, kind === "pop" ? 0.015 : 0, kind === "pop" ? 0.041 : 0.045);+ const f = kind === "pop" ? 370 * Math.pow(2, 0.7 / 12 * Math.exp(-t / 0.0075)) : 108 * (1 + 0.35 * Math.exp(-t / 0.025)); phase += tau * f * pitch / sr;+ a[i] = e * (Math.sin(phase) + (kind === "pop" ? 0.57 * Math.sin(2 * phase) + 0.35 * Math.sin(3 * phase) + 0.12 * Math.sin(1.72 * phase) : 0)) + breath[i] * e * 0.2 + Math.sin(tau * 129 * t) * env(t, 0.005, 0, 0.025) * 0.16;+ }+ filt(a, sr, { hp: 112, lp: 3500 }); bus.add(a);+ if (kind === "pop-in") click(bus, 0, sr, r, 3500, 0.18);+ } else if (kind.startsWith("whoosh")) {+ const N = secs(sr, length), apex = length * 0.48, source = pink(r, N), sig = buf(N), fs = [new SVF(sr), new SVF(sr), new SVF(sr)], lp = new SVF(sr); hit = secs(sr, apex);+ for (let i = 0; i < N; i++) { const t = i / sr, d = t < apex ? -30 * Math.pow((apex - t) / apex, 0.7) : -30 * Math.pow((t - apex) / (length - apex), 1.3), amp = Math.pow(10, d / 20), wake = t > apex ? Math.pow(2, -0.6 * (1 - Math.exp(-(t - apex) / 0.25))) : 1;+ const f = 420 * (0.35 + 2.5 * Math.sqrt(amp)) * wake * Math.pow(2, -0.35 * Math.tanh((t - apex) / 0.06)); let x = 0;+ for (let j = 0; j < 3; j++) { fs[j].set(f * [1, 1.6, 2.5][j], 1); fs[j].tick(source[i]); x += fs[j].bp / (1 + j); }+ lp.set(f * 4, 0.7); lp.tick(x); sig[i] = lp.lp * amp * Math.min(1, i / (sr * 0.008)) * Math.min(1, (N - i - 1) / (sr * 0.015));+ }+ bus.add(sig, 0, 1, i => (options.dir ?? 1) * 0.06 * Math.tanh((i / sr - apex) / 0.06)); room(bus, sig, seed, 0.06);+ } else if (kind === "dark-riser") {+ const N = secs(sr, length), noise = pink(r, N), sig = buf(N), sv = new SVF(sr, 150, 1); hit = N;+ for (let i = 0; i < N; i++) { const t = i / sr, u = t / length, amp = Math.pow(10, -42 * Math.pow(1 - u, 1.4) / 20); sv.set(150 + 350 * u, 1); sv.tick(noise[i]);+ const back = length - 0.03 - t, phase = tau * (20 * back - 6 * back * back / Math.max(0.001, 0.3 * length - 0.03)); const depth = Math.min(1, Math.max(0, (u - 0.7) * length / 0.02)); const gate = u < 0.7 || back <= 0 ? 1 : 1 - depth * (0.5 - 0.5 * Math.cos(phase));+ sig[i] = amp * (sv.bp + 0.28 * Math.sin(tau * 48 * t)) * gate * Math.min(1, (N - 1 - i) / (sr * 0.025)); }+ bus.add(sig);+ } else if (kind === "impact" || kind === "cut-hit" || kind === "sub-drop") {+ const a = buf(n), noise = pink(r, n); filt(noise, sr, { lp: 140 }); let ph = 0; const root = (options.keyHz ?? 44) * pitch;+ let kickPhase = 0;+ for (let i = 0; i < n; i++) { const t = i / sr, f = kind === "sub-drop" ? root * (1 + 0.45 * Math.exp(-t / 0.75)) : 46 + (kind === "cut-hit" ? 179 : 94) * Math.exp(-t / 0.048); ph += tau * f / sr;+ const e = env(t, 0.003, kind === "sub-drop" ? 0.15 : 0, kind === "sub-drop" ? 0.45 : 0.19); let v = Math.sin(ph) * e;+ if (kind === "cut-hit") { kickPhase += tau * (93 + 82 * Math.exp(-t / 0.04)) / sr; v += 0.5 * Math.sin(kickPhase) * env(t, 0.002, 0, 0.06); }+ if (kind === "sub-drop") for (let h = 2; h <= 6; h++) v += Math.sin(ph * h) * e * 0.23 / h;+ if (kind === "impact") v += noise[i] * 8 * env(t, 0.04, 3.0, 0.18);+ a[i] = v;+ }+ bus.add(a); if (kind !== "sub-drop") {+ bus.add(strike(sr, n, 140, [1, 1.59, 2.14, 2.30], 0.14, 0.001, r), 0, 0.08); click(bus, 0, sr, r, 2200, 0.25);+ if (kind === "impact") { const blast = pink(r, secs(sr, 0.35)); filt(blast, sr, { bp: 900, q: 0.8 }); for (let i = 0; i < blast.length; i++) blast[i] *= env(i / sr, 0.002, 0, 0.06); bus.add(blast, 0, 0.8); room(bus, blast, seed, 0.1); }+ }+ } else {+ const a = strike(sr, n, 1820 * pitch, [1, 3.42, 0.5], 0.14, 0.0003, r);+ for (let i = 0; i < n; i++) { const t = i / sr; a[i] *= (t < 0.032 ? 1 : 0.063 + 0.937 * Math.exp(-(t - 0.032) / 0.002)) * (1 + 0.08 * Math.sin(tau * 24 * t)); } bus.add(a);+ }+ // Fade the constructed end; the audit also examines the pre-fade level separately.+ const fade = Math.min(n, secs(sr, kind === "impact" ? 0.25 : kind === "pop" ? 0.025 : 0.035));+ let peak = 0, tail = 0;+ for (const channel of [bus.L, bus.R]) for (let i = 0; i < n; i++) { const x = Math.abs(channel[i]); peak = Math.max(peak, x); if (i >= Math.max(0, n - fade - secs(sr, 0.005)) && i < n - fade) tail = Math.max(tail, x); }+ const fadeStartDb = 20 * Math.log10(Math.max(tail, 1e-20) / Math.max(peak, 1e-20));+ for (const c of [bus.L, bus.R]) for (let i = 0; i < fade; i++) c[n - 1 - i] *= (1 - Math.cos(Math.PI * i / fade)) / 2;+ return { bus, hit, fadeStartDb };+};diff --git a/skills/anidoodle/engine/tools/sfx-audit-unit.mjs b/skills/anidoodle/engine/tools/sfx-audit-unit.mjsnew file mode 100644index 0000000..3e5724c--- /dev/null+++ b/skills/anidoodle/engine/tools/sfx-audit-unit.mjs@@ -0,0 +1,24 @@+import { strict as assert } from "node:assert";+import { build } from "esbuild";+const { outputFiles } = await build({ entryPoints: ["src/canvas-core/music/sfxAudit.ts"], bundle: true, write: false, format: "esm", platform: "neutral" });+const { auditSfx, hasRisingGlide, rerollTake } = await import("data:text/javascript;base64," + Buffer.from(outputFiles[0].text).toString("base64"));+const sr = 48000, n = sr / 2;+const clean = Float32Array.from({ length: n }, (_, i) => Math.sin(2 * Math.PI * 400 * i / sr) * Math.sin(Math.PI * i / n) ** 2);+const check = a => auditSfx([a, a], sr);+assert.deepEqual(check(clean).failures, []);+assert(check(new Float32Array(n)).failures.includes("silence"));+const edge = clean.slice(); edge[0] = 0.1; assert(check(edge).failures.includes("edge"));+const dc = clean.map(x => x + 0.02); assert(check(dc).failures.includes("dc"));+const cut = clean.slice(); cut[n - 100] = 0.3; assert(check(cut).failures.includes("truncated tail"));+const gap = clean.slice(); gap.fill(0, 5000, 5100); assert(check(gap).failures.includes("digital silence gap"));+const click = clean.slice(); click[8000] += 1; assert(check(click).failures.includes("second-difference click"));+assert.throws(() => auditSfx([clean, clean.slice(1)], sr), /equal/);+const glide = new Float32Array(sr / 5); let phase = 0;+for (let i = 0; i < glide.length; i++) { phase += 2 * Math.PI * (500 + 1000 * i / glide.length) / sr; glide[i] = Math.sin(phase); }+assert(hasRisingGlide(glide, sr));+assert(!hasRisingGlide(clean, sr));+assert.equal(hasRisingGlide(new Float32Array(4), 1), false);+const attempts=[]; const result=rerollTake(9, seed => { attempts.push(seed); return seed; }, seed => ({ok:seed===2009,failures:['test'],peak:1}));+assert.equal(result,2009); assert.deepEqual(attempts,[9,1009,2009]);+assert.throws(() => rerollTake(0, seed=>seed, () => ({ok:false,failures:['test'],peak:0})), /after 4 takes/);+console.log("sfx audit unit: 13 checks passed");diff --git a/skills/anidoodle/engine/tools/sfx-legacy-unit.mjs b/skills/anidoodle/engine/tools/sfx-legacy-unit.mjsnew file mode 100644index 0000000..76b05da--- /dev/null+++ b/skills/anidoodle/engine/tools/sfx-legacy-unit.mjs@@ -0,0 +1,13 @@+import { build } from 'esbuild';+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { resolve } from 'node:path';+const entry=resolve('src/canvas-core/music/sfxKit.ts');+const old=execFileSync('git',['show','cf5ccfc:skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts'],{encoding:'utf8'});+const bundle=async plugins=>{const {outputFiles}=await build({entryPoints:[entry],bundle:true,write:false,format:'esm',platform:'neutral',plugins});return import('data:text/javascript;base64,'+Buffer.from(outputFiles[0].text).toString('base64'));};+const original=await bundle([{name:'original',setup(b){b.onLoad({filter:/sfxKit\.ts$/},()=>({contents:old,loader:'ts',resolveDir:resolve('src/canvas-core/music')}));}}]);+const current=await bundle([]);+const hash=s=>createHash('sha256').update(Buffer.from(s.L.buffer)).update(Buffer.from(s.R.buffer)).digest('hex');+let count=0;+for(const kind of original.SFX_KINDS) for(const variant of original.sfxVariants(kind)) for(const seed of [1,11]) {const opts={variant,seed,key:'C',bpm:120};const a=original.renderSfx(kind,opts,48000),b=current.renderSfx(kind,opts,48000),c=current.renderSfx(kind,{...opts,legacy:true},48000);if(hash(a)!==hash(b)||hash(a)!==hash(c)||a.hit!==b.hit||a.hit!==c.hit)throw Error(`legacy changed ${kind}:${variant} seed ${seed}`);count++;}+console.log(`legacy: ${count} original takes bit-identical`);diff --git a/skills/anidoodle/engine/tools/sfx-models-unit.mjs b/skills/anidoodle/engine/tools/sfx-models-unit.mjsnew file mode 100644index 0000000..e2107f4--- /dev/null+++ b/skills/anidoodle/engine/tools/sfx-models-unit.mjs@@ -0,0 +1,39 @@+import { build } from 'esbuild';+import { strict as assert } from 'node:assert';+const bundle=async entry=>{const {outputFiles}=await build({entryPoints:[entry],bundle:true,write:false,format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(outputFiles[0].text).toString('base64'));};+const M=await bundle('src/canvas-core/music/index.ts'), K=await bundle('src/canvas-core/music/sfxModels.ts'), sr=48000;+assert.throws(() => M.validateSfxPlan({fps:30, frames:1, cues:[], sfxVersion:3}), /sfxVersion/);+assert.throws(() => M.validateSfxPlan({fps:30, frames:1, cues:[], legacy:'yes'}), /legacy/);+assert.throws(() => M.validateSfx('tick', {variant:'new'}), /no variant/);+assert.equal(M.renderSfx('notification', {sfxVersion:2, legacy:false, seed:1}, sr).variant, 'default');+assert.notEqual(Buffer.compare(Buffer.from(M.renderSfx('notification', {variant:'drop', seed:1, pitch:12}, sr).L.buffer), Buffer.from(M.renderSfx('notification', {variant:'drop', seed:1, pitch:0}, sr).L.buffer)), 0);+for (const variant of ['mech', 'laptop', 'soft', 'real']) for (const lengthS of [.05, .16]) assert.equal(M.renderSfx('typing', {variant, lengthS, seed:1}, sr).L.length, Math.round(sr*lengthS));+for (const seed of [1, 7, 4294967295]) {+ const typing = M.renderSfx('typing', {sfxVersion:2, seed}, sr);+ const real = M.renderSfx('typing', {variant:'real', seed}, sr);+ assert.equal(Buffer.compare(Buffer.from(typing.L.buffer), Buffer.from(real.L.buffer)), 0); assert.equal(Buffer.compare(Buffer.from(typing.R.buffer), Buffer.from(real.R.buffer)), 0); assert.equal(typing.hit, real.hit);+ const plan = {fps:30, frames:90, sfxVersion:2, cues:[{frame:30, kind:'typing', seed}]};+ assert.equal(Buffer.compare(Buffer.from(M.placeSfx(plan,sr)[0].sound.L.buffer), Buffer.from(real.L.buffer)), 0);+ const old = M.renderSfx('typing', {variant:'old', seed}, sr), tick = M.renderSfx('tick', {variant:'key', seed, legacy:true}, sr);+ assert.equal(Buffer.compare(Buffer.from(old.L.buffer), Buffer.from(tick.L.buffer)), 0);+ const notification = M.renderSfx('notification', {sfxVersion:2, seed, key:'E'}, sr);+ const drop = M.renderSfx('notification', {variant:'drop', seed, key:'E'}, sr);+ assert.equal(Buffer.compare(Buffer.from(notification.L.buffer), Buffer.from(drop.L.buffer)), 0); assert.equal(Buffer.compare(Buffer.from(notification.R.buffer), Buffer.from(drop.R.buffer)), 0);+}+assert.deepEqual(K.keyProperties(4),K.keyProperties(4)); assert.notDeepEqual(K.keyProperties(4),K.keyProperties(5));+for(const variant of ['mech','laptop','soft']){+ const takes=[1,2,3].map(seed=>M.renderSfx('typing',{variant,seed,lengthS:6},sr));+ for(const s of takes){const hz=M.centroid([s.L,s.R],sr).energyWeighted;assert(hz>=900&&hz<=2200,`${variant} centroid ${hz}`);assert(M.auditSfx([s.L,s.R],sr).ok);assert.equal(s.L.length,sr*6);}+ assert.notDeepEqual(takes[0].L,takes[1].L);assert.notDeepEqual(takes[1].L,takes[2].L);+}+for(const variant of ['bar','glass','drop']) for(const key of ['E','Am']){+ const s=M.renderSfx('notification',{variant,key,seed:1},sr);let peak=0,at=0;for(let i=0;i<s.L.length;i++)if(Math.abs(s.L[i])>peak){peak=Math.abs(s.L[i]);at=i;}+ assert(at/sr<=.008,`${variant} peak ${at/sr}`);assert(M.auditSfx([s.L,s.R],sr).ok);assert.equal(s.L.length,sr*.7);+ if(variant!=='drop')assert(!M.hasRisingGlide(s.L,sr),variant+' rising glide');+}+const base={fps:30,frames:300,key:'C',bpm:120,cues:[{frame:90,kind:'pop',variant:'pop',seed:1}]};+const unchanged=M.placeSfx(base,sr)[0].sound, old=M.renderSfx('pop',{variant:'pop',seed:1,key:'C',bpm:120,legacy:true},sr);+assert.deepEqual(unchanged.L,old.L,'unversioned plan uses shipped pop');+assert.deepEqual(M.placeSfx({...base,sfxVersion:2},sr)[0].sound.L,old.L,'v2 keeps old pop');+assert.notDeepEqual(M.renderSfx('pop',{variant:'new',seed:1,key:'C',bpm:120},sr).L,M.renderSfx('pop',{variant:'old',seed:1,key:'C',bpm:120},sr).L,'explicit old/new');+console.log('typing and notification: key map, varied typing, centroid, duration, audit, notification peak and glide pass');diff --git a/skills/anidoodle/engine/tools/sfx-physics-unit.mjs b/skills/anidoodle/engine/tools/sfx-physics-unit.mjsnew file mode 100644index 0000000..c6aeaee--- /dev/null+++ b/skills/anidoodle/engine/tools/sfx-physics-unit.mjs@@ -0,0 +1,10 @@+import { build } from 'esbuild';+import { strict as assert } from 'node:assert';+const {outputFiles}=await build({entryPoints:['src/canvas-core/music/index.ts'],bundle:true,write:false,format:'esm'});+const M=await import('data:text/javascript;base64,'+Buffer.from(outputFiles[0].text).toString('base64'));+const sr=48000, kinds=['click','pop','pop-in','whoosh-short','whoosh-long','dark-riser','impact','cut-hit','sub-drop','typing','notification','toggle-on','toggle-off'];+for(const kind of kinds){const opts={seed:1,key:'C',bpm:120,legacy:false};const a=M.renderSfx(kind,opts,sr),b=M.renderSfx(kind,opts,sr),c=M.renderSfx(kind,{...opts,seed:2},sr);assert.deepEqual(a.L,b.L,kind+' determinism');assert.notDeepEqual(a.L,c.L,kind+' seed variation');assert(M.auditSfx([a.L,a.R],sr).ok,kind+' audit');let lr=0,ll=0,rr=0;for(let i=0;i<a.L.length;i++){lr+=a.L[i]*a.R[i];ll+=a.L[i]**2;rr+=a.R[i]**2}assert(lr/Math.sqrt(ll*rr)>.9,kind+' correlation');}+const pop=M.renderSfx('pop',{seed:1,legacy:false},sr);assert(Math.abs(pop.L.length/sr-.16)<.01);const hz=M.centroid([pop.L,pop.R],sr).energyWeighted;assert(hz>500&&hz<750,`pop centroid ${hz}`);+const rms=(a,start,end)=>{let sum=0;for(let i=Math.round(start*sr);i<Math.round(end*sr);i++)sum+=a[i]**2;return Math.sqrt(sum/((end-start)*sr))};+const imp=M.renderSfx('impact',{variant:'boom',seed:1,key:'C',legacy:false},sr), roll=20*Math.log10(rms(imp.L,2,3)/rms(imp.L,0,.1));assert(roll >= -14 && roll <= -10, `impact roll ${roll} dB`);console.log('impact 2–3 s vs first 100 ms:',roll.toFixed(1),'dB');+console.log('physics: 13 kinds deterministic, varied, audited and correlated; pop duration and centroid pass');diff --git a/skills/anidoodle/engine/tools/sfx-typing-real-unit.mjs b/skills/anidoodle/engine/tools/sfx-typing-real-unit.mjsnew file mode 100644index 0000000..4d18e1a--- /dev/null+++ b/skills/anidoodle/engine/tools/sfx-typing-real-unit.mjs@@ -0,0 +1,30 @@+import { build } from 'esbuild';+import { strict as assert } from 'node:assert';++const {outputFiles}=await build({entryPoints:['src/canvas-core/music/index.ts'],bundle:true,write:false,format:'esm'});+const M=await import('data:text/javascript;base64,'+Buffer.from(outputFiles[0].text).toString('base64'));+const fftBundle=await build({entryPoints:['src/canvas-core/music/meter.ts'],bundle:true,write:false,format:'esm'});+const {fft}=await import('data:text/javascript;base64,'+Buffer.from(fftBundle.outputFiles[0].text).toString('base64'));+function measure(x){+ const hop=48, rms=[]; for(let i=0;i+hop<=x.length;i+=hop){let s=0;for(let j=0;j<hop;j++)s+=x[i+j]**2;rms.push(Math.sqrt(s/hop));}+ const peak=Math.max(...rms), candidates=[];for(let i=2;i<rms.length-2;i++)if(rms[i]>peak*.08&&rms[i]>=rms[i-1]&&rms[i]>rms[i+1]&&rms[i]>=rms[i-2]&&rms[i]>=rms[i+2])candidates.push(i);+ const events=[];for(const i of candidates){if(events.length&&i-events.at(-1)<70){if(rms[i]>rms[events.at(-1)])events[events.length-1]=i;}else events.push(i);}+ const q=(a,p)=>{if(!a.length)return null;a.sort((a,b)=>a-b);return +a[Math.floor((a.length-1)*p)].toFixed(2)};+ const decay30=[],decay45=[],rise=[],upDelay=[],upGap=[],levels=[],intervals=[],bands=[0,0,0,0,0], freqs=[80,300,1000,3000,8000,24000]; let power=0,weight=0;+ for(let k=0;k<events.length;k++){let p=events[k],v=rms[p], before=p;while(before>0&&p-before<30&&rms[before]>v*.1)before--;rise.push(p-before);levels.push(20*Math.log10(v/peak));if(k)intervals.push(p-events[k-1]);+ let end=Math.min(p+150,events[k+1]??rms.length);for(const [threshold,arr] of [[.03162,decay30],[.005623,decay45]]){let i=p+1;while(i<end&&rms[i]>v*threshold)i++;if(i<end)arr.push(i-p);}+ let sub=[];for(let i=p+20;i<Math.min(end,p+150)-2;i++)if(rms[i]>v*.02&&rms[i]>rms[i-1]&&rms[i]>=rms[i+1]&&rms[i]>rms[i-2]&&rms[i]>=rms[i+2])sub.push(i);if(sub.length){let u=sub.reduce((a,b)=>rms[a]>rms[b]?a:b);upDelay.push(u-p);upGap.push(20*Math.log10(rms[u]/v));}+ const N=2048,re=new Float64Array(N),im=new Float64Array(N),start=Math.max(0,(p-5)*hop);for(let i=0;i<N&&start+i<x.length;i++)re[i]=x[start+i]*(.5-.5*Math.cos(2*Math.PI*i/(N-1)));fft(re,im);for(let i=1;i<N/2;i++){const f=i*sr/N,e=re[i]**2+im[i]**2;for(let b=0;b<5;b++)if(f>=freqs[b]&&f<freqs[b+1])bands[b]+=e;power+=e;weight+=e*f;}+ }+ return {events:events.length,onset_ms:[q(rise,.1),q(rise,.5),q(rise,.9)],decay30_ms:[q(decay30,.1),q(decay30,.5),q(decay30,.9)],decay45_ms:[q(decay45,.1),q(decay45,.5),q(decay45,.9)],centroid_hz:Math.round(weight/power),bands:bands.map(x=>+(100*x/power).toFixed(2)),up_delay_ms:[q(upDelay,.1),q(upDelay,.5),q(upDelay,.9)],up_gap_db:[q(upGap,.1),q(upGap,.5),q(upGap,.9)],interval_ms:[q(intervals,.1),q(intervals,.5),q(intervals,.9)],level_db:[q(levels,.1),q(levels,.5),q(levels,.9)],noise_floor_db:+(20*Math.log10(Math.max(1e-12,[...rms].sort((a,b)=>a-b)[Math.floor(rms.length*.1)])/peak)).toFixed(2)};+}+const sr=48000, takes=[1,2,3].map(seed=>M.renderSfx('typing',{variant:'real',seed,lengthS:6},sr));+assert.deepEqual(takes[0].L,M.renderSfx('typing',{variant:'real',seed:1,lengthS:6},sr).L);+assert.notDeepEqual(takes[0].L,takes[1].L);assert.notDeepEqual(takes[1].L,takes[2].L);+const measurements=[];+for(const take of takes){assert.equal(take.L.length,6*sr);assert(M.auditSfx([take.L,take.R],sr).ok);const m=measure(take.L);measurements.push(m);console.log(JSON.stringify(m));const inRange=(name,x,lo,hi)=>assert(x>=lo&&x<=hi,`${name}: ${x} outside ${lo}..${hi}`);+ inRange('centroid',m.centroid_hz,1749,4459);for(let i=0;i<5;i++)inRange(`band ${i}`,m.bands[i],[2.41,.67,16.7,19.36,1.05][i],[38.79,24.33,53.38,71.14,8.86][i]);+ for(const [name,lo,hi] of [['onset_ms',3,9],['decay30_ms',25,89],['up_delay_ms',25,74],['up_gap_db',-15.29,-5.31],['interval_ms',108,267],['level_db',-18.98,-10.17]])inRange(name,m[name][1],lo,hi);+ inRange('noise floor',m.noise_floor_db,-69.6,-43.67);}+const decay45=measurements.map(m=>m.decay45_ms[1]).sort((a,b)=>a-b)[1]; assert(decay45>=75&&decay45<=83, `median decay45: ${decay45}`);+console.log('typing.real determinism, variation, duration, audit and spectral range pass');diff --git a/skills/anidoodle/engine/tools/sfx.mjs b/skills/anidoodle/engine/tools/sfx.mjsindex e84c4cd..14d9446 100644--- a/skills/anidoodle/engine/tools/sfx.mjs+++ b/skills/anidoodle/engine/tools/sfx.mjs@@ -221,7 +221,7 @@ const test = async () => {const [cmd, ...args] = process.argv.slice(2);if (cmd === "list") { const M = await load(); for (const k of M.SFX_KINDS) { const i = M.sfxInfo(k); console.log(`${k.padEnd(8)} [${i.variants.join(", ")}] level ${i.levelLufs} LUFS(win), duck ${i.duckDb} dB\n ${i.use}`); } }-else if (cmd === "one") { const M = await load(), out = args.pop(), [kind, variant, seed] = args; const s = M.renderSfx(kind, { variant, seed: seed ? Number(seed) : undefined, key: process.env.KEY, bpm: process.env.BPM ? Number(process.env.BPM) : undefined }, SR); writeAudio(out, s.L, s.R); console.log(`${kind}:${s.variant} seed ${s.seed}: ${(s.L.length / SR).toFixed(2)} s, hit @ ${(s.hit / SR).toFixed(3)} s, ${s.lufs.toFixed(1)} LUFS(win)`); }+else if (cmd === "one") { const M = await load(), out = args.pop(), [kind, variant, seed] = args; const s = M.renderSfx(kind, { variant, seed: seed ? Number(seed) : undefined, legacy: process.env.SFX_LEGACY === "1", key: process.env.KEY, bpm: process.env.BPM ? Number(process.env.BPM) : undefined }, SR); writeAudio(out, s.L, s.R); console.log(`${kind}:${s.variant} seed ${s.seed}: ${(s.L.length / SR).toFixed(2)} s, hit @ ${(s.hit / SR).toFixed(3)} s, ${s.lufs.toFixed(1)} LUFS(win)`); }else if (cmd === "kit" && args[0]) await kit(args[0]);else if (cmd === "test") await test();else { console.log("usage: node tools/sfx.mjs list | one <kind> [variant] [seed] <out> | kit <outdir> | test"); process.exit(cmd ? 1 : 0); }diff --git a/skills/anidoodle/references/music/sound-design.md b/skills/anidoodle/references/music/sound-design.mdindex c44bcd6..940bcec 100644--- a/skills/anidoodle/references/music/sound-design.md+++ b/skills/anidoodle/references/music/sound-design.md@@ -55,6 +55,12 @@ speaking window (K-weighted, see below). Duck is how far the score dips under itThe impact's in-key shimmer applies only to scores the engine composes. The route for a generated orsupplied track: `generated-tracks.md`.+### Versioned effects++Set `sfxVersion: 2` on a new `SfxPlan` or `renderSfx` call. Unversioned plans retain the original renderer for original kinds; cues can override their plan. Version 2 defaults to `notification:drop` and `typing:real`. The `bar` and `glass` notification variants and `mech`, `laptop`, and `soft` typing variants remain available. `typing:old` selects the legacy key tick.++Additional kinds are `click`, `pop-in`, `whoosh-short`, `whoosh-long`, `dark-riser`, `cut-hit`, `sub-drop`, `typing`, `notification`, `toggle-on`, and `toggle-off`. Use `old` or `new` to select the original or physical model where supported. For kinds absent from the original kit, the old reference uses the nearest original sound. `legacy: true` selects that reference and `legacy: false` selects physical models where available. See `engine/SFX_VERSIONING.md` for details.+## Placing effects in a filmCues are addressed by **film frame**, a whole number (a fractional frame throws; to land a hit@@ -68,6 +74,7 @@ import { filmSfx, filmAudio, composePiece, type SfxPlan } from "./music";import { myScore } from "./myScore"; // the Material YOU composed for this film (compose.md)const score = composePiece(myScore);const plan: SfxPlan = {+ sfxVersion: 2,fps: 30, frames: 450, score: { piece: score }, beatZeroS: 0, seed: 7, // key, bpm, bar from the scorecues: [{ frame: 12, kind: "tick" }, // ...one per typed character