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
chore: sync the plugin mirror with the sound pack work
Alex Greenshpun831f66afb97b
diff --git a/plugins/anidoodle/.codex-plugin/plugin.json b/plugins/anidoodle/.codex-plugin/plugin.jsonindex deb5ad0..55fd1ca 100644--- a/plugins/anidoodle/.codex-plugin/plugin.json+++ b/plugins/anidoodle/.codex-plugin/plugin.json@@ -6,7 +6,7 @@"interface": {"displayName": "anidoodle","shortDescription": "Hand-drawn art, written as code.",- "longDescription": "Illustrations, drawing timelapses, films of any length, explainers, infographics and interactive web animations in 31 hand-made styles, with original scores composed and synthesized in code. Match a style from your image, recreate a photo in any style, keep a character consistent, or learn how a drawing is built. Every render is deterministic, with no generated assets.",+ "longDescription": "Illustrations, drawing timelapses, films of any length, explainers, infographics and interactive web animations in 31 hand-made styles, with original scores composed as data and played by an engine written in code. Match a style from your image, recreate a photo in any style, keep a character consistent, or learn how a drawing is built. Every render is deterministic, with no generated assets.","developerName": "Alex Greenshpun","category": "Creativity","capabilities": [diff --git a/plugins/anidoodle/NOTICE b/plugins/anidoodle/NOTICEindex cae6e32..f4a3b95 100644--- a/plugins/anidoodle/NOTICE+++ b/plugins/anidoodle/NOTICE@@ -6,6 +6,27 @@ licensed under the Apache License, Version 2.0.Third-party material+The optional anidoodle sound pack (not part of this repository; installed by+skills/anidoodle/engine/tools/soundfetch.mjs)++ Instruments: recordings from the Versilian Community Sample Library (VCSL),+ https://github.com/sgossner/VCSL, CC0 1.0 Universal (public domain). Grand Piano+ Steinway B, Upright Piano Knight, Concert Harp, Marimba, Vibraphone, Glockenspiel,+ Tubular Bells 1, Timpani 2. No attribution is required.++ Rooms: recorded impulse responses from OpenAIR, the Open Acoustic Impulse Response+ library, Audio Lab, University of York, https://www.openair.hosted.york.ac.uk/,+ Creative Commons Attribution 4.0 International (CC BY 4.0). Attribution is required and+ is given above: OpenAIR, Audio Lab, University of York, CC BY 4.0, with each room's+ own URL. Arthur Sykes Rymer Auditorium (small-room),+ https://www.openair.hosted.york.ac.uk/?page_id=425; Jack Lyons Concert Hall+ (recital-hall), https://www.openair.hosted.york.ac.uk/?page_id=571; Genesis 6 Studio+ live room (live-room), https://www.openair.hosted.york.ac.uk/?page_id=483. The+ B-format (W X Y Z) recordings were decoded to stereo as L = W + Y, R = W - Y.++ Full provenance: skills/anidoodle/references/music/sounds-licenses.md. Redistribution+ must carry the CC BY 4.0 attribution above.+skills/anidoodle/engine/assets/refs/vangogh-almond-blossom.jpgVincent van Gogh, Almond Blossom (1890), Van Gogh Museum, Amsterdam.Public domain (the author died in 1890; a faithful reproduction of a two-dimensionaldiff --git a/plugins/anidoodle/README.md b/plugins/anidoodle/README.mdindex af621e4..3658bae 100644--- a/plugins/anidoodle/README.md+++ b/plugins/anidoodle/README.md@@ -2,11 +2,11 @@**Hand-drawn art, written as code.**-anidoodle makes illustrations, drawing timelapses, films of any length, explainers, infographics and interactive web animations in 31 hand-made styles, with original music composed and synthesized in code. Ask for a picture in plain words, match a style from your own image, recreate a photo in any style, keep a character consistent across scenes, or learn step by step how a drawing is built.+anidoodle makes illustrations, drawing timelapses, films of any length, explainers, infographics and interactive web animations in 31 hand-made styles, with original music composed as data and played by an engine written in code. Ask for a picture in plain words, match a style from your own image, recreate a photo in any style, keep a character consistent across scenes, or learn step by step how a drawing is built.-Music is composed for each piece from 21 genre vocabularies, never presets, and played by a sound engine built in code: a piano modelled on a real Steinway, Rhodes and Wurlitzer, orchestral sections and choir, guitars, real drum kits, real lo-fi, a full mix with reverb. `music.mjs check` clears a score (key, loudness, balance, novelty) before anyone listens. The launch kit turns your product's prompts, screens and install lines into a launch film in four shapes (16:9, 1:1, 4:5, 9:16), with sound cued from the picture, captions and a sync check; `launch.mjs new` starts one and `launch.mjs ship` delivers every shape.+Music is composed for each piece from 21 genre vocabularies, never presets, and played by a sound engine written in code: a piano modelled on a real Steinway, Rhodes and Wurlitzer, orchestral sections and choir, guitars, real drum kits, real lo-fi, a full mix with reverb. An optional sound pack adds recordings of eight real acoustic instruments and three recorded rooms; every score plays without it. `music.mjs check` clears a score (key, loudness, balance, novelty) before anyone listens. The launch kit turns your product's prompts, screens and install lines into a launch film in four shapes (16:9, 1:1, 4:5, 9:16), with sound cued from the picture, captions and a sync check; `launch.mjs new` starts one and `launch.mjs ship` delivers every shape.-Every mark is a function and every note is arithmetic, so the same source redraws the same picture on every machine, at every size. There are no generated image assets and no image model calls.+Every mark is a function and every score is written, so the same source redraws the same picture on every machine, at every size. There are no generated image assets and no image model calls.Works in Claude Code, Codex and Grok Build, and in any agent that reads skills. It needs Node 20 or newer on your machine; films also use ffmpeg.diff --git a/plugins/anidoodle/skills/anidoodle/SKILL.md b/plugins/anidoodle/skills/anidoodle/SKILL.mdindex c24b812..c206da8 100644--- a/plugins/anidoodle/skills/anidoodle/SKILL.md+++ b/plugins/anidoodle/skills/anidoodle/SKILL.md@@ -9,8 +9,9 @@ metadata:# anidoodlePictures, films and interactive pieces drawn entirely in code. One pure function paints every-frame; another composes and synthesizes every audio sample. The same source rebuilds the same-pixels and the same sound on any machine, at any size, at any length.+frame; another composes the score and plays it. The same source rebuilds the same pixels and the+same sound on any machine, at any size, at any length. Eight acoustic instruments play recordings+of real ones when the optional sound pack is installed; every score plays without it, unchanged.The engine is the easy half. Work gets thrown away because it had no point, because the subjectwas an icon of itself, because a style was only a palette swap, because the music had no form,@@ -57,8 +58,8 @@ say why in one line. Write the answers into a short brief before drawing.4. **Prove the look on ONE still, then build end to end.** After that, gates cost more than theysave. → `references/working-method.md`5. **The contract is absolute.** Pure in `(frame, env)` (and the input log, for interactive- pieces), `rng(seed)` only, no clock, no `ctx.filter`. Nothing generated or downloaded; images- the person brings may be embedded, pinned by hash. → `references/determinism-and-contract.md`+ pieces), `rng(seed)` only, no clock, no `ctx.filter`. Nothing generated; images they bring may be+ embedded by hash, and the sound pack is a separate, hash-pinned download. → `references/determinism-and-contract.md`6. **Music gets a plan, never an adjective.** A style, a mood per section, the notes as data, thenmeasurements. You cannot hear it, so one human listens before it ships. → `references/music/`7. **One directs, one builds, both write everything down.** When a session degrades, reset; the@@ -112,6 +113,8 @@ node tools/still.mjs intro --frame 0 --out out/look.png --scale 2 # a still, wnode tools/render.mjs intro # MP4; --out x.gif|x.webm|x.apngnode tools/gate.mjs intro # determinism, contract, dead airnode tools/emit.mjs intro --out out/intro.html # one self-contained offline player+node <skill>/engine/tools/soundfetch.mjs list # the install directory and what is installed; no network+node <skill>/engine/tools/soundfetch.mjs get all # the one command that downloads; then parts play recordings```| Tool | What it does |@@ -124,7 +127,8 @@ node tools/emit.mjs intro --out out/intro.html # one self-co| `verify-export.mjs` | QA on the rendered file: frames, duration, score, A/V sync, true peak after the encode; opt-in first frame, loop seam, `--delivery` || `launch.mjs` | a launch film: `new <name>` scaffolds the spec; `ship <name> --shapes 16x9,9x16` renders, posters, captions, verifies and framechecks each (`framecheck.mjs`: no text cut by the frame's edge) || `test.mjs` (`npm test`) | unit suites in `engine/test/`, no browser |-| `music.mjs` | `vocab` prints a style's vocabulary; `check` gates your composed score (key, master, guards, stems, novelty); `render`, `meter` |+| `music.mjs` | `vocab` prints a style's vocabulary; `check` gates your composed score (key, master, guards, stems, novelty, and which parts played recordings); `render`, `meter` |+| `soundfetch.mjs` | the sound pack: `list`, `get <id...\|all>`, `where`, `verify`, `remove <id>` || `sfx.mjs` | the sound-effects kit: `list`, `one`, `kit <dir>`, `test` |Four backends, one art core: `playwright`, `html-player`, `remotion`, `hyperframes`.diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.tsindex f88fc42..10d8e94 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts@@ -1,6 +1,10 @@// FILM RUNTIME. A film is data: meta, an asset manifest, and shots that tile [0, duration).// renderFrame(film, ctx, frame, env) is the whole contract between the art and any backend.import type { Ctx, Env } from "./core";+import type { Piece } from "./music/plan";++/** Hosts preload these scores' verified banks before calling the complete audio mix. */+export type FilmAudio = ((sampleRate: number) => [Float32Array, Float32Array]) & { scores?: Piece[] };export type Shot = { id: string; start: number; end: number; draw: (ctx: Ctx, local: number, env: Env) => void }; // frames, end exclusiveexport type Assets = { images: Record<string, string>; fonts?: Record<string, string> }; // name -> url (the page build inlines them)@@ -28,7 +32,7 @@ export type Film = { meta: {captions?: { from: number; to: number; text: string }[];// a legible frame for the poster image and the thumbnail (render --poster-frame, launch.mjs ship)poster?: number;-}; assets: Assets; shots: Shot[]; audio?: (sampleRate: number) => [Float32Array, Float32Array];+}; assets: Assets; shots: Shot[]; audio?: FilmAudio;// the same film composed for another frame shape (launch template films); hosts/page.ts calls it for <film>-<shape>reshape?: (shape: string) => Film };diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchSound.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchSound.tsindex cb2f360..874886f 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchSound.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchSound.ts@@ -11,6 +11,7 @@import { placeSfx, sfxDuck, sfxAudibility, type SfxCue, type SfxPlan, type SfxAudibility, type PlacedCue } from "./music/sfx";import { limiter } from "./music/render";import { loudness, truePeak } from "./music/meter";+import type { FilmAudio } from "./film";/** A cue as the template emits it: a kit cue, plus where on screen it happens (px) and what made it. */export type LaunchCue = SfxCue & { x?: number; role: "key" | "press" | "drop" | "bloom" | "land" | "arrive" | "riser" | "impact" };@@ -51,8 +52,8 @@ export const mixLaunch = (music: [Float32Array, Float32Array] | null, plan: Launreturn { L, R, placed, audibility: aud, raised: [...raised].map(([i, db]) => ({ i, role: cues[i].role, db })), lufs: lu, dbtp: truePeak([L, R]).dbtp, ok: aud.every((a) => a.ok) };};/** What a Film's audio(sampleRate) returns; throws when a cue is still buried after raising it. */-export const launchAudio = (music: ((sr: number) => [Float32Array, Float32Array]) | null, plan: LaunchPlan) => (sr: number): [Float32Array, Float32Array] => {+export const launchAudio = (music: FilmAudio | null, plan: LaunchPlan) => Object.assign((sr: number): [Float32Array, Float32Array] => {const m = mixLaunch(music ? music(sr) : null, plan, sr);if (!m.ok) throw new Error(`launch sound: ${m.audibility.filter((a) => !a.ok).map((a) => `cue #${a.i} ${a.kind} @ ${a.atS.toFixed(2)} s is ${a.marginDb.toFixed(1)} dB under the score even raised +8 dB`).join("; ")}: thin the score there or move the cue`);return [m.L, m.R];-};+}, { scores: music?.scores ?? [] });diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.tsindex 5394115..93c744f 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts@@ -619,7 +619,9 @@ export const gridScore = (score: () => Piece | Material, bpm: number, fps: numbe// peak ceiling first (render prints how far short); `limit: true` lets a look-ahead limiter take// those few peaks instead so the bed reaches the target. Compose the piece for this film at the// film's bpm, so the cuts sit on its downbeats. `piece` may return a Piece or a fitScore result.-export const musicBed = (piece: () => Piece | Fit, frames: number, fps = 30, lufs = -14, o: { limit?: boolean; tempo?: number } = {}) => (sr: number): [Float32Array, Float32Array] => {+export const musicBed = (piece: () => Piece | Fit, frames: number, fps = 30, lufs = -14, o: { limit?: boolean; tempo?: number } = {}) => {+ const source = piece(), score = "order" in source ? source.piece : o.tempo ? source : fitScore(source, frames / fps).piece;+ return Object.assign((sr: number): [Float32Array, Float32Array] => {const seconds = frames / fps, x = piece(), fit = "order" in x ? x : o.tempo ? { piece: x, tempo: o.tempo } : fitScore(x, seconds);const m = renderPiece(fit.piece, sr, { seconds, tempo: fit.tempo }), n = Math.round(seconds * sr);const L = new Float32Array(n), R = new Float32Array(n); L.set(m.L.subarray(0, n)); R.set(m.R.subarray(0, n));@@ -630,5 +632,5 @@ export const musicBed = (piece: () => Piece | Fit, frames: number, fps = 30, lufconst again = lufs - loudness([L, R], sr).integrated; if (again > 0) { gain(Math.min(again, 1)); limiter(L, R, sr, Math.pow(10, -1.3 / 20)); }const tp = truePeak([L, R]).dbtp; if (tp > -1) gain(-1.05 - tp); // an inter-sample overshoot: a last static trimreturn [L, R];+ }, { scores: [score] });};-diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.tsindex 667a2eb..41d9474 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts@@ -96,7 +96,7 @@ export const maskingPlan = (piece: Piece, o: { seconds?: number; tempo?: number;const spans: [number, number][] = []; for (let b = 0; b < total; b += bpb) spans.push([perf.sec(b), perf.sec(b + bpb)]);const melNotes = piece.parts.flatMap((p) => p.notes.filter((n) => n.role === "melody"));const sounding = spans.map((_, i) => melNotes.some((n) => n.t < (i + 1) * bpb && n.t + n.d > i * bpb));- return { roles, spans, sounding, opts: (r: Role): RenderOpts => ({ seconds: o.seconds, tempo: o.tempo, master: "none", cache: o.cache, perf: played(r) }) };+ return { roles, spans, sounding, opts: (r: Role): RenderOpts => ({ seconds: o.seconds, tempo: o.tempo, master: "none", cache: o.cache, perf: played(r), mixKeys: perf.parts.map(p => p.keys) }) };};export type MaskingPlan = NonNullable<ReturnType<typeof maskingPlan>>;export const roleBandDb = (piece: Piece, sr: number, opts: RenderOpts, spans: [number, number][]) => { const x = renderPiece(piece, sr, opts); return bandDb(x.L, x.R, sr, spans); };diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.tsindex 9e58b37..29b7858 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts@@ -1,4 +1,6 @@-// anidoodle music: 100 % procedural, notes as data, synthesized in code. No samples, ever.+// anidoodle music: notes as data, modeled voices and optional banks of real recordings.+export * from "./sampler";+export { registerRoom, roomFor, clearRooms } from "./mixReverb";export * from "./theory";export * from "./tables";export * from "./plan";diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysPiano.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysPiano.tsindex f351f31..7fc1dc6 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysPiano.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysPiano.ts@@ -88,6 +88,7 @@ const VOICINGS: Record<PianoVariant, Voicing> = {const stretchCents = (m: number) => (m > 60 ? 0.012 * Math.pow(m - 60, 1.9) : -0.02 * Math.pow(60 - m, 1.6));const nStrings = (m: number) => (m < 29 ? 1 : m < 41 ? 2 : 3);+export const pianoVelocity = (v: number) => v < 0.6 ? Math.pow(v, 1.55) : Math.pow(0.6, 1.55) * Math.pow(v / 0.6, 0.9);/** Register trim (dB): matches the legacy piano's listened register balance (tools/keys-demo.mjs + a C1-C8 probe at mf, first second RMS), smoothed. */const REG_TRIM = [[21, -0.9], [28, -1.1], [36, -1.6], [44, 2.1], [52, 4.8], [60, 4.7], [68, 6.9], [76, 7.8], [84, 7.0], [92, 6.9], [100, 5.0], [108, 4.0]];const regTrim = (m: number) => { if (m <= 21) return REG_TRIM[0][1]; for (let i = 1; i < REG_TRIM.length; i++) if (m <= REG_TRIM[i][0]) return lerp(REG_TRIM[i - 1][1], REG_TRIM[i][1], (m - REG_TRIM[i - 1][0]) / (REG_TRIM[i][0] - REG_TRIM[i - 1][0])); return REG_TRIM[REG_TRIM.length - 1][1]; };@@ -149,7 +150,7 @@ export const renderPianoV2 = (keys: KeyPress[], pedal: PedalSpan[], sr: number,buf.fill(0, 0, len);const nb = buf.subarray(0, len);// loudness law (felt hardening above mf: a faster hammer buys brightness more than level)- const loud = v < 0.6 ? Math.pow(v, 1.55) : Math.pow(0.6, 1.55) * Math.pow(v / 0.6, 0.9);+ const loud = pianoVelocity(v);// tension modulation: a big swing stretches the string, so the loud prompt sound sits a hair sharp (strike to strike it differs)const tension = Math.pow(2, ((0.5 + 0.35 * seq) * v * v * 1.4 * clamp(Math.pow(262 / f0, 0.3), 0.6, 1.6)) / 1200);const amps: number[] = [], freqs: number[] = [];diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.tsindex d9f5145..ef0bb82 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts@@ -98,7 +98,7 @@ const cinematicP: MixProfile = { eq: 0.9, drumBus: { ratio: 3, targetGrDb: 2.5,const P = (base: MixProfile, o: Partial<MixProfile>): MixProfile => ({ ...base, ...o });export const MIX_PROFILES: Record<StyleId, MixProfile> = {- nocturne: P(intimate, { sends: { melody: 0.5, accomp: 0.35, inner: 0.35, bass: 0.3, color: 0.5 }, space: conv(1.7, 24, { size: 0.6, late: 0.17, er: 0.4, hp: 300, lp: 6500 }), /* hp 300: the left hand's low-mids stay out of the room (masking guard 75 -> 81 %) */ width: W(1.0, 1.1, 150), classEq: { piano: { hp: 28 } } }),+ nocturne: P(intimate, { sends: { melody: 0.5, accomp: 0.35, inner: 0.35, bass: 0.3, color: 0.5 }, space: conv(1.7, 24, { room: "small-room", size: 0.6, late: 0.17, er: 0.4, hp: 300, lp: 6500 }), /* optional treated-room recording; hp 300 keeps the left hand's low-mids out of the send */ width: W(1.0, 1.1, 150), classEq: { piano: { hp: 28 } } }),lullaby: P(intimate, { space: conv(1.5, 18, { size: 0.5 }), tilt: -0.8 }),musicBox: P(intimate, { space: null /* the recipe: one reflection, handled in render */, width: W(1.0, 1.05) }),folk: P(intimate, { space: conv(1.2, 12, { size: 0.4, late: 0.28 }), width: W(1.05, 1.15), feel: "natural" }),@@ -133,6 +133,14 @@ export const partEq = (prof: MixProfile, inst: InstId, role: Role): StemEq => {if (role === "melody" && c !== "bass") e.bells = [...(e.bells ?? []), [2800, 1.1, 0.8 * k]];return e;};+/** Leave the lead band open on recorded support parts, without changing faders or the voice. */+export const recordedEq = (e: StemEq, role: Role, excessDb: number, fractionDb: number): StemEq => {+ if (role !== "bass" && role !== "accomp") return e;+ // A reference can itself be bright. Also limit absolute band occupancy toward 6% (-12 dB).+ // One broad bell spans the guard's 500 Hz-4 kHz band; the existing makeup stage holds level.+ const depth = Math.min(role === "bass" ? 12 : 9, Math.max(0, excessDb, fractionDb + 12) * (role === "bass" ? 0.8 : 1.4));+ return depth > 0 ? { ...e, bells: [...(e.bells ?? []), [1400, 0.45, -depth]] } : e;+};/** A one-line summary for tools/music.mjs vocab. */export const describeMix = (style: StyleId) => {const p = MIX_PROFILES[style], s = p.space;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.tsindex 7ec8375..81ba530 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts@@ -8,13 +8,30 @@// figure-of-eight tank, the paper's output taps. Implemented from the published algorithm.// conv convolution with a SYNTHESIZED impulse response: decorrelated L/R noise in 8 octave// bands, each with its own exponential decay (T60 falls above 4 kHz), a sparse early--// reflection pattern and a 20 ms fade-in; FFT overlap-add. No recorded IR.+// reflection pattern and a 20 ms fade-in; FFT overlap-add. Optional recorded rooms use+// the same convolution, with their first 40 ms counted as early reflections.import { Biquad, onePoleCoef, gauss, type Rng } from "./dsp";import { fft } from "./meter";export type SpaceKind = "fdn" | "plate" | "conv";-export type Space = { kind: SpaceKind; rt60: number; predelayMs: number; /** send filter */ hp: number; lp: number; /** early reflections level (0..1) and the late tail level (0..1) */ er: number; late: number; /** room size 0..1 (fdn/conv delay spread) */ size?: number; /** HF / LF decay multipliers */ highMult?: number; lowMult?: number; /** tank modulation depth 0..1 */ mod?: number };+export type Space = { kind: SpaceKind; room?: string; rt60: number; predelayMs: number; /** send filter */ hp: number; lp: number; /** early reflections level (0..1) and the late tail level (0..1) */ er: number; late: number; /** room size 0..1 (fdn/conv delay spread) */ size?: number; /** HF / LF decay multipliers */ highMult?: number; lowMult?: number; /** tank modulation depth 0..1 */ mod?: number };type Wet = readonly [Float32Array, Float32Array, Float32Array, Float32Array];+export type RecordedRoom = { L: Float32Array; R: Float32Array; rt60: number; sha256: string; directFrames?: number };+const rooms = new Map<string, RecordedRoom>();+export const roomFor = (id?: string) => id ? rooms.get(id) : undefined;+export const clearRooms = () => rooms.clear();+export const registerRoom = (id: string, room: RecordedRoom) => {+ if (!id || !(room.L instanceof Float32Array) || !(room.R instanceof Float32Array) || !room.L.length || room.L.length !== room.R.length || !room.L.every(Number.isFinite) || !room.R.every(Number.isFinite) || !(room.rt60 > 0) || !Number.isFinite(room.rt60) || !/^[a-f0-9]{64}$/i.test(room.sha256)) throw new Error(`${id}: invalid recorded room`);+ const directFrames = room.directFrames ?? 0;+ if (!Number.isInteger(directFrames) || directFrames < 0 || directFrames > room.L.length) throw new Error(`${id}: invalid directFrames`);+ const r = { ...room, directFrames, sha256: room.sha256.toLowerCase() }; rooms.set(id, r); return r;+};+/** A missing room-only override must not create a space on styles that have none. */+export const effectiveSpace = (s?: Partial<Space>): Partial<Space> | undefined => {+ if (!s?.room || roomFor(s.room)) return s;+ const { room: _room, ...rest } = s;+ return Object.keys(rest).length ? rest : undefined;+};const sendFilter = (L: Float32Array, R: Float32Array, sr: number, s: Space) => {const a = Float32Array.from(L), b = Float32Array.from(R);@@ -157,5 +174,31 @@ export const convReverb = (L: Float32Array, R: Float32Array, sr: number, s: Spacreturn [wL, wR, tL, tR];};-export const reverb = (L: Float32Array, R: Float32Array, sr: number, s: Space, rng: Rng): Wet =>- s.kind === "plate" ? plateReverb(L, R, sr, s, rng) : s.kind === "conv" ? convReverb(L, R, sr, s, rng) : fdnReverb(L, R, sr, s, rng);+const recordedReverb = (L: Float32Array, R: Float32Array, sr: number, s: Space, room: RecordedRoom): Wet => {+ const n = L.length, [a, b] = sendFilter(L, R, sr, s), pd = Math.round(s.predelayMs * sr / 1000), xL = new Float32Array(n), xR = new Float32Array(n);+ for (let i = pd; i < n; i++) { xL[i] = a[i - pd]; xR[i] = b[i - pd]; }+ const rate = 48000 / sr, len = Math.ceil(room.L.length / rate), split = Math.round(0.04 * sr), direct = Math.round((room.directFrames ?? 0) / rate);+ const responses = [room.L, room.R].map((src) => {+ const pcm = Float32Array.from(src); if (rate > 1) for (let j = 0; j < 2; j++) Biquad.make(48000, "lp", sr * 0.45, 0.7071).run(pcm);+ const early = new Float32Array(len), late = new Float32Array(len);+ for (let i = direct; i < len; i++) { const x = i * rate, j = Math.floor(x), f = x - j; (i < split ? early : late)[i] = (pcm[j] + f * ((pcm[j + 1] ?? 0) - pcm[j])) * rate; }+ return { early, late };+ });+ // synthIR normalizes each stereo component to total energy 2, preserving channel balance.+ for (const key of ['early', 'late'] as const) {+ const a = responses[0][key], b = responses[1][key]; let e = 0;+ for (let i = 0; i < len; i++) e += a[i] * a[i] + b[i] * b[i];+ const g = e > 0 ? Math.sqrt(2 / e) : 0;+ for (let i = 0; i < len; i++) { a[i] *= g; b[i] *= g; }+ }+ const wL = new Float32Array(n), wR = new Float32Array(n), tL = new Float32Array(n), tR = new Float32Array(n);+ convolve(xL, responses[0].late, tL, s.late * 0.36); convolve(xR, responses[1].late, tR, s.late * 0.36);+ convolve(xR, responses[0].late, tL, s.late * 0.18); convolve(xL, responses[1].late, tR, s.late * 0.18);+ convolve(xL, responses[0].early, wL, s.er * 0.51); convolve(xR, responses[1].early, wR, s.er * 0.51);+ for (let i = 0; i < n; i++) { wL[i] += tL[i]; wR[i] += tR[i]; }+ return [wL, wR, tL, tR];+};+export const reverb = (L: Float32Array, R: Float32Array, sr: number, s: Space, rng: Rng): Wet => {+ const r = roomFor(s.room); if (r) return recordedReverb(L, R, sr, s, r);+ return s.kind === "plate" ? plateReverb(L, R, sr, s, rng) : s.kind === "conv" ? convReverb(L, R, sr, s, rng) : fdnReverb(L, R, sr, s, rng);+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.tsindex ac9ec1b..2952282 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts@@ -26,7 +26,7 @@ export type Section = {export type MusicPlan = { style: StyleId; tempo: number; meter: Meter; sections: Section[]; pickupBeats?: number; swing?: number; phraseBars?: number; sync?: string[];/** tempo-arch depth per phrase (1 = +-2.5 %); final ritard end-tempo ratio (1 = none) */ rubato?: number; ritard?: number;/** a seamless loop (renderLoop): the end must not relax into a cadence */ loop?: boolean;- /** room override (the guards' bad fixture uses it; films normally take the style's room) */ space?: { er?: number; late?: number; rt60?: number; hp?: number } };+ /** room override (the guards' bad fixture uses it; films normally take the style's room) */ space?: Partial<import("./mixReverb").Space> };export type Chord = { t: number; name: string };/** Bus moves (lofiKit): `duck` pumps the named parts on every onset of the `by` part; `tape` wobbles and saturates the master. */export type PieceFx = { clean?: boolean /* skip the lo-fi colour (sampler, vinyl, tilt: lofiFx.ts) */; duck?: { by: string; parts: string[]; depth?: number; release?: number }; tape?: TapeFx; /** the lo-fi production chain (lofiFx.ts); a lofi-style piece without one gets LOFI_DUSTY */ lofi?: LofiFx };diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.tsindex 7b3d021..e79fbb1 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts@@ -6,6 +6,7 @@ import { type Piece, type Part, resequence, beatsPerBar } from "./plan";import { perform, type Performance, type Played } from "./perform";import { renderPiano, PIANO_REAL, type PianoOpts } from "./piano";import { keysVoice, renderPianoV2 } from "./keys";+import { bankFor, samplerVoice, sampleZones, registerBank, type SampleBank, type SampleTrim } from "./sampler";import * as I from "./instruments";import * as O from "./orchestra";import { chokeTimes, type KitCtx } from "./drums";@@ -16,11 +17,12 @@ import { loudness, truePeak, stemBalance } from "./meter";import { STYLES } from "./tables";import { rng as mkRng } from "../core";import { eqChain, runEq, stereoPan, compress, saturate, bandWidth, smoothLimiter, ampSim, transientGain } from "./mixDsp";-import { reverb, type Space } from "./mixReverb";-import { mixProfile, partEq, ROLE_SEND, isStruck, TRANSIENT_DEFAULT, type MixProfile } from "./mixProfiles";+import { reverb, roomFor, effectiveSpace, type Space } from "./mixReverb";+import { mixProfile, partEq, recordedEq, ROLE_SEND, isStruck, TRANSIENT_DEFAULT, type MixProfile } from "./mixProfiles";export type RenderOpts = { /** sound v2, gentle styles only: a <= 1 dB 2:1 glue on the mix bus (spec 08 forbids a compressor on gentle masters; Alex decides) */ gentleGlue?: boolean; expressive?: boolean; piano?: PianoOpts; flatVelocity?: number; seconds?: number; tempo?: number; master?: "auto" | "gentle" | "dense" | "none"; stems?: boolean; only?: (p: Part) => boolean;/** play this performance instead of performing the piece (the guards render one role of the SAME performance the mix plays) */ perf?: Performance;+ /** Complete part strikes keep recorded EQ fixed when a guard isolates one note role. */ mixKeys?: Played[][];/** reuse synthesized voices by their exact inputs (tools/music.mjs check: each part is synthesized once for the mix, the guards and the stems); output is bit-identical */ cache?: VoiceCache };/**@@ -31,13 +33,20 @@ export type RenderOpts = { /** sound v2, gentle styles only: a <= 1 dB 2:1 glueexport type VoiceOut = { L: Float32Array; R: Float32Array; halo?: Float32Array; /** the transient gain's reduction (dB), when the job ran it */ transientGr?: number };/** Per-stem processing that depends on nothing but the stem (sound v2): the lo-fi stem colour, the amp, the gentle master's transient gain. */type StemPost = { lofi?: LofiFx; id: string; seed: number; period?: number; amp?: number; transient?: { maxDb: number; thrDb: number; ratio: number } };-export type VoiceJob =+export type VoiceJob = (+ | { kind: "sampled"; bank: string; bankHash: string; inst: Part["inst"]; opts?: Part["opts"]; keys: Played[]; pedal: Performance["pedal"]; sr: number; n: number; seed: number; post?: StemPost }| { kind: "voice"; inst: Part["inst"]; opts?: Part["opts"]; keys: Played[]; sr: number; n: number; seed: number; ctx: KitCtx; post?: StemPost }- | { kind: "piano"; keys: Played[]; pedal: Performance["pedal"]; sr: number; n: number; seed: number; opts?: Part["opts"]; v1?: PianoOpts; post?: StemPost };+ | { kind: "piano"; keys: Played[]; pedal: Performance["pedal"]; sr: number; n: number; seed: number; opts?: Part["opts"]; v1?: PianoOpts; post?: StemPost }) & { roomHashes?: [string, string, number, number][] };export type VoiceCache = Map<string, VoiceOut>;export const runVoiceJob = (j: VoiceJob): VoiceOut => {+ for (const [id, sha, rt60, directFrames] of j.roomHashes ?? []) { const r = roomFor(id); if (!r || r.sha256 !== sha || r.rt60 !== rt60 || (r.directFrames ?? 0) !== directFrames) throw new Error(`recorded room missing or changed: ${id} (${sha})`); }let out: VoiceOut;- if (j.kind === "piano") { const r = j.v1 ? renderPiano(j.keys, j.pedal, j.sr, j.n, j.v1, j.seed) : renderPianoV2(j.keys, j.pedal, j.sr, j.n, j.opts ?? {}, j.seed); out = { L: r.L, R: r.R, halo: r.halo }; }+ if (j.kind === "sampled") {+ const b = bankFor(j.inst, typeof j.opts?.variant === "string" ? j.opts.variant : undefined);+ if (!b || b.id !== j.bank || b.hash !== j.bankHash) throw new Error(`sample bank missing or changed: ${j.bank} (${j.bankHash})`);+ out = samplerVoice(b, j.keys, j.pedal, j.sr, j.n, j.opts ?? {}, j.seed);+ }+ else if (j.kind === "piano") { const r = j.v1 ? renderPiano(j.keys, j.pedal, j.sr, j.n, j.v1, j.seed) : renderPianoV2(j.keys, j.pedal, j.sr, j.n, j.opts ?? {}, j.seed); out = { L: r.L, R: r.R, halo: r.halo }; }else out = voice({ id: "", role: "accomp", notes: [], inst: j.inst, ...(j.opts ? { opts: j.opts } : {}) }, j.keys, j.sr, j.n, j.seed, j.ctx);const q = j.post; if (!q) return out;if (q.lofi) lofiStem(q.lofi, q.id, out.L, out.R, j.sr, j.keys.map((k) => k.t), q.seed, q.period);@@ -55,9 +64,13 @@ const v2Job = (piece: Piece, pt: Part, pi: number, keys: Played[], perf: Performconst tg = prof.transient === undefined ? TRANSIENT_DEFAULT : prof.transient, amp = typeof pt.opts?.amp === "number" ? (pt.opts.amp as number) : undefined;const transient = style.master === "gentle" && tg && isStruck(pt.inst, pt.opts) ? tg : undefined;const post: StemPost | undefined = lofi || amp !== undefined || transient ? { id: pt.id, seed: piece.seed, ...(lofi ? { lofi, period } : {}), ...(amp !== undefined ? { amp } : {}), ...(transient ? { transient } : {}) } : undefined;- const base = pt.inst === "piano" ? (o.piano ? { kind: "piano" as const, keys, pedal: perf.pedal, sr, n, seed: piece.seed + pi, v1: o.piano } : { kind: "piano" as const, keys, pedal: perf.pedal, sr, n, seed: piece.seed + pi, opts: pt.opts ?? {} })+ const bank = pt.opts?.sampled === false ? undefined : bankFor(pt.inst, typeof pt.opts?.variant === "string" ? pt.opts.variant : undefined);+ const base = bank ? { kind: "sampled" as const, bank: bank.id, bankHash: bank.hash, inst: pt.inst, keys, pedal: perf.pedal, sr, n, seed: pt.inst === "piano" ? piece.seed + pi : piece.seed * 101 + pi, opts: pt.opts }+ : pt.inst === "piano" ? (o.piano ? { kind: "piano" as const, keys, pedal: perf.pedal, sr, n, seed: piece.seed + pi, v1: o.piano } : { kind: "piano" as const, keys, pedal: perf.pedal, sr, n, seed: piece.seed + pi, opts: pt.opts ?? {} }): { kind: "voice" as const, inst: pt.inst, opts: pt.opts, keys, sr, n, seed: piece.seed * 101 + pi, ctx };- return post ? { ...base, post } : base;+ const roomHashes: [string, string, number, number][] = [effectiveSpace(piece.plan.space)?.room ?? prof.space?.room, prof.drumRoom?.room].flatMap((id) => { const r = roomFor(id); return r && id ? [[id, r.sha256, r.rt60, r.directFrames ?? 0] as [string, string, number, number]] : []; });+ const job = post ? { ...base, post } : base;+ return roomHashes.length ? { ...job, roomHashes } : job;};/** Synthesize (or reuse) one voice. The caller owns the returned arrays (it mutates them in place). */const synth = (j: VoiceJob, cache?: VoiceCache): VoiceOut => {@@ -122,6 +135,39 @@ const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number, ct}};+/** Fixed single-note energy references at each zone's pitch and layer centre.+ * Keep the instrument median trim; cap zone deviation so a near-silent recording never gets a huge lift. */+export const calibrateBank = (id: string) => {+ const [inst, ...variant] = id.split("."), bank = bankFor(inst, variant.join(".") || undefined); if (!bank) throw new Error(`sample bank missing: ${id}`);+ const sr = 24000, n = sr * 12, opts = { ...(variant.length ? { variant: variant.join(".") } : {}), pedal: false }, bare: SampleBank = { entry: bank.entry, zones: bank.zones };+ // Gated RMS would match the average tail instead of energy per strike, changing a fast+ // arpeggio's balance when recorded and modeled decays differ. Use one fixed 12 s window.+ const level = (r: VoiceOut) => { const mid = Float32Array.from(r.L, (x, i) => (x + r.R[i]) * 0.5); Biquad.make(sr, "hp", 30, 0.7071).run(mid); let energy = 0; for (const x of mid) energy += x * x; return 10 * Math.log10(energy / n); };+ const bandFraction = (r: VoiceOut) => {+ const mid = Float32Array.from(r.L, (x, i) => (x + r.R[i]) * 0.5);+ Biquad.make(sr, "hp", 40, Math.SQRT1_2).run(mid);+ let total = 0; for (const x of mid) total += x * x;+ Biquad.make(sr, "hp", 500, Math.SQRT1_2).run(mid); Biquad.make(sr, "lp", 4000, Math.SQRT1_2).run(mid);+ let band = 0; for (const x of mid) band += x * x;+ return 10 * Math.log10(Math.max(1e-15, band) / Math.max(1e-15, total));+ };+ const references = new Map<string, { level: number; band: number }>();+ const trim: SampleTrim[] = bank.zones.filter(({ zone }) => zone.art !== "rel").map((z) => {+ const p = z.zone.midi, v = bank.entry.layerVelocity?.[z.zone.layer - 1] ?? (z.zone.layer - 0.5) / bank.entry.layers;+ const keys: Played[] = [{ p, v, tone: v, t: 0, off: 1, role: "melody", w: v }], one: SampleBank = { entry: { ...bare.entry, zones: [{ ...z.zone, art: undefined }] }, zones: [{ ...z, zone: { ...z.zone, art: undefined } }] }, recorded = samplerVoice(one, keys, [], sr, n, opts, 1);+ const ref = `${p}:${v}`; let modeled = references.get(ref);+ if (modeled === undefined) { const r = inst === "piano" ? renderPianoV2(keys, [], sr, n, opts, 1) : voice({ id: "ref", inst: inst as Part["inst"], role: "melody", notes: [], opts }, keys, sr, n, 1); modeled = { level: level(r), band: bandFraction(r) }; references.set(ref, modeled); }+ const modeledDb = modeled.level;+ const measuredDb = level(recorded);+ const correctionDb = modeledDb - measuredDb;+ if (!Number.isFinite(correctionDb)) throw new Error(`${id}: silent calibration at MIDI ${p}`);+ const bandFractionDb = bandFraction(recorded);+ return { file: z.zone.file, midi: p, layer: z.zone.layer, measuredDb, modeledDb, correctionDb, bandFractionDb, bandExcessDb: bandFractionDb - modeled.band };+ });+ const sorted = trim.map((t) => t.correctionDb).sort((a, b) => a - b), middle = Math.floor(sorted.length / 2), medianDb = sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;+ return registerBank(id, { ...bare, trim: trim.map((t) => ({ ...t, requestedDb: t.correctionDb, medianDb, correctionDb: medianDb + Math.max(-9, Math.min(9, t.correctionDb - medianDb)), boostLimited: t.correctionDb > medianDb + 9 })) });+};+export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => (piece.legacy ? renderLegacy(piece, sr, o) : renderV2(piece, sr, o));/** The pre-v2 render, frozen: the shipped launch score renders through this bit for bit. */@@ -150,7 +196,7 @@ const renderLegacy = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered =>// ---- spaceconst rng = mkRng(piece.seed * 7 + 5), dry: [Float32Array, Float32Array] = [Float32Array.from(L), Float32Array.from(R)];let wet: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)];- const sp = piece.plan.space;+ const sp = effectiveSpace(piece.plan.space);if (style.id === "musicBox" && !sp) { // the recipe: ONE early reflection, 30 ms late, 14 dB down, no tailconst d = Math.round(0.03 * sr), g = db(-14); for (let i = d; i < n; i++) { wet[0][i] = dry[0][i - d] * g; wet[1][i] = dry[1][i - d] * g * 0.9; L[i] += wet[0][i]; R[i] += wet[1][i]; }} else if (style.reverb !== "none" || sp) {@@ -203,14 +249,23 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {let sL: Float32Array, sR: Float32Array;// piano v2 (keysPiano.ts) unless the caller asks for the v1 model by passing RenderOpts.piano// the voice, then its stem processing (lo-fi colour, amp, transient gain): one job (v2Job), cached as a whole- const r = synth(v2Job(piece, pt, pi, keys, perf, sr, n, o, kitCtx), o.cache); sL = r.L; sR = r.R;- if (pt.inst === "piano" && (o.piano ? o.piano.pedal : pt.opts?.pedal !== false)) for (let i = 0; i < n; i++) haloL[i] += r.halo![i] * db(pt.gainDb ?? 0);+ const job = v2Job(piece, pt, pi, keys, perf, sr, n, o, kitCtx), r = synth(job, o.cache); sL = r.L; sR = r.R;+ if (r.halo && (job.kind === "sampled" || (pt.inst === "piano" && (o.piano ? o.piano.pedal : pt.opts?.pedal !== false)))) for (let i = 0; i < n; i++) haloL[i] += r.halo[i] * db(pt.gainDb ?? 0);if (r.transientGr !== undefined) report.transientGr = Math.max(report.transientGr ?? 0, r.transientGr);if (pump && dk!.parts.includes(pt.id)) for (let i = 0; i < n; i++) { sL[i] *= pump[i]; sR[i] *= pump[i]; }// corrective EQ, then match the stem's RMS back (+-3 dB cap): EQ shapes the tone, the fader keeps the calibrated balance// the stem meter reads the part as the fader set it (pre-EQ, after its pan): the EQ is energy-neutral in the audible bandconst pre = o.stems ? [Float32Array.from(sL), Float32Array.from(sR)] as [Float32Array, Float32Array] : null;- const before = audible(sL, sR, sr), e = partEq(prof, pt.inst, pt.role); runEq(sL, eqChain(sr, e)); runEq(sR, eqChain(sr, e));+ const before = audible(sL, sR, sr);+ let e = partEq(prof, pt.inst, pt.role);+ if (job.kind === "sampled" && (pt.role === "bass" || pt.role === "accomp")) {+ const bank = bankFor(pt.inst, typeof pt.opts?.variant === "string" ? pt.opts.variant : undefined)!;+ const selected = sampleZones(bank, (o.mixKeys?.[pi] ?? keys).slice().sort((a, b) => a.t - b.t || a.p - b.p), job.seed, pt.opts?.pedal === false ? [] : perf.pedal);+ const spectra = selected.map(z => bank.trim?.find(t => t.file === z.zone.file));+ const median = (xs: number[], fallback: number) => xs.length ? xs.sort((a, b) => a - b)[Math.floor(xs.length / 2)] : fallback;+ e = recordedEq(e, pt.role, median(spectra.map(t => t?.bandExcessDb ?? 0), 0), median(spectra.map(t => t?.bandFractionDb ?? -Infinity), -Infinity));+ }+ runEq(sL, eqChain(sr, e)); runEq(sR, eqChain(sr, e));const after = audible(sL, sR, sr), mk = after > 0 && before > 0 ? Math.min(db(3), Math.max(db(-3), Math.sqrt(before / after))) : 1;const g = db(pt.gainDb ?? 0) * mk;for (let i = 0; i < n; i++) { sL[i] *= g; sR[i] *= g; }@@ -232,7 +287,7 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {// ---- spaceconst rng = mkRng(piece.seed * 7 + 5), dry: [Float32Array, Float32Array] = [Float32Array.from(L), Float32Array.from(R)];let wet: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)];- const sp = piece.plan.space;+ const sp = effectiveSpace(piece.plan.space);if (style.id === "musicBox" && !sp && !piece.mix?.space) { // the recipe: ONE early reflection, 30 ms late, 14 dB down, no tailconst d = Math.round(0.03 * sr), g = db(-14); for (let i = d; i < n; i++) { wet[0][i] = dry[0][i - d] * g; wet[1][i] = dry[1][i - d] * g * 0.9; L[i] += wet[0][i]; R[i] += wet[1][i]; }} else {@@ -242,7 +297,8 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {if (!prof.drumRoom) for (let i = 0; i < n; i++) { mS[0][i] += rS[0][i]; mS[1][i] += rS[1][i]; }const [wL, wR, tL, tR] = reverb(mS[0], mS[1], sr, main, rng);for (let i = 0; i < n; i++) { L[i] += wL[i]; R[i] += wR[i]; }- wet = [tL, tR]; report.space = `${main.kind} ${main.rt60}s`;+ const recorded = roomFor(main.room);+ wet = [tL, tR]; report.space = recorded ? `${main.room} ${recorded.rt60}s (${recorded.sha256})` : `${main.kind} ${main.rt60}s`;}if (prof.drumRoom && anyRoom) {const [wL, wR, tL, tR] = reverb(rS[0], rS[1], sr, prof.drumRoom, mkRng(piece.seed * 11 + 3));@@ -372,7 +428,7 @@ export const fitToDuration = (piece: Piece, seconds: number): { piece: Piece; te};/** What a Film's `audio(sampleRate)` returns: [L, R] at exactly the film's length. */-export const filmAudio = (piece: Piece, seconds: number) => (sr: number): [Float32Array, Float32Array] => {+export const filmAudio = (piece: Piece, seconds: number) => Object.assign((sr: number): [Float32Array, Float32Array] => {const fit = fitScore(piece, seconds), r = renderPiece(fit.piece, sr, { seconds, tempo: fit.tempo });return [r.L, r.R];-};+}, { scores: [fitScore(piece, seconds).piece] });diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.tsnew file mode 100644index 0000000..7743653--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts@@ -0,0 +1,152 @@+// Recorded voices. Decoding belongs to the host; a bank is only the manifest entry and 48 kHz PCM.+import type { Played } from "./perform";+import type { PedalSpan } from "./piano";+import type { Opts } from "./keysCore";+import { clamp, db } from "./dsp";+import { nameOf } from "./theory";+import { rng } from "../core";+import { pianoVelocity } from "./keysPiano";++export type SampleZone = { file: string; midi: number; layer: number; rr: number; frames: number; channels: number; peakDb: number; rmsDb: number; sha256: string; art?: "sus" | "rel"; unpitched?: boolean; measuredHz?: number; loop?: [number, number] };+export type SampleEntry = { title: string; source: string; license: string; kind: "struck" | "sustained"; range: [number, number]; layers: number; layerVelocity?: number[]; sparse?: boolean; maxShift?: number; damped: boolean; normalized?: boolean; zones: SampleZone[] };+export type SampleTrim = { file: string; midi: number; layer: number; measuredDb: number; modeledDb: number; correctionDb: number; requestedDb?: number; medianDb?: number; boostLimited?: boolean;+ /** 500 Hz-4 kHz energy as a fraction of audible energy, and its excess over the modeled reference. */+ bandFractionDb?: number; bandExcessDb?: number };+export type SampleBank = { entry: SampleEntry; zones: { zone: SampleZone; channels: Float32Array[] }[]; /** fixed modeled references at each recording's pitch and layer centre */ trim?: SampleTrim[] };+export type RegisteredBank = SampleBank & { id: string; hash: string };+const banks = new Map<string, RegisteredBank>();+export const bankId = (inst: string, variant?: string) => variant ? `${inst}.${variant}` : inst;+export const bankFor = (inst: string, variant?: string) => banks.get(bankId(inst, variant));+export const clearBanks = () => banks.clear();++/** Synchronous SHA-256 of ASCII identity data, also available in the browser without a decoder. */+const hash = (s: string) => {+ const K = [0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2];+ const h = [0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19], b = new Uint8Array(Math.ceil((s.length + 9) / 64) * 64), w = new Int32Array(64), rot = (x: number, n: number) => (x >>> n) | (x << (32 - n));+ for (let i = 0; i < s.length; i++) b[i] = s.charCodeAt(i);+ b[s.length] = 128; const view = new DataView(b.buffer); view.setUint32(b.length - 4, s.length * 8);+ for (let off = 0; off < b.length; off += 64) {+ for (let i = 0; i < 16; i++) w[i] = view.getInt32(off + i * 4);+ for (let i = 16; i < 64; i++) { const a = w[i - 15], c = w[i - 2]; w[i] = w[i - 16] + (rot(a, 7) ^ rot(a, 18) ^ (a >>> 3)) + w[i - 7] + (rot(c, 17) ^ rot(c, 19) ^ (c >>> 10)); }+ let [a,c,d,e,f,g,j,k] = h;+ for (let i = 0; i < 64; i++) { const t = (k + (rot(f, 6) ^ rot(f, 11) ^ rot(f, 25)) + ((f & g) ^ (~f & j)) + K[i] + w[i]) | 0, u = ((rot(a, 2) ^ rot(a, 13) ^ rot(a, 22)) + ((a & c) ^ (a & d) ^ (c & d))) | 0; k = j; j = g; g = f; f = (e + t) | 0; e = d; d = c; c = a; a = (t + u) | 0; }+ [a,c,d,e,f,g,j,k].forEach((v, i) => h[i] = (h[i] + v) | 0);+ }+ return h.map((v) => (v >>> 0).toString(16).padStart(8, "0")).join("");+};+/** Hashes pin the recordings; the playable metadata also belongs in the identity (a changed range or mapping is a new voice). */+export const bankIdentity = (entry: SampleEntry) => hash(JSON.stringify([entry.kind, entry.range, entry.layers, entry.layerVelocity ?? null, entry.damped, entry.normalized === true, entry.zones.map((z) => [z.sha256.toLowerCase(), z.midi, z.layer, z.rr, z.frames, z.channels, z.unpitched === true, z.loop ?? null, ...(z.art ? [z.art] : [])])]));+export const registerBank = (id: string, bank: SampleBank): RegisteredBank => {+ const e = bank.entry;+ if (!Array.isArray(e.range) || e.range.length !== 2 || !e.range.every((p) => Number.isInteger(p) && p >= 0 && p <= 127) || e.range[0] > e.range[1] || !Number.isInteger(e.layers) || e.layers < 1 || typeof e.damped !== "boolean") throw new Error(`${id}: invalid sample range, layers or damping`);+ if (e.layerVelocity !== undefined && (!Array.isArray(e.layerVelocity) || e.layerVelocity.length !== e.layers || e.layerVelocity.some((v, i) => !Number.isFinite(v) || v < 0 || v > 1 || (i > 0 && v <= e.layerVelocity![i - 1])))) throw new Error(`${id}: layerVelocity needs one increasing centre in 0..1 per layer`);+ if (!Array.isArray(e.zones)) throw new Error(`${id}: invalid sample zones`);+ if (e.kind === "sustained") { if (e.zones.some((z) => !z.loop)) throw new Error(`${id}: sustained zone without a loop`); throw new Error(`${id}: sustained banks are not supported in pack version 1`); }+ if (e.kind !== "struck" || !e.zones.length || bank.zones.length !== e.zones.length) throw new Error(`${id}: invalid or empty sample bank`);+ bank.zones.forEach(({ zone: z, channels }, i) => {+ if (z.art !== undefined && z.art !== "sus" && z.art !== "rel") throw new Error(`${id}: invalid articulation ${z.file}`);+ if (JSON.stringify(z) !== JSON.stringify(e.zones[i]) || !Number.isInteger(z.midi) || z.midi < e.range[0] || z.midi > e.range[1] || !Number.isInteger(z.layer) || z.layer < 1 || z.layer > e.layers || !Number.isInteger(z.rr) || z.rr < 1 || !Number.isInteger(z.frames) || z.frames < 1 || ![1, 2].includes(z.channels) || !/^[a-f0-9]{64}$/i.test(z.sha256) || channels.length !== z.channels || channels.some((c) => !(c instanceof Float32Array) || c.length !== z.frames)) throw new Error(`${id}: invalid zone or PCM ${z.file}`);+ });+ if (!e.zones.some((z) => !z.art)) throw new Error(`${id}: no ordinary sample zones`);+ if (bank.trim && (new Set(bank.trim.map((t) => t.file)).size !== bank.trim.length || bank.trim.some((t) => !e.zones.some((z) => z.file === t.file && z.midi === t.midi && z.layer === t.layer) || ![t.measuredDb, t.modeledDb, t.correctionDb, t.requestedDb ?? 0, t.medianDb ?? 0, t.bandFractionDb ?? 0, t.bandExcessDb ?? 0].every(Number.isFinite) || (t.medianDb !== undefined && Math.abs(t.correctionDb - t.medianDb) > 9.000001) || (t.boostLimited !== undefined && typeof t.boostLimited !== "boolean")))) throw new Error(`${id}: invalid sampled calibration`);+ const identity = bankIdentity(e), b = { ...bank, id, hash: bank.trim ? hash(JSON.stringify([identity, bank.trim])) : identity }; banks.set(id, b); return b;+};++const layerV = (e: SampleEntry, layer: number) => e.layerVelocity?.[layer - 1] ?? (layer - 0.5) / e.layers;+/** Relative filtering is the default; the alternatives support a controlled audition. */+export const sampleCutoff = (e: SampleEntry, z: SampleZone, k: Played, sr: number, mode?: string) => {+ const tone = clamp(k.tone ?? k.v, 0, 1), centre = layerV(e, z.layer);+ if (mode === "off" || (mode !== "asis" && tone >= centre)) return Infinity;+ const t = mode !== "asis" ? 1 - Math.max(0, centre - tone) : tone;+ return Math.min(sr * 0.45, 350 + 17650 * t * t);+};+export const sampleGain = (e: SampleEntry, z: SampleZone, v: number) => e.normalized ? pianoVelocity(v) * db(-8 * Math.max(0, 0.6 - v)) : v <= 0 ? 0 : db(clamp(16 * (v - layerV(e, z.layer)), -6, 6));+/** Nearest pitch, then nearest layer, then this note's seeded recording. State stays local to a render. */+export const sampleZones = (bank: SampleBank, keys: Played[], seed: number, pedal: PedalSpan[] = [], art?: "rel") => {+ const previous = new Map<string, SampleBank["zones"][number]>(), e = bank.entry, pool = bank.zones.filter(({ zone }) => zone.art === art);+ return keys.map((k, i) => {+ if (k.p < e.range[0] || k.p > e.range[1]) throw new Error(`${e.title}: note ${nameOf(k.p)} (${k.p}) outside range ${nameOf(e.range[0])}-${nameOf(e.range[1])} (${e.range.join("-")})`);+ let pitch = Infinity, distance = Infinity;+ for (const { zone: z } of pool) { const d = Math.abs(z.midi - k.p); if (d < distance || (d === distance && z.midi < pitch)) { pitch = z.midi; distance = d; } }+ const atPitch = pool.filter(({ zone }) => zone.midi === pitch), v = clamp(k.v, 0, 1);+ let layer = 0, delta = Infinity;+ for (const { zone: z } of atPitch) { const d = Math.abs(layerV(e, z.layer) - v); if (d < delta || (Math.abs(d - delta) < 1e-12 && z.layer > layer)) { layer = z.layer; delta = d; } }+ const down = !art && pedal.some(([a, b]) => k.t >= a && k.t < b), r = rng(k.vary?.seed ?? ((seed * 7919 + i * 104729 + k.p * 31) >>> 0));+ const pick = (layer: number) => {+ const sus = down ? bank.zones.filter(({ zone }) => zone.art === "sus" && zone.midi === pitch && zone.layer === layer) : [];+ const choices = (sus.length ? sus : atPitch.filter(({ zone }) => zone.layer === layer)).sort((a, b) => a.zone.rr - b.zone.rr);+ if (!choices.length) throw new Error(`${e.title}: no recording for ${nameOf(k.p)}`);+ const last = previous.get(`${k.p}:${choices[0].zone.art ?? "ordinary"}`), available = choices.length > 1 ? choices.filter((z) => z !== last) : choices;+ return available[Math.floor(r() * available.length)];+ };+ let z = pick(layer);+ // A near-silent recording must not lift its noise to the reference. Try a louder layer at this pitch.+ while (!art && bank.trim?.find((t) => t.file === z.zone.file)?.boostLimited) {+ const next = Math.min(...atPitch.filter(({ zone }) => zone.layer > z.zone.layer).map(({ zone }) => zone.layer));+ if (!Number.isFinite(next)) break; z = pick(next);+ }+ previous.set(`${k.p}:${z.zone.art ?? "ordinary"}`, z); return z;+ });+};++/** Blackman-windowed sinc, narrowed before any downsampling (pitch up OR a 24 kHz stem). */+const sincTable = (rate: number) => {+ const taps = 48, phases = 256, cut = 0.94 / Math.max(1, rate), table = new Float64Array(taps * (phases + 1));+ for (let p = 0; p <= phases; p++) {+ let sum = 0; for (let t = 0; t < taps; t++) { const d = t - taps / 2 + 1 - p / phases, x = Math.PI * d * cut, win = 0.42 + 0.5 * Math.cos(Math.PI * d / (taps / 2)) + 0.08 * Math.cos(2 * Math.PI * d / (taps / 2)), v = Math.abs(d) >= taps / 2 ? 0 : (Math.abs(x) < 1e-12 ? cut : cut * Math.sin(x) / x) * win; table[p * taps + t] = v; sum += v; }+ for (let t = 0; t < taps; t++) table[p * taps + t] /= sum;+ }+ return table;+};+const sincRead = (a: Float32Array, x: number, table: Float64Array) => {+ const i = Math.floor(x), ph = (x - i) * 256, p = Math.floor(ph), f = ph - p; let y = 0;+ for (let t = 0; t < 48; t++) { const j = i - 23 + t; if (j >= 0 && j < a.length) { const k = p * 48 + t; y += a[j] * (table[k] + f * (table[k + 48] - table[k])); } }+ return y;+};++export const samplerVoice = (bank: SampleBank, keys: Played[], pedal: PedalSpan[], sr: number, n: number, opts: Opts, seed: number) => {+ if (!Number.isFinite(sr) || sr <= 0 || !Number.isInteger(n) || n < 0) throw new Error("sampler: invalid sample rate or length");+ if (bank.entry.kind !== "struck") throw new Error(`${bank.entry.title}: ${bank.entry.zones.some((z) => !z.loop) ? "sustained zone without a loop" : "sustained banks are not supported in pack version 1"}`);+ const L = new Float32Array(n), R = new Float32Array(n), halo = new Float32Array(n), e = bank.entry;+ const sorted = keys.slice().sort((a, b) => a.t - b.t || a.p - b.p), usePedal = opts.pedal !== false, zones = sampleZones(bank, sorted, seed, usePedal ? pedal : []);+ const releases = e.damped && bank.zones.some(({ zone }) => zone.art === "rel") ? sampleZones(bank, sorted, seed + 401, [], "rel") : null;+ const id = "id" in bank ? String(bank.id) : "", grand = id.split(".")[0] === "piano" && !["upright", "honky"].includes(id.split(".")[1] ?? String(opts.variant));+ const pedalAt = (t: number) => usePedal && pedal.some(([a, b]) => t >= a && t < b);+ const pedalUpAfter = (t: number) => { for (const [a, b] of pedal) if (t >= a && t < b) return b; return t; };+ sorted.forEach((k, idx) => {+ const { zone: z, channels } = zones[idx], i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const rate = (48000 / sr) * (z.unpitched ? 1 : Math.pow(2, (k.p - z.midi) / 12 + (k.vary?.cents ?? 0) / 1200));+ const table = rate !== 1 ? sincTable(rate) : null, v = clamp(k.v, 0, 1);+ // Keep the source's layer levels intact. A normalized source gets all its dynamics from this law.+ const gain = sampleGain(e, z, v) * db((k.vary?.db ?? 0) + (bank.trim?.find((t) => t.file === z.file)?.correctionDb ?? 0));+ const fc = sampleCutoff(e, z, k, sr, typeof opts.sampleFilter === "string" ? opts.sampleFilter : undefined), alpha = 1 - Math.exp(-2 * Math.PI * fc / sr);+ let damp = e.damped ? (pedalAt(k.off) ? pedalUpAfter(k.off) : k.off) : Infinity;+ if (grand && k.p >= 89) damp = Infinity; // the top grand keys have no dampers; vibes and uprights still stop+ const releaseAt = damp;+ if (e.damped) for (let j = idx + 1; j < sorted.length; j++) if (sorted[j].p === k.p && sorted[j].t > k.t) { damp = Math.min(damp, sorted[j].t + 0.004); break; }+ const tDamp = 0.08 + 0.45 * clamp((60 - k.p) / 36, 0, 1), dampI = Math.round((damp - k.t) * sr), dec = Math.exp(-6.91 / (tDamp * sr));+ const len = Math.min(n - i0, Math.ceil(z.frames / rate), damp === Infinity ? Infinity : dampI + Math.round(tDamp * 1.6 * sr) + 1), inPedal = e.damped && (pedalAt(k.t) || pedalAt(k.t + 0.25));+ const read = (a: Float32Array, i: number) => table ? sincRead(a, i * rate, table) : a[i];+ const rel = releases?.[idx], window = Math.max(1, Math.round(0.02 * sr)); let remaining = 0, count = 0;+ let l = 0, r = 0, env = 1;+ for (let i = 0; i < len; i++) {+ if (i >= dampI) env *= dec;+ l = fc === Infinity ? read(channels[0], i) : l + alpha * (read(channels[0], i) - l); r = channels.length === 1 ? l : fc === Infinity ? read(channels[1], i) : r + alpha * (read(channels[1], i) - r);+ const j = i0 + i; if (j < 0) continue;+ const a = l * gain * env, b = r * gain * env; L[j] += a; R[j] += b;+ if (rel && i >= Math.max(0, dampI - window) && i < dampI) { remaining += (a * a + b * b) * 0.5; count++; }+ if (inPedal) halo[j] += 0.5 * (a + b);+ }+ // Match the release noise to the string's last 20 ms, 15 dB below it. Never extend a dead string.+ const allowance = k.p === e.range[0] || k.p === e.range[1] ? 3 : 2;+ if (rel && Number.isFinite(releaseAt) && dampI > 0 && (releaseAt - k.t) * sr < z.frames / rate && count && (rel.zone.unpitched || Math.abs(k.p - rel.zone.midi + (k.vary?.cents ?? 0) / 100) <= allowance)) {+ const rz = rel.zone, rr = 48000 / sr * (rz.unpitched ? 1 : Math.pow(2, (k.p - rz.midi) / 12 + (k.vary?.cents ?? 0) / 1200)), rt = rr !== 1 ? sincTable(rr) : null;+ const readRel = (a: Float32Array, i: number) => rt ? sincRead(a, i * rr, rt) : a[i];+ const size = Math.ceil(rz.frames / rr), ref = Math.min(size, Math.round(0.5 * sr)); let power = 0;+ for (let i = 0; i < ref; i++) { const a = readRel(rel.channels[0], i), b = readRel(rel.channels[rz.channels - 1], i); power += (a * a + b * b) * 0.5; }+ const g = power > 0 ? Math.sqrt(remaining / count / (power / ref)) * db(-15) * Math.pow(dec, Math.round((releaseAt - damp) * sr)) : 0, start = Math.round(releaseAt * sr);+ for (let i = 0; i < size && start + i < n; i++) if (start + i >= 0) { L[start + i] += readRel(rel.channels[0], i) * g; R[start + i] += readRel(rel.channels[rz.channels - 1], i) * g; }+ }+ });+ return { L, R, halo };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/audio.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/audio.tsnew file mode 100644index 0000000..1070d1d--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/audio.ts@@ -0,0 +1,24 @@+import { Biquad } from '../canvas-core/music/dsp';+export type AudioPayload = { sampleRate: number; frames: number; float32: string };++/** Embedded Float32 is the complete Node mix, including cues. No decoder or fetch changes it. */+export const embeddedAudio = (a: AudioPayload) => {+ const bytes = atob(a.float32), data = new Uint8Array(bytes.length);+ for (let i = 0; i < data.length; i++) data[i] = bytes.charCodeAt(i);+ if (data.length !== a.frames * 8 || !Number.isSafeInteger(a.sampleRate) || a.sampleRate <= 0) throw new Error('invalid embedded film audio');+ const view = new DataView(data.buffer), L = new Float32Array(a.frames), R = new Float32Array(a.frames);+ for (let i = 0; i < a.frames; i++) { L[i] = view.getFloat32(i * 8, true); R[i] = view.getFloat32(i * 8 + 4, true); }+ const cache = new Map<number, [Float32Array, Float32Array]>([[a.sampleRate, [L, R]]]);+ return (sr: number): [Float32Array, Float32Array] => {+ if (!Number.isSafeInteger(sr) || sr <= 0) throw new Error('invalid film audio sample rate');+ const hit = cache.get(sr); if (hit) return hit;+ const resample = (c: Float32Array) => {+ const source = Float32Array.from(c);+ if (sr < a.sampleRate) for (const q of [0.5412, 1.3066]) Biquad.make(a.sampleRate, 'lp', sr * 0.45, q).run(source);+ const out = new Float32Array(Math.round(a.frames * sr / a.sampleRate));+ for (let i = 0; i < out.length; i++) { const x = i * a.sampleRate / sr, j = Math.floor(x), f = x - j; out[i] = (source[j] ?? 0) * (1 - f) + (source[Math.min(j + 1, source.length - 1)] ?? 0) * f; }+ return out;+ };+ const out: [Float32Array, Float32Array] = [resample(L), resample(R)]; cache.set(sr, out); return out;+ };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.tsindex d1422fb..eafcbcb 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts@@ -3,8 +3,9 @@// Audio) lives HERE; the art core never sees it.import type { Ctx, Env, Layer, ProbeRec } from "../canvas-core/core";import { Film, renderFrame, validate } from "../canvas-core/film";+import { embeddedAudio, type AudioPayload } from './audio';-declare global { interface Window { FILM: unknown; __ASSETS__?: Record<string, string>; __BAKE_SRC__?: Record<string, string>; __ANIDOODLE_SRC__?: WeakMap<object, string>; __SHAPE__?: string } }+declare global { interface Window { FILM: unknown; __ASSETS__?: Record<string, string>; __BAKE_SRC__?: Record<string, string>; __ANIDOODLE_SRC__?: WeakMap<object, string>; __SHAPE__?: string; __AUDIO__?: AudioPayload } }// THE BAKE STORE (Env.bake). A finished plate frame, keyed by the hash of the source that draws it// (build-page.mjs hashes each film module's whole import closure, plus the engine's own renderer),@@ -34,6 +35,7 @@ const bakeStore = (surface: (w: number, h: number) => Layer) => {export const mountFilm = (film: Film) => {// <film>-<shape> (build-page.mjs sets __SHAPE__): the same film, re-composed for that frameif (window.__SHAPE__) { if (!film.reshape) throw new Error(`${film.meta.title} has one shape; ${window.__SHAPE__} is for launch template films (film.reshape)`); film = film.reshape(window.__SHAPE__); }+ const filmSound = window.__AUDIO__ ? embeddedAudio(window.__AUDIO__) : film.audio;const canvas = document.getElementById("film") as HTMLCanvasElement, images = new Map<string, CanvasImageSource>();let env: Env, ctx: Ctx, current = 0;// Safari before 16.4 has no 2D OffscreenCanvas: fall back to a detached <canvas>. The core cannot tell the difference.@@ -150,7 +152,7 @@ export const mountFilm = (film: Film) => {} finally { protos.forEach((p, i) => (p.fillText = orig[i] as never)); delete g.__ANIDOODLE_PROBE__; }return out;};- const audio = (sr: number) => { if (!film.audio) return null; const [L, R] = film.audio(sr); if (L.length !== R.length) throw new Error("audio channels have different lengths"); const pcm = new Float32Array(L.length * 2); for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; } return { sampleRate: sr, frames: L.length, float32: b64(new Uint8Array(pcm.buffer)) }; };+ const audio = (sr: number) => { if (!filmSound) return null; const [L, R] = filmSound(sr); if (L.length !== R.length) throw new Error("audio channels have different lengths"); const pcm = new Float32Array(L.length * 2); for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; } return { sampleRate: sr, frames: L.length, float32: b64(new Uint8Array(pcm.buffer)) }; };const warm = () => film.shots.forEach((s) => { seek(s.start); seek(s.start + ((s.end - s.start) >> 1)); }); // first + middle frame of every shot: builds tiles, pre-allocates the layer pool// POSTER. Platforms show frame 0 as the thumbnail, so a delivery may open on a chosen frame (the// wall of styles, the logo) and dissolve into the film's real opening over `fade` frames. The@@ -181,7 +183,7 @@ export const mountFilm = (film: Film) => {const stop = () => { playing = false; node?.stop(); node = null; };const play = () => {ac ??= new (window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)(); playing = true; f0 = current >= film.meta.durationFrames - 1 ? 0 : current; t0 = ac.currentTime;- if (film.audio) { const [L, R] = film.audio(ac.sampleRate), buf = ac.createBuffer(2, L.length, ac.sampleRate); buf.getChannelData(0).set(L); buf.getChannelData(1).set(R); node = ac.createBufferSource(); node.buffer = buf; node.connect(ac.destination); node.start(0, f0 / film.meta.fps); }+ if (filmSound) { const sr = window.__AUDIO__?.sampleRate ?? ac.sampleRate, [L, R] = filmSound(sr), buf = ac.createBuffer(2, L.length, sr); buf.getChannelData(0).set(L); buf.getChannelData(1).set(R); node = ac.createBufferSource(); node.buffer = buf; node.connect(ac.destination); node.start(0, f0 / film.meta.fps); }const tick = () => { if (!playing) return; const f = f0 + Math.floor((ac!.currentTime - t0) * film.meta.fps); if (f >= film.meta.durationFrames) { seek(film.meta.durationFrames - 1); stop(); return; } if (f !== current) seek(f); requestAnimationFrame(tick); }; tick();};const toggle = () => (playing ? stop() : play());diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/hostAudio.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/hostAudio.test.tsnew file mode 100644index 0000000..8b54044--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/hostAudio.test.ts@@ -0,0 +1,12 @@+import { embeddedAudio } from '../src/hosts/audio';+export const name = 'embedded film track';+export const run = (ok: (cond: boolean, label: string) => void) => {+ const sr = 48000, n = sr / 10, bytes = new Uint8Array(n * 8), view = new DataView(bytes.buffer);+ for (let i = 0; i < n; i++) { view.setFloat32(i * 8, 1.4 * Math.sin(2 * Math.PI * 18000 * i / sr), true); view.setFloat32(i * 8 + 4, -0.25, true); }+ const audio = embeddedAudio({ sampleRate: sr, frames: n, float32: btoa(String.fromCharCode(...bytes)) }), [L, R] = audio(sr);+ ok(L.every((v, i) => v === view.getFloat32(i * 8, true)) && R.every(v => v === -0.25), 'embedded stereo keeps every Float32 sample, including unclipped values');+ const [down] = audio(24000), [up] = audio(96000), [device] = audio(44100);+ ok(down.length === n / 2 && up.length === n * 2 && device.length === 4410, 'alternate sample rates keep the complete track duration');+ ok(down.slice(100).reduce((e, x) => e + x * x, 0) / down.length < 0.01, 'downsampling removes tones above the new Nyquist frequency');+ ok(audio(sr)[0].every((v, i) => v === view.getFloat32(i * 8, true)), 'sample-rate conversion leaves the pinned 48 kHz master untouched');+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/launchTemplate.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/launchTemplate.test.tsindex 66078b8..497cf7d 100644--- a/plugins/anidoodle/skills/anidoodle/engine/test/launchTemplate.test.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/test/launchTemplate.test.ts@@ -20,6 +20,7 @@ export const run = (ok: (cond: boolean, label: string) => void) => {});let film: Film | null = null; try { film = makeLaunchFilm({ ...base, score: mine }); } catch (e) { ok(false, `a composed Material is accepted: ${(e as Error).message}`); }ok(!!film && typeof film.audio === "function", "a composed Material is accepted as the score");+ ok(film?.audio?.scores?.length === 1, "film audio exposes its fitted score so hosts load only its recorded instruments");ok(refused(launchLofi3), "refuses our launch score by identity");ok(refused(launchLofi3Material), "refuses our launch score's material by identity");ok(refused(chiptunePlayful), "refuses a demo");diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/recordedMix.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/recordedMix.test.tsnew file mode 100644index 0000000..eb06294--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/recordedMix.test.ts@@ -0,0 +1,57 @@+import { registerBank, clearBanks, type SampleBank } from '../src/canvas-core/music/sampler';+import { calibrateBank, renderPiece } from '../src/canvas-core/music/render';+import { maskingPlan, roleBandDb } from '../src/canvas-core/music/guards';+import { perform } from '../src/canvas-core/music/perform';+import { Biquad } from '../src/canvas-core/music/dsp';+import { hz } from '../src/canvas-core/music/theory';+import { marimbaCurious } from '../src/canvas-core/music/pieces/families';+import type { Piece, Role } from '../src/canvas-core/music/plan';++export const name = 'recorded support mix';+export const run = (ok: (cond: boolean, label: string) => void) => {+ const sr = 24000, frames = 48000, pitches = [48, 60, 72];+ const zones = pitches.map((midi, i) => {+ const pcm = Float32Array.from({ length: frames }, (_, n) => {+ const t = n / 48000, f = hz(midi);+ return 0.2 * Math.exp(-t * 3) * (Math.sin(2 * Math.PI * f * t) + (i < 2 ? 0.8 * Math.sin(2 * Math.PI * f * 5 * t) : 0));+ });+ return { zone: { file: `${midi}.flac`, midi, layer: 1, rr: 1, frames, channels: 1, peakDb: -6, rmsDb: -18, sha256: String(i + 1).repeat(64) }, channels: [pcm] };+ });+ const bank: SampleBank = { entry: { title: 'spectral fixture', source: 'synthetic', license: 'CC0-1.0', kind: 'struck', range: [48, 72], layers: 1, damped: false, normalized: false, zones: zones.map(z => z.zone) }, zones };+ const source = marimbaCurious();+ const part = source.parts[0];+ const piece = (role: Role, mixed = false): Piece => ({ ...source, tail: 0.2,+ plan: { ...source.plan, space: undefined }, mix: { ...source.mix, eq: 0, transient: null, space: null, drumRoom: null, tilt: 0, busDrive: 0, glue: null, width: { mid: 1, high: 1, monoHz: 0, splitHz: 800 } },+ parts: [{ ...part, inst: 'marimba', role, pan: 0, gainDb: 0, notes: mixed+ ? [{ t: 0, d: 0.4, p: 48, v: 0.5, role: 'bass' }, { t: 0.5, d: 0.4, p: 72, v: 0.5, role: 'accomp' }, { t: 1, d: 0.4, p: 72, v: 0.5, role: 'accomp' }]+ : [{ t: 0, d: 0.4, p: role === 'bass' ? 48 : 60, v: 0.5, role }] }] });+ const fraction = (a: Float32Array) => {+ const x = Biquad.make(sr, 'hp', 40, Math.SQRT1_2).run(Float32Array.from(a));+ const total = x.reduce((s, v) => s + v * v, 0);+ Biquad.make(sr, 'hp', 500, Math.SQRT1_2).run(x); Biquad.make(sr, 'lp', 4000, Math.SQRT1_2).run(x);+ return 10 * Math.log10(x.reduce((s, v) => s + v * v, 0) / total);+ };+ const rms = (a: Float32Array) => Math.sqrt(a.reduce((s, v) => s + v * v, 0) / a.length);+ clearBanks();+ try {+ registerBank('marimba', bank); const calibrated = calibrateBank('marimba');+ const neutral = { ...calibrated, trim: calibrated.trim!.map(t => ({ ...t, bandFractionDb: -40, bandExcessDb: 0 })) };+ const render = (role: Role) => renderPiece(piece(role), sr, { seconds: 2, master: 'none', expressive: false }).dry[0];+ registerBank('marimba', neutral); const unchanged = render('melody'), bassBefore = render('bass'), accompBefore = render('accomp');+ registerBank('marimba', calibrated); const lead = render('melody'), bass = render('bass'), accomp = render('accomp');+ ok(lead.every((v, i) => v === unchanged[i]), 'recorded melody keeps every sample when support EQ measurements change');+ ok(fraction(bass) < fraction(bassBefore) - 2 && fraction(accomp) < fraction(accompBefore) - 1, 'load-measured recorded bass and accompaniment lose masking-band energy');+ ok(Math.abs(20 * Math.log10(rms(bass) / rms(bassBefore))) < 2.5 && Math.abs(20 * Math.log10(rms(accomp) / rms(accompBefore))) < 2.5, 'support EQ retains broadband balance through the existing makeup stage');+ // Keep this fixture below the EQ cap so a wrong role-only selection is audible.+ registerBank('marimba', { ...calibrated, trim: calibrated.trim!.map(t => ({ ...t,+ bandExcessDb: 0, bandFractionDb: t.midi === 48 ? -10 : -6 })) });+ const p = piece('accomp', true);+ // Include one melody note so the guard has a melody role; keep the complete accompaniment context.+ p.parts[0].notes[2].role = 'melody';+ const complete = perform(p, p.plan.tempo, { expressive: false }), plan = maskingPlan(p, { seconds: 2, perf: complete })!;+ const isolated = { ...complete, parts: complete.parts.map(q => ({ ...q, keys: q.keys.filter(k => k.role === 'bass') })) };+ const expected = roleBandDb(p, sr, { seconds: 2, master: 'none', perf: isolated, mixKeys: complete.parts.map(q => q.keys) }, plan.spans);+ const actual = roleBandDb(p, sr, plan.opts('bass'), plan.spans);+ ok(actual.every((v, i) => Math.abs(v - expected[i]) < 1e-8), 'role-isolated guard uses the complete part spectral choice, including mixed-role parts');+ } finally { clearBanks(); }+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/rooms.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/rooms.test.tsnew file mode 100644index 0000000..aee11cb--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/rooms.test.ts@@ -0,0 +1,68 @@+// Recorded responses change the room, never the dry mix. Missing packs retain the old spaces.+import { registerRoom, roomFor, clearRooms, reverb, type Space } from "../src/canvas-core/music/mixReverb";+import { renderPiece, voiceJobs, voiceJobKey, runVoiceJob } from "../src/canvas-core/music/render";+import { nocturne } from "../src/canvas-core/music/pieces/nocturne";+import { rng } from "../src/canvas-core/core";+import { MIX_PROFILES } from '../src/canvas-core/music/mixProfiles';+import { musicBoxJoy, chiptunePlayful } from '../src/canvas-core/music/pieces/samplers';+import { Biquad } from '../src/canvas-core/music/dsp';+const fsModule = 'node:fs', { readFileSync } = await import(fsModule);+export const name = "recorded rooms";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const same = (a: Float32Array, b: Float32Array) => a.length === b.length && a.every((v, i) => v === b[i]);+ const throws = (f: () => unknown) => { try { f(); return false; } catch { return true; } };+ clearRooms();+ try {+ const builder = readFileSync('tools/soundpack.mjs', 'utf8').match(/const ROOMS = \[([\s\S]*?)\n\];/)[1];+ const roomIds = new Set([...builder.matchAll(/id: "([^"]+)"/g)].map((m: any) => m[1]));+ ok(Object.values(MIX_PROFILES).every(p => [p.space?.room, p.drumRoom?.room].every(id => !id || roomIds.has(id))), 'every profile room is present in the pack builder room list');+ const L = new Float32Array(9600), R = new Float32Array(9600); L[0] = 0.6; R[0] = 0.5; L[3840] = 0.4; R[4320] = -0.4;+ const p = nocturne(), roomPiece = { ...p, plan: { ...p.plan, space: { ...p.plan.space, room: "test" } } }, o = { seconds: 0.7, master: "none" as const, stems: true }, before = renderPiece(p, 48000, o), missing = renderPiece(roomPiece, 48000, o), jobs = voiceJobs(roomPiece, 48000, o);+ ok(same(before.L, missing.L) && same(before.R, missing.R), "unregistered room falls back bit for bit");+ registerRoom("test", { L, R, rt60: 0.2, sha256: "a".repeat(64) });+ const recorded = renderPiece(roomPiece, 48000, o), again = renderPiece(roomPiece, 48000, o);+ ok(same(before.dry[0], recorded.dry[0]) && same(before.dry[1], recorded.dry[1]) && Object.keys(before.stems).every((id) => same(before.stems[id][0], recorded.stems[id][0])), "registered room leaves dry mix and stems untouched");+ ok(!same(before.wet[0], recorded.wet[0]) && same(recorded.L, again.L) && same(recorded.R, again.R), "recorded wet signal changes and is deterministic");+ const registeredJobs = voiceJobs(roomPiece, 48000, o);+ ok(registeredJobs.every((j, i) => voiceJobKey(j) !== voiceJobKey(jobs[i]) && j.roomHashes?.[0][1] === "a".repeat(64)), "room sha256 pins voice and guard job keys");+ const cache = new Map(), cached = renderPiece(roomPiece, 48000, { ...o, cache });+ ok(same(cached.L, recorded.L) && same(renderPiece(roomPiece, 48000, { ...o, cache }).L, recorded.L), "room renders are identical through cache hits");+ const low = renderPiece(roomPiece, 24000, o);+ ok(low.L.length === 16800 && low.L.every(Number.isFinite) && low.R.every(Number.isFinite) && same(low.L, renderPiece(roomPiece, 24000, o).L), "24 kHz recorded room renders finite and deterministically");+ const s: Space = { kind: "conv", room: "test", rt60: 1, er: 0.4, late: 0.2, hp: 100, lp: 7000, predelayMs: 20 }, impulse = new Float32Array(24000); impulse[0] = 1;+ const wet = reverb(impulse, impulse, 48000, s, rng(1)), lateOnly = reverb(impulse, impulse, 48000, { ...s, er: 0 }, rng(1)), earlyOnly = reverb(impulse, impulse, 48000, { ...s, late: 0 }, rng(1));+ ok(wet[0].slice(0, 960).every((x) => Math.abs(x) < 1e-7) && wet[2].slice(0, 960 + 1920).every((x) => Math.abs(x) < 1e-7), "predelay and 40 ms early/late split keep their timing");+ ok(same(wet[2], lateOnly[2]) && earlyOnly[2].every((x) => x === 0) && !same(earlyOnly[0], wet[0]), "er and late independently control the recorded reflections and tail");+ registerRoom("test", { L: Float32Array.from(L, (x) => -x), R, rt60: 0.2, sha256: "b".repeat(64) });+ ok(voiceJobKey(voiceJobs(roomPiece, 48000, o)[0]) !== voiceJobKey(registeredJobs[0]) && throws(() => runVoiceJob(registeredJobs[0])) && !same(renderPiece(roomPiece, 48000, { ...o, cache }).L, cached.L), "replacing a room invalidates jobs and cache identity");+ ok(throws(() => registerRoom("bad", { L, R: new Float32Array(1), rt60: 0.2, sha256: "c".repeat(64) })) && !roomFor("bad"), "invalid room PCM is rejected before registration");+ clearRooms();+ for (const kind of ["conv", "plate", "fdn"] as const) {+ const a = reverb(impulse, impulse, 48000, { ...s, kind, room: undefined }, rng(3)), b = reverb(impulse, impulse, 48000, { ...s, kind }, rng(3));+ ok(a.every((c, i) => same(c, b[i])), `${kind}: missing room preserves every wet channel bit for bit`);+ }+ for (const make of [musicBoxJoy, chiptunePlayful]) {+ const p = make(), before = renderPiece(p, 24000, o), unknown = renderPiece({ ...p, plan: { ...p.plan, space: { room: 'not-installed' } } }, 24000, o);+ ok(same(before.L, unknown.L) && same(before.R, unknown.R), `${make.name}: an unavailable room-only override retains the original no-pack recipe`);+ }+ const ir = new Float32Array(4800); ir[0] = 0.8; ir[119] = 0.2; ir[240] = 0.1; ir[2400] = 0.01;+ const recordedRoom = { L: ir, R: Float32Array.from(ir), rt60: 0.1, sha256: 'd'.repeat(64), directFrames: 120 };+ registerRoom('trimmed', recordedRoom);+ const roomSpace = { ...s, room: 'trimmed', predelayMs: 0, er: 1, late: 1 };+ for (const rate of [48000, 24000]) {+ const input = new Float32Array(rate / 2); input[0] = 1;+ const a = reverb(input, input, rate, roomSpace, rng(1));+ ok(a[0].slice(0, Math.round(120 * rate / 48000)).every(x => Math.abs(x) < 1e-7), `${rate} Hz: directFrames is removed before the wet reflections`);+ }+ const a = reverb(impulse, impulse, 48000, roomSpace, rng(1));+ const filtered = Float32Array.from(impulse); Biquad.make(48000, 'hp', s.hp, 0.7071).run(filtered); Biquad.make(48000, 'lp', s.lp, 0.7071).run(filtered);+ const energy = (x: Float32Array) => x.reduce((sum, v) => sum + v * v, 0);+ const early = reverb(impulse, impulse, 48000, { ...roomSpace, late: 0 }, rng(1));+ ok(Math.abs(energy(a[2]) / energy(filtered) - (1.5 * 0.36) ** 2) < 1e-6 && Math.abs(energy(early[0]) / energy(filtered) - 0.51 ** 2) < 1e-6, 'recorded early and late each use synthIR unit-per-channel energy');+ registerRoom('trimmed', { ...recordedRoom, directFrames: 121 });+ const named = { ...p, plan: { ...p.plan, space: { room: 'trimmed' } } }, oldJobs = voiceJobs(named, 48000, o);+ registerRoom('trimmed', { ...recordedRoom, directFrames: 122 });+ ok(voiceJobKey(oldJobs[0]) !== voiceJobKey(voiceJobs(named, 48000, o)[0]) && throws(() => runVoiceJob(oldJobs[0])), 'directFrames participates in room cache identity and stale-job rejection');+ ok(throws(() => registerRoom('bad-direct', { ...recordedRoom, directFrames: -1 })), 'invalid directFrames is rejected');+ } finally { clearRooms(); }+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sampler.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sampler.test.tsnew file mode 100644index 0000000..e77b6c8--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/sampler.test.ts@@ -0,0 +1,194 @@+// Tiny synthetic recordings: pitch, dynamics, dampers, bank routing and cache identity, no files.+import { registerBank, bankFor, clearBanks, samplerVoice, sampleZones, sampleCutoff, sampleGain, bankIdentity, type SampleBank, type SampleZone } from "../src/canvas-core/music/sampler";+import { renderPiece, voiceJobs, runVoiceJob, voiceJobKey, calibrateBank } from "../src/canvas-core/music/render";+import { nocturne } from "../src/canvas-core/music/pieces/nocturne";+import { marimbaCurious } from "../src/canvas-core/music/pieces/families";+import { hz } from "../src/canvas-core/music/theory";+import { centroid, stemRms } from "../src/canvas-core/music/meter";+import { pianoVelocity } from "../src/canvas-core/music/keysPiano";+import { Biquad } from "../src/canvas-core/music/dsp";+import { ampSim, transientGain } from "../src/canvas-core/music/mixDsp";+import { lofiStem, LOFI_DUSTY } from "../src/canvas-core/music/lofiFx";+import type { Played } from "../src/canvas-core/music/perform";+const cryptoModule = "node:crypto", { createHash } = await import(cryptoModule);++export const name = "sampler";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const SR = 48000, key = (p = 60, v = 1, t = 0, off = 0.2): Played => ({ p, v, t, off, role: "melody", w: v });+ const bank = (pitches = [60], layers = 1, rrs = 1, damped = false, rich = false): SampleBank => {+ const zones: SampleBank["zones"] = [];+ for (const midi of pitches) for (let layer = 1; layer <= layers; layer++) for (let rr = 1; rr <= rrs; rr++) {+ const a = new Float32Array(SR * 3), f = hz(midi);+ for (let i = 0; i < a.length; i++) a[i] = 0.3 * Math.exp(-i / (SR * 2)) * (Math.sin(2 * Math.PI * f * i / SR + (rr - 1) * 0.3) + (rich ? 0.7 * Math.sin(2 * Math.PI * 6500 * i / SR) : 0));+ const zone: SampleZone = { file: `${midi}_${layer}_${rr}.flac`, midi, layer, rr, frames: a.length, channels: 1, peakDb: -6, rmsDb: -14, sha256: (midi * 100 + layer * 10 + rr).toString(16).padStart(64, "0") };+ zones.push({ zone, channels: [a] });+ }+ return { entry: { title: "Test", source: "synthetic", license: "CC0-1.0", kind: "struck", range: [21, 108], layers, damped, normalized: true, zones: zones.map((z) => z.zone) }, zones };+ };+ const render = (b: SampleBank, ks = [key()], sr = SR, pedal: [number, number][] = [], opts = {}, seed = 1) => samplerVoice(b, ks, pedal, sr, sr * 3, opts, seed);+ const same = (a: Float32Array, b: Float32Array) => a.length === b.length && a.every((v, i) => v === b[i]);+ const rms = (a: Float32Array) => Math.sqrt(a.reduce((s, v) => s + v * v, 0) / Math.max(1, a.length));+ const throws = (f: () => unknown, re: RegExp) => { try { f(); return false; } catch (e) { return re.test(String(e)); } };+ const pitch = (a: Float32Array, sr: number) => {+ const ts = []; for (let i = Math.round(sr * 0.1); i < sr * 0.6; i++) if (a[i - 1] <= 0 && a[i] > 0) ts.push(i - 1 - a[i - 1] / (a[i] - a[i - 1]));+ return sr * (ts.length - 1) / (ts[ts.length - 1] - ts[0]);+ };+ const cents = (f: number, m: number) => Math.abs(1200 * Math.log2(f / hz(m)));+ clearBanks();+ try {+ const b = bank(), a = render(b), up = render(b, [key(62)]), lowRate = render(b, [key(62)], 24000);+ ok(cents(pitch(up.L, SR), 62) < 3, "two-semitone repitch is within 3 cents");+ ok(cents(pitch(lowRate.L, 24000), 62) < 3 && lowRate.L.every(Number.isFinite), "24 kHz stems render finite and in tune");+ // Unity playback still has the velocity low-pass, but the source reader must use integer frames.+ const expected = Float32Array.from(b.zones[0].channels[0], (v) => v * sampleGain(b.entry, b.zones[0].zone, 1));+ ok(same(a.L, expected) && same(a.L, a.R), "in-tune 48 kHz mono keeps original attack frames above the layer centre");+ const rich = bank([60], 1, 1, false, true), soft = render(rich, [key(60, 0.2)]), loud = render(rich, [key()]);+ ok(rms(loud.L) > rms(soft.L) * 3 && centroid([soft.L, soft.R], SR).energyWeighted > centroid([loud.L, loud.R], SR).energyWeighted * 0.85, "normalized dynamics stay expressive and soft notes retain their attack spectrum");+ const natural = bank([60], 2); natural.entry.normalized = false; natural.zones[1].channels[0] = Float32Array.from(natural.zones[0].channels[0], (v) => v * 2);+ const softLayer = render(natural, [{ ...key(60, 0.25), tone: 0.25 }]), hardLayer = render(natural, [{ ...key(60, 0.75), tone: 0.75 }]);+ ok(rms(hardLayer.L) > rms(softLayer.L) * 1.9, "unnormalized layers retain the source's level relationship");+ const damped = bank([60], 1, 1, true), dry = render(damped), held = render(damped, [key()], SR, [[0, 2]]), noPedal = render(damped, [key()], SR, [[0, 2]], { pedal: false });+ const tail = (o: { L: Float32Array }) => rms(o.L.subarray(Math.round(SR * 1.2), Math.round(SR * 1.4)));+ ok(tail(dry) === 0 && tail(noPedal) === 0 && tail(held) > 0.01 && tail(a) > 0.01, "middle-register damper is silent 1 s after lift; pedal holds; undamped rings");+ ok(rms(held.halo!) > 0 && rms(noPedal.halo!) === 0, "the pedal feeds a room halo and pedal:false disables it");+ const caught = render(damped, [key()], SR, [[0.2, 1.5]]), boundary = render(damped, [key()], SR, [[0, 0.2]]);+ ok(tail(caught) > 0.01 && tail(boundary) === 0, "pedal spans use the piano's inclusive down, exclusive up boundary");+ const registers = bank([36, 90], 1, 1, true), bass = render(registers, [key(36)]), treble = render(registerBank("piano", registers), [key(90)]);+ ok(rms(bass.L.subarray(SR * 0.3, SR * 0.4)) > 0 && tail(treble) > 0.01, "bass dampers close slowly; top grand keys have no dampers");+ ok(tail(render(registerBank("vibes", registers), [key(90)])) === 0 && tail(render(registerBank("piano.upright", registers), [key(90)])) === 0, "vibes and upright top keys still have dampers");+ clearBanks();+ ok(throws(() => render(b, [key(20)]), /Ab0.*A0.*C8/), "out-of-range note throws with note name and playable range");+ const varied = { ...key(), vary: { cents: 12, db: -6, bright: 1, decay: 1, phase: 0, seed: 17 } }, detuned = render(b, [varied]);+ ok(Math.abs(1200 * Math.log2(pitch(detuned.L, SR) / hz(60)) - 12) < 3 && rms(detuned.L) < rms(a.L) * 0.6, "per-note cents and dB are applied");+ const unpitched = bank(); unpitched.zones[0].zone.unpitched = true;+ ok(cents(pitch(render(unpitched, [varied]).L, SR), 60) < 3 && same(render(unpitched, [key(62)]).L, a.L), "unpitched zones never transpose, including cents variation");+ ok(same(render(b).L, a.L) && same(render(b, [key()], SR, [], {}, 99).L, a.L), "deterministic output; changing seed cannot change a single recording");++ const rb = bank([60, 63], 3, 3), repeated = Array.from({ length: 8 }, (_, i) => ({ ...key(61, 0.65, i * 0.3), vary: { cents: 0, db: 0, bright: 1, decay: 1, phase: 0, seed: 42 } }));+ const picks = sampleZones(rb, repeated, 1);+ ok(picks.every((z) => z.zone.midi === 60 && z.zone.layer === 2), "nearest pitch is chosen before the nearest velocity layer");+ ok(picks.every((z, i) => !i || z !== picks[i - 1]), "round robins never repeat back to back, even with identical note seeds");+ ok(sampleZones(rb, repeated, 1).every((z, i) => z === picks[i]) && sampleZones(rb, repeated, 99).every((z, i) => z === picks[i]), "each note's own seed owns its round robin");+ const fallback = repeated.map(({ vary, ...k }) => k), p1 = sampleZones(rb, fallback, 1), p2 = sampleZones(rb, fallback, 2);+ ok(p1.some((z, i) => z !== p2[i]) && p2.every((z) => z.zone.midi === 60 && z.zone.layer === 2), "a changed fallback seed changes round robins only");+ const rrA = render(rb, repeated), rrB = render(rb, repeated);+ ok(same(rrA.L, rrB.L) && same(rrA.R, rrB.R) && same(rrA.halo!, rrB.halo!), "repeated-note renders are bit-identical");+ const sparse = bank([60, 63], 3); sparse.zones = sparse.zones.filter((z) => z.zone.midi !== 60 || z.zone.layer === 1); sparse.entry.zones = sparse.zones.map((z) => z.zone);+ ok(sampleZones(sparse, [key(61, 1)], 1)[0].zone.midi === 60, "a missing layer never pulls a note to a farther pitch");+ ok(sampleZones(rb, [key(60, 0.332), key(60, 1 / 3), key(60, 0.666), key(60, 2 / 3)], 1).map((z) => z.zone.layer).join() === "1,2,2,3", "default centres split layers at 1/3 and 2/3, boundaries choose the harder layer");+ const custom = bank([60], 3); custom.entry.layerVelocity = [0.1, 0.35, 0.6];+ ok(sampleZones(custom, [key(60, 0.55), { ...key(60, 1), tone: 0.2 }], 1).map((z) => z.zone.layer).join() === "3,3", "manifest centres override defaults; played velocity owns the layer, tone only shapes the filter");+ const arts = bank([60], 2, 2, true), add = (art: "sus" | "rel") => {+ for (const z of arts.zones.slice().filter((z) => !z.zone.art)) { const zone = { ...z.zone, art, file: `${art}_${z.zone.file}`, sha256: (art === "sus" ? "a" : "b").repeat(64) }, channels = [art === "rel" ? new Float32Array(480).fill(0.25) : Float32Array.from(z.channels[0], (v) => v * 0.5)]; zone.frames = channels[0].length; arts.zones.push({ zone, channels }); }+ arts.entry.zones = arts.zones.map((z) => z.zone);+ };+ add("sus"); add("rel");+ const strikes = [key(60, 0.2, 0), key(60, 0.2, 0.2), key(60, 0.8, 0.5), key(60, 0.2, 1)];+ ok(sampleZones(arts, strikes, 7, [[0.2, 1]]).map((z) => z.zone.art ?? "ordinary").join() === "ordinary,sus,sus,ordinary", "sus only for strikes under the pedal, including both boundaries");+ const missingSus = { ...arts, zones: arts.zones.filter((z) => z.zone.art !== "sus" || z.zone.layer === 1) };+ ok(!sampleZones(missingSus, [key(60, 0.8)], 1, [[0, 1]])[0].zone.art, "missing sus at the ordinary pitch/layer falls back to ordinary");+ const ordinary = { ...arts, zones: arts.zones.filter((z) => !z.zone.art) }, withoutRel = { ...arts, zones: arts.zones.filter((z) => z.zone.art !== "rel") };+ ok(same(render(arts, [key()], SR, [[0, 2]], { pedal: false }).L.subarray(0, SR * 0.2), render(ordinary, [key()]).L.subarray(0, SR * 0.2)), "pedal:false never selects a sus recording");+ const release = (off: number, pedal: [number, number][] = []) => { const ks = [key(60, 0.5, 0, off)], a = render(arts, ks, SR, pedal), b = render(withoutRel, ks, SR, pedal); return Float32Array.from(a.L, (v, i) => v - b.L[i]); };+ const relEarly = release(0.1), relLate = release(1), relHeld = release(0.1, [[0.05, 1.2]]);+ ok(relEarly.slice(0, SR * 0.1).every((x) => x === 0) && rms(relEarly.subarray(SR * 0.1, SR * 0.11)) > 0 && relEarly.slice(SR * 0.11).every((x) => x === 0), "rel fires once at key-up for its exact recorded duration");+ ok(relHeld.slice(0, SR * 1.2).every((x) => x === 0) && rms(relHeld.subarray(SR * 1.2, SR * 1.21)) > 0 && relHeld.slice(SR * 1.21).every((x) => x === 0), "a caught note fires rel at pedal-up, once");+ const overlapping = [key(60, 0.5, 0, 0.12), key(60, 0.5, 0.1, 0.3)], overlapWith = render(arts, overlapping), overlapDry = render(withoutRel, overlapping), overlapRel = Float32Array.from(overlapWith.L, (x, i) => x - overlapDry.L[i]);+ ok(overlapRel.subarray(0, SR * 0.12).every((x) => x === 0) && rms(overlapRel.subarray(SR * 0.12, SR * 0.13)) > 0 && overlapRel.subarray(SR * 0.13, SR * 0.3).every((x) => x === 0) && rms(overlapRel.subarray(SR * 0.3, SR * 0.31)) > 0, "restruck notes release at each actual key-up, never at the artificial string choke");+ const ownLevel = rms(render(withoutRel, [key(60, 0.5, 0, 0.1)]).L.subarray(SR * 0.08, SR * 0.1));+ ok(Math.abs(20 * Math.log10(rms(relEarly.subarray(SR * 0.1, SR * 0.11)) / ownLevel) + 15) < 0.01 && rms(relEarly) > rms(relLate) * 1.4, "rel is 15 dB below the remaining string level, later releases are quieter");+ const undamped = { ...arts, entry: { ...arts.entry, damped: false } };+ ok(same(render(undamped).L, render({ ...undamped, zones: undamped.zones.filter((z) => z.zone.art !== "rel") }).L), "undamped instruments never add rel");+ const top = bank([90], 1, 1, true), relTop = { ...top.zones[0], zone: { ...top.zones[0].zone, art: "rel" as const }, channels: [new Float32Array(SR * 3).fill(0.25)] }; top.zones.push(relTop); top.entry.zones.push(relTop.zone);+ ok(same(render(registerBank("piano", top), [key(90)]).L, render({ ...top, entry: { ...top.entry, damped: false } }, [key(90)]).L), "undamped grand treble never adds rel"); clearBanks();+ ok(same(render(arts, strikes, SR, [[0.2, 1]], {}, 7).L, render(arts, strikes, SR, [[0.2, 1]], {}, 7).L), "sus and rel round robins render deterministically");+ ok(same(render(arts, [key(64)]).L, render(withoutRel, [key(64)]).L), "rel outside the two-semitone allowance is skipped");+ const ordinaryHash = bankIdentity(arts.entry), changedArt = { ...arts.entry, zones: arts.entry.zones.map((z) => z.art === "sus" ? { ...z, art: "rel" as const } : z) };+ ok(bankIdentity(changedArt) !== ordinaryHash, "articulations belong in the bank identity");+ ok(Math.abs(sampleCutoff(custom.entry, custom.zones[1].zone, { ...key(), tone: 0.2 }, SR, "relative") - (350 + 17650 * 0.85 ** 2)) < 1e-8 && sampleCutoff(custom.entry, custom.zones[1].zone, { ...key(), tone: 0.35 }, SR, "relative") === Infinity, "relative filter uses the chosen centre, bypassing at and above it");+ ok(same(render(b, [key()], SR, [], { sampleFilter: "off" }).L, expected), "filter-off plays unity-rate PCM with only its dynamic gain");+ ok(sampleGain(natural.entry, natural.zones[0].zone, 0.25) === 1 && Math.abs(20 * Math.log10(sampleGain(natural.entry, natural.zones[0].zone, 0.35)) - 1.6) < 1e-10 && sampleGain(natural.entry, natural.zones[0].zone, 0) === 0, "non-normalized gain is unity at the layer centre, gently relative below and above, silent at zero");+ ok([0.1, 0.3, 0.6, 0.8, 1].every((v) => sampleGain(b.entry, b.zones[0].zone, v) === pianoVelocity(v) * Math.pow(10, -8 * Math.max(0, 0.6 - v) / 20)), "normalized banks use exactly the modeled piano velocity law, including its soft-register level compensation");+ const calibration = bank([60], 3, 2); calibration.entry.normalized = false;+ for (const z of calibration.zones) { const v = (z.zone.layer - 0.5) / 3, dynamic = pianoVelocity(v) * Math.pow(10, -8 * Math.max(0, 0.6 - v) / 20); z.channels[0] = Float32Array.from(z.channels[0], (x) => x * dynamic); }+ const original = calibration.zones.map((z) => Float32Array.from(z.channels[0])); registerBank("piano", calibration);+ const calibrated = calibrateBank("piano"), redo = calibrateBank("piano");+ ok(calibrated.hash === redo.hash && JSON.stringify(calibrated.trim) === JSON.stringify(redo.trim), "pitch/layer calibration is deterministic from PCM and fixed modeled references");+ ok(calibrated.trim!.every(t => Number.isFinite(t.bandFractionDb) && Number.isFinite(t.bandExcessDb)), "load calibration measures every zone's masking-band fraction and excess over its modeled reference");+ ok(calibrated.zones.every((z, i) => same(z.channels[0], original[i])), "calibration never changes recording PCM or tone");+ const measured = (x: Float32Array, y: Float32Array) => { const mid = Float32Array.from(x, (v, i) => (v + y[i]) * 0.5); Biquad.make(SR, "hp", 30, 0.7071).run(mid); let energy = 0; for (const v of mid) energy += v * v; return 10 * Math.log10(energy / (SR * 12)); };+ const levels = [1, 2, 3].map((layer) => { const v = (layer - 0.5) / 3, r = render(calibrated, [{ ...key(60, v, 0, 1), tone: v }], SR, [], { pedal: false }); return measured(r.L, r.R); });+ const refs = [1, 2, 3].map((layer) => calibrated.trim!.find((t) => t.layer === layer)!.modeledDb);+ ok(calibrated.trim!.every((t) => !t.boostLimited && Math.abs(t.correctionDb - t.requestedDb!) < 1e-9) && levels.every((v, i) => Math.abs(v - refs[i]) <= 0.15) && levels.slice(1).every((v, i) => v - levels[i] >= refs[i + 1] - refs[i] - 0.15), "healthy calibrated layers meet fixed references and preserve at least the modeled dynamic range");+ ok([0.05, 0.25, 0.65, 1].every((v) => Math.abs(20 * Math.log10(sampleGain(calibration.entry, calibration.zones[2].zone, v))) <= 6.000001), "calibrated non-normalized notes add only a bounded relative adjustment");+ const noisy = bank([60], 3, 2); noisy.entry.normalized = false;+ for (const z of noisy.zones) { const v = (z.zone.layer - 0.5) / 3, dynamic = pianoVelocity(v) * Math.pow(10, -8 * Math.max(0, 0.6 - v) / 20), scale = z.zone.layer === 1 ? 1e-4 : z.zone.layer === 3 ? 1e3 : 1; z.channels[0] = Float32Array.from(z.channels[0], (x) => x * dynamic * 0.001 * scale); }+ registerBank("piano", noisy); const capped = calibrateBank("piano");+ ok(capped.trim!.every((t) => Math.abs(t.correctionDb - t.medianDb!) <= 9.000001) && capped.trim![0].medianDb! > 40, "zone corrections stay within 9 dB of the instrument median, while the whole-instrument trim is unlimited");+ ok(capped.trim!.filter((t) => t.boostLimited).every((t) => t.layer === 1) && capped.trim!.filter((t) => t.boostLimited).length === 2, "only zones needing excessive upward correction trigger louder-layer fallback");+ ok(capped.trim!.filter((t) => t.layer === 3).every((t) => t.requestedDb! < t.medianDb! - 9 && t.correctionDb === t.medianDb! - 9 && !t.boostLimited), "excessive downward corrections are capped too, without promoting an already-loud zone");+ const quietKeys = Array.from({ length: 8 }, (_, i) => key(60, 0.1, i * 0.1));+ const safePicks = sampleZones(capped, quietKeys, 42);+ ok(safePicks.every((z) => z.zone.midi === 60 && z.zone.layer === 2) && safePicks.every((z, i) => !i || z !== safePicks[i - 1]) && sampleZones(capped, quietKeys, 42).every((z, i) => z === safePicks[i]), "quiet zones use the next louder layer at the same pitch, with deterministic non-repeating round robin");+ ok(sampleGain(capped.entry, safePicks[0].zone, 0.1) < 1 && sampleGain(capped.entry, safePicks[0].zone, 0.1) >= Math.pow(10, -6 / 20), "louder-layer fallback is brought down only by the gentle bounded relative gain");+ const noHigher = { ...capped, zones: capped.zones.filter((z) => z.zone.layer === 1) };+ ok(sampleZones(noHigher, [key(60, 0.1)], 1)[0].zone.layer === 1, "a quiet zone without a louder layer keeps its capped correction, never changes pitch or disappears");+ const stillQuiet = { ...capped, trim: capped.trim!.map((t) => t.layer === 2 ? { ...t, boostLimited: true } : t) };+ ok(sampleZones(stillQuiet, [key(60, 0.1)], 1)[0].zone.layer === 3 && sampleZones({ ...capped, zones: capped.zones.filter((z) => z.zone.layer !== 2) }, [key(60, 0.1)], 1)[0].zone.layer === 3, "protection skips still-quiet and missing layers, staying at the selected pitch");+ const protectedArts = { ...arts, trim: arts.zones.filter((z) => z.zone.art !== "rel").map(({ zone: z }) => ({ file: z.file, midi: z.midi, layer: z.layer, measuredDb: -40, modeledDb: -20, correctionDb: z.layer === 1 ? 9 : 0, requestedDb: z.layer === 1 ? 20 : 0, medianDb: 0, boostLimited: z.layer === 1 })) };+ ok(sampleZones(protectedArts, [key(60, 0.1)], 1, [[0, 1]])[0].zone.art === "sus" && sampleZones(protectedArts, [key(60, 0.1)], 1)[0].zone.art === undefined && sampleZones(protectedArts, [key(60, 0.1)], 1)[0].zone.layer === 2, "louder-layer protection keeps sus tied to pedal-at-strike and ordinary playback otherwise");+ clearBanks();+ const invalid = bank([60], 3); invalid.entry.layerVelocity = [0.1, 0.5];+ ok(throws(() => registerBank("piano", invalid), /layerVelocity/), "invalid layerVelocity is rejected");+ const stereo = bank(); stereo.zones[0].zone.channels = 2; stereo.zones[0].channels.push(Float32Array.from(stereo.zones[0].channels[0], (v) => v * -0.25));+ const wide = render(stereo); ok(wide.R.every((v, i) => Math.abs(v + wide.L[i] * 0.25) < 1e-7), "stereo channel phase and level survive playback");+ const high = bank(); for (let i = 0; i < high.zones[0].channels[0].length; i++) high.zones[0].channels[0][i] = 0.3 * Math.sin(2 * Math.PI * 23000 * i / SR);+ const upHigh = render(high, [key(62)]), downHigh = render(high, [key()], 24000), center = (x: Float32Array, sr: number) => rms(x.subarray(sr * 0.1, sr * 0.6));+ ok(center(upHigh.L, SR) < 0.001 && center(downHigh.L, 24000) < 0.001, "sinc removes above-Nyquist energy before pitch-up and 24 kHz downsampling");+ const imagesDb = (x: Float32Array, f: number) => {+ let cc = 0, ss = 0, cs = 0, xc = 0, xs = 0;+ for (let i = 0; i < x.length; i++) { const c = Math.cos(2 * Math.PI * f * i / SR), s = Math.sin(2 * Math.PI * f * i / SR); cc += c*c; ss += s*s; cs += c*s; xc += x[i]*c; xs += x[i]*s; }+ const d = cc*ss-cs*cs, a = (xc*ss-xs*cs)/d, b = (xs*cc-xc*cs)/d;+ let residual = 0, signal = 0;+ for (let i = 0; i < x.length; i++) { const fit = a*Math.cos(2*Math.PI*f*i/SR)+b*Math.sin(2*Math.PI*f*i/SR); residual += (x[i]-fit)**2; signal += fit*fit; }+ return 10*Math.log10(residual/signal);+ };+ const tone = bank([60]); tone.zones[0].channels[0] = Float32Array.from({ length: SR*3 }, (_, i) => 0.3*Math.sin(2*Math.PI*15000*i/SR));+ for (const shift of [-3, -200]) {+ const k = { ...key(), vary: { cents: shift, db: 0, bright: 1, decay: 1, phase: 0, seed: 4 } }, f = 15000*2**(shift/1200);+ const played = render(tone, [k]);+ ok(imagesDb(played.L.slice(SR*0.1, SR*0.3), f) < -65, `${shift} cents: downward humanisation has no audible interpolation images`);+ const relZone = { ...tone.zones[0].zone, art: 'rel' as const, file: 'release.flac' }, withRel = { ...tone, entry: { ...tone.entry, damped: true, zones: [...tone.entry.zones, relZone] }, zones: [...tone.zones, { zone: relZone, channels: tone.zones[0].channels }] };+ const release = render(withRel, [k]), without = render({ ...tone, entry: { ...tone.entry, damped: true } }, [k]);+ const isolated = Float32Array.from(release.L.slice(SR*0.22, SR*0.32), (v, i) => v - without.L[SR*0.22+i]);+ ok(imagesDb(isolated, f) < -65, `${shift} cents: pitch-down release noise uses the same clean sinc path`);+ }+ const canonical = JSON.stringify([b.entry.kind, b.entry.range, b.entry.layers, null, b.entry.damped, true, b.entry.zones.map((z) => [z.sha256, z.midi, z.layer, z.rr, z.frames, z.channels, false, null])]);+ ok(bankIdentity(b.entry) === createHash("sha256").update(canonical).digest("hex"), "browser-safe bank identity agrees with SHA-256");+ const wideGaps = bank([60, 72]); wideGaps.entry.sparse = true; wideGaps.entry.maxShift = 6; wideGaps.zones[0].zone.measuredHz = 260;+ const shifted = render(wideGaps, [key(66)]);+ ok(cents(pitch(shifted.L, SR), 66) < 3 && shifted.L.every(Number.isFinite), "sparse banks allow wide shifts; measuredHz does not retune the recording");++ for (const [make, want] of [[nocturne, "acd240c8adffd25d00ee5279f2c72d3e"], [marimbaCurious, "d787a58c5704cf940a4404281e33d07a"]] as const) {+ const r = renderPiece(make(), SR), h = createHash("md5"); h.update(new Uint8Array(r.L.buffer)); h.update(new Uint8Array(r.R.buffer));+ ok(h.digest("hex") === want, `${make.name}: no-bank audio matches the pre-change md5`);+ }+ const piece = nocturne(), model = voiceJobs(piece, 24000, { seconds: 0.5 });+ const reg = registerBank("piano", b), sampled = voiceJobs(piece, 24000, { seconds: 0.5 });+ ok(sampled.every((j) => j.kind === "sampled" && j.bankHash === reg.hash) && voiceJobKey(model[0]) !== voiceJobKey(sampled[0]), "sampled jobs carry the bank hash and cannot hit modeled cache entries");+ const processed = { ...sampled[0], post: { id: "probe", seed: 1, lofi: LOFI_DUSTY, amp: 0.3, transient: { maxDb: 3, thrDb: -18, ratio: 2 } } }, { post, ...bare } = processed;+ const full = runVoiceJob(processed), manual = runVoiceJob(bare);+ lofiStem(post.lofi, post.id, manual.L, manual.R, bare.sr, bare.keys.map((k) => k.t), post.seed);+ ampSim(manual.L, manual.R, bare.sr, post.amp); const gr = transientGain(manual.L, manual.R, bare.sr, post.transient);+ ok(same(full.L, manual.L) && same(full.R, manual.R) && full.transientGr === gr, "sampled stems run the existing lo-fi, amp and transient chain in order");+ const disabled = { ...piece, parts: piece.parts.map((p) => ({ ...p, opts: { ...p.opts, sampled: false } })) };+ ok(voiceJobs(disabled, 24000, { seconds: 0.5 }).every((j, i) => { const a = runVoiceJob(j), b = runVoiceJob(model[i]); return j.kind === "piano" && same(a.L, b.L) && same(a.R, b.R); }), "sampled:false retains exact modeled audio");+ ok(voiceJobs({ ...piece, legacy: true }, 24000, { seconds: 0.5 }).every((j) => j.kind !== "sampled"), "legacy pieces never use a registered bank");+ registerBank("piano.upright", bank([63]));+ ok(bankFor("piano", "upright")?.id === "piano.upright" && !bankFor("piano", "felt"), "variants are exact bank ids, with no bare-id fallback");+ const job = sampled[0], replacement = bank(); replacement.zones[0].zone.sha256 = "f".repeat(64); registerBank("piano", replacement);+ ok(bankIdentity(replacement.entry) !== reg.hash && throws(() => runVoiceJob(job), /missing or changed/), "replaced banks invalidate jobs instead of silently serving another voice");+ const sustained = bank(); sustained.entry.kind = "sustained";+ ok(throws(() => registerBank("strings", sustained), /sustained zone without a loop/), "sustained zones without loops are rejected");+ } finally { clearBanks(); }+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/hyperframes.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/hyperframes.mjsindex 27f2269..b648594 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/hyperframes.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/hyperframes.mjs@@ -33,6 +33,7 @@ import { mkdirSync, readFileSync } from "node:fs";import { join, resolve } from "node:path";import { pathToFileURL } from "node:url";import { buildPage } from "../build-page.mjs";+import { loadFilmModule, prepareFilmSounds, filmFloat32 } from '../audio.mjs';const require = createRequire(import.meta.url);const version = (id) => { try { return require(`${id}/package.json`).version; } catch { return null; } };@@ -87,6 +88,8 @@ export const open = async (film, opts = {}) => {mkdirSync(dir, { recursive: true });const out = join(dir, `${film}.html`);const built = await buildPage({ entry: `src/hosts/page-${film}.ts`, out, title: film });+ const source = await loadFilmModule(film);+ prepareFilmSounds(source.film, source.music);const { writeFileSync } = await import("node:fs");writeFileSync(out, readFileSync(out, "utf8").replace("</body>", `<script>${FRAME_ADAPTER(film)}</script></body>`));@@ -112,7 +115,7 @@ export const open = async (film, opts = {}) => {info: () => built.meta,frame: async (n, w = 0) => { const r = await grab(n, w); return { png: r.png, shot: null, drawMs: r.drawMs }; },hash: async (n, w = 0) => createHash("sha256").update((await grab(n, w)).png).digest("hex").slice(0, 16),- audio: async (sr) => { const s = pick(0); return s && engine.captureAudio ? engine.captureAudio(s, sr) : null; }, /* the engine mixes audio from <audio> elements; this film synthesizes its score in the page, so there is none to mix */+ audio: async (sr) => filmFloat32(source.film, sr),artifact: () => null,close: async () => { for (const s of sessions) await engine.closeCaptureSession(s); for (const l of leases) await l.release(); },};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/remotion.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/remotion.mjsindex dc4b261..231e3ac 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/remotion.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/remotion.mjs@@ -13,7 +13,7 @@ import { createHash } from "node:crypto";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { createRequire } from "node:module";import { join, resolve } from "node:path";-import { overlay } from "../overlay.mjs";+import { loadFilmModule, prepareFilmSounds, filmFloat32 } from '../audio.mjs';const require = createRequire(import.meta.url);const tryRequire = (id) => { try { return require(id); } catch { return null; } };@@ -35,17 +35,9 @@ export const probe = () => {// The film module is the source of truth for meta and for the score. It is read the way// build-page.mjs reads it: bundled on its own, with no host attached, so nothing can disagree.const loadFilm = async (film) => {- const { build } = await import("esbuild");- const out = (await build({ stdin: { contents: `export { ${film} as film } from "./src/canvas-core/${film}";`, resolveDir: process.cwd(), loader: "ts" }, bundle: true, format: "esm", write: false, platform: "neutral", plugins: [overlay] })).outputFiles[0].text;- return (await import("data:text/javascript;base64," + Buffer.from(out).toString("base64"))).film;-};--const float32 = (film, sr) => {- if (!film.audio) return null;- const [L, R] = film.audio(sr), pcm = new Float32Array(L.length * 2);- if (L.length !== R.length) throw new Error("audio channels have different lengths");- for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; }- return { sampleRate: sr, frames: L.length, float32: Buffer.from(pcm.buffer).toString("base64") };+ const data = await loadFilmModule(film);+ prepareFilmSounds(data.film, data.music);+ return data.film;};// Bundling is per FILM, not per session: the gate opens an adapter many times in one process and@@ -111,7 +103,7 @@ export const open = async (film, opts = {}) => {// Hashed through the PNG the renderer wrote: that file IS what this backend produces, so// hashing anything else would be grading something the backend does not actually deliver.hash: async (n, w = 0) => createHash("sha256").update((await still(n, w)).png).digest("hex").slice(0, 16),- audio: async (sr) => float32(data, sr),+ audio: async (sr) => filmFloat32(data, sr),artifact: () => null, /* like playwright: a means to an MP4, not a deliverable of its own */close: async () => { for (const b of browsers) await b.close({ silent: true }); },};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/audio.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/audio.mjsindex b6890db..018f072 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/audio.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/audio.mjs@@ -1,4 +1,41 @@// Interleaved stereo Float32 transport stays unclipped until the final AAC encoder.+import { build } from 'esbuild';+import { writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { overlay } from './overlay.mjs';+import { splitShape, requireFilm } from './names.mjs';+import { loadBanks, soundIds, printSounds, codeBuiltNotice } from './sounds.mjs';+import { soundsDir } from './soundfetch.mjs';+let filmModuleId = 0;++/** Film and music registry share one bundle, so its audio closure sees the loaded banks. */+export const loadFilmModule = async (title, plugins = [overlay]) => {+ const { base, shape } = splitShape(title);+ const js = (await build({ stdin: { contents: `export { ${base} as film } from "./src/canvas-core/${base}"; export * as music from "./src/canvas-core/music/index";`, resolveDir: process.cwd(), loader: 'ts' }, bundle: true, format: 'esm', write: false, platform: 'neutral', plugins })).outputFiles[0].text;+ const mod = await import('data:text/javascript;base64,' + Buffer.from(js).toString('base64') + `#film-${++filmModuleId}`);+ if (shape && !mod.film.reshape) throw new Error(`${base} has one shape; ${shape} needs film.reshape`);+ return { film: shape ? mod.film.reshape(shape) : mod.film, music: mod.music };+};+export const prepareFilmSounds = (film, M, pack = process.env.ANIDOODLE_SOUNDS || soundsDir()) => {+ M.clearBanks(); M.clearRooms();+ if (!film.audio) return false;+ const scores = film.audio.scores ?? [];+ loadBanks(M, pack, [...new Set(scores.flatMap(soundIds))]);+ for (const p of scores) printSounds(M, p);+ const recorded = scores.some(p => !p.legacy && (p.parts.some(part => part.notes.length && part.opts?.sampled !== false && M.bankFor(part.inst, typeof part.opts?.variant === 'string' ? part.opts.variant : undefined)) ||+ [p.plan.space?.room ?? M.mixProfile(p.plan.style, p.mix).space?.room, M.mixProfile(p.plan.style, p.mix).drumRoom?.room].some(id => M.roomFor(id))));+ if (!recorded) codeBuiltNotice();+ return recorded;+};+export const filmFloat32 = (film, sampleRate = 48000) => {+ if (!film.audio) return null;+ const [L, R] = film.audio(sampleRate);+ if (L.length !== R.length) throw new Error('audio channels have different lengths');+ const pcm = Buffer.alloc(L.length * 8);+ for (let i = 0; i < L.length; i++) { pcm.writeFloatLE(L[i], i * 8); pcm.writeFloatLE(R[i], i * 8 + 4); }+ return { sampleRate, frames: L.length, float32: pcm.toString('base64') };+};export const float32Wav = ({ sampleRate, frames, float32 }) => {const pcm = Buffer.from(float32, "base64");if (!Number.isSafeInteger(sampleRate) || sampleRate < 1 || pcm.length !== frames * 8) throw new Error("invalid stereo Float32 audio payload");@@ -10,3 +47,13 @@ export const float32Wav = ({ sampleRate, frames, float32 }) => {h.write("data", 36); h.writeUInt32LE(pcm.length, 40);return Buffer.concat([h, pcm]);};+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {+ const title = requireFilm(process.argv[2], 'audio', 'node tools/audio.mjs <film> <out.wav>');+ if (!process.argv[3]) throw new Error('audio needs an output WAV path');+ const { film, music } = await loadFilmModule(title);+ prepareFilmSounds(film, music);+ const audio = filmFloat32(film);+ if (!audio) throw new Error(`${title}: silent film`);+ writeFileSync(process.argv[3], float32Wav(audio));+ console.log(`audio: ${audio.frames} frames @ ${audio.sampleRate} Hz -> ${process.argv[3]}`);+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjsindex 106c404..15900ab 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs@@ -6,6 +6,7 @@ import { createHash } from "node:crypto";import { extname, join, relative, resolve } from "node:path";import { overlay, resolveOverlay } from "./overlay.mjs";import { requireFilm, splitShape } from "./names.mjs";+import { loadFilmModule, prepareFilmSounds, filmFloat32 } from './audio.mjs';// BAKE KEYS (see Env.bake and hosts/page.ts). Every module that exports `const X: Film` is tagged// in the bundle with its own path, and each tagged module gets a hash of its WHOLE import closure@@ -48,20 +49,20 @@ export const buildPage = async ({ entry, out, title, plugins: extra = [] }) => {if (shape) { entry = entry.replace(`page-${title}.ts`, `page-${base}.ts`); title = base; }if (!existsSync(entry)) entry = resolveOverlay("./" + entry, process.cwd()) ?? entry; // e.g. the example's own host pageif (!existsSync(entry) && title) requireFilm(title, "build", "a film name: src/hosts/page-<film>.ts"); // a clear exit with the known films, not an esbuild trace- const main = await build({ entryPoints: [entry], bundle: true, format: "iife", target: "es2020", minify: true, write: false, legalComments: "none", metafile: true, plugins: [...plugins, tagFilms] });+ const main = await build({ absWorkingDir: process.cwd(), entryPoints: [resolve(entry)], bundle: true, format: "iife", target: "es2020", minify: true, write: false, legalComments: "none", metafile: true, plugins: [...plugins, tagFilms] });const js = main.outputFiles[0].text;// read the manifest out of the film module itself, so the page and the film can never disagree- const probe = (await build({ stdin: { contents: `export { ${title} as film } from "./src/canvas-core/${title}";`, resolveDir: process.cwd(), loader: "ts" }, bundle: true, format: "esm", write: false, platform: "neutral", plugins })).outputFiles[0].text;- const { film } = await import("data:text/javascript;base64," + Buffer.from(probe).toString("base64"));+ const { film, music } = await loadFilmModule(shape ? `${title}-${shape}` : title, plugins);+ const recorded = prepareFilmSounds(film, music), audio = recorded ? filmFloat32(film) : null;const assets = Object.fromEntries(Object.entries(film.assets.images).map(([name, file]) => { const mime = MIME[extname(file).toLowerCase()]; if (!mime) throw new Error(`asset '${name}': unsupported type ${file}`); return [name, `data:${mime};base64,${readFileSync(join(process.cwd(), file)).toString("base64")}`]; }));// the renderer that draws every plate frame, and the assets any plate may read, salt every keyconst salt = [BAKE_FORMAT, ...["src/canvas-core/film.ts", "src/canvas-core/core.ts"].map((f) => readFileSync(resolve(f), "utf8")), JSON.stringify(assets)].join("\0");const bakeSrc = bakeHashes(main.metafile, salt);const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${film.meta.title}</title><style>html,body{margin:0;height:100%;background:#1b1a1a;display:grid;place-items:center}canvas{max-width:100vw;max-height:100vh;aspect-ratio:${film.meta.W}/${film.meta.H};cursor:pointer;background:#fff}</style></head>-<body><canvas id="film"></canvas><script>window.__ASSETS__=${JSON.stringify(assets)};window.__BAKE_SRC__=${JSON.stringify(bakeSrc)};${shape ? `window.__SHAPE__=${JSON.stringify(shape)};` : ""}</script><script>${js.replace(/<\/script/g, "<\\/script")}</script></body></html>`;+<body><canvas id="film"></canvas><script>window.__ASSETS__=${JSON.stringify(assets)};window.__BAKE_SRC__=${JSON.stringify(bakeSrc)};${audio ? `window.__AUDIO__=${JSON.stringify(audio)};` : ''}${shape ? `window.__SHAPE__=${JSON.stringify(shape)};` : ""}</script><script>${js.replace(/<\/script/g, "<\\/script")}</script></body></html>`;mkdirSync(join(out, ".."), { recursive: true }); writeFileSync(out, html);- const meta = shape ? (film.reshape ? film.reshape(shape).meta : (() => { throw new Error(`${base} has one shape (it has no reshape); ${shape} is for launch template films`); })()) : film.meta;+ const meta = film.meta;return { out, bytes: html.length, meta, assets: Object.keys(film.assets.images) };};if (import.meta.url === `file://${process.argv[1]}`) { const title = requireFilm(process.argv[2], "build-page", "node tools/build-page.mjs <film>"); const r = await buildPage({ entry: `src/hosts/page-${title}.ts`, out: `dist/${title}.html`, title }); console.log(`built ${r.out} (${(r.bytes / 1024).toFixed(0)} KB, self-contained)`); }diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjsindex b8aa7c6..8cdc9a0 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs@@ -88,7 +88,7 @@ say(bad.length === 0, `${frames.length} frames across the film hash the same asconst sr = 48000;const [aShip, aGold] = [await shipped.page.evaluate((s) => window.FILM.audio(s), sr), await golden.page.evaluate((s) => window.FILM.audio(s), sr)];const sameAudio = !aShip && !aGold || aShip && aGold && aShip.frames === aGold.frames && aShip.sampleRate === aGold.sampleRate && aShip.float32 === aGold.float32;-say(!!sameAudio, "the page synthesizes the same score, in the page", sameAudio ? (aShip ? `${aShip.frames} samples @ ${aShip.sampleRate} Hz` : "silent film") : "audio missing or different");+say(!!sameAudio, "the emitted page plays the same complete audio track", sameAudio ? (aShip ? `${aShip.frames} samples @ ${aShip.sampleRate} Hz` : "silent film") : "audio missing or different");await browser.close();console.log(`\n${"=".repeat(58)}\nEMIT: ${fails ? `FAIL ${fails} of ${checks} checks failed` : `PASS ${checks}/${checks} checks`} ${out}`);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/listen.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/listen.mjsnew file mode 100644index 0000000..f8f4199--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/listen.mjs@@ -0,0 +1,211 @@+#!/usr/bin/env node+// LISTENING PAGE BUILDER. Two takes of the same piece, loudness-matched and side by side on one+// web page, because every sound change is judged by ear in a browser, never from files in a+// terminal. Each take is a `node tools/music.mjs render` child process, so the two sides can be two+// different engine directories (two branches) or the same engine under different environment+// variables (a sound pack switched on through ANIDOODLE_SOUNDS).+//+// node tools/listen.mjs <outdir> --a "<label A>" --b "<label B>" --pieces nocturne,marimbaCurious+// [--a-env KEY=VALUE ...] [--b-env KEY=VALUE ...]+// [--a-engine <engine dir>] [--b-engine <engine dir>]+// [--title "..."] [--intro "..."] [--blind] [--seed N]+//+// Loudness matching: both wavs are metered with ffmpeg's ebur128 (integrated LUFS, the loudness+// the owner actually hears), and only the LOUDER one is turned down to the quieter one, never up. A+// gain that only lowers a signal cannot clip. Then both to mp3 256k. When the two takes render the+// same audio they measure the same LUFS, and the tool says the takes are identical.+import { execFileSync, spawnSync } from "node:child_process";+import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, readdirSync, copyFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const HERE_ENGINE = resolve(here, ".."); // the engine this tool lives in: both takes by default+const WAVE = ".render"; // intermediate wavs, beside the mp3s, deleted at the end++// ---------------------------------------------------------------- arguments+const USAGE = `usage: node tools/listen.mjs <outdir> --a "<label A>" --b "<label B>" --pieces a,b,c+ [--a-env KEY=VALUE ...] [--b-env KEY=VALUE ...] [--a-engine <dir>] [--b-engine <dir>]+ [--title "..."] [--intro "..."] [--blind] [--seed N]`;+const opts = { a: null, b: null, pieces: [], aEnv: {}, bEnv: {}, aEngine: HERE_ENGINE, bEngine: HERE_ENGINE, title: null, intro: null, blind: false, seed: 1, outdir: null };+try {+ const argv = process.argv.slice(2);+ /** KEY=VALUE for a child's environment; the value may hold more '=' (a path, a query string). */+ const envPair = (s, where) => {+ const i = s.indexOf("=");+ if (i < 1 || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.slice(0, i))) throw new Error(`--${where} wants KEY=VALUE, got "${s}"`);+ return [s.slice(0, i), s.slice(i + 1)];+ };+ for (let i = 0; i < argv.length; i++) {+ const f = argv[i], next = () => { if (i + 1 >= argv.length) throw new Error(`${f} needs a value`); return argv[++i]; };+ if (f === "--a") opts.a = next();+ else if (f === "--b") opts.b = next();+ else if (f === "--pieces") opts.pieces = next().split(",").map((s) => s.trim()).filter(Boolean);+ else if (f === "--a-env") { const [k, v] = envPair(next(), "a-env"); opts.aEnv[k] = v; }+ else if (f === "--b-env") { const [k, v] = envPair(next(), "b-env"); opts.bEnv[k] = v; }+ else if (f === "--a-engine") opts.aEngine = resolve(next());+ else if (f === "--b-engine") opts.bEngine = resolve(next());+ else if (f === "--title") opts.title = next();+ else if (f === "--intro") opts.intro = next();+ else if (f === "--blind") opts.blind = true;+ else if (f === "--seed") opts.seed = Number(next());+ else if (f.startsWith("--")) throw new Error(`no flag "${f}"`);+ else if (opts.outdir === null) opts.outdir = f;+ else throw new Error(`extra argument "${f}" (the outdir comes first)`);+ }+ if (!opts.outdir) throw new Error(`name an outdir\n${USAGE}`);+ if (!opts.a || !opts.b) throw new Error(`--a and --b label the two takes\n${USAGE}`);+ if (!opts.pieces.length) throw new Error(`--pieces names at least one piece\n${USAGE}`);+ if (!Number.isFinite(opts.seed)) throw new Error(`--seed wants a number`);+ for (const [tag, dir] of [["a", opts.aEngine], ["b", opts.bEngine]]) if (!existsSync(join(dir, "tools/music.mjs"))) throw new Error(`--${tag}-engine ${dir} has no tools/music.mjs`);+} catch (e) {+ console.error(`listen: ${e.message}`); process.exit(2);+}++// ---------------------------------------------------------------- audio+/** ffmpeg's own ebur128 summary: integrated loudness, range and true peak. */+const ebu = (file) => {+ const r = spawnSync("sh", ["-c", 'ffmpeg -hide_banner -nostats -i "$1" -vn -af ebur128=peak=true -f null - 2>&1', "sh", file], { encoding: "utf8", maxBuffer: 1 << 28 });+ if (r.status !== 0) throw new Error(`ffmpeg could not meter ${file}: ${(r.stderr || r.stdout || "").trim().split("\n").pop()}`);+ const sum = r.stdout.slice(r.stdout.lastIndexOf("Summary:")), g = (re) => { const m = re.exec(sum); return m ? Number(m[1]) : NaN; };+ return { I: g(/I:\s+(-?[\d.]+) LUFS/), LRA: g(/LRA:\s+(-?[\d.]+) LU/), TP: g(/Peak:\s+(-?[\d.]+) dBFS/) };+};+const seconds = (file) => Number(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" }).trim());+const db = (x) => (Number.isFinite(x) ? `${x.toFixed(1)} LUFS` : "no reading");++/** One take: the engine's own render, as a child process, with this side's environment. */+const take = (piece, wav, engine, env) => {+ rmSync(wav, { force: true }); // a wav left by an earlier run must not pass for this one's+ const r = spawnSync(process.execPath, [join(engine, "tools/music.mjs"), "render", piece, wav], { env: { ...process.env, ...env }, encoding: "utf8", maxBuffer: 1 << 26 });+ // `render` exits 1 when a guard fails (a masking FAIL on the nocturne is the common one) and+ // still writes the wav: a guard is the engine's opinion about the mix, not about whether it rendered.+ if (!existsSync(wav)) throw new Error(`${piece}: ${engine}/tools/music.mjs render wrote no wav (exit ${r.status})\n${(r.stderr || r.stdout || "").trim()}`);+ return r.status === 0 ? null : `render exited ${r.status} (a guard, not the render; the wav is there)`;+};+/** The wav turned DOWN by `att` dB, as float wav. `att` is never negative: nothing is ever raised. */+const quieter = (from, to, att) => execFileSync("ffmpeg", ["-v", "error", "-y", "-i", from, "-af", `volume=-${att.toFixed(2)}dB`, "-c:a", "pcm_f32le", to]);++// ---------------------------------------------------------------- the page+const DARK = `--bg: #101814; --fg: #eef3ef; --panel: #18231e; --line: #33443b; --accent: #6fd3b1; --accent-fg: #0b1511; color-scheme: dark`;+// A fragment: no doctype/html/head/body (the wrapper that publishes it adds the document). Fonts+// from Google Fonts and nothing else off-box; every colour a variable, dark repeated both ways.+const STYLE = ` :root {+ --bg: #f3f5f1; --fg: #14201b; --panel: #ffffff; --line: #c9d3cc; --accent: #0f6b52; --accent-fg: #ffffff;+ --display: "Fraunces", Georgia, serif; --body: "Figtree", system-ui, sans-serif;+ }+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { ${DARK} } }+ :root[data-theme="dark"] { ${DARK} }+ * { box-sizing: border-box; }+ body { background: var(--bg); color: var(--fg); font-family: var(--body); font-size: 17px; line-height: 1.5; padding-inline: 20px; padding-block: 40px; }+ main { max-width: 34rem; margin-inline: auto; display: flex; flex-direction: column; gap: 28px; }+ h1 { font-family: var(--display); font-size: 2rem; line-height: 1.15; margin: 0; text-wrap: balance; }+ p { margin: 0; }+ .piece { display: flex; flex-direction: column; gap: 12px; }+ .piece h2 { font-family: var(--display); font-size: 1.5rem; line-height: 1.2; margin: 0; }+ .take { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 20px; display: flex; flex-direction: column; gap: 12px; min-width: 0; }+ .take h3 { font-family: var(--display); font-size: 1.35rem; line-height: 1.25; margin: 0; display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; overflow-wrap: break-word; }+ .letter { background: var(--accent); color: var(--accent-fg); border-radius: 8px; padding: 0 12px; font-family: var(--body); font-weight: 600; flex: none; }+ audio { width: 100%; min-width: 0; }+ button { align-self: start; background: var(--panel); color: var(--fg); border: 1px solid var(--line); border-radius: 10px; padding: 10px 18px; font-family: var(--body); font-size: 1rem; cursor: pointer; }+ button:hover { border-color: var(--accent); }+ audio:focus-visible, button:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }+ @media (max-width: 430px) { body { padding-inline: 14px; padding-block: 28px; } .take { padding: 14px; } }`;+// Play one at a time, and carry the position across so the same bar can be compared: starting a+// player pauses every other one, and a partner from the same piece starts where it was.+const PLAY_ONE = ` const players = [...document.querySelectorAll("audio[data-piece]")];+ for (const on of players) on.addEventListener("play", () => {+ for (const off of players) {+ if (off === on || off.paused) continue;+ if (off.dataset.piece === on.dataset.piece) on.currentTime = off.currentTime;+ off.pause();+ }+ });`;+const REVEAL = ` const reveal = document.getElementById("reveal");+ reveal.addEventListener("click", () => {+ for (const h of document.querySelectorAll("[data-label]")) {+ h.querySelector(".letter").textContent = h.dataset.label;+ h.querySelector(".name").textContent = h.dataset.text;+ }+ reveal.remove();+ });`;++const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);+const labelOf = (takeLabel) => opts[takeLabel.toLowerCase()];+/** A demo name for a heading: marimbaCurious -> Marimba curious, pianoPhrase8 -> Piano phrase 8. */+const heading = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/(\D)(\d)/g, "$1 $2").trim()+ .split(/\s+/).map((w, i) => (i ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1))).join(" ");+const takeCard = (t) => ` <div class="take">+ <h3${opts.blind ? ` data-label="${esc(t.label)}" data-text="${esc(labelOf(t.label))}"` : ""}><span class="letter">${esc(t.slot)}</span> <span class="name">${esc(opts.blind ? `Take ${t.slot}` : labelOf(t.label))}</span></h3>+ <audio data-piece="${esc(t.piece)}" controls preload="auto" src="${esc(t.file)}"></audio>+ </div>`;+const page = (title, intro, pieces) => `<title>${esc(title)}</title>+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,[email protected],600&family=Figtree:wght@400;600&display=swap">+<style>+${STYLE}+</style>+<main>+ <h1>${esc(title)}</h1>+${intro ? ` <p>${esc(intro)}</p>\n` : ""}${pieces.map((p) => ` <section class="piece">+ <h2>${esc(heading(p.piece))}</h2>+ <p>${p.seconds.toFixed(1)} seconds each.</p>+${p.takes.map(takeCard).join("\n")}+ </section>`).join("\n")}+ <p>Starting one pauses the other, so you can jump between them at the same spot.</p>+${opts.blind ? ` <button id="reveal" type="button">Show which is which</button>\n` : ""}</main>+<script>+${PLAY_ONE}${opts.blind ? `\n${REVEAL}` : ""}+</script>+`;++// ---------------------------------------------------------------- run+/** A shuffle by the seed: the same --seed always puts 1 and 2 the same way round. */+const shuffler = (seed) => { let s = (seed >>> 0) || 1; return () => (s = (s + 0x6d2b79f5) >>> 0, (() => { let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; })()); };++try {+ const out = resolve(opts.outdir), work = join(out, WAVE);+ mkdirSync(work, { recursive: true });+ const rng = shuffler(opts.seed), rows = [], notes = [];+ for (const piece of opts.pieces) {+ const raw = { A: join(work, `${piece}-A.wav`), B: join(work, `${piece}-B.wav`) };+ for (const side of ["A", "B"]) { const note = take(piece, raw[side], side === "A" ? opts.aEngine : opts.bEngine, side === "A" ? opts.aEnv : opts.bEnv); if (note) notes.push(`${piece} ${side}: ${note}`); }+ const before = { A: ebu(raw.A), B: ebu(raw.B) };+ const same = readFileSync(raw.A).equals(readFileSync(raw.B));+ // only ever down: the quieter of the pair is the reference, and `att` is how far the other one+ // has to come down to meet it (never negative, so nothing is ever turned up)+ const quiet = Math.min(before.A.I, before.B.I), att = { A: before.A.I - quiet, B: before.B.I - quiet };+ const matched = {};+ for (const side of ["A", "B"]) {+ matched[side] = join(work, `${piece}-${side}-match.wav`);+ if (att[side] > 0.05) quieter(raw[side], matched[side], att[side]); else copyFileSync(raw[side], matched[side]);+ }+ const after = { A: ebu(matched.A), B: ebu(matched.B) };+ const mp3 = {}, dur = [];+ for (const side of ["A", "B"]) {+ mp3[side] = `${piece}-${side}.mp3`;+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", matched[side], "-c:a", "libmp3lame", "-b:a", "256k", join(out, mp3[side])]);+ dur.push(seconds(join(out, mp3[side])));+ }+ const order = opts.blind && rng() < 0.5 ? ["B", "A"] : ["A", "B"];+ rows.push({ piece, seconds: Math.max(...dur), takes: order.map((label, i) => ({ label, slot: opts.blind ? String(i + 1) : label, file: mp3[label], piece })), before, after, att: att, same });+ console.log(`\n${heading(piece)} (${piece}, ${dur[0].toFixed(1)} s)`);+ for (const side of ["A", "B"]) console.log(` ${side} ${labelOf(side)} ${db(before[side].I)} -> ${db(after[side].I)}${att[side] > 0.05 ? ` (${att[side].toFixed(1)} dB down to the quieter take)` : " (no change)"}`);+ console.log(` ${same ? "the two takes are identical: the same audio, not just the same loudness" : `the two takes differ, A reads ${(before.A.I - before.B.I).toFixed(1)} LU against B`} -> ${mp3.A}, ${mp3.B}`);+ }+ if (notes.length) console.log(`\n${notes.map((n) => `NOTE: ${n}`).join("\n")}`);++ // The answer key, blind or not: which labelled take sits in which slot on the page.+ const key = {+ seed: opts.seed, blind: opts.blind, labels: { A: opts.a, B: opts.b },+ pieces: Object.fromEntries(rows.map((r) => [r.piece, Object.fromEntries(r.takes.map((t) => [t.slot, { label: t.label, text: labelOf(t.label), file: t.file }]))])),+ loudness: Object.fromEntries(rows.map((r) => [r.piece, { identical: r.same, A: { before: r.before.A.I, after: r.after.A.I, attenuationDb: +r.att.A.toFixed(2) }, B: { before: r.before.B.I, after: r.after.B.I, attenuationDb: +r.att.B.toFixed(2) } }])),+ };+ writeFileSync(join(out, "key.json"), JSON.stringify(key, null, 1) + "\n");+ const title = opts.title ?? (opts.blind ? `${rows.length} pieces, two takes each` : `${opts.a} vs ${opts.b}`);+ const intro = opts.intro ?? `${rows.map((r) => heading(r.piece)).join(", ")}. Two takes each, matched to the same loudness.`;+ writeFileSync(join(out, "index.html"), page(title, intro, rows));+ for (const f of readdirSync(work)) rmSync(join(work, f)); // the wavs are intermediate: the mp3s beside them are the deliverable+ rmSync(work, { recursive: true, force: true });+ console.log(`\nwrote ${join(out, "index.html")}, ${rows.length * 2} mp3s, key.json${opts.blind ? ` (blind, seed ${opts.seed})` : ""}`);+} catch (e) {+ console.error(`listen: ${e.message}`); process.exit(1);+}\ No newline at end of filediff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjsindex 618aa5e..ea61a91 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs@@ -23,6 +23,8 @@// node tools/music.mjs probe # piano realism probes// node tools/music.mjs calibrate [--voices] # palette trims (vocabTrim.ts); --voices: alternates' trims and your own voices' levels (vocabVoices.ts)// (check/render run voices on all but one core; ANIDOODLE_THREADS=1 renders serially, ANIDOODLE_TIMING=1 prints check's stage times)+// ANIDOODLE_SOUNDS=<pack-dir> or --sounds <pack-dir> plays optional, hash-verified FLAC banks.+// --room <id> selects a recorded room; an unregistered id keeps the synthesized space.import { build } from "esbuild";import { execFileSync } from "node:child_process";import { writeFileSync, readFileSync, existsSync, mkdirSync, unlinkSync } from "node:fs";@@ -30,10 +32,17 @@ import { dirname, join, resolve, basename } from "node:path";import { fileURLToPath } from "node:url";import { Worker } from "node:worker_threads";import { availableParallelism } from "node:os";+import { loadBanks, soundIds, printSounds, codeBuiltNotice } from "./sounds.mjs";+import { soundsDir } from './soundfetch.mjs';const here = dirname(fileURLToPath(import.meta.url));const SR = 48000;let ENGINE_URL = "";+let SOUNDS_DIR;+let ROOM_ID;+const SOUNDS_URL = new URL("./sounds.mjs", import.meta.url).href;+let noticed = false;+const loadSounds = (M, piece) => { loadBanks(M, SOUNDS_DIR, soundIds(piece)); if (!SOUNDS_DIR && !noticed) { codeBuiltNotice(); noticed = true; } };const load = async () => {const r = await build({ entryPoints: [join(here, "../src/canvas-core/music/index.ts")], bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });ENGINE_URL = "data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64");@@ -47,7 +56,8 @@ const load = async () => {// the same code on the same inputs, so the audio is bit-identical to a serial render// (tools/music-unit.mjs checks it). ANIDOODLE_THREADS=1 renders serially.const WORKER = `const { parentPort, workerData } = require("node:worker_threads");-import(workerData).then((M) => {+Promise.all([import(workerData.engine), import(workerData.loader)]).then(([M, S]) => {+ S.loadBanks(M, workerData.sounds, workerData.ids);parentPort.on("message", ({ id, job, task }) => {if (job) { const o = M.runVoiceJob(job); parentPort.postMessage({ id, o }, [...new Set([o.L.buffer, o.R.buffer, o.halo && o.halo.buffer].filter(Boolean))]); return; }const opts = { ...task.opts, cache: new Map(task.voices) };@@ -57,10 +67,10 @@ import(workerData).then((M) => {});`;const THREADS = () => Number(process.env.ANIDOODLE_THREADS) || Math.max(1, availableParallelism() - 1);/** Run messages on a pool of `threads` workers; resolves to their replies by id, in the order given. */-const pool = (msgs, threads) => { const queue = msgs.slice(), out = new Map(); return Promise.all(Array.from({ length: Math.min(threads, msgs.length) }, () => new Promise((ok, fail) => {- const w = new Worker(WORKER, { eval: true, workerData: ENGINE_URL });+const pool = (msgs, threads) => { const queue = msgs.slice(), out = new Map(), ids = [...new Set(msgs.flatMap((m) => m.job ? (m.job.kind === "sampled" ? [m.job.bank] : []) : soundIds(m.task.piece)))]; return Promise.all(Array.from({ length: Math.min(threads, msgs.length) }, () => new Promise((ok, fail) => {+ const w = new Worker(WORKER, { eval: true, workerData: { engine: ENGINE_URL, loader: SOUNDS_URL, sounds: SOUNDS_DIR, ids } });const next = () => { const x = queue.shift(); if (!x) { w.terminate(); ok(); return; } w.postMessage(x); };- w.on("message", (m) => { if (!m.ready) out.set(m.id, m); next(); }); w.on("error", fail);+ w.on("message", (m) => { if (!m.ready) out.set(m.id, m); next(); }); w.on("error", (e) => { queue.length = 0; w.terminate(); fail(e); });}))).then(() => out); };export const prewarm = async (M, cache, jobs) => {const todo = new Map(); for (const j of jobs) { const k = M.voiceJobKey(j); if (!cache.has(k) && !todo.has(k)) todo.set(k, j); }@@ -108,7 +118,7 @@ const getPiece = async (M, ref) => {const mod = await import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));v = mod[exp]; if (v === undefined) throw new Error(`${file} has no export "${exp}" (exports: ${Object.keys(mod).join(", ")})`);}- const make = () => { const x = typeof v === "function" ? v() : v; return x && x.sections && x.chords ? M.composePiece(x) : x; };+ const make = () => { const x = typeof v === "function" ? v() : v, p = x && x.sections && x.chords ? M.composePiece(x) : x; return ROOM_ID ? { ...p, plan: { ...p.plan, space: { ...p.plan.space, room: ROOM_ID } } } : p; };return { make, name: ref, demo: Boolean(fromDemo) };};@@ -151,6 +161,7 @@ const renderOne = async (M, spec) => {let tempo = spec.tempo ?? piece.plan.tempo;let form;if (spec.fit) { const f = M.fitScore(piece, spec.seconds); piece = f.piece; tempo = f.tempo; form = `${f.form}: ${f.piece.plan.sections.map((x) => x.id).join(", ")}`; }+ loadSounds(M, piece);const opts = { seconds: spec.seconds, tempo };if (spec.flat) Object.assign(opts, { expressive: false, piano: M.PIANO_FLAT, flatVelocity: 0.6 });const loop = spec.loop || piece.plan.loop, go = (cache) => (loop ? M.renderLoop(piece, SR, { cache, stems: true }) : M.renderPiece(piece, SR, { ...opts, cache, stems: true }));@@ -178,11 +189,21 @@ const noteVoicing = (r, piece) => {};const main = async () => {const [cmd, ...args] = process.argv.slice(2);+ const soundsAt = args.indexOf("--sounds");+ if (soundsAt >= 0 && (!args[soundsAt + 1] || args[soundsAt + 1].startsWith("--"))) throw new Error("--sounds needs a pack directory");+ SOUNDS_DIR = soundsAt >= 0 ? args.splice(soundsAt, 2)[1] : process.env.ANIDOODLE_SOUNDS || soundsDir();+ if (SOUNDS_DIR) SOUNDS_DIR = resolve(SOUNDS_DIR);+ const roomAt = args.indexOf("--room");+ if (roomAt >= 0 && (!args[roomAt + 1] || args[roomAt + 1].startsWith("--"))) throw new Error("--room needs a room id");+ ROOM_ID = roomAt >= 0 ? args.splice(roomAt, 2)[1] : undefined;const M = await load();const flag = (k) => args.includes(k), val = (k, d) => { const i = args.indexOf(k); return i >= 0 ? Number(args[i + 1]) : d; };if (cmd === "list") { console.log("demos (listening references and the novelty corpus, never a film's score):\n " + Object.keys(M.DEMOS).join("\n ") + "\nfixtures (tests):\n " + Object.keys(M.FIXTURES).join("\n ")); return; }if (cmd === "vocab") { if (args[0] === "--md") vocabMarkdown(M); else printVocab(M, args[0]); return; }- if (cmd === "calibrate") { if (flag("--voices")) calibrateVoices(M); else calibrate(M); return; }+ if (cmd === "calibrate") {+ if (SOUNDS_DIR) { const manifest = JSON.parse(readFileSync(join(SOUNDS_DIR, "manifest.json"), "utf8")); loadBanks(M, SOUNDS_DIR, Object.keys(manifest.instruments)); console.log(JSON.stringify(Object.fromEntries(Object.keys(manifest.instruments).map((id) => [id, { hash: M.bankFor(id).hash, trim: M.bankFor(id).trim }])), null, 1)); }+ else if (flag("--voices")) calibrateVoices(M); else calibrate(M); return;+ }if (cmd === "novelty") {const refs = args.filter((a) => !a.startsWith("--") && !/^[\d.]+$/.test(a)), pcs = [];for (const ref of refs) pcs.push(await getPiece(M, ref));@@ -204,6 +225,7 @@ const main = async () => {if (cmd === "check") {const pc = await getPiece(M, args[0]); let piece = pc.make(), tempo = piece.plan.tempo, seconds = val("--seconds", undefined);if (flag("--fit")) { const f = M.fitScore(piece, seconds); piece = f.piece; tempo = f.tempo; }+ loadSounds(M, piece); printSounds(M, piece);const T = process.env.ANIDOODLE_TIMING ? (l) => console.error(`[timing] ${l} ${((Date.now() - T0) / 1000).toFixed(1)} s`) : () => {}, T0 = Date.now();const cache = new Map(); await prewarm(M, cache, checkJobs(M, piece, tempo, seconds)); T("voices"); // every voice once, in parallelconst pending = startGuards(M, cache, piece, tempo, seconds).then((x) => { T("guard renders + stems"); return x; }); // the guards' role renders and the stems, on workers meanwhile@@ -217,6 +239,7 @@ const main = async () => {if (cmd === "render") {const [name, out] = args, pc = await getPiece(M, name), cache = new Map();const { r, tempo, ms, deterministic, piece, guards } = await renderOne(M, { make: pc.make, seconds: val("--seconds", undefined), tempo: val("--tempo", undefined), flat: flag("--flat"), fit: flag("--fit"), loop: flag("--loop"), cache, verify: flag("--verify"), stems: flag("--stems") });+ printSounds(M, piece);// an mp3 is encoded from a private intermediate next to it (never x.wav: rendering x.mp3 must not touch an x.wav you already have)const mp3 = out.endsWith(".mp3"), wav = mp3 ? join(dirname(resolve(out)), `.${basename(out)}.${process.pid}.tmp.wav`) : out;if (mp3 && (piece.plan.loop || flag("--loop"))) console.log("NOTE: mp3 is not gapless (encoder padding clicks at the loop point). Ship loops as .wav (or ogg/m4a with gapless metadata).");@@ -232,6 +255,7 @@ const main = async () => {if (cmd === "stems") {const [name] = args; let piece = (await getPiece(M, name)).make(), tempo = piece.plan.tempo, seconds = val("--seconds", undefined);if (flag("--fit")) { const f = M.fitScore(piece, seconds); piece = f.piece; tempo = f.tempo; }+ loadSounds(M, piece);const cache = new Map(); await prewarm(M, cache, M.voiceJobs(piece, STEM_SR, { tempo, seconds }));printStems(M, piece, tempo, seconds, cache); return;}@@ -403,6 +427,7 @@ const vocabMarkdown = (M) => {/** Key/mode problems, composer warnings, the master (did the peak cap stop it short?), and the guards. Returns pass. */const report = (M, r, piece, cache, bands) => {+ if (ROOM_ID || (SOUNDS_DIR && r.mixReport?.space)) console.log(`space ${r.mixReport?.space ?? "legacy space"}`);let ok = true; const probs = M.planProblems(piece), warn = piece.warnings ?? [];for (const p of probs) console.log(`PROBLEM ${p}`); ok = ok && !probs.length;for (const w of warn) console.log(`WARNING ${w}`);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjsindex ebbdf63..0a97fa2 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs@@ -95,7 +95,8 @@ console.log(`film: "${meta.title}" ${meta.W}x${meta.H} @ ${meta.fps} fps, ${N} fif (BLURRED) console.log(`motion blur: ${BLUR === "auto" ? `adaptive (subframes <= ${BPX} px apart, max ${BMAX})` : `${BLUR} subframes per frame`}, ${SHUTTER}-degree shutter, linear light`);if (ranged) console.log(`range render: frames [${FROM}, ${TO}) of ${N}, silent by design`);-// audio: pure JS in the page -> WAV here (skipped for a range render: the score would not line up)+// audio: the page returns its embedded recorded track or its code-built mix -> WAV here+// (skipped for a range render: the score would not line up).mkdirSync(resolve(".tmp"), { recursive: true }); const wav = resolve(`.tmp/${film}.wav`), a = ranged ? null : await session.audio(48000);if (a) writeFileSync(wav, float32Wav(a));if (a) { // the audio report: loudness and true peak, and the score's fit against the picture's griddiff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/soundfetch-unit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/soundfetch-unit.mjsnew file mode 100644index 0000000..cf326b8--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/soundfetch-unit.mjs@@ -0,0 +1,359 @@+#!/usr/bin/env node+// Unit test for tools/soundfetch.mjs and `soundpack.mjs dist`: builds a TINY synthetic pack in+// the contract's format (2 instruments x 2 zones + 1 room), dists it, then exercises+// get/list/where/verify/remove against a local dist dir, and every refusal path: foreign+// install roots, corrupt archives, tar escapes (traversal, absolute, backslash, link, wrong+// top, oversized size), tampered and oversized indexes, over-long and interrupted downloads,+// and two parallel gets. Needs ffmpeg for the synthetic FLACs. Durable directory required -+// never /tmp. No cp -R: the suite runs on Windows too.+// node tools/soundfetch-unit.mjs <durable-test-dir>+import { execFileSync, execFile } from "node:child_process";+import { promisify } from "node:util";+import { strict as assert } from "node:assert";+import { createHash } from "node:crypto";+import { createServer } from "node:http";+import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, rmSync, cpSync, statSync, openSync, closeSync, writeSync } from "node:fs";+import { join, resolve, dirname } from "node:path";+import { tarHeader } from "./soundpack.mjs";+import { soundsDir } from "./soundfetch.mjs";++const TOOLS = import.meta.dirname;+const dir = process.argv[2];+if (!dir) throw new Error("name a durable test directory");+const root = resolve(dir);+mkdirSync(root, { recursive: true });+const sha = (f) => createHash("sha256").update(readFileSync(f)).digest("hex");+const SR = 48000;+const INDEX = "anidoodle-sounds-v1.json";+let pass = 0;+const ok = (name) => console.log(`PASS ${++pass} ${name}`);++// ---------------------------------------------------------------- a tiny pack (contract format)+const pack = join(root, "tiny-pack");+const mkFlac = (file, frames, ch, seed0) => {+ const pcm = Buffer.alloc(frames * ch * 4);+ let seed = seed0;+ for (let i = 0; i < frames * ch; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; pcm.writeFloatLE(((seed >>> 0) / 4294967296 - 0.5) * 0.4, i * 4); }+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "f32le", "-ar", String(SR), "-ac", String(ch), "-i", "pipe:0",+ "-map_metadata", "-1", "-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24", file], { input: pcm });+};+const zone = (id, i, midi) => {+ const file = `${id}/z${i}.flac`, p = join(pack, ...file.split("/")), frames = 4800 * (i + 1);+ mkdirSync(dirname(p), { recursive: true });+ mkFlac(p, frames, 2, 11 + i);+ return { file, midi, layer: 1, rr: 1, frames, channels: 2, peakDb: -8, rmsDb: -20, sha256: sha(p) };+};+const inst = (id, title, midis) => ({ title, source: "test", license: "CC0-1.0", kind: "struck", range: [midis[0], midis.at(-1)], layers: 1, damped: true, zones: midis.map((m, i) => zone(id, i, m)) });+const manifest = { pack: "anidoodle-sounds", version: 1, sampleRate: SR, instruments: {+ piano: inst("piano", "Tiny Piano", [60, 62]),+ harp: inst("harp", "Tiny Harp", [55, 57]),+} };+{+ const f = "rooms/test-room.flac", p = join(pack, "rooms", "test-room.flac"), frames = 2400;+ mkdirSync(dirname(p), { recursive: true });+ mkFlac(p, frames, 2, 99);+ manifest.rooms = { "test-room": { title: "Test Room, Nowhere", source: "test", license: "CC-BY-4.0", file: f, channels: 2, frames, rt60: 0.05, sha256: sha(p), directFrames: 120 } };+}+writeFileSync(join(pack, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");+writeFileSync(join(pack, "LICENSES.md"), "# Licenses\n\n- Tiny Piano (`piano`), Tiny Harp (`harp`): synthetic test zones, CC0-1.0\n- Test Room, Nowhere (`rooms/test-room.flac`): CC-BY-4.0\n");+ok("tiny synthetic pack: piano, harp, test-room");++// ---------------------------------------------------------------- dist+const dist = join(root, "dist");+execFileSync("node", [join(TOOLS, "soundpack.mjs"), "dist", pack, dist], { stdio: "pipe" });+const indexSha = sha(join(dist, INDEX));+assert(existsSync(join(dist, "anidoodle-sounds-v1-piano.tar")) && existsSync(join(dist, "anidoodle-sounds-v1-rooms.tar")), "dist wrote archives");+ok("dist: archives + index written");++const install = join(root, "install");+rmSync(install, { recursive: true, force: true }); // re-runs start from a clean install+process.env.ANIDOODLE_SOUNDS = install; // the exported soundsDir() resolves through the env+const ENV = { ANIDOODLE_SOUNDS: install, ANIDOODLE_SOUNDS_URL: dist, ANIDOODLE_SOUNDS_INDEX_SHA256: indexSha };+// async spawn: the in-process http servers below need the event loop free to answer+const execFileP = promisify(execFile);+const run = async (args, env = {}) => (await execFileP("node", [join(TOOLS, "soundfetch.mjs"), ...args], { env: { ...process.env, ...ENV, ...env }, encoding: "utf8" })).stdout;+const runFail = async (args, env = {}) => { try { await run(args, env); } catch (e) { return e; } throw new Error(`expected nonzero exit: soundfetch ${args.join(" ")}`); };+const merged = () => JSON.parse(readFileSync(join(install, "manifest.json"), "utf8"));+// foreign dotfiles are NOT leftovers - only this tool's own .anidoodle-* temps may appear+const noLeftovers = () => assert.deepEqual(readdirSync(install).filter((e) => e.startsWith(".anidoodle-")), [], "no staging/download leftovers");++// ---------------------------------------------------------------- happy path+assert.equal((await run(["where"])).trim(), install, "where prints the resolved install dir");+assert.equal(soundsDir(), null, "soundsDir() null before install");+ok("where + soundsDir() before install");++await run(["get", "piano"]);+assert(existsSync(join(install, "piano", "z0.flac")), "piano flacs unpacked");+assert(existsSync(join(install, "LICENSES.md")), "LICENSES.md written");+assert.deepEqual(Object.keys(merged().instruments), ["piano"]);+assert.equal(soundsDir(), install, "soundsDir() resolves once installed");+noLeftovers();+ok("get piano: unpacked, merged manifest, soundsDir() resolves");++const list1 = await run(["list"]);+assert(list1.includes("anidoodle-sounds-v1-piano.tar") && /piano\.tar.*installed/s.test(list1.replace(/\n/g, " ")) && list1.includes("available"), "list shows installed + available");+ok("list: available vs installed with sizes");++await run(["get", "harp"]);+assert.deepEqual(Object.keys(merged().instruments).sort(), ["harp", "piano"], "second get merged into one manifest");+ok("two instruments in two calls -> one valid merged manifest");++assert((await run(["verify"])).includes("all sha256 match"), "verify passes");+ok("verify: re-hashes everything installed");++await run(["remove", "harp"]);+assert.deepEqual(Object.keys(merged().instruments), ["piano"]);+assert(!existsSync(join(install, "harp")), "harp dir removed");+assert((await run(["verify"])).includes("all sha256 match"), "verify still passes after remove");+ok("remove: manifest updated, files gone, verify still clean");++// remove an inherited-property name: constructor is truthy on a plain object, must not match+{+ const e = await runFail(["remove", "constructor"]);+ assert.match(String(e.stderr), /not installed/, "constructor is not an installed instrument");+}+ok("remove constructor: inherited props are not instruments (Object.hasOwn)");++// ---------------------------------------------------------------- finding 1: a foreign root is off-limits+{+ const foreign = join(root, "foreign");+ mkdirSync(foreign, { recursive: true });+ writeFileSync(join(foreign, "keep.txt"), "precious");+ writeFileSync(join(foreign, ".old-dotfiles"), "precious2"); // the old sweep regex would eat these+ writeFileSync(join(foreign, ".tmp-anything"), "precious3");+ for (const c of [["list"], ["get", "piano"], ["verify"], ["remove", "piano"], ["where"]]) {+ const e = await runFail(c, { ANIDOODLE_SOUNDS: foreign });+ assert.match(String(e.stderr), /refusing to touch/, `soundfetch ${c[0]} must refuse a foreign root`);+ }+ assert.equal(readFileSync(join(foreign, "keep.txt"), "utf8"), "precious");+ assert.equal(readFileSync(join(foreign, ".old-dotfiles"), "utf8"), "precious2");+ assert.equal(readFileSync(join(foreign, ".tmp-anything"), "utf8"), "precious3");+ assert.equal(readdirSync(foreign).length, 3, "nothing was created, renamed or deleted");+ process.env.ANIDOODLE_SOUNDS = foreign;+ assert.equal(soundsDir(), null, "soundsDir() is null on a foreign root");+ process.env.ANIDOODLE_SOUNDS = install;+}+ok("foreign-content root: every command refuses, nothing touched");++// and inside an OWNED dir, sweep only ever removes this tool's own .anidoodle-* names+{+ writeFileSync(join(install, ".old-dotfiles"), "mine");+ writeFileSync(join(install, ".tmp-user"), "mine2");+ writeFileSync(join(install, ".anidoodle-dl-stale-1"), "leftover"); // stale tool temp: fair game+ await run(["get", "rooms"]);+ assert.equal(readFileSync(join(install, ".old-dotfiles"), "utf8"), "mine");+ assert.equal(readFileSync(join(install, ".tmp-user"), "utf8"), "mine2");+ assert(!existsSync(join(install, ".anidoodle-dl-stale-1")), "stale tool temp swept");+}+ok("sweep removes only .anidoodle-* tool temps, foreign dotfiles survive");++// ---------------------------------------------------------------- finding 5: partial get keeps its licence+{+ const install2 = join(root, "install-partial");+ const distMiss = join(root, "dist-missing");+ cpSync(dist, distMiss, { recursive: true });+ rmSync(join(distMiss, "anidoodle-sounds-v1-harp.tar"));+ const e = await runFail(["get", "piano", "harp"], { ANIDOODLE_SOUNDS: install2, ANIDOODLE_SOUNDS_URL: distMiss });+ assert(e, "missing archive fails");+ assert(existsSync(join(install2, "LICENSES.md")), "licence written before the archive loop");+ assert((await run(["verify"], { ANIDOODLE_SOUNDS: install2 })).includes("all sha256 match"), "partial install still verifies");+ rmSync(install2, { recursive: true, force: true });+}+ok("failed second archive: first stays installed with LICENSES.md, verify clean");++// ---------------------------------------------------------------- refusal paths+// corrupt archive: same length, different bytes - the sha256 the index pins no longer matches+const distBad = join(root, "dist-corrupt");+rmSync(distBad, { recursive: true, force: true });+cpSync(dist, distBad, { recursive: true });+{+ const f = join(distBad, "anidoodle-sounds-v1-harp.tar");+ const b = readFileSync(f);+ b[b.length >> 1] ^= 0xff;+ writeFileSync(f, b);+}+{+ const e = await runFail(["get", "harp"], { ANIDOODLE_SOUNDS_URL: distBad });+ assert.match(String(e.stderr), /sha256 mismatch/, "corrupt archive refused on hash");+}+assert(!existsSync(join(install, "harp")), "corrupt archive left no files");+assert.deepEqual(Object.keys(merged().instruments), ["piano"]);+noLeftovers();+assert((await run(["verify"])).includes("all sha256 match"));+ok("corrupted archive refused, nothing left behind");++// tar escape vectors: each archive is honestly sha256'd by its own index, so the refusal has+// to come from the entry checks - a tampered index or archive hash would be a different bug+const rawTar = (file, entries) => {+ const fd = openSync(file, "w");+ try {+ for (const e of entries) {+ const h = tarHeader(e.name, e.size ?? e.data.length);+ if (e.type !== undefined) h[156] = e.type; // forge a link etc.+ writeSync(fd, h);+ writeSync(fd, e.data);+ const pad = (512 - (e.data.length % 512)) % 512;+ if (pad) writeSync(fd, Buffer.alloc(pad));+ }+ writeSync(fd, Buffer.alloc(1024));+ } finally {+ closeSync(fd);+ }+};+const evilDist = (name, entries) => {+ const d = join(root, name);+ rmSync(d, { recursive: true, force: true });+ cpSync(dist, d, { recursive: true });+ rawTar(join(d, "anidoodle-sounds-v1-harp.tar"), entries);+ const index = JSON.parse(readFileSync(join(dist, INDEX), "utf8"));+ const harp = index.archives.find((a) => a.instruments.includes("harp"));+ const f = join(d, "anidoodle-sounds-v1-harp.tar");+ harp.bytes = statSync(f).size;+ harp.sha256 = sha(f);+ writeFileSync(join(d, INDEX), JSON.stringify(index, null, 2) + "\n");+ return { ANIDOODLE_SOUNDS_URL: d, ANIDOODLE_SOUNDS_INDEX_SHA256: sha(join(d, INDEX)) };+};+const blob = Buffer.alloc(64, 1);+for (const [label, entries, re] of [+ ["traversal ../", [{ name: "../evil.flac", data: blob }], /unsafe entry/],+ ["absolute path", [{ name: "/tmp/evil.flac", data: blob }], /unsafe entry/],+ ["backslash", [{ name: "harp\\..\\evil.flac", data: blob }], /unsafe entry/],+ ["link typeflag", [{ name: "harp/x.flac", data: blob, type: 0x32 }], /link or non-file/],+ ["wrong top folder", [{ name: "other/x.flac", data: blob }], /unsafe entry/],+ ["oversized size", [{ name: "harp/x.flac", data: blob, size: 0x7fffffff }], /past the archive's real length/],+]) {+ const e = await runFail(["get", "harp"], evilDist(`dist-evil-${label.replace(/\W+/g, "-")}`, entries));+ assert.match(String(e.stderr), re, `${label}: expected refusal via ${re}`);+ assert(!existsSync(join(install, "harp")), `${label}: nothing installed`);+}+assert(!existsSync(join(root, "evil.flac")), "traversal payload never escaped");+assert(!existsSync(join(install, "evil.flac")), "traversal payload never reached the install");+assert(!existsSync("/tmp/evil.flac"), "absolute payload never written");+noLeftovers();+ok("tar escapes refused: ../, absolute, backslash, link, wrong top, oversized size");++// tampered index: pinned sha256 does not match+{+ const e = await runFail(["get", "harp"], { ANIDOODLE_SOUNDS_INDEX_SHA256: "0".repeat(64) });+ assert.match(String(e.stderr), /tampered index/, "index pin enforced");+}+noLeftovers();+ok("tampered index refused before any download");++// the REAL pinned hash path: no override at all, so the hard-coded INDEX_SHA256 is consulted.+// Negative leg first - the tiny index cannot match the release pin and must be refused.+{+ const e = await runFail(["get", "harp"], { ANIDOODLE_SOUNDS_INDEX_SHA256: "" });+ assert.match(String(e.stderr), /tampered index/, "without the override the release pin guards the index");+}+ok("no env override: the compiled-in pin is what refuses");++// Positive leg, when the real release dist is on this machine: fetch through the actual pin.+const REAL_DIST = "/Users/alexgreenshpun/CascadeProjects/Prompts/Claude-Skills/anidoodle-research/sound-pack/dist-v1";+if (existsSync(join(REAL_DIST, INDEX))) {+ const installReal = join(root, "install-real");+ let e = null;+ try {+ await run(["get", "marimba"], { ANIDOODLE_SOUNDS: installReal, ANIDOODLE_SOUNDS_URL: REAL_DIST, ANIDOODLE_SOUNDS_INDEX_SHA256: "" });+ } catch (x) {+ e = x;+ }+ assert.equal(e, null, "get marimba through the real pin succeeded");+ const m = JSON.parse(readFileSync(join(installReal, "manifest.json"), "utf8"));+ assert(Object.hasOwn(m.instruments, "marimba"), "marimba installed via the pinned index");+ ok("real pinned hash path: get marimba installs without any override");+} else {+ console.log("SKIP real pinned hash path (dist-v1 not on this machine)");+}++// oversized index: over the cap, refused before the hash is even compared+{+ const distBig = join(root, "dist-bigindex");+ cpSync(dist, distBig, { recursive: true });+ writeFileSync(join(distBig, INDEX), Buffer.alloc(9 * 1024 * 1024, 0x20));+ const e = await runFail(["get", "harp"], { ANIDOODLE_SOUNDS_URL: distBig, ANIDOODLE_SOUNDS_INDEX_SHA256: sha(join(distBig, INDEX)) });+ assert.match(String(e.stderr), /index cap/, "oversized index refused");+}+ok("oversized index refused before parsing");++// malformed index fields, reachable only with the pin overridden: an archive name that is not+// the release's own, and a zone file escaping its instrument dir+for (const [label, mutate, re] of [+ ["bad archive name", (ix) => { ix.archives.find((a) => a.instruments.includes("harp")).file = "../../etc/harp.tar"; }, /unsafe archive name/],+ ["bad zone file", (ix) => { ix.archives.find((a) => a.instruments.includes("harp")).manifest.instruments.harp.zones[0].file = "../x.flac"; }, /unsafe zone/],+]) {+ const d = join(root, `dist-ix-${label.replace(/\W+/g, "-")}`);+ cpSync(dist, d, { recursive: true });+ const ix = JSON.parse(readFileSync(join(d, INDEX), "utf8"));+ mutate(ix);+ writeFileSync(join(d, INDEX), JSON.stringify(ix, null, 2) + "\n");+ const e = await runFail(["get", "harp"], { ANIDOODLE_SOUNDS_URL: d, ANIDOODLE_SOUNDS_INDEX_SHA256: sha(join(d, INDEX)) });+ assert.match(String(e.stderr), re, `${label}: shape check refuses`);+}+ok("index shape checks: archive name and zone file validated");++// over-long stream: the server keeps sending past the declared bytes - the download is cut+{+ const server = createServer((req, res) => {+ const name = decodeURIComponent(req.url.split("?")[0].slice(1));+ const f = join(dist, name);+ if (!name || !existsSync(f)) { res.writeHead(404); return void res.end(); }+ const data = name.includes("harp") ? Buffer.concat([readFileSync(f), Buffer.of(0xaa)]) : readFileSync(f);+ res.writeHead(200, { "content-length": data.length });+ res.end(data);+ });+ await new Promise((r) => server.listen(0, "127.0.0.1", r));+ try {+ const e = await runFail(["get", "harp"], { ANIDOODLE_SOUNDS_URL: `http://127.0.0.1:${server.address().port}/` });+ assert.match(String(e.stderr ?? e.stdout), /more than the declared|bytes/, "over-long stream cut");+ } finally {+ server.close();+ }+ assert(!existsSync(join(install, "harp")));+ noLeftovers();+}+ok("over-long stream cut at the declared bytes");++// interrupted download: a live http server drops the connection mid-body+const server = createServer((req, res) => {+ const name = decodeURIComponent(req.url.split("?")[0].slice(1));+ const f = join(dist, name);+ if (!name || !existsSync(f)) { res.writeHead(404); return void res.end(); }+ const data = readFileSync(f);+ res.writeHead(200, { "content-length": data.length });+ if (name.includes("harp")) { res.write(data.subarray(0, data.length >> 1)); return void res.socket.destroy(); }+ res.end(data);+});+await new Promise((r) => server.listen(0, "127.0.0.1", r));+try {+ const e = await runFail(["get", "harp"], { ANIDOODLE_SOUNDS_URL: `http://127.0.0.1:${server.address().port}/` });+ assert(e, "interrupted download fails");+} finally {+ server.close();+}+assert.deepEqual(Object.keys(merged().instruments), ["piano"], "old install untouched");+noLeftovers();+assert((await run(["verify"])).includes("all sha256 match"), "previous state still verifies");+ok("interrupted download leaves the old install working");++// ---------------------------------------------------------------- two parallel gets+await Promise.all([run(["get", "harp"]), run(["get", "rooms"])]);+{+ const m = merged();+ assert(Object.hasOwn(m.instruments, "harp"), "parallel get: harp landed");+ assert.equal(Object.keys(m.rooms ?? {}).length, 1, "parallel get: rooms landed");+ assert(existsSync(join(install, "harp")) && existsSync(join(install, "rooms")), "both trees on disk");+}+noLeftovers();+ok("two parallel gets: both archives land, one merged manifest");++// ---------------------------------------------------------------- get all to finish+const out = await run(["get", "all"]);+assert(out.includes("already installed"), "installed ids skipped");+assert.deepEqual(Object.keys(merged().instruments).sort(), ["harp", "piano"]);+assert((await run(["verify"])).includes("all sha256 match"));+const list2 = await run(["list"]);+assert(!list2.includes("available"), "everything installed");+ok("get all: skips installed, installs the rest, merged manifest verifies");++console.log(`\n${pass} checks passed`);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/soundfetch.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/soundfetch.mjsnew file mode 100644index 0000000..c6c967c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/soundfetch.mjs@@ -0,0 +1,494 @@+#!/usr/bin/env node+// Sound pack fetcher: puts the anidoodle-sounds-v1 release on a user's machine. The pack is too+// big for the plugin, so it lives as a separate download of one tar per instrument + rooms ++// an index JSON (built by `tools/soundpack.mjs dist`).+//+// node tools/soundfetch.mjs list # what exists and what is installed, sizes+// node tools/soundfetch.mjs get piano harp rooms # download, verify, unpack (or: get all)+// node tools/soundfetch.mjs where # print the sounds directory+// node tools/soundfetch.mjs verify # re-hash everything installed+// node tools/soundfetch.mjs remove <id> # uninstall an instrument (or rooms)+//+// Source: ANIDOODLE_SOUNDS_URL or the default release URL below; a file:// URL or a bare local+// directory works too (that is how the unit test runs). The index is fetched first and refused+// unless its sha256 matches the release hash pinned in INDEX_SHA256+// (ANIDOODLE_SOUNDS_INDEX_SHA256 overrides, for testing a different dist), so a tampered index+// or archive never unpacks.+// Install dir: ANIDOODLE_SOUNDS if set, else ~/.anidoodle/sounds. It holds one merged+// manifest.json in the exact pack format of CONTRACT.md, the FLAC files and LICENSES.md.+//+// Ownership (security): this tool never deletes, renames or overwrites anything in a directory+// it does not own. A root that exists, holds entries other than this tool's own .anidoodle-*+// temp names, and has no manifest.json with pack "anidoodle-sounds" is refused by EVERY+// command - so pointing ANIDOODLE_SOUNDS at ~/Music can never eat it. Temp names carry the+// .anidoodle- prefix, so sweep can only ever match files this tool created.+//+// Safety: an archive downloads to a temp file inside the install dir, the stream is cut past+// the declared bytes, and size + sha256 are checked BEFORE unpacking. Every tar entry must be+// a regular file named <id>/<file>.flac (or manifest.json / LICENSES.md at the archive root):+// absolute names, "..", backslashes, links and declared sizes past the archive's real length+// are all refused. Unpack stages beside the instrument dir and swaps with rename; the merged+// manifest is rewritten after each instrument, atomically, so a failed or interrupted run+// leaves the previous state intact. Mutating commands hold an .anidoodle-lock mkdir lock, so+// two parallel gets cannot drop an instrument out of the manifest. Only `get` touches the+// network. Node built-ins only; the tar reader is below.+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, statSync, copyFileSync, readdirSync, createWriteStream, openSync, closeSync, readSync, realpathSync } from "node:fs";+import { homedir } from "node:os";+import { join, dirname, basename, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { Readable, Transform } from "node:stream";+import { pipeline } from "node:stream/promises";++const RELEASE = "anidoodle-sounds-v1";+const INDEX_FILE = `${RELEASE}.json`;+const DEFAULT_URL = "https://github.com/alexgreensh/anidoodle/releases/download/sounds-v1/";+// sha256 of anidoodle-sounds-v1.json for the release, produced by `soundpack.mjs dist` of+// pack-v1; a tampered index is refused before anything downloads.+const INDEX_SHA256 = "558d7fcb9138afa090ccf16b23355edbf8b98f63c26151646bf1721a6969840a";+const MAX_INDEX_BYTES = 8 * 1024 * 1024; // the real index is ~100 KB; this is headroom, not fit+const MAX_ARCHIVE_BYTES = 8 * 1024 * 1024 * 1024; // 8 GiB: a sane bound, far over the ~234 MB real++// Every temp name this tool ever creates carries the .anidoodle- prefix, so sweep and the+// ownership check below can recognise exactly what is ours and nothing else.+const tmpName = (kind, f) => `.anidoodle-${kind}-${f}-${process.pid}`;+const LOCK_DIR = ".anidoodle-lock";+const OWN_TEMP = /^\.anidoodle-(lock|dl|unpack|old|tmp)(-|$)/; // ours even when stale+const SWEEP_RE = /^\.anidoodle-(dl|unpack|old|tmp)-/; // stale temps only - NEVER the live lock++const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");+const sha256File = (f) => sha256(readFileSync(f));++// ---------------------------------------------------------------- paths+export const installRoot = () =>+ process.env.ANIDOODLE_SOUNDS ? resolve(process.env.ANIDOODLE_SOUNDS) : join(homedir(), ".anidoodle", "sounds");+// The resolved install directory, or null when nothing is installed (for tools/sounds.mjs+// callers deciding whether a pack exists at all).+export const soundsDir = () => {+ const d = installRoot();+ try {+ return JSON.parse(readFileSync(join(d, "manifest.json"), "utf8")).pack === "anidoodle-sounds" ? d : null;+ } catch {+ return null;+ }+};+const source = () => process.env.ANIDOODLE_SOUNDS_URL || DEFAULT_URL;+const isLocalSrc = (s) => !/^https?:\/\//i.test(s);+const srcFile = (s, name) => (s.startsWith("file://") ? join(fileURLToPath(s), name) : join(s, name));+const srcUrl = (s, name) => `${s.replace(/\/*$/, "")}/${name}`;++// Ownership gate, run by every command before anything else: a directory we do not own is+// never deleted from, renamed in or written to. "Ours" means: does not exist, contains only+// this tool's own temp names (stale or live), or has a manifest.json with+// pack "anidoodle-sounds". Anything else - a stray file, a foreign manifest, LICENSES.md alone+// - makes the root off-limits.+const claimRoot = (root) => {+ if (!existsSync(root)) return;+ const foreign = readdirSync(root).filter((e) => !OWN_TEMP.test(e));+ if (!foreign.length) return;+ let pack = null;+ try {+ pack = JSON.parse(readFileSync(join(root, "manifest.json"), "utf8")).pack;+ } catch { /* unreadable or foreign JSON: not ours */ }+ if (pack === "anidoodle-sounds") return;+ throw new Error(`refusing to touch ${root}: not empty and no manifest.json with pack "anidoodle-sounds". Point ANIDOODLE_SOUNDS at a dedicated directory.`);+};++// Stale temp cleanup. Only ever runs while holding the lock (a live process's temps are never+// swept from under it) and only ever matches the exact .anidoodle-* names this tool creates.+const sweep = (root) => {+ for (const e of readdirSync(root))+ if (SWEEP_RE.test(e)) rmSync(join(root, e), { recursive: true, force: true });+};+const atomicWrite = (file, data) => {+ const tmp = join(dirname(file), tmpName("tmp", basename(file)));+ writeFileSync(tmp, data);+ renameSync(tmp, file);+};+const readMerged = (root) => {+ const f = join(root, "manifest.json");+ if (!existsSync(f)) return null;+ try {+ const m = JSON.parse(readFileSync(f, "utf8"));+ return m?.pack === "anidoodle-sounds" ? m : null;+ } catch {+ return null;+ }+};++// ---------------------------------------------------------------- the lock+// Mutating commands (get, remove) hold an exclusive mkdir lock: two parallel gets can no+// longer sweep each other's temps or lose a manifest merge. A dead holder's lock is stolen+// (its recorded pid is gone); a live one is waited out.+const acquireLock = async (root) => {+ const dir = join(root, LOCK_DIR);+ for (let i = 0; i < 200; i++) {+ try {+ mkdirSync(dir);+ writeFileSync(join(dir, "pid"), `${process.pid} ${Date.now()}`);+ return;+ } catch (e) {+ if (e.code !== "EEXIST") throw e;+ }+ let pid = NaN;+ try {+ pid = Number(readFileSync(join(dir, "pid"), "utf8").split(" ")[0]);+ } catch { /* pid file not written yet - the creator had a microsecond to do it */ }+ if (pid > 0) {+ let alive = true;+ try {+ process.kill(pid, 0);+ } catch (e) {+ alive = e.code === "EPERM"; // exists but not ours+ }+ if (!alive) { rmSync(dir, { recursive: true, force: true }); continue; } // dead holder: steal+ } else if (i > 20) {+ rmSync(dir, { recursive: true, force: true }); // no pid for ~2 s: stale, steal+ continue;+ }+ await new Promise((r) => setTimeout(r, 100));+ }+ throw new Error(`${root} is still locked by another soundfetch after 20 s`);+};+const releaseLock = (root) => rmSync(join(root, LOCK_DIR), { recursive: true, force: true });++// ---------------------------------------------------------------- the index+// Every field that ends up in a path, a size or a manifest merge is shape-checked here - the+// pin makes tampering unprofitable, but an overridden pin must not become a path escape.+const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; // engine ids (piano.upright) and tar suffixes+const FORBIDDEN_ID = new Set(["__proto__", "constructor", "prototype", "manifest.json", "LICENSES.md", "rooms", "all"]);+const okId = (s) => typeof s === "string" && ID_RE.test(s) && !s.includes("..") && !FORBIDDEN_ID.has(s);+const SHA_RE = /^[0-9a-f]{64}$/;+const ZONE_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9#_+.-]+\.flac$/; // <id>/<name>.flac, two segments+const loadIndex = async () => {+ const src = source(), pin = process.env.ANIDOODLE_SOUNDS_INDEX_SHA256 || INDEX_SHA256;+ if (!pin) throw new Error("no index sha256 is pinned for this release (ANIDOODLE_SOUNDS_INDEX_SHA256 overrides for a test dist)");+ let buf;+ if (isLocalSrc(src)) {+ const f = srcFile(src, INDEX_FILE);+ if (!existsSync(f)) throw new Error(`${INDEX_FILE} not found in ${src}`);+ if (statSync(f).size > MAX_INDEX_BYTES) throw new Error(`${INDEX_FILE} exceeds the ${MAX_INDEX_BYTES}-byte index cap`);+ buf = readFileSync(f);+ } else {+ const res = await fetch(srcUrl(src, INDEX_FILE));+ if (!res.ok || !res.body) throw new Error(`index fetch failed: HTTP ${res.status}`);+ const chunks = [];+ let n = 0;+ for await (const c of Readable.fromWeb(res.body)) {+ n += c.length;+ if (n > MAX_INDEX_BYTES) throw new Error(`${INDEX_FILE} exceeds the ${MAX_INDEX_BYTES}-byte index cap`);+ chunks.push(c);+ }+ buf = Buffer.concat(chunks);+ }+ const sha = sha256(buf);+ if (sha !== pin) throw new Error(`refusing a tampered index: sha256 ${sha}, pinned ${pin}`);+ const index = JSON.parse(buf.toString("utf8"));+ const bad = (w) => { throw new Error(`${INDEX_FILE}: ${w}`); };+ if (index.release !== RELEASE || index.pack !== "anidoodle-sounds" || index.version !== 1 || !Array.isArray(index.archives))+ bad("not an anidoodle-sounds-v1 index");+ if (typeof index.licenses !== "string") bad("missing licenses text");+ for (const a of index.archives) {+ if (!a || typeof a !== "object") bad("malformed archive entry");+ if (!Array.isArray(a.instruments) || !Array.isArray(a.rooms)) bad(`${a.file}: malformed id lists`);+ if (a.instruments.length > 1) bad(`${a.file}: one archive holds one instrument`);+ for (const id of [...a.instruments, ...a.rooms]) if (!okId(id)) bad(`unsafe id ${JSON.stringify(id)}`);+ const top = a.instruments[0] ?? (a.rooms.length ? "rooms" : null);+ if (!top || typeof a.file !== "string" || a.file !== `${RELEASE}-${top}.tar`) bad(`unsafe archive name ${JSON.stringify(a.file)}`);+ if (!Number.isSafeInteger(a.bytes) || a.bytes < 1 || a.bytes > MAX_ARCHIVE_BYTES) bad(`${a.file}: implausible bytes ${a.bytes}`);+ if (typeof a.sha256 !== "string" || !SHA_RE.test(a.sha256)) bad(`${a.file}: malformed sha256`);+ const frag = a.manifest;+ if (!frag || typeof frag !== "object") bad(`${a.file}: no manifest fragment`);+ const sameKeys = (o, ids) => Object.keys(o ?? {}).sort().join("") === [...ids].sort().join("");+ if (!sameKeys(frag.instruments, a.instruments) || !sameKeys(frag.rooms, a.rooms)) bad(`${a.file}: fragment does not match its id list`);+ for (const id of a.instruments) {+ const inst = frag.instruments[id];+ if (!Array.isArray(inst.zones)) bad(`${a.file}: ${id} has no zones`);+ for (const z of inst.zones)+ if (typeof z.file !== "string" || !ZONE_FILE_RE.test(z.file) || z.file.split("/")[0] !== id || typeof z.sha256 !== "string" || !SHA_RE.test(z.sha256))+ bad(`${a.file}: unsafe zone ${JSON.stringify(z.file)}`);+ }+ for (const rid of a.rooms) {+ const r = frag.rooms[rid];+ if (typeof r.file !== "string" || !ZONE_FILE_RE.test(r.file) || r.file.split("/")[0] !== "rooms" || typeof r.sha256 !== "string" || !SHA_RE.test(r.sha256))+ bad(`${a.file}: unsafe room file ${JSON.stringify(r.file)}`);+ }+ }+ return index;+};++// ---------------------------------------------------------------- download+const download = async (src, a, tmp) => {+ if (isLocalSrc(src)) {+ const f = srcFile(src, a.file);+ if (!existsSync(f)) throw new Error(`${a.file}: not in ${src}`);+ if (statSync(f).size !== a.bytes) throw new Error(`${a.file}: ${statSync(f).size} bytes, index says ${a.bytes} - refusing`);+ copyFileSync(f, tmp);+ return;+ }+ const res = await fetch(srcUrl(src, a.file));+ if (!res.ok || !res.body) throw new Error(`${a.file}: download failed, HTTP ${res.status}`);+ let seen = 0;+ // the declared size bounds the stream: a server that keeps sending is cut, not believed+ const cap = new Transform({+ transform(c, _e, cb) {+ seen += c.length;+ cb(seen > a.bytes ? new Error(`${a.file}: more than the declared ${a.bytes} bytes`) : null, c);+ },+ });+ await pipeline(Readable.fromWeb(res.body), cap, createWriteStream(tmp));+};++// ---------------------------------------------------------------- tar reader+// Minimal ustar reader: our dist writes regular files only, mtime 0, no links - anything else+// is refused. Entry names must be <top>/<file>.flac two segments deep, or manifest.json /+// LICENSES.md at the root: no absolute paths, no "..", no backslashes, no empty segments. A+// declared size is trusted only inside the archive's real length, never enough to allocate on.+const octal = (h, at, len) => {+ const s = h.subarray(at, at + len).toString("latin1").replace(/\0[\s\S]*$/, "").trim();+ if (!/^[0-7]+$/.test(s)) throw new Error("tar: malformed numeric field");+ return parseInt(s, 8);+};+const cstr = (h, at, len) => h.subarray(at, at + len).toString("latin1").replace(/\0[\s\S]*$/, "");+const safeEntry = (name, top) => {+ const seg = name.split("/");+ if (!name || name.length > 255 || name.startsWith("/") || /^[A-Za-z]:/.test(name) || name.includes("\\")) return false;+ if (seg.some((s) => s === "" || s === "." || s === "..")) return false;+ if (seg.length === 1) return name === "manifest.json" || name === "LICENSES.md";+ return seg.length === 2 && seg[0] === top && seg[1].length > 0 && seg[1].endsWith(".flac");+};+const untar = (file, stage, top) => {+ const fileSize = statSync(file).size;+ const fd = openSync(file, "r");+ try {+ const hdr = Buffer.alloc(512);+ let pos = 0;+ for (;;) {+ let got = 0;+ while (got < 512) {+ const n = readSync(fd, hdr, got, 512 - got, pos + got);+ if (n === 0) break;+ got += n;+ }+ if (got === 0) break;+ if (got < 512) throw new Error(`${file}: truncated tar header at ${pos}`);+ if (hdr.every((b) => b === 0)) break; // end-of-archive zero block+ if (cstr(hdr, 257, 6) !== "ustar") throw new Error(`${file}: not a ustar archive at ${pos}`);+ const name = (() => { const p = cstr(hdr, 345, 155), n = cstr(hdr, 0, 100); return p ? `${p}/${n}` : n; })();+ const size = octal(hdr, 124, 12);+ const type = hdr[156];+ if (type !== 0x30 && type !== 0) throw new Error(`${file}: entry ${name} is a link or non-file (type ${String.fromCharCode(type || 0x30)})`);+ if (!safeEntry(name, top)) throw new Error(`${file}: refusing unsafe entry name ${JSON.stringify(name)}`);+ if (pos + 512 + size > fileSize) throw new Error(`${file}: entry ${name} declares ${size} bytes past the archive's real length`);+ const data = Buffer.alloc(size);+ let dgot = 0;+ while (dgot < size) {+ const n = readSync(fd, data, dgot, size - dgot, pos + 512 + dgot);+ if (n === 0) throw new Error(`${file}: truncated entry ${name}`);+ dgot += n;+ }+ const out = join(stage, ...name.split("/"));+ mkdirSync(dirname(out), { recursive: true });+ writeFileSync(out, data);+ pos += 512 + size + ((512 - (size % 512)) % 512);+ }+ } finally {+ closeSync(fd);+ }+};++// ---------------------------------------------------------------- install+// The staged tree must be exactly the fragment's declared files, each hashing to the manifest's+// sha256; the archive's own manifest.json must be the same fragment the index carries, and its+// LICENSES.md the index's text. A mismatch means dist and index disagree - refuse.+const checkStage = (stage, top, frag, licenses) => {+ for (const e of readdirSync(stage)) if (e !== top && e !== "manifest.json" && e !== "LICENSES.md") throw new Error(`unexpected archive entry ${e}`);+ const sm = join(stage, "manifest.json"), sl = join(stage, "LICENSES.md");+ if (!existsSync(sm) || readFileSync(sm, "utf8") !== JSON.stringify(frag, null, 2) + "\n") throw new Error("archive manifest.json does not match the index fragment");+ if (!existsSync(sl) || readFileSync(sl, "utf8") !== licenses) throw new Error("archive LICENSES.md does not match the index");+ const want = new Map();+ for (const inst of Object.values(frag.instruments ?? {})) for (const z of inst.zones) want.set(z.file, z.sha256);+ for (const r of Object.values(frag.rooms ?? {})) want.set(r.file, r.sha256);+ const topDir = join(stage, top);+ const staged = existsSync(topDir) ? readdirSync(topDir).map((f) => `${top}/${f}`) : [];+ for (const f of staged) if (!want.has(f)) throw new Error(`${f}: not declared in the manifest fragment`);+ for (const [f, sha] of want) {+ const p = join(stage, ...f.split("/"));+ if (!existsSync(p)) throw new Error(`${f}: missing from the archive`);+ if (sha256File(p) !== sha) throw new Error(`${f}: sha256 mismatch inside the archive`);+ }+};+// Stage sits beside the destination; swap by rename. A crash mid-swap can strand the old dir as+// .anidoodle-old-* (swept next run) but never leaves a half-written instrument under its name.+const swap = (root, stage, top) => {+ const dest = join(root, top), aside = join(root, tmpName("old", top));+ if (existsSync(dest)) renameSync(dest, aside);+ try {+ renameSync(join(stage, top), dest);+ } catch (e) {+ if (existsSync(aside) && !existsSync(dest)) renameSync(aside, dest);+ throw e;+ }+ if (existsSync(aside)) rmSync(aside, { recursive: true, force: true });+};+const mergeManifest = (root, frag) => {+ const m = readMerged(root) ?? { pack: "anidoodle-sounds", version: 1, sampleRate: 48000, instruments: {}, rooms: {} };+ // keys are validated against the id denylist in loadIndex before this ever runs+ for (const [k, v] of Object.entries(frag.instruments ?? {})) m.instruments[k] = v;+ for (const [k, v] of Object.entries(frag.rooms ?? {})) m.rooms[k] = v;+ atomicWrite(join(root, "manifest.json"), JSON.stringify(m, null, 2) + "\n");+};+const archiveInstalled = (m, a) =>+ !!m && a.instruments.every((i) => Object.hasOwn(m.instruments ?? {}, i)) && (!a.rooms.length || Object.keys(m.rooms ?? {}).length > 0);++const installArchive = async (a, root, index) => {+ const src = source();+ const tmp = join(root, tmpName("dl", a.file));+ const stage = join(root, tmpName("unpack", a.file));+ const top = a.instruments[0] ?? "rooms";+ try {+ process.stdout.write(`${a.file}: downloading ${(a.bytes / 1e6).toFixed(1)} MB... `);+ await download(src, a, tmp);+ const sz = statSync(tmp).size;+ if (sz !== a.bytes) throw new Error(`\n${a.file}: ${sz} bytes, index says ${a.bytes} - refusing`);+ if (sha256File(tmp) !== a.sha256) throw new Error(`\n${a.file}: sha256 mismatch - refusing a tampered archive`);+ mkdirSync(stage);+ untar(tmp, stage, top);+ checkStage(stage, top, a.manifest, index.licenses);+ swap(root, stage, top);+ mergeManifest(root, a.manifest);+ console.log("installed");+ } finally {+ rmSync(tmp, { force: true });+ rmSync(stage, { recursive: true, force: true });+ }+};++// ---------------------------------------------------------------- commands+const cmdGet = async (ids) => {+ const root = installRoot();+ claimRoot(root); // before mkdir, before the lock, before a single byte moves+ mkdirSync(root, { recursive: true });+ await acquireLock(root);+ try {+ sweep(root);+ const index = await loadIndex();+ const byId = new Map();+ for (const a of index.archives) {+ for (const id of a.instruments) byId.set(id, a);+ if (a.rooms.length) byId.set("rooms", a);+ }+ const wanted = ids.length === 1 && ids[0] === "all" ? [...byId.keys()] : ids;+ const unknown = wanted.filter((w) => !byId.has(w));+ if (unknown.length) throw new Error(`unknown sound id ${unknown.join(", ")} (the index has: ${[...byId.keys()].join(", ")})`);+ // claim the directory in its own format first: even a first get that fails leaves a valid,+ // owned install (and its licence) instead of ambiguous debris+ if (!readMerged(root)) mergeManifest(root, {});+ atomicWrite(join(root, "LICENSES.md"), index.licenses);+ const m = readMerged(root);+ for (const a of new Set(wanted.map((w) => byId.get(w)))) {+ if (archiveInstalled(m, a)) { console.log(`${a.file}: already installed (remove first to reinstall)`); continue; }+ await installArchive(a, root, index);+ }+ } finally {+ releaseLock(root);+ }+};++const sizeOf = (root, files) => files.reduce((s, rel) => { try { return s + statSync(join(root, ...rel.split("/"))).size; } catch { return s; } }, 0);+const printInstalled = (m, root) => {+ console.log(`${"id".padEnd(20)} ${"zones".padStart(5)} ${"MB".padStart(8)}`);+ for (const [id, inst] of Object.entries(m.instruments ?? {}))+ console.log(`${id.padEnd(20)} ${String(inst.zones.length).padStart(5)} ${(sizeOf(root, inst.zones.map((z) => z.file)) / 1e6).toFixed(1).padStart(8)}`);+ const rooms = Object.entries(m.rooms ?? {});+ if (rooms.length)+ console.log(`${"rooms".padEnd(20)} ${String(rooms.length).padStart(5)} ${(sizeOf(root, rooms.map(([, r]) => r.file)) / 1e6).toFixed(1).padStart(8)}`);+};++const cmdList = async () => {+ const root = installRoot();+ claimRoot(root);+ const m = readMerged(root);+ const src = source();+ console.log(`install: ${root}${m ? "" : " (nothing installed)"}`);+ if (isLocalSrc(src)) {+ // a local or file:// source is read from disk - no network involved - so the index's+ // available set can be shown beside the installed state+ const index = await loadIndex();+ console.log(`source: ${src}\n`);+ console.log(`${"archive".padEnd(44)} ${"MB".padStart(8)} ${"holds".padEnd(22)} status`);+ for (const a of index.archives) {+ const holds = a.instruments.concat(a.rooms.length ? ["rooms"] : []).join(", ");+ console.log(`${a.file.padEnd(44)} ${(a.bytes / 1e6).toFixed(1).padStart(8)} ${holds.padEnd(22)} ${archiveInstalled(m, a) ? "installed" : "available"}`);+ }+ } else {+ // never downloads without being asked: only get touches the network, so a remote source+ // reports the installed set from the merged manifest alone+ console.log(`source: ${src} (remote index is fetched by get only)`);+ if (m) { console.log(); printInstalled(m, root); }+ }+};++const cmdVerify = () => {+ const root = installRoot();+ claimRoot(root);+ const m = readMerged(root);+ if (!m) { console.error("nothing installed"); process.exit(1); }+ const bad = [];+ let n = 0;+ const check = (rel, want) => {+ const f = join(root, ...rel.split("/"));+ if (!existsSync(f)) { bad.push(`${rel}: missing`); return; }+ n++;+ if (sha256File(f) !== want) bad.push(`${rel}: sha256 mismatch`);+ };+ for (const inst of Object.values(m.instruments ?? {})) for (const z of inst.zones) check(z.file, z.sha256);+ for (const r of Object.values(m.rooms ?? {})) check(r.file, r.sha256);+ if (!existsSync(join(root, "LICENSES.md"))) bad.push("LICENSES.md missing");+ if (bad.length) { for (const b of bad) console.error(`FAIL ${b}`); console.error(`verify: ${bad.length} failure${bad.length > 1 ? "s" : ""}`); process.exit(1); }+ console.log(`verify: ${n} installed files, all sha256 match`);+};++const cmdRemove = async (id) => {+ const root = installRoot();+ claimRoot(root);+ await acquireLock(root);+ try {+ sweep(root);+ // read the manifest inside the lock: a parallel get's merge must not be read over and lost+ const m = readMerged(root);+ if (!m) { console.error("nothing installed"); process.exit(1); }+ let top = null;+ if (id === "rooms" && Object.keys(m.rooms ?? {}).length) { m.rooms = {}; top = "rooms"; }+ else if (Object.hasOwn(m.instruments ?? {}, id)) { delete m.instruments[id]; top = id; }+ if (!top) { console.error(`${id}: not installed`); process.exit(1); }+ // manifest first: it must never claim files that are already gone; a leftover dir is just+ // unclaimed disk a later get overwrites+ atomicWrite(join(root, "manifest.json"), JSON.stringify(m, null, 2) + "\n");+ rmSync(join(root, top), { recursive: true, force: true });+ console.log(`removed ${id}`);+ } finally {+ releaseLock(root);+ }+};++// ---------------------------------------------------------------- main+const isMain = () => {+ try {+ return !!process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);+ } catch {+ return false;+ }+};+if (isMain()) (async () => {+ const [cmd, ...args] = process.argv.slice(2);+ if (cmd === "list" && !args.length) await cmdList();+ else if (cmd === "get" && args.length) await cmdGet(args);+ else if (cmd === "where" && !args.length) { claimRoot(installRoot()); console.log(installRoot()); }+ else if (cmd === "verify" && !args.length) cmdVerify();+ else if (cmd === "remove" && args.length === 1) await cmdRemove(args[0]);+ else {+ console.error("usage: node tools/soundfetch.mjs list | get <id...|all> | where | verify | remove <id>");+ process.exit(2);+ }+})().catch((e) => { console.error(`error: ${e.message}`); process.exit(1); });diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/soundpack.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/soundpack.mjsnew file mode 100644index 0000000..80f4026--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/soundpack.mjs@@ -0,0 +1,928 @@+#!/usr/bin/env node+// Sound pack builder: free CC0 recordings (VCSL) -> the anidoodle pack both tracks build to+// (CONTRACT.md: manifest.json + FLAC zones + LICENSES.md). Track B's sampler plays this pack; we+// meet at the format and nowhere else.+//+// node tools/soundpack.mjs fetch <source-dir> [--only piano,marimba] # download the source files the recipes need (skip files already there, verify size)+// node tools/soundpack.mjs build <source-dir> <pack-dir> [--only ...] # write the pack: FLAC zones + manifest.json + LICENSES.md+// node tools/soundpack.mjs verify <pack-dir> # every rule of the contract, exit 1 on any failure+// node tools/soundpack.mjs report <pack-dir> # per instrument: zones, layers, widest pitch gap, MB+// node tools/soundpack.mjs dist <pack-dir> <dist-dir> # the release artifacts: one tar per instrument + rooms + anidoodle-sounds-v1.json+//+// Determinism: fixed ffmpeg flags with -bitexact, no metadata, manifest keys in a fixed order;+// building twice from the same sources gives the same manifest and the same sha256 per file.+// Zone gain is never touched; where the source normalized its layers (the Steinway, NORMALIZED.txt)+// the instrument says so ("normalized": true) and the engine supplies the dynamics.+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync, openSync, closeSync, writeSync } from "node:fs";+import { join, dirname, basename } from "node:path";+import { pathToFileURL } from "node:url";++const SR = 48000;+const VCSL_RAW = "https://raw.githubusercontent.com/sgossner/VCSL/master/";+// The whole-repo file index (size TAB path), kept with the research notes this tool was built from.+const VCSL_TREE = "/Users/alexgreenshpun/CascadeProjects/Prompts/Claude-Skills/anidoodle-research/sound-pack/vcsl-tree.tsv";++// ---------------------------------------------------------------- note names+const SEMI = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };+const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];+const noteMidi = (n, shift = 0) => {+ const m = /^([A-G])([#b]?)(-?\d+)$/.exec(n);+ if (!m) throw new Error(`bad note name "${n}"`);+ return (Number(m[3]) + 1) * 12 + SEMI[m[1]] + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0) + shift;+};+const midiName = (midi) => `${NAMES[midi % 12]}${Math.floor(midi / 12) - 1}`;+const hzOf = (midi) => 440 * 2 ** ((midi - 69) / 12);++// ---------------------------------------------------------------- recipes+// One table per instrument: the VCSL folder, how to read note/layer/rr out of its file names (they+// differ per instrument), the engine id, kind, damped, and which notes and layers to take. Mic+// position: one per instrument, the closest and driest the source records (Steinway Close, Knight+// Player, Harp KSHarp single pair, Marimba Outrigger, Vibes Main, Glock/Chimes/Timpani as recorded).+// Dynamic names -> layer 1 (softest) .. layers (hardest).+const LAYER_OF_DYN = { ppp: 1, pp: 1, p: 1, mp: 1, mf: 1, soft: 1, f: 2, ff: 2, fff: 2, med: 2, loud: 3 };+// Octave naming traps, both verified by measuring the recorded pitch, not assumed:+// - The Knight names its octaves one below standard MIDI (its PitchValueConversionChart.txt:+// A-1 = 21 ... C7 = 108), hence +12.+// - The struck idiophones (marimba, vibes, glockenspiel, chimes) are also all named one octave+// BELOW sounding pitch: measured zone spectra land on name+12 for every zone (e.g. marimba+// "F1" reads 87.3 Hz = F2; glock "G4" reads 787.8 Hz = G5), and the corrected spans reproduce+// the real instruments' compasses exactly: vibes F3..F6, glockenspiel G5..C8, chimes C4..F5.+// realRange is the real instrument's compass; the manifest range = recorded span widened by+// maxShift (default 2, the repitch allowance) at each end, clipped to realRange.+const RECIPES = [+ {+ id: "piano", title: "Grand Piano, Steinway B", kind: "struck", damped: true, normalized: true,+ dir: "Chordophones/Zithers/Grand Piano, Steinway B/NoSus",+ notesFiles: ["Chordophones/Zithers/Grand Piano, Steinway B/NORMALIZED.txt"],+ re: /^JHPiano_NoSus_Close_([A-G][#b]?-?\d+)_vl(\d+)_rr(\d+)\.wav$/,+ zone: (m) => ({ midi: noteMidi(m[1]), layer: Number(m[2]) - 1, rr: Number(m[3]) }), // vl2..4 -> layers 1..3+ take: (z) => z.midi % 4 === 2, // whole-tone source 22..104, every other note: gaps of 4, inside the +-2 repitch rule+ realRange: [21, 108], // the Steinway keyboard, A0..C8+ // Amendment b (2026-10-04): Sus = the same takes recorded with the pedal down (dampers lifted,+ // the whole harp rings in sympathy); Rel = the key/damper return noise after a NoSus note.+ // Same naming and vl2..4 layers, rr1 only. Rel covers only 33 of the 42 source notes (nothing+ // above ~G#5), so it ships what exists at the same every-other-note density.+ arts: [+ { art: "sus", dir: "Chordophones/Zithers/Grand Piano, Steinway B/Sus", re: /^JHPiano_Sus_Close_([A-G][#b]?-?\d+)_vl(\d+)_rr(\d+)\.wav$/ },+ { art: "rel", dir: "Chordophones/Zithers/Grand Piano, Steinway B/Rel", re: /^JHPiano_NoSusRel_Close_([A-G][#b]?-?\d+)_vl(\d+)_rr(\d+)\.wav$/ },+ ],+ },+ {+ id: "piano.upright", title: "Upright Piano, Knight", kind: "struck", damped: true,+ dir: "Chordophones/Zithers/Upright Piano, Knight/Sustains",+ notesFiles: ["Chordophones/Zithers/Upright Piano, Knight/Info.txt", "Chordophones/Zithers/Upright Piano, Knight/PitchValueConversionChart.txt"],+ re: /^Player_vl(\d+)_rr(\d+)_([A-G][#b]?-?\d+)\.wav$/,+ zone: (m) => ({ midi: noteMidi(m[3], 12), layer: Number(m[1]), rr: Number(m[2]) }),+ take: (z) => z.midi % 4 === 1 || z.midi === 108, // whole-tone 21..108, every other note, top C8 kept+ realRange: [21, 108],+ // Amendment b/c: the Knight ships key/damper release takes for its full note set (Player_rel_rr1_*,+ // one take per note, no velocity layers) - art "rel" at layer 1, same every-other-note density.+ arts: [+ { art: "rel", dir: "Chordophones/Zithers/Upright Piano, Knight/Releases",+ re: /^Player_rel_rr(\d+)_([A-G][#b]?-?\d+)\.wav$/,+ zone: (m) => ({ midi: noteMidi(m[2], 12), layer: 1, rr: Number(m[1]) }) },+ ],+ },+ {+ id: "harp", title: "Concert Harp", kind: "struck", damped: false,+ dir: "Chordophones/Composite Chordophones/Concert Harp",+ re: /^KSHarp_([A-G][#b]?-?\d+)_(fff|pp|ff|mf|mp|f|p)(\d?)\.wav$/,+ zone: (m) => ({ midi: noteMidi(m[1]), layer: LAYER_OF_DYN[m[2]], rr: 1 }), // trailing digit is a take number, one file per note+dynamic+ take: () => true,+ realRange: [23, 103], // concert harp Cb1..Gb7+ },+ {+ id: "marimba", title: "Marimba", kind: "struck", damped: false, sparse: true,+ dir: "Idiophones/Struck Idiophones/Marimba",+ re: /^Marimba_hit_Outrigger_([A-G][#b]?-?\d+)_(soft|med|loud)_\d+\.wav$/,+ zone: (m) => ({ midi: noteMidi(m[1], 12), layer: LAYER_OF_DYN[m[2]], rr: 1 }), // +12: VCSL names one octave below sounding pitch (measured)+ take: () => true,+ realRange: [36, 96], // 5-octave marimba C2..C7; the corrected recordings span F2..C7+ },+ {+ id: "vibes", title: "Vibraphone", kind: "struck", damped: true,+ dir: "Idiophones/Struck Idiophones/Vibraphone", // Hard Mallets + Soft Mallets subfolders+ re: /^Vibes_(hard|soft)_([A-G][#b]?-?\d+)_v(\d)_rr(\d)_Main\.wav$/,+ zone: (m) => ({ mallet: m[1], v: Number(m[3]), midi: noteMidi(m[2], 12), layer: m[1] === "soft" ? 1 : Number(m[3]), rr: Number(m[4]) }), // +12: VCSL names one octave below sounding pitch (measured)+ // soft v1 = layer 1 (the source has no soft-and-quiet hard take); hard v2/v3 = layers 2/3.+ // soft v2 is a different mallet at the same dynamic, not a round robin, so it is left out.+ take: (z) => !(z.mallet === "soft" && z.v === 2),+ realRange: [53, 89], // 3-octave vibraphone F3..F6+ },+ {+ id: "glockenspiel", title: "Glockenspiel", kind: "struck", damped: false, sparse: true,+ dir: "Idiophones/Struck Idiophones/Glockenspiel",+ re: /^glock_(soft|medium|loud)_([A-G][#b]?-?\d+)_\d+\.wav$/,+ zone: (m) => ({ midi: noteMidi(m[2], 12), layer: { soft: 1, medium: 2, loud: 3 }[m[1]], rr: 1 }), // +12: VCSL names one octave below sounding pitch (measured)+ take: () => true,+ realRange: [79, 108], // orchestral glockenspiel G5..C8; the corrected recordings span exactly that+ },+ {+ id: "bell.tubular", title: "Tubular Bells 1", kind: "struck", damped: false, pitch: "chime",+ dir: "Idiophones/Struck Idiophones/Tubular Bells 1",+ re: /^chimes_([A-G][#b]?-?\d+)_(fff|pp|ff|mf|mp|f|p)_rr(\d+)\.wav$/,+ // +12: a chime's perceived strike note sits an octave below its 4th flexural mode, and that+ // measured strike note is name+12 within +-11 cents on all 9 tubes (mode4/2: e.g. the "C3" tube+ // peaks at 524.2 Hz, strike 262.1 Hz = C4). name+24 would imply chimes sounding up to E6, which+ // no real chime set reaches; name+12 lands the set at C4..E5, inside the real C4..F5/G5 compass.+ zone: (m) => ({ midi: noteMidi(m[1], 12), layer: LAYER_OF_DYN[m[2]], rr: 1 }), // rr digits are take numbers: one file per note+dynamic+ take: () => true,+ realRange: [60, 79], // orchestral chimes C4..G5+ },+ {+ id: "timpani", title: "Timpani", kind: "struck", damped: false, pitchedByMeasurement: true,+ dir: "Membranophones/Struck Membranophones/Timpani 2/Hit",+ re: /^Timpani(\d+[A-Z])_hit_v(\d+)_rr(\d+)_main\.wav$/,+ zone: (m) => ({ drum: `Timpani${m[1]}`, layer: { 2: 1, 3: 2, 5: 3 }[Number(m[2])], rr: Number(m[3]) }),+ // Drums chosen from a measured pass over all 34 (see the report's pitch table): a spanning set+ // across E2..A3 with measured gaps of 1-2 semitones, preferring drums whose hits agree. The+ // letters do not encode pitch (no sfz or notes file in the repo decodes them), so every hit is+ // measured: a hit is kept only when its estimate is stable and agrees with its drum's median;+ // anything else is skipped, never guessed. measuredHz rides along so Alex can check it by ear.+ take: (z) => TIMPANI_DRUMS.includes(z.drum),+ realRange: [36, 72], // a kettle's pedal range is about a fifth; the whole set C2..C5+ },+];+// Filled in from the measurement pass (build asserts it is not empty).+const TIMPANI_DRUMS = ["7G", "7D", "2A", "7B", "3A", "6G", "3B", "6E", "3C", "6D", "4A", "8E", "5A", "5B"].map((d) => `Timpani${d}`);++// ---------------------------------------------------------------- rooms (contract amendment b)+// Recorded impulse responses of real spaces, from OpenAIR (Audio Lab, University of York, CC BY+// 4.0): B-format W X Y Z decoded to stereo as L = W + Y, R = W - Y, direct sound at frame 0,+// unit energy, tail cut by the same rule as zones. manifest.rooms maps room id -> metadata;+// directFrames is the length of the direct sound, for the engine to skip.+const ROOMS_SRC = "/Users/alexgreenshpun/CascadeProjects/Prompts/Claude-Skills/anidoodle-research/sound-pack/rooms-src";+const ROOMS = [+ { id: "small-room", title: "Arthur Sykes Rymer Auditorium, University of York",+ wav: "arthur-sykes-rymer-auditorium-university-york/arthur-sykes-rymer-auditorium-university-york/b-format/s1r7.wav",+ page: "https://www.openair.hosted.york.ac.uk/?page_id=425" },+ { id: "recital-hall", title: "Jack Lyons Concert Hall, University of York",+ wav: "jack-lyons-concert-hall-university-york/jack-lyons-concert-hall-university-york/b-format/rir_jack_lyons_lp1_96k.wav",+ page: "https://www.openair.hosted.york.ac.uk/?page_id=571" },+ // average_space_ir_0.wav is the set's space-averaged B-format IR: the room response averaged+ // over every drum position, neutral by construction where a single drum position's take+ // carries that spot's coloration.+ { id: "live-room", title: "Genesis 6 Studio live room, University of York",+ wav: "genesis-6-studio-live-room-drum-set/genesis-6-studio-live-room-drum-set/examples/average_space_ir_0.wav",+ page: "https://www.openair.hosted.york.ac.uk/?page_id=483" },+];+const DIRECT_FRAMES = Math.round(0.0025 * SR); // ~2.5 ms of direct sound, for the engine to skip++// ---------------------------------------------------------------- the VCSL index+const tree = () => {+ const map = new Map(); // path -> size+ for (const line of readFileSync(VCSL_TREE, "utf8").split("\n")) {+ const [size, path] = line.split("\t");+ if (path) map.set(path, Number(size));+ }+ return map;+};+const needed = (recipes, index) => {+ const files = [];+ for (const r of recipes) {+ const sources = [{ dir: r.dir, re: r.re }, ...(r.arts ?? [])];+ for (const src of sources) {+ for (const [path, size] of index) {+ if (!path.startsWith(src.dir + "/")) continue;+ const m = src.re.exec(basename(path));+ if (!m) continue;+ const z = (src.zone ?? r.zone)(m);+ if (!r.take(z)) continue;+ if (src.art) z.art = src.art;+ files.push({ recipe: r, path, size, z });+ }+ }+ for (const n of r.notesFiles ?? []) {+ const size = index.get(n);+ if (size === undefined) throw new Error(`${n} not in the VCSL index`);+ files.push({ recipe: r, path: n, size, notes: true });+ }+ }+ return files;+};+const local = (dir, path) => join(dir, ...path.split("/"));+const enc = (path) => path.split("/").map(encodeURIComponent).join("/");++// ---------------------------------------------------------------- fetch+const fetchFiles = async (files, srcDir) => {+ const queue = files.filter(({ path, size }) => {+ const f = local(srcDir, path);+ if (existsSync(f) && statSync(f).size === size) return false;+ if (existsSync(f)) console.log(` re-fetch ${path} (size ${statSync(f).size} != ${size})`);+ return true;+ });+ console.log(`fetch: ${files.length} files needed, ${queue.length} to download`);+ let done = 0;+ const failed = [];+ const worker = async () => {+ while (queue.length) {+ const { path, size } = queue.shift();+ const res = await fetch(VCSL_RAW + enc(path));+ if (!res.ok) { failed.push(`${path}: HTTP ${res.status}`); continue; }+ const buf = Buffer.from(await res.arrayBuffer());+ if (buf.length !== size) { failed.push(`${path}: got ${buf.length} bytes, index says ${size}`); continue; }+ const f = local(srcDir, path);+ mkdirSync(dirname(f), { recursive: true });+ writeFileSync(f, buf);+ if (++done % 25 === 0) console.log(` ${done} fetched`);+ }+ };+ await Promise.all(Array.from({ length: 6 }, worker));+ if (failed.length) { for (const f of failed) console.error(` FAILED ${f}`); process.exit(1); }+ console.log(`fetch: ${done} downloaded, all sizes verified`);+};++// ---------------------------------------------------------------- decode / encode / measure+// Every ffmpeg/ffprobe call goes through here: a spawned child can wedge (seen live: an flac+// encode sat at 0% CPU for 30+ min with 99% of its output written - the classic spawnSync+// large-stdin deadlock on macOS). A hard timeout turns that into a loud, named failure instead+// of a silent hang.+const runFf = (bin, args, opts, what) => {+ try {+ return execFileSync(bin, args, { maxBuffer: 1 << 30, timeout: 120000, ...opts });+ } catch (e) {+ throw new Error(e.killed ? `${bin} timed out after 120 s on ${what} (wedged child killed)` : `${bin} failed on ${what}: ${e.message}`);+ }+};+const ffprobe = (f) => JSON.parse(runFf("ffprobe", ["-v", "error", "-print_format", "json", "-show_streams", f], {}, basename(f)).toString()).streams[0];+const decode = (f, ch) => {+ const b = runFf("ffmpeg", ["-v", "error", "-i", f, "-f", "f32le", "-ac", String(ch), "-ar", String(SR), "-"], {}, basename(f));+ return new Float32Array(b.buffer, b.byteOffset, b.byteLength / 4);+};+const db = (x) => 20 * Math.log10(x);++// Trim, fade, cut, encode one zone. Never changes gain: the fades are the only multiplies.+// Tail cut (contract, amendment c 2026-10-04, same rule for every instrument and art): whichever+// comes first - the level comes within 6 dB of the SOURCE file's own noise floor (the RMS of its+// last 0.5 s), or 60 dB below the note's peak, or a 20 s cap - then a 250 ms fade-out, so a cut at+// the noise floor is never heard. The earlier "stopped falling" trigger was wrong: a piano's slow+// second-stage decay and a pedalled piano's sympathy ring both fall slowly enough to trip it.+const processZone = (wav, ch, out) => {+ const x = decode(wav, ch), n = x.length / ch;+ let peak = 0;+ for (let i = 0; i < x.length; i++) { const a = Math.abs(x[i]); if (a > peak) peak = a; }+ const amp = (i) => { let m = 0; for (let c = 0; c < ch; c++) { const a = Math.abs(x[i * ch + c]); if (a > m) m = a; } return m; };+ const on = (() => { const thr = peak * 10 ** (-40 / 20); for (let i = 0; i < n; i++) if (amp(i) > thr) return i; return n; })();+ // 2 ms of pre-onset silence, minus a 4-sample guard: 24-bit quantization can nudge the onset a+ // sample or two later, and the contract's 2 ms is measured on the WRITTEN file+ const s0 = Math.max(0, on - Math.round(0.002 * SR) + 4);+ // 0.5 s RMS envelope (absolute dBFS) drives the tail cut, against the source file's own noise+ // floor: the RMS of its last 0.5 s (a digital-silence floor is -inf and simply never triggers)+ const B = Math.round(0.5 * SR), nb = Math.floor(n / B), env = [];+ for (let k = 0; k < nb; k++) {+ let sum = 0;+ for (let i = k * B; i < (k + 1) * B; i++) for (let c = 0; c < ch; c++) sum += x[i * ch + c] * x[i * ch + c];+ env.push(db(Math.sqrt(sum / (B * ch)) || 1e-12));+ }+ const TAIL = Math.min(Math.round(0.5 * SR), n);+ let fsum = 0;+ for (let i = (n - TAIL) * ch; i < n * ch; i++) fsum += x[i] * x[i];+ const floorDb = db(Math.sqrt(fsum / (TAIL * ch)) || 1e-12);+ const end = (() => {+ const kon = Math.floor(on / B), kcap = Math.min(nb, Math.ceil((on + 20 * SR) / B));+ for (let k = kon + 1; k < kcap; k++) {+ if (env[k] <= floorDb + 6) return k * B; // within 6 dB of the source's noise floor+ if (env[k] <= db(peak) - 60) return k * B; // 60 dB below the note's peak+ }+ return Math.min(nb * B, on + 20 * SR); // cap: never past onset + 20 s+ })();+ const cut = Math.max(end, on + Math.round(0.2 * SR), s0 + 1);+ // the 0.5 ms fade-in exists so the CUT never clicks; when the source itself starts at the onset+ // (s0 = 0, VCSL files begin near digital silence) there is no cut and the fade would only bury+ // the attack's own precursor below the -40 dB onset threshold+ const fadeIn = s0 > 0 ? Math.min(Math.round(0.0005 * SR), cut - s0) : 0, fadeOut = Math.min(Math.round(0.25 * SR), cut - s0);+ const frames = cut - s0;+ for (let i = 0; i < fadeIn; i++) { const g = i / fadeIn; for (let c = 0; c < ch; c++) x[(s0 + i) * ch + c] *= g; }+ for (let i = 0; i < fadeOut; i++) { const g = 1 - i / fadeOut; for (let c = 0; c < ch; c++) x[(cut - fadeOut + i) * ch + c] *= g; }+ const pcm = Buffer.from(x.buffer, x.byteOffset + s0 * ch * 4, frames * ch * 4);+ encFlac(pcm, ch, out);+ return { frames, channels: ch };+};+const encFlac = (pcm, ch, out) => {+ runFf("ffmpeg", ["-v", "error", "-y", "-bitexact", "-f", "f32le", "-ar", String(SR), "-ac", String(ch), "-i", "-",+ "-map_metadata", "-1", "-bitexact", "-c:a", "flac", "-compression_level", "8", "-sample_fmt", "s32", "-bits_per_raw_sample", "24", out],+ { input: pcm }, out);+};+// One recorded impulse response -> a normalized stereo FLAC under rooms/<id>.flac. Steps per+// amendment b: decode B-format (W X Y Z) to stereo L = W + Y / R = W - Y, trim so the direct+// arrival sits at frame 0 (the direct sound stays in the file), cut the tail by the zone rule+// (within 6 dB of the source's own last-0.5 s floor, or 60 dB below peak, or 20 s), 250 ms+// fade-out, and normalize the written region to unit energy.+const processRoom = (wav, out) => {+ const x = decode(wav, 4), n = x.length / 4;+ const y = new Float32Array(n * 2);+ let peak = 0;+ for (let i = 0; i < n; i++) {+ const l = x[i * 4] + x[i * 4 + 2], r = x[i * 4] - x[i * 4 + 2];+ y[i * 2] = l; y[i * 2 + 1] = r;+ const a = Math.max(Math.abs(l), Math.abs(r)); if (a > peak) peak = a;+ }+ const thr = peak * 10 ** (-40 / 20);+ let on = 0;+ while (on < n && Math.max(Math.abs(y[on * 2]), Math.abs(y[on * 2 + 1])) <= thr) on++;+ const z = y.subarray(on * 2), m = n - on;+ const B = Math.round(0.5 * SR), nb = Math.floor(m / B), env = [];+ for (let k = 0; k < nb; k++) {+ let sum = 0;+ for (let i = k * B; i < (k + 1) * B; i++) sum += z[i] * z[i];+ env.push(db(Math.sqrt(sum / (B * 2)) || 1e-12));+ }+ const TAIL = Math.min(Math.round(0.5 * SR), m);+ let fs = 0;+ for (let i = (m - TAIL) * 2; i < m * 2; i++) fs += z[i] * z[i];+ const floorDb = db(Math.sqrt(fs / (TAIL * 2)) || 1e-12), peakDb = db(peak);+ const end = (() => {+ const kcap = Math.min(nb, Math.ceil(20 * SR / B));+ for (let k = 1; k < kcap; k++) {+ if (env[k] <= floorDb + 6) return k * B;+ if (env[k] <= peakDb - 60) return k * B;+ }+ return Math.min(nb * B, 20 * SR);+ })();+ const cut = Math.max(end, Math.round(0.2 * SR));+ const fadeOut = Math.min(Math.round(0.25 * SR), cut);+ for (let i = 0; i < fadeOut; i++) { const g = 1 - i / fadeOut; z[(cut - fadeOut + i) * 2] *= g; z[(cut - fadeOut + i) * 2 + 1] *= g; }+ let e = 0;+ for (let i = 0; i < cut * 2; i++) e += z[i] * z[i];+ const g = 1 / Math.sqrt(e);+ const pcm = Buffer.alloc(cut * 2 * 4);+ for (let i = 0; i < cut * 2; i++) pcm.writeFloatLE(z[i] * g, i * 4);+ encFlac(pcm, 2, out);+ return { frames: cut, channels: 2 };+};+// rt60 by Schroeder integration in the 500 Hz-1 kHz band: RBJ bandpass (1 octave, centered at+// the band's geometric mean ~707 Hz) on the channel-sum mono, reverse-cumulative energy, a+// least-squares line over the -5..-35 dB portion of the decay curve, rt60 = -60/slope.+const rt60Of = (x, ch) => {+ const n = x.length / ch;+ const f0 = Math.sqrt(500 * 1000), w0 = 2 * Math.PI * f0 / SR;+ const alpha = Math.sin(w0) * Math.sinh(Math.LN2 / 2 * 1 * w0 / Math.sin(w0));+ const b0 = alpha, b2 = -alpha, a0 = 1 + alpha, a1 = -2 * Math.cos(w0), a2 = 1 - alpha;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;+ const sq = new Float64Array(n);+ for (let i = 0; i < n; i++) {+ const v = (b0 * (x[i * ch] + x[i * ch + (ch - 1)]) / 2 + b2 * x2 - a1 * y1 - a2 * y2) / a0;+ x2 = x1; x1 = (x[i * ch] + x[i * ch + (ch - 1)]) / 2; y2 = y1; y1 = v;+ sq[i] = v * v;+ }+ const edc = new Float64Array(n);+ let acc = 0;+ for (let i = n - 1; i >= 0; i--) { acc += sq[i]; edc[i] = acc; }+ const e0 = edc[0], curve = new Float64Array(n);+ for (let i = 0; i < n; i++) curve[i] = 10 * Math.log10(edc[i] / e0 || 1e-30);+ let i0 = curve.findIndex((v) => v <= -5), i1 = curve.findIndex((v) => v <= -35);+ if (i1 <= i0 + SR / 20) i1 = curve.findIndex((v) => v <= -25); // very short room: T20 instead+ if (i0 < 0 || i1 <= i0) return null;+ let sx = 0, sy = 0, sxx = 0, sxy = 0, cnt = 0;+ for (let i = i0; i <= i1; i += 8) { const t = i / SR; sx += t; sy += curve[i]; sxx += t * t; sxy += t * curve[i]; cnt++; }+ return -60 / ((cnt * sxy - sx * sy) / (cnt * sxx - sx * sx));+};+// Measure the WRITTEN file: peakDb over everything, rmsDb over the first 500 ms, and (when id is+// given) the zone's pitch via the estimator the recipe's physics needs.+const measureFlac = (f, id) => {+ const s = ffprobe(f), ch = s.channels, x = decode(f, ch), n = x.length / ch;+ let peak = 0;+ for (let i = 0; i < x.length; i++) { const a = Math.abs(x[i]); if (a > peak) peak = a; }+ const m = Math.min(n, Math.round(0.5 * SR));+ let sum = 0;+ for (let i = 0; i < m * ch; i++) sum += x[i] * x[i];+ const r = { frames: n, channels: ch, peakDb: db(peak), rmsDb: db(Math.sqrt(sum / (m * ch))) };+ if (id) { const p = measureZone(id, x, ch); if (p.stable) r.pitchHz = p.hz; }+ return r;+};++// ---------------------------------------------------------------- pitch by measurement+// Iterative radix-2 FFT (no dependencies in tools).+const fft = (re, im) => {+ const n = re.length;+ for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } }+ for (let len = 2; len <= n; len <<= 1) {+ const ang = -2 * Math.PI / len, wr = Math.cos(ang), wi = Math.sin(ang);+ for (let i = 0; i < n; i += len) {+ let cr = 1, ci = 0;+ for (let j = 0; j < len / 2; j++) {+ const ur = re[i + j], ui = im[i + j], vr = re[i + j + len / 2] * cr - im[i + j + len / 2] * ci, vi = re[i + j + len / 2] * ci + im[i + j + len / 2] * cr;+ re[i + j] = ur + vr; im[i + j] = ui + vi; re[i + j + len / 2] = ur - vr; im[i + j + len / 2] = ui - vi;+ const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t;+ }+ }+ }+};+// Hann-windowed magnitude spectrum, N samples at frac into the signal, zero-padded to FFTN.+const FFTN = 32768;+const spectrumOf = (x, ch, frac) => {+ const n = x.length / ch;+ let N = 16384;+ while (N > n) N >>= 1;+ if (N < 2048) return null;+ const o = Math.min(Math.floor(n * frac), n - N);+ const re = new Float64Array(FFTN), im = new Float64Array(FFTN);+ for (let i = 0; i < N; i++) { let s = 0; for (let c = 0; c < ch; c++) s += x[(o + i) * ch + c]; re[i] = s / ch * (0.5 - 0.5 * Math.cos(2 * Math.PI * i / N)); }+ fft(re, im);+ const mag = new Float64Array(FFTN / 2);+ for (let i = 0; i < FFTN / 2; i++) mag[i] = Math.hypot(re[i], im[i]);+ return mag;+};+// Strongest spectral peaks, parabolic-refined, >=1.5% apart, lo..hi Hz.+const peakList = (mag, loHz, hiHz, count) => {+ const binHz = SR / FFTN, lo = Math.max(2, Math.ceil(loHz / binHz)), hi = Math.min(mag.length - 2, Math.floor(hiHz / binHz));+ const idx = [];+ for (let i = lo; i <= hi; i++) idx.push(i);+ idx.sort((a, b) => mag[b] - mag[a]);+ const out = [];+ for (const i of idx) {+ const a = Math.log(mag[i - 1]), b = Math.log(mag[i]), c = Math.log(mag[i + 1]);+ const d = a - 2 * b + c;+ const hz = (i + (d ? 0.5 * (a - c) / d : 0)) * binHz;+ if (!isFinite(hz) || hz < loHz) continue;+ if (out.some((p) => Math.abs(hz - p.hz) / hz < 0.015)) continue;+ out.push({ hz, mag: mag[i] });+ if (out.length >= count) break;+ }+ return out;+};+const centsOf = (a, b) => 1200 * Math.log2(a / b);+// Fundamental of a harmonic zone (strings, bars). Candidates come from the observed peaks+// themselves (peak / k for k = 1..12), not a blind grid: a dense grid can lock onto subsonic+// rumble (a ~30 Hz cluster explains the whole spectrum if every partial lands on a high k), while+// a peak-derived candidate for the true f0 also explains its own ladder and still wins on 1/n-+// weighted comb energy. Bounded octave descent (f/2 wins only if it keeps >=85% of the comb+// energy) covers the missing-fundamental case. Two windows of the ring must agree within 50 cents+// or the estimate is unstable.+const harmonicPitch = (x, ch) => {+ const est = (frac) => {+ const mag = spectrumOf(x, ch, frac);+ if (!mag) return null;+ const pk = peakList(mag, 40, 12000, 20);+ if (!pk.length) return null;+ const score = (f0) => {+ let s = 0;+ for (const p of pk) {+ const k = Math.round(p.hz / f0);+ if (k < 1 || k > 16) continue;+ if (Math.abs(centsOf(p.hz, k * f0)) < 40) s += p.mag / k;+ }+ return s;+ };+ const cands = new Map();+ for (const p of pk) for (let k = 1; k <= 12; k++) { const f0 = p.hz / k; if (f0 >= 24 && f0 <= 6000) cands.set(f0, score(f0)); }+ let best = 0, bs = -1;+ for (const [f0, s] of cands) if (s > bs) { bs = s; best = f0; }+ for (let k = 0; k < 3 && best / 2 >= 24 && score(best / 2) >= 0.85 * score(best); k++) best /= 2;+ const ests = [], matched = [];+ for (const p of pk) { const k = Math.round(p.hz / best); if (k >= 1 && Math.abs(centsOf(p.hz, k * best)) < 40) { ests.push(p.hz / k); matched.push(p); } }+ // a believable winner explains >= 2 peaks, or is a lone partial that towers over the rest;+ // a single low peak no stronger than its neighbors is just rumble, and rumble must not+ // answer confidently (the softest marimba hits are rumble-dominated end to end)+ const unmatchedMax = pk.filter((p) => !matched.includes(p)).reduce((a, p) => Math.max(a, p.mag), 0);+ if (matched.length < 2 && !(matched.length === 1 && matched[0].mag >= 3 * unmatchedMax)) return null;+ ests.sort((a, b) => a - b);+ return ests[ests.length >> 1];+ };+ const a = est(0.06), b = est(0.25);+ if (!a || !b) return { hz: 0, stable: false };+ return { hz: (a + b) / 2, stable: Math.abs(centsOf(a, b)) < 50 };+};+// Strike note of a tubular bell: fit the tube's flexural modes {1, 2.76, 5.40, 8.93, 13.3, 18.6}+// and take the 4th mode down an octave (the perceived strike pitch; measured = name+12 on all 9+// VCSL tubes within +-11 cents). Fewer than 4 matched modes = unstable.+const CHIME_MODES = [1, 2.76, 5.40, 8.93, 13.3, 18.6];+const bellPitch = (x, ch) => {+ const mag = spectrumOf(x, ch, 0.2);+ if (!mag) return { hz: 0, stable: false };+ const pk = peakList(mag, 40, 6000, 14);+ let best = null;+ for (const p of pk) for (const r of CHIME_MODES) {+ const f1 = p.hz / r;+ if (f1 < 40 || f1 > 400) continue;+ let matched = 0, score = 0;+ for (const m of CHIME_MODES) {+ const hit = pk.find((q) => Math.abs(q.hz - f1 * m) / (f1 * m) < 0.025);+ if (hit) { matched++; score += hit.mag; }+ }+ if (!best || matched > best.matched || (matched === best.matched && score > best.score)) best = { f1, matched };+ }+ if (!best || best.matched < 4) return { hz: 0, stable: false };+ const m4 = pk.reduce((b, p) => Math.abs(p.hz / best.f1 - 8.93) < Math.abs(b.hz / best.f1 - 8.93) ? p : b);+ return { hz: m4.hz / 2, stable: true };+};+// Fundamental of a timpani hit. The membrane's modes are INHARMONIC (the strongest spectral peak is+// usually the (2,1) mode, and autocorrelation locks onto difference frequencies), so score candidate+// f0 against the kettle's mode ratios instead of a harmonic comb. Two windows of the ring must agree+// within 20 cents or the hit is reported unstable and skipped, never guessed.+const MODES = [1, 1.45, 1.93, 2.39, 2.71]; // (1,1) (2,1) (3,1) (4,1) (2,2) of a kettle membrane+const pitchOf = (x, ch) => {+ const est = (frac) => {+ const mag = spectrumOf(x, ch, frac);+ if (!mag) return null;+ const at = (hz) => { const b = hz * FFTN / SR, i = Math.max(1, Math.floor(b)), f = b - i; return Math.max(mag[i - 1] * (1 - f) + mag[i] * f, mag[i] * (1 - f) + mag[i + 1] * f, mag[i + 1] * (1 - f) + mag[i + 2] * f); };+ let best = 0, bs = -1;+ for (let f0 = 55; f0 <= 260; f0 += 0.25) {+ let s = 0; for (const m of MODES) s += at(f0 * m);+ if (s > bs) { bs = s; best = f0; }+ }+ return best || null;+ };+ const a = est(0.3), b = est(0.55);+ if (!a || !b) return { hz: 0, stable: false };+ return { hz: (a + b) / 2, stable: Math.abs(1200 * Math.log2(a / b)) < 20 };+};+// pitchOf measured on the untrimmed source (timpani selection happens before encode); for every+// other instrument the zone's measuredHz is taken on the trimmed, faded PCM that becomes the FLAC.+const PITCH_MEASURE = { "bell.tubular": bellPitch, timpani: pitchOf };+const REPORT_ONLY_PITCH = new Set(["timpani", "bell.tubular"]); // inharmonic strikes: report, don't fail+const measureZone = (id, pcm, ch) => (PITCH_MEASURE[id] ?? harmonicPitch)(pcm, ch);++// ---------------------------------------------------------------- build+const buildPack = async (srcDir, packDir, recipes) => {+ const index = tree(), files = needed(recipes, index);+ for (const { path } of files) if (!existsSync(local(srcDir, path))) {+ console.error(`missing source file ${path} (run fetch first)`); process.exit(1);+ }+ mkdirSync(packDir, { recursive: true });+ const manifest = { pack: "anidoodle-sounds", version: 1, sampleRate: SR, instruments: {} };+ const licenses = ["# Licenses", "", "All recordings from the Versilian Community Sample Library (VCSL).", "",+ "Source: https://github.com/sgossner/VCSL", "License: CC0 1.0 Universal (public domain)", ""];+ for (const r of recipes) {+ const mine = files.filter((f) => f.recipe === r && !f.notes);+ const zones = [];+ let wavBytes = 0;+ // (timpani) measure every hit first: a hit is kept only when its estimate is stable AND agrees+ // with its drum's median within 40 cents — a hit that disagrees is a mode mis-lock, not a pitch.+ const keepHz = new Map(); // path -> hz+ if (r.pitchedByMeasurement) {+ const byDrum = new Map();+ for (const { path, z } of mine) {+ const wav = local(srcDir, path), s = ffprobe(wav), p = pitchOf(decode(wav, s.channels), s.channels);+ if (p.stable) { if (!byDrum.has(z.drum)) byDrum.set(z.drum, []); byDrum.get(z.drum).push({ path, hz: p.hz }); }+ else console.log(` skip ${basename(path)}: pitch estimate unstable`);+ }+ for (const [drum, hits] of byDrum) {+ const sorted = hits.map((h) => h.hz).sort((a, b) => a - b), med = sorted[sorted.length >> 1];+ for (const h of hits) {+ if (Math.abs(1200 * Math.log2(h.hz / med)) < 40) keepHz.set(h.path, h.hz);+ else console.log(` skip ${basename(h.path)}: disagrees with ${drum}'s other hits`);+ }+ }+ }+ for (const { path, z } of mine) {+ const wav = local(srcDir, path);+ const s = ffprobe(wav);+ if (s.channels !== 1 && s.channels !== 2) { console.error(`${path}: ${s.channels} channels, the contract allows 1 or 2`); process.exit(1); }+ let midi = z.midi, measuredHz;+ if (r.pitchedByMeasurement) {+ if (!keepHz.has(path)) continue;+ measuredHz = +keepHz.get(path).toFixed(2);+ midi = Math.round(69 + 12 * Math.log2(measuredHz / 440));+ }+ const id = r.pitchedByMeasurement ? z.drum : midiName(z.midi);+ const rel = `${r.id}/${id}_l${z.layer}_rr${z.rr}${z.art ? `_${z.art}` : ""}.flac`;+ const out = join(packDir, ...rel.split("/"));+ mkdirSync(dirname(out), { recursive: true });+ const raw = processZone(wav, s.channels, out);+ // pitch is only measurable where the physics cooperates: the contract's check band is+ // midi 48..84; outside it low fundamentals are weak and top partials decay too fast.+ // Chimes are measured everywhere via the strike-note estimator; timpani comes from keepHz.+ // rel zones are key/damper noise: there is no pitch to measure.+ const wantPitch = !r.pitchedByMeasurement && z.art !== "rel" && (r.pitch === "chime" || (z.midi >= 48 && z.midi <= 84));+ const m = measureFlac(out, wantPitch ? r.id : null);+ if (m.channels !== raw.channels || m.frames !== raw.frames) { console.error(`${rel}: encode/decode mismatch`); process.exit(1); }+ if (measuredHz === undefined && m.pitchHz) measuredHz = +m.pitchHz.toFixed(2);+ if (measuredHz === undefined && wantPitch) console.log(` ${rel}: pitch estimate unstable, measuredHz omitted`);+ zones.push({ file: rel, midi, layer: z.layer, rr: z.rr, ...(z.art && { art: z.art }), frames: m.frames, channels: m.channels,+ peakDb: +m.peakDb.toFixed(2), rmsDb: +m.rmsDb.toFixed(2), ...(measuredHz !== undefined && { measuredHz }),+ sha256: createHash("sha256").update(readFileSync(out)).digest("hex") });+ wavBytes += statSync(wav).size;+ }+ zones.sort((a, b) => a.midi - b.midi || a.layer - b.layer || a.rr - b.rr || (a.art ?? "").localeCompare(b.art ?? ""));+ if (!zones.length) { console.error(`${r.id}: no zones survived (check the recipe and the source)`); process.exit(1); }+ const midis = [...new Set(zones.map((z) => z.midi))].sort((a, b) => a - b);+ let maxShift = 0;+ for (let p = midis[0]; p <= midis[midis.length - 1]; p++) {+ let d = Infinity; for (const q of midis) d = Math.min(d, Math.abs(p - q));+ maxShift = Math.max(maxShift, d);+ }+ // declared range = recorded span widened by the repitch allowance (maxShift on sparse+ // instruments, the default 2 otherwise), clipped to the real instrument's compass+ const widen = r.sparse ? maxShift : 2;+ const range = [Math.max(r.realRange[0], midis[0] - widen), Math.min(r.realRange[1], midis[midis.length - 1] + widen)];+ const inst = { title: r.title, source: "VCSL", license: "CC0-1.0", kind: r.kind, range,+ layers: Math.max(...zones.map((z) => z.layer)), damped: r.damped };+ if (r.normalized) inst.normalized = true;+ if (r.sparse) { inst.sparse = true; inst.maxShift = maxShift; }+ inst.zones = zones;+ manifest.instruments[r.id] = inst;+ const dirs = [r.dir, ...(r.arts ?? []).map((a) => `${a.dir} (${a.art} articulation)`)];+ licenses.push(`## ${r.title} (\`${r.id}\`)`, "", `Folder: ${dirs.map((d) => `\`${d}\``).join(", ")} (${(wavBytes / 1e6).toFixed(1)} MB of source WAV)`, "");+ for (const t of [...new Set(mine.map((f) => f.path))].sort()) licenses.push(`- ${t}`);+ licenses.push("");+ console.log(`${r.id}: ${zones.length} zones, layers ${inst.layers}, range ${midiName(midis[0])}..${midiName(midis.at(-1))}${r.sparse ? `, maxShift ${maxShift}` : ""}`);+ }+ // rooms (amendment b): recorded impulse responses under rooms/, attributed in LICENSES.md+ manifest.rooms = {};+ for (const rm of ROOMS) {+ const wav = join(ROOMS_SRC, ...rm.wav.split("/"));+ if (!existsSync(wav)) { console.error(`missing room source ${wav}`); process.exit(1); }+ const rel = `rooms/${rm.id}.flac`, out = join(packDir, ...rel.split("/"));+ mkdirSync(dirname(out), { recursive: true });+ const raw = processRoom(wav, out);+ const s = ffprobe(out), rt60 = rt60Of(decode(out, s.channels), s.channels);+ manifest.rooms[rm.id] = { title: rm.title, source: "OpenAIR", license: "CC-BY-4.0",+ file: rel, channels: raw.channels, frames: raw.frames, rt60: +rt60.toFixed(3),+ sha256: createHash("sha256").update(readFileSync(out)).digest("hex"), directFrames: DIRECT_FRAMES };+ console.log(`room ${rm.id}: ${(raw.frames / SR).toFixed(2)} s, rt60 ${rt60.toFixed(2)} s`);+ }+ licenses.push("## Rooms (impulse responses)", "",+ "Recorded impulse responses from OpenAIR, the Open Acoustic Impulse Response library,",+ "Audio Lab, University of York: https://www.openair.hosted.york.ac.uk/",+ "License: Creative Commons Attribution 4.0 International (CC BY 4.0).",+ "The B-format (W X Y Z) recordings were decoded to stereo as L = W + Y, R = W - Y.", "");+ for (const rm of ROOMS) licenses.push(`- ${rm.title} (\`rooms/${rm.id}.flac\`): ${rm.page}`);+ licenses.push("");+ writeFileSync(join(packDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");+ writeFileSync(join(packDir, "LICENSES.md"), licenses.join("\n"));+ const kb = Number(execFileSync("du", ["-sk", packDir]).toString().split("\t")[0]);+ console.log(`pack: ${join(packDir, "manifest.json")} + LICENSES.md, ${(kb / 1024).toFixed(1)} MB on disk`);+};++// ---------------------------------------------------------------- verify+const verifyPack = (packDir) => {+ const bad = [];+ const fail = (msg) => bad.push(msg);+ const mPath = join(packDir, "manifest.json");+ if (!existsSync(mPath)) { console.error(`verify: ${mPath} not found`); process.exit(1); }+ let m;+ try { m = JSON.parse(readFileSync(mPath, "utf8")); } catch (e) { fail(`manifest.json does not parse: ${e.message}`); return finish(); }+ if (m.pack !== "anidoodle-sounds") fail(`manifest.pack is ${JSON.stringify(m.pack)}, expected "anidoodle-sounds"`);+ if (m.version !== 1) fail(`manifest.version is ${m.version}, expected 1`);+ if (m.sampleRate !== SR) fail(`manifest.sampleRate is ${m.sampleRate}, expected ${SR}`);+ if (!m.instruments || typeof m.instruments !== "object") fail("manifest.instruments missing");+ const licenses = existsSync(join(packDir, "LICENSES.md")) ? readFileSync(join(packDir, "LICENSES.md"), "utf8") : "";+ if (!licenses) fail("LICENSES.md missing or empty");+ let total = 0;+ for (const [id, inst] of Object.entries(m.instruments ?? {})) {+ for (const f of ["title", "source", "license", "kind", "range", "layers", "damped", "zones"]) if (inst[f] === undefined) fail(`${id}: missing field ${f}`);+ if (inst.kind !== "struck" && inst.kind !== "sustained") fail(`${id}: kind ${JSON.stringify(inst.kind)} is not struck|sustained`);+ if (inst.kind === "sustained") fail(`${id}: version 1 packs are struck only`);+ if (!licenses.includes(`\`${id}\``)) fail(`${id}: not named in LICENSES.md`);+ const zones = inst.zones ?? [];+ const pitchStats = { inBand: 0, within: 0, outOfBand: 0 };+ for (const z of zones) {+ if (z.art !== undefined && z.art !== "sus" && z.art !== "rel") fail(`${z.file}: art ${JSON.stringify(z.art)} is not sus|rel (amendment b)`);+ const f = join(packDir, ...z.file.split("/"));+ if (!existsSync(f)) { fail(`${z.file}: missing`); continue; }+ total += statSync(f).size;+ const sha = createHash("sha256").update(readFileSync(f)).digest("hex");+ if (sha !== z.sha256) fail(`${z.file}: sha256 mismatch (manifest ${z.sha256}, file ${sha})`);+ const s = ffprobe(f);+ if (s.sample_rate !== String(SR)) fail(`${z.file}: sample rate ${s.sample_rate}, expected ${SR}`);+ if (Number(s.bits_per_raw_sample) !== 24) fail(`${z.file}: ${s.bits_per_raw_sample} bits per sample, expected 24`);+ if (s.channels !== z.channels) fail(`${z.file}: ${s.channels} channels, manifest says ${z.channels}`);+ const x = decode(f, s.channels), n = x.length / s.channels;+ if (n !== z.frames) fail(`${z.file}: ${n} frames, manifest says ${z.frames}`);+ let peak = 0;+ for (let i = 0; i < x.length; i++) { const a = Math.abs(x[i]); if (a > peak) peak = a; }+ if (peak >= 1) fail(`${z.file}: clips (peak ${db(peak).toFixed(2)} dBFS)`);+ if (Math.abs(db(peak) - z.peakDb) > 0.05) fail(`${z.file}: peakDb ${z.peakDb} but file measures ${db(peak).toFixed(2)}`);+ const amp = (i) => { let v = 0; for (let c = 0; c < s.channels; c++) { const a = Math.abs(x[i * s.channels + c]); if (a > v) v = a; } return v; };+ const thr = peak * 10 ** (-40 / 20);+ let on = n; for (let i = 0; i < n; i++) if (amp(i) > thr) { on = i; break; }+ if (on > Math.round(0.002 * SR)) fail(`${z.file}: onset at ${(on / SR * 1000).toFixed(1)} ms, contract allows 2 ms`);+ // the zone must sound at its declared pitch. Only midi 48..84 is measurable physics+ // (below it fundamentals are weak, above it partials decay too fast), so the check runs+ // only there: an instrument fails when fewer than 80% of its in-band zones land within+ // 1 semitone of the label. Bells and timpani are inharmonic strikes, reported not failed.+ // rel zones are key/damper noise (amendment b): no pitch to check - hash, format and+ // clipping were already verified above, and the note-decay tail rules never applied.+ if (z.art === "rel") continue;+ if (z.midi < 48 || z.midi > 84) { pitchStats.outOfBand++; }+ else {+ pitchStats.inBand++;+ const p = measureZone(id, x, s.channels);+ if (!p.stable) console.log(` ${z.file}: pitch estimate unstable (counts as off)`);+ else {+ const cents = 1200 * Math.log2(p.hz / hzOf(z.midi));+ if (Math.abs(cents) <= 100) pitchStats.within++;+ else {+ const msg = `${z.file}: measured ${p.hz.toFixed(1)} Hz, ${cents.toFixed(0)} cents from declared ${midiName(z.midi)}`;+ if (REPORT_ONLY_PITCH.has(id)) { console.log(` ${msg} (reported, not failed)`); pitchStats.within++; }+ else console.log(` ${msg}`);+ }+ }+ }+ }+ if (pitchStats.outOfBand) console.log(` ${id}: ${pitchStats.outOfBand} zones not measured (outside 48-84)`);+ if (pitchStats.inBand) {+ const frac = pitchStats.within / pitchStats.inBand;+ const line = ` ${id}: ${pitchStats.within}/${pitchStats.inBand} in-band zones within 1 semitone of label`;+ if (frac < 0.8 && !REPORT_ONLY_PITCH.has(id)) fail(`${id}: only ${pitchStats.within}/${pitchStats.inBand} in-band zones within 1 semitone of label (contract requires 80%)`);+ else console.log(line + (REPORT_ONLY_PITCH.has(id) ? " (reported, not failed)" : ""));+ }+ for (const z of zones) {+ if (z.midi < inst.range[0] || z.midi > inst.range[1]) fail(`${z.file}: midi ${z.midi} outside declared range [${inst.range}]`);+ if (z.layer < 1 || z.layer > inst.layers) fail(`${z.file}: layer ${z.layer} outside 1..${inst.layers}`);+ if (z.rr < 1) fail(`${z.file}: rr ${z.rr} below 1`);+ }+ const midis = [...new Set(zones.map((z) => z.midi))].sort((a, b) => a - b);+ let widest = 0;+ for (let i = 1; i < midis.length; i++) widest = Math.max(widest, midis[i] - midis[i - 1]);+ if (inst.sparse) console.log(` ${id}: sparse source, widest gap ${widest} semitones, maxShift ${inst.maxShift} (reported, not failed)`);+ else if (widest > 4) fail(`${id}: widest pitch gap ${widest} semitones exceeds the density target (a zone may be repitched at most 2, so gaps of 4 still cover; 3 at the range ends)`);+ }+ for (const [rid, room] of Object.entries(m.rooms ?? {})) {+ for (const f of ["title", "source", "license", "file", "channels", "frames", "rt60", "sha256", "directFrames"]) if (room[f] === undefined) fail(`rooms.${rid}: missing field ${f}`);+ if (room.license !== "CC-BY-4.0") fail(`rooms.${rid}: license ${JSON.stringify(room.license)}, the pack ships CC BY 4.0 rooms only`);+ if (!licenses.includes(room.title)) fail(`rooms.${rid}: ${room.title} not attributed in LICENSES.md`);+ const f = join(packDir, ...room.file.split("/"));+ if (!existsSync(f)) { fail(`${room.file}: missing`); continue; }+ total += statSync(f).size;+ const sha = createHash("sha256").update(readFileSync(f)).digest("hex");+ if (sha !== room.sha256) fail(`${room.file}: sha256 mismatch`);+ const s = ffprobe(f);+ if (s.sample_rate !== String(SR)) fail(`${room.file}: sample rate ${s.sample_rate}, expected ${SR}`);+ if (Number(s.bits_per_raw_sample) !== 24) fail(`${room.file}: ${s.bits_per_raw_sample} bits, expected 24`);+ if (s.channels !== room.channels) fail(`${room.file}: ${s.channels} channels, manifest says ${room.channels}`);+ const x = decode(f, s.channels), n = x.length / s.channels;+ if (n !== room.frames) fail(`${room.file}: ${n} frames, manifest says ${room.frames}`);+ let peak = 0, energy = 0;+ for (let i = 0; i < x.length; i++) { const a = Math.abs(x[i]); if (a > peak) peak = a; energy += x[i] * x[i]; }+ if (peak >= 1) fail(`${room.file}: clips (peak ${db(peak).toFixed(2)} dBFS)`);+ if (Math.abs(energy - 1) > 0.01) fail(`${room.file}: energy ${energy.toFixed(4)}, contract wants unit energy`);+ // the direct arrival must sit at frame 0: the first sample above -40 dB of the peak is the+ // spike itself, within a couple of frames of the file start+ const thr = peak * 10 ** (-40 / 20);+ let on = n;+ for (let i = 0; i < n; i++) { let v = 0; for (let c = 0; c < s.channels; c++) v = Math.max(v, Math.abs(x[i * s.channels + c])); if (v > thr) { on = i; break; } }+ if (on > 8) fail(`${room.file}: direct sound starts at frame ${on}, contract wants frame 0`);+ if (!(room.rt60 > 0 && room.rt60 < 30)) fail(`rooms.${rid}: rt60 ${room.rt60} implausible`);+ console.log(` room ${rid}: ${(n / SR).toFixed(2)} s, rt60 ${room.rt60} s`);+ }+ console.log(` total: ${(total / 1e6).toFixed(1)} MB of FLAC (no size budget since amendment c: sound comes before size)`);+ return finish();+ function finish() {+ if (bad.length) { for (const b of bad) console.error(`FAIL ${b}`); console.error(`verify: ${bad.length} failure${bad.length > 1 ? "s" : ""}`); process.exit(1); }+ console.log("verify: all contract checks pass");+ }+};++// ---------------------------------------------------------------- report+const reportText = (packDir) => {+ const m = JSON.parse(readFileSync(join(packDir, "manifest.json"), "utf8"));+ const rows = [];+ let total = 0;+ for (const [id, inst] of Object.entries(m.instruments)) {+ const midis = [...new Set(inst.zones.map((z) => z.midi))].sort((a, b) => a - b);+ let widest = 0;+ for (let i = 1; i < midis.length; i++) widest = Math.max(widest, midis[i] - midis[i - 1]);+ let bytes = 0;+ for (const z of inst.zones) bytes += statSync(join(packDir, ...z.file.split("/"))).size;+ total += bytes;+ const arts = {};+ for (const z of inst.zones) if (z.art) arts[z.art] = (arts[z.art] ?? 0) + 1;+ rows.push({ id, zones: inst.zones.length, layers: inst.layers, gap: widest, mb: bytes / 1e6,+ range: `${midiName(inst.range[0])}..${midiName(inst.range[1])}`, sparse: !!inst.sparse,+ arts: Object.entries(arts).map(([a, c]) => `+${c} ${a}`).join(" ") });+ }+ console.log(`${"instrument".padEnd(16)} ${"zones".padStart(5)} ${"layers".padStart(6)} ${"widest gap".padStart(12)} ${"range".padEnd(9)} ${"MB".padStart(7)} arts`);+ for (const r of rows) console.log(`${r.id.padEnd(16)} ${String(r.zones).padStart(5)} ${String(r.layers).padStart(6)} ${(String(r.gap) + (r.sparse ? " (sparse)" : "")).padStart(12)} ${r.range.padEnd(9)} ${r.mb.toFixed(1).padStart(7)} ${r.arts}`);+ if (m.rooms && Object.keys(m.rooms).length) {+ console.log(`\nrooms:`);+ console.log(`${"id".padEnd(14)} ${"rt60 s".padStart(7)} ${"len s".padStart(7)} ${"MB".padStart(7)} title`);+ for (const [rid, room] of Object.entries(m.rooms)) {+ const mb = statSync(join(packDir, ...room.file.split("/"))).size / 1e6;+ total += statSync(join(packDir, ...room.file.split("/"))).size;+ console.log(`${rid.padEnd(14)} ${room.rt60.toFixed(2).padStart(7)} ${(room.frames / m.sampleRate).toFixed(2).padStart(7)} ${mb.toFixed(1).padStart(7)} ${room.title}`);+ }+ }+ console.log(`${"total".padEnd(16)} ${"".padStart(5)} ${"".padStart(6)} ${"".padStart(12)} ${"".padEnd(9)} ${(total / 1e6).toFixed(1).padStart(7)} (no budget since amendment c)`);+ // zone lengths per instrument and articulation (amendments b and c)+ const median = (a) => { const s = [...a].sort((x, y) => x - y); return s[s.length >> 1]; };+ for (const [id, inst] of Object.entries(m.instruments)) {+ const byArt = new Map();+ for (const z of inst.zones) { const k = z.art ?? "note"; if (!byArt.has(k)) byArt.set(k, []); byArt.get(k).push(z.frames / m.sampleRate); }+ const parts = [...byArt.entries()].map(([a, d]) => `${a} ${d.length} (median ${median(d).toFixed(2)} s, max ${Math.max(...d).toFixed(2)} s)`);+ console.log(`${id}: ${parts.join(", ")}`);+ }+ console.log();+ // declared midi vs the pitch measured on the written zone at build time, per instrument+ console.log(`\npitch check (declared midi vs measuredHz):`);+ console.log(`${"instrument".padEnd(16)} ${"zones".padStart(5)} ${"measured".padStart(9)} ${"med |c|".padStart(9)} ${"worst c".padStart(8)} worst zone`);+ for (const [id, inst] of Object.entries(m.instruments)) {+ const deltas = inst.zones.filter((z) => z.measuredHz).map((z) => ({ c: 1200 * Math.log2(z.measuredHz / hzOf(z.midi)), f: basename(z.file) }));+ if (!deltas.length) { console.log(`${id.padEnd(16)} ${String(inst.zones.length).padStart(5)} ${"0".padStart(9)}`); continue; }+ const abs = deltas.map((d) => Math.abs(d.c)).sort((a, b) => a - b), worst = deltas.reduce((a, b) => Math.abs(b.c) > Math.abs(a.c) ? b : a);+ console.log(`${id.padEnd(16)} ${String(inst.zones.length).padStart(5)} ${String(deltas.length).padStart(9)} ${abs[abs.length >> 1].toFixed(1).padStart(9)} ${worst.c.toFixed(1).padStart(8)} ${worst.f}`);+ }+ for (const [id, inst] of Object.entries(m.instruments).filter(([i]) => i === "timpani" || i === "bell.tubular")) {+ console.log(`\n${id}: measured pitch per zone`);+ console.log(`${"file".padEnd(26)} ${"Hz".padStart(9)} ${"note".padStart(5)} ${"cents".padStart(7)}`);+ for (const z of inst.zones) {+ if (!z.measuredHz) continue;+ const cents = 1200 * Math.log2(z.measuredHz / hzOf(z.midi));+ console.log(`${basename(z.file).padEnd(26)} ${z.measuredHz.toFixed(2).padStart(9)} ${midiName(z.midi).padStart(5)} ${((cents >= 0 ? "+" : "") + cents.toFixed(1)).padStart(7)}`);+ }+ }+};++// ---------------------------------------------------------------- dist+// Ship track: a built pack -> the release artifacts tools/soundfetch.mjs installs. ONE+// uncompressed tar per instrument plus one for the rooms (FLAC is already compressed), each+// carrying its files under their pack-relative paths plus a manifest.json fragment and+// LICENSES.md, so an unpacked archive is a valid partial pack on its own. Beside them sits+// anidoodle-sounds-v1.json: per archive the file name, bytes, sha256, the instrument ids (and+// room ids) it holds and the manifest fragment for those ids, plus the LICENSES.md text.+// Reproducible: ustar, entries sorted by name, uid/gid 0, no names, mode 0644, mtime 0 -+// running dist twice on the same pack gives byte-identical archives.+const TAR_ZERO = Buffer.alloc(1024);+const tarName = (h, at, len, s) => h.write(s, at, Math.min(Buffer.byteLength(s), len - 1), "utf8");+export const tarHeader = (name, size) => {+ // POSIX ustar: 100-byte name, 155-byte prefix for longer paths (prefix/name <= 255 total)+ let prefix = "", nm = name;+ if (Buffer.byteLength(nm) > 100) {+ const parts = nm.split("/");+ while (parts.length > 1 && Buffer.byteLength(nm) > 100) { prefix = prefix ? `${prefix}/${parts.shift()}` : parts.shift(); nm = parts.join("/"); }+ if (Buffer.byteLength(nm) > 100 || Buffer.byteLength(prefix) > 155) throw new Error(`tar: path too long for ustar: ${name}`);+ }+ const h = Buffer.alloc(512);+ tarName(h, 0, 100, nm);+ h.write("0000644\0", 100); // mode+ h.write("0000000\0", 108); // uid+ h.write("0000000\0", 116); // gid+ h.write(size.toString(8).padStart(11, "0") + "\0", 124); // size+ h.write("00000000000\0", 136); // mtime 0+ h.write(" ", 148); // checksum computed over spaces+ h.write("0", 156); // regular file+ h.write("ustar\0", 257); h.write("00", 263); // magic + version+ tarName(h, 345, 155, prefix);+ let sum = 0;+ for (const b of h) sum += b;+ h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148);+ return h;+};+export const writeTar = (out, entries) => {+ const fd = openSync(out, "w");+ try {+ for (const e of entries) {+ const data = e.data ?? readFileSync(e.path);+ writeSync(fd, tarHeader(e.name, data.length));+ writeSync(fd, data);+ const pad = (512 - (data.length % 512)) % 512;+ if (pad) writeSync(fd, TAR_ZERO, 0, pad);+ }+ writeSync(fd, TAR_ZERO);+ } finally {+ closeSync(fd);+ }+};+const RELEASE = "anidoodle-sounds-v1";+const distPack = (packDir, distDir) => {+ const m = JSON.parse(readFileSync(join(packDir, "manifest.json"), "utf8"));+ if (m.pack !== "anidoodle-sounds" || m.version !== 1 || !m.instruments || typeof m.instruments !== "object") {+ console.error("dist: not a version 1 anidoodle pack (run verify first)"); process.exit(1);+ }+ const licenses = readFileSync(join(packDir, "LICENSES.md"), "utf8");+ mkdirSync(distDir, { recursive: true });+ const top = { pack: m.pack, version: m.version, sampleRate: m.sampleRate };+ const archives = [];+ const emit = (id, files, fragment) => {+ const entries = [+ ...files.map((rel) => ({ name: rel, path: join(packDir, ...rel.split("/")) })),+ { name: "manifest.json", data: Buffer.from(JSON.stringify(fragment, null, 2) + "\n") },+ { name: "LICENSES.md", data: Buffer.from(licenses) },+ ].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));+ for (const e of entries) if (e.path && !existsSync(e.path)) { console.error(`dist: manifest names ${e.name}, the file is missing`); process.exit(1); }+ const file = `${RELEASE}-${id}.tar`, out = join(distDir, file);+ writeTar(out, entries);+ const bytes = statSync(out).size;+ archives.push({ file, bytes, sha256: createHash("sha256").update(readFileSync(out)).digest("hex"),+ instruments: Object.keys(fragment.instruments ?? {}), rooms: Object.keys(fragment.rooms ?? {}), manifest: fragment });+ const a = archives.at(-1);+ console.log(`${file.padEnd(44)} ${(bytes / 1e6).toFixed(1).padStart(8)} MB ${a.instruments.concat(a.rooms.map((r) => `room ${r}`)).join(", ")}`);+ };+ for (const id of Object.keys(m.instruments).sort())+ emit(id, m.instruments[id].zones.map((z) => z.file), { ...top, instruments: { [id]: m.instruments[id] } });+ if (Object.keys(m.rooms ?? {}).length)+ emit("rooms", Object.values(m.rooms).map((r) => r.file), { ...top, rooms: m.rooms });+ const index = { release: RELEASE, ...top, licenses, archives };+ writeFileSync(join(distDir, `${RELEASE}.json`), JSON.stringify(index, null, 2) + "\n");+ const total = archives.reduce((s, a) => s + a.bytes, 0);+ console.log(`${`${RELEASE}.json`.padEnd(44)} ${"".padStart(8)} ${archives.length} archives, ${(total / 1e6).toFixed(1)} MB total`);+};++// ---------------------------------------------------------------- main+const [cmd, ...args] = process.argv.slice(2);+const onlyFlag = args.indexOf("--only");+const only = onlyFlag >= 0 ? args.splice(onlyFlag, 2)[1].split(",") : null;+const recipes = only ? RECIPES.filter((r) => only.includes(r.id)) : RECIPES;+if (only && recipes.length !== only.length) { console.error(`unknown instrument in --only: ${only.filter((o) => !RECIPES.some((r) => r.id === o))}`); process.exit(2); }++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) (async () => {+ if (cmd === "fetch" && args.length === 1) await fetchFiles(needed(recipes, tree()), args[0]);+ else if (cmd === "build" && args.length === 2) await buildPack(args[0], args[1], recipes);+ else if (cmd === "verify" && args.length === 1) verifyPack(args[0]);+ else if (cmd === "report" && args.length === 1) reportText(args[0]);+ else if (cmd === "dist" && args.length === 2) distPack(args[0], args[1]);+ else { console.error("usage: node tools/soundpack.mjs fetch <source-dir> [--only ...] | build <source-dir> <pack-dir> [--only ...] | verify <pack-dir> | report <pack-dir> | dist <pack-dir> <dist-dir>"); process.exit(2); }+})().catch((e) => { console.error(e); process.exit(1); });diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/sounds-unit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/sounds-unit.mjsnew file mode 100644index 0000000..d8d9c28--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/sounds-unit.mjs@@ -0,0 +1,113 @@+#!/usr/bin/env node+// Loader regression: ffprobe can close stdin early on a large FLAC. No real pack required.+// node tools/sounds-unit.mjs <durable-test-dir>+import { build } from "esbuild";+import { strict as assert } from "node:assert";+import { execFileSync, spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { mkdirSync, readFileSync, writeFileSync, symlinkSync, chmodSync, existsSync } from "node:fs";+import { resolve, join } from "node:path";+import { loadBanks } from "./sounds.mjs";++const dir = process.argv[2]; if (!dir) throw new Error("name a durable test directory");+const root = resolve(dir); mkdirSync(root, { recursive: true });+const frames = 48000 * 12, pcm = Buffer.alloc(frames * 8); let seed = 7;+for (let i = 0; i < frames * 2; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; pcm.writeFloatLE(((seed >>> 0) / 4294967296 - 0.5) * 0.5, i * 4); }+const file = join(root, "large.flac");+execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "f32le", "-ar", "48000", "-ac", "2", "-i", "pipe:0", "-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24", file], { input: pcm });+const bytes = readFileSync(file); assert(bytes.length > 2 * 1024 * 1024, "fixture must exceed the stdin pipe buffer by megabytes");+const zone = { file: "large.flac", midi: 60, layer: 1, rr: 1, frames, channels: 2, peakDb: -12, rmsDb: -17, sha256: createHash("sha256").update(bytes).digest("hex") };+const entry = { title: "Synthetic stereo", source: "test", license: "CC0-1.0", kind: "struck", range: [60, 60], layers: 1, normalized: true, damped: false, zones: [zone] };+const manifest = { pack: "anidoodle-sounds", version: 1, sampleRate: 48000, instruments: { piano: entry } };+manifest.rooms = { test: { title: "Synthetic IR", source: "test", license: "CC0-1.0", file: "large.flac", channels: 2, frames, rt60: 0.5, sha256: zone.sha256 } };+writeFileSync(join(root, "manifest.json"), JSON.stringify(manifest));+const js = (await build({ entryPoints: [join(import.meta.dirname, "../src/canvas-core/music/index.ts")], bundle: true, write: false, platform: "neutral", format: "esm" })).outputFiles[0].text;+const M = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));+loadBanks(M, root, ["piano"]);+const bank = M.bankFor("piano"); assert(bank); assert.equal(bank.zones[0].channels.length, 2);+for (const c of bank.zones[0].channels) { assert.equal(c.length, frames); assert(c.every(Number.isFinite)); }+console.log(`PASS large FLAC: ${bytes.length} bytes, ${frames} stereo frames loaded without EPIPE`);+assert.equal(M.roomFor("test").L.length, frames); assert.equal(M.roomFor("test").R.length, frames); assert.equal(M.roomFor("test").sha256, zone.sha256);+M.clearBanks(); M.clearRooms(); loadBanks(M, root, []); assert(M.roomFor("test")); assert.equal(M.bankFor("piano"), undefined);+console.log("PASS rooms load as stereo float even when no sampled instrument is requested");+M.clearRooms(); const originalRoom = { ...manifest.rooms.test };+for (const [field, value, re] of [["sha256", "0".repeat(64), /sha256 mismatch/], ["frames", frames - 1, /frame count mismatch/], ["channels", 1, /expected 48 kHz/], ["file", file, /invalid FLAC path/]]) {+ manifest.rooms.test = { ...originalRoom, [field]: value }; writeFileSync(join(root, "manifest.json"), JSON.stringify(manifest));+ assert.throws(() => loadBanks(M, root, []), re); assert.equal(M.roomFor("test"), undefined);+}+console.log("PASS corrupt room hash, frame count, channels and absolute path rejected before registration");+manifest.rooms = {};+M.clearBanks(); zone.sha256 = "0".repeat(64); writeFileSync(join(root, "manifest.json"), JSON.stringify(manifest));+assert.throws(() => loadBanks(M, root, ["piano"]), /sha256 mismatch/); assert.equal(M.bankFor("piano"), undefined);+console.log("PASS corrupt large FLAC hash: rejected before registration");+let failures = 0;+const check = (label, fn) => { if (process.env.ANIDOODLE_TEST_CASE && !label.includes(process.env.ANIDOODLE_TEST_CASE)) return; try { fn(); console.log(`PASS ${label}`); } catch (e) { failures++; console.error(`FAIL ${label}: ${e.message}`); } };+zone.sha256 = originalRoom.sha256; manifest.rooms = {}; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest));+check('inherited constructor never becomes a sample-bank lookup', () => {+ M.clearBanks(); loadBanks(M, root, ['constructor']); assert.equal(M.bankFor('constructor'), undefined);+});+check('symlink outside the pack is rejected before decode', () => {+ const outside = join(root, '..', 'outside-loader.flac'); writeFileSync(outside, bytes);+ const linked = join(root, 'escaped.flac'); symlinkSync(outside, linked);+ zone.file = 'escaped.flac'; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest));+ try { assert.throws(() => loadBanks(M, root, ['piano']), /zone escapes pack/); } finally { zone.file = 'large.flac'; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest)); }+});+check('forced FLAC demuxers decode the exact hashed bytes even after the path changes', () => {+ const wrappers = join(root, 'decoder-wrappers'); mkdirSync(wrappers, { recursive: true });+ const oldPath = process.env.PATH;+ for (const command of ['ffprobe', 'ffmpeg']) {+ const real = execFileSync('which', [command], { encoding: 'utf8' }).trim();+ const shim = `#!/usr/bin/env node\nimport {readFileSync,writeFileSync} from 'node:fs';\nimport {execFileSync} from 'node:child_process';\nimport {createHash} from 'node:crypto';\nconst args=process.argv.slice(2), input=readFileSync(0);\nif(args[args.indexOf('-f')+1]!=='flac'||!args.includes('pipe:0'))throw Error('decoder must force FLAC on stdin');\nif(createHash('sha256').update(input).digest('hex')!==${JSON.stringify(zone.sha256)})throw Error('decoder did not receive hashed bytes');\n${command === 'ffprobe' ? `writeFileSync(${JSON.stringify(file)},'#EXTM3U\\nhttps://invalid.example/external.flac\\n');` : ''}\nprocess.stdout.write(execFileSync(${JSON.stringify(real)},args,{input,maxBuffer:1<<28}));\n`;+ const path = join(wrappers, command); writeFileSync(path, shim); chmodSync(path, 0o755);+ }+ try { process.env.PATH = wrappers + ':' + oldPath; M.clearBanks(); loadBanks(M, root, ['piano']); assert.equal(M.bankFor('piano').zones[0].channels[0].length, frames); }+ finally { process.env.PATH = oldPath; writeFileSync(file, bytes); }+});+check('a wedged decoder is killed and retried', () => {+ const wrappers = join(root, 'wedge-wrappers'), marker = join(root, 'wedged-once'); mkdirSync(wrappers, { recursive: true });+ const oldPath = process.env.PATH, real = execFileSync('which', ['ffmpeg'], { encoding: 'utf8' }).trim();+ writeFileSync(join(wrappers, 'ffmpeg'), `#!/usr/bin/env node\nimport {readFileSync,writeFileSync,existsSync} from 'node:fs';\nimport {execFileSync} from 'node:child_process';\nconst input=readFileSync(0);\nif(!existsSync(${JSON.stringify(marker)})){writeFileSync(${JSON.stringify(marker)},'x');setInterval(()=>{},1000);}\nelse process.stdout.write(execFileSync(${JSON.stringify(real)},process.argv.slice(2),{input,maxBuffer:1<<28}));\n`); chmodSync(join(wrappers, 'ffmpeg'), 0o755);+ try { process.env.PATH = wrappers + ':' + oldPath; process.env.ANIDOODLE_DECODE_TIMEOUT_MS = '3000'; M.clearBanks(); loadBanks(M, root, ['piano']); assert.equal(M.bankFor('piano').zones[0].channels[0].length, frames); assert.ok(existsSync(marker)); }+ finally { process.env.PATH = oldPath; delete process.env.ANIDOODLE_DECODE_TIMEOUT_MS; }+});+check('room directFrames is loaded and participates in reload identity', () => {+ manifest.rooms = { test: { ...originalRoom, directFrames: 120 } }; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest));+ M.clearRooms(); loadBanks(M, root, []); assert.equal(M.roomFor('test').directFrames, 120);+ manifest.rooms.test.directFrames = 121; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest));+ loadBanks(M, root, []); assert.equal(M.roomFor('test').directFrames, 121);+});+const isolatedHome = join(root, 'default-home'), install = join(isolatedHome, '.anidoodle', 'sounds'); mkdirSync(install, { recursive: true });+writeFileSync(join(install, 'large.flac'), bytes);+writeFileSync(join(install, 'manifest.json'), JSON.stringify({ ...manifest, rooms: {}, instruments: { piano: { ...entry, range: [21, 108] } } }));+const preload = join(root, 'home.cjs');+writeFileSync(preload, "require('node:os').homedir=()=>process.env.ANIDOODLE_TEST_HOME; require('node:module').syncBuiltinESMExports();");+const env = { ...process.env, ANIDOODLE_TEST_HOME: isolatedHome }; delete env.ANIDOODLE_SOUNDS;+check('music CLI discovers a default install with env and --sounds unset', () => {+ const result = spawnSync(process.execPath, ['--require', preload, 'tools/music.mjs', 'check', 'nocturne', '--seconds', '1'], { env: { ...env, ANIDOODLE_THREADS: '1' }, encoding: 'utf8', maxBuffer: 1<<24 });+ assert.notEqual(result.status, null, result.stderr); assert.match(result.stdout, /calibration piano:/);+});+check('film audio discovers and plays a default install with env unset', () => {+ const script = join(root, 'default-film.mjs');+ const audioUrl = new URL('./audio.mjs', import.meta.url).href;+ writeFileSync(script, `import assert from 'node:assert/strict'; import {prepareFilmSounds,filmFloat32} from ${JSON.stringify(audioUrl)}; const M=await import(${JSON.stringify('data:text/javascript;base64,'+Buffer.from(js).toString('base64'))}); const film={audio:M.filmAudio(M.nocturne(),1)}; assert.equal(prepareFilmSounds(film,M),true); assert.equal(filmFloat32(film).frames,48000); console.log('DEFAULT FILM RECORDINGS PASS');`);+ const out = execFileSync(process.execPath, ['--require', preload, script], { env, encoding: 'utf8', maxBuffer: 1<<24 });+ assert.match(out, /DEFAULT FILM RECORDINGS PASS/);+});+check('Windows decoder selection uses absolute PATH binaries, not implicit current-directory lookup', () => {+ const windowsPath = join(root, 'windows-path'); mkdirSync(windowsPath, { recursive: true });+ const marker = join(root, 'windows-decoder-marker');+ for (const command of ['ffprobe', 'ffmpeg']) {+ const real = execFileSync('which', [command], { encoding: 'utf8' }).trim();+ const shim = join(windowsPath, command + '.mjs');+ writeFileSync(shim, `import {readFileSync,writeFileSync} from 'node:fs'; import {execFileSync} from 'node:child_process'; writeFileSync(${JSON.stringify(marker)},'PATH binary'); process.stdout.write(execFileSync(${JSON.stringify(real)},process.argv.slice(2),{input:readFileSync(0),maxBuffer:1<<28}));`);+ const quote = s => "'" + s.replaceAll("'", "'\"'\"'") + "'";+ writeFileSync(join(windowsPath, command + '.exe'), `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(shim)} \"$@\"\n`);+ chmodSync(join(windowsPath, command + '.exe'), 0o755);+ }+ const script = join(root, 'windows-loader.mjs');+ writeFileSync(script, `import {loadBanks} from ${JSON.stringify(new URL('./sounds.mjs', import.meta.url).href)}; const M=await import(${JSON.stringify('data:text/javascript;base64,'+Buffer.from(js).toString('base64'))}); Object.defineProperty(process,'platform',{value:'win32'}); loadBanks(M,${JSON.stringify(root)},['piano']);`);+ execFileSync(process.execPath, [script], { env: { ...process.env, PATH: windowsPath, PATHEXT: '.exe' }, maxBuffer: 1<<24 });+ assert.equal(readFileSync(marker, 'utf8'), 'PATH binary');+});+if (failures) process.exitCode = 1;+else console.log('SOUNDS LOADER REVIEW PASS');diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/sounds.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/sounds.mjsnew file mode 100644index 0000000..9d5d9b5--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/sounds.mjs@@ -0,0 +1,80 @@+// Host-side sound packs: verify the pinned FLAC bytes, decode once, then hand PCM to the engine.+import { readFileSync, realpathSync, existsSync } from "node:fs";+import { resolve, sep, isAbsolute } from "node:path";+import { createHash } from "node:crypto";+import { execFileSync } from "node:child_process";++export const soundIds = (piece) => piece.legacy ? [] : [...new Set(piece.parts.filter((p) => p.notes.length && p.opts?.sampled !== false).map((p) => typeof p.opts?.variant === "string" && p.opts.variant ? `${p.inst}.${p.opts.variant}` : p.inst))];+// Windows otherwise searches the current directory before PATH.+const decoderPath = (command) => {+ if (process.platform !== "win32") return command;+ const suffixes = (process.env.PATHEXT || ".EXE").split(";");+ for (const dir of (process.env.PATH || "").split(";")) {+ if (!isAbsolute(dir)) continue;+ for (const suffix of suffixes) {+ const file = resolve(dir, command + suffix);+ if (existsSync(file)) return file;+ }+ }+ throw new Error(`${command}: executable missing from absolute PATH directories`);+};+// A piped child can wedge at 0% CPU with its input half read (seen live on macOS, from a worker).+// Decoding is deterministic, so kill it after a minute and try again rather than hang the render.+const runDecoder = (command, args, opts, what) => {+ for (let attempt = 1; ; attempt++) {+ try { return execFileSync(decoderPath(command), args, { timeout: Number(process.env.ANIDOODLE_DECODE_TIMEOUT_MS) || 60000, killSignal: "SIGKILL", ...opts }); }+ catch (e) {+ if (e.code !== "ETIMEDOUT") throw e;+ if (attempt === 3) throw new Error(`${command} timed out three times on ${what}`);+ }+ }+};+const decodeFlac = (root, id, zone) => {+ if (typeof zone.file !== "string" || isAbsolute(zone.file) || !zone.file.endsWith(".flac")) throw new Error(`${id}: invalid FLAC path`);+ const file = realpathSync(resolve(root, zone.file)); if (!file.startsWith(root + sep)) throw new Error(`${id}: zone escapes pack: ${zone.file}`);+ const bytes = readFileSync(file), sha = createHash("sha256").update(bytes).digest("hex");+ if (typeof zone.sha256 !== "string" || sha !== zone.sha256.toLowerCase()) throw new Error(`${id}: sha256 mismatch: ${zone.file}`);+ // Count frames so ffprobe consumes the complete verified buffer rather than closing stdin early.+ const info = JSON.parse(runDecoder("ffprobe", ["-v", "error", "-f", "flac", "-i", "pipe:0", "-count_frames", "-show_streams", "-of", "json"], { input: bytes, encoding: "utf8", maxBuffer: 1 << 20 }, zone.file)).streams;+ if (info.length !== 1 || info[0].codec_name !== "flac" || Number(info[0].sample_rate) !== 48000 || Number(info[0].bits_per_raw_sample) !== 24 || info[0].channels !== zone.channels || ![1, 2].includes(zone.channels)) throw new Error(`${id}: expected 48 kHz 24-bit FLAC with ${zone.channels} channels: ${zone.file}`);+ const pcm = runDecoder("ffmpeg", ["-v", "error", "-f", "flac", "-i", "pipe:0", "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ar", "48000", "pipe:1"], { input: bytes, maxBuffer: 1 << 28 }, zone.file);+ if (!Number.isInteger(zone.frames) || zone.frames < 1 || pcm.length !== zone.frames * zone.channels * 4) throw new Error(`${id}: frame count mismatch: ${zone.file}`);+ const channels = Array.from({ length: zone.channels }, () => new Float32Array(zone.frames));+ for (let i = 0; i < zone.frames; i++) for (let c = 0; c < zone.channels; c++) { const v = pcm.readFloatLE((i * zone.channels + c) * 4); if (!Number.isFinite(v)) throw new Error(`${id}: non-finite PCM: ${zone.file}`); channels[c][i] = v; }+ return channels;+};+export const loadBanks = (M, dir, ids) => {+ if (!dir) return;+ const root = realpathSync(dir), manifest = JSON.parse(readFileSync(resolve(root, "manifest.json"), "utf8"));+ if (manifest.pack !== "anidoodle-sounds" || manifest.version !== 1 || manifest.sampleRate !== 48000 || !manifest.instruments || typeof manifest.instruments !== "object" || Array.isArray(manifest.instruments)) throw new Error(`invalid sound pack manifest: ${dir}`);+ for (const id of ids) {+ if (!Object.hasOwn(manifest.instruments, id)) continue;+ const entry = manifest.instruments[id]; if (!entry) continue;+ const [inst, ...variant] = id.split("."); if (M.bankFor(inst, variant.join(".") || undefined)) continue;+ if (!Array.isArray(entry.zones) || !entry.zones.length) throw new Error(`${id}: empty sample bank`);+ // Validate the playable metadata before starting ffmpeg, including future sustained zones.+ if (entry.kind === "sustained") throw new Error(`${id}: ${entry.zones.some((z) => !z.loop) ? "sustained zone without a loop" : "sustained banks are not supported in pack version 1"}`);+ const zones = entry.zones.map((zone) => ({ zone, channels: decodeFlac(root, id, zone) }));+ M.registerBank(id, { entry, zones });+ const calibrated = M.calibrateBank(id);+ console.log(`spectrum ${id}: zone | 500 Hz-4 kHz fraction dB | excess over modeled dB`);+ for (const t of calibrated.trim) console.log(` ${t.file} | ${t.bandFractionDb.toFixed(2)} | ${t.bandExcessDb.toFixed(2)}`);+ console.log(`calibration ${id}: median trim ${calibrated.trim[0].medianDb.toFixed(2)} dB; zone | layer | measured dB | modeled dB | requested dB | applied dB | deviation dB`);+ for (const t of calibrated.trim) console.log(` ${t.file} | ${t.layer} | ${t.measuredDb.toFixed(2)} | ${t.modeledDb.toFixed(2)} | ${t.requestedDb.toFixed(2)} | ${t.correctionDb.toFixed(2)} | ${(t.correctionDb - t.medianDb).toFixed(2)}${Math.abs(t.correctionDb) > 9 ? " | FLAG applied >9 dB (includes instrument trim)" : ""}${Math.abs(t.requestedDb - t.medianDb) > 9 ? " | FLAG >9 dB deviation: capped, inspect zone/reference" : ""}${t.boostLimited ? " | prefer louder layer" : ""}`);+ }+ if (manifest.rooms !== undefined && (!manifest.rooms || typeof manifest.rooms !== "object" || Array.isArray(manifest.rooms))) throw new Error("invalid sound pack rooms");+ for (const [id, entry] of Object.entries(manifest.rooms ?? {})) {+ if (M.roomFor(id)?.sha256 === entry.sha256?.toLowerCase() && M.roomFor(id)?.rt60 === entry.rt60 && M.roomFor(id)?.L.length === entry.frames && (M.roomFor(id)?.directFrames ?? 0) === (entry.directFrames ?? 0)) continue;+ const channels = decodeFlac(root, `room ${id}`, entry);+ M.registerRoom(id, { L: channels[0], R: channels[entry.channels - 1], rt60: entry.rt60, sha256: entry.sha256, directFrames: entry.directFrames });+ }+};+export const printSounds = (M, piece) => {+ const recorded = [], modeled = [];+ for (const p of piece.parts) {+ const b = !piece.legacy && p.opts?.sampled !== false && M.bankFor(p.inst, typeof p.opts?.variant === "string" ? p.opts.variant : undefined);+ (b ? recorded : modeled).push(`${p.id} (${b ? b.id + (b.entry.sparse ? `, sparse, max shift ${b.entry.maxShift} semitones` : "") : p.inst})`);+ }+ console.log(`voices recordings: ${recorded.join(", ") || "none"}; modeled: ${modeled.join(", ") || "none"}`);+};+export const codeBuiltNotice = () => console.log('audio: using code-built instruments; run node tools/soundfetch.mjs get all to install recordings, or set ANIDOODLE_SOUNDS=<pack-dir>');diff --git a/plugins/anidoodle/skills/anidoodle/references/determinism-and-contract.md b/plugins/anidoodle/skills/anidoodle/references/determinism-and-contract.mdindex edca569..ed0c934 100644--- a/plugins/anidoodle/skills/anidoodle/references/determinism-and-contract.md+++ b/plugins/anidoodle/skills/anidoodle/references/determinism-and-contract.md@@ -10,7 +10,7 @@1. `renderFrame(frame, env)` is PURE. No state carried between frames, no module-level mutable state that touches pixels. Audio is the same: samples are a pure function of the sample rate.2. Randomness only from `rng(seed)`. Never `Math.random`. Never `Date`, never `performance.now` in the core; timing belongs to hosts.3. A restricted canvas: paths, fill, stroke, clip, transforms, alpha, composite operations, patterns, gradients, `drawImage`, image data, `fillText` with a preloaded font. **No `ctx.filter` in any form.** No DOM, no `window`, no `new OffscreenCanvas` or `new Image`; surfaces come from `env.canvas()`.-4. **No assets.** No images, no fonts from the network, no audio samples. Lettering is pen strokes; texture is seeded noise; music is arithmetic. This is what makes the repo the whole film, with no licensing questions.+4. **No assets.** No images, no fonts, no audio files in the repository. Lettering is pen strokes; texture is seeded noise; music is arithmetic. This is what makes the repo the whole film, with no licensing questions. The optional sound pack is the one thing fetched from outside, it is installed by hash, and a film renders without it.5. Caches are legal only when the value is a pure function of its key, and **the key names everything the pixels depend on**. We found two violations by machine, never by eye: an annotation layer whose key omitted the crank angle two of its leaders pointed at, and one that omitted the pose. A cached frame and a cold frame of the same number must be the same pixels.6. Never scale a bitmap up. Close shots are re-inked at that view; cached surfaces may only be downscaled, and only a little.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/README.md b/plugins/anidoodle/skills/anidoodle/references/music/README.mdindex fac91ff..c1cbf5b 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/README.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/README.md@@ -1,11 +1,16 @@-# Music: composed as data, synthesized in code, measured, then heard once+# Music: composed as data, performed, measured, then heard once-Every score in anidoodle is **100 % procedural**: you write the notes as data, the engine performs-and synthesizes them in code. No samples, no recordings, no licensed audio, ever. You cannot hear-what you make, so every choice is a number, every number is measured, and a human hears 8 seconds-before anything ships.+Every score in anidoodle is written as data and every voice is the engine's own: you write the+notes, the engine performs them. You cannot hear what you make, so every choice is a number, every+number is measured, and a human hears 8 seconds before anything ships.-Code: `engine/src/canvas-core/music/`. Tool: `engine/tools/music.mjs`.+Eight acoustic instruments also play **recordings of the real thing**, from an optional sound pack+you install separately: grand and upright piano, concert harp, marimba, vibraphone, glockenspiel,+tubular bells and timpani, plus three recorded rooms. Everything else, and every score on a machine+without the pack, is synthesized in code exactly as before. See+[Recorded instruments](#recorded-instruments-the-optional-sound-pack) below.++Code: `engine/src/canvas-core/music/`. Tools: `engine/tools/music.mjs`, `engine/tools/soundfetch.mjs`.**Start here: [`compose.md`](compose.md).** It takes you from a brief to an original score. A styleis a vocabulary: sound, grooves, harmony language, melody rules, arrangement grammar. It is never@@ -22,6 +27,8 @@ Pages:depth, and the stem balance meter.- [`styles/music-box.md`](styles/music-box.md): the original music-box recipe's sound numbers andthe scar story behind the guards.+- [`sounds-licenses.md`](sounds-licenses.md): where the recordings come from, and the attribution+ CC BY asks for. Required reading before you redistribute a pack.**Demos are not scores.** The pieces in `pieces/` (samplers, families, nocturne, our launch scores)were written to prove the synth and the meters, and one of them is our own film's score. They are@@ -63,7 +70,7 @@ MusicPlan + notes (you write) -> perform -> instruments (one stem per part)- humanize from `rng(seed)`, smoothed so it correlates across a phrase.Parts with `opts.grid` (music box, chiptune, drive) stay mechanical on purpose.-3. **Synthesize.** Each part is an instrument:+3. **Perform the instruments.** Each part is an instrument:| Instrument | How it's made ||---|---|@@ -85,14 +92,21 @@ MusicPlan + notes (you write) -> perform -> instruments (one stem per part)| `leadSynth` | Mono saw + square, portamento, a filter envelope, blooming vibrato || `bowedSolo` | A bowed waveguide string (violin, or `cello: true`): touching notes are one bow with a finger slide, delayed vibrato, measured body |- The acoustic voices are procedural approximations: cinematic and stylized, never "realistic". Every note varies- (seeded), so repeats never clone. A human listens before one carries a film. A shipped score sets- `legacy: true` on its piece to keep the sound it shipped with.+ Eight of these play recordings of real instruments when the sound pack is installed. The table+ below is what the engine builds; [Recorded instruments](#recorded-instruments-the-optional-sound-pack)+ is what it plays instead.++ The modelled voices are approximations: cinematic and stylized, never "realistic". Every note+ varies (seeded), so repeats never clone. A human listens before one carries a film. A shipped+ score sets `legacy: true` on its piece to keep the sound it shipped with, and never reaches the+ sampler at all.4. **Room.** The style chooses it:- music box: one reflection, no tail;- nocturne and lullaby: a small room;- cinematic and drive: a hall;- chiptune: nothing.+ With the pack installed, a style may name a recorded room instead and the engine convolves with+ the recording.5. **Master.**- **Gentle styles:** one static gain to **-16 LUFS**, true peak <= -1 dBTP, never a compressor on the master.Struck stems (plucks, plucked basses, piano, mallets and bells, timpani) first go through a transient-aware@@ -108,6 +122,98 @@ the last frame and is never chopped. Any film mix that renders a score (sound effit it the same way. `engine/src/canvas-core/score.ts` is an empty skeleton: `filmScore(material,fps, frames)` composes your material and fits it.+## Recorded instruments: the optional sound pack++The pack is a separate download (about 390 MB), not part of the skill. Once it is installed, eight+acoustic parts play recordings of real instruments and three rooms are recorded impulse responses.+Without it every score still plays, on the modelled voices, unchanged.++```bash+node tools/soundfetch.mjs list # the install directory and what is installed; no network+node tools/soundfetch.mjs get all # the one command that downloads: hash, unpack, install+node tools/soundfetch.mjs where # the install directory+node tools/soundfetch.mjs verify # re-hash every installed file+node tools/soundfetch.mjs remove <id> # drop one instrument, or `rooms`+```++`get` names the ids it wants, or `all`. It installs to `ANIDOODLE_SOUNDS`, or+`~/.anidoodle/sounds`, and refuses any archive whose size or sha256 disagrees with the index+before it unpacks. `ANIDOODLE_SOUNDS_URL` points the fetch at a different release; point it at a+local directory or a `file://` URL and `list` also prints what is available there, since a local+source is read off disk. Against the GitHub release `list` reads the installed manifest alone and+prints that the index is fetched by `get` only. The engine finds an installed pack on its own; to+render from a pack directory without installing it, pass `--sounds <dir>` to `music.mjs`.++| Part | `variant` | Recording | Range | What it brings |+|---|---|---|---|---|+| `piano` | | Grand Piano, Steinway B | A0 to G#7 | 3 velocity layers, pedal-down resonance (`sus`) and key-release (`rel`) |+| `piano` | `"upright"` | Upright Piano, Knight | A0 to C8 | 2 layers, key-release only, no pedal resonance |+| `harp` | | Concert Harp | D1 to G7 | rings out, nothing damps it |+| `marimba` | | Marimba | D2 to C7 | 3 layers, rings out. Sparse: some notes are a recording shifted up to 3 semitones |+| `vibes` | | Vibraphone | F3 to F6 | 3 layers, damped, so the pedal holds it |+| `glockenspiel` | | Glockenspiel | G5 to C8 | 3 layers, rings out. Sparse: up to 3 semitones |+| `bell` | `"tubular"` | Tubular Bells 1 | C4 to F#5 | 2 layers, rings out |+| `timpani` | | Timpani | C#2 to B3 | 3 layers, rings out |++The recordings are from VCSL, CC0. Ranges and the layer counts above are read from the installed+pack's own `manifest.json`; `check` names a sparse bank when it meets one. `bell` without+`"tubular"`, and every other instrument in the table above, are still modeled.++Not recorded, and still synthesized in code: strings, guitar, bass, brass, woodwinds, choir,+celesta, music box, the electric pianos and the acoustic drum kit. Synths, lo-fi colour, electronic+drums and every sound effect are code and stay code.++### What changes when you write for a recording++- **Write inside the range.** A note outside the bank's range throws and the render stops. The grand+ reaches A0; the timpani stops at B3, so anything above B3 in a timpani part needs another+ instrument. Inside the range every note plays: the engine takes the nearest recorded pitch.+- **The decay is the instrument's own.** A low grand note rings for tens of seconds and nothing+ trims it to fit the tail. Let the low notes ring and give them room.+- **The pedal is a pedal.** A `sus` zone is the strings ringing with the dampers lifted, played+ instead of the ordinary zone for any note struck while the pedal is down; a `rel` zone is the+ damper coming back, added quietly at key-up. `perform.ts` moves the pedal just after each harmony+ change, so write pedal changes where the harmony changes. `opts: { pedal: false }` holds it up.+- **Soft playing keeps a real attack.** The Steinway bank has three velocity layers and its source+ was normalized, so soft notes come from the soft recording with the modeled piano's velocity law+ rather than a quiet copy of a loud one. Do not add an attack that isn't there.+- **A real marimba's low notes are rich.** D2 to C4 carries as much as the top of the instrument.+ Keep bass lines out of the melody's register rather than reaching down for the modeled marimba's+ thin bass.+- **Sparse banks name themselves.** Marimba and glockenspiel are flagged `sparse`, so a note in a+ gap is a shifted recording. `check` says so on the `voices` line rather than hiding it.++### Picking a room++| Room | rt60 | Where the recording is from |+|---|---|---|+| `live-room` | 0.2 s | Genesis 6 Studio live room, University of York |+| `small-room` | 0.4 s | Arthur Sykes Rymer Auditorium, University of York |+| `recital-hall` | 1.8 s | Jack Lyons Concert Hall, University of York |++A style's `space.room` names one; `node tools/music.mjs --room <id> ...` overrides it for one run.+An id that is not installed keeps the synthesized space, so the same command is safe with no pack.+Pick the room for the size of the room, not the length of the piece: `live-room` for a take that+should feel close and dry, `small-room` for a nocturne or a lullaby, `recital-hall` when seats are+in the room. The reverb guard still runs: a recorded hall that pushes the late tail within 10 dB of+the dry mix fails `check` like any other space.++### Checking what actually played++`check` and `render` print one line naming every part and which side of the split it took:++```+voices recordings: lead (piano), accomp (piano.upright); modeled: bass (bass), drums (kick)+```++Anything that should have played a recording and did not is a part whose notes fall outside the+bank's range, or a part that opted out.++A part opts out with `opts: { sampled: false }`, which is how you hear a modeled voice beside a+recorded one on purpose, and how a pitch or a register the recording cannot cover stays safe. An+opted-out part renders bit-identical audio to the same part with no pack installed, so the opt-out+is never a guess.+## Any length, never hard-coded`fitScore(piece, seconds)` first calls the piece's own `refit(seconds)` if it has one. A composeddiff --git a/plugins/anidoodle/skills/anidoodle/references/music/compose.md b/plugins/anidoodle/skills/anidoodle/references/music/compose.mdindex f774174..145a5b8 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/compose.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/compose.md@@ -14,7 +14,8 @@ It never gives you notes. **You write every note**:- the form.The engine refuses to fill gaps. Missing harmony, melody, grooves or form is an error that tells you-what to compose. The engine then performs, synthesizes, mixes and masters, deterministically, in code.+what to compose. The engine then performs, mixes and masters, deterministically, in code, and it+plays recordings of real instruments where you ask for one.> **Never reuse shipped material.** The demos (`node tools/music.mjs list`) and our own film scores> are listening references and the novelty corpus. They are never a film's score or a template. Don't@@ -204,6 +205,43 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deterOnly an ear says right. For a **loop**, deliver a `.wav`: mp3 adds encoder padding, so it clicksor gaps at the loop point.+## Recorded instruments++Eight acoustic parts play recordings of the real thing when the sound pack is installed: `piano`+(and `piano` with `variant: "upright"`), `harp`, `marimba`, `vibes`, `glockenspiel`, `bell` with+`variant: "tubular"`, and `timpani`. Strings, guitar, bass, brass, woodwinds, choir, celesta, music+box, the electric pianos and the acoustic drum kit stay modeled either way, and every score plays+without the pack.++Four things decide what you write:++- **Stay inside the range, or the render throws.** The grand reaches A0; the timpani stops at B3;+ the vibraphone starts at F3 and the glockenspiel at G5. The full table is in+ [README.md](README.md#recorded-instruments-the-optional-sound-pack).+- **A recorded note decays the way that instrument decays.** A low grand note rings for tens of+ seconds. Do not write a dense texture under it and expect the tail to get out of the way.+- **The piano has a real pedal.** `sus` zones sound while the dampers are lifted, so the pedal+ changes `perform.ts` already writes just after each harmony change are audible, and a chord left+ ringing under the next one is what a real player does. `opts: { pedal: false }` holds the pedal.+- **A real marimba's low notes are rich.** D2 to C4 carries as much as its top. Keep a bass line out+ of the melody's register instead of reaching down for a note that will not sit under a tune.++Two options go in a part's `opts`:++| Option | What it does |+|---|---|+| `variant: "upright"` / `variant: "tubular"` | picks the second recording of that instrument |+| `sampled: false` | keeps the modeled voice for that part, whatever is installed |++`node tools/music.mjs check` prints the split, so read it before you believe the instrument table:++```+voices recordings: lead (piano), accomp (piano.upright); modeled: bass (bass), drums (kick)+```++A part you expected to be recorded and find modeled is either out of range or opted out. Both are+yours to fix; neither is a silent fallback.+## The material formatWrite the score in the film's own file, next to the film module: `src/canvas-core/<film>Score.ts`@@ -244,7 +282,8 @@ form to the exact length. `score.ts` is an empty skeleton to copy.play in. So leave your voice's `gainDb` out (0 = at the target) and set it, like `levels`, onlyas an offset: `gainDb: 2` is two dB over. Then read `check`'s stems and adjust by the dB itprints. Options (`attack`, `bright`, `drive`) move the level a little; a piano far up its range- is quiet by nature.+ is quiet by nature. `variant` and `sampled` are the two options that change which sound you get,+ and they are in [Recorded instruments](#recorded-instruments) above.- **Loops:** `loop: true`, and the form length is the loop. `render` makes it seamless.- **Split bars:** `harmony: ["<chord> <chord>"]` splits a bar where the meter divides, not at itsarithmetic middle. Give that section a `bass` override for it.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.mdindex 27f1def..b4754a1 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md@@ -1,7 +1,8 @@# Sound design: the effects kit, placed by frame, heard over the score-anidoodle makes its sound effects the way it makes its music: **in code, from nothing**. No samples-or recordings. Every effect is deterministic: the same cue and seed give identical samples.+Every anidoodle sound effect is **built in code, from nothing**: no samples, no recordings, ever.+(The music's acoustic instruments can play recordings from the optional sound pack; effects never+do.) Every effect is deterministic: the same cue and seed give identical samples.Code: `engine/src/canvas-core/music/sfxKit.ts` (the kit), `sfxMix.ts` (placement), `sfxCore.ts`(building blocks). Tool: `engine/tools/sfx.mjs`.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/sounds-licenses.md b/plugins/anidoodle/skills/anidoodle/references/music/sounds-licenses.mdnew file mode 100644index 0000000..f106523--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/music/sounds-licenses.md@@ -0,0 +1,69 @@+# Sound pack licenses++The sound pack is a separate download, installed by `engine/tools/soundfetch.mjs`. Nothing in this+repository is licensed here; this page is what you need to carry if you redistribute the pack or a+film made with it. The short version also lives in the repository's `NOTICE`.++Two sources, two licenses. The instruments need nothing. The rooms need a line of credit.++## Instruments: CC0++All recordings from the Versilian Community Sample Library (VCSL).++- Source: https://github.com/sgossner/VCSL+- License: CC0 1.0 Universal (public domain)++CC0 asks for nothing: no attribution, no licence notice, no share-alike, no restriction. Attribution+is still welcome and the anidoodle page names the library.++Eight instruments are taken from it:++| Instrument id | Recording | VCSL folder |+|---|---|---|+| `piano` | Grand Piano, Steinway B | `Chordophones/Zithers/Grand Piano, Steinway B` |+| `piano.upright` | Upright Piano, Knight | `Chordophones/Zithers/Upright Piano, Knight` |+| `harp` | Concert Harp | `Chordophones/Composite Chordophones/Concert Harp` |+| `marimba` | Marimba | `Idiophones/Struck Idiophones/Marimba` |+| `vibes` | Vibraphone | `Idiophones/Struck Idiophones/Vibraphone` |+| `glockenspiel` | Glockenspiel | `Idiophones/Struck Idiophones/Glockenspiel` |+| `bell.tubular` | Tubular Bells 1 | `Idiophones/Struck Idiophones/Tubular Bells 1` |+| `timpani` | Timpani | `Membranophones/Struck Membranophones/Timpani 2` |++The exact WAV taken from each folder, and its sha256, are in the pack's own `LICENSES.md` next to+`manifest.json`. That file is the authority; this table is the map.++## Rooms: CC BY 4.0++Recorded impulse responses from OpenAIR, the Open Acoustic Impulse Response library, Audio Lab,+University of York: https://www.openair.hosted.york.ac.uk/++- License: Creative Commons Attribution 4.0 International (CC BY 4.0)+- The B-format (W X Y Z) recordings were decoded to stereo as L = W + Y, R = W - Y++CC BY 4.0 requires attribution. Anyone redistributing the pack, or a film rendered with one of these+rooms, must carry this credit:++> Recorded impulse responses from OpenAIR, the Open Acoustic Impulse Response library, Audio Lab,+> University of York (https://www.openair.hosted.york.ac.uk/), licensed CC BY 4.0.++Credit each room where you can:++| Room id | Room | URL |+|---|---|---|+| `small-room` | Arthur Sykes Rymer Auditorium, University of York | https://www.openair.hosted.york.ac.uk/?page_id=425 |+| `recital-hall` | Jack Lyons Concert Hall, University of York | https://www.openair.hosted.york.ac.uk/?page_id=571 |+| `live-room` | Genesis 6 Studio live room, University of York | https://www.openair.hosted.york.ac.uk/?page_id=483 |++The other three things CC BY 4.0 allows are worth knowing: commercial use, modification (so+processing the impulse response does not break it), and distribution. The one condition is the+credit above.++## Where this comes from++`anidoodle-research/sound-pack/CONTRACT.md` sets the rules for version 1: FLAC, 48 kHz, 24-bit, the+pack under 200 MB, and CC0 or public domain only. The three OpenAIR rooms are the exception the+amendment of 2026-10-04 (b) authorized once the microphone was heard to sell the recordings. They+are the only CC BY material the skill ships, and they are the only part that needs a credit line.++Reproduce the pack and the licences with `node tools/soundpack.mjs`, which writes the per-file+`LICENSES.md` from the same manifest the engine reads.\ No newline at end of filediff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md b/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.mdindex 2272aff..a2894e4 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md@@ -26,7 +26,7 @@ pick", pick, say what you picked and why in one line, and carry on.(`long-film.md`).5. **Sound?** Silent, or a score: name a music style and a mood per section(`references/music/`). Their own voice-over or track is theirs to bring; anidoodle composes- and synthesizes everything else.+ and plays everything else.6. **Characters?** A new one (build it once, `character-consistency.md`), one they already havein a module, or one from their image (reference, embedded only if they ask).