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
keys rebuild (S3): measured-physics piano v2 (grand/felt/upright/honky), Rhodes/Wurli/DX electric pianos, modal mallets/bells on VCSL-fitted tables, tonewheel+Leslie and pipe organs; per-strike anti-clone; Piece.legacy keeps the launch films on the old voices
Alex Greenshpun031c64eb190e
diff --git a/skills/anidoodle/engine/src/canvas-core/music/index.ts b/skills/anidoodle/engine/src/canvas-core/music/index.tsindex d8bfe6e..4686856 100644--- a/skills/anidoodle/engine/src/canvas-core/music/index.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/index.ts@@ -34,3 +34,4 @@ export const DEMOS = { launchLofi, launchLofi2, launchLofi3, nocturne, pianoPhraexport const DEMO_FAMILIES: Record<string, string[]> = { launch: ["launchLofi", "launchLofi2", "launchLofi3"], nocturne: ["nocturne", "pianoPhrase8"] };/** Test fixtures, never scores: the ghost (must fail the ghost guard), the copy (must fail novelty). */export const FIXTURES = { ghostFixture, daylightCopy };+export * from "./keys";diff --git a/skills/anidoodle/engine/src/canvas-core/music/keys.ts b/skills/anidoodle/engine/src/canvas-core/music/keys.tsnew file mode 100644index 0000000..02ba0ad--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/keys.ts@@ -0,0 +1,35 @@+// Keys family (track S3, 2026-09-28): piano v2, electric pianos, mallets and bells, organs.+// New sound by default. Piece.legacy (the one freeze flag, shared with the other tracks) keeps the pre-rebuild voices+// bit-for-bit: render.ts skips keysVoice and runs its old switch. The shipped launch films set it.+import type { Played } from "./perform";+import type { Out, Opts } from "./keysCore";+import { electricPiano } from "./keysEP";+import { bars, musicBoxV2, fmBellV2 } from "./keysMallets";+import { tonewheel, pipeOrgan } from "./keysOrgan";+export { renderPianoV2, measuredB, type PianoVariant } from "./keysPiano";++/** Instruments this family renders (piano goes through render.ts's pedal-aware path). */+export const KEYS_INSTS = ["musicBox", "bell", "celesta", "marimba", "vibes", "glockenspiel", "fmBell", "ePiano", "wurlitzer", "organ", "pipeOrgan"] as const;+/**+ * The new keys voices. Returns null for instruments outside the family. Options (all optional):+ * ePiano model "rhodes" | "wurli" | "dx", detune (c, per-note spread), trem (Hz), tremDepth, drive, width+ * organ kind "tonewheel" | "pipe", drawbars "888000000", bright (legacy registration), leslie "slow" | "fast" | "off" (trem: 0 = off), perc "2nd" | "3rd", click, drive+ * pipeOrgan stops "principal" | "flute" | "full", trem (Hz tremulant, default off)+ * vibes trem (motor Hz, 0 = off), tremDepth+ */+export const keysVoice = (inst: string, keys: Played[], sr: number, n: number, o: Opts, seed: number): Out | null => {+ switch (inst) {+ case "musicBox": return musicBoxV2(keys, sr, n, o, seed);+ case "bell": return bars(keys, sr, n, o, seed, "bell");+ case "celesta": return bars(keys, sr, n, o, seed, "celesta");+ case "marimba": return bars(keys, sr, n, o, seed, "marimba");+ case "vibes": return bars(keys, sr, n, o, seed, "vibes");+ case "glockenspiel": return bars(keys, sr, n, o, seed, "glockenspiel");+ case "fmBell": return fmBellV2(keys, sr, n, o, seed);+ case "ePiano": return electricPiano(keys, sr, n, o, seed);+ case "wurlitzer": return electricPiano(keys, sr, n, o, seed, "wurli");+ case "organ": return o.kind === "pipe" ? pipeOrgan(keys, sr, n, o, seed) : tonewheel(keys, sr, n, o, seed);+ case "pipeOrgan": return pipeOrgan(keys, sr, n, o, seed);+ default: return null;+ }+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/keysCore.ts b/skills/anidoodle/engine/src/canvas-core/music/keysCore.tsnew file mode 100644index 0000000..a125582--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/keysCore.ts@@ -0,0 +1,108 @@+// Shared pieces for the keys voices (keysPiano, keysEP, keysMallets, keysOrgan).+// Anti-clone rule: every note draws its own seeded variation (pitch, level, brightness, decay,+// phase) from rng(seed, note index), so a repeated key never renders the same waveform twice,+// while the same piece + seed always renders the same samples.+import { type Rng, TAU, clamp, pan, gauss } from "./dsp";+import { rng as mkRng } from "../core";+import type { Played } from "./perform";++export type Out = { L: Float32Array; R: Float32Array };+export type Opts = Record<string, number | boolean | string>;+export const num = (o: Opts, k: string, d: number) => (typeof o[k] === "number" ? (o[k] as number) : d);+export const str = (o: Opts, k: string, d: string) => (typeof o[k] === "string" ? (o[k] as string) : d);+export const out0 = (n: number): Out => ({ L: new Float32Array(n), R: new Float32Array(n) });+export const mtof = (m: number) => 440 * Math.pow(2, (m - 69) / 12);+export const dbA = (x: number) => Math.pow(10, x / 20);++/**+ * Per-note variation, seeded by (instrument seed, note index, onset). Sizes follow research sec. 2 item 3.+ * Repeats of ONE key walk a golden-ratio sequence (`seq`, -1..1) instead of iid noise, so two strikes of the+ * same key never land on nearly the same pitch/phase by chance (iid draws sometimes do: a clone).+ */+export type NoteVar = { r: Rng; cents: number; gain: number; bright: number; decay: number; seq: number; seq2: number; phase: () => number };+const frac = (x: number) => x - Math.floor(x);+export const noteVar = (seed: number, idx: number, k: Played, o: { cents?: number; db?: number; bright?: number; decay?: number } = {}, strike = idx): NoteVar => {+ const r = mkRng((seed * 7919 + idx * 104729 + Math.round(k.t * 1000) * 13 + k.p * 31) >>> 0);+ const g = () => clamp(gauss(r), -2.5, 2.5), h = frac(Math.sin(k.p * 12.9898 + seed * 78.233) * 43758.5453);+ const seq = 2 * frac(h + (strike + 1) * 0.6180339887) - 1, seq2 = 2 * frac(h * 1.7 + (strike + 1) * 0.7548776662) - 1;+ return {+ r, seq, seq2,+ cents: (seq * 1.6 + g() * 0.25) * (o.cents ?? 1.2),+ gain: dbA(g() * (o.db ?? 0.6)),+ bright: 1 + g() * (o.bright ?? 0.05),+ decay: 1 + g() * (o.decay ?? 0.06),+ phase: () => r() * TAU,+ };+};+/** Counts strikes per key while walking notes in time order: strike(p) = how many times p sounded before. */+export const strikeCounter = () => { const m = new Map<number, number>(); return (p: number) => { const c = m.get(p) ?? 0; m.set(p, c + 1); return c; }; };++/** A slow 1/f-ish pitch wander shared by a whole instrument (cents), two octave-spaced smoothed random walks. */+export const drift = (seed: number, n: number, sr: number, cents: number): Float32Array => {+ const r = mkRng(seed * 131 + 17), out = new Float32Array(n);+ if (cents <= 0) return out;+ const step = Math.max(1, Math.round(sr / 200)); // control rate 200 Hz+ let a = 0, b = 0, va = 0, vb = 0;+ const ka = 1 - Math.exp(-TAU * 0.15 / 200), kb = 1 - Math.exp(-TAU * 0.6 / 200);+ let prev = 0, next = 0;+ for (let i = 0; i < n; i += step) {+ va += ka * (gauss(r) * 3 - va); a += ka * (va - a);+ vb += kb * (gauss(r) * 1.5 - vb); b += kb * (vb - b);+ prev = next; next = (a + 0.5 * b) * cents;+ for (let j = 0; j < step && i + j < n; j++) out[i + j] = prev + ((next - prev) * j) / step;+ }+ return out;+};++/**+ * Decaying sinusoid added into a mono buffer from sample i0: amplitude a, frequency f, T60-ish decay+ * sigma (1/s), start phase ph (sine start = 0), optional damping from sample dI on with extra sigma sD.+ * Stops once the partial is `floorRel` below its start. Recursive rotation, no sin() per sample.+ */+export const partial = (buf: Float64Array, i0: number, f: number, a: number, sigma: number, ph: number, sr: number, dI = Infinity, sD = 0, floorRel = 1e-4) => {+ if (a <= 0 || f <= 0 || f >= sr * 0.49) return;+ const n = buf.length, w = (TAU * f) / sr, cw = Math.cos(w), sw = Math.sin(w);+ const d1 = Math.exp(-sigma / sr), d2 = Math.exp(-(sigma + sD) / sr);+ let c = a * Math.cos(ph), s = a * Math.sin(ph);+ const floor2 = a * a * floorRel * floorRel;+ const end = Math.min(n - i0, Math.ceil((Math.log(1 / floorRel) / Math.max(sigma, 1e-3)) * sr) + 2);+ for (let i = Math.max(0, -i0); i < end; i++) {+ buf[i0 + i] += s;+ const d = i < dI ? d1 : d2, c2 = (c * cw - s * sw) * d; s = (c * sw + s * cw) * d; c = c2;+ if (i > dI && (i & 255) === 0 && c * c + s * s < floor2) break;+ }+};++/** Add a mono Float64 buffer into the stereo out with an equal-power pan and gain. */+export const mixIn = (out: Out, buf: Float64Array | Float32Array, p: number, g: number, from = 0, to = buf.length) => {+ const [gl, gr] = pan(p);+ for (let i = from; i < to; i++) { const v = buf[i] * g; out.L[i] += v * gl; out.R[i] += v * gr; }+};++/** One-pole DC blocker in place. */+export const dcBlock = (x: Float64Array | Float32Array, sr: number, fc = 12) => {+ const R = Math.exp((-TAU * fc) / sr); let x1 = 0, y1 = 0;+ for (let i = 0; i < x.length; i++) { const y = x[i] - x1 + R * y1; x1 = x[i]; y1 = y; x[i] = y; }+};++/** 2x-oversampled waveshaper (linear-interpolated upsample, two-tap average down): cheap alias control for tanh-style drives. */+export const shape2x = (x: Float64Array | Float32Array, fn: (v: number) => number, from = 0, to = x.length) => {+ let prev = from > 0 ? x[from - 1] : 0, prevY = fn(prev);+ for (let i = from; i < to; i++) { const cur = x[i], mid = fn(0.5 * (prev + cur)), y = fn(cur); x[i] = 0.25 * prevY + 0.5 * mid + 0.25 * y; prev = cur; prevY = y; }+};++/** Band-limited noise burst (seeded): a raised-cosine-windowed gaussian through a 2-pole band-pass. */+export const noiseBurst = (buf: Float64Array, i0: number, len: number, fc: number, q: number, g: number, r: Rng, sr: number, decayS = 0) => {+ const w = (TAU * Math.min(fc, sr * 0.45)) / sr, al = Math.sin(w) / (2 * q), a0 = 1 + al, b0 = al / a0, a1 = (-2 * Math.cos(w)) / a0, a2 = (1 - al) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;+ for (let i = 0; i < len && i0 + i < buf.length; i++) {+ const env = decayS > 0 ? Math.exp(-i / (decayS * sr)) * Math.min(1, i / 8) : Math.sin((Math.PI * i) / len);+ const x = gauss(r), y = b0 * x - b0 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x; y2 = y1; y1 = y;+ if (i0 + i >= 0) buf[i0 + i] += y * env * g;+ }+};++/** Keys that the next strike of the same key cuts (a restrike re-damps the strings/bar): onset of the next same-pitch key, or Infinity. */+export const nextSameKey = (sorted: Played[], idx: number) => { const k = sorted[idx]; for (let j = idx + 1; j < sorted.length; j++) if (sorted[j].p === k.p && sorted[j].t > k.t) return sorted[j].t; return Infinity; };+export const byTime = (keys: Played[]) => keys.slice().sort((a, b) => a.t - b.t || a.p - b.p);+export const pitchPan = (m: number, w: number) => clamp((m - 64) / 30, -1, 1) * w;diff --git a/skills/anidoodle/engine/src/canvas-core/music/keysEP.ts b/skills/anidoodle/engine/src/canvas-core/music/keysEP.tsnew file mode 100644index 0000000..7454b28--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/keysEP.ts@@ -0,0 +1,103 @@+// Electric pianos, modelled from the mechanism, not from a 2-op FM preset.+//+// RHODES (Fender Rhodes Mk I style). A neoprene hammer strikes a tine (a stiff rod) bolted to a tone bar;+// the tine swings in front of a magnetic pickup. (a) Tine = modal sum: the fundamental (T60 ~6 s at C3,+// ~1.5 s at C6) plus the tine's first inharmonic mode at ~7.1-7.3 f0 that dies in 50-150 ms (the "ping").+// (b) Hammer: a raised-cosine contact of 1-3 ms (shorter when harder); velocity sets the displacement.+// (c) Pickup: the field of a pole piece seen by a tine that sits OFF-centre (voicing offset d):+// y = (x+d)/sqrt((x+d)^2+h^2) - d/sqrt(d^2+h^2). Asymmetric, so even harmonics appear, and the+// nonlinearity only bites at large swings: bell-clean at pp, the growling "bark" at ff (DAFx-17 Rhodes /+// Wurlitzer model; ISMA 2014). (d) One stereo tremolo LFO for the instrument, L/R 180 degrees apart.+// (e) A small amp: 2x oversampled soft clip, +2 dB at 250 Hz, low-pass ~6.5 kHz.+// WURLITZER (200A style). A steel reed, plucked by a felt hammer, over an electrostatic pickup: reed modes+// 1 and 6.27 (cantilever), the pickup is a capacitor, y = x/(1-kx): strongly asymmetric, reedy and+// nasal, growling hard at ff; shorter sustain; mono amplitude tremolo.+// DX (the '83 digital EP, re-implemented from the published algorithm-5 idea, no ROM data, no code copied):+// three 2-operator stacks: 1:1 body, 1:14 tine "bark" with a 20-60 ms index, 1:1 detuned warmth; each+// modulator's index decays faster than its carrier, all scaled by velocity.+// Anti-clone: per note +-3 c (opts.detune widens it), free tine phase, +-15 % ping, +-0.6 dB; slow+// instrument-wide pitch drift for Rhodes/Wurli (the mechanical instrument is never perfectly in tune).+import { TAU, clamp, pan, Biquad, gauss } from "./dsp";+import type { Played } from "./perform";+import { type Out, type Opts, num, str, out0, mtof, noteVar, strikeCounter, drift, dcBlock, shape2x, noiseBurst, byTime, nextSameKey } from "./keysCore";++type Model = "rhodes" | "wurli" | "dx";+const LEVEL: Record<Model, number> = { rhodes: 0.29, wurli: 0.24, dx: 0.16 }; // matched to the legacy ePiano stem RMS (tools/keys-demo.mjs calibrate)++export const electricPiano = (keys: Played[], sr: number, n: number, o: Opts, seed: number, model: Model = str(o, "model", "rhodes") as Model): Out => {+ const out = out0(n), sorted = byTime(keys), width = num(o, "width", 0.35), detSd = num(o, "detune", 4) * 0.5;+ const dr = model === "dx" ? null : drift(seed, n, sr, 2.5);+ const note = new Float64Array(Math.ceil(12 * sr)), strike = strikeCounter();+ sorted.forEach((k, idx) => {+ const i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const nv = noteVar(seed, idx, k, { cents: Math.max(1, detSd), db: 0.6, bright: 0.12, decay: 0.08 }, strike(k.p));+ const v = clamp(k.v * nv.bright, 0.02, 1), m = k.p;+ const f = mtof(m) * Math.pow(2, (nv.cents + (dr ? dr[i0] : 0)) / 1200);+ const dur = Math.max(0.01, Math.min(k.off, nextSameKey(sorted, idx)) - k.t);+ const relTau = model === "wurli" ? 0.05 : model === "dx" ? 0.12 : 0.075;+ const t60 = (model === "wurli" ? clamp(3.2 * Math.pow(2, -(m - 48) / 16), 0.5, 6) : clamp(6 * Math.pow(2, -(m - 48) / 18), 0.8, 9)) * nv.decay;+ const len = Math.min(note.length, n - i0, Math.ceil((dur + relTau * 7) * sr), Math.ceil(t60 * 1.3 * sr));+ if (len <= 0) return;+ const relI = Math.round(dur * sr), sig = 6.91 / t60, decR = Math.exp(-1 / (relTau * sr));+ const buf = note.subarray(0, len); buf.fill(0);+ const contact = Math.max(2, Math.round(((model === "wurli" ? 2.4 : 3) - 1.8 * v) / 1000 * sr));+ if (model === "dx") {+ // three stacks, phase modulation; the carriers start at zero phase, the modulators free+ const I1 = 1.1 + 2.3 * v * v, I2 = 0.2 + 3.2 * Math.pow(v, 1.6), I3 = 0.5 + 0.7 * v;+ const tb = 0.02 + 0.04 * (1 - v), w = TAU * f / sr, d2 = Math.pow(2, 2 / 1200), d3 = Math.pow(2, -3 / 1200);+ let pm2 = nv.phase(), pm3 = nv.phase(), fb = 0;+ const e1 = Math.exp(-sig / sr), e1i = Math.exp(-1 / (0.55 * sr)), e2 = Math.exp(-1 / (0.28 * sr)), e2i = Math.exp(-1 / (tb * sr)), e3 = Math.exp(-(sig * 0.7) / sr), e3i = Math.exp(-1 / (1.5 * sr));+ let a1 = 1, i1 = I1, a2 = 0.55 * v, i2 = I2, a3 = 0.35, i3 = I3, rel = 1;+ for (let i = 0; i < len; i++) {+ const t = i * w;+ const m1 = Math.sin(t + 0.5 * fb); fb = m1; // op feedback on the body modulator+ const y = a1 * Math.sin(t + i1 * m1) + a2 * Math.sin(t * d2 + i2 * Math.sin(14 * t + pm2)) + a3 * Math.sin(t * d3 + i3 * Math.sin(t * d3 + pm3));+ buf[i] = y * rel * Math.min(1, i / contact);+ a1 *= e1; i1 *= e1i; a2 *= e2; i2 *= e2i; a3 *= e3; i3 *= e3i; if (i >= relI) rel *= decR;+ }+ void pm3;+ } else {+ // tine / reed displacement: fundamental + the first inharmonic mode+ const pr = model === "wurli" ? 6.27 : 7.1 + 0.25 * ((m * 0.618) % 1); // per-key tine geometry+ const pingA = (model === "wurli" ? 0.18 : 0.28) * Math.pow(v, 1.4) * (1 + 0.15 * clamp(gauss(nv.r), -2, 2));+ const pingT = (model === "wurli" ? 0.035 : 0.05 + 0.1 * (1 - v)) * Math.pow(262 / f, 0.3);+ const X = Math.pow(v, 0.85) * (model === "wurli" ? 0.9 : 1.15) * clamp(Math.pow(262 / f, 0.25), 0.6, 1.4); // bigger swings low on the keyboard+ const w1 = TAU * f / sr, w2 = TAU * f * pr / sr, e1 = Math.exp(-sig / sr), e2 = Math.exp(-1 / (pingT * sr));+ let c1 = 0, s1 = 0, c2 = 0, s2 = 0; { const p2 = nv.phase(); c1 = 1; s1 = 0; c2 = Math.cos(p2); s2 = Math.sin(p2); }+ const cw1 = Math.cos(w1), sw1 = Math.sin(w1), cw2 = Math.cos(w2), sw2 = Math.sin(w2);+ const d = model === "wurli" ? 0 : 0.22 + 0.08 * ((m * 0.37) % 1), h = 0.72, base = d / Math.sqrt(d * d + h * h);+ const kC = 0.3 + 0.45 * v; // Wurli pickup: the reed closes on the plate+ let rel = 1;+ for (let i = 0; i < len; i++) {+ const x = X * (s1 + pingA * s2) * Math.min(1, i / contact);+ let y: number;+ if (model === "wurli") { const xx = clamp(x, -0.95 / kC, 0.95 / kC) * kC; y = xx / (1 - xx) / Math.max(kC, 1e-3); }+ else y = (x + d) / Math.sqrt((x + d) * (x + d) + h * h) - base;+ buf[i] = y * rel;+ let t2 = (c1 * cw1 - s1 * sw1) * e1; s1 = (c1 * sw1 + s1 * cw1) * e1; c1 = t2;+ t2 = (c2 * cw2 - s2 * sw2) * e2; s2 = (c2 * sw2 + s2 * cw2) * e2; c2 = t2;+ if (i >= relI) rel *= decR;+ }+ dcBlock(buf, sr, 15);+ // damper felt on key-up+ if (relI < len) noiseBurst(buf, relI, Math.round(0.03 * sr), 600, 0.8, 0.004 * v, nv.r, sr);+ }+ const g = Math.pow(k.v, 1.1) * LEVEL[model] * nv.gain, [gl, gr] = pan(clamp((m - 64) / 30, -1, 1) * width);+ for (let i = 0; i < len; i++) { const y = buf[i] * g; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; }+ });+ // the amp: 2x oversampled soft clip, a low-mid bump, the speaker roll-off+ const drive = num(o, "drive", model === "wurli" ? 1.6 : 1.25);+ for (const c of [out.L, out.R]) {+ shape2x(c, (x) => Math.tanh(drive * x + 0.05 * drive * x * x) / drive);+ Biquad.make(sr, "peak", model === "wurli" ? 900 : 250, 0.8, model === "wurli" ? 2.5 : 2).run(c);+ Biquad.make(sr, "lp", model === "wurli" ? 5200 : model === "dx" ? 9000 : 6500, 0.6).run(c);+ dcBlock(c, sr, 10);+ }+ // tremolo: one LFO for the whole instrument; stereo auto-pan (Rhodes Suitcase) or mono (Wurli)+ const rate = num(o, "trem", 4.6), depth = num(o, "tremDepth", model === "wurli" ? 0.18 : 0.3);+ if (rate > 0 && depth > 0) {+ const ph = ((seed * 0.6180339) % 1) * TAU;+ for (let i = 0; i < n; i++) { const s = Math.sin((TAU * rate * i) / sr + ph) * depth; if (model === "wurli") { const a = 1 - depth * (0.5 + 0.5 * s / depth); out.L[i] *= a; out.R[i] *= a; } else { out.L[i] *= 1 - s; out.R[i] *= 1 + s; } }+ }+ return out;+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/keysMallets.ts b/skills/anidoodle/engine/src/canvas-core/music/keysMallets.tsnew file mode 100644index 0000000..076b6fd--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/keysMallets.ts@@ -0,0 +1,134 @@+// Mallets, bells, celesta, glockenspiel, music box: modal synthesis on MEASURED mode tables+// (keysTables.ts, VCSL CC0) instead of harmonic guesses.+// bar/tube each mode = a decaying sinusoid at ratio x f0, its level and T60 measured at a reference+// pitch and scaled by frequency (T60 ~ f^-alpha: alpha 1.0 rosewood, 0.6 aluminium/steel)+// mallet a half-sine contact of tc ms: its spectrum |cos(pi f tc) / (1 - (2 f tc)^2)| weights the+// modes, so a soft yarn mallet (4-6 ms) is round and a hard one (0.4 ms) rings the top modes;+// velocity shortens the contact (harder blow) and adds a band-passed "tock"+// resonator marimba/vibes/celesta tubes or box: a coupled copy of the fundamental with a slower rise+// ("bloom"); the vibraphone's motor tremolo modulates ONLY this coupled fundamental, as the+// rotating discs do on the real instrument+// dampers vibes and celesta damp on key-up; a restrike re-damps the bar+// music box a steel comb tooth = a cantilever (modes 1 : 6.27 : 17.55) plucked by a pin, a tiny tick,+// ringing through a small wooden box (fixed resonances seeded per instrument)+// Anti-clone: per note +-0.8 dB per mode, +-10 % contact time, +-6 % decay, onset phase jitter, seeded ticks.+import { TAU, clamp, SVF, gauss, pan } from "./dsp";+import { rng as mkRng } from "../core";+import type { Played } from "./perform";+import { type Out, type Opts, num, out0, mtof, dbA, noteVar, strikeCounter, partial, noiseBurst, byTime, nextSameKey, pitchPan } from "./keysCore";+import { MARIMBA, MARIMBA_T60_REF_HZ, VIBES, VIBES_T60_REF_HZ, GLOCK, GLOCK_T60_REF_HZ, CHIME, CHIME_T60_REF_HZ, type ModeRow } from "./keysTables";++type Spec = {+ modes: ModeRow[]; refHz: number; alpha: number; tcMs: [number, number]; // contact ms at v=0 / v=1+ bloom: number; damped: boolean; dampSigma: number; tock: [number, number]; level: number; maxS: number; width: number; octave?: number; t60Mul?: number;+};+const SPECS: Record<string, Spec> = {+ marimba: { modes: MARIMBA, refHz: MARIMBA_T60_REF_HZ, alpha: 1.0, tcMs: [5.5, 1.6], bloom: 0.45, damped: false, dampSigma: 0, tock: [1800, 0.05], level: 0.4, maxS: 9, width: 0.7 },+ vibes: { modes: VIBES, refHz: VIBES_T60_REF_HZ, alpha: 0.6, tcMs: [3.5, 0.9], bloom: 0.5, damped: true, dampSigma: 7, tock: [2600, 0.03], level: 0.4, maxS: 12, width: 0.6 },+ glockenspiel: { modes: GLOCK, refHz: GLOCK_T60_REF_HZ, alpha: 0.6, tcMs: [0.9, 0.3], bloom: 0, damped: false, dampSigma: 0, tock: [5500, 0.04], level: 0.2, maxS: 10, width: 0.5 },+ celesta: { modes: GLOCK.slice(0, 4).map(([r, d, t]) => [r, d - 6, t * 0.5] as ModeRow), refHz: GLOCK_T60_REF_HZ, alpha: 0.55, tcMs: [2.8, 1.4], bloom: 0.6, damped: true, dampSigma: 9, tock: [1400, 0.025], level: 0.8, maxS: 8, width: 0.5, t60Mul: 0.35 },+ bell: { modes: CHIME, refHz: CHIME_T60_REF_HZ, alpha: 0.7, tcMs: [1.2, 0.5], bloom: 0, damped: false, dampSigma: 0, tock: [3000, 0.02], level: 0.48, maxS: 14, width: 0.3, t60Mul: 0.35 },+};++/** Spectrum of a half-sine force pulse of duration tc (s) at f: 1 at DC, first zero at 1.5/tc. */+const pulseW = (f: number, tc: number) => { const x = 2 * f * tc; if (Math.abs(x - 1) < 1e-6) return Math.PI / 4; return Math.abs(Math.cos(Math.PI * f * tc) / (1 - x * x)); };++export const bars = (keys: Played[], sr: number, n: number, o: Opts, seed: number, kind: keyof typeof SPECS): Out => {+ const S = SPECS[kind], out = out0(n), sorted = byTime(keys), width = num(o, "width", S.width);+ const trem = kind === "vibes" ? num(o, "trem", 5.2) : 0, tremDepth = num(o, "tremDepth", 0.45);+ const buf = new Float64Array(Math.ceil(S.maxS * sr)), res = kind === "vibes" && trem > 0 ? new Float64Array(n) : null;+ const resBuf = new Float64Array(buf.length), strike = strikeCounter();+ sorted.forEach((k, idx) => {+ const i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const nv = noteVar(seed, idx, k, { cents: 1.0, db: 0.5, bright: 0.1, decay: 0.06 }, strike(k.p));+ const v = clamp(k.v, 0.02, 1), f0 = mtof(k.p) * Math.pow(2, nv.cents / 1200);+ const tc = ((S.tcMs[0] + (S.tcMs[1] - S.tcMs[0]) * Math.pow(v, 0.8)) / 1000) * (1 + 0.1 * clamp(gauss(nv.r), -2, 2)) / nv.bright;+ let damp = Infinity;+ if (S.damped) damp = Math.min(k.off, nextSameKey(sorted, idx));+ else { const nx = nextSameKey(sorted, idx); if (nx < Infinity) damp = nx + 0.003; } // a restrike stops the old ring+ const dI = damp === Infinity ? Infinity : Math.round((damp - k.t) * sr);+ const len = Math.min(buf.length, n - i0); if (len <= 0) return;+ const b = buf.subarray(0, len); b.fill(0);+ const rb = resBuf.subarray(0, len); rb.fill(0);+ const W0 = pulseW(f0, tc);+ for (const [ratio, db, t60ref] of S.modes) {+ const f = ratio * f0; if (f > sr * 0.45) continue;+ const t60 = clamp(t60ref * (S.t60Mul ?? 1) * Math.pow((ratio * S.refHz) / f, S.alpha), 0.02, 60) * nv.decay;+ const a = dbA(db + (ratio === S.modes[0][0] ? 0 : 2 * (ratio < 5 ? nv.seq2 : -nv.seq2)) + 0.6 * clamp(gauss(nv.r), -2, 2)) * (pulseW(f, tc) / W0); // strike position moves the upper modes against each other+ if (a < 1e-4) continue;+ const ph = 0.35 * nv.seq2 + 0.1 * clamp(gauss(nv.r), -2, 2);+ if (ratio === S.modes[0][0] && S.bloom > 0) {+ partial(b, 0, f, a * (1 - S.bloom * 0.5), 6.91 / t60, ph, sr, dI, S.dampSigma);+ // the resonator: the same pitch (a hair sharp), a slower rise, a little longer ring+ partial(rb, 0, f * 1.0015, a * S.bloom * (1 + 0.25 * nv.seq), 6.91 / (t60 * 1.15), ph + 0.3 + 0.8 * nv.seq, sr, dI, S.dampSigma); // the air column's phase vs the bar's differs strike to strike+ const rise = Math.max(1, Math.round(0.012 * sr));+ for (let i = 0; i < Math.min(rise, len); i++) rb[i] *= i / rise;+ } else partial(b, 0, f, a, 6.91 / t60, ph, sr, dI, S.dampSigma || 12);+ }+ if (!res) for (let i = 0; i < len; i++) b[i] += rb[i];+ // contact ramp (the mallet is on the bar for tc)+ const rampN = Math.max(2, Math.round(tc * sr));+ for (let i = 0; i < Math.min(rampN, len); i++) b[i] *= Math.sin((0.5 * Math.PI * i) / rampN);+ // the "tock": wood/metal contact noise, louder and brighter for harder blows+ noiseBurst(b, 0, Math.round((0.004 + tc) * sr), S.tock[0] * (0.7 + 0.6 * v), 0.9, S.tock[1] * v * v, nv.r, sr, 0.0025);+ const g = Math.pow(v, 1.25) * S.level * nv.gain, p = pitchPan(k.p, width);+ const [gl, gr] = pan(p);+ for (let i = 0; i < len; i++) { const y = b[i] * g; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; }+ if (res) for (let i = 0; i < len; i++) res[i0 + i] += rb[i] * g;+ });+ if (res) { // vibraphone motor: the discs open and close the resonators; only the coupled fundamental pulses+ const ph = ((seed * 0.381966) % 1) * TAU;+ for (let i = 0; i < n; i++) { const m = 1 - tremDepth * (0.5 + 0.5 * Math.sin((TAU * trem * i) / sr + ph)), y = res[i] * m; out.L[i] += y * 0.72; out.R[i] += y * 0.69; }+ }+ return out;+};++/** Music box: comb teeth (cantilever modes), a pin tick, and a small wooden box. */+export const musicBoxV2 = (keys: Played[], sr: number, n: number, o: Opts, seed: number): Out => {+ const out = out0(n), sorted = byTime(keys), width = num(o, "width", 0.5), buf = new Float64Array(Math.ceil(7 * sr)), strike = strikeCounter();+ const dry = new Float64Array(n);+ sorted.forEach((k, idx) => {+ const i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const nv = noteVar(seed, idx, k, { cents: 1.2, db: 0.7, bright: 0.12, decay: 0.08 }, strike(k.p)), v = clamp(k.v, 0.05, 1);+ const f = mtof(k.p) * Math.pow(2, nv.cents / 1200), T60 = clamp(3.1 * Math.sqrt(440 / f), 0.6, 7) * nv.decay;+ const nx = nextSameKey(sorted, idx), dI = nx < Infinity ? Math.round((nx - k.t) * sr) : Infinity; // the pin re-plucks: the old ring is damped+ const len = Math.min(buf.length, n - i0, Math.ceil(T60 * 1.2 * sr)); if (len <= 0) return;+ const b = buf.subarray(0, len); b.fill(0);+ const pluck = 0.55 + 0.45 * v * nv.bright; // how far the pin bends the tooth: brighter when faster+ partial(b, 0, f, 1, 6.91 / T60, 0.35 * nv.seq2, sr, dI, 40);+ partial(b, 0, f * 6.267, 0.16 * pluck * pluck, 6.91 / clamp(0.35 * Math.sqrt(440 / f), 0.05, 0.6), nv.phase(), sr, dI, 40);+ partial(b, 0, f * 17.55, 0.05 * pluck * pluck, 6.91 / 0.05, nv.phase(), sr, dI, 40);+ partial(b, 0, f * 2, 0.06, 6.91 / (T60 * 0.5), nv.phase(), sr, dI, 40); // the tooth's nonlinear 2nd (large swings)+ noiseBurst(b, 0, Math.round(0.0025 * sr), 4200, 1.1, 0.05 * v, nv.r, sr, 0.0008); // pin tick+ const g = Math.pow(v, 1.2) * 0.27 * nv.gain, p = pitchPan(k.p, width);+ const [gl, gr] = pan(p);+ for (let i = 0; i < len; i++) { const y = b[i] * g; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; dry[i0 + i] += y; }+ });+ // the box: a handful of wooden resonances (seeded per instrument), fed by the comb+ const br = mkRng(seed * 71 + 3);+ for (let j = 0; j < 7; j++) {+ const f = 380 * Math.pow(6, (j + br()) / 7), q = 6 + 10 * br(), g = (0.05 + 0.05 * br()) * (j % 2 ? 1 : -1), sv = new SVF(sr, f, q);+ for (let i = 0; i < n; i++) { sv.tick(dry[i]); const y = sv.bp * g; out.L[i] += y; out.R[i] += y * 0.9; }+ }+ return out;+};++/** FM bell (lead bell in many styles): 2 detuned carriers (beating), free modulator phase, the tierce, index decaying faster than loudness. */+export const fmBellV2 = (keys: Played[], sr: number, n: number, o: Opts, seed: number): Out => {+ const out = out0(n), width = num(o, "width", 0.5), ratio = num(o, "ratio", 3.5), sorted = byTime(keys), strike = strikeCounter();+ sorted.forEach((k, idx) => {+ const i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const nv = noteVar(seed, idx, k, { cents: 1, db: 0.6, bright: 0.1, decay: 0.08 }, strike(k.p)), v = clamp(k.v, 0.02, 1);+ const f = mtof(k.p) * Math.pow(2, nv.cents / 1200), ta = clamp(2.2 * Math.pow(440 / f, 0.4), 0.5, 6) * nv.decay, ti = ta * 0.25, I0 = (1.2 + 2.4 * v) * nv.bright, g = Math.pow(v, 1.3) * 0.26 * nv.gain;+ const len = Math.min(n - i0, Math.ceil(ta * 7 * sr)), p = pitchPan(k.p, width), [gl, gr] = pan(p);+ const pm = nv.phase(), pt = nv.phase(), dA = Math.pow(2, 0.9 / 1200), dB = Math.pow(2, -0.9 / 1200), w = (TAU * f) / sr;+ const eA = Math.exp(-1 / (ta * sr)), eI = Math.exp(-1 / (ti * sr)), eT = Math.exp(-1 / (ta * 0.5 * sr));+ let a = 1, I = I0, tA = 0.3;+ for (let i = 0; i < len; i++) {+ const t = i * w, mod = I * Math.sin(ratio * t + pm), atk = Math.min(1, i / (0.0007 * sr));+ const y = (0.5 * Math.sin(t * dA + mod) + 0.5 * Math.sin(t * dB + mod * 0.97) + tA * Math.sin(2.4 * t + pt)) * a * atk * g;+ out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; a *= eA; I *= eI; tA *= eT;+ }+ });+ return out;+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/keysOrgan.ts b/skills/anidoodle/engine/src/canvas-core/music/keysOrgan.tsnew file mode 100644index 0000000..2380492--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/keysOrgan.ts@@ -0,0 +1,118 @@+// Organs.+// TONEWHEEL (B3-style): 9 drawbars (16' 5 1/3' 8' 4' 2 2/3' 2' 1 3/5' 1 1/3' 1'). Each drawbar reads a+// tonewheel of the nearest EQUAL-TEMPERED note (so the "5th" and "3rd" harmonics are 2 and 14 cents off+// just, as on the real gear), with the top-octave foldback. The 91 wheels spin all the time: a wheel's+// phase is global, so two keys sharing a wheel add coherently and no two strikes start alike. Each key's+// 9 busbar contacts close a fraction of a ms apart (key click), plus optional single-trigger percussion,+// a tube preamp (2x oversampled, slightly asymmetric) and a Leslie: 800 Hz crossover, horn and drum+// rotating at their own speeds (chorale 0.83/0.7 Hz, tremolo 6.7/5.9 Hz) with Doppler (modulated delay),+// amplitude and two mics 90 degrees apart.+// PIPE (church): ranks voiced from MEASURED VCSL pipe spectra (keysTables.ts): the open principal chorus+// (plenum) or the stopped flute; every pipe has its own fixed detune (ranks beat against each other),+// speech = harmonics building up at their own rates (higher later, bigger pipes slower) + a "chiff" of+// wind noise at the upper harmonics, a steady flue breath, a small wind-sag when many pipes open.+import { TAU, clamp, pan, SVF, gauss } from "./dsp";+import { rng as mkRng } from "../core";+import type { Played } from "./perform";+import { type Out, type Opts, num, str, out0, mtof, dbA, noteVar, noiseBurst, byTime, shape2x, dcBlock } from "./keysCore";+import { PIPE_PLENUM, PIPE_FLUTE } from "./keysTables";++// ---------------------------------------------------------------- shared sine table (fast, deterministic)+const TN = 4096, SIN = new Float64Array(TN + 1); for (let i = 0; i <= TN; i++) SIN[i] = Math.sin((TAU * i) / TN);+const sinT = (ph: number) => { let x = ph - Math.floor(ph); x *= TN; const i = x | 0, f = x - i; return SIN[i] + (SIN[i + 1] - SIN[i]) * f; }; // ph in cycles++// ---------------------------------------------------------------- tonewheel+const FOOT = [-12, 7, 0, 12, 19, 24, 28, 31, 36];+/** legacy `bright` (1 = default) maps onto a registration; `drawbars` ("888000000") overrides it. */+const registration = (o: Opts) => {+ if (typeof o.drawbars === "string" && /^[0-8]{9}$/.test(o.drawbars as string)) return (o.drawbars as string).split("").map(Number);+ const b = num(o, "bright", 1);+ return b < 0.7 ? [8, 0, 8, 4, 0, 0, 0, 0, 0] : b < 1.15 ? [8, 6, 8, 5, 2, 2, 0, 0, 0] : [8, 8, 8, 6, 3, 4, 0, 2, 3];+};+export const tonewheel = (keys: Played[], sr: number, n: number, o: Opts, seed: number): Out => {+ const reg = registration(o), raw = reg.map((d) => (d === 0 ? 0 : dbA(-3 * (8 - d)))), norm = 1 / Math.sqrt(raw.reduce((a, x) => a + x * x, 0) || 1), gains = raw.map((x) => x * norm), sorted = byTime(keys); // registration changes colour, not loudness+ const wr = mkRng(seed * 17 + 1), wheelPh = Array.from({ length: 128 }, () => wr());+ const mono = new Float64Array(n), click = num(o, "click", 0.5), perc = str(o, "perc", "off");+ const heldAt = (t: number) => sorted.some((k) => k.t < t - 0.002 && k.off > t);+ sorted.forEach((k, idx) => {+ const i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const nv = noteVar(seed, idx, k, { db: 0.3 }), iEnd = Math.min(n, Math.round(k.off * sr) + Math.round(0.012 * sr));+ const g = 0.068 * k.v * nv.gain; // an organ key has no velocity: the expression (swell) pedal follows the dynamics+ for (let d = 0; d < 9; d++) {+ if (!gains[d]) continue;+ let w = k.p + FOOT[d]; while (w > 108) w -= 12; while (w < 24) w += 12; // foldback into the 91 wheels+ const f = mtof(w), inc = f / sr, a = gains[d] * g, ph0 = wheelPh[w];+ const on = i0 + Math.round(nv.r() * 0.0012 * sr), off = iEnd - Math.round(nv.r() * 0.0015 * sr); // busbar contacts close/open at slightly different times+ for (let i = on; i < off; i++) { const ph = ph0 + inc * i; mono[i] += a * (sinT(ph) + 0.02 * sinT(3 * ph)); }+ }+ if (click > 0) { noiseBurst(mono, i0, Math.round(0.003 * sr), 3200, 0.7, 0.05 * click * g / 0.068, nv.r, sr, 0.0009); if (iEnd < n) noiseBurst(mono, iEnd - Math.round(0.012 * sr), Math.round(0.002 * sr), 2500, 0.7, 0.025 * click * g / 0.068, nv.r, sr, 0.0006); }+ if (perc !== "off" && !heldAt(k.t)) { // single-trigger percussion: only a detached key fires it+ const w = k.p + (perc === "3rd" ? 19 : 12), f = mtof(w), dec = Math.exp(-1 / (0.25 * sr)); let e = 0.12 * g / 0.068;+ for (let i = i0; i < iEnd; i++) { mono[i] += e * sinT(wheelPh[Math.min(127, w)] + (f / sr) * i); e *= dec; }+ }+ });+ // tube preamp+ const drive = num(o, "drive", 1.3); shape2x(mono, (x) => Math.tanh(drive * (x + 0.08 * x * x)) / drive); dcBlock(mono, sr, 10);+ const out = out0(n), speed = num(o, "trem", 1) === 0 ? "off" : str(o, "leslie", "slow");+ if (speed === "off") { const [gl, gr] = pan(num(o, "pan", 0)); for (let i = 0; i < n; i++) { out.L[i] = mono[i] * gl; out.R[i] = mono[i] * gr; } return out; }+ // Leslie: crossover, two rotors, Doppler + AM + mic pair+ const lo = new Float64Array(n), hi = new Float64Array(n), xl = new SVF(sr, 800, 0.707);+ for (let i = 0; i < n; i++) { xl.tick(mono[i]); lo[i] = xl.lp; hi[i] = mono[i] - xl.lp; }+ const [hornHz, drumHz] = speed === "fast" ? [6.7, 5.9] : [0.83, 0.7];+ const rotor = (x: Float64Array, hz: number, depthMs: number, am: number, ph0: number, g: number) => {+ const D = Math.ceil(0.004 * sr), line = new Float64Array(D * 4 + 8), mask = line.length;+ for (let i = 0; i < n; i++) {+ line[i % mask] = x[i];+ const th = (TAU * hz * i) / sr + ph0;+ for (const [ch, off] of [[0, 0], [1, Math.PI / 2]] as const) {+ const s = Math.sin(th + off), dl = (D + s * depthMs * 0.001 * sr), di = Math.floor(dl), fr = dl - di;+ const a = line[(i - di + mask * 4) % mask], b = line[(i - di - 1 + mask * 4) % mask], y = (a + (b - a) * fr) * (1 + am * s) * g;+ if (ch === 0) out.L[i] += y; else out.R[i] += y;+ }+ }+ };+ rotor(hi, hornHz, 0.35, 0.35, ((seed * 0.618) % 1) * TAU, 0.36);+ rotor(lo, drumHz, 0.12, 0.12, ((seed * 0.382) % 1) * TAU, 0.38);+ return out;+};++// ---------------------------------------------------------------- pipe organ+export const pipeOrgan = (keys: Played[], sr: number, n: number, o: Opts, seed: number): Out => {+ const stops = str(o, "stops", num(o, "bright", 1) < 0.7 ? "flute" : num(o, "bright", 1) > 1.15 ? "full" : "principal");+ const ranks: { spec: [number, number][]; oct: number; g: number }[] =+ stops === "flute" ? [{ spec: PIPE_FLUTE, oct: 0, g: 1 }] : stops === "full" ? [{ spec: PIPE_PLENUM, oct: 0, g: 1 }, { spec: PIPE_FLUTE, oct: -12, g: 0.55 }, { spec: PIPE_FLUTE, oct: 0, g: 0.4 }] : [{ spec: PIPE_PLENUM, oct: 0, g: 1 }, { spec: PIPE_FLUTE, oct: 0, g: 0.35 }];+ const out = out0(n), sorted = byTime(keys), pr = mkRng(seed * 29 + 5);+ const pipeDetune = new Map<number, number>(); const detOf = (key: number) => { if (!pipeDetune.has(key)) pipeDetune.set(key, (pr() - 0.5) * 3); return pipeDetune.get(key)!; };+ // wind load: how many pipes are speaking, smoothed (the reservoir sags a little under a big chord)+ const ctl = Math.ceil(n / 64) + 2, load = new Float64Array(ctl);+ for (const k of sorted) { const a = Math.floor((k.t * sr) / 64), b = Math.min(ctl - 1, Math.ceil((k.off * sr) / 64)); for (let j = Math.max(0, a); j < b; j++) load[j] += ranks.length; }+ { const kk = 1 - Math.exp(-64 / (0.08 * sr)); let z = 0; for (let j = 0; j < ctl; j++) { z += kk * (load[j] - z); load[j] = z; } }+ const trem = num(o, "trem", 0), tremPh = pr() * TAU;+ sorted.forEach((k, idx) => {+ const i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const nv = noteVar(seed, idx, k, { db: 0.3 }), iOff = Math.round(k.off * sr), rel = 0.045, iEnd = Math.min(n, iOff + Math.round(rel * 6 * sr));+ const g = 0.074 * (0.6 + 0.4 * k.v) * nv.gain, [gl, gr] = pan((k.p % 2 ? 1 : -1) * (0.15 + 0.25 * clamp(Math.abs(k.p - 60) / 30, 0, 1))); // pipes stand on C and C# chests, bigger pipes at the ends+ for (const rk of ranks) {+ const m = k.p + rk.oct, f0 = mtof(m) * Math.pow(2, detOf(m * 8 + ranks.indexOf(rk)) / 1200), big = Math.pow(262 / f0, 0.5);+ for (const [h, db] of rk.spec) {+ const f = f0 * h; if (f > sr * 0.45) continue;+ const a = dbA(db) * rk.g * g, tau = (0.012 + 0.03 * big) * (1 + 0.15 * h), ph0 = pr();+ const riseK = Math.exp(-1 / (tau * sr)), relK = Math.exp(-1 / (rel * sr));+ let env = 0, ph = ph0;+ for (let i = i0; i < iEnd; i++) {+ env = i < iOff ? 1 - (1 - env) * riseK : env * relK;+ const sag = 1 - 0.00012 * load[(i / 64) | 0], tr = trem > 0 ? 1 + 0.004 * Math.sin((TAU * trem * i) / sr + tremPh) : 1;+ ph += (f * sag * tr) / sr;+ const y = a * env * sinT(ph); out.L[i] += y * gl; out.R[i] += y * gr;+ }+ }+ // chiff: wind noise at the upper harmonics while the pipe speaks, then the steady flue breath+ const tmp = new Float64Array(Math.min(n - i0, Math.round(0.09 * sr)));+ noiseBurst(tmp, 0, tmp.length, f0 * (3 + 2 * nv.r()), 4, 0.25 * rk.g * g, nv.r, sr, 0.018 + 0.02 * big);+ for (let i = 0; i < tmp.length; i++) { out.L[i0 + i] += tmp[i] * gl; out.R[i0 + i] += tmp[i] * gr; }+ const bp = new SVF(sr, Math.min(f0 * 2, 9000), 3), br = mkRng(seed * 7 + idx * 13 + m);+ for (let i = i0; i < Math.min(iOff, n); i++) { bp.tick(gauss(br)); const y = bp.bp * 0.012 * rk.g * g; out.L[i] += y * gl; out.R[i] += y * gr; }+ }+ });+ return out;+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/keysPiano.ts b/skills/anidoodle/engine/src/canvas-core/music/keysPiano.tsnew file mode 100644index 0000000..f48086b--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/keysPiano.ts@@ -0,0 +1,239 @@+// Piano v2: a modal piano whose spectrum, inharmonicity and decays are MEASURED (keysTables.ts,+// fitted from the CC0 VCSL Steinway B) instead of guessed. Every sample is still synthesized.+//+// strings f_n = n f0 sqrt(1 + B n^2), B per key from the Steinway fit (1.3e-4 in the bass,+// 3.5e-4 at C4, 1.2e-3 at C5, 1.1e-2 at C7), stretched octaves (Railsback)+// hammer the attack spectrum per key AND per velocity is the measured envelope (p/mf/ff layers,+// interpolated), so a harder blow is brighter the way a Steinway is; the strike point+// (~1/8.5 of the string, per key) notches its own partials; contact time 0.7-4 ms+// unisons 1-3 strings per key, detuned 0.3-2 c: a fast "prompt" decay and a slow, beating+// "aftersound", both T60s and the aftersound level fitted per register+// phantoms longitudinal sum partials in the bass (f_i + f_j, -34 dB, louder at ff)+// body a dense soundboard (hundreds of modes, 60 Hz-7 kHz, T60 40-350 ms) rung by each hammer+// blow, plus the key/keybed thump and the hammer's contact noise; all seeded per note+// dampers felt lands on key-up (or pedal-up): fast decay by register + felt noise + key-return tick+// pedal dampers off; strings whose partials coincide ring in sympathy; damper-lift whoosh and+// pedal-up thud; the pedal halo feeds the room+// anti-clone per note: phase jitter, +-0.6 dB, +-5 % brightness, +-6 % decay, micro-detune of the unisons,+// round-robin noises. Same seed = same samples.+// Variants (opts.variant): grand (default), felt (felt strip between hammer and string: dark, soft,+// close and noisy), upright (shorter strings: more inharmonic, shorter sustain, boxy mids),+// honky (upright with unisons 6-14 c apart, bright hammers).+import { TAU, clamp, pan, SVF, gauss } from "./dsp";+import { rng as mkRng } from "../core";+import type { KeyPress, PedalSpan } from "./piano";+import { GRAND_ENV, GRAND_LAYER_V, GRAND_DECAY, PIANO_BANDS } from "./keysTables";+import { partial, noiseBurst, dbA, strikeCounter, type Opts } from "./keysCore";++export type PianoVariant = "grand" | "felt" | "upright" | "honky";+type Voicing = { bMul: number; promptMul: number; afterMul: number; detuneC: [number, number]; tilt: (f: number, v: number) => number; contactMs: (v: number) => number; knock: number; noise: number; board: number; width: number; level: number };++const LOG_BANDS = PIANO_BANDS.map(Math.log);+const lerp = (a: number, b: number, x: number) => a + (b - a) * x;+const interpBands = (row: number[], f: number) => {+ const lf = Math.log(f);+ if (lf <= LOG_BANDS[0]) return row[0];+ for (let i = 1; i < LOG_BANDS.length; i++) if (lf <= LOG_BANDS[i]) return lerp(row[i - 1], row[i], (lf - LOG_BANDS[i - 1]) / (LOG_BANDS[i] - LOG_BANDS[i - 1]));+ return row[row.length - 1] - 24 * Math.log2(f / PIANO_BANDS[PIANO_BANDS.length - 1]);+};+/** One measured row's envelope at velocity v (layers interpolated; extrapolated gently past p and ff). */+const rowAtV = (layers: Record<number, number[]>, v: number) => {+ const ks = Object.keys(layers).map(Number).sort(), vs = ks.map((k) => GRAND_LAYER_V[k]);+ const at = (i: number) => layers[ks[i]];+ const out: number[] = [];+ for (let b = 0; b < PIANO_BANDS.length; b++) {+ let y: number;+ if (v <= vs[0]) { const lo = at(0)[b], hi = at(ks.length - 1)[b], slope = (hi - lo) / (vs[vs.length - 1] - vs[0]); y = lo - Math.min(22, slope * (vs[0] - v) * 0.9); }+ else if (v >= vs[vs.length - 1]) { const lo = at(0)[b], hi = at(ks.length - 1)[b], slope = (hi - lo) / (vs[vs.length - 1] - vs[0]); y = hi + Math.min(6, slope * (v - vs[vs.length - 1]) * 0.5); }+ else { let i = 0; while (v > vs[i + 1]) i++; y = lerp(at(i)[b], at(i + 1)[b], (v - vs[i]) / (vs[i + 1] - vs[i])); }+ out.push(Math.min(0, y));+ }+ return out;+};+/** Envelope bands for key m at velocity v, interpolated between the measured keys. */+const envBands = (m: number, v: number) => {+ const T = GRAND_ENV;+ if (m <= T[0][0]) return rowAtV(T[0][2], v);+ if (m >= T[T.length - 1][0]) return rowAtV(T[T.length - 1][2], v);+ let i = 0; while (m > T[i + 1][0]) i++;+ const a = rowAtV(T[i][2], v), b = rowAtV(T[i + 1][2], v), x = (m - T[i][0]) / (T[i + 1][0] - T[i][0]);+ return a.map((y, j) => lerp(y, b[j], x));+};+const tableAt = (m: number, col: number, T: number[][]) => {+ if (m <= T[0][0]) return T[0][col];+ if (m >= T[T.length - 1][0]) return T[T.length - 1][col];+ let i = 0; while (m > T[i + 1][0]) i++;+ const x = (m - T[i][0]) / (T[i + 1][0] - T[i][0]);+ return col === 3 ? lerp(T[i][col], T[i + 1][col], x) : Math.exp(lerp(Math.log(T[i][col]), Math.log(T[i + 1][col]), x));+};+/** Inharmonicity by key: the Steinway fit, log-interpolated. */+export const measuredB = (m: number) => {+ const T = GRAND_ENV;+ if (m <= T[0][0]) return T[0][1];+ if (m >= T[T.length - 1][0]) return T[T.length - 1][1] * Math.pow(2, (m - T[T.length - 1][0]) / 12 * 1.1);+ let i = 0; while (m > T[i + 1][0]) i++;+ const x = (m - T[i][0]) / (T[i + 1][0] - T[i][0]);+ return Math.exp(lerp(Math.log(T[i][1]), Math.log(T[i + 1][1]), x));+};++const VOICINGS: Record<PianoVariant, Voicing> = {+ grand: { bMul: 1, promptMul: 1, afterMul: 1, detuneC: [0.3, 1.8], tilt: () => 0, contactMs: (v) => 4.2 - 3.3 * v, knock: 1, noise: 1, board: 1, width: 0.55, level: 1 },+ // felt strip: the felt eats the hammer's highs (-12 dB/oct above ~0.6-1.4 kHz), a soft, slow contact, and the+ // mechanism right in the microphone+ felt: { bMul: 1, promptMul: 0.9, afterMul: 0.85, detuneC: [0.3, 1.6], tilt: (f, v) => -12 * Math.max(0, Math.log2(f / (600 + 800 * v))), contactMs: (v) => 8 - 3 * v, knock: 2.6, noise: 3.2, board: 1.2, width: 0.35, level: 1.25 },+ // shorter, stiffer strings on a smaller board: more inharmonic, less bass, a boxy 1-2 kHz, a shorter ring+ upright: { bMul: 1.8, promptMul: 0.75, afterMul: 0.5, detuneC: [0.8, 3], tilt: (f) => -6 * Math.max(0, Math.log2(110 / f)) + 3 * Math.exp(-Math.pow(Math.log2(f / 1400), 2) * 2), contactMs: (v) => 3.4 - 2.6 * v, knock: 1.4, noise: 1.4, board: 1.5, width: 0.3, level: 1.1 },+ honky: { bMul: 2, promptMul: 0.7, afterMul: 0.45, detuneC: [6, 14], tilt: (f) => -6 * Math.max(0, Math.log2(110 / f)) + 4 * Math.exp(-Math.pow(Math.log2(f / 2000), 2) * 1.5), contactMs: (v) => 2.2 - 1.6 * v, knock: 1.6, noise: 1.5, board: 1.5, width: 0.3, level: 1.05 },+};++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);+/** 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]; };++/** The soundboard: a dense modal impulse response (seeded per instrument), rung by every hammer blow. */+const boardIR = (sr: number, seed: number, soft: boolean) => {+ const r = mkRng(seed * 977 + (soft ? 5 : 3)), len = Math.round(0.35 * sr), ir = new Float64Array(len);+ const N = 420;+ for (let k = 0; k < N; k++) {+ const u = (k + r()) / N, f = 60 * Math.pow(7000 / 60, Math.pow(u, 0.8)); // denser towards the top (modal density rises with f)+ const t60 = clamp(0.35 * Math.pow(120 / f, 0.5) * (0.6 + 0.8 * r()), 0.04, 0.35), sig = 6.91 / t60;+ const a = ((r() < 0.5 ? -1 : 1) * (0.4 + r())) / Math.sqrt(1 + Math.pow(f / (soft ? 900 : 2600), 2)) / Math.pow(f / 200, 0.25);+ const w = (TAU * f) / sr, cw = Math.cos(w), sw = Math.sin(w), d = Math.exp(-sig / sr);+ let c = 0, s = a, end = Math.min(len, Math.ceil((t60 * 1.2) * sr));+ for (let i = 0; i < end; i++) { ir[i] += c; const c2 = (c * cw - s * sw) * d; s = (c * sw + s * cw) * d; c = c2; }+ }+ let pk = 1e-9; for (let i = 0; i < len; i++) pk = Math.max(pk, Math.abs(ir[i]));+ for (let i = 0; i < len; i++) ir[i] /= pk;+ return ir;+};++export const renderPianoV2 = (keys: KeyPress[], pedal: PedalSpan[], sr: number, n: number, opts: Opts, seed: number) => {+ const variant = (["grand", "felt", "upright", "honky"].includes(String(opts.variant)) ? opts.variant : "grand") as PianoVariant;+ const V = VOICINGS[variant], width = typeof opts.width === "number" ? (opts.width as number) : V.width;+ const L = new Float32Array(n), R = new Float32Array(n), halo = new Float32Array(n);+ const usePedal = opts.pedal !== false;+ 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; };+ const sorted = keys.slice().sort((a, b) => a.t - b.t || a.p - b.p);+ const maxLen = Math.min(n, Math.ceil(40 * sr));+ const buf = new Float64Array(maxLen), mech = new Float64Array(Math.ceil(0.5 * sr));+ const irHard = boardIR(sr, seed, false), irSoft = boardIR(sr, seed, true);+ const nyq = Math.min(0.45 * sr, 16000), strike = strikeCounter();++ sorted.forEach((k, idx) => {+ const m = k.p, v = clamp(k.v, 0.02, 1), i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const keyR = mkRng(m * 7919 + seed * 13 + 1); // per-KEY constants (tuning, strike point): the same key keeps its strings+ const nr = mkRng((seed * 104729 + idx * 7919 + m * 31 + Math.round(k.t * 1e3)) >>> 0); // per-NOTE variation+ const g = () => clamp(gauss(nr), -2.5, 2.5), sk = strike(m), seq = 2 * ((((m * 0.1234 + seed * 0.577) % 1) + (sk + 1) * 0.6180339887) % 1) - 1;+ const f0 = 440 * Math.pow(2, (m - 69) / 12 + stretchCents(m) / 1200);+ const B = measuredB(m) * V.bMul, S = nStrings(m);+ const [d0, d1] = V.detuneC, spread = d0 + (d1 - d0) * keyR();+ const detune = Array.from({ length: S }, (_, s) => (S === 1 ? 0 : ((s - (S - 1) / 2) / ((S - 1) / 2)) * spread * 0.5 + (seq * 0.25 + g() * 0.05) * (s - (S - 1) / 2)) / 1200 * Math.LN2);+ const beta = 1 / (8.2 + 1.2 * keyR()) + (m > 80 ? -0.015 * (m - 80) / 28 : 0);+ const brightV = clamp(v * (1 + g() * 0.05), 0.02, 1);+ const bands = envBands(m, brightV);+ const decVar = 1 + g() * 0.06, gainVar = dbA(g() * 0.6);+ const t60p = tableAt(m, 1, GRAND_DECAY) * V.promptMul * decVar, t60a = tableAt(m, 2, GRAND_DECAY) * V.afterMul * decVar, a0 = tableAt(m, 3, GRAND_DECAY);+ const sigP0 = 6.91 / t60p, sigA0 = 6.91 / t60a, wa = dbA(a0);+ // when does the felt land?+ let damp = pedalAt(k.off) ? pedalUpAfter(k.off) : k.off;+ if (m >= 89 && variant !== "upright" && variant !== "honky") damp = Infinity; // no dampers on the top keys of a grand+ for (let j = idx + 1; j < sorted.length; j++) if (sorted[j].p === m && sorted[j].t > k.t) { damp = Math.min(damp, sorted[j].t + 0.004); break; }+ const tDamp = (variant === "upright" || variant === "honky" ? 0.12 : 0.08) + 0.45 * clamp((60 - m) / 36, 0, 1), sigD = 6.91 / tDamp;+ const dampI = damp === Infinity ? Infinity : Math.round((damp - k.t) * sr);+ const natural = Math.round(Math.min(t60a * 1.1, 40) * sr);+ const len = Math.min(maxLen, n - i0, dampI === Infinity ? natural : Math.min(natural, dampI + Math.round(tDamp * 1.6 * sr) + 1));+ if (len <= 0) return;+ 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);+ // 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[] = [];+ let aMax = 1e-9;+ for (let p = 1; p <= 80; p++) {+ const fn = p * f0 * Math.sqrt(1 + B * p * p); if (fn > nyq) break;+ const comb = 0.3 + 0.7 * Math.abs(Math.sin(Math.PI * p * beta)); // the table is the upper envelope (notches smoothed out), so the strike comb only carves partway+ const db = interpBands(bands, fn) + V.tilt(fn, v);+ const A = dbA(db) * (p > 4 ? comb : 0.5 + 0.5 * comb);+ amps.push(A); freqs.push(fn); if (A > aMax) aMax = A;+ }+ for (let q = 0; q < amps.length; q++) {+ const A = amps[q] / aMax, fn = freqs[q]; if (A < 3e-5) continue;+ const floorRel = clamp(3e-5 / A, 1e-4, 0.3);+ const sp = sigP0 * (1 + fn / 1500), sa = sigA0 * (1 + fn / 4000); // fitted: the prompt sound's loss climbs ~1x per 1.5 kHz, the aftersound's barely+ const ph = g() * 0.2 + seq * 0.3; // sine start: the string is at rest when the hammer lands; jitter = no two strikes alike+ const waP = clamp(wa * dbA(-4 * Math.max(0, Math.log2(fn / 2000))) * (1 + 0.3 * g()), 0.003, 0.5); // fitted: upper partials keep a -25..-33 dB aftersound+ partial(nb, 0, fn * tension, A * (1 - waP), sp, ph, sr, dampI, sigD, floorRel);+ if (S > 1 && q < 16) for (let s = 0; s < S; s++) partial(nb, 0, fn * Math.exp(detune[s]), (A * waP) / S, sa * (1 + 0.04 * s), ph + 0.9 * g(), sr, dampI, sigD, floorRel); // the aftersound grows out of phase (and a restrike lands on moving strings)+ else if (S > 1) { partial(nb, 0, fn * Math.exp(detune[0]), (A * waP) / 2, sa, ph, sr, dampI, sigD, floorRel); partial(nb, 0, fn * Math.exp(detune[S - 1]), (A * waP) / 2, sa * 1.05, ph, sr, dampI, sigD, floorRel); }+ else { partial(nb, 0, fn, (A * waP) * 0.6, sa, ph, sr, dampI, sigD, floorRel); partial(nb, 0, fn * Math.pow(2, 0.12 / 1200), (A * waP) * 0.4, sa * 1.1, ph, sr, dampI, sigD, floorRel); } // two polarisations+ }+ // phantom partials: longitudinal string motion, sum frequencies of low transverse pairs (bass and tenor)+ if (m < 64) for (let a = 1; a <= 5; a++) for (let b = a; b <= 6; b++) {+ if (a - 1 >= freqs.length || b - 1 >= freqs.length) continue;+ const f = freqs[a - 1] + freqs[b - 1]; if (f > nyq) continue;+ const A = Math.sqrt((amps[a - 1] / aMax) * (amps[b - 1] / aMax)) * dbA(-36 + 10 * v) * (1 - (m - 21) / 50);+ partial(nb, 0, f, A, sigP0 * (1 + f / 1500) * 1.3, g() * 0.3, sr, dampI, sigD, 1e-3);+ }+ // hammer contact: a raised-cosine ramp over the contact time (a gentle low-pass on the attack alone)+ const ramp = Math.max(2, Math.round((V.contactMs(v) * Math.pow(262 / f0, 0.15) * (1 + g() * 0.05)) / 1000 * sr));+ for (let i = 0; i < ramp && i < len; i++) buf[i] *= 0.5 - 0.5 * Math.cos((Math.PI * i) / ramp);+ const norm = 0.2 * loud * gainVar * V.level * dbA(regTrim(m) - 8 * Math.max(0, 0.6 - v)); // below mf the measured (darker) spectrum alone under-drops the level: the listened legacy dynamic range+ // mechanism: keybed thump, hammer contact noise, soundboard knock (round-robin: each strike its own noise and gains)+ const ml = Math.min(mech.length, len); mech.fill(0);+ const thumpF = 70 + 40 * nr(), thumpW = (TAU * thumpF) / sr;+ for (let i = 0; i < Math.min(ml, Math.round(0.05 * sr)); i++) mech[i] += Math.sin(thumpW * i) * Math.exp(-i / (0.014 * sr)) * 0.012 * V.knock * Math.pow(v, 1.3);+ noiseBurst(mech, 0, Math.round((0.0015 + 0.0015 * (1 - v)) * sr), 2200 + 2000 * v, 0.7, 0.02 * V.noise * v * v, nr, sr);+ const bw = 0.05 * V.board * Math.pow(v, 1.2) * (0.8 + 0.4 * nr()) * (m < 48 ? 1.4 : m > 84 ? 0.7 : 1), hard = clamp(v * v, 0, 1), sh = Math.round(nr() * 40);+ for (let i = 0; i < ml && i + sh < irHard.length; i++) mech[i] += (irHard[i + sh] * hard + irSoft[i + sh] * (1 - hard)) * bw * Math.min(1, i / 24);+ for (let i = 0; i < ml; i++) buf[i] += mech[i];+ // felt landing on the strings, and the key coming back up (the tick is heard even under the pedal)+ if (dampI !== Infinity && dampI < len) {+ const sv = new SVF(sr, 420 + 200 * nr(), 0.7), dl = Math.min(len - dampI, Math.round(0.08 * sr));+ for (let i = 0; i < dl; i++) buf[dampI + i] += sv.tick(gauss(nr)) * Math.sin((Math.PI * i) / dl) * 0.004 * V.noise * v;+ }+ const upI = Math.round((k.off - k.t) * sr);+ if (upI > 0 && upI < len) noiseBurst(nb, upI, Math.round(0.012 * sr), 900 + 500 * nr(), 1.2, 0.0025 * V.noise * (0.4 + v), nr, sr);+ // stereo: bass left, treble right (the player's seat) + a sub-ms time offset by key position (spaced pair)+ const [gl, gr] = pan(clamp((m - 62) / 34, -1, 1) * width), itd = Math.round(((m - 64) / 44) * 0.00025 * sr);+ const inPedal = pedalAt(k.t) || pedalAt(k.t + 0.25);+ for (let i = 0; i < len; i++) {+ const s = buf[i] * norm, j = i0 + i;+ const jl = j + Math.max(0, itd), jr = j + Math.max(0, -itd);+ if (jl < n) L[jl] += s * gl; if (jr < n) R[jr] += s * gr;+ if (inPedal) halo[j] += s;+ }+ // sympathetic strings: open strings (pedal down) whose partials coincide with this note's ring+ if (usePedal && inPedal) {+ const up = pedalUpAfter(k.t + 0.25), endI = Math.min(n - i0, Math.round((up - k.t) * sr) + Math.round(0.3 * sr), Math.round(10 * sr));+ for (const [off, hg, hn, cpl] of [[-12, 2, 1, 0.07], [-19, 3, 1, 0.05], [-24, 4, 1, 0.035], [-28, 5, 1, 0.02], [12, 1, 2, 0.05], [19, 1, 3, 0.03], [7, 2, 3, 0.03], [24, 1, 4, 0.02]] as const) {+ const gm = m + off; if (gm < 21 || gm > 108) continue;+ const gf0 = 440 * Math.pow(2, (gm - 69) / 12 + stretchCents(gm) / 1200), gB = measuredB(gm) * V.bMul;+ const f = hg * gf0 * Math.sqrt(1 + gB * hg * hg), noteP = hn * f0 * Math.sqrt(1 + B * hn * hn);+ if (Math.abs(f - noteP) / noteP > 0.004) continue;+ const sig = (6.91 / (tableAt(gm, 2, GRAND_DECAY) * V.afterMul)) * (1 + f / 1500), dec = Math.exp(-sig / sr), decD = Math.exp(-(sig + 25) / sr);+ const [pl, pr] = pan(clamp((gm - 62) / 34, -1, 1) * width), amp = 0.2 * loud * cpl * (hn === 1 ? 1 : 0.5) * gainVar, w = (TAU * f) / sr, rise = Math.exp(-1 / (0.18 * sr));+ let e = 1, gg = 1, c = 1, sn = 0; const cw = Math.cos(w), sw = Math.sin(w), dampStart = Math.round((up - k.t) * sr);+ for (let i = 0; i < endI; i++) { const env = 1 - (e *= rise), o = sn * amp * env * gg; L[i0 + i] += o * pl; R[i0 + i] += o * pr; halo[i0 + i] += o; gg *= i < dampStart ? dec : decD; const c2 = c * cw - sn * sw; sn = c * sw + sn * cw; c = c2; }+ }+ }+ });+ // pedal mechanics: dampers lifting (a soft whoosh of freed strings) and landing (a felt thud)+ if (usePedal && sorted.length && opts.pedalNoise !== false) {+ const pr = mkRng(seed * 31 + 9), tmp = new Float64Array(Math.round(0.2 * sr));+ const lastT = sorted[sorted.length - 1].off + 4;+ for (const [a, b] of pedal) {+ if (a > lastT) continue;+ for (const [t, fc, lenS, gain] of [[a, 700, 0.16, 0.0012], [b, 260, 0.06, 0.0018]] as const) {+ const i0 = Math.round(t * sr); if (i0 >= n || i0 < 0) continue;+ tmp.fill(0); noiseBurst(tmp, 0, Math.round(lenS * sr), fc * (0.8 + 0.4 * pr()), 0.8, gain * V.noise, pr, sr);+ for (let i = 0; i < tmp.length && i0 + i < n; i++) { L[i0 + i] += tmp[i] * 0.9; R[i0 + i] += tmp[i]; }+ }+ }+ }+ return { L, R, halo };+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/keysTables.ts b/skills/anidoodle/engine/src/canvas-core/music/keysTables.tsnew file mode 100644index 0000000..098dd05--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/keysTables.ts@@ -0,0 +1,72 @@+// "Measured physics" for the keys voices: small numeric tables fitted OFFLINE from CC0 recordings.+// Nothing recorded ships or plays: the engine synthesizes every sample; these are only numbers.+//+// PROVENANCE (all tables below unless a table says otherwise)+// Source VCSL, the Versilian Community Sample Library, github.com/sgossner/VCSL, CC0 1.0 Universal+// Fitter tools/keys-fit.py (numpy): comb search + least squares for (f0, B), per-partial Hann DFT+// tracks for levels and two-stage decays, prominence peak picking + T60 slopes for bars+// Date 2026-09-28, track S3 (keys)+// VCSL names its mallet/chime files an octave below the sounding pitch (marimba "C4" sounds 524 Hz);+// the ratios below are relative to the SOUNDING fundamental.++/** Half-octave band centres (Hz) for the piano spectral envelopes. */+export const PIANO_BANDS = [30, 42, 60, 85, 120, 170, 240, 339, 480, 679, 960, 1358, 1920, 2715, 3840, 5431, 7680, 10861, 15360];++/**+ * Steinway B grand, "NoSus Close" layers vl2 (p), vl3 (mf), vl4 (ff), files JHPiano_NoSus_Close_<note>_vl<k>_rr1.wav.+ * Row: [midi, inharmonicity B, { layer: attack level (dB re loudest partial) of the partials at each band }].+ * Envelope = per-partial attack levels (first 150 ms), local-max smoothed above partial 4 so the strike-point+ * notches of that one key do not bleed into its neighbours (the engine adds its own strike comb).+ */+export const GRAND_ENV: [number, number, Record<number, number[]>][] = [+ [24, 0.000218, { 2: [-32, -26, -15, -5, -6, -10, -13, -21, -28, -42, -39, -51, -75, -77, -83, -82, -84, -90, -90], 4: [-36, -26, -13, -3, -7, -7, -6, -6, -9, -7, -9, -13, -37, -53, -48, -58, -90, -90, -90] }],+ [30, 0.000126, { 2: [-29, -29, -18, -3, -5, -3, -2, -16, -20, -30, -37, -52, -61, -68, -74, -71, -74, -82, -90], 4: [-38, -38, -23, -4, -6, -3, 0, -11, -9, -14, -6, -8, -21, -35, -51, -67, -90, -90, -90] }],+ [36, 0.000151, { 2: [-2, -2, -2, -1, 0, -1, -5, -2, -3, -7, -8, -25, -28, -63, -73, -70, -73, -73, -84], 4: [-2, -2, -2, -2, -2, -2, -8, -1, -2, -3, -2, -10, -7, -34, -44, -62, -76, -88, -90] }],+ [42, 0.00016, { 2: [0, 0, 0, 0, 0, 0, -5, -3, -4, -18, -24, -39, -54, -59, -76, -76, -78, -74, -88], 4: [-2, -2, -2, -2, -2, -1, -4, -2, -2, -11, -10, -17, -23, -27, -29, -60, -84, -90, -90] }],+ [48, 0.000125, { 2: [-8, -8, -8, -8, -8, -13, -19, -7, -9, -14, -26, -35, -54, -65, -73, -76, -78, -77, -87], 3: [-10, -10, -10, -10, -10, -14, -18, -7, -9, -14, -19, -23, -28, -37, -49, -70, -90, -90, -90], 4: [-11, -11, -11, -11, -11, -15, -20, -7, -8, -13, -19, -19, -22, -29, -36, -45, -69, -90, -90] }],+ [54, 0.000209, { 2: [-8, -8, -8, -8, -8, -8, -5, -1, -9, -18, -20, -35, -44, -57, -69, -65, -78, -76, -89], 4: [-10, -10, -10, -10, -10, -10, -6, -1, -7, -13, -11, -10, -12, -20, -24, -37, -52, -84, -90] }],+ [60, 0.000353, { 2: [0, 0, 0, 0, 0, 0, 0, -4, -9, -15, -18, -22, -35, -60, -68, -78, -78, -76, -86], 3: [0, 0, 0, 0, 0, 0, 0, -2, -6, -10, -7, -6, -20, -32, -41, -56, -88, -88, -90], 4: [0, 0, 0, 0, 0, 0, 0, -2, -6, -12, -8, -5, -14, -20, -23, -29, -43, -55, -66] }],+ [66, 0.000726, { 2: [0, 0, 0, 0, 0, 0, 0, 0, -1, -3, -12, -26, -30, -33, -57, -53, -79, -78, -89], 4: [0, 0, 0, 0, 0, 0, 0, 0, -1, -2, -6, -16, -18, -21, -25, -26, -53, -61, -70] }],+ [72, 0.0012, { 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, -6, -13, -20, -32, -35, -47, -70, -70, -76, -85], 3: [0, 0, 0, 0, 0, 0, 0, 0, 0, -3, -7, -8, -16, -20, -27, -55, -64, -78, -90], 4: [0, 0, 0, 0, 0, 0, 0, 0, 0, -2, -5, -3, -8, -12, -18, -29, -41, -59, -76] }],+ [78, 0.00191, { 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8, -19, -30, -46, -52, -61, -73, -74, -85], 4: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, -10, -14, -22, -26, -32, -56, -69, -81] }],+ [84, 0.00351, { 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, -21, -32, -45, -50, -69, -76, -88], 4: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -5, -11, -21, -28, -28, -36, -48, -60] }],+ [90, 0.00527, { 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -12, -29, -40, -56, -64, -88, -90], 4: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -13, -29, -38, -49, -54, -64, -78] }],+ [96, 0.011, { 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -12, -29, -51, -71, -76, -83], 4: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -6, -13, -29, -45, -49, -58] }],+];+/** VCSL layer -> our velocity 0..1 (vl1 is not in the Steinway set; vl2 plays like p, vl4 like ff). */+export const GRAND_LAYER_V: Record<number, number> = { 2: 0.35, 3: 0.62, 4: 0.92 };++/**+ * Steinway B decay, fitted per note (median of partials 1-3 over the three layers) and smoothed across+ * neighbours: [midi, prompt T60 s, aftersound T60 s, aftersound level dB re attack]. The prompt sound is+ * the unison strings in phase (energy leaves fast through the bridge); the aftersound is what is left+ * once they drift out of phase (Weinreich 1977). Raw fits: C1 10.5/30, F#1 9.6/39, C2 5.6/67, F#2 2.3/35,+ * C3 6.7/30, F#3 4.6/24, C4 2.1/15, F#4 2.8/15, C5 1.1/14, F#5 0.75/12.5, C6 0.79/6.8, F#6 0.89/5.8, C7 -/4.0.+ */+export const GRAND_DECAY: [number, number, number, number][] = [+ [21, 10, 30, -12], [24, 9.5, 32, -12], [30, 8, 36, -14], [36, 6, 40, -20], [42, 4.6, 34, -21], [48, 4.8, 30, -19],+ [54, 3.8, 24, -21], [60, 2.3, 16, -18], [66, 2.1, 15, -22], [72, 1.2, 13.5, -19], [78, 0.9, 11, -22], [84, 0.8, 7, -23],+ [90, 0.7, 5.5, -25], [96, 0.5, 3.8, -25], [108, 0.35, 2.2, -25],+];++/** Tuned bars and tubes: [ratio to the sounding fundamental, level dB re fundamental, T60 s at the measured pitch]. */+export type ModeRow = [number, number, number];+/** Marimba (rosewood, tuned 1:4:10), Marimba_hit_Outrigger_C2_loud_01 (sounds C3 130.9 Hz): 4.007x -20.4 dB T60 2.5 s, 10.08x -28.8 dB 0.47 s; fundamental T60 8.6 s at 131 Hz, 2.2 s at 525 Hz (C4_med), 0.51 s at 2094 Hz (C6_med). */+export const MARIMBA: ModeRow[] = [[1, 0, 8.6], [4.007, -20.4, 2.5], [10.08, -28.8, 0.47]];+export const MARIMBA_T60_REF_HZ = 131;+/** Vibraphone (aluminium, tuned 1:4:10.4), Vibes_hard_C3_v2 (sounds C4 261.4 Hz): 3.998x -25.6 dB T60 2.9 s, 10.41x -29.2 dB 0.65 s, fundamental 8.5 s. */+export const VIBES: ModeRow[] = [[1, 0, 8.5], [3.998, -25.6, 2.9], [10.41, -29.2, 0.65]];+export const VIBES_T60_REF_HZ = 261;+/** Glockenspiel (steel bars, hard mallets), glock_medium_G4 / glock_loud_C5 / glock_loud_C6, ratios re the sounding fundamental (two octaves over the label). */+export const GLOCK: ModeRow[] = [[1, 0, 8.7], [2.94, -23, 1.3], [3.93, -30, 5.5], [5.62, -20, 1.0], [8.94, -21, 1.6], [11.1, -36, 0.6]];+export const GLOCK_T60_REF_HZ = 1053;+/** Tubular bells, chimes_C4_ff_rr2 (strike note C5 525 Hz is the virtual pitch of modes 3-5, ~2:3:4). */+export const CHIME: ModeRow[] = [[0.632, -14.7, 25], [1.227, 0, 60], [2.0, -15.9, 15], [2.921, 0, 7], [3.977, -5.5, 3.05], [5.142, -14.6, 1.6]];+export const CHIME_T60_REF_HZ = 525;+/**+ * Pipe organ, VCSL "Pipe Organ" (harmonic levels dB re the loudest, from the peak-picked spectrum of the steady tone):+ * PLENUM Rode_Man3Open_C4 (open principal chorus with mixture): harmonics 1-16+ * FLUTE NT5_Man3Quiet_C4 (stopped flute: odd harmonics lead, 3rd at -10 dB)+ */+export const PIPE_PLENUM: [number, number][] = [[1, -6.7], [2, -2.7], [3, -3.5], [4, 0], [5, -17.2], [6, -4.5], [7, -15.7], [8, -6.2], [10, -17.5], [12, -14.2], [16, -13.5]];+export const PIPE_FLUTE: [number, number][] = [[1, 0], [2, -23.3], [3, -10.2], [4, -26.5], [5, -45.3], [6, -38.3]];diff --git a/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts b/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.tsindex 65ea174..baf63a0 100644--- a/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts@@ -41,7 +41,8 @@ const HATS = Array.from({ length: 16 }, (_, i) => `C4:.25@${[0.85, 0.35, 0.6, 0.// 21 sparkle [the film] · 22-23 breakdown, drums out [the five words] · 24 everything back, Cmaj9// [All in pure code.] · 25 held home [the end card].export const LAUNCH2_BARS = 26;-export const launchLofi2 = (): Piece => {+export const launchLofi2 = (): Piece => shipped(launchLofi2Raw());+const launchLofi2Raw = (): Piece => {const B = LAUNCH2_BARS, last = B - 1, ci = (b: number) => (b < 2 ? -1 : (b - 2) % 4);const bars = (fn: (b: number, c: number) => string | null, role: Role, v: number, extra: { roll?: number } = {}): Note[] => { const out: Note[] = []; for (let b = 0; b < B; b++) { const x = fn(b, ci(b)); if (x) out.push(...L(b * 4, x, role, v, extra)); } return out; };const full: [number, number][] = [[2, 12], [15, 21], [24, 24]], half: [number, number][] = [[13, 14]];@@ -99,9 +100,12 @@ export const launchLofi3Material = (): Material => {],};};-export const launchLofi3 = (): Piece => composePiece(launchLofi3Material());+/** The shipped launch films render with the pre-rebuild voices, bit-for-bit (SOUND-BRIEF legacy freeze); refits and short forms keep the flag. */+const shipped = (p: Piece): Piece => ({ ...p, legacy: true, refit: p.refit && ((s: number) => shipped(p.refit!(s))), shortForm: p.shortForm && (() => shipped(p.shortForm!())) });+export const launchLofi3 = (): Piece => shipped(composePiece(launchLofi3Material()));-export const launchLofi = (): Piece => {+export const launchLofi = (): Piece => shipped(launchLofiRaw());+const launchLofiRaw = (): Piece => {const full: [number, number][] = [[2, 18], [23, 33], [36, 36]], half: [number, number][] = [[19, 22]], last = LAUNCH_BARS - 1;const pad = byBar("accomp", 0.62, (b, ci) => (b === last ? `${PAD[2]}:[email protected]` : ci < 0 ? `${PAD_INTRO[b]}:[email protected]` : `${PAD[ci]}:4`), { roll: 0.03 });const sub = byBar("bass", 0.85, (b, ci) => (ci < 0 || inRanges(b, [[34, 35]]) ? null : b === last ? "C2:4" : b >= 37 ? SUB_HOLD[ci] : SUB[ci]));diff --git a/skills/anidoodle/engine/src/canvas-core/music/plan.ts b/skills/anidoodle/engine/src/canvas-core/music/plan.tsindex c7fd979..44e4002 100644--- a/skills/anidoodle/engine/src/canvas-core/music/plan.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/plan.ts@@ -12,7 +12,7 @@ export const isCompound = (m: Meter) => m === "6/8" || m === "9/8" || m === "12/export type Role = "melody" | "inner" | "bass" | "accomp" | "color" | "drum";/** t, d in beats from the piece start; p = MIDI; v = written velocity 0..1 (performance shapes it). */export type Note = { t: number; d: number; p: number; v: number; role: Role; roll?: number; kind?: string };-export type InstId = "piano" | "musicBox" | "bell" | "celesta" | "marimba" | "vibes" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "pulse" | "triangle" | "noiseDrum" | "kick" | "snare" | "hat" | "bass" | "vinyl" | "warmPad" | "softPluck" | "sub" | "organ" | "brass" | "woodwind" | "choir" | "timpani" | "leadSynth" | "bowedSolo";+export type InstId = "piano" | "musicBox" | "bell" | "celesta" | "marimba" | "vibes" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "pulse" | "triangle" | "noiseDrum" | "kick" | "snare" | "hat" | "bass" | "vinyl" | "warmPad" | "softPluck" | "sub" | "organ" | "brass" | "woodwind" | "choir" | "timpani" | "leadSynth" | "bowedSolo" | "glockenspiel" | "wurlitzer" | "pipeOrgan";export type Part = { id: string; inst: InstId; role: Role; notes: Note[]; gainDb?: number; pan?: number; opts?: Record<string, number | boolean | string>; send?: number };export type Section = {id: string; bars: number; mood: MoodId | [MoodId, MoodId, number]; key: string; mode: ModeId; melody: MelodyType[];@@ -29,6 +29,7 @@ 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 master tone (low-pass, shelf, saturation) */; duck?: { by: string; parts: string[]; depth?: number; release?: number }; tape?: { wowCents?: number; wowHz?: number; flutterCents?: number; flutterHz?: number; drive?: number } };export type Piece = { title: string; plan: MusicPlan; parts: Part[]; harmony: Chord[]; tail: number; seed: number; fx?: PieceFx;+ /** render with the pre-2026-09-28 voices, bit-for-bit (the shipped launch films); everything else gets the rebuilt sound */ legacy?: boolean;/** a shorter complete form of the same music, chosen automatically when the film is too short for this one */ shortForm?: () => Piece;/** rebuild the same music for a film `seconds` long so it still ends on its phrase (lofiElectronic: loop cycles added or removed); `fitScore` calls it before fitToDuration */ refit?: (seconds: number) => Piece;/** composer-facing notes from compose (a line shorter than its section, ...): printed by tools/music.mjs check */ warnings?: string[];diff --git a/skills/anidoodle/engine/src/canvas-core/music/render.ts b/skills/anidoodle/engine/src/canvas-core/music/render.tsindex f9fa296..87abf0c 100644--- a/skills/anidoodle/engine/src/canvas-core/music/render.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/render.ts@@ -5,6 +5,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 * as I from "./instruments";import * as O from "./orchestra";import { room, Biquad, db } from "./dsp";@@ -17,8 +18,9 @@ export type RenderOpts = { expressive?: boolean; piano?: PianoOpts; flatVelocity/** dry = the pre-room mix; wet = the room's late tail (for music-box: its single reflection). Kept so the guards can measure reverb-to-dry per bar. */export type Rendered = { L: Float32Array; R: Float32Array; perf: Performance; tempo: number; gainDb: number; masterMode: string; stems: Record<string, [Float32Array, Float32Array]>; piece: Piece; dry: [Float32Array, Float32Array]; wet: [Float32Array, Float32Array] };-const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) => {+const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number, legacy = false) => {const o = pt.opts ?? {}, r = mkRng(seed);+ if (!legacy) { const kv = keysVoice(pt.inst, keys, sr, n, o, seed); if (kv) return kv; } // S3 keys rebuildswitch (pt.inst) {case "musicBox": return I.musicBox(keys, sr, n, o);case "bell": return I.bell(keys, sr, n, o);@@ -38,6 +40,9 @@ const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) =>case "hat": return I.hat(keys, sr, n, o, r);case "bass": return I.bass(keys, sr, n, o);case "vinyl": return I.vinyl(keys, sr, n, o, r);+ case "glockenspiel": return I.celesta(keys, sr, n, o); // new instruments have no legacy voice: the nearest old one+ case "wurlitzer": return I.ePiano(keys, sr, n, o);+ case "pipeOrgan": return O.organ(keys, sr, n, o);case "warmPad": return warmPad(keys, sr, n, o, r);case "softPluck": return softPluck(keys, sr, n, o);case "sub": return sub(keys, sr, n, o);@@ -53,7 +58,7 @@ const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) =>};export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {- const expressive = o.expressive ?? true, tempo = o.tempo ?? piece.plan.tempo, style = STYLES[piece.plan.style];+ const expressive = o.expressive ?? true, tempo = o.tempo ?? piece.plan.tempo, style = STYLES[piece.plan.style], legacy = piece.legacy === true;const perf = perform(piece, tempo, { expressive, flatVelocity: o.flatVelocity });const n = o.seconds ? Math.round(o.seconds * sr) : Math.ceil((perf.lastOnset + piece.tail) * sr);const L = new Float32Array(n), R = new Float32Array(n), haloL = new Float32Array(n), stems: Record<string, [Float32Array, Float32Array]> = {};@@ -65,8 +70,8 @@ export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rendeif (o.only && !o.only(pt)) return;const keys = perf.parts[pi].keys; if (!keys.length) return;let sL: Float32Array, sR: Float32Array;- if (pt.inst === "piano") { const r = renderPiano(keys, perf.pedal, sr, n, o.piano ?? PIANO_REAL, piece.seed + pi); sL = r.L; sR = r.R; if ((o.piano ?? PIANO_REAL).pedal) for (let i = 0; i < n; i++) haloL[i] += r.halo[i] * db(pt.gainDb ?? 0); }- else { const r = voice(pt, keys, sr, n, piece.seed * 101 + pi); sL = r.L; sR = r.R; }+ if (pt.inst === "piano") { const old = legacy || !!o.piano, r = old ? renderPiano(keys, perf.pedal, sr, n, o.piano ?? PIANO_REAL, piece.seed + pi) : renderPianoV2(keys, perf.pedal, sr, n, pt.opts ?? {}, piece.seed + pi); sL = r.L; sR = r.R; if (old ? (o.piano ?? PIANO_REAL).pedal : pt.opts?.pedal !== false) for (let i = 0; i < n; i++) haloL[i] += r.halo[i] * db(pt.gainDb ?? 0); }+ else { const r = voice(pt, keys, sr, n, piece.seed * 101 + pi, legacy); sL = r.L; sR = r.R; }if (pump && dk!.parts.includes(pt.id)) for (let i = 0; i < n; i++) { sL[i] *= pump[i]; sR[i] *= pump[i]; }const g = db(pt.gainDb ?? 0);if (pt.pan) { const a = Math.max(0, pt.pan), b = Math.max(0, -pt.pan); for (let i = 0; i < n; i++) { sL[i] *= 1 - a * 0.6; sR[i] *= 1 - b * 0.6; } }diff --git a/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts b/skills/anidoodle/engine/src/canvas-core/music/vocabMore.tsindex 0fd49af..5beb112 100644--- a/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts@@ -112,8 +112,8 @@ export const VOCAB_MORE: StyleVocab[] = [melody: { range: "a 10th around the drone", contour: "ornamented steps (grace notes, turns), phrases that return to the drone note", density: "flowing 8ths and 16ths with long held notes", motif: "a modal phrase that grows by adding ornaments on repeats" },arrangement: { shape: "drone alone -> melody free -> percussion enters -> faster, denser -> return to the drone", transitions: "an accelerando, a percussion break", endings: "the melody alone on the tonic over the drone" }, avoid: "copying a traditional melody; Western functional cadences everywhere" },{ id: "choral", name: "choral / sacred", atmosphere: "vast, human, reverent: voices in parts, organ, bells, a slow swell", tempo: [50, 90], meters: ["4/4", "3/4"], swing: [0.5, 0.5],- palette: { chords: V("choir", "accomp", -2, { vowel: "a", attack: 0.5 }, 0.7), lead: V("choir", "melody", 0, { vowel: "o", attack: 0.25, width: 0.3 }, 0.6), bass: V("organ", "bass", -4, { bright: 0.5 }, 0.5), counter: V("fmBell", "color", -8, undefined, 0.7), arp: V("harp", "accomp", -6, undefined, 0.6), perc: V("timpani", "drum", -4, { pitch: 38 }, 0.6), kick: V("timpani", "drum", -6, { pitch: 31, decay: 1.2 }, 0.6) },- alternates: { chords: { organ: V("organ", "accomp", -4, { bright: 0.9 }, 0.6), strings: V("strings", "accomp", -4, { attack: 0.8, release: 1.6 }, 0.6) }, lead: { bowed: V("bowedSolo", "melody", 0, undefined, 0.6), flute: V("woodwind", "melody", -2, undefined, 0.6) } }, fx: {},+ palette: { chords: V("choir", "accomp", -2, { vowel: "a", attack: 0.5 }, 0.7), lead: V("choir", "melody", 0, { vowel: "o", attack: 0.25, width: 0.3 }, 0.6), bass: V("organ", "bass", -4, { bright: 0.5, kind: "pipe" }, 0.5), counter: V("fmBell", "color", -8, undefined, 0.7), arp: V("harp", "accomp", -6, undefined, 0.6), perc: V("timpani", "drum", -4, { pitch: 38 }, 0.6), kick: V("timpani", "drum", -6, { pitch: 31, decay: 1.2 }, 0.6) },+ alternates: { chords: { organ: V("organ", "accomp", -4, { bright: 0.9, kind: "pipe" }, 0.6), strings: V("strings", "accomp", -4, { attack: 0.8, release: 1.6 }, 0.6) }, lead: { bowed: V("bowedSolo", "melody", 0, undefined, 0.6), flute: V("woodwind", "melody", -2, undefined, 0.6) } }, fx: {},stemTargets: T({ chords: -19, lead: -17, bass: -21, counter: -26, arp: -24, perc: -20 }), calibrated: false, grooves: ["pulse"], moods: ["awe", "grief", "hopeful", "tender", "heroic"],harmony: { modes: ["major", "aeolian", "dorian", "lydian"], qualities: "triads in 4 parts, suspensions, the picardy third", tendencies: "chorale motion: I-IV-V-I, vi-IV-I-V, plagal amen (IV-I), deceptive V-vi before the final cadence", rhythm: "one chord per beat or per half bar (chorale), slower in swells", voicing: "SATB spacing: no gaps wider than an octave between upper voices, bass free; avoid parallel 5ths", tension: "4-3 suspensions, a held dominant; release on a plagal amen" },melody: { range: "C4-G5 (singable)", contour: "stepwise, phrase-shaped like breath", density: "1 note per beat or slower", motif: "a hymn-like phrase whose cadence changes each time" },diff --git a/skills/anidoodle/engine/tools/keys-compare.py b/skills/anidoodle/engine/tools/keys-compare.pynew file mode 100644index 0000000..978e765--- /dev/null+++ b/skills/anidoodle/engine/tools/keys-compare.py@@ -0,0 +1,75 @@+#!/usr/bin/env python3+"""Spectral A/B of rendered piano notes vs the CC0 VCSL Steinway B (offline, numpy only).++ python3 tools/keys-compare.py <VCSL root> <probe dir> (probe dir holds old-<note>_vl<k>.wav / v2-<note>_vl<k>.wav)++Per note: partial-envelope error (mean |dB| over partials 1-20 above -60 dB), log-mel distance over the first+3 s (loudness-normalised, dB), spectral-centroid trajectory error (first 2 s, cents), fundamental aftersound T60.+Gate on moving TOWARD the reference, not on matching it (research sec. 9.1).+"""+import importlib.util, os, sys, numpy as np+spec = importlib.util.spec_from_file_location("kf", os.path.join(os.path.dirname(__file__), "keys-fit.py")); kf = importlib.util.module_from_spec(spec); spec.loader.exec_module(kf)++def mel_fb(sr, nfft, nm=48, fmin=40, fmax=12000):+ mel = lambda f: 2595 * np.log10(1 + f / 700); imel = lambda m: 700 * (10 ** (m / 2595) - 1)+ pts = imel(np.linspace(mel(fmin), mel(fmax), nm + 2)); bins = np.fft.rfftfreq(nfft, 1 / sr)+ fb = np.zeros((nm, len(bins)))+ for i in range(nm):+ a, c, b = pts[i], pts[i + 1], pts[i + 2]+ fb[i] = np.clip(np.minimum((bins - a) / (c - a), (b - bins) / (b - c)), 0, None)+ return fb++def logmel(x, sr, secs=3.0):+ x = x[kf.onset(x):][: int(secs * sr)]+ x = np.pad(x, (0, max(0, int(secs * sr) - len(x))))+ nfft, hop = 2048, 882+ fb = mel_fb(sr, nfft)+ frames = [x[i:i + nfft] * np.hanning(nfft) for i in range(0, len(x) - nfft, hop)]+ S = np.abs(np.fft.rfft(np.array(frames), axis=1)) ** 2+ M = 10 * np.log10(fb @ S.T + 1e-10)+ return M - M.max()++def centroid_traj(x, sr, secs=2.0):+ x = x[kf.onset(x):][: int(secs * sr)]+ out = []+ for i in range(0, len(x) - 4096, 2205):+ s = np.abs(np.fft.rfft(x[i:i + 4096] * np.hanning(4096))); f = np.fft.rfftfreq(4096, 1 / sr)+ out.append((s * f).sum() / (s.sum() + 1e-12))+ return np.array(out)++def env(r):+ return np.array([p["rel"] for p in r["partials"][:20]])++if __name__ == "__main__":+ root, probe = sys.argv[1], sys.argv[2]+ ref_dir = os.path.join(root, "Chordophones/Zithers/Grand Piano, Steinway B/NoSus")+ rows = []+ for fn in sorted(os.listdir(probe)):+ if not fn.startswith("v2-") or not fn.endswith(".wav"): continue+ tag = fn[3:-4]; note, vl = tag.split("_")+ ref = os.path.join(ref_dir, f"JHPiano_NoSus_Close_{note}_{vl}_rr1.wav")+ if not os.path.exists(ref): continue+ midi = kf.midi_of(note)+ rr = kf.fit_string(ref, midi); xr, sr = kf.load(ref); Mr = logmel(xr, sr); Cr = centroid_traj(xr, sr)+ res = {}+ for which in ["old", "v2"]:+ p = os.path.join(probe, f"{which}-{tag}.wav")+ if not os.path.exists(p): continue+ r = kf.fit_string(p, midi); x, _ = kf.load(p)+ a, b = env(r), env(rr); k = min(len(a), len(b)); sel = (b[:k] > -60) | (a[:k] > -60)+ envErr = float(np.mean(np.abs(np.maximum(a[:k][sel], -60) - np.maximum(b[:k][sel], -60))))+ Mx = logmel(x, sr); mel = float(np.mean(np.abs(np.maximum(Mx, -80) - np.maximum(Mr, -80))))+ C = centroid_traj(x, sr); kk = min(len(C), len(Cr)); cen = float(np.mean(np.abs(1200 * np.log2(C[:kk] / Cr[:kk]))))+ t60 = [pp["afterDbS"] for pp in r["partials"][:2] if pp["afterDbS"]]+ res[which] = (envErr, mel, cen, -60 / np.mean(t60) if t60 else None, r["B"])+ t60r = [pp["afterDbS"] for pp in rr["partials"][:2] if pp["afterDbS"]]+ rows.append((tag, res, -60 / np.mean(t60r) if t60r else None, rr["B"]))+ print(f"{'note':9} {'env dB old->new':>16} {'log-mel dB old->new':>20} {'centroid c old->new':>21} {'T60 s old/new/ref':>20} B new/ref")+ tot = {"old": np.zeros(3), "v2": np.zeros(3)}+ for tag, res, t60r, Br in rows:+ o, v = res.get("old"), res.get("v2")+ f = lambda x: "-" if x is None else f"{x:.1f}"+ print(f"{tag:9} {o[0]:7.1f} -> {v[0]:5.1f} {o[1]:8.1f} -> {v[1]:6.1f} {o[2]:8.0f} -> {v[2]:6.0f} {f(o[3])}/{f(v[3])}/{f(t60r)} {v[4]:.1e}/{Br:.1e}")+ for w in tot: tot[w] += np.array(res[w][:3])+ n = len(rows)+ print(f"{'MEAN':9} {tot['old'][0]/n:7.1f} -> {tot['v2'][0]/n:5.1f} {tot['old'][1]/n:8.1f} -> {tot['v2'][1]/n:6.1f} {tot['old'][2]/n:8.0f} -> {tot['v2'][2]/n:6.0f}")diff --git a/skills/anidoodle/engine/tools/keys-demo.mjs b/skills/anidoodle/engine/tools/keys-demo.mjsnew file mode 100644index 0000000..5e87141--- /dev/null+++ b/skills/anidoodle/engine/tools/keys-demo.mjs@@ -0,0 +1,145 @@+#!/usr/bin/env node+// Keys rebuild (S3): listening phrases, level calibration and anti-MIDI checks, old (legacy) vs new.+// node tools/keys-demo.mjs phrases <outDir> # before-<name>.mp3 / after-<name>.mp3 (+ .wav for the metrics) per instrument+// node tools/keys-demo.mjs calibrate # every style's test signal: keys stem RMS new vs legacy (dB)+// node tools/keys-demo.mjs clones # 8 strikes of one key: max correlation between strikes (1.0 = a clone)+// node tools/keys-demo.mjs notes <outDir> # single piano notes (old-/v2-<note>_vl<k>.wav) for tools/keys-compare.py+// Every render is deterministic (same seed, same bytes). The human listen is the final gate.+import { build } from "esbuild";+import { join } from "node:path";+import { mkdirSync, writeFileSync } from "node:fs";+import { execFileSync } from "node:child_process";++const js = (await build({ entryPoints: [join(import.meta.dirname, "../src/canvas-core/music/index.ts")], bundle: true, write: false, platform: "neutral", format: "esm", logLevel: "error" })).outputFiles[0].text;+const M = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));+const [, , mode = "phrases", outDir = "."] = process.argv;+const SR = 48000;++const wav = (path, L, R, sr = SR) => {+ const n = L.length, b = Buffer.alloc(44 + n * 4);+ b.write("RIFF", 0); b.writeUInt32LE(36 + n * 4, 4); b.write("WAVEfmt ", 8); b.writeUInt32LE(16, 16); b.writeUInt16LE(1, 20); b.writeUInt16LE(2, 22);+ b.writeUInt32LE(sr, 24); b.writeUInt32LE(sr * 4, 28); b.writeUInt16LE(4, 32); b.writeUInt16LE(16, 34); b.write("data", 36); b.writeUInt32LE(n * 4, 40);+ for (let i = 0; i < n; i++) { b.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(L[i] * 32767))), 44 + i * 4); b.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(R[i] * 32767))), 46 + i * 4); }+ writeFileSync(path, b);+};+const mp3 = (w, out) => execFileSync("ffmpeg", ["-y", "-loglevel", "error", "-i", w, "-codec:a", "libmp3lame", "-b:a", "192k", out]);++// ---------------------------------------------------------------- phrases (composed for the listen, not templates)+const piece = (title, style, tempo, meter, bpb, parts, harmony, o = {}) => ({+ title, seed: o.seed ?? 11, tail: o.tail ?? 2.5, harmony: harmony.map(([t, name]) => ({ t, name })),+ plan: { style, tempo, meter, swing: o.swing, sections: [{ id: "a", bars: o.bars ?? 5, mood: o.mood ?? "tender", key: o.key ?? "C", mode: "major", melody: ["stepwise"], dyn: o.dyn ?? [0.55, 0.75] }] },+ parts: parts.map(([id, inst, role, src, opts, gainDb]) => ({ id, inst, role, notes: M.line(0, src, { role, bpb, roll: role === "accomp" ? 0.02 : undefined }), opts, gainDb })),+});+const perBar = (bars, b = 4) => bars.map((_, i) => [i * b, bars[i]]);+const BALLAD_H = perBar(["Fmaj7", "Dm7", "Bbmaj7", "C7", "Fmaj7"]);+const ballad = (inst, opts) => piece("ballad", "nocturne", 64, "4/4", 4, [+ ["rh", inst, "melody", "A4:1.5 G4:.5 A4:1 C5:1 | D5:2 C5:1 A4:1 | Bb4:1.5 A4:.5 G4:1 F4:1 | G4:2 E4:1 G4:1 | [A4 F4]:4", opts],+ ["lh", inst, "accomp", "F2:.5 C3:.5 A3:.5 C4:.5 E4:.5 C4:.5 A3:.5 C3:.5 | D2:.5 A2:.5 F3:.5 A3:.5 C4:.5 A3:.5 F3:.5 A2:.5 | Bb1:.5 F2:.5 D3:.5 F3:.5 A3:.5 F3:.5 D3:.5 F2:.5 | C2:.5 G2:.5 E3:.5 G3:.5 Bb3:.5 G3:.5 E3:.5 G2:.5 | [F1 F2]:1 [C3 F3 A3 C4]:3", opts],+], BALLAD_H, { key: "F", dyn: [0.45, 0.7], tail: 4 });+const LIVELY_H = perBar(["C", "Am", "F", "G7", "C"]);+const lively = (inst, opts) => piece("lively", "jazz", 132, "4/4", 4, [+ ["rh", inst, "melody", "E5:.5 G5:.5 C6:.5 G5:.5 E5:.5 D5:.5 C5:.5 D5:.5 | E5:.5 A5:.5 C6:.5 A5:.5 E5:.5 C5:.5 A4:.5 C5:.5 | F5:.25 E5:.25 D5:.25 C5:.25 A4:.5 C5:.5 F5:1 A5:1 | G5:.5 F5:.5 D5:.5 B4:.5 G4:.5 B4:.5 D5:.5 F5:.5 | [C5 E5 G5 C6]:1 r:.5 [C5 E5 G5 C6]:.5 [C5 E5 G5 C6]:2", opts],+ ["lh", inst, "accomp", "C2:1 [E3 G3 C4]:1 G1:1 [E3 G3 C4]:1 | A1:1 [E3 A3 C4]:1 E2:1 [E3 A3 C4]:1 | F1:1 [F3 A3 C4]:1 C2:1 [F3 A3 C4]:1 | G1:1 [F3 G3 B3]:1 D2:1 [F3 G3 B3]:1 | [C2 C3]:1 r:.5 [C2 C3]:.5 [C2 G2 C3]:2", opts],+], LIVELY_H, { dyn: [0.7, 0.85], mood: "playful", tail: 3 });+const EP_H = perBar(["Dm9", "G13", "Cmaj9", "A7"]);+const epPhrase = (inst, opts) => piece("ep", "lofi", 82, "4/4", 4, [+ ["chords", inst, "accomp", "[D3 F3 A3 C4 E4]:1.5 [D3 F3 A3 C4 E4]:.5 r:2 | [F3 A3 B3 E4]:1.5 [F3 A3 B3 E4]:.5 r:2 | [E3 G3 B3 D4]:2 [E3 G3 B3 D4]:1 r:1 | [G3 C#4 E4 A4]:1.5 [G3 Bb3 C#4 F4]:2.5", { ...opts }],+ ["lead", inst, "melody", "r:2 A4:.5 C5:.5 D5:1 | F5:1 E5:.5 D5:.5 B4:2 | r:1 G4:.5 B4:.5 E5:1.5 D5:.5 | C#5:1 E5:1 A5:2", { ...opts, width: 0.2 }, 3],+ ["bass", "bass", "bass", "D2:2 r:1 A1:1 | G1:2 r:1 D2:1 | C2:2 r:1 G1:1 | A1:2 r:1 E2:1", {}, -4],+], EP_H, { bars: 4, swing: 0.56, mood: "nostalgic", dyn: [0.6, 0.7] });+const MAL_H = perBar(["C", "F", "G", "C"]);+const malletPhrase = (inst, style, tempo, opts) => piece("mallets", style, tempo, "4/4", 4, [+ ["lead", inst, "melody", "C5:.5 E5:.5 G5:.5 E5:.5 D5:.5 F5:.5 A5:.5 F5:.5 | C5:.5 F5:.5 A5:.5 C6:.5 A5:.5 F5:.5 C5:.5 A4:.5 | B4:.5 D5:.5 G5:.5 B5:.5 A5:.5 G5:.5 F5:.5 D5:.5 | [C5 E5]:1 G5:.5 E5:.5 C5:2", opts],+ ["low", inst, "bass", "C3:1 G3:1 C3:1 G3:1 | F3:1 C4:1 F3:1 C4:1 | G3:1 D4:1 G3:1 B3:1 | C3:2 [C3 G3]:2", opts, -4],+], MAL_H, { bars: 4, mood: "playful", dyn: [0.65, 0.8] });+const slowPhrase = (inst, style, opts, gain = 0) => piece("slow", style, 72, "3/4", 3, [+ ["lead", inst, "melody", "E5:1 G5:1 C6:1 | B5:2 G5:1 | A5:1.5 G5:.5 E5:1 | D5:3 | C5:1 E5:1 G5:1 | C6:3", opts, gain],+], perBar(["C", "G", "Am", "G", "C", "C"], 3), { bars: 6, key: "C", mood: "tender", dyn: [0.5, 0.7], tail: 4 });+const ORG_H = perBar(["C", "Am", "F", "G", "C"]);+const organRock = (opts) => piece("organ", "rock", 104, "4/4", 4, [+ ["chords", "organ", "accomp", "[C4 E4 G4]:1.5 [C4 E4 G4]:.5 r:1 [C4 E4 G4]:1 | [C4 E4 A4]:1.5 [C4 E4 A4]:.5 r:1 [C4 E4 A4]:1 | [C4 F4 A4]:1.5 [C4 F4 A4]:.5 r:1 [C4 F4 A4]:1 | [D4 G4 B4]:2 [D4 F4 B4]:2 | [C4 E4 G4 C5]:4", opts],+ ["bass", "organ", "bass", "C2:2 G2:2 | A1:2 E2:2 | F1:2 C2:2 | G1:2 G2:2 | C2:4", { ...opts, drawbars: "808000000" }, -3],+], ORG_H, { mood: "joy", dyn: [0.7, 0.8] });+const HYMN_H = perBar(["C", "F", "G", "Am", "F", "G", "C"], 4);+const hymn = (inst, opts) => piece("hymn", "choral", 66, "4/4", 4, [+ ["s", inst, "melody", "E4:2 F4:2 | A4:2 G4:2 | G4:2 E4:2 | E4:4 | F4:2 A4:2 | G4:2 F4:2 | E4:4", opts],+ ["a", inst, "inner", "C4:2 C4:2 | C4:2 B3:2 | C4:2 C4:2 | C4:4 | C4:2 C4:2 | D4:2 B3:2 | C4:4", opts],+ ["b", inst, "bass", "C3:2 A2:2 | F2:2 G2:2 | C3:2 A2:2 | A2:4 | F2:2 F2:2 | G2:2 G2:2 | C2:4", opts],+], HYMN_H, { bars: 7, mood: "awe", dyn: [0.6, 0.75], tail: 4 });++const PHRASES = [+ ["piano-ballad", () => ballad("piano", {}), "grand, slow ballad, pedal"],+ ["piano-lively", () => lively("piano", {}), "grand, lively stride passage, pedal"],+ ["piano-felt-ballad", () => ballad("piano", { variant: "felt" }), "felt piano (before = the old piano)"],+ ["piano-upright-lively", () => lively("piano", { variant: "upright" }), "upright (before = the old piano)"],+ ["piano-honky-lively", () => lively("piano", { variant: "honky" }), "honky-tonk upright (before = the old piano)"],+ ["rhodes", () => epPhrase("ePiano", { detune: 5 }), "Rhodes (tine + asymmetric pickup)"],+ ["wurlitzer", () => epPhrase("wurlitzer", {}), "Wurlitzer (before = the old ePiano)"],+ ["dx-epiano", () => epPhrase("ePiano", { model: "dx" }), "DX-style FM EP (before = the old ePiano)"],+ ["marimba", () => malletPhrase("marimba", "playful", 126, {}), "marimba"],+ ["vibes", () => malletPhrase("vibes", "jazz", 100, { trem: 4.5 }), "vibraphone, motor on"],+ ["glockenspiel", () => malletPhrase("glockenspiel", "playful", 112, {}), "glockenspiel (before = the old celesta)"],+ ["celesta", () => slowPhrase("celesta", "lullaby", {}), "celesta"],+ ["music-box", () => slowPhrase("musicBox", "lullaby", {}), "music box"],+ ["bell", () => slowPhrase("bell", "ambient", {}, -2), "tubular bells"],+ ["fm-bell", () => slowPhrase("fmBell", "ambient", {}), "FM bell"],+ ["organ-tonewheel", () => organRock({ bright: 1.2 }), "tonewheel + Leslie (slow)"],+ ["organ-tonewheel-fast", () => organRock({ bright: 1.2, leslie: "fast", perc: "3rd" }), "tonewheel + Leslie fast + percussion"],+ ["pipe-organ", () => hymn("organ", { kind: "pipe" }), "church organ, principal chorus (before = the old organ)"],+ ["pipe-organ-flute", () => hymn("organ", { kind: "pipe", stops: "flute" }), "church organ, stopped flute"],+];++if (mode === "phrases") {+ mkdirSync(outDir, { recursive: true });+ const only = process.argv[4] ? new RegExp(process.argv[4]) : null, lines = [];+ for (const [name, mk, what] of PHRASES) {+ if (only && !only.test(name)) continue;+ for (const [tag, legacy] of [["before", true], ["after", false]]) {+ const t0 = Date.now(), p = mk(), r = M.renderPiece({ ...p, legacy }, SR), w = join(outDir, `${tag}-${name}.wav`);+ wav(w, r.L, r.R); mp3(w, join(outDir, `${tag}-${name}.mp3`));+ lines.push(`${tag}-${name}.mp3 ${what} (${(r.L.length / SR).toFixed(1)} s, ${M.loudness([r.L, r.R], SR).integrated.toFixed(1)} LUFS, rendered in ${((Date.now() - t0) / 1000).toFixed(1)} s)`);+ console.log(lines[lines.length - 1]);+ }+ }+ writeFileSync(join(outDir, "PHRASES.txt"), lines.join("\n") + "\n");+}++if (mode === "calibrate") {+ const KEYS = new Set(["piano", ...M.KEYS_INSTS]), rows = [];+ for (const v of Object.values(M.VOCAB)) {+ const p = M.composePiece(M.testMaterial(v, { bars: 4 }));+ if (!p.parts.some((x) => KEYS.has(x.inst))) continue;+ const a = M.renderPiece({ ...p, legacy: true }, 24000, { stems: true, master: "none" }), b = M.renderPiece({ ...p, legacy: false }, 24000, { stems: true, master: "none" });+ for (const pt of p.parts) if (KEYS.has(pt.inst)) { const d = M.stemRms(b.stems[pt.id][0]) - M.stemRms(a.stems[pt.id][0]); rows.push([v.id, pt.id, pt.inst, JSON.stringify(pt.opts ?? {}), d]); }+ }+ for (const r of rows) console.log(`${r[0].padEnd(15)} ${r[1].padEnd(8)} ${r[2].padEnd(12)} new-old ${r[4] >= 0 ? "+" : ""}${r[4].toFixed(1)} dB ${r[3]}`);+ const by = {}; for (const r of rows) (by[r[2]] ??= []).push(r[4]);+ console.log("mean by instrument:", Object.entries(by).map(([k, v]) => `${k} ${(v.reduce((a, b) => a + b, 0) / v.length).toFixed(1)}`).join(", "));+}++if (mode === "clones") {+ // the same key 8 times, 1 s apart, same velocity: how alike are the strikes? (research sec. 9.2: < 0.98)+ const insts = ["piano", "ePiano", "wurlitzer", "marimba", "vibes", "glockenspiel", "celesta", "musicBox", "bell", "fmBell", "organ"];+ for (const inst of insts) {+ const res = [];+ for (const legacy of [true, false]) {+ const p = { title: "clone", seed: 5, tail: 1, harmony: [], plan: { style: "nocturne", tempo: 60, meter: "4/4", sections: [{ id: "a", bars: 2, mood: "tender", key: "C", mode: "major", melody: ["stepwise"], dyn: [0.6, 0.6] }] }, parts: [{ id: "x", inst, role: "melody", notes: M.line(0, "C5:.5 r:.5 C5:.5 r:.5 C5:.5 r:.5 C5:.5 r:.5 | C5:.5 r:.5 C5:.5 r:.5 C5:.5 r:.5 C5:.5 r:.5", { role: "melody", bpb: 4 }) }] };+ const r = M.renderPiece({ ...p, legacy }, SR, { expressive: false, flatVelocity: 0.6, master: "none" }), ons = r.perf.parts[0].keys.map((k) => Math.round(k.t * SR)), W = Math.round(0.4 * SR);+ let worst = 0;+ for (let a = 0; a + 1 < ons.length; a++) { const A = r.dry[0].subarray(ons[a], ons[a] + W), B = r.dry[0].subarray(ons[a + 1], ons[a + 1] + W); let ab = 0, aa = 0, bb = 0; for (let i = 0; i < W; i++) { ab += A[i] * B[i]; aa += A[i] * A[i]; bb += B[i] * B[i]; } worst = Math.max(worst, Math.abs(ab) / Math.sqrt(aa * bb + 1e-20)); }+ res.push(worst);+ }+ console.log(`${inst.padEnd(13)} max strike-to-strike correlation: legacy ${res[0].toFixed(4)} new ${res[1].toFixed(4)} ${res[1] < 0.98 ? "ok" : "CLONE"}`);+ }+}++if (mode === "notes") {+ mkdirSync(outDir, { recursive: true });+ for (const [m, v, tag] of [[36, 0.35, "C2_vl2"], [36, 0.92, "C2_vl4"], [48, 0.62, "C3_vl3"], [60, 0.35, "C4_vl2"], [60, 0.62, "C4_vl3"], [60, 0.92, "C4_vl4"], [72, 0.62, "C5_vl3"], [84, 0.92, "C6_vl4"]]) {+ const keys = [{ t: 0.05, off: 16, p: m, v }], n = Math.round(17 * 44100);+ const a = M.renderPiano(keys, [], 44100, n, M.PIANO_REAL, 1), b = M.renderPianoV2(keys, [], 44100, n, {}, 1);+ const norm = (r) => { let pk = 1e-9; for (let i = 0; i < n; i++) pk = Math.max(pk, Math.abs(r.L[i]), Math.abs(r.R[i])); const g = 0.5 / pk; return [r.L.map((x) => x * g), r.R.map((x) => x * g)]; };+ wav(join(outDir, `old-${tag}.wav`), ...norm(a), 44100); wav(join(outDir, `v2-${tag}.wav`), ...norm(b), 44100);+ }+ console.log("notes written to", outDir);+}diff --git a/skills/anidoodle/engine/tools/keys-fit.py b/skills/anidoodle/engine/tools/keys-fit.pynew file mode 100644index 0000000..c2b7856--- /dev/null+++ b/skills/anidoodle/engine/tools/keys-fit.py@@ -0,0 +1,245 @@+#!/usr/bin/env python3+"""Offline "measured physics" fitter for the keys voices (piano, mallets, organ).++ python3 tools/keys-fit.py <VCSL root> [--json out.json]++Reads CC0 recordings from a local checkout of VCSL (github.com/sgossner/VCSL, CC0 1.0) and fits the+small numeric tables in src/canvas-core/music/keysTables.ts: per-note inharmonicity B and f0 (least+squares on (f_n/n)^2 = f0^2 + f0^2 B n^2), per-partial attack level (dB re partial 1) and a two-stage+decay per partial (prompt slope over the first ~10 dB, aftersound slope later), and for idiophones the+partial ratios and T60s. Nothing recorded is copied into the engine; only these numbers are. numpy only.+"""+import json, os, re, sys, wave+import numpy as np++NOTE = {"C": 0, "C#": 1, "D": 2, "D#": 3, "E": 4, "F": 5, "F#": 6, "G": 7, "G#": 8, "A": 9, "A#": 10, "B": 11}+++def midi_of(name, octave_offset=12):+ m = re.match(r"([A-G]#?)(-?\d)", name)+ return NOTE[m.group(1)] + (int(m.group(2)) + 1) * 12 + (octave_offset - 12)+++def load(path):+ w = wave.open(path)+ sr, sw, ch, n = w.getframerate(), w.getsampwidth(), w.getnchannels(), w.getnframes()+ raw = w.readframes(n)+ if sw == 2:+ x = np.frombuffer(raw, dtype="<i2").astype(np.float64) / 32768+ else:+ b = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3)+ v = (b[:, 0].astype(np.int32) | (b[:, 1].astype(np.int32) << 8) | (b[:, 2].astype(np.int32) << 16))+ v = np.where(v >= 1 << 23, v - (1 << 24), v)+ x = v.astype(np.float64) / (1 << 23)+ x = x.reshape(-1, ch).mean(axis=1)+ return x, sr+++def onset(x):+ a = np.abs(x)+ thr = 0.1 * a.max()+ return int(np.argmax(a > thr))+++def spectrum(seg, sr, pad=4):+ N = len(seg)+ win = np.hanning(N)+ nfft = 1 << int(np.ceil(np.log2(N * pad)))+ S = np.abs(np.fft.rfft(seg * win, nfft))+ return S, sr / nfft+++def peak_near(S, df, f, tol):+ lo, hi = max(1, int((f - tol) / df)), min(len(S) - 2, int((f + tol) / df) + 1)+ if hi <= lo:+ return None+ k = lo + int(np.argmax(S[lo:hi]))+ a, b, c = np.log(S[k - 1] + 1e-12), np.log(S[k] + 1e-12), np.log(S[k + 1] + 1e-12)+ d = 0.5 * (a - c) / (a - 2 * b + c) if (a - 2 * b + c) != 0 else 0+ return (k + d) * df, float(np.exp(b - 0.25 * (a - c) * d))+++def tone_track(x, sr, f, hop, win):+ """Level (dB) of one frequency over time: a Hann-windowed single-bin DFT per frame."""+ n = len(x)+ frames = (n - win) // hop+ if frames < 2:+ return np.array([])+ w = np.hanning(win)+ ph = np.exp(-2j * np.pi * f * np.arange(win) / sr) * w+ out = np.empty(frames)+ for i in range(frames):+ s = x[i * hop:i * hop + win]+ out[i] = 20 * np.log10(abs(np.dot(s, ph)) * 2 / w.sum() + 1e-12)+ return out+++def fit_string(path, midi):+ x, sr = load(path)+ i0 = onset(x)+ x = x[i0:]+ f_nom = 440 * 2 ** ((midi - 69) / 12)+ dur = min(len(x) / sr - 0.1, max(1.0, 3.0 * (262 / f_nom) ** 0.5))+ seg = x[int(0.03 * sr):int((0.03 + dur) * sr)]+ S, df = spectrum(seg, sr)+ # comb search: the (f0, B) whose predicted partials sit on the most spectral energy (log), then a+ # least-squares refinement on the peaks found near the prediction+ logS = np.log(S + 1e-9 * S.max())+ def score(f0, B):+ tot, cnt = 0.0, 0+ for n in range(1, 40):+ fn = n * f0 * np.sqrt(1 + B * n * n)+ if fn > min(0.45 * sr, 9000):+ break+ k = int(round(fn / df))+ tot += logS[max(0, k - 1):k + 2].max(); cnt += 1+ return tot / max(cnt, 1) if cnt >= 3 else -1e9+ best = (-1e18, f_nom, 3e-4)+ for c in np.arange(-60, 61, 4):+ for B in np.geomspace(2e-5, 3e-2, 60):+ sc = score(f_nom * 2 ** (c / 1200), B)+ if sc > best[0]:+ best = (sc, f_nom * 2 ** (c / 1200), B)+ _, f0, B = best+ for it in range(2):+ found = []+ for n in range(1, 60):+ fn = n * f0 * np.sqrt(1 + B * n * n)+ if fn > min(0.45 * sr, 12000):+ break+ pk = peak_near(S, df, fn, min(0.08 * f0, 25))+ if pk:+ found.append((n, pk[0], pk[1]))+ if len(found) < 3:+ break+ nn = np.array([p[0] for p in found], float)+ ff = np.array([p[1] for p in found])+ A = np.vstack([np.ones_like(nn), nn * nn]).T+ wts = 1 / nn+ c, *_ = np.linalg.lstsq(A * wts[:, None], (ff / nn) ** 2 * wts, rcond=None)+ f0 = float(np.sqrt(max(c[0], 1)))+ B = float(max(c[1] / c[0], 1e-6))+ # attack levels from the first 60 ms (dB re partial 1) and per-partial decays+ hop, win = int(0.01 * sr), int(max(0.04, 6 / f0) * sr)+ partials = []+ for n in range(1, 121):+ fn = n * f0 * np.sqrt(1 + B * n * n)+ if fn > min(0.45 * sr, 12000):+ break+ tr = tone_track(x, sr, fn, hop, win)+ if len(tr) < 10:+ continue+ t = np.arange(len(tr)) * hop / sr + win / 2 / sr+ peak_i = int(np.argmax(tr[: int(0.15 * sr / hop) + 1]))+ L0 = tr[peak_i]+ floor = np.percentile(tr, 3)+ # prompt: slope over the first 12 dB (or 0.8 s); aftersound: slope after that down to floor + 8 dB+ idx = np.arange(peak_i, len(tr))+ def slope(sel):+ if len(sel) < 4:+ return None+ p = np.polyfit(t[sel], tr[sel], 1)+ return p+ drop = tr[idx] < L0 - 12+ k12 = idx[np.argmax(drop)] if drop.any() else idx[-1]+ k12 = min(k12, peak_i + int(0.8 * sr / hop))+ pp = slope(np.arange(peak_i + 1, max(k12, peak_i + 5)))+ late = np.arange(k12, len(tr))+ late = late[tr[late] > floor + 8]+ pa = slope(late) if len(late) > 20 else None+ partials.append({"n": n, "f": round(fn, 2), "L0": round(float(L0), 2),+ "promptDbS": None if pp is None else round(float(pp[0]), 2),+ "afterDbS": None if pa is None else round(float(pa[0]), 2),+ "afterAt0Db": None if pa is None else round(float(pa[1] - L0), 2)})+ L1 = partials[0]["L0"] if partials else 0+ for p in partials:+ p["rel"] = round(p["L0"] - L1, 2)+ # attack centroid (first 100 ms) and the attack's inharmonic "noise" floor between partials+ a = x[: int(0.1 * sr)]+ Sa, dfa = spectrum(a, sr, 2)+ fr = np.arange(len(Sa)) * dfa+ cen = float((Sa * fr).sum() / Sa.sum())+ return {"midi": midi, "f0": round(f0, 3), "B": B, "cents": round(1200 * np.log2(f0 / f_nom), 2), "centroid100ms": round(cen, 1), "partials": partials}+++def fit_bar(path, f_nom, maxRatio=40):+ """Idiophone: the strongest peaks, their ratios to the fundamental and their T60s."""+ x, sr = load(path)+ x = x[onset(x):]+ seg = x[int(0.005 * sr):int(min(len(x) / sr - 0.05, 1.5) * sr)]+ S, df = spectrum(seg, sr)+ f0 = peak_near(S, df, f_nom, 0.06 * f_nom)[0]+ Sd = 20 * np.log10(S / S.max() + 1e-12)+ # prominent local maxima: above -55 dB and 12 dB over the local median+ from numpy.lib.stride_tricks import sliding_window_view as swv+ W = max(5, int(40 / df)) | 1+ med = np.median(swv(np.pad(Sd, W // 2, mode="edge"), W), axis=1)+ pk = [k for k in range(2, len(S) - 2) if Sd[k] > -55 and Sd[k] - med[k] > 12 and S[k] == S[k - 2:k + 3].max() and k * df > 0.8 * f0 and k * df < min(maxRatio * f0, 18000)]+ pk.sort(key=lambda k: -S[k])+ modes = []+ hop, win = int(0.005 * sr), int(max(0.02, 8 / f0) * sr)+ for k in pk[:24]:+ f = peak_near(S, df, k * df, 2 * df)[0]+ if any(abs(f - m["f"]) < 0.01 * f for m in modes):+ continue+ tr = tone_track(x, sr, f, hop, win)+ t = np.arange(len(tr)) * hop / sr+ i = int(np.argmax(tr[:40]))+ floor = np.percentile(tr, 5)+ sel = np.arange(i, len(tr))+ sel = sel[tr[sel] > max(floor + 6, tr[i] - 40)]+ sel = sel[: np.argmax(np.diff(sel) > 1) + 1] if len(sel) > 1 and (np.diff(sel) > 1).any() else sel+ slope = np.polyfit(t[sel], tr[sel], 1)[0] if len(sel) > 5 else None+ modes.append({"f": round(f, 2), "ratio": round(f / f0, 4), "db": round(float(Sd[k]), 1), "t60": None if not slope or slope >= 0 else round(-60 / slope, 3)})+ if len(modes) >= 12:+ break+ modes.sort(key=lambda m: m["f"])+ return {"f0": round(f0, 2), "modes": modes}+++if __name__ == "__main__":+ root = sys.argv[1]+ out = {"source": "VCSL (github.com/sgossner/VCSL), CC0 1.0", "piano": {}, "upright": {}, "bars": {}}+ g = os.path.join(root, "Chordophones/Zithers/Grand Piano, Steinway B/NoSus")+ for fn in sorted(os.listdir(g)):+ m = re.match(r"JHPiano_NoSus_Close_([A-G]#?\d)_vl(\d)_rr1\.wav", fn)+ if not m:+ continue+ midi = midi_of(m.group(1))+ r = fit_string(os.path.join(g, fn), midi)+ r["file"] = fn+ out["piano"][f"{midi}_v{m.group(2)}"] = r+ print(f"grand {m.group(1)} vl{m.group(2)} midi {midi}: f0 {r['f0']} ({r['cents']:+.1f} c) B {r['B']:.2e} partials {len(r['partials'])} centroid {r['centroid100ms']}", file=sys.stderr)+ u = os.path.join(root, "Chordophones/Zithers/Upright Piano, Yamaha/Sustains")+ for fn in sorted(os.listdir(u)):+ m = re.match(r"Upright1_Sus_([A-G]#?\d)_vl(\d)_rr1\.wav", fn)+ if not m:+ continue+ midi = midi_of(m.group(1))+ r = fit_string(os.path.join(u, fn), midi)+ r["file"] = fn+ out["upright"][f"{midi}_v{m.group(2)}"] = r+ print(f"upright {m.group(1)} midi {midi}: f0 {r['f0']} ({r['cents']:+.1f} c) B {r['B']:.2e} centroid {r['centroid100ms']}", file=sys.stderr)+ bars = {+ "glock": ("Idiophones/Struck Idiophones/Glockenspiel", r"glock_(loud|medium)_([A-G]#?\d)_01\.wav", 24),+ "marimba": ("Idiophones/Struck Idiophones/Marimba", r"Marimba_hit_Outrigger_([A-G]#?\d)_(loud|med)_01\.wav", 24),+ "vibes": ("Idiophones/Struck Idiophones/Vibraphone/Hard Mallets", r"Vibes_hard_([A-G]#?\d)_v2_rr1_Main\.wav", 24),+ "chimes": ("Idiophones/Struck Idiophones/Tubular Bells 1", r"chimes_([A-G]#?\d)_ff_rr\d\.wav", 12),+ "organ": ("Aerophones/Edge-blown Aerophones/Pipe Organ", None, 40),+ }+ for name, (d, pat, mr) in bars.items():+ base = os.path.join(root, d)+ for dp, _, fs in os.walk(base):+ for fn in sorted(fs):+ if not fn.endswith(".wav"):+ continue+ notes = re.findall(r"_([A-G]#?\d)[_.]", fn)+ if not notes:+ continue+ midi = midi_of(notes[0])+ r = fit_bar(os.path.join(dp, fn), 440 * 2 ** ((midi - 69) / 12), mr)+ r["file"] = fn+ out["bars"][f"{name}:{fn}"] = r+ print(f"{name} {fn}: f0 {r['f0']} modes {[(m['ratio'], m['db'], m['t60']) for m in r['modes']]}", file=sys.stderr)+ if "--json" in sys.argv:+ json.dump(out, open(sys.argv[sys.argv.index("--json") + 1], "w"), indent=1)