Skip to content

Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.

chore: resync Codex mirror

Alex Greenshpuna3e0f973cbd8
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/lessonOwlScore.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/lessonOwlScore.ts
index aba6c2b..4954ef4 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/lessonOwlScore.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/lessonOwlScore.ts
@@ -82,7 +82,7 @@ export const owlPiece = (sp: OwlSoundPlan): Piece => {
];
const bars = Math.ceil((E + 7) / 4);
return {
- title: "How to draw an owl (social cut)", seed: 1109, tail: 1.5, harmony: [],
+ title: "How to draw an owl (social cut)", seed: 1109, tail: 1.5, harmony: [], legacy: true, // shipped lesson: frozen on the pre-rebuild sound (Piece.legacy)
plan: { style: "minimalist", tempo: sp.bpm, meter: "4/4", rubato: 0, ritard: 1, sections: [{ id: "all", bars, mood: "curious", key: "G", mode: "major", melody: ["ostinato", "hook"], dyn: [0.62, 0.7], ending: "button" }] },
parts,
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/breach.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/breach.ts
new file mode 100644
index 0000000..8b47d46
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/breach.ts
@@ -0,0 +1,59 @@
+// BREACH: 30 s cybersecurity reveal teaser. drive vocabulary, tension mood, C# aeolian, 4/4, 130 bpm.
+// Picture beats (bar = 1.846 s): 0 s pulse starts, 3.7 s scan motif, 11.1 s pressure rises,
+// 18.5 s build, 22.2 s one bar of held breath, 24.0 s HARD REVEAL (bar 14), 27.7 s tag button.
+import type { Material } from "../compose";
+
+const P = "C#2:.5 C#2:.5 C#2:.5 C#3:.5 C#2:.5 C#2:.5 C#2:.25 C#2:.25 G#1:.5"; // the pedal pulse
+export const breach = (): Material => ({
+ style: "drive", title: "Breach", seed: 4471, mood: "tension",
+ bpm: 130, key: "C#", mode: "aeolian", meter: "4/4",
+ tail: 2.4, levels: { bass: 0.2, hat: 6.5, arp: -5.8, lead: 1.6, kick: 0.6, snare: -2.9, perc: -6 } /* sound v2: re-balanced so every stem sits where the composer put it against its target (the notes are untouched); written for v1 as bass: -3.5, hat: 25, arp: -1, lead: 7.9 */,
+ moodControls: { energy: 0.7, warmth: 0.3, brightness: 0.35, tension: 0.85, space: 0.35 },
+ chords: {
+ i: { voicing: "[G#3 C#4 D#4 E4]", bass: P },
+ iv_i: { voicing: "[A3 C#4 F#4]", bass: P },
+ VI_i: { voicing: "[G#3 A3 C#4 E4]", bass: P },
+ III: { voicing: "[G#3 B3 E4]", bass: "E2:.75 E2:.25 r:.5 E2:.5 E3:.25 E2:.75 B1:.5 D#2:.5" },
+ v: { voicing: "[F#3 B3 D#4]", bass: "G#1:.75 G#1:.25 r:.5 G#1:.5 G#2:.25 G#1:.75 G#1:.5 F#1:.5" },
+ VI: { voicing: "[G#3 C#4 E4]", bass: "A1:.75 A1:.25 r:.5 A1:.5 A2:.25 A1:.75 A1:.5 B1:.5" },
+ // build: a G# pedal under climbing shapes
+ ivG: { voicing: "[A3 C#4 F#4]", bass: "G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25" },
+ VIG: { voicing: "[A3 C#4 E4 B4]", bass: "G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25 G#1:.25" },
+ Vsus: { voicing: "[G#3 C#4 D#4]", bass: "r:4" },
+ // the reveal and the tag
+ I5: { voicing: "[C#3 G#3 C#4 E4 G#4]", bass: "C#2:1.5 C#2:.5 r:.5 C#3:.5 C#2:.5 C#2:.5" },
+ bIII: { voicing: "[B3 E4 G#4]" }, IV: { voicing: "[C#4 F#4 A#4]" },
+ home: { voicing: "[C#3 G#3 C#4 G#4]", bass: "C#2:1 r:3" },
+ },
+ motifs: {
+ // the scan: an upbeat start, a semitone twitch, then a leap to a long high note
+ scan: "r:.5 G#4:.5 A4:.25 G#4:.75 r:.5 E5:1.5",
+ scanQ: "r:.5 G#4:.5 A4:.25 G#4:.75 r:.5 F#5:.5 E5:1",
+ scanA: "r:.5 E4:.5 F#4:.25 E4:.75 r:.5 C#5:1.5",
+ scanUp: "r:.5 B4:.5 C#5:.25 B4:.75 r:.5 G#5:1.5",
+ scanUp2: "r:.5 C#5:.5 D#5:.25 C#5:.75 r:.5 A5:.5 G#5:1",
+ frag1: "G#4:.5 A4:.25 G#4:.25 B4:.5 C#5:.25 B4:.25 C#5:.5 D#5:.25 C#5:.25 E5:.5 F#5:.25 E5:.25",
+ frag2: "G#5:.25 A5:.25 G#5:.25 A5:.25 B5:.25 A5:.25 B5:.25 C#6:.25 D#6:1 r:1",
+ whisper: "r:2.5 D#5:.5 G#5:1",
+ // the reveal: the scan augmented an octave up, then the tag's answer
+ big: "G#5:1 A5:.5 G#5:1.5 E6:1",
+ bigA: "C#6:1.5 B5:.5 A#5:1 G#5:1",
+ button: "[C#5 G#5]:.75 r:3.25",
+ // the pulse: a 3-note cell across 16ths (it realigns every 3 bars)
+ pulse16: "C#5:.25 G#4:.25 D#5:.25 C#5:.25 G#4:.25 D#5:.25 C#5:.25 G#4:.25 D#5:.25 C#5:.25 G#4:.25 D#5:.25 C#5:.25 G#4:.25 D#5:.25 C#5:.25",
+ },
+ grooves: {
+ main: { family: "tension", density: 0.55, variation: 0.35 },
+ build: { family: "build", density: 0.8 },
+ drop: { family: "fourFloor", density: 0.85, variation: 0.3, fill: true },
+ },
+ sections: [
+ { kind: "intro", bars: 2, harmony: ["i"], chordVel: 0.55, arp: ["pulse16", "pulse16"] },
+ { kind: "verse", bars: 4, harmony: ["i", "i", "VI_i", "iv_i"], lead: ["scan", "scanQ", "scanA", "r:4"], arp: Array(4).fill("pulse16"), energy: 0.25, chordVel: 0.7 },
+ { kind: "hook", bars: 4, harmony: ["i", "III", "v", "VI"], lead: ["scanUp", "scanUp2", "scan", "scanQ"], arp: Array(4).fill("pulse16"), energy: 0.7 },
+ { kind: "build", bars: 2, harmony: ["ivG", "VIG"], lead: ["frag1", "frag2"], arp: ["pulse16", "pulse16"], energy: 0.9 },
+ { kind: "breath", bars: 1, harmony: ["Vsus"], chordVel: 0.15, lead: ["whisper"] },
+ { kind: "drop", bars: 2, groove: "drop", harmony: ["I5", "bIII IV"], bass: [P.replace(/C#2:\.5 C#2:\.5 C#2:\.5/, "C#2:1 C#2:.5"), "E2:.5 E2:.5 E2:.5 E3:.5 F#2:.5 F#2:.5 F#3:.5 F#2:.5"], lead: ["big", "bigA"], arp: ["pulse16", "r:2 C#5:.25 G#4:.25 D#5:.25 C#5:.25 G#4:.25 D#5:.25 E5:.25 F#5:.25"], energy: 1 },
+ { kind: "outro", bars: 1, harmony: ["home"], chordVel: 0.6, lead: ["button"] },
+ ],
+});
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/morningCrumb.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/morningCrumb.ts
new file mode 100644
index 0000000..9beeb94
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/morningCrumb.ts
@@ -0,0 +1,75 @@
+// MORNING CRUMB: a 40 s seamless loop for a small bakery. playful vocabulary, playful mood,
+// F major, 4/4 shuffle at 120 bpm: 20 bars x 2 s = exactly 40 s. Marimba hook, fingerpicked
+// guitar, tuba oom-pah, celesta crumbs answering. A bVI surprise in the bridge, then a
+// turnaround whose C7 falls back into bar 1.
+import type { Material } from "../compose";
+
+// Chord tones (low to high) for the guitar picking, per chord name.
+const T: Record<string, string[]> = {
+ F6: ["F3", "C4", "A3", "D4"], Am7: ["A3", "E4", "C4", "G4"], D7: ["D3", "C4", "F#3", "A3"],
+ Gm7: ["G3", "D4", "Bb3", "F4"], Bb6: ["Bb2", "F3", "D4", "G3"], C7: ["C3", "G3", "E4", "Bb3"],
+ Db: ["Db3", "Ab3", "F4", "C4"], Bdim: ["B2", "F3", "D4", "Ab3"], Dm7: ["D3", "A3", "F4", "C4"],
+};
+// a bar of picking: bass-note on the beat, a two-note pinch on the swung upbeat; halves for split bars
+const half = (c: string) => { const t = T[c]; return `${t[0]}:.5 [${t[2]} ${t[3]}]:[email protected] ${t[1]}:.5 [${t[2]} ${t[3]}]:[email protected]`; };
+const pick = (bar: string) => { const cs = bar.split(" "); return cs.length === 1 ? `${half(cs[0])} ${half(cs[0])}` : `${half(cs[0])} ${half(cs[1])}`; };
+const picks = (bars: string[]) => bars.map(pick);
+// tuba: oom-pah, root and fifth, a walk-up pickup where the next chord moves
+const R: Record<string, [string, string]> = {
+ F6: ["F2", "C2"], Am7: ["A1", "E2"], D7: ["D2", "A1"], Gm7: ["G1", "D2"], Bb6: ["Bb1", "F2"],
+ C7: ["C2", "G1"], Db: ["Db2", "Ab1"], Bdim: ["B1", "F2"], Dm7: ["D2", "A1"],
+};
+const tuba = (bar: string) => { const cs = bar.split(" "); if (cs.length === 2) return `${R[cs[0]][0]}:1 ${R[cs[0]][1]}:1 ${R[cs[1]][0]}:1 ${R[cs[1]][1]}:1`; const [r, f] = R[cs[0]]; return `${r}:1 ${f}:1 ${r}:1 ${f}:.5 ${f}:[email protected]`; };
+const tubas = (bars: string[]) => bars.map(tuba);
+
+const A = ["F6", "Am7 D7", "Gm7", "Bb6 C7"];
+const A2 = ["F6", "Am7 D7", "Gm7 C7", "F6"];
+const BR = ["Db", "C7", "Bb6", "Bdim"];
+const TA = ["F6", "Dm7", "Gm7 C7", "Gm7 C7"];
+
+export const morningCrumb = (): Material => ({
+ style: "playful", title: "Morning Crumb", seed: 2207, mood: "playful",
+ bpm: 120, key: "F", mode: "major", meter: "4/4", swing: 0.58, loop: true,
+ levels: { counter: -6.3, chords: -2, lead: -0.5, bass: 0.4, kick: 0.4, snare: 0.5, arp: 4.6 } /* sound v2: re-balanced so every stem sits where the composer put it against its target (the notes are untouched); written for v1 as counter: 7, chords: -6 */,
+ moodControls: { energy: 0.45, warmth: 0.75, brightness: 0.45, tension: 0.2, space: 0.35 },
+ voices: { arp: { inst: "guitar", role: "accomp", gainDb: 8 }, bass: "tuba" },
+ chords: {
+ F6: { voicing: "[A3 C4 D4 F4]" }, Am7: { voicing: "[G3 C4 E4]" }, D7: { voicing: "[F#3 C4 D4]" },
+ Gm7: { voicing: "[F3 Bb3 D4]" }, Bb6: { voicing: "[F3 G3 Bb3 D4]" }, C7: { voicing: "[E3 G3 Bb3]" },
+ Db: { voicing: "[F3 Ab3 C4]" }, Bdim: { voicing: "[F3 Ab3 D4]" }, Dm7: { voicing: "[F3 A3 C4]" },
+ },
+ motifs: {
+ // the crumb: an upbeat pickup, a hop up a 4th, a staccato repeat, a zig-zag, then a gap
+ crumb: "r:.5 C5:.5 F5:.5 F5:.25 r:.25 E5:.5 G5:.5 r:1",
+ crumbUp: "r:.5 D5:.5 G5:.5 G5:.25 r:.25 F5:.5 A5:.5 r:1",
+ tumble: "A5:.5 G5:.5 E5:1 F#5:.5 A5:.5 r:1",
+ askEnd: "Bb5:.5 A5:.5 G5:1 E5:.5 G5:.5 C6:.5 r:.5",
+ tumble2: "A5:.5 C6:.5 B5:.5 A5:.5 F#5:1 r:1",
+ walkDown: "r:.5 Bb5:.5 A5:.5 G5:.5 E5:.5 C5:.5 D5:.5 E5:.5",
+ homeHop: "F5:1.5 r:.5 C5:.25 r:.25 F4:.5 r:1",
+ // bridge: the crumb on the bVI, then a comic stop
+ crumbDb: "r:.5 Ab4:.5 Db5:.5 Db5:.25 r:.25 C5:.5 Eb5:.5 r:1",
+ stop: "E5:.5 G5:.5 Bb5:1 r:2",
+ crumbBb: "r:.5 F5:.5 Bb5:.5 Bb5:.25 r:.25 A5:.5 C6:.5 r:1",
+ slide: "D6:.5 B5:.5 Ab5:.5 F5:.5 D5:.5 r:1.5",
+ // turnaround
+ bite: "A5:.5 F5:.5 D5:1 r:2",
+ climb: "r:.5 Bb4:.5 D5:.5 F5:.5 E5:.5 G5:.5 Bb5:.5 r:.5",
+ shrug: "A5:.25 Bb5:.25 A5:.5 G5:.5 E5:.5 r:2",
+ // celesta crumbs answering in the gaps
+ c1: "r:3 G6:.25 F6:.25 C6:.5", c2: "r:3 A6:.25 G6:.25 D6:.5", c3: "r:3.5 C7:.25 A6:.25",
+ },
+ grooves: { main: { family: "shuffle", density: 0.45, variation: 0.35, fill: true } },
+ sections: [
+ { kind: "verse", bars: 4, harmony: A, bass: tubas(A), arp: picks(A), energy: 0.35,
+ lead: ["crumb", "r:4", "crumbUp", "r:4"], counter: ["r:4", "c1", "r:4", "c2"] },
+ { kind: "hook", bars: 4, harmony: A, bass: tubas(A), arp: picks(A), energy: 0.55,
+ lead: ["crumb", "tumble", "crumbUp", "askEnd"] },
+ { kind: "hook", bars: 4, harmony: A2, bass: tubas(A2), arp: picks(A2), energy: 0.6,
+ lead: ["crumb", "tumble2", "walkDown", "homeHop"], counter: ["c1", "r:4", "c3", "r:4"] },
+ { kind: "bridge", bars: 4, harmony: BR, bass: tubas(BR), arp: picks(BR), energy: 0.4, chordVel: 0.9,
+ lead: ["crumbDb", "stop", "crumbBb", "slide"] },
+ { kind: "groove", bars: 4, harmony: TA, bass: tubas(TA), arp: picks(TA), energy: 0.5,
+ lead: ["crumb", "bite", "climb", "shrug"], counter: ["r:4", "c2", "r:4", "c3"] },
+ ],
+});
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/skywardKids.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/skywardKids.ts
new file mode 100644
index 0000000..e9d85e5
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/skywardKids.ts
@@ -0,0 +1,92 @@
+// SKYWARD KIDS: a 30 s trailer for a children's adventure game. orchestral vocabulary, heroic
+// mood, C major, a chromatic-mediant (E major) turn in the finish, 6/8 gallop at 88 bpm (a bar = 1.36 s, 20 bars).
+// The fanfare: two pickup eighths, a rising 4th then a 5th, a step down, then a climb to a long
+// note ("sky-ward, HO!"). Question lands on the 6th/5th, answer on the tonic; fragmented in the
+// bridge between brass and flute, climbed in the build, augmented at the finish.
+// Picture beats: 0 s ostinato, 2.7 s fanfare, 8.2 s full theme, 13.6 s the journey (bridge),
+// 19.1 s climb, 21.8 s the big finish, 25.9 s final chord + timpani.
+import type { Material } from "../compose";
+
+const T = (n: number) => `${n}/3`;
+// the string ostinato: a galloping 8th figure through the chord (low-high-mid, twice per bar)
+const ost = (a: string, b: string, c: string) => `${a}:${T(1)} ${c}:${T(1)} ${b}:${T(1)} ${a}:${T(1)} ${c}:${T(1)}@0.8 ${b}:${T(1)}@0.7`;
+const gallop = (r: string, f: string) => `${r}:${T(2)} ${r}:${T(1)} ${f}:${T(2)} ${r}:${T(1)}`;
+
+// timpani / drums written per ABSOLUTE bar (literal grooves cycle on the absolute bar number)
+const roots = ["C2", "C2", "C2", "C2", "A1", "G1", "C2", "D2", "F1", "C2", "A1", "F1", "D2", "A1", "G1", "G1", "C2", "E2", "F1", "C2"];
+const fifth: Record<string, string> = { C2: "G1", A1: "E2", G1: "D2", D2: "A1", F1: "C2", E2: "B1" };
+const timp = roots.map((r) => `${r}:${T(2)} r:${T(1)} ${fifth[r]}:${T(2)} ${fifth[r]}:${T(1)}@0.7`);
+const H = `C4:${T(1)}@0.5 C4:${T(1)}@0.3 C4:${T(1)}@0.35 C4:${T(1)}@0.5 C4:${T(1)}@0.3 C4:${T(1)}@0.35`;
+
+export const skywardKids = (): Material => ({
+ style: "orchestral", title: "Skyward Kids", seed: 6128, mood: "heroic",
+ bpm: 88, key: "C", mode: "major", meter: "6/8", tail: 2.8,
+ moodControls: { energy: 0.7, warmth: 0.5, brightness: 0.65, tension: 0.3, space: 0.55 },
+ voices: { counter: "flute" },
+ levels: { hat: 9.2, perc: -8.2, counter: 6.4, chords: -1.2, arp: -1.6, bass: 1.3, kick: 1, snare: -1.4 } /* sound v2: re-balanced so every stem sits where the composer put it against its target (the notes are untouched); written for v1 as hat: 19, perc: -2.3, counter: 8, chords: -2, arp: 2.5, lead: 10 */,
+ chords: {
+ C: { voicing: "[E3 G3 C4 E4]", bass: gallop("C2", "G2") },
+ F_C: { voicing: "[F3 A3 C4 F4]", bass: gallop("C2", "C3") },
+ Am: { voicing: "[E3 A3 C4 E4]", bass: gallop("A1", "E2") },
+ G: { voicing: "[D3 G3 B3 D4]", bass: gallop("G1", "D2") },
+ D: { voicing: "[F#3 A3 D4]", bass: gallop("D2", "A2") },
+ F: { voicing: "[F3 A3 C4]", bass: gallop("F1", "C2") },
+ Dm7: { voicing: "[F3 A3 C4 D4]", bass: gallop("D2", "A1") },
+ Bb: { voicing: "[F3 Bb3 D4]", bass: gallop("Bb1", "F2") },
+ G7sus: { voicing: "[F3 G3 C4 D4]" }, G7: { voicing: "[F3 B3 D4 G4]" },
+ // the finish
+ CC: { voicing: "[E3 G3 C4 E4 G4]", bass: `C2:${T(4)} C2:${T(1)} G1:${T(1)}` },
+ E: { voicing: "[E3 G#3 B3 E4]" }, Am2: { voicing: "[E3 A3 C4 E4]" },
+ FF: { voicing: "[F3 A3 C4 F4]" }, GG: { voicing: "[G3 B3 D4 G4]" },
+ Cend: { voicing: "[C3 G3 C4 E4 G4 C5]", bass: "C2:2" },
+ },
+ motifs: {
+ fanA: `r:${T(1)} G3:${T(1)} C4:${T(1)} G4:${T(2)} F4:${T(1)}`,
+ fanB: `E4:${T(1)} F4:${T(1)} G4:${T(1)} A4:1`,
+ fanA2: `r:${T(1)} G3:${T(1)} C4:${T(1)} G4:${T(2)} A4:${T(1)}`,
+ fanQ: `B4:${T(1)} A4:${T(1)} B4:${T(1)} D5:1`,
+ // hook: the answer, landing home
+ hk2: `F#4:${T(1)} G4:${T(1)} A4:${T(1)} D5:1`,
+ hk3: `C5:${T(2)} A4:${T(1)} B4:${T(2)} G4:${T(1)}`,
+ home: `C5:${T(5)} r:${T(1)}`,
+ // bridge: the rising cell tossed between brass and flute
+ brA: `r:${T(1)} E3:${T(1)} A3:${T(1)} E4:1`,
+ brC: `r:${T(1)} F3:${T(1)} A3:${T(1)} D4:${T(2)} C4:${T(1)}`,
+ flB: `r:${T(1)} C5:${T(1)} F5:${T(1)} C6:1`,
+ flD: `r:${T(1)} D5:${T(1)} F5:${T(1)} Bb5:1`,
+ // climb
+ cl1: `G3:${T(1)} C4:${T(1)} D4:${T(1)} G3:${T(1)} C4:${T(1)} D4:${T(1)}`,
+ cl2: `B3:${T(1)} D4:${T(1)} F4:${T(1)} G4:1`,
+ // the finish in D: the fanfare augmented
+ fin1: `G3:${T(2)} C4:${T(2)} G4:${T(2)}`,
+ fin2: `G#4:${T(2)} B4:${T(1)} C5:1`,
+ fin3: `A4:${T(2)} C5:${T(1)} B4:${T(2)} D5:${T(1)}`,
+ fin4: `C5:${T(5)} r:${T(1)}`,
+ // flute counter: bright running 8ths answering the brass long notes
+ fl1: `r:1 E5:${T(1)} D5:${T(1)} C5:${T(1)}`, fl2: `r:1 A5:${T(1)} G5:${T(1)} E5:${T(1)}`,
+ fl3: `r:1 D6:${T(1)} C#6:${T(1)} A5:${T(1)}`, fl4: `r:1 A5:${T(1)} G#5:${T(1)} E5:${T(1)}`
+ , fl5: `r:1 C6:${T(1)} B5:${T(1)} G5:${T(1)}`,
+ },
+ grooves: {
+ main: { kick: [`C4:${T(2)} r:${T(4)}`], snare: [`r:${T(5)} C4:${T(1)}@0.6`], hat: [H], perc: timp },
+ build: { family: "build", density: 0.7 },
+ lift: { kick: [`C4:1 C4:1`], snare: [`r:1 C4:${T(2)} C4:${T(1)}@0.6`], hat: [H], perc: timp },
+ roll: { kick: [`C4:2`], perc: [Array.from({ length: 12 }, (_, i) => `C2:${T(0.5)}@${(0.35 + i * 0.05).toFixed(2)}`).join(" ")] },
+ },
+ sections: [
+ { kind: "intro", bars: 2, harmony: ["C", "F_C"], chordVel: 0.7, arp: [ost("C4", "E4", "G4"), ost("C4", "F4", "A4")] },
+ { kind: "verse", bars: 4, harmony: ["C", "F_C", "Am", "G"], lead: ["fanA", "fanB", "fanA2", "fanQ"],
+ arp: [ost("C4", "E4", "G4"), ost("C4", "F4", "A4"), ost("A3", "C4", "E4"), ost("G3", "B3", "D4")], energy: 0.5 },
+ { kind: "hook", bars: 4, harmony: ["C", "D", "F G", "C"], bass: [gallop("C2", "G2"), gallop("D2", "A2"), `F1:1 G1:1`, gallop("C2", "G2")],
+ lead: ["fanA", "hk2", "hk3", "home"], counter: ["fl1", "fl3", "r:2", "fl2"],
+ arp: [ost("C4", "E4", "G4"), ost("D4", "F#4", "A4"), `F4:${T(1)} A4:${T(1)} C5:${T(1)} G4:${T(1)} B4:${T(1)} D5:${T(1)}`, ost("C4", "E4", "G4")], energy: 0.7 },
+ { kind: "bridge", bars: 4, harmony: ["Am", "F", "Dm7", "Bb"], lead: ["brA", "r:2", "brC", "r:2"], counter: ["r:2", "flB", "r:2", "flD"],
+ arp: [ost("A3", "C4", "E4"), ost("F3", "A3", "C4"), ost("D4", "F4", "A4"), ost("D4", "F4", "Bb4")], energy: 0.5, chordVel: 0.85 },
+ { kind: "build", bars: 2, harmony: ["G7sus", "G7"], bass: [`G1:${T(1)} G1:${T(1)} G1:${T(1)} G1:${T(1)} G1:${T(1)} G1:${T(1)}`, `G1:${T(1)} G1:${T(1)} G1:${T(1)} G1:${T(1)} B1:${T(1)} D2:${T(1)}`],
+ lead: ["cl1", "cl2"], arp: [ost("C4", "D4", "G4"), ost("B3", "D4", "F4")], energy: 0.9 },
+ { kind: "drop", bars: 3, groove: "lift", harmony: ["CC", "E Am2", "FF GG"], bass: [`C2:${T(4)} C2:${T(1)} G1:${T(1)}`, `E1:1 A1:1`, `F1:1 G1:1`],
+ lead: ["fin1", "fin2", "fin3"], counter: ["fl5", "fl4", "r:2"],
+ arp: [ost("C4", "E4", "G4"), `E4:${T(1)} G#4:${T(1)} B4:${T(1)} E4:${T(1)} A4:${T(1)} C5:${T(1)}`, `F4:${T(1)} A4:${T(1)} C5:${T(1)} G4:${T(1)} B4:${T(1)} D5:${T(1)}`], energy: 1 },
+ { kind: "outro", bars: 1, groove: "roll", harmony: ["Cend"], lead: ["fin4"] },
+ ],
+});
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/stillwater.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/stillwater.ts
new file mode 100644
index 0000000..e59e8dc
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/blind/stillwater.ts
@@ -0,0 +1,46 @@
+// STILLWATER: a 45 s intro for a sleep and meditation app. ambient vocabulary, calm mood,
+// Db lydian, 3/4 at 52 bpm (a bar = 3.46 s, 12 bars + a long tail). No drums. A bell figure
+// that falls and then lifts by a step (a breath out, a small breath in), echoed by a pluck an
+// octave up; a slow celesta ripple keeps the water moving. It ends on the II chord over the
+// tonic pedal with the melody hanging on the 9th: floating, unresolved.
+import type { Material } from "../compose";
+
+export const stillwater = (): Material => ({
+ style: "ambient", title: "Stillwater", seed: 9013, mood: "calm",
+ bpm: 52, key: "Db", mode: "lydian", meter: "3/4", tail: 4.9,
+ levels: { lead: 10, arp: 5.9, chords: 0.4, counter: 1.3, bass: 0.3 } /* sound v2: re-balanced so every stem sits where the composer put it against its target (the notes are untouched); written for v1 as lead: 10.5, arp: 5, chords: 2, counter: 9 */,
+ moodControls: { energy: 0.15, warmth: 0.6, brightness: 0.4, tension: 0.1, space: 0.5 },
+ chords: {
+ I: { voicing: "[Ab3 C4 Eb4 F4]", bass: "Db2:3" },
+ iii: { voicing: "[Ab3 C4 Eb4 G4]", bass: "Db2:3" },
+ vi: { voicing: "[Ab3 Db4 F4 C5]", bass: "Bb1:3" },
+ Vadd9: { voicing: "[Bb3 C4 Eb4 G4]", bass: "Ab1:3" },
+ ivo: { voicing: "[Ab3 Bb3 Db4 F4]", bass: "G1:3" },
+ II: { voicing: "[G3 Bb3 Eb4 F4]", bass: "Db2:3" },
+ },
+ motifs: {
+ // the exhale: a long falling 4th, a step, then the small lift (the high point is the last note)
+ ex: "F5:1.5 C5:.5 Db5:1",
+ exR: "r:3",
+ // varied: the lift reaches the lydian G (the colour note, early)
+ exG: "F5:1.5 C5:.5 G5:1",
+ ex2: "Ab5:1.5 Eb5:.5 F5:1",
+ ex3: "G5:1.5 Db5:.5 Eb5:1",
+ // the last word: the exhale starts but stops on the 9th and hangs
+ last: "F5:1.5 C5:.5 Eb5:1",
+ // pluck echoes an octave up, late in the bar
+ e1: "r:2 F6:.5 Eb6:.5", e2: "r:2 G6:.5 Ab6:.5", e3: "r:2.5 Eb6:.5",
+ // celesta ripples: one onset a beat, never on the same pattern twice in a row
+ w1: "Db5:1 Ab5:1 C6:.5 Eb6:.5", w2: "Eb5:1 G5:.5 C6:.5 Ab5:1", w3: "Db5:1 F5:1 Db6:.5 C6:.5", w4: "G5:1 C6:.5 Eb6:.5 G5:1",
+ w5: "Bb4:1 Db5:.5 F5:.5 C6:1", w6: "Bb4:1 Eb5:1 G5:.5 F5:.5",
+ },
+ grooves: {},
+ sections: [
+ { kind: "intro", bars: 2, harmony: ["I"], chordVel: 0.6, arp: ["w1", "w2"] },
+ { kind: "verse", groove: null, bars: 4, harmony: ["I", "iii", "vi", "vi"], chordVel: 0.75,
+ lead: ["ex", "exR", "exG", "exR"], counter: ["r:3", "e1", "r:3", "e2"], arp: ["w3", "w4", "w5", "w3"] },
+ { kind: "bridge", groove: null, bars: 4, harmony: ["Vadd9", "ivo", "iii", "vi"], chordVel: 0.7,
+ lead: ["ex2", "exR", "ex3", "r:3"], counter: ["r:3", "e3", "r:3", "e1"], arp: ["w6", "w5", "w2", "w3"] },
+ { kind: "outro", bars: 2, harmony: ["II"], chordVel: 0.6, lead: ["last", "r:3"], arp: ["w6", "Eb5:1 G5:.5 Bb5:.5 F5:1"] },
+ ],
+});
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/compose.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/compose.ts
index dc1b9dd..086a8bb 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/compose.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/compose.ts
@@ -8,9 +8,10 @@ import type { ModeId } from "./theory";
import type { MoodId, StyleId, MelodyType } from "./tables";
import { pcOf } from "./theory";
import { perform } from "./perform";
-import { drumBar, type Groove, type Lane } from "./grooves";
+import { drumBar, laneKind, type Groove, type Lane } from "./grooves";
import { VOCAB_TRIM, VOCAB_TARGET_FIX } from "./vocabTrim";
import { VOCAB, KINDS, BASE_SLOTS, resolveVoice, moodVoice, moodFx, fullMood, type Slot, type Voice, type SectionKind, type MoodControls } from "./vocab";
+import type { MixProfile } from "./mixProfiles";
/** One chord of YOUR harmony: its voicing (a notation chord) and a one-bar bass line you wrote for it. */
export type ComposedChord = { voicing: string; bass?: string };
@@ -40,6 +41,8 @@ export type Material = {
/** 0.5 straight .. 0.67 hard swing (default the style's lower bound) */ swing?: number;
/** the piece's dynamic level [start, end] 0..1, ramped over the whole piece (default [0.62, 0.66]); section `energy` shapes it locally */ dyn?: [number, number];
/** seconds of ring-out after the last onset (default 3.2) */ tail?: number; loop?: boolean;
+ /** a shipped score frozen on the old sound (the launch film): never set this for a new piece */ legacy?: boolean;
+ /** override the style's mix/space/feel profile (mixProfiles.ts), e.g. { space: {...}, feel: "tight" } */ mix?: Partial<MixProfile>;
};
/** line() with the composer's context on its error: which section, slot or chord wrote the bad bar. */
@@ -96,7 +99,7 @@ export const composePiece = (m: Material): Piece => {
const g = m.grooves?.[gname];
need(g, `section "${x.id}" (${x.s.kind}) needs a groove "${gname}": add grooves["${gname}"] = { family: one of ${vocab.grooves.join(", ")}, density, variation } or write it (kick/snare/ghost/hat bars), or set groove: null.`);
const bar = drumBar(g!, meter, m.seed, b, b - x.from, x.s.bars, x.s.energy ?? 0.5);
- for (const ln of lanes) if (bar[ln]) push(ln, lineIn(`section "${x.id}" ${ln} (bar ${b})`, b * bpb, bar[ln]!, { role: "drum", v: vel[ln], bpb }));
+ for (const ln of lanes) if (bar[ln]) push(ln, lineIn(`section "${x.id}" ${ln} (bar ${b})`, b * bpb, bar[ln]!, { role: "drum", v: vel[ln], bpb, kind: laneKind(g!, ln) }));
}
}
const warnings: string[] = [];
@@ -128,7 +131,8 @@ export const composePiece = (m: Material): Piece => {
v = resolveVoice(v, m.bpm);
let dGain = 0; if (mood) { const r = moodVoice(slot, v, mood); v = r.voice; dGain = r.dGain; }
const lv = m.levels?.[slot];
- const trim = pick !== undefined ? 0 : VOCAB_TRIM[vocab.id]?.[slot] ?? 0; let gainDb = trim ? v.gainDb + trim : v.gainDb; if (lv) gainDb += lv;
+ // a legacy (shipped) score keeps the gains it was listened at: no trim
+ const trim = pick !== undefined || m.legacy ? 0 : VOCAB_TRIM[vocab.id]?.[slot] ?? 0; let gainDb = trim ? v.gainDb + trim : v.gainDb; if (lv) gainDb += lv;
// a timpani (or any pitched drum voice) playing a drum lane is tuned to the key: the tonic in its low register
if (v.inst === "timpani" && role(slot) === "drum" && typeof pick !== "object") { const tp = pcOf(m.key.replace(/m$/, "")), lo = typeof v.opts?.pitch === "number" ? (v.opts.pitch as number) - 5 : slot === "kick" ? 31 : 38; /* the tonic nearest the voice's own register */ v = { ...v, opts: { ...(v.opts ?? {}), pitch: lo + ((tp - (lo % 12) + 12) % 12) } }; }
if (vocab.stemTargets[slot] !== undefined) targets[slot] = vocab.stemTargets[slot] + dGain + (pick === undefined ? VOCAB_TARGET_FIX[vocab.id]?.[slot] ?? 0 : 0); // a mood that lifts the hats lifts their target too
@@ -144,10 +148,11 @@ export const composePiece = (m: Material): Piece => {
const planSections = regions.length === 1 ? [{ id: "a", bars: B, mood: m.mood, key: m.key, mode: m.mode, melody: ["stepwise", "hook"] as MelodyType[], dyn, ending: "tail" as const, repeatable: false }]
: regions.map((r, i) => ({ id: `key${i}`, bars: r.to - r.from, mood: m.mood, key: r.key, mode: r.mode, melody: ["stepwise", "hook"] as MelodyType[], dyn: [lvl(r.from), lvl(r.to)] as [number, number], ending: "tail" as const, repeatable: false }));
const piece: Piece = {
- title: m.title, seed: m.seed, tail: m.tail ?? 3.2, harmony, parts,
+ title: m.title, seed: m.seed, tail: m.tail ?? 3.2, harmony, parts, ...(m.legacy ? { legacy: true } : {}),
plan: { style: m.style, tempo: m.bpm, meter, swing: m.swing ?? vocab.swing[0], ritard: m.loop ? 1 : 0.92, loop: m.loop,
sections: planSections },
fx: mood ? moodFx(vocab.fx, mood) : vocab.fx, stemTargets: targets,
+ ...(m.mix ? { mix: m.mix } : {}),
arrangement: lay.map((x) => ({ id: x.id, kind: x.s.kind, from: x.from, bars: x.s.bars })),
warnings, refit: m.loop ? undefined : (seconds: number) => composePiece(refitMaterial(m, seconds)),
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/drums.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/drums.ts
new file mode 100644
index 0000000..386749a
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/drums.ts
@@ -0,0 +1,384 @@
+// DRUM KITS, in code. One voice renders any piece of a kit: the lane gives the default piece, a
+// note's `kind` or its General-MIDI pitch picks another (C4 = the lane's own piece). Six kit
+// characters: acoustic (studio kit), 808, 909, dusty (a sampled break: 26 kHz / 12-bit), brush
+// (jazz), orch (concert bass drum, concert snare, clash cymbals; timpani below).
+// Every hit is new: seeded round-robin (tune, decay, level, noise, strike spectrum), free-running
+// oscillator phases, velocity changes the timbre (pitch sweep, click, wire share, brightness), and
+// each piece sits at its own place on the stereo stage (audience view: hats right, ride and floor
+// tom left). Choke: a closed or pedal hat anywhere in the piece stops a ringing open hat.
+// Physics used: circular-membrane mode ratios 1, 1.59, 2.14, 2.30, 2.65, 2.92 (Rossing, Science of
+// Percussion Instruments); TR-808 metal bank 205.3/304.4/369.6/522.7/540/800 Hz squares (Roland
+// service notes, as in Tone.js MetalSynth, MIT); PhISEM stochastic shakers (Cook 1997, STK, MIT-style);
+// timpani (1,1)..(6,1) ratios 1, 1.50, 1.98, 2.44, 2.90, 3.37 (Rossing/Fletcher). All reimplemented.
+import { type Rng, TAU, clamp, pan, SVF, blep, db, gauss } from "./dsp";
+import type { Played } from "./perform";
+import { rng as mkRng } from "../core";
+
+type Out = { L: Float32Array; R: Float32Array };
+type Opts = Record<string, number | boolean | string>;
+type Buf = Float64Array;
+
+export type KitId = "acoustic" | "808" | "909" | "dusty" | "brush" | "orch";
+export const KITS: KitId[] = ["acoustic", "808", "909", "dusty", "brush", "orch"];
+/** The kit a style plays when its palette names none (opts.kit overrides). */
+export const STYLE_KIT: Record<string, KitId> = {
+ lofiElectronic: "808", drive: "909", cinematic: "orch", ambient: "808", folk: "brush", playful: "acoustic", minimalist: "acoustic", jazz: "brush",
+ lofi: "dusty", orchestral: "orch", suspense: "orch", rock: "acoustic", hipHop: "808", house: "909", synthwave: "909", world: "acoustic", choral: "orch",
+};
+export type DrumPiece = "kick" | "snare" | "rimshot" | "ghost" | "cross" | "clap" | "hat" | "open" | "pedal" | "ride" | "bell" | "crash" | "tomHi" | "tomMid" | "tomLo"
+ | "shaker" | "tamb" | "brush" | "sweep" | "dum" | "tek" | "ka" | "cowbell";
+const PIECES = new Set<string>(["kick", "snare", "rimshot", "ghost", "cross", "clap", "hat", "open", "pedal", "ride", "bell", "crash", "tomHi", "tomMid", "tomLo", "shaker", "tamb", "brush", "sweep", "dum", "tek", "ka", "cowbell"]);
+/** note kinds: lane names, the old one-letter kinds, and piece names */
+const ALIAS: Record<string, DrumPiece> = { k: "kick", s: "snare", h: "hat", o: "open", p: "pedal", perc: "shaker", ghost: "ghost", kick: "kick", snare: "snare", hat: "hat" };
+/** General MIDI percussion (35-81) -> piece. C4 (60) is never here: it is the lane's own piece. */
+export const GM_DRUMS: Record<number, DrumPiece> = {
+ 35: "kick", 36: "kick", 37: "cross", 38: "snare", 39: "clap", 40: "rimshot", 41: "tomLo", 42: "hat", 43: "tomLo", 44: "pedal", 45: "tomMid", 46: "open", 47: "tomMid",
+ 48: "tomHi", 49: "crash", 50: "tomHi", 51: "ride", 52: "crash", 53: "bell", 54: "tamb", 55: "crash", 56: "cowbell", 57: "crash", 59: "ride", 61: "tek", 62: "ka", 63: "tek", 64: "dum", 69: "shaker", 70: "shaker",
+};
+export const pieceOf = (k: { p: number; kind?: string }, inst: string, o: Opts): DrumPiece => {
+ if (k.p !== 60 && GM_DRUMS[k.p]) return GM_DRUMS[k.p];
+ if (typeof o.piece === "string" && PIECES.has(o.piece)) return o.piece as DrumPiece;
+ const kd = k.kind ? (PIECES.has(k.kind) ? (k.kind as DrumPiece) : ALIAS[k.kind]) : undefined;
+ if (kd) return kd === "ghost" && o.rim === true ? "cross" : kd;
+ return inst === "kick" ? "kick" : inst === "snare" ? (o.rim === true ? "cross" : "snare") : "hat";
+};
+export const kitOf = (o: Opts, style?: string): KitId => (typeof o.kit === "string" && (KITS as string[]).includes(o.kit) ? (o.kit as KitId) : STYLE_KIT[style ?? ""] ?? "acoustic");
+
+// ---------------------------------------------------------------- stage and feel
+/** Audience-view placement, -1 left .. 1 right. */
+const PAN: Record<DrumPiece, number> = { kick: 0, snare: 0.06, rimshot: 0.06, ghost: 0.06, cross: 0.08, clap: 0, hat: 0.34, open: 0.34, pedal: 0.3, ride: -0.38, bell: -0.38, crash: 0.42,
+ tomHi: 0.2, tomMid: -0.05, tomLo: -0.32, shaker: -0.45, tamb: 0.5, brush: 0.06, sweep: 0.06, dum: -0.1, tek: 0.15, ka: 0.3, cowbell: -0.2 };
+// Microtiming is NOT here: perform.ts owns the feel (mixProfiles FEELS, keyed by the style: lane offsets, humanize,
+// jitter, hat drift) and hands the kit keys that are already placed. A kit adding its own offsets doubled them (the
+// dusty snare landed 35 ms late instead of 18; measured at the sound-v2 merge).
+
+// ---------------------------------------------------------------- building blocks
+type Var = { g: number; tune: number; dec: number; bright: number; ph: number; wire: number };
+/** Snare-on-snare variance (the research numbers): +-0.7 dB, +-1.5 % tune, +-10 % decay, +-6 % brightness. */
+const vary = (r: Rng): Var => ({ g: db(clamp(gauss(r), -2, 2) * 0.7), tune: 1 + (r() - 0.5) * 0.03, dec: 1 + (r() - 0.5) * 0.2, bright: 1 + (r() - 0.5) * 0.12, ph: r(), wire: 1 + (r() - 0.5) * 0.2 });
+const nz = (r: Rng) => r() * 2 - 1;
+const lenOf = (sr: number, s: number) => Math.max(1, Math.ceil(s * sr));
+/** Membrane: modes (ratio, amp, tau) sharing one pitch glide (tension modulation), higher modes cut by a soft strike. */
+const membrane = (sr: number, f: number, modes: readonly (readonly [number, number, number])[], o: { v: number; glide: number; glideTau: number; hard: number; rise?: number; ph?: number; len: number }): Buf => {
+ const N = lenOf(sr, o.len), y = new Float64Array(N), rise = Math.max(1, (o.rise ?? 0.0004) * sr);
+ for (let m = 0; m < modes.length; m++) {
+ const [ratio, a0, tau] = modes[m], fm = f * ratio; if (fm > sr * 0.45) continue;
+ const a = a0 * Math.pow(o.hard, ratio - 1), dk = Math.exp(-1 / (tau * sr)), gk = Math.exp(-1 / (o.glideTau * sr)), M = Math.min(N, Math.ceil(tau * 9 * sr));
+ let ph = ((o.ph ?? 0) + m * 0.137) % 1, env = a, gl = o.glide;
+ for (let i = 0; i < M; i++) { ph += (fm * (1 + gl)) / sr; gl *= gk; env *= dk; y[i] += Math.sin(TAU * ph) * env * Math.min(1, i / rise); }
+ }
+ return y;
+};
+/** Short band-limited noise burst: a click (stick, beater, tip). */
+const click = (sr: number, r: Rng, f: number, q: number, tau: number, amp: number, len = tau * 8): Buf => {
+ const N = lenOf(sr, len), y = new Float64Array(N), bp = new SVF(sr, f, q), k = Math.exp(-1 / (tau * sr)); let e = amp;
+ for (let i = 0; i < N; i++) { bp.tick(nz(r)); y[i] = bp.bp * e; e *= k; }
+ return y;
+};
+const add = (a: Buf, b: Buf, g = 1, at = 0) => { const n = Math.min(b.length, a.length - at); for (let i = 0; i < n; i++) a[at + i] += b[i] * g; return a; };
+const sat = (y: Buf, drive: number) => { if (drive <= 1) return y; const k = Math.tanh(drive); for (let i = 0; i < y.length; i++) y[i] = Math.tanh(y[i] * drive) / k; return y; };
+
+// ---------------------------------------------------------------- kick
+type KickP = { f: number; sweep: number; tauP: number; dec: number; modes: [number, number, number][]; click: number; clickF: number; drive: number; rise: number; shell?: number };
+const KICK: Record<KitId, KickP> = {
+ acoustic: { f: 57, sweep: 1.5, tauP: 0.03, dec: 0.19, modes: [[1, 1, 1], [1.59, 0.3, 0.35], [2.14, 0.16, 0.25]], click: 0.55, clickF: 2800, drive: 1.3, rise: 0.0006, shell: 0.12 },
+ "808": { f: 49, sweep: 2.1, tauP: 0.045, dec: 0.42, modes: [[1, 1, 1]], click: 0.18, clickF: 3000, drive: 1.5, rise: 0.0003 },
+ "909": { f: 52, sweep: 4.4, tauP: 0.022, dec: 0.26, modes: [[1, 1, 1]], click: 0.75, clickF: 4500, drive: 2.4, rise: 0.0002 },
+ dusty: { f: 54, sweep: 2.0, tauP: 0.035, dec: 0.24, modes: [[1, 1, 1], [1.59, 0.22, 0.3]], click: 0.4, clickF: 2200, drive: 1.9, rise: 0.0006, shell: 0.08 },
+ brush: { f: 66, sweep: 1.25, tauP: 0.04, dec: 0.32, modes: [[1, 1, 1], [1.59, 0.35, 0.45], [2.14, 0.2, 0.3], [2.3, 0.12, 0.25]], click: 0.2, clickF: 1500, drive: 1.1, rise: 0.0012, shell: 0.06 },
+ orch: { f: 43, sweep: 1.06, tauP: 0.08, dec: 1.35, modes: [[1, 1, 1], [1.59, 0.5, 0.6], [2.14, 0.4, 0.45], [2.3, 0.3, 0.4], [2.65, 0.22, 0.35], [2.92, 0.16, 0.3], [3.16, 0.1, 0.25]], click: 0.06, clickF: 700, drive: 1, rise: 0.004 },
+};
+const kickSyn = (sr: number, r: Rng, v: number, x: Var, P: KickP): Buf => {
+ // beater and head vary more than a snare: +-2.5 % pitch, +-15 % sweep, the strike point moves the overtone mix
+ const f = P.f * (1 + (x.tune - 1) * 1.7), dec = P.dec * x.dec, sweep = 1 + (P.sweep - 1) * (0.45 + 0.55 * v) * (0.85 + 0.3 * r()), mix = P.modes.map(([ratio], m) => (m ? (0.7 + 0.6 * r()) * Math.pow(0.35 + 0.65 * v, (ratio - 1) * 2) : 1)), N = lenOf(sr, Math.min(3, dec * 7)), y = new Float64Array(N), rise = P.rise * sr;
+ const phs = P.modes.map((_, m) => (x.ph * 0.08 + m * 0.21) % 1), kp = Math.exp(-1 / (P.tauP * (0.85 + 0.3 * r()) * sr));
+ let sw = sweep - 1;
+ for (let i = 0; i < N; i++) {
+ const t = i / sr, fq = f * (1 + sw); sw *= kp; let s = 0;
+ for (let m = 0; m < P.modes.length; m++) { const [ratio, a, d] = P.modes[m]; phs[m] += (fq * ratio) / sr; s += Math.sin(TAU * phs[m]) * a * mix[m] * Math.exp(-t / (dec * d)); }
+ y[i] = s * Math.min(1, i / rise);
+ }
+ sat(y, P.drive * (0.8 + 0.4 * v));
+ add(y, click(sr, r, P.clickF * (0.6 + 0.7 * v) * x.bright, 0.8, 0.0015, P.click * Math.pow(v, 1.5)));
+ if (P.shell) add(y, membrane(sr, 172 * x.tune, [[1, 1, 0.05], [1.6, 0.5, 0.03]], { v, glide: 0, glideTau: 1, hard: 0.6, len: 0.3 }), P.shell * v);
+ if (P.f < 45) add(y, click(sr, r, 180, 0.6, 0.02, 0.25 * v)); // felt beater thump into a big head
+ return y;
+};
+
+// ---------------------------------------------------------------- snare, clap, rim
+type SnareP = { f: number; modes: [number, number, number][]; glide: number; wire: number; wireDec: number; hp: number; lp: number; buzz: number; stick: number; drive: number; tone: number };
+const MEM6 = (d: number): [number, number, number][] => [[1, 1, d], [1.59, 0.62, d * 0.62], [2.14, 0.48, d * 0.5], [2.3, 0.34, d * 0.44], [2.65, 0.26, d * 0.38], [2.92, 0.2, d * 0.33]];
+const SNARE: Record<KitId, SnareP> = {
+ acoustic: { f: 192, modes: MEM6(0.085), glide: 0.045, wire: 0.95, wireDec: 0.075, hp: 1900, lp: 9500, buzz: 0.6, stick: 0.5, drive: 1.2, tone: 0.75 },
+ "808": { f: 238, modes: [[1, 1, 0.075], [2, 0.55, 0.045]], glide: 0, wire: 0.8, wireDec: 0.05, hp: 1800, lp: 13000, buzz: 0, stick: 0.12, drive: 1.1, tone: 0.8 },
+ "909": { f: 186, modes: [[1, 1, 0.07], [1.79, 0.62, 0.045]], glide: 0.16, wire: 1.05, wireDec: 0.065, hp: 1300, lp: 10000, buzz: 0, stick: 0.3, drive: 1.8, tone: 0.72 },
+ dusty: { f: 176, modes: MEM6(0.12), glide: 0.04, wire: 1.0, wireDec: 0.09, hp: 1500, lp: 7200, buzz: 0.55, stick: 0.35, drive: 1.6, tone: 0.8 },
+ brush: { f: 200, modes: MEM6(0.09), glide: 0.03, wire: 0.8, wireDec: 0.08, hp: 1700, lp: 8500, buzz: 0.6, stick: 0.3, drive: 1, tone: 0.65 },
+ orch: { f: 228, modes: MEM6(0.07), glide: 0.035, wire: 1.2, wireDec: 0.055, hp: 2400, lp: 11500, buzz: 0.5, stick: 0.45, drive: 1, tone: 0.55 },
+};
+const snareSyn = (sr: number, r: Rng, v: number, x: Var, P: SnareP, kind: "snare" | "rimshot" | "ghost"): Buf => {
+ const rim = kind === "rimshot", hard = clamp(0.35 + 0.65 * v, 0, 1) * x.bright, len = Math.min(1.2, Math.max(P.wireDec * 10, P.modes[0][2] * 7));
+ const mem = membrane(sr, P.f * x.tune, P.modes, { v, glide: P.glide * v, glideTau: 0.02, hard, ph: x.ph, len });
+ let peak = 1e-9; for (let i = 0; i < mem.length; i++) peak = Math.max(peak, Math.abs(mem[i]));
+ const N = mem.length, y = new Float64Array(N), hp1 = new SVF(sr, P.hp, 0.7), hp2 = new SVF(sr, P.hp, 0.7), lp = new SVF(sr, P.lp * (0.75 + 0.35 * v) * x.bright, 0.7), lp2 = new SVF(sr, P.lp * 1.3, 0.6);
+ // wires: rattling against the bottom head, so the noise is amplitude-modulated by the membrane (the buzz); longer and a bigger share at ff
+ const wAmt = P.wire * (kind === "ghost" ? 0.75 : 0.55 + 0.6 * v) * x.wire, wTau = P.wireDec * (0.7 + 0.5 * v) * x.dec, kw = Math.exp(-1 / (wTau * sr)), on = Math.exp(-1 / (0.0012 * sr));
+ let e = 1, o = 1;
+ for (let i = 0; i < N; i++) {
+ hp1.tick(nz(r)); hp2.tick(hp1.hp); lp.tick(hp2.hp); lp2.tick(lp.lp);
+ const buzz = 1 - P.buzz + P.buzz * Math.min(1.6, (Math.abs(mem[i]) / peak) * 2.2);
+ y[i] = mem[i] * P.tone * (rim ? 0.8 : 1) + lp2.lp * e * (1 - o) * wAmt * buzz * 2.2; e *= kw; o *= on;
+ }
+ add(y, click(sr, r, 3500 * x.bright, 0.7, 0.0007, P.stick * v * v * 1.4));
+ if (rim) { add(y, membrane(sr, 880 * x.tune, [[1, 1, 0.05], [1.93, 0.6, 0.03], [3.1, 0.4, 0.015]], { v, glide: 0, glideTau: 1, hard: 1, len: 0.4 }), 0.45); add(y, click(sr, r, 5000, 0.5, 0.001, 1.2 * v)); }
+ return sat(y, P.drive);
+};
+const clapSyn = (sr: number, r: Rng, v: number, x: Var, kit: KitId): Buf => {
+ const machine = kit === "808" || kit === "909", tail = (kit === "808" ? 0.14 : kit === "909" ? 0.1 : 0.085) * x.dec, bursts = machine ? 4 : 3 + Math.floor(r() * 3);
+ const N = lenOf(sr, 0.06 + tail * 7), y = new Float64Array(N);
+ let t0 = 0;
+ for (let b = 0; b < bursts; b++) {
+ const last = b === bursts - 1, fc = (machine ? (kit === "808" ? 1050 : 1250) : 1300 + r() * 900) * x.bright, bp = new SVF(sr, fc, machine ? 1.3 : 1.1), hp = new SVF(sr, 650, 0.7);
+ const i0 = Math.round(t0 * sr), tau = last ? tail : 0.0024, k = Math.exp(-1 / (tau * sr)), M = Math.min(N - i0, Math.ceil(tau * 8 * sr)); let e = last ? 1 : 0.85 + 0.3 * r();
+ for (let i = 0; i < M; i++) { bp.tick(nz(r)); hp.tick(bp.bp); y[i0 + i] += hp.hp * e * Math.min(1, i / (0.0003 * sr)); e *= k; }
+ t0 += (machine ? 0.0095 : 0.006 + r() * 0.01) * (0.8 + 0.4 * r());
+ }
+ for (let i = 0; i < N; i++) y[i] *= 2.6 * (0.5 + 0.5 * v);
+ return y;
+};
+const crossSyn = (sr: number, r: Rng, v: number, x: Var, kit: KitId): Buf => {
+ const machine = kit === "808" || kit === "909"; // the 808 rim shot: two bridged-T rings at 455 and 1667 Hz
+ const modes: [number, number, number][] = machine ? [[1, 1, 0.011], [3.664, 0.8, 0.008]] : [[1, 1, 0.03], [2.3, 0.6, 0.018], [3.66, 0.42, 0.011], [5.9, 0.25, 0.007]];
+ const y = membrane(sr, (machine ? 455 : 470) * x.tune, modes, { v, glide: 0, glideTau: 1, hard: 0.6 + 0.4 * v, ph: x.ph, len: 0.15 });
+ return add(y, click(sr, r, machine ? 6000 : 2400, 0.7, 0.0006, machine ? 0.3 : 0.9));
+};
+
+// ---------------------------------------------------------------- hats, cymbals
+const METAL = [205.3, 304.4, 369.6, 522.7, 540, 800];
+type HatP = { scale: number[]; noise: number; bp: number; q: number; hp: number; closed: number; open: number; pedal: number; lp: number };
+const HAT: Record<KitId, HatP> = {
+ acoustic: { scale: [1.47, 1.73], noise: 0.45, bp: 8200, q: 0.8, hp: 5800, closed: 0.042, open: 0.46, pedal: 0.03, lp: 15000 },
+ "808": { scale: [1], noise: 0.04, bp: 9500, q: 1.1, hp: 7000, closed: 0.032, open: 0.34, pedal: 0.026, lp: 18000 },
+ "909": { scale: [1.21], noise: 0.35, bp: 10500, q: 0.9, hp: 7500, closed: 0.026, open: 0.3, pedal: 0.024, lp: 17000 },
+ dusty: { scale: [1.41, 1.66], noise: 0.5, bp: 7200, q: 0.8, hp: 5200, closed: 0.045, open: 0.42, pedal: 0.03, lp: 9500 },
+ brush: { scale: [1.43, 1.69], noise: 0.4, bp: 7600, q: 0.8, hp: 5000, closed: 0.05, open: 0.5, pedal: 0.035, lp: 13000 },
+ orch: { scale: [1.39, 1.61], noise: 0.45, bp: 7400, q: 0.8, hp: 5200, closed: 0.045, open: 0.5, pedal: 0.03, lp: 12000 },
+};
+/** Square bank through band-pass and a 4-pole high-pass; open hats shimmer (the two cymbals rattle) and are choked. */
+const hatSyn = (sr: number, r: Rng, v: number, x: Var, P: HatP, piece: "hat" | "open" | "pedal", chokeIn: number): Buf => {
+ const dec = (piece === "pedal" ? P.pedal : piece === "open" ? P.open * (0.75 + 0.45 * v) : P.closed * (0.8 + 0.45 * v)) * x.dec;
+ const N = Math.min(lenOf(sr, dec * 7), chokeIn + Math.round(0.04 * sr)), y = new Float64Array(N);
+ const osc = P.scale.flatMap((s, b) => METAL.map((f) => ({ inc: (f * s * (1 + (r() - 0.5) * 0.004)) / sr, ph: r(), g: b ? 0.8 : 1 })));
+ const bp = new SVF(sr, P.bp * (0.7 + 0.45 * v) * x.bright, P.q), h1 = new SVF(sr, P.hp, 0.7), h2 = new SVF(sr, P.hp, 0.7), lp = new SVF(sr, P.lp * (0.55 + 0.45 * v), 0.7), am = new SVF(sr, 38, 0.7);
+ const k = Math.exp(-1 / (dec * sr)), kc = Math.exp(-1 / (0.005 * sr)), atk = Math.max(1, 0.00025 * sr); let e = 1, s0 = 0;
+ const mix = 1 / osc.length;
+ for (let i = 0; i < N; i++) {
+ let m = 0; for (const o of osc) { let s = o.ph < 0.5 ? 1 : -1; s += blep(o.ph, o.inc); let q = o.ph + 0.5; if (q >= 1) q -= 1; s -= blep(q, o.inc); m += s * o.g; o.ph += o.inc; if (o.ph >= 1) o.ph -= 1; }
+ const src = m * mix * 2.2 * (1 - P.noise) + nz(r) * P.noise;
+ bp.tick(src); h1.tick(bp.bp); h2.tick(h1.hp); lp.tick(h2.hp);
+ const shim = piece === "open" ? 1 + 0.9 * am.tick(nz(r)) : 1;
+ if (i >= chokeIn) e *= kc;
+ y[i] = lp.lp * e * shim * Math.min(1, i / atk); e *= k; s0 = y[i];
+ }
+ void s0;
+ if (piece === "pedal" || (piece === "hat" && v > 0.72)) add(y, click(sr, r, piece === "pedal" ? 2100 : 3600, 1.2, piece === "pedal" ? 0.01 : 0.006, (piece === "pedal" ? 0.5 : 0.25) * v));
+ return y;
+};
+type CymPartial = { f: number; a: number; tau: number; rise: number; p: number };
+type CymP = { n: number; lo: number; hi: number; fc: number; oct: number; T: number; rise: number; wash: number; stick: number; maxS: number; bell?: boolean; seed: number };
+const CYM: Record<string, CymP> = {
+ ride: { n: 90, lo: 330, hi: 13000, fc: 4200, oct: 1.2, T: 2.2, rise: 0.004, wash: 0.25, stick: 0.8, maxS: 3.2, seed: 11 },
+ bell: { n: 26, lo: 480, hi: 9000, fc: 1500, oct: 1.0, T: 1.9, rise: 0.001, wash: 0.1, stick: 0.5, maxS: 3, bell: true, seed: 13 },
+ crash: { n: 130, lo: 300, hi: 15000, fc: 5600, oct: 1.4, T: 1.5, rise: 0.03, wash: 0.7, stick: 0.6, maxS: 4, seed: 17 },
+ cymbal: { n: 150, lo: 220, hi: 13000, fc: 3800, oct: 1.4, T: 2.6, rise: 0.05, wash: 0.8, stick: 0.3, maxS: 6, seed: 19 },
+ ride808: { n: 18, lo: 400, hi: 11000, fc: 5500, oct: 1.0, T: 1.0, rise: 0.003, wash: 0.4, stick: 0.3, maxS: 2.2, seed: 23 },
+};
+const cymTables = new Map<string, CymPartial[]>();
+/** One cymbal's partials, fixed per cymbal (the same cymbal every hit; the strike changes the mix). */
+const cymTable = (id: string, P: CymP): CymPartial[] => {
+ let t = cymTables.get(id); if (t) return t;
+ const r = mkRng(P.seed * 7919 + 3); t = [];
+ for (let i = 0; i < P.n; i++) {
+ const u = (i + 0.2 + 0.6 * r()) / P.n, f = P.lo * Math.pow(P.hi / P.lo, u), oc = Math.log2(f / P.fc);
+ let a = Math.exp(-0.5 * (oc / P.oct) ** 2) * (0.6 + 0.4 * r());
+ if (P.bell) a = Math.pow(0.82, i) * (0.7 + 0.3 * r()); else a *= Math.sqrt(40 / P.n); // denser = each mode smaller, same loudness
+ t.push({ f, a, tau: clamp(P.T * Math.pow(1500 / f, 0.45) * (0.7 + 0.6 * r()), 0.08, P.T * 2.2), rise: P.rise * Math.pow(f / 2000, 1.2) * (0.5 + r()), p: (r() - 0.5) * 1.1 });
+ }
+ cymTables.set(id, t); return t;
+};
+const cymSyn = (sr: number, r: Rng, v: number, x: Var, id: string, soft = false): [Buf, Buf] => {
+ const P = CYM[id], tab = cymTable(id, P), N = lenOf(sr, P.maxS * (0.7 + 0.4 * v)), L = new Float64Array(N), R = new Float64Array(N), tilt = 0.7 * (v - 0.7) + (x.bright - 1) * 2;
+ for (const q of tab) {
+ const f = q.f * (1 + (x.tune - 1) * 0.15); if (f > sr * 0.45) continue;
+ const a = q.a * Math.pow(f / 2000, tilt) * (0.75 + 0.5 * r()), tau = q.tau * x.dec, M = Math.min(N, Math.ceil(tau * Math.log(Math.max(2, a * 3e4)) * sr)); if (M <= 0) continue;
+ const w = (TAU * f) / sr, cw = Math.cos(w), sw = Math.sin(w), d = Math.exp(-1 / (tau * sr)), ph = TAU * r(), riseS = (soft ? q.rise * 3 + 0.012 : q.rise / (0.5 + v)) * sr, kr = riseS > 1 ? Math.exp(-1 / riseS) : 0;
+ const [gl, gr] = pan(q.p); let c = Math.cos(ph) * a, s = Math.sin(ph) * a, re = 1;
+ for (let i = 0; i < M; i++) { const y = s * (1 - re); L[i] += y * gl; R[i] += y * gr; const c2 = (c * cw - s * sw) * d; s = (c * sw + s * cw) * d; c = c2; re *= kr; }
+ }
+ // wash: the dense top the partial list cannot hold, decorrelated per side
+ if (P.wash) { const hl = new SVF(sr, 4500, 0.7), hr = new SVF(sr, 4500, 0.7), k = Math.exp(-1 / (P.T * 0.45 * x.dec * sr)), M = Math.min(N, Math.ceil(P.T * 3 * sr)); let e = P.wash * 0.35 * (0.5 + 0.5 * v);
+ const rs = Math.max(1, (soft ? 0.03 : P.rise) * sr); for (let i = 0; i < M; i++) { hl.tick(nz(r)); hr.tick(nz(r)); const g = e * (1 - Math.exp(-i / rs)); L[i] += hl.hp * g; R[i] += hr.hp * g; e *= k; } }
+ if (!soft) { const c = click(sr, r, 6500, 0.6, 0.0012, P.stick * v); add(L, c, 0.9); add(R, c, 0.9); }
+ return [L, R];
+};
+
+// ---------------------------------------------------------------- toms, hand drums, cowbell
+const TOM: Record<"tomHi" | "tomMid" | "tomLo", [number, number]> = { tomHi: [196, 0.34], tomMid: [147, 0.42], tomLo: [98, 0.55] };
+const tomSyn = (sr: number, r: Rng, v: number, x: Var, piece: "tomHi" | "tomMid" | "tomLo", kit: KitId): Buf => {
+ const [f, d] = TOM[piece], machine = kit === "808" || kit === "909", tune = kit === "808" ? 0.82 : kit === "909" ? 0.95 : 1;
+ const modes: [number, number, number][] = machine ? [[1, 1, d * 0.9]] : [[1, 1, d], [1.59, 0.5, d * 0.5], [2.14, 0.35, d * 0.35], [2.3, 0.25, d * 0.3], [2.65, 0.18, d * 0.25], [2.92, 0.12, d * 0.2]];
+ const y = membrane(sr, f * tune * x.tune, modes, { v, glide: (machine ? 0.35 : 0.07) * (0.5 + 0.5 * v), glideTau: machine ? 0.05 : 0.04, hard: (0.4 + 0.6 * v) * x.bright, ph: x.ph, len: d * x.dec * 7 });
+ sat(y, machine ? 1.4 : 1.1);
+ return add(y, click(sr, r, kit === "brush" ? 1800 : 3200, 0.8, 0.001, (machine ? 0.15 : 0.5) * v));
+};
+const handSyn = (sr: number, r: Rng, v: number, x: Var, piece: "dum" | "tek" | "ka"): Buf => {
+ if (piece === "dum") { const y = membrane(sr, 88 * x.tune, [[1, 1, 0.3], [1.59, 0.45, 0.15], [2.14, 0.3, 0.1], [2.3, 0.2, 0.08]], { v, glide: 0.06 * v, glideTau: 0.05, hard: 0.5 + 0.3 * v, rise: 0.002, ph: x.ph, len: 1.6 }); return add(y, click(sr, r, 500, 0.7, 0.004, 0.4 * v)); }
+ const f = piece === "tek" ? 660 : 510, y = membrane(sr, f * x.tune, [[1, 1, piece === "tek" ? 0.06 : 0.035], [1.59, 0.7, 0.035], [2.14, 0.55, 0.025], [2.65, 0.35, 0.015]], { v, glide: 0.02, glideTau: 0.02, hard: 0.7 + 0.3 * v, ph: x.ph, len: 0.4 });
+ return add(y, click(sr, r, piece === "tek" ? 3200 : 2400, 0.8, 0.0012, 1.1 * v));
+};
+const cowbellSyn = (sr: number, v: number, x: Var): Buf => { // the 808 cowbell: 540 + 800 Hz squares, band-passed, a fast then slow decay
+ const N = lenOf(sr, 0.5), y = new Float64Array(N), bp = new SVF(sr, 2640, 1.4), f1 = (540 * x.tune) / sr, f2 = (800 * x.tune) / sr; let p1 = x.ph, p2 = (x.ph + 0.3) % 1;
+ for (let i = 0; i < N; i++) { const t = i / sr; let s1 = p1 < 0.5 ? 1 : -1, s2 = p2 < 0.5 ? 1 : -1; s1 += blep(p1, f1) - blep((p1 + 0.5) % 1, f1); s2 += blep(p2, f2) - blep((p2 + 0.5) % 1, f2); p1 = (p1 + f1) % 1; p2 = (p2 + f2) % 1;
+ bp.tick(s1 + s2); y[i] = (bp.bp + 0.3 * (s1 + s2) * 0.2) * (0.6 * Math.exp(-t / 0.012) + 0.4 * Math.exp(-t / 0.09)) * v; }
+ return y;
+};
+
+// ---------------------------------------------------------------- shakers, tambourine, brushes (PhISEM: Cook 1997)
+const phisem = (sr: number, r: Rng, v: number, x: Var, dur: number, P: { beads: number; stroke: number; grain: number; res: [number, number, number][]; body?: number }): Buf => {
+ const strokeS = Math.min(Math.max(0.05, dur * 0.6), P.stroke) * x.dec, N = lenOf(sr, strokeS + 0.25), y = new Float64Array(N), filt = P.res.map(([f, q]) => new SVF(sr, f * x.bright, q));
+ const kE = Math.exp(-1 / (strokeS * 0.35 * sr)), kS = Math.exp(-1 / (P.grain * sr)), rate = (P.beads * 60) / sr; let E = 0, S = 0;
+ for (let i = 0; i < N; i++) {
+ if (i < strokeS * sr * 0.3) E += (1 - E) * 0.004; // the shake gathers energy, then the beads settle
+ E *= kE; if (r() < rate * E) S += (0.3 + 0.7 * r()) * E; S *= kS;
+ const s = nz(r) * S; let o = 0; for (let j = 0; j < filt.length; j++) { filt[j].tick(s); o += filt[j].bp * P.res[j][2]; } y[i] = o * (0.4 + 0.6 * v);
+ }
+ if (P.body) add(y, membrane(sr, 190 * x.tune, [[1, 1, 0.03], [1.59, 0.5, 0.02]], { v, glide: 0, glideTau: 1, hard: 0.5, len: 0.2 }), P.body * v);
+ return y;
+};
+const SHAKER = { beads: 90, stroke: 0.09, grain: 0.0012, res: [[5200, 1.3, 1], [8400, 1.8, 0.6], [2900, 1.2, 0.25]] as [number, number, number][] };
+const TAMB = { beads: 40, stroke: 0.1, grain: 0.0045, res: [[5600, 9, 1], [8100, 11, 0.8], [2300, 5, 0.4]] as [number, number, number][], body: 0.35 };
+const brushSyn = (sr: number, r: Rng, v: number, x: Var, dur: number, sweep: boolean): Buf => {
+ if (sweep) { // a circle on the head: a swell of band-passed noise whose centre travels with the brush
+ const D = clamp(dur, 0.12, 2) * x.dec, N = lenOf(sr, D + 0.08), y = new Float64Array(N), bp = new SVF(sr, 3000, 0.8), lp = new SVF(sr, 7000, 0.7), ph = x.ph * TAU;
+ for (let i = 0; i < N; i++) { const t = i / sr, u = clamp(t / D, 0, 1), e = Math.sin(Math.PI * u) ** 1.5 * (t < D ? 1 : Math.exp(-(t - D) / 0.02)); if ((i & 15) === 0) bp.set(2600 + 1600 * Math.sin(TAU * u + ph), 0.8); bp.tick(nz(r)); lp.tick(bp.bp); y[i] = lp.lp * e * 0.9 * (0.4 + 0.6 * v); }
+ return y;
+ }
+ // a tap: wire-heavy, soft rise (bristles arrive over ~3 ms), a little membrane
+ const N = lenOf(sr, 0.5), y = new Float64Array(N), hp = new SVF(sr, 500, 0.7), lp = new SVF(sr, 5200 + 2500 * v, 0.7), rise = 0.003 * sr, k = Math.exp(-1 / (0.075 * (0.8 + 0.5 * v) * x.dec * sr)); let e = 1;
+ for (let i = 0; i < N; i++) { hp.tick(nz(r)); lp.tick(hp.hp); y[i] = lp.lp * e * Math.min(1, i / rise) * 1.2; e *= k; }
+ return add(y, membrane(sr, 200 * x.tune, MEM6(0.07), { v, glide: 0, glideTau: 1, hard: 0.35, len: 0.4 }), 0.18 * v);
+};
+
+// ---------------------------------------------------------------- rolls
+/** Single strokes at `rate`/s across a held note, a swell from `from` to 1 of the velocity (orch snare buzz roll, bass drum, cymbal rolls). */
+const roll = (dur: number, v: number, rate: number, r: Rng, from = 0.55) => { const out: [number, number][] = []; const n = Math.max(2, Math.floor(dur * rate)); for (let j = 0; j < n; j++) out.push([(j / rate) + (r() - 0.5) * 0.004, v * (from + (1 - from) * (j / (n - 1))) * (j % 2 ? 0.9 : 1)]); return out; };
+
+// ---------------------------------------------------------------- the voice
+/** Level trims per piece, set by measuring each against the legacy voice it replaces (stem RMS on the test signals). */
+const TRIM: Partial<Record<DrumPiece, number>> = { kick: 1.05, snare: 0.62, rimshot: 0.62, ghost: 0.62, cross: 0.55, clap: 0.55, hat: 0.34, open: 0.24, pedal: 0.34, ride: 0.2, bell: 0.2, crash: 0.13, tomHi: 0.5, tomMid: 0.5, tomLo: 0.55, shaker: 0.9, tamb: 0.45, brush: 0.7, sweep: 0.6, dum: 0.6, tek: 0.45, ka: 0.45, cowbell: 0.35 };
+/** dB per kit and piece on top of TRIM: measured (stem meter, every style's test signal) so each lane plays where the calibrated palettes expect it. */
+const LEVEL: Record<KitId, Partial<Record<DrumPiece | "timpani", number>>> = {
+ acoustic: { kick: -0.8, snare: -7.8, rimshot: -7.8, ghost: -7.8, cross: -2.5, clap: -2.5, hat: 4.9, open: 4.9, pedal: 4.9, ride: -33.9, bell: -33.9, crash: -8.5, tomHi: -7.8, tomMid: -7.8, tomLo: -7.8, shaker: -24.7, tamb: -18, dum: -1.5, tek: -1.5, ka: -1.5, cowbell: 0 },
+ "808": { kick: -2, snare: -8.3, rimshot: -8.3, ghost: -8.3, cross: -1.7, clap: -2, hat: 12.7, open: 11.9, pedal: 12.7, ride: -30, bell: -30, crash: -9.5, tomHi: -9.3, tomMid: -9.3, tomLo: -9.3, shaker: -22.5, tamb: -18, dum: -1.5, tek: -1.5, ka: -1.5, cowbell: 0 },
+ "909": { kick: -7, snare: -9, rimshot: -9, ghost: -9, cross: -1.7, clap: -2.6, hat: 10, open: 10, pedal: 10, ride: -30, bell: -30, crash: -9.5, tomHi: -9, tomMid: -9, tomLo: -9, shaker: -22.5, tamb: -18, dum: -1.5, tek: -1.5, ka: -1.5, cowbell: 0 },
+ dusty: { kick: -1.6, snare: -7.3, rimshot: -7.3, ghost: -7.3, cross: -2.8, clap: -2.5, hat: 6.6, open: 6.5, pedal: 6.6, ride: -34, bell: -34, crash: -9.5, tomHi: -7.3, tomMid: -7.3, tomLo: -7.3, shaker: -24, tamb: -18, dum: -1.5, tek: -1.5, ka: -1.5, cowbell: 0 },
+ brush: { kick: -1.6, brush: 2, sweep: -6.4, cross: -2.5, clap: -2.5, hat: 5, open: 5, pedal: 8.7, ride: -33.9, bell: -33.9, crash: -9.5, tomHi: -7.8, tomMid: -7.8, tomLo: -7.8, shaker: -24, tamb: -18, dum: -1.5, tek: -1.5, ka: -1.5, cowbell: 0 },
+ orch: { kick: -6.1, snare: -8.9, rimshot: -8.9, ghost: -8.9, cross: -2.5, clap: -2.5, hat: 5, open: 5, pedal: 5, ride: -34, bell: -34, crash: -12, tomHi: -9, tomMid: -9, tomLo: -9, shaker: -24, tamb: -18, dum: -1.5, tek: -1.5, ka: -1.5, cowbell: 0, timpani: 3.5 },
+};
+const lvl = (kit: KitId, pc: DrumPiece) => db(LEVEL[kit][pc] ?? 0);
+/** legacy = the piece is frozen on the old kit (Piece.legacy); style picks the default kit; choke = closed/pedal hat onsets across the piece. */
+export type KitCtx = { legacy?: boolean; style?: string; choke?: number[] };
+
+/** Every closed / pedal hat onset in a piece's drum parts (for choking open hats across lanes). */
+export const chokeTimes = (parts: { inst: string; opts?: Opts; keys: Played[] }[]): number[] => {
+ const t: number[] = [];
+ for (const pt of parts) if (["kick", "snare", "hat"].includes(pt.inst) && pt.opts?.legacy !== true) for (const k of pt.keys) { const pc = pieceOf(k, pt.inst, pt.opts ?? {}); if (pc === "hat" || pc === "pedal") t.push(k.t); }
+ return t.sort((a, b) => a - b);
+};
+
+/** A kit voice: kick / snare / hat lanes (the inst gives the lane's default piece). */
+export const kitVoice = (inst: string, keys: Played[], sr: number, n: number, o: Opts, r: Rng, ctx: KitCtx = {}): Out => {
+ const kit = kitOf(o, ctx.style), L = new Float32Array(n), R = new Float32Array(n), choke = ctx.choke ?? [];
+ const width = typeof o.width === "number" ? (o.width as number) : 1;
+ const put = (y: Buf | [Buf, Buf], t: number, p: number, g: number) => {
+ const i0 = Math.round(t * sr); if (i0 >= n) return;
+ const [gl, gr] = pan(p * width);
+ if (y instanceof Float64Array) { const m = Math.min(y.length, n - i0); for (let i = 0; i < m; i++) { L[i0 + i] += y[i] * g * gl; R[i0 + i] += y[i] * g * gr; } }
+ else { const m = Math.min(y[0].length, n - i0), cl = gl * Math.SQRT2 * g, cr = gr * Math.SQRT2 * g; for (let i = 0; i < m; i++) { L[i0 + i] += y[0][i] * cl; R[i0 + i] += y[1][i] * cr; } }
+ };
+ for (const k of keys) {
+ let pc = pieceOf(k, inst, o);
+ if (kit === "brush" && (pc === "snare" || pc === "ghost" || pc === "cross" || pc === "rimshot")) pc = "brush";
+ if (kit !== "brush" && pc === "sweep") pc = "shaker";
+ if (kit !== "brush" && pc === "brush") pc = "ghost";
+ const t = k.t;
+ const x = vary(r), v = clamp(k.v, 0.02, 1), dur = Math.max(0.02, k.off - k.t), rolled = o.roll === true || k.kind === "roll", g = x.g * (TRIM[pc] ?? 0.5) * lvl(kit, pc), p = PAN[pc] + (r() - 0.5) * 0.04;
+ switch (pc) {
+ case "kick":
+ if (kit === "orch" && rolled) { for (const [dt, vv] of roll(dur, v, 11, r, 0.35)) put(kickSyn(sr, r, vv * 0.6, vary(r), KICK.orch), t + dt, p, g); break; }
+ put(kickSyn(sr, r, v, x, KICK[kit]), t, p, g * v); break;
+ case "snare": case "rimshot": case "ghost": {
+ const kind = pc === "ghost" ? "ghost" : pc === "rimshot" || (kit === "acoustic" && v > 0.93) ? "rimshot" : "snare", vv = pc === "ghost" ? v * 0.55 : v;
+ if (rolled) { for (const [dt, rv] of roll(dur, vv, 26, r)) put(snareSyn(sr, r, rv * 0.7, vary(r), SNARE.orch, "snare"), t + dt, p, g * 0.55); break; }
+ put(snareSyn(sr, r, vv, x, SNARE[kit], kind), t, p, g * vv); break;
+ }
+ case "clap": put(clapSyn(sr, r, v, x, kit), t, p, g * v); break;
+ case "cross": put(crossSyn(sr, r, v, x, kit), t, p, g * v); break;
+ case "hat": case "open": case "pedal": {
+ let ci = Infinity; if (pc === "open") { const c = choke.find((c) => c > t + 0.01); if (c !== undefined) ci = Math.round((c - t) * sr); }
+ put(hatSyn(sr, r, v, x, HAT[kit], pc, ci), t, p, g * v); break;
+ }
+ case "ride": case "bell": put(cymSyn(sr, r, v, x, kit === "808" || kit === "909" ? "ride808" : pc), t, p, g * v); break;
+ case "crash": {
+ const id = kit === "orch" ? "cymbal" : "crash";
+ if (rolled) { for (const [dt, rv] of roll(dur, v, 12, r, 0.1)) put(cymSyn(sr, r, rv * 0.5, vary(r), id, true), t + dt, p, g * 0.35); break; } // a mallet roll on the suspended cymbal
+ put(cymSyn(sr, r, v, x, id), t, p, g * v); break;
+ }
+ case "tomHi": case "tomMid": case "tomLo": put(tomSyn(sr, r, v, x, pc, kit), t, p, g * v); break;
+ case "shaker": put(phisem(sr, r, v, x, dur, SHAKER), t, p, g * v); break;
+ case "tamb": put(phisem(sr, r, v, x, dur, TAMB), t, p, g * v); break;
+ case "brush": case "sweep": put(brushSyn(sr, r, v, x, dur, pc === "sweep"), t, p, g * v); break;
+ case "dum": case "tek": case "ka": put(handSyn(sr, r, v, x, pc), t, p, g * v); break;
+ case "cowbell": put(cowbellSyn(sr, v, x), t, p, g); break;
+ }
+ }
+ if (kit === "acoustic" || kit === "brush" || kit === "orch" || kit === "dusty") ambience(L, R, sr, kit === "orch" ? 0.55 : kit === "dusty" ? 0.3 : 0.4);
+ if (kit === "dusty" && ctx.style !== "lofi") sampler(L, R, sr); // in the lofi style the lo-fi chain (lofiFx) crunches the drum bus; never twice
+ return { L, R };
+};
+
+/** Overheads and room mics: a few decorrelated early reflections off the kit (3-19 ms), high-passed so the lows stay mono. */
+const ambience = (L: Float32Array, R: Float32Array, sr: number, amt: number) => {
+ const n = L.length, tl = [3.1, 7.3, 11.9, 17.3].map((ms) => Math.round((ms / 1000) * sr)), tr = [4.3, 8.9, 13.7, 19.1].map((ms) => Math.round((ms / 1000) * sr)), gs = [0.3, 0.22, 0.15, 0.1].map((g) => g * amt);
+ const m = new Float32Array(n), hpC = Math.exp((-TAU * 250) / sr), lpC = 1 - Math.exp((-TAU * 6500) / sr); let hz = 0, lz = 0, prev = 0;
+ for (let i = 0; i < n; i++) { const x = (L[i] + R[i]) * 0.5; hz = hpC * (hz + x - prev); prev = x; lz += lpC * (hz - lz); m[i] = lz; }
+ for (let i = n - 1; i >= 0; i--) { let a = 0, b = 0; for (let j = 0; j < 4; j++) { if (i >= tl[j]) a += m[i - tl[j]] * gs[j] * (j % 2 ? -1 : 1); if (i >= tr[j]) b += m[i - tr[j]] * gs[j] * (j % 2 ? 1 : -1); } L[i] += a; R[i] += b; }
+};
+/** The sampled break: SP-1200 style zero-order hold at 26.04 kHz (no anti-alias filter, so it aliases), 12-bit, a 4-pole 11 kHz output filter, a push into soft clip. */
+const sampler = (L: Float32Array, R: Float32Array, sr: number) => {
+ for (const c of [L, R]) {
+ const step = sr / 26040, a = new SVF(sr, 11000, 0.54), b = new SVF(sr, 11000, 1.3); let acc = 0, hold = 0;
+ for (let i = 0; i < c.length; i++) { acc += 1; if (acc >= step) { acc -= step; hold = Math.round(c[i] * 1.6 * 2048) / 2048; } a.tick(hold); b.tick(a.lp); c[i] = Math.tanh(b.lp * 1.3) / (1.3 * 1.6); }
+ }
+};
+
+// ---------------------------------------------------------------- timpani
+/** Kettle drum: the air-loaded (1,1)..(6,1) modes (near-harmonic, so it has a pitch), a fast-dying (0,1) thud, a felt mallet whose contact time sets the brightness, a tension glide on hard strokes, rolls on held notes. `pitch` pins the drum's note (compose tunes it to the key); `decay` = the fundamental's time constant. */
+export const timpani = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
+ const L = new Float32Array(n), R = new Float32Array(n), dec = typeof o.decay === "number" ? (o.decay as number) : 1.6, lv = db(LEVEL.orch.timpani ?? 0);
+ const strike = (t: number, midi: number, v: number, g: number) => {
+ const x = vary(r), f = 440 * Math.pow(2, (midi - 69) / 12) * x.tune, hard = 0.35 + 0.55 * v, d = dec * x.dec;
+ const y = membrane(sr, f, [[1, 1, d], [1.504, 0.62, d * 0.72], [1.742, 0.14, d * 0.2], [1.98, 0.42, d * 0.55], [2.44, 0.24, d * 0.4], [2.9, 0.13, d * 0.3], [3.37, 0.07, d * 0.22]], { v, glide: 0.018 * v * v, glideTau: 0.15, hard, rise: 0.0025 - 0.0015 * v, ph: x.ph, len: Math.min(8, d * 6) });
+ add(y, membrane(sr, f * 0.62, [[1, 1, 0.07]], { v, glide: 0, glideTau: 1, hard: 1, rise: 0.002, len: 0.5 }), 0.5 * v);
+ add(y, click(sr, r, 450 + 900 * v, 0.6, 0.006, 0.6 * v));
+ const i0 = Math.round(t * sr), [gl, gr] = pan(clamp((midi - 45) / 18, -1, 1) * -0.25 + (r() - 0.5) * 0.03), m = Math.min(y.length, n - i0);
+ for (let i = 0; i < m; i++) { L[i0 + i] += y[i] * g * gl; R[i0 + i] += y[i] * g * gr; }
+ };
+ for (const k of keys) {
+ const midi = typeof o.pitch === "number" ? (o.pitch as number) : k.p, dur = k.off - k.t, v = clamp(k.v, 0.02, 1);
+ if (o.roll === true || k.kind === "roll") for (const [dt, vv] of roll(dur, v, 15, r, 0.4)) strike(k.t + dt, midi, vv * 0.75, 0.26 * lv);
+ else strike(k.t, midi, v, 0.34 * v * lv);
+ }
+ ambience(L, R, sr, 0.6);
+ return { L, R };
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/dsp.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/dsp.ts
index 55bda99..a482c26 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/dsp.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/dsp.ts
@@ -21,7 +21,8 @@ export class SVF {
export class Biquad {
private x1 = 0; private x2 = 0; private y1 = 0; private y2 = 0; b0 = 1; b1 = 0; b2 = 0; a1 = 0; a2 = 0;
static make(sr: number, type: "lp" | "hp" | "bp" | "peak" | "lowshelf" | "highshelf", f: number, q: number, gainDb = 0) {
- const bq = new Biquad(), w = (TAU * f) / sr, c = Math.cos(w), s = Math.sin(w), al = s / (2 * q), A = Math.pow(10, gainDb / 40);
+ // a corner at or past Nyquist is not a filter (the coefficients go unstable: NaN at 16 kHz for a 17.5 kHz low-pass); hold it at 0.45 sr
+ const bq = new Biquad(), w = (TAU * Math.min(f, 0.45 * sr)) / sr, c = Math.cos(w), s = Math.sin(w), al = s / (2 * q), A = Math.pow(10, gainDb / 40);
let b0 = 1, b1 = 0, b2 = 0, a0 = 1, a1 = 0, a2 = 0;
if (type === "lp") { b0 = (1 - c) / 2; b1 = 1 - c; b2 = b0; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }
else if (type === "hp") { b0 = (1 + c) / 2; b1 = -(1 + c); b2 = b0; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/ensemble.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/ensemble.ts
new file mode 100644
index 0000000..6c7057a
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/ensemble.ts
@@ -0,0 +1,383 @@
+// ENSEMBLE VOICES, v2 (2026-09-28 sound rebuild, track S4): string sections as independent
+// players, pizzicato, a bowed-waveguide solo, section brass, flute and clarinet, a glottal-source
+// choir, plucked guitars (nylon, steel, clean electric) and harp, and four basses. Every note varies
+// (seeded per note), nothing restarts at phase zero, and players drift like players.
+// These are CINEMATIC, STYLIZED models: honest physics where we can reach it (plucks, bows, the
+// voice source and its formants), careful spectral models where we can't (brass, winds). A human
+// listens before any acoustic timbre carries a film (spec 08 DECISION B).
+// The old voices stay in instruments.ts / orchestra.ts behind `opts.legacy` (shipped films).
+import { type Rng, TAU, clamp, pan, SVF, Biquad, blep } from "./dsp";
+import type { Played } from "./perform";
+import {
+ type Out, type Opts, num, f0, out0, wn, gn, subRng, keysRng, concurrency, Drift, Reson, runBody, VIOLIN_BODY, CELLO_BODY,
+ type IRSpec, monoLows, IR_NYLON, IR_STEEL, IR_HARP, IR_UPRIGHT, bodyIR, convolve, pluckExc, ksRender, headRms, FORMANTS, FORMANT_BW, BRASS_FORMANT, bumpDb,
+} from "./ensembleCore";
+
+// Output levels, matched to the legacy voices' stem RMS on the same material (tools/ensemble-check.mjs
+// calibrate), so the style vocabularies' calibrated gains and stem targets still hold.
+const LEVEL = { strings: 0.125, pizz: 0.16, solo: 0.146, cello: 1.13, brass: 0.059, horn: 1.4, flute: 0.119, clarinet: 0.118, choir: 3.07, guitar: 0.066, harp: 0.0757, bass: 0.3, synthBass: 0.3 };
+
+const addStereo = (o: Out, i0: number, y: Float64Array | Float32Array, gl: number, gr: number) => { const m = Math.min(y.length, o.L.length - i0); for (let i = Math.max(0, -i0); i < m; i++) { o.L[i0 + i] += y[i] * gl; o.R[i0 + i] += y[i] * gr; } };
+const onsetI = (t: number, sr: number) => Math.max(0, Math.round(t * sr));
+
+// ------------------------------------------------------------------ strings: the section
+// Seating (audience view): violins left, violas centre-right, cellos and basses right.
+const SEAT = [0.3, 0.12, -0.3];
+const BUS_BODY: [typeof VIOLIN_BODY, number][] = [[CELLO_BODY, 1], [VIOLIN_BODY, 0.82], [VIOLIN_BODY, 1]];
+const regOf = (p: number, bassRole: boolean) => (bassRole || p < 55 ? 0 : p < 63 ? 1 : 2);
+
+/**
+ * String section: each note is played by `players` (default 10, divided across a chord) independent
+ * players. Each has its own onset (+-12 ms), tuning (+-6 c), 1/f drift, vibrato (5-6.5 Hz, 10-25 c,
+ * delayed 150-400 ms, its rate wandering), bow attack and release, a band-limited sawtooth (the
+ * Helmholtz motion) with pulse-synchronous bow noise and a scratch at the attack, and a low-pass that
+ * opens with loudness (cutoff ~ amp^0.7). Players sum into register buses (cellos, violas, violins),
+ * each through its measured body resonances (ensembleCore). `pizz: true` plucks instead.
+ * Options kept from v1: attack, release, width, bright, bass; new: players, vibrato, noise, pizz.
+ */
+export const strings = (keys: Played[], sr: number, n: number, o: Opts, r0: Rng): Out => {
+ if (o.pizz === true) return pizzicato(keys, sr, n, o, r0);
+ const atk = num(o, "attack", 0.45), rel = num(o, "release", 0.9), w = num(o, "width", 0.8), bright = num(o, "bright", 1), S = Math.round(num(o, "players", 10)), vibAmt = num(o, "vibrato", 1), noiseAmt = num(o, "noise", 1), bassRole = o.bass === true;
+ const buses = [out0(n), out0(n), out0(n)], used = [false, false, false], conc = concurrency(keys), short = atk < 0.06;
+ keys.forEach((k, ki) => {
+ const r = subRng(r0), f = f0(k.p), reg = regOf(k.p, bassRole), P = clamp(Math.round(S / conc[ki]) + 1, 3, S), dur = Math.max(0.03, k.off - k.t), bus = buses[reg]; used[reg] = true;
+ const g = (LEVEL.strings * (bassRole ? 1.6 : 1) * Math.min(1, Math.pow(1047 / f, 0.8)) /* above C6 the section thins */ * Math.pow(k.v, 1.2)) / Math.sqrt(P), sig = (short ? 2.5 : 3 + 4 * clamp(atk / 0.4, 0, 1)) / 1000;
+ for (let p = 0; p < P; p++) {
+ const i0 = onsetI(k.t + clamp(gn(r) * sig, -0.015, 0.015), sr), a = Math.max(0.007, atk * (0.75 + 0.5 * r())), rl = rel * (0.85 + 0.3 * r()), vel = k.v * (0.88 + 0.24 * r());
+ const cents0 = clamp(gn(r) * 3, -7, 7), vr = 5 + 1.5 * r(), vd = (10 + 15 * r()) * vibAmt, vDel = 0.15 + 0.25 * r(), dr = new Drift(r, 0.35, sr), vw = new Drift(r, 0.5, sr, 256), ad = new Drift(r, 0.3, sr, 256);
+ const [gl, gr] = pan(clamp((bassRole ? 0.12 : SEAT[reg]) * w + (r() - 0.5) * w, -1, 1)), lp = new SVF(sr, 2000, 0.6), cutK = reg === 0 ? 0.7 : 1;
+ const len = Math.min(n - i0, Math.ceil((dur + rl * 1.6) * sr)), riseEnd = 1 - Math.exp(-dur / (a / 3)), scratch = (short ? 0.5 : 0.18) * noiseAmt, bowN = (0.05 + 0.07 * (1 - k.v)) * noiseAmt;
+ let ph = r(), vph = r() * TAU, nz = 0, env = 0;
+ for (let i = 0; i < len; i++) {
+ const t = i / sr;
+ env = t < dur ? 1 - Math.exp(-t / (a / 3)) : riseEnd * Math.exp(-(t - dur) / (rl / 3));
+ const vibR = clamp((t - vDel) / 0.35, 0, 1);
+ vph += (TAU * vr * (1 + 0.1 * vw.tick())) / sr;
+ const cents = cents0 + 3 * dr.tick() + (vibR > 0 ? vd * vibR * Math.sin(vph) : 0), inc = (f * Math.pow(2, cents / 1200)) / sr;
+ ph += inc; if (ph >= 1) ph -= 1;
+ const x0 = wn(r); nz += 0.25 * (x0 - nz); // one-pole low-pass of the noise; x0 - nz is its high-passed residue
+ const bn = (x0 - nz) * (ph < 0.12 ? 1 : 0.3) * (bowN + scratch * Math.exp(-t / 0.035));
+ if ((i & 15) === 0) lp.set(clamp((650 + 7500 * Math.pow(env * vel, 0.7)) * bright * cutK, f * 1.5, sr * 0.45), 0.65);
+ const y = lp.tick(2 * ph - 1 - blep(ph, inc) + bn) * env * g * (1 + 0.06 * ad.tick()), j = i0 + i;
+ bus.L[j] += y * gl; bus.R[j] += y * gr;
+ }
+ }
+ });
+ return mixBuses(buses, used, sr, n, bassRole);
+};
+const mixBuses = (buses: Out[], used: boolean[], sr: number, n: number, bassRole: boolean): Out => {
+ const out = out0(n);
+ buses.forEach((b, i) => { if (!used[i]) return; const [body, sc] = BUS_BODY[i]; runBody(b.L, sr, body, sc * 0.97); runBody(b.R, sr, body, sc * 1.03); for (let j = 0; j < n; j++) { out.L[j] += b.L[j]; out.R[j] += b.R[j]; } });
+ if (!bassRole) { Biquad.make(sr, "hp", 90, 0.7).run(out.L); Biquad.make(sr, "hp", 90, 0.7).run(out.R); }
+ return monoLows(out, sr);
+};
+
+/** Pizzicato section: 2-5 players per note, each a finger-plucked string (extended KS) through the same register bodies. */
+const pizzicato = (keys: Played[], sr: number, n: number, o: Opts, r0: Rng): Out => {
+ const w = num(o, "width", 0.8), S = Math.round(num(o, "players", 10)), bassRole = o.bass === true, conc = concurrency(keys);
+ const buses = [out0(n), out0(n), out0(n)], used = [false, false, false];
+ keys.forEach((k, ki) => {
+ const reg = regOf(k.p, bassRole), P = clamp(Math.round(S / conc[ki] / 2) + 1, 2, 5); used[reg] = true;
+ for (let p = 0; p < P; p++) {
+ const r = subRng(r0), f = f0(k.p) * Math.pow(2, clamp(gn(r) * 3, -6, 6) / 1200), i0 = onsetI(k.t + clamp(gn(r) * 0.007, -0.015, 0.015), sr), v = k.v * (0.85 + 0.3 * r());
+ const exc = pluckExc(sr, f, { width: 0.0025 * (1.25 - 0.45 * v), beta: 0.2 + 0.12 * r(), noise: 0.3, lp: f * 2.5 * (0.6 + 0.8 * v) }, r);
+ const T60 = clamp(1.1 * Math.pow(262 / f, 0.7), 0.25, 2.6) * (0.9 + 0.2 * r()), len = Math.min(n - i0, Math.ceil(T60 * 1.2 * sr));
+ if (len <= 0) continue;
+ const y = ksRender(sr, { f, T60, loss: 0.4, exc, len, relI: len, relT60: 1, pol2: { cents: 0.4 + 0.6 * r(), mix: 0.6, t60: 0.5, share: r() } });
+ const g = (LEVEL.pizz * Math.pow(v, 1.3)) / headRms(y, sr) / Math.sqrt(P), [gl, gr] = pan(clamp(SEAT[reg] * w + (r() - 0.5) * 0.6 * w, -1, 1));
+ addStereo(buses[reg], i0, y, gl * g, gr * g);
+ }
+ });
+ return mixBuses(buses, used, sr, n, bassRole);
+};
+
+// ------------------------------------------------------------------ bowed solo: a waveguide string
+/**
+ * Solo violin / cello: a bowed digital waveguide after STK's Bowed (Cook & Scavone, STK licence,
+ * MIT-style; re-implemented, not copied): neck and bridge delay lines around a bow junction whose
+ * friction table is (|slope (dv + 0.001)| + 0.75)^-4, a one-pole string loss at the bridge, vibrato
+ * as a delay-length change. Touching notes are one bow stroke with a finger slide (legato), so a line
+ * sings instead of re-attacking. The bridge signal goes through the measured body (ensembleCore).
+ * The loop is tuned exactly: the loss filter's phase delay is taken out of the delay lengths.
+ * Options: attack, vibrato (cents), pan, cello; new: pressure (0..1), position (0..1).
+ */
+export const bowedSolo = (keys: Played[], sr: number, n: number, o: Opts, r0: Rng): Out => {
+ const out = out0(n), cello = o.cello === true, atk = num(o, "attack", 0.09), vibC = num(o, "vibrato", cello ? 12 : 22), [gl, gr] = pan(num(o, "pan", -0.1));
+ const press = num(o, "pressure", 0.5), posn = num(o, "position", 0.5), mono = new Float32Array(n);
+ const ks = keys.slice().sort((a, b) => a.t - b.t || a.p - b.p), lines: Played[][] = [];
+ for (const k of ks) { const ln = lines.find((l) => { const e = l[l.length - 1]; return e.t < k.t - 0.02 && Math.abs(e.off - k.t) < 0.06; }); if (ln) ln.push(k); else lines.push([k]); }
+ const pole = 0.75 - (0.2 * 22050) / sr, sg = 0.95;
+ for (const ln of lines) {
+ const r = subRng(r0), start = ln[0].t, end = ln[ln.length - 1].off, i0 = onsetI(start, sr), fLo = f0(Math.min(...ln.map((k) => k.p))) * 0.97;
+ const M = Math.ceil(sr / fLo) + 8, neck = new Float64Array(M), brid = new Float64Array(M); let wi = 0, sl = 0;
+ const tail = cello ? 1.2 : 0.7, len = Math.min(n - i0, Math.ceil((end - start + tail) * sr)); if (len <= 0) continue;
+ const beta = 0.027236 + 0.2 * posn * (0.85 + 0.3 * r()), slope0 = 5 - 4 * (0.88 + 0.12 * clamp(press, 0, 1)) /* below ~0.9 the string slips into its octave on high legato notes (tools/ensemble-check.mjs track) */, dr = new Drift(r, 0.3, sr), vw = new Drift(r, 0.6, sr, 256);
+ let seg = 0, fCur = f0(ln[0].p), vph = r() * TAU, env = 0, segT = 0, vel = ln[0].v, slope = slope0 * (0.9 + 0.2 * r());
+ const vr = 5.3 + 0.7 * r(), tune = ln.map(() => clamp(gn(r) * 2.5, -5, 5)), kEnv = Math.exp(-1 / (Math.max(0.01, atk / 3) * sr)), kRel = Math.exp(-1 / (0.03 * sr)), kGl = Math.exp(-1 / (0.02 * sr)), kVel = Math.exp(-1 / (0.06 * sr));
+ const y = new Float64Array(len);
+ for (let i = 0; i < len; i++) {
+ const t = start + i / sr;
+ while (seg + 1 < ln.length && t >= ln[seg + 1].t) { seg++; segT = 0; }
+ const k = ln[seg], fT = f0(k.p) * Math.pow(2, tune[seg] / 1200); fCur = fT + (fCur - fT) * kGl; vel = k.v + (vel - k.v) * kVel;
+ const on = t < end; env = on ? 1 + (env - 1) * kEnv : env * kRel;
+ const vib = vibC * clamp((segT - 0.18) / 0.35, 0, 1), vibc = vib > 0 ? vib * Math.sin(vph) : 0; vph += (TAU * vr * (1 + 0.08 * vw.tick())) / sr; segT += 1 / sr;
+ const fr = fCur * Math.pow(2, (vibc + 2 * dr.tick()) / 1200), w = (TAU * fr) / sr, pd = Math.atan2(pole * Math.sin(w), 1 - pole * Math.cos(w)) / w;
+ const P0 = sr / fr, base = clamp(P0 - pd + 0.3 + 0.00045 * P0, 4, M - 4) /* measured junction offset, tools/ensemble-check.mjs check */, Dn = base * (1 - beta), Db = base * beta;
+ const rn = wi - Dn, rb = wi - Db, rn0 = Math.floor(rn), rb0 = Math.floor(rb), fn = rn - rn0, fb = rb - rb0;
+ const nOut = neck[(rn0 + M) % M] * (1 - fn) + neck[(rn0 + 1 + M) % M] * fn, bOut = brid[(rb0 + M) % M] * (1 - fb) + brid[(rb0 + 1 + M) % M] * fb;
+ sl = sg * (1 - pole) * bOut + pole * sl;
+ const bridgeRefl = -sl, nutRefl = -nOut, strVel = bridgeRefl + nutRefl;
+ const bowVel = (0.03 + 0.2 * (0.3 + 0.7 * vel)) * env * (1 + 0.012 * wn(r)), dv = bowVel - strVel;
+ const tbl = Math.min(1, Math.pow(Math.abs(slope * (dv + 0.001)) + 0.75, -4)), nv = dv * tbl;
+ neck[wi] = bridgeRefl + nv; brid[wi] = nutRefl + nv; wi = wi + 1 === M ? 0 : wi + 1;
+ y[i] = bOut;
+ }
+ const g = LEVEL.solo * (cello ? LEVEL.cello : 1); for (let i = 0; i < len; i++) mono[i0 + i] += y[i] * g;
+ }
+ const L = Float32Array.from(mono), R = Float32Array.from(mono), body = cello ? CELLO_BODY : VIOLIN_BODY;
+ runBody(L, sr, body, 0.99); runBody(R, sr, body, 1.01);
+ Biquad.make(sr, "lp", Math.min(9000, sr * 0.45), 0.7).run(L); Biquad.make(sr, "lp", Math.min(9000, sr * 0.45), 0.7).run(R);
+ for (let i = 0; i < n; i++) { out.L[i] = L[i] * gl; out.R[i] = R[i] * gr; }
+ return out;
+};
+
+// ------------------------------------------------------------------ additive core (brass, winds)
+/** sum_n w[n] sin(n th) by the Chebyshev recurrence: one sin + one cos per sample, band-limited by construction. */
+const harmonics = (th: number, w: Float64Array, N: number) => { const s1 = Math.sin(th), c2 = 2 * Math.cos(th); let sp = 0, sc = s1, acc = w[0] * s1; for (let h = 1; h < N; h++) { const sn = c2 * sc - sp; acc += w[h] * sn; sp = sc; sc = sn; } return acc; };
+const BLK = 32;
+
+// ------------------------------------------------------------------ brass
+/**
+ * Cinematic brass: a spectral model of a lip-reed instrument. Harmonic n's amplitude follows the
+ * loudness L as L^(1 + gamma (n-1)) (Risset / Beauchamp: brass brightens with loudness, and the upper
+ * harmonics build after the fundamental, the "blat"), times a bell-radiation formant (trumpet,
+ * trombone or horn, ensembleCore). A lip scoop of -30..-50 c into each note, breath and a tongued
+ * puff, growl at ff, 3 players per section by default with their own timing, tuning and drift.
+ * Options: attack, bright, width; new: players, release, vibrato (cents), type (trumpet|trombone|horn).
+ */
+export const brass = (keys: Played[], sr: number, n: number, o: Opts): Out => {
+ const out = out0(n), r0 = keysRng(keys, 0xb7a55), atk = num(o, "attack", 0.06), bright = num(o, "bright", 1), w = num(o, "width", 0.5), rel = num(o, "release", 0.14), vibC = num(o, "vibrato", 8);
+ const players = Math.round(num(o, "players", 3)), conc = concurrency(keys), gamma = 0.55 / Math.max(0.3, bright);
+ const fixed = typeof o.type === "string" ? String(o.type) : bright < 0.75 ? "horn" : null;
+ keys.forEach((k, ki) => {
+ const P = clamp(Math.round(players / conc[ki]), 1, players), type = BRASS_FORMANT[fixed ?? (k.p >= 58 ? "trumpet" : "trombone")] ?? BRASS_FORMANT.trumpet, dur = Math.max(0.03, k.off - k.t);
+ for (let p = 0; p < P; p++) {
+ const r = subRng(r0), i0 = onsetI(k.t + clamp(gn(r) * 0.006, -0.012, 0.012), sr), f = f0(k.p) * Math.pow(2, clamp(gn(r) * 2.5, -5, 5) / 1200), v = clamp(k.v * (0.92 + 0.16 * r()), 0, 1);
+ const N = Math.max(1, Math.min(40, Math.floor((0.45 * sr) / (f * 1.04)))), gdb = new Float64Array(N), wA = new Float64Array(N), wB = new Float64Array(N), wC = new Float64Array(N);
+ for (let h = 0; h < N; h++) gdb[h] = Math.pow(10, bumpDb((h + 1) * f, type) / 20) * Math.pow(h + 1, -0.35);
+ const a = atk * (0.8 + 0.4 * r()), rl = rel * (0.85 + 0.3 * r()), scoop = -(30 + 20 * r()), sT = (0.04 + 0.04 * r()) / 3, dyn = 0.22 + 0.78 * v, dr = new Drift(r, 0.3, sr);
+ const itd = Math.round(Math.abs(((k.p - 60) / 30) * w) * 0.0005 * sr + r() * 0.0002 * sr), vr = 5 + r(), vph0 = r() * TAU, growl = Math.max(0, v - 0.75) * 0.6, gph = r() * TAU, bp = new SVF(sr, clamp(f * 3, 700, 3000), 0.8), [gl, gr] = pan(clamp(((k.p - 60) / 30) * w + (r() - 0.5) * 0.9 * w, -1, 1));
+ const len = Math.min(n - i0, Math.ceil((dur + rl * 1.5) * sr)), riseEnd = 1 - Math.exp(-dur / (a / 3)), g = (LEVEL.brass * (type === BRASS_FORMANT.horn ? LEVEL.horn : 1) * Math.sqrt(v)) / Math.sqrt(P);
+ let th = r() * TAU;
+ const weights = (t: number, dst: Float64Array) => { const e = t < dur ? 1 - Math.exp(-t / (a / 3)) : riseEnd * Math.exp(-(t - dur) / (rl / 4)), L = Math.max(1e-4, e * dyn);
+ for (let h = 0; h < N; h++) dst[h] = gdb[h] * Math.pow(L, 1 + gamma * h); return e; };
+ let e0 = weights(0, wA), e1 = e0;
+ for (let i = 0; i < len; i++) {
+ const bi = i % BLK; if (bi === 0) { e0 = weights(i / sr, wA); e1 = weights((i + BLK) / sr, wB); }
+ const x = bi / BLK; for (let h = 0; h < N; h++) wC[h] = wA[h] + (wB[h] - wA[h]) * x;
+ const t = i / sr, e = e0 + (e1 - e0) * x, vibR = dur > 0.5 ? clamp((t - 0.3) / 0.4, 0, 1) : 0;
+ const cents = scoop * Math.exp(-t / sT) + 3 * dr.tick() + (vibR > 0 ? vibC * vibR * Math.sin(TAU * vr * t + vph0) : 0);
+ th += (TAU * f * Math.pow(2, cents / 1200)) / sr; if (th > TAU) th -= TAU;
+ bp.tick(wn(r)); const breath = bp.bp * (0.02 * e * dyn + 0.12 * v * Math.exp(-t / 0.02));
+ const am = growl > 0 ? 1 + growl * Math.sin(TAU * 31 * t + gph) : 1, y = (harmonics(th, wC, N) * am + breath) * g, j = i0 + i;
+ // a spaced microphone pair: the far channel hears each player a fraction of a millisecond later
+ if (gl >= gr) { out.L[j] += y * gl; if (j + itd < n) out.R[j + itd] += y * gr; } else { if (j + itd < n) out.L[j + itd] += y * gl; out.R[j] += y * gr; }
+ }
+ }
+ });
+ return monoLows(out, sr);
+};
+
+// ------------------------------------------------------------------ woodwinds
+// Flute: nearly a sine when soft, the 2nd harmonic strong in the low register, richer when loud
+// (Fletcher & Rossing 1998, ch. 16). Clarinet: odd harmonics under the bore cut-off (~1.6 kHz), both
+// parities above it (Benade). Shapes voiced by hand.
+const FLUTE = [1, 0.45, 0.2, 0.1, 0.05, 0.03, 0.02, 0.012, 0.008, 0.005];
+/**
+ * Woodwind: flute (jet: a chiff and an overblown octave flicker at the attack, breath noise both
+ * broadband and pitched at the jet, amplitude-led vibrato) or `reed: true` clarinet (odd harmonics,
+ * reed noise, no vibrato). Slurred notes (touching) glide without re-tonguing. Seeded per note.
+ * Options: reed, breath, width; new: vibrato (cents).
+ */
+export const woodwind = (keys: Played[], sr: number, n: number, o: Opts, r0: Rng): Out => {
+ const out = out0(n), reed = o.reed === true, breath = num(o, "breath", reed ? 0.02 : 0.08) / (reed ? 0.02 : 0.08), w = num(o, "width", 0.3), vibC = num(o, "vibrato", reed ? 0 : 7);
+ const ks = keys.slice().sort((a, b) => a.t - b.t);
+ ks.forEach((k, ki) => {
+ const r = subRng(r0), prev = ki > 0 ? ks[ki - 1] : null, next = ki + 1 < ks.length ? ks[ki + 1] : null;
+ const legato = !!prev && prev.t < k.t - 0.02 && Math.abs(prev.off - k.t) < 0.03, slurOut = !!next && next.t > k.t + 0.02 && Math.abs(k.off - next.t) < 0.03;
+ const f = f0(k.p) * Math.pow(2, clamp(gn(r) * 2, -4, 4) / 1200), i0 = onsetI(k.t + (legato ? 0 : clamp(gn(r) * 0.003, -0.006, 0.006)), sr), v = clamp(k.v * (0.93 + 0.14 * r()), 0, 1), dur = Math.max(0.03, k.off - k.t);
+ const a = legato ? 0.018 : (reed ? 0.03 : 0.05) * (0.8 + 0.4 * r()), rl = slurOut ? 0.03 : 0.09 * (0.8 + 0.4 * r()), dyn = 0.3 + 0.7 * v, riseEnd = 1 - Math.exp(-dur / (a / 3));
+ const N = Math.max(1, Math.min(reed ? 24 : 10, Math.floor((0.45 * sr) / (f * 1.02)))), base = new Float64Array(N), wA = new Float64Array(N), wB = new Float64Array(N), wC = new Float64Array(N);
+ for (let h = 0; h < N; h++) { const m = h + 1, fr = m * f;
+ base[h] = reed ? (fr < 1600 ? (m % 2 ? 1 : 0.035) * Math.pow(m, -0.75) : Math.pow(m, -0.75) * Math.pow(1600 / fr, 1.2)) : FLUTE[h] * (m === 2 && f < 400 ? 1.5 : 1) * (f > 1000 ? Math.pow(m, -0.5) : 1); }
+ const gam = reed ? 1.1 : 0.9, chiff = !legato && !reed, vr = 4.9 + 0.7 * r(), vph = r() * TAU, dr = new Drift(r, 0.3, sr), [gl, gr] = pan(clamp(((k.p - 64) / 30) * w, -1, 1));
+ const bpJet = new SVF(sr, Math.min(f, sr * 0.4), 5), bpC = new SVF(sr, Math.min(reed ? 2000 : 2600, sr * 0.4), reed ? 0.7 : 1.2), len = Math.min(n - i0, Math.ceil((dur + rl * 1.6) * sr)), g = LEVEL[reed ? "clarinet" : "flute"];
+ let th = r() * TAU, hp = 0;
+ const weights = (t: number, dst: Float64Array) => { const e = t < dur ? 1 - Math.exp(-t / (a / 3)) : riseEnd * Math.exp(-(t - dur) / (rl / 4)), L = Math.max(1e-4, e * dyn), ch = chiff ? 1 + 2 * Math.exp(-t / 0.03) : 1;
+ for (let h = 0; h < N; h++) dst[h] = base[h] * Math.pow(L, 1 + gam * h) * (h === 1 ? ch : 1); return e; };
+ let e0 = weights(0, wA), e1 = e0;
+ for (let i = 0; i < len; i++) {
+ const bi = i % BLK; if (bi === 0) { e0 = weights(i / sr, wA); e1 = weights((i + BLK) / sr, wB); }
+ const x = bi / BLK; for (let h = 0; h < N; h++) wC[h] = wA[h] + (wB[h] - wA[h]) * x;
+ const t = i / sr, e = e0 + (e1 - e0) * x, vibR = dur > 0.35 ? clamp((t - 0.22) / 0.3, 0, 1) : 0, vs = vibR > 0 ? Math.sin(TAU * vr * t + vph) : 0;
+ const cents = (chiff ? -12 * Math.exp(-t / 0.03) : 0) + 2 * dr.tick() + vibC * vibR * vs;
+ th += (TAU * f * Math.pow(2, cents / 1200)) / sr; if (th > TAU) th -= TAU;
+ const nz = wn(r); hp += 0.2 * (nz - hp); bpJet.tick(nz); bpC.tick(nz);
+ const air = reed ? bpC.bp * (0.012 * breath * e * dyn + 0.05 * v * Math.exp(-t / 0.012)) : (nz - hp) * 0.03 * breath * (0.3 + e * dyn) * e + bpJet.bp * 0.2 * breath * e * dyn + (chiff ? bpC.bp * 0.2 * v * Math.exp(-t / 0.025) : 0);
+ const y = (harmonics(th, wC, N) * (reed ? 1 : 1 + 0.07 * vibR * vs) + air) * g, j = i0 + i;
+ out.L[j] += y * gl; out.R[j] += y * gr;
+ }
+ });
+ return out;
+};
+
+// ------------------------------------------------------------------ choir
+/**
+ * Choir: singers with a glottal source (Rosenberg pulse, the flow derivative with its closure step
+ * band-limited by PolyBLEP; open quotient ~0.62, smaller when loud = brighter), per-period jitter
+ * (~0.4 %) and shimmer (~0.4 dB), aspiration during the open phase and a soft "h" on entries, their
+ * own vibrato, tuning and drift. Singers sum into bass / tenor / alto / soprano buses, each through a
+ * cascade of five formant resonators for the vowel (Peterson & Barney), with F1 raised to follow a
+ * high soprano pitch (formant tuning) and L/R vocal tracts 3 % apart. `vowel`: one of a e i o u, or a
+ * sequence ("ao", "uoa") that morphs across each note. Options: vowel, attack, width; new: singers,
+ * vibrato, breath, release.
+ */
+export const choir = (keys: Played[], sr: number, n: number, o: Opts, r0: Rng): Out => {
+ const seq = String(o.vowel ?? "a").split("").filter((c) => FORMANTS[c]), vowels = seq.length ? seq : ["a"];
+ const atk = num(o, "attack", 0.35), rel = num(o, "release", 0.7), w = num(o, "width", 0.8), S = Math.round(num(o, "singers", 8)), vibAmt = num(o, "vibrato", 1), breath = num(o, "breath", 1), conc = concurrency(keys);
+ const secOf = (p: number) => (p < 52 ? 0 : p < 60 ? 1 : p < 67 ? 2 : 3), SEC_SCALE = [0.97, 1.04, 0.97, 1.04], SEC_PAN = [0.3, 0.1, -0.1, -0.3];
+ const buses = [0, 1, 2, 3].map(() => out0(n)), secKeys: Played[][] = [[], [], [], []];
+ keys.forEach((k, ki) => {
+ const sec = secOf(k.p), P = clamp(Math.round(S / conc[ki]) + 1, 3, S), dur = Math.max(0.05, k.off - k.t), bus = buses[sec]; secKeys[sec].push(k);
+ for (let p = 0; p < P; p++) {
+ const r = subRng(r0), i0 = onsetI(k.t + clamp(gn(r) * (0.008 + 0.02 * clamp(atk, 0, 1)), -0.03, 0.03), sr), v = clamp(k.v * (0.88 + 0.24 * r()), 0, 1), f = f0(k.p), tune = clamp(gn(r) * 4, -9, 9);
+ const a = Math.max(0.02, atk * (0.75 + 0.5 * r())), rl = rel * (0.8 + 0.4 * r()), vr = 4.6 + 1.2 * r(), vd = (18 + 20 * r()) * vibAmt, vDel = 0.25 + 0.25 * r(), vph0 = r() * TAU, dr = new Drift(r, 0.3, sr);
+ const oq = clamp(0.64 - 0.12 * v + 0.04 * gn(r), 0.45, 0.78), sq = 2.4 + 0.8 * r(), tp = (oq * sq) / (1 + sq), tn = oq / (1 + sq), kO = Math.PI / (2 * tp), kC = Math.PI / (2 * tn);
+ const [gl, gr] = pan(clamp(SEC_PAN[sec] * w + (r() - 0.5) * 0.9 * w, -1, 1)), len = Math.min(n - i0, Math.ceil((dur + rl * 1.6) * sr)), riseEnd = 1 - Math.exp(-dur / (a / 3));
+ const g = (LEVEL.choir * Math.pow(v, 0.8)) / Math.sqrt(P), asp = 0.035 * breath, hBurst = 0.25 * breath;
+ let ph = r(), jit = 1, shim = 1;
+ for (let i = 0; i < len; i++) {
+ const t = i / sr, env = t < dur ? 1 - Math.exp(-t / (a / 3)) : riseEnd * Math.exp(-(t - dur) / (rl / 3)), vibR = clamp((t - vDel) / 0.5, 0, 1);
+ const cents = tune + 4 * dr.tick() + (vibR > 0 ? vd * vibR * Math.sin(TAU * vr * t + vph0) : 0), inc = (f * jit * Math.pow(2, cents / 1200)) / sr;
+ ph += inc; if (ph >= 1) { ph -= 1; jit = 1 + 0.004 * gn(r); shim = 1 + 0.05 * gn(r); }
+ let gs = ph < tp ? (kO / kC) * Math.sin(Math.PI * (ph / tp)) : ph < oq ? -Math.sin(Math.PI * ((ph - tp) / (2 * tn))) : 0;
+ let tc = ph - oq; if (tc < 0) tc += 1; gs += 0.5 * blep(tc, inc); // the closure step (+1), band-limited
+ const y = (gs * shim + wn(r) * (asp * (ph < oq ? 1 : 0.35) + hBurst * Math.exp(-t / 0.05) * (1 - env))) * env * g, j = i0 + i;
+ bus.L[j] += y * gl; bus.R[j] += y * gr;
+ }
+ }
+ });
+ const out = out0(n), B = 64;
+ buses.forEach((bus, sec) => {
+ const sk = secKeys[sec].slice().sort((a, b) => a.t - b.t); if (!sk.length) return;
+ const tab = sec < 2 ? "m" : "w", bw = FORMANT_BW[tab], rs = [0, 1].map(() => [0, 1, 2, 3, 4].map(() => new Reson()));
+ let kIdx = 0, gPrev = -1;
+ for (let b0 = 0; b0 < n; b0 += B) {
+ const t = b0 / sr; while (kIdx + 1 < sk.length && sk[kIdx + 1].t <= t) kIdx++;
+ const k = sk[kIdx], pos = vowels.length > 1 ? clamp((t - k.t) / Math.max(0.2, k.off - k.t), 0, 1) * (vowels.length - 1) : 0, vi = Math.min(vowels.length - 2, Math.floor(pos)), fr = vowels.length > 1 ? pos - Math.max(0, vi) : 0;
+ const A = FORMANTS[vowels[Math.max(0, vi)]][tab], Z = FORMANTS[vowels[Math.min(vowels.length - 1, Math.max(0, vi) + 1)]][tab];
+ let fmax = 0; for (let q = kIdx; q >= 0 && q > kIdx - 12; q--) if (sk[q].t <= t && sk[q].off + 0.3 > t) fmax = Math.max(fmax, f0(sk[q].p));
+ let gg = 0;
+ for (let s = 0; s < 2; s++) { const sc = SEC_SCALE[sec] * (s ? 1.015 : 0.985);
+ for (let fi = 0; fi < 5; fi++) { let F = (A[fi] + (Z[fi] - A[fi]) * fr) * sc; if (fi === 0) F = Math.max(F, fmax * 1.12); if (fi === 1) F = Math.max(F, (A[0] + (Z[0] - A[0]) * fr) * sc + 250); rs[s][fi].set(sr, F, bw[fi]); }
+ if (s === 0) { const F1 = rs[0][0]; let m = 1; const fq = Math.max(fmax * 1.12, (A[0] + (Z[0] - A[0]) * fr) * sc); for (const q of rs[0]) m *= q.mag(sr, fq); gg = 1 / Math.max(1e-6, m); void F1; } }
+ if (gPrev < 0) gPrev = gg;
+ const end = Math.min(n, b0 + B);
+ for (let i = b0; i < end; i++) { const gi = gPrev + ((gg - gPrev) * (i - b0)) / B; let l = bus.L[i], rr = bus.R[i]; for (let fi = 0; fi < 5; fi++) { l = rs[0][fi].tick(l); rr = rs[1][fi].tick(rr); } out.L[i] += l * gi; out.R[i] += rr * gi; }
+ gPrev = gg;
+ }
+ });
+ Biquad.make(sr, "hp", 70, 0.7).run(out.L); Biquad.make(sr, "hp", 70, 0.7).run(out.R);
+ return monoLows(out, sr, 220);
+};
+
+// ------------------------------------------------------------------ plucked strings
+type PluckSpec = { width: number; beta: number; noise: number; lpMul: number; /** absolute excitation low-pass (Hz) instead of lpMul x f */ lpAbs?: number; /** contact width grows as (f / 131 Hz)^widthExp (thicker treble strings, softer finger) */ widthExp?: number; loss: number; t60: (f: number) => number; relT60: number; ring: boolean; pol2: number; ir?: IRSpec; pick: number; level: number };
+const PLUCK: Record<string, PluckSpec> = {
+ nylon: { width: 0.0022, beta: 0.2, noise: 0.25, lpMul: 3.5, loss: 0.3, t60: (f) => clamp(3.4 * Math.pow(196 / f, 0.55), 0.7, 7), relT60: 0.18, ring: false, pol2: 0.6, ir: IR_NYLON, pick: 0, level: LEVEL.guitar },
+ steel: { width: 0.0009, beta: 0.13, noise: 0.4, lpMul: 8, loss: 0.16, t60: (f) => clamp(4.5 * Math.pow(196 / f, 0.5), 1, 9), relT60: 0.15, ring: false, pol2: 0.7, ir: IR_STEEL, pick: 0.03, level: LEVEL.guitar },
+ electric: { width: 0.0008, beta: 0.12, noise: 0.35, lpMul: 7, loss: 0.14, t60: (f) => clamp(6 * Math.pow(196 / f, 0.45), 1.5, 12), relT60: 0.12, ring: false, pol2: 0.4, pick: 0.035, level: LEVEL.guitar },
+ // harp: brightness, pluck point and ring fitted by ear-free A/B to VCSL Concert Harp C3/C5 (CC0; tools/ensemble-check.mjs ref)
+ harp: { width: 0.0018, widthExp: 0.35, beta: 0.1, noise: 0.2, lpMul: 3, lpAbs: 900, loss: 0.14, t60: (f) => clamp(9.5 * Math.pow(262 / f, 0.45), 1.5, 16), relT60: 1, ring: true, pol2: 0.5, ir: IR_HARP, pick: 0, level: LEVEL.harp },
+};
+/** One plucked note (mono): excitation, commuted body, extended KS, optional pickup comb and pick scrape; RMS-normalised then scaled by velocity. */
+const pluckNote = (sr: number, n: number, k: Played, s: PluckSpec, r: Rng, extra: { pickup?: number; glide?: { cents: number; tau: number }; thump?: number } = {}) => {
+ const f = f0(k.p) * Math.pow(2, clamp(gn(r) * 1.5, -4, 4) / 1200), v = clamp(k.v * (0.9 + 0.2 * r()), 0.02, 1), T60 = s.t60(f) * (0.92 + 0.16 * r());
+ let exc = pluckExc(sr, f, { width: s.width * Math.pow(f / 131, s.widthExp ?? 0) * (1.3 - 0.6 * v) * (0.9 + 0.2 * r()), beta: s.beta * (0.88 + 0.24 * r()), noise: s.noise, lp: (s.lpAbs ? Math.max(f * 1.2, s.lpAbs) : f * s.lpMul) * (0.6 + 0.8 * v) }, r);
+ if (s.ir) exc = convolve(exc, bodyIR(sr, s.ir));
+ const dur = Math.max(0.02, k.off - k.t), relI = s.ring ? Infinity : Math.round(dur * sr), len = Math.max(1, Math.min(n, Math.ceil((s.ring ? T60 * 1.1 : Math.min(T60 * 1.1, dur + s.relT60 * 1.5)) * sr)));
+ const y = ksRender(sr, { f, T60, loss: s.loss * (0.92 + 0.16 * r()), exc, len, relI: relI === Infinity ? len : relI, relT60: s.relT60, pol2: { cents: 0.3 + 0.7 * r(), mix: s.pol2, t60: 0.45, share: r() }, glide: extra.glide });
+ if (extra.pickup) { const D = extra.pickup * (sr / f), Di = Math.floor(D), Df = D - Di; for (let i = len - 1; i >= 0; i--) { const a = i - Di >= 0 ? y[i - Di] : 0, b = i - Di - 1 >= 0 ? y[i - Di - 1] : 0; y[i] -= 0.9 * (a * (1 - Df) + b * Df); } }
+ const g = (Math.pow(v, 1.3) * (s.ring ? clamp(Math.pow(523 / f, 0.15), 0.3, 0.9) : clamp(Math.pow(523 / f, 0.5), 0.3, 1.2))) / headRms(y, sr); // high notes of real plucked strings are quieter
+ for (let i = 0; i < len; i++) y[i] *= g;
+ if (s.pick > 0 || extra.thump) { let lp = 0; const m = Math.min(len, Math.round(0.02 * sr)), kLp = extra.thump ? 0.03 : 0.5;
+ for (let i = 0; i < m; i++) { const nz = wn(r); lp += kLp * (nz - lp); const e = Math.exp(-i / (0.003 * sr)); y[i] += (extra.thump ? lp * extra.thump * 4 : (nz - lp) * s.pick * 3) * e * v; } }
+ return y;
+};
+
+/**
+ * Guitar and harp: extended Karplus-Strong (ensembleCore.ksRender) with a pick/finger excitation,
+ * pick-position comb, two polarisations and a commuted body IR (nylon or steel dreadnought, harp
+ * soundboard). `kind`: nylon (default) | steel | electric. Electric = no body, a pickup-position comb
+ * (`pickup`: neck | bridge), the pickup's resonant low-pass, then a small clean amp (asymmetric tanh
+ * `drive`, a mid scoop, a 1x12 cab). Harp notes ring past their release, as harpists let them.
+ */
+export const pluck = (keys: Played[], sr: number, n: number, o: Opts, r0: Rng, inst: "harp" | "guitar"): Out => {
+ const out = out0(n), w = num(o, "width", 0.6), kind = inst === "harp" ? "harp" : String(o.kind ?? "nylon"), s = PLUCK[kind] ?? PLUCK.nylon, elec = kind === "electric";
+ const pickup = o.pickup === "bridge" ? 0.08 : 0.25;
+ for (const k of keys) {
+ const r = subRng(r0), i0 = onsetI(k.t + clamp(gn(r) * 0.002, -0.004, 0.004), sr), y = pluckNote(sr, n - i0, k, s, r, elec ? { pickup } : {});
+ const [gl, gr] = pan(clamp(clamp((k.p - 64) / 30, -1, 1) * w + (r() - 0.5) * 0.1, -1, 1)); addStereo(out, i0, y, gl * s.level, gr * s.level);
+ }
+ if (elec) { const drive = num(o, "drive", 1.6);
+ for (const ch of [out.L, out.R]) {
+ Biquad.make(sr, "lp", Math.min(o.pickup === "bridge" ? 4300 : 3300, sr * 0.45), o.pickup === "bridge" ? 2 : 1.6).run(ch);
+ const tb = Math.tanh(0.15), td = Math.tanh(drive); for (let i = 0; i < n; i++) ch[i] = ((Math.tanh(drive * ch[i] * 2 + 0.15) - tb) / td) * 0.5;
+ Biquad.make(sr, "hp", 80, 0.7).run(ch); Biquad.make(sr, "lowshelf", 150, 0.7, 2).run(ch); Biquad.make(sr, "peak", 600, 0.8, -3).run(ch); Biquad.make(sr, "peak", 120, 1, 2).run(ch); Biquad.make(sr, "lp", Math.min(5200, sr * 0.45), 0.9).run(ch);
+ } }
+ return out;
+};
+
+// ------------------------------------------------------------------ bass
+const BASS: Record<string, PluckSpec & { pickup?: number; lp: [number, number]; amp: boolean }> = {
+ finger: { width: 0.003, beta: 0.2, noise: 0.2, lpMul: 2.5, loss: 0.4, t60: (f) => clamp(3.5 * Math.pow(41 / f, 0.3), 1.2, 4), relT60: 0.08, ring: false, pol2: 0.3, pick: 0, level: LEVEL.bass, pickup: 0.14, lp: [2600, 1.1], amp: true },
+ pick: { width: 0.0006, beta: 0.12, noise: 0.4, lpMul: 7, loss: 0.25, t60: (f) => clamp(3.2 * Math.pow(41 / f, 0.3), 1.1, 3.6), relT60: 0.07, ring: false, pol2: 0.3, pick: 0.05, level: LEVEL.bass * 0.85, pickup: 0.1, lp: [4200, 1.3], amp: true },
+ upright: { width: 0.004, beta: 0.27, noise: 0.25, lpMul: 2, loss: 0.5, t60: (f) => clamp(1.5 * Math.pow(41 / f, 0.25), 0.6, 2), relT60: 0.12, ring: false, pol2: 0.4, ir: IR_UPRIGHT, pick: 0, level: LEVEL.bass * 1.27, lp: [5000, 0.7], amp: false },
+};
+/**
+ * Bass. `kind`: finger (default: electric, fingered, DI + amp) | pick | upright (commuted body, a
+ * tension-modulation pitch settle of +12 c, the finger's thump) | synth (saw + sub square into a
+ * 24 dB low-pass with a velocity-keyed envelope, glide on touching notes). Mono, centred.
+ * Options: drive (amp saturation, as v1); new: kind.
+ */
+export const bass = (keys: Played[], sr: number, n: number, o: Opts): Out => {
+ const kind = String(o.kind ?? "finger"), r0 = keysRng(keys, 0xba55);
+ if (kind === "synth") return synthBass(keys, sr, n, o, r0);
+ const s = BASS[kind] ?? BASS.finger, mono = new Float32Array(n);
+ for (const k of keys) { const r = subRng(r0), i0 = onsetI(k.t + clamp(gn(r) * 0.002, -0.004, 0.004), sr);
+ const y = pluckNote(sr, n - i0, k, s, r, { pickup: s.pickup, glide: kind === "upright" ? { cents: 10 + 6 * k.v, tau: 0.045 } : undefined, thump: kind === "upright" ? 0.12 : undefined });
+ const m = Math.min(y.length, n - i0); for (let i = 0; i < m; i++) mono[i0 + i] += y[i] * s.level; }
+ if (s.amp) { const drive = num(o, "drive", 1.3), td = Math.tanh(drive); for (let i = 0; i < n; i++) mono[i] = Math.tanh(drive * mono[i]) / td; }
+ Biquad.make(sr, "hp", 32, 0.7).run(mono); Biquad.make(sr, "lp", Math.min(s.lp[0], sr * 0.45), s.lp[1]).run(mono);
+ return { L: mono, R: Float32Array.from(mono) };
+};
+const synthBass = (keys: Played[], sr: number, n: number, o: Opts, r0: Rng): Out => {
+ const mono = new Float32Array(n), ks = keys.slice().sort((a, b) => a.t - b.t), drive = num(o, "drive", 1.5), td = Math.tanh(drive), cut0 = num(o, "cut", 1.4), envAmt = num(o, "env", 1);
+ ks.forEach((k, ki) => {
+ const r = subRng(r0), prev = ki > 0 ? ks[ki - 1] : null, glideFrom = prev && prev.off > k.t - 0.01 && prev.t < k.t - 0.02 ? f0(prev.p) : 0, f = f0(k.p), i0 = onsetI(k.t, sr), dur = Math.max(0.02, k.off - k.t);
+ const next = ki + 1 < ks.length ? ks[ki + 1] : null, cutEnd = next && next.t < k.off + 0.005 ? next.t - k.t : dur + 0.03;
+ const len = Math.min(n - i0, Math.ceil(cutEnd * sr) + 1), la = new SVF(sr, 400, 0.8), lb = new SVF(sr, 400, 0.8), dec = 0.15 * (0.9 + 0.2 * r()), cj = 0.94 + 0.12 * r(), dr = new Drift(r, 0.4, sr);
+ let ph = r(), ph2 = r();
+ for (let i = 0; i < len; i++) {
+ const t = i / sr, fr = (glideFrom ? f + (glideFrom - f) * Math.exp(-t / 0.012) : f) * Math.pow(2, (2.5 * dr.tick()) / 1200), inc = fr / sr, inc2 = inc / 2;
+ ph += inc; if (ph >= 1) ph -= 1; ph2 += inc2; if (ph2 >= 1) ph2 -= 1;
+ let sq = ph2 < 0.5 ? 1 : -1; sq += blep(ph2, inc2); let q = ph2 - 0.5; if (q < 0) q += 1; sq -= blep(q, inc2);
+ const x = 2 * ph - 1 - blep(ph, inc) + 0.45 * sq;
+ if ((i & 15) === 0) { const c = clamp((fr * 2.2 * cut0 + 1600 * envAmt * k.v * Math.exp(-t / dec)) * cj, 60, sr * 0.4); la.set(c, 0.75); lb.set(c, 0.9); }
+ const e = Math.min(1, t / 0.003) * (0.8 + 0.2 * Math.exp(-t / 0.2)) * (t < dur ? 1 : Math.exp(-(t - dur) / 0.03)) * (t > cutEnd - 0.004 && next && next.t < k.off + 0.005 ? Math.max(0, (cutEnd - t) / 0.004) : 1);
+ mono[i0 + i] += (Math.tanh(drive * lb.tick(la.tick(x)) * 0.7) / td) * e * Math.pow(k.v, 1.1) * LEVEL.synthBass;
+ }
+ });
+ Biquad.make(sr, "hp", 30, 0.7).run(mono);
+ return { L: mono, R: Float32Array.from(mono) };
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/ensembleCore.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/ensembleCore.ts
new file mode 100644
index 0000000..a712d69
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/ensembleCore.ts
@@ -0,0 +1,187 @@
+// Shared machinery for the ensemble voices (ensemble.ts): per-note seeded variation, slow random
+// drift, an extended Karplus-Strong string, commuted body impulse responses, formant resonators and
+// the "measured physics" tables (body modes, formants, spectra) with their provenance.
+// Everything is pure in its inputs: same keys + seed -> the same samples.
+import { type Rng, TAU, clamp, Biquad } 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 f0 = (m: number) => 440 * Math.pow(2, (m - 69) / 12);
+export const out0 = (n: number): Out => ({ L: new Float32Array(n), R: new Float32Array(n) });
+/** Fast unit-variance noise (uniform, sqrt 12 scaled): cheap enough to run per sample per player. */
+export const wn = (r: Rng) => (r() - 0.5) * 3.4641016;
+export const gn = (r: Rng) => { let u = r(); if (u < 1e-12) u = 1e-12; return Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * r()); };
+/** An independent stream per note, drawn from the part's stream: a note's randomness never shifts its neighbours'. */
+export const subRng = (r: Rng): Rng => mkRng(Math.floor(r() * 4294967296));
+/** A part stream for voices the renderer hands no rng: a hash of the performed keys (deterministic). */
+export const keysRng = (keys: Played[], salt: number): Rng => {
+ let h = (2166136261 ^ salt) >>> 0;
+ for (const k of keys) { h = Math.imul(h ^ Math.round(k.t * 1000), 16777619); h = Math.imul(h ^ k.p, 16777619); h = Math.imul(h ^ Math.round(k.v * 1000), 16777619); }
+ return mkRng(h >>> 0);
+};
+/** How many keys sound at each key's onset (itself included): a section divides its players across a chord (divisi). */
+export const concurrency = (keys: Played[]) => {
+ const idx = keys.map((_, i) => i).sort((a, b) => keys[a].t - keys[b].t), c = new Array<number>(keys.length).fill(1);
+ for (let a = 0; a < idx.length; a++) { const k = keys[idx[a]]; let m = 0;
+ for (let b = a; b >= 0; b--) { const q = keys[idx[b]]; if (q.off > k.t && q.t <= k.t + 0.03) m++; if (k.t - q.t > 12) break; }
+ for (let b = a + 1; b < idx.length && keys[idx[b]].t <= k.t + 0.03; b++) m++;
+ c[idx[a]] = Math.max(1, m); }
+ return c;
+};
+
+/**
+ * Slow random drift (Ornstein-Uhlenbeck, unit standard deviation), updated every `block` samples
+ * and interpolated between, so pitch and level wander the way a player does instead of a sine LFO.
+ */
+export class Drift {
+ private a = 0; private b = 0; private i = 0; private k: number; private s: number;
+ constructor(private r: Rng, hz: number, sr: number, private block = 64) { const th = TAU * hz * (block / sr); this.k = Math.exp(-th); this.s = Math.sqrt(1 - this.k * this.k); this.a = gn(r); this.b = this.a * this.k + this.s * gn(r); }
+ tick() { if (this.i >= this.block) { this.i = 0; this.a = this.b; this.b = this.b * this.k + this.s * wn(this.r); } return this.a + ((this.b - this.a) * this.i++) / this.block; }
+}
+
+/** Klatt-style resonator (unity gain at DC); a cascade of five is a vowel's vocal tract. */
+export class Reson {
+ private y1 = 0; private y2 = 0; A = 1; B = 0; C = 0;
+ set(sr: number, f: number, bw: number) { const T = 1 / sr, fr = clamp(f, 20, sr * 0.46); this.C = -Math.exp(-TAU * bw * T); this.B = 2 * Math.exp(-Math.PI * bw * T) * Math.cos(TAU * fr * T); this.A = 1 - this.B - this.C; }
+ tick(x: number) { const y = this.A * x + this.B * this.y1 + this.C * this.y2; this.y2 = this.y1; this.y1 = y; return y; }
+ /** |H| at frequency f (for level normalisation) */
+ mag(sr: number, f: number) { const w = (TAU * f) / sr, cr = 1 - this.B * Math.cos(w) - this.C * Math.cos(2 * w), ci = this.B * Math.sin(w) + this.C * Math.sin(2 * w); return Math.abs(this.A) / Math.hypot(cr, ci); }
+}
+
+/** Mono below `f` Hz (M/S: the side channel high-passed), the mix rule for low end; the highs keep their width. */
+export const monoLows = (o: Out, sr: number, f = 160) => { const h1 = Biquad.make(sr, "hp", f, 0.54), h2 = Biquad.make(sr, "hp", f, 1.31); // 4th-order Butterworth on the side
+ for (let i = 0; i < o.L.length; i++) { const m = 0.5 * (o.L[i] + o.R[i]), sd = h2.tick(h1.tick(0.5 * (o.L[i] - o.R[i]))); o.L[i] = m + sd; o.R[i] = m - sd; } return o; };
+/** A body as a chain of peaking filters (strings): run on a whole bus, one chain per channel. */
+export type PeakBody = { peaks: [number, number, number][]; shelf: [number, number]; hp: number };
+export const runBody = (buf: Float32Array, sr: number, b: PeakBody, scale = 1) => {
+ const ny = sr * 0.45;
+ Biquad.make(sr, "hp", Math.min(b.hp * scale, ny), 0.7).run(buf);
+ for (const [f, q, g] of b.peaks) if (f * scale < ny) Biquad.make(sr, "peak", f * scale, q, g).run(buf);
+ if (b.shelf[0] * scale < ny) Biquad.make(sr, "highshelf", b.shelf[0] * scale, 0.7, b.shelf[1]).run(buf);
+};
+
+// ------------------------------------------------------------------ measured-physics tables
+// Provenance: mode FREQUENCIES are published measurements; gains, Q and amplitudes are voiced by
+// hand to those measurements (no recording was fitted, none ships). Sources:
+// violin: Bissinger, "Structural acoustics of good and bad violins", JASA 124(3) 2008 (A0 ~275,
+// CBR ~405, B1- ~470, B1+ ~540 Hz; the 2-3 kHz bridge hill); Jansson, "Acoustics for Violin and
+// Guitar Makers" (KTH, 2002) ch. 7-8; Duennwald 1991 bands (a dip in the 1.3-1.6 kHz "nasal" band).
+// viola = violin modes x0.82 (Rossing, "The Science of String Instruments", 2010, ch. 13).
+// cello: Bynum & Rossing in Rossing 2010 ch. 13 (A0 ~100, B1- ~175, B1+ ~210 Hz, bridge hill ~1.6 kHz).
+export const VIOLIN_BODY: PeakBody = { hp: 180, shelf: [5200, -9], peaks: [[275, 6, 5], [405, 8, 2], [470, 7, 6], [540, 7, 5.5], [700, 4, 1.5], [1000, 3, 3], [1450, 2, -4], [2500, 1.2, 6], [3500, 2.5, 2]] };
+export const CELLO_BODY: PeakBody = { hp: 55, shelf: [4200, -9], peaks: [[100, 5, 5], [150, 6, 2], [175, 6, 6], [210, 6, 5], [340, 4, 2], [600, 3, 2], [900, 2, -3], [1650, 1.2, 5], [2800, 2.5, 1.5]] };
+
+/** A commuted body impulse response: low modes from measurements, a seeded dense modal field above. */
+export type IRSpec = { key: string; modes: [number, number, number][]; dense: [number, number, number, number]; len: number; direct: number };
+// nylon: Christensen & Vistisen, JASA 68 (1980); Rossing & Fletcher, "The Physics of Musical
+// Instruments" (1998) ch. 9: A0 ~98, T(1,1)1 ~204, T(1,1)2 ~240, (1,2) ~385 Hz, then plate modes.
+// steel: Rossing 2010 ch. 12 (dreadnought: A0 ~102, T1 ~195, ~225, ~370, ~440 Hz).
+// harp: soundboard modes after Le Carrou et al., JASA 2005 (concert harp, 60-700 Hz region).
+// upright bass: Askenfelt, "Eigenmodes and tone quality of the double bass" (KTH STL-QPSR 1982): A0 ~57 Hz, ~105, ~130 Hz.
+export const IR_NYLON: IRSpec = { key: "nylon", len: 0.09, direct: 1, dense: [800, 5000, 60, 0.35], modes: [[98, 16, 1], [204, 24, 0.9], [240, 28, 0.55], [290, 30, 0.3], [385, 34, 0.45], [455, 38, 0.3], [550, 40, 0.35], [650, 44, 0.25]] };
+export const IR_STEEL: IRSpec = { key: "steel", len: 0.08, direct: 1, dense: [700, 7000, 80, 0.45], modes: [[102, 15, 1], [195, 22, 0.8], [225, 26, 0.6], [370, 34, 0.5], [440, 38, 0.4], [540, 40, 0.4], [690, 44, 0.3], [870, 48, 0.25]] };
+export const IR_HARP: IRSpec = { key: "harp", len: 0.07, direct: 1.2, dense: [700, 4000, 40, 0.25], modes: [[75, 10, 0.5], [150, 14, 0.6], [250, 20, 0.5], [400, 24, 0.4], [600, 28, 0.3]] };
+export const IR_UPRIGHT: IRSpec = { key: "upright", len: 0.11, direct: 0.9, dense: [400, 2500, 40, 0.3], modes: [[57, 9, 0.8], [105, 13, 1], [130, 15, 0.8], [180, 18, 0.5], [250, 22, 0.4], [350, 28, 0.3]] };
+const IR_CACHE = new Map<string, Float64Array>();
+export const bodyIR = (sr: number, s: IRSpec): Float64Array => {
+ const ck = `${s.key}@${sr}`, hit = IR_CACHE.get(ck); if (hit) return hit;
+ const n = Math.round(s.len * sr), ir = new Float64Array(n), r = mkRng(0x5eed + s.key.length * 977 + s.key.charCodeAt(0));
+ const modes = s.modes.slice(), [lo, hi, cnt, amp] = s.dense;
+ for (let i = 0; i < cnt; i++) { const f = lo * Math.pow(hi / lo, r()); modes.push([f, 25 + 35 * r(), amp * Math.sqrt(lo / f) * (0.4 + 0.6 * r())]); }
+ for (const [f, q, a] of modes) { if (f > sr * 0.45) continue; const dec = Math.exp(-Math.PI * f / q / sr), w = (TAU * f) / sr, cw = Math.cos(w), sw = Math.sin(w); let c = a, sn = 0;
+ for (let i = 0; i < n; i++) { ir[i] += sn; const c2 = (c * cw - sn * sw) * dec; sn = (c * sw + sn * cw) * dec; c = c2; } }
+ let e = 0; for (let i = 0; i < n; i++) e += ir[i] * ir[i]; const k = 1 / Math.sqrt(e / 40 + 1e-12); // modal energy relative to the direct pulse
+ for (let i = 0; i < n; i++) ir[i] *= k * 0.55; ir[0] += s.direct;
+ const fade = Math.round(0.01 * sr); for (let i = 0; i < fade; i++) ir[n - 1 - i] *= i / fade;
+ IR_CACHE.set(ck, ir); return ir;
+};
+export const convolve = (x: Float64Array, h: Float64Array) => { const y = new Float64Array(x.length + h.length - 1);
+ for (let i = 0; i < x.length; i++) { const xi = x[i]; if (xi === 0) continue; for (let j = 0; j < h.length; j++) y[i + j] += xi * h[j]; } return y; };
+
+/**
+ * A pluck's excitation (bridge force): a raised-cosine contact `width` s long plus a little
+ * seeded contact noise, low-passed above `lp` Hz (the 1/n fall of a plucked string's spectrum),
+ * then the pick-position comb (harmonics at multiples of 1/beta vanish). No DC by construction.
+ */
+export const pluckExc = (sr: number, f: number, o: { width: number; beta: number; noise: number; lp: number }, r: Rng) => {
+ const W = Math.max(2, Math.round(o.width * sr)), D = o.beta * (sr / f), Di = Math.floor(D), Df = D - Di, n = W + Di + 3, e = new Float64Array(n), c = new Float64Array(n);
+ const a = Math.exp((-TAU * Math.min(o.lp, sr * 0.45)) / sr); let y = 0;
+ for (let i = 0; i < n; i++) { const x = i < W ? 0.5 * (1 - Math.cos((TAU * (i + 0.5)) / W)) * (1 + o.noise * wn(r)) : 0; y = (1 - a) * x + a * y; e[i] = y; }
+ for (let i = 0; i < n; i++) { const j = i - D, j0 = Math.floor(j), fr = j - j0, v = j0 >= 0 ? e[j0] * (1 - fr) + (j0 + 1 < n ? e[j0 + 1] : 0) * fr : j0 === -1 ? e[0] * fr : 0; c[i] = e[i] - v; }
+ void Df; return c;
+};
+
+export type KSOpts = { f: number; T60: number; loss: number; exc: Float64Array; len: number; relI: number; relT60: number;
+ /** second polarisation: detune (cents), level, decay factor vs the first, share of the pluck (0..1) */ pol2?: { cents: number; mix: number; t60: number; share: number };
+ /** tension-modulation pitch glide at the attack: +cents decaying with tau s (Lagrange-read line) */ glide?: { cents: number; tau: number } };
+/**
+ * Extended Karplus-Strong (Jaffe & Smith 1983; Karjalainen, Valimaki & Tolonen 1998): a loop of
+ * delay + one-pole loss + Thiran allpass tuning, with the excitation INJECTED over time (so a
+ * commuted body can ride on it), two polarisations (a detuned, faster-decaying vertical one gives
+ * the two-stage decay and slow beating) and finger damping after release. The loss filter's phase
+ * delay is subtracted from the loop so every note is in tune (checked in tools/ensemble-check.mjs).
+ */
+export const ksRender = (sr: number, o: KSOpts): Float64Array => {
+ const out = new Float64Array(o.len);
+ const run = (fHz: number, T60: number, share: number, mix: number) => {
+ const a = o.loss, w = (TAU * fHz) / sr, pd = Math.atan2(a * Math.sin(w), 1 - a * Math.cos(w)) / w, mag = (1 - a) / Math.sqrt(1 - 2 * a * Math.cos(w) + a * a);
+ // the loop's DC gain is g (the one-pole passes DC at unity): keep it below 1 or low frequencies grow without bound
+ const g = Math.min(0.99995, Math.pow(10, -3 / (T60 * fHz)) / mag), gRel = Math.min(g, Math.pow(10, -3 / (Math.max(0.02, o.relT60) * fHz)) / mag), L = sr / fHz - pd;
+ const kRel = Math.exp(-1 / (0.012 * sr)); let gc = g, lp = 0;
+ if (!o.glide) {
+ const N = Math.max(2, Math.floor(L - 0.5)), d = L - N, c = (1 - d) / (1 + d), buf = new Float64Array(N); let idx = 0, apx = 0, apy = 0;
+ for (let i = 0; i < o.len; i++) {
+ if (i >= o.relI) gc = gRel + (gc - gRel) * kRel;
+ lp = (1 - a) * buf[idx] + a * lp; const v = gc * lp, ap = c * v + apx - c * apy; apx = v; apy = ap;
+ const y = ap + (i < o.exc.length ? o.exc[i] * share : 0); buf[idx] = y; idx = idx + 1 === N ? 0 : idx + 1; out[i] += y * mix;
+ }
+ } else {
+ const M = Math.ceil(L * (1 + o.glide.cents / 1000)) + 8, buf = new Float64Array(M); let wi = 0; const kg = Math.exp(-1 / (o.glide.tau * sr));
+ let cents = o.glide.cents;
+ for (let i = 0; i < o.len; i++) {
+ if (i >= o.relI) gc = gRel + (gc - gRel) * kRel;
+ const D = clamp(L / Math.pow(2, cents / 1200), 3, M - 4); cents *= kg;
+ let pos = wi - D; if (pos < 0) pos += M; const i1 = Math.floor(pos), x = pos - i1;
+ const ym1 = buf[(i1 - 1 + M) % M], y0 = buf[i1 % M], y1 = buf[(i1 + 1) % M], y2 = buf[(i1 + 2) % M];
+ const rd = (-x * (x - 1) * (x - 2) / 6) * ym1 + ((x + 1) * (x - 1) * (x - 2) / 2) * y0 - ((x + 1) * x * (x - 2) / 2) * y1 + ((x + 1) * x * (x - 1) / 6) * y2; // 3rd-order Lagrange
+ lp = (1 - a) * rd + a * lp; const y = gc * lp + (i < o.exc.length ? o.exc[i] * share : 0); buf[wi] = y; wi = wi + 1 === M ? 0 : wi + 1; out[i] += y * mix;
+ }
+ }
+ };
+ const p2 = o.pol2;
+ run(o.f, o.T60, p2 ? Math.sqrt(1 - p2.share) : 1, 1);
+ if (p2 && p2.mix > 0) run(o.f * Math.pow(2, p2.cents / 1200), o.T60 * p2.t60, Math.sqrt(p2.share), p2.mix);
+ return out;
+};
+/** RMS of the first `sec` seconds (note-level normalisation, so level follows velocity, not period or pluck width). */
+export const headRms = (x: Float64Array, sr: number, sec = 0.08) => { const m = Math.min(x.length, Math.round(sec * sr)); let e = 0; for (let i = 0; i < m; i++) e += x[i] * x[i]; return Math.sqrt(e / Math.max(1, m)) + 1e-12; };
+
+// Formants: Peterson & Barney, JASA 24 (1952), average adult men / women F1-F3 (a = /A/ "hod",
+// e = /E/ "head", i = /i/ "heed", o = /O/ "hawed" with F1 x0.88 for the rounded sung "oh",
+// u = /u/ "who'd"); F4, F5 and the bandwidths are typical values (Sundberg, "The Science of the
+// Singing Voice", 1987; F1 bandwidth 60-90 Hz rising to ~200 Hz at F5).
+export const FORMANTS: Record<string, { m: number[]; w: number[] }> = {
+ a: { m: [730, 1090, 2440, 3350, 3850], w: [850, 1220, 2810, 3950, 4650] },
+ e: { m: [530, 1840, 2480, 3350, 3850], w: [610, 2330, 2990, 4000, 4700] },
+ i: { m: [270, 2290, 3010, 3400, 3900], w: [310, 2790, 3310, 4100, 4800] },
+ o: { m: [500, 840, 2410, 3300, 3800], w: [520, 920, 2710, 3900, 4600] },
+ u: { m: [300, 870, 2240, 3300, 3800], w: [370, 950, 2670, 3900, 4600] },
+};
+export const FORMANT_BW = { m: [70, 80, 110, 140, 180], w: [85, 95, 125, 160, 200] };
+
+// Brass radiation formants in dB bumps on a log-frequency axis [fc, width octaves, dB] plus a
+// roll-off corner and slope. Trumpet regions ~1.2 and ~2.5 kHz, trombone ~520 Hz / 1.2 kHz, horn
+// ~340-450 Hz with a dark top (Meyer, "Acoustics and the Performance of Music", 2009, ch. 2;
+// Luce & Clark, JASA 1967). Shapes voiced by hand.
+export const BRASS_FORMANT: Record<string, { bumps: [number, number, number][]; roll: number; slope: number }> = {
+ trumpet: { bumps: [[1250, 0.45, 6], [2500, 0.5, 4]], roll: 4200, slope: 12 },
+ trombone: { bumps: [[540, 0.5, 5], [1200, 0.6, 3]], roll: 2600, slope: 12 },
+ horn: { bumps: [[420, 0.55, 6], [850, 0.6, 1]], roll: 1300, slope: 16 },
+};
+export const bumpDb = (fr: number, b: { bumps: [number, number, number][]; roll: number; slope: number }) => {
+ let g = 0; for (const [fc, wo, db] of b.bumps) { const x = Math.log2(fr / fc) / wo; g += db * Math.exp(-0.5 * x * x); }
+ if (fr > b.roll) g -= b.slope * Math.log2(fr / b.roll); return g;
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/grooves.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/grooves.ts
index c6b5ff9..653be19 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/grooves.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/grooves.ts
@@ -45,11 +45,11 @@ const grid = (meter: Meter, triplet: boolean) => {
};
const round = (x: number) => +x.toFixed(3);
/** Hits (step -> velocity multiplier) to one bar of notation. */
-export const stepsToLine = (hits: Map<number, number>, steps: number, per: number): string | null => {
+export const stepsToLine = (hits: Map<number, number>, steps: number, per: number, pitch?: Map<number, string>): string | null => {
const at = [...hits.keys()].filter((s) => s >= 0 && s < steps).sort((a, b) => a - b); if (!at.length) return null;
const d = (n: number) => (per === 3 ? `${n}/3` : String(n / per)); // exact: fractions for triplets, decimals for 16ths
const toks: string[] = []; if (at[0] > 0) toks.push(`r:${d(at[0])}`);
- at.forEach((s, i) => { const nx = i + 1 < at.length ? at[i + 1] : steps; toks.push(`C4:${d(nx - s)}@${round(Math.min(1, Math.max(0.05, hits.get(s)!)))}`); });
+ at.forEach((s, i) => { const nx = i + 1 < at.length ? at[i + 1] : steps; toks.push(`${pitch?.get(s) ?? "C4"}:${d(nx - s)}@${round(Math.min(1, Math.max(0.05, hits.get(s)!)))}`); });
return toks.join(" ");
};
@@ -171,13 +171,24 @@ export const grooveBar = (g: GrooveChoice, meter: Meter, seed: number, abs: numb
break;
}
}
- if (g.fill && pos === len - 1) { const f0 = steps - per; for (let s = f0; s < steps; s++) S.set(s, 0.45 + 0.5 * ((s - f0) / per)); }
+ // the fill: kit families roll down the toms (GM notes: high tom D3, mid B2 / A2, floor G2 / F2); machine and orchestral ones stay on the snare
+ const toms = new Map<number, string>();
+ if (g.fill && pos === len - 1) { const f0 = steps - per, TOMS = per === 3 ? ["D3", "A2", "F2"] : ["D3", "B2", "A2", "G2"], onToms = TOM_FILL.has(g.family);
+ for (let s = f0; s < steps; s++) { S.set(s, 0.45 + 0.5 * ((s - f0) / per)); if (onToms) toms.set(s, TOMS[s - f0]); } }
const out: DrumBar = {};
- for (const [lane, m] of [["kick", K], ["snare", S], ["ghost", Gh], ["hat", H], ["perc", P]] as [Lane, Map<number, number>][]) out[lane] = stepsToLine(m, steps, per);
+ for (const [lane, m] of [["kick", K], ["snare", S], ["ghost", Gh], ["hat", H], ["perc", P]] as [Lane, Map<number, number>][]) out[lane] = stepsToLine(m, steps, per, lane === "snare" ? toms : undefined);
return out;
};
export const isLiteral = (g: Groove): g is LiteralGroove => !("family" in g);
+const TOM_FILL = new Set<GrooveFamily>(["rock", "bounce", "halfTime", "broken", "shuffle", "swing", "epic", "tension"]);
+/** What each lane of a family IS, as a note kind for the kit voice (drums.ts): a fourFloor snare lane is a clap, a swing hat lane a ride. */
+const LANE_KIND: Partial<Record<GrooveFamily, Partial<Record<Lane, string>>>> = {
+ fourFloor: { snare: "clap", perc: "open" }, skip: { snare: "clap", perc: "shaker" }, trap: { snare: "clap", perc: "open" }, halfTime: { perc: "open" }, shuffle: { perc: "open" },
+ swing: { hat: "ride", perc: "pedal" }, brushes: { ghost: "cross", perc: "sweep" }, pulse: { perc: "shaker" }, rock: { perc: "crash" }, epic: { perc: "crash" }, build: { perc: "crash" },
+ hand: { kick: "dum", ghost: "tek", perc: "ka" }, tension: { perc: "ride" },
+};
+export const laneKind = (g: Groove, lane: Lane): string => (isLiteral(g) ? undefined : LANE_KIND[g.family]?.[lane]) ?? (lane === "perc" ? "perc" : lane);
/** One bar of any groove (literal lanes cycle on the absolute bar). */
export const drumBar = (g: Groove, meter: Meter, seed: number, abs: number, pos: number, len: number, energy?: number): DrumBar => {
if (!isLiteral(g)) return grooveBar(g, meter, seed, abs, pos, len, energy);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
index d8bfe6e..33e3f37 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
@@ -17,6 +17,9 @@ export * from "./calibration";
export * as instruments from "./instruments";
export * from "./sfx";
export * as orchestra from "./orchestra";
+export * as lofiFx from "./lofiFx";
+export { MIX_PROFILES, FEELS, mixProfile, describeMix, type MixProfile, type Feel } from "./mixProfiles";
+export * as drums from "./drums";
import { nocturne, pianoPhrase8 } from "./pieces/nocturne";
import { launchLofi, launchLofi2, launchLofi3, launchLofi3Material } from "./pieces/launch";
import { musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic } from "./pieces/samplers";
@@ -34,3 +37,4 @@ export const DEMOS = { launchLofi, launchLofi2, launchLofi3, nocturne, pianoPhra
export 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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/instruments.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/instruments.ts
index e2d2e43..60190a5 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/instruments.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/instruments.ts
@@ -2,6 +2,8 @@
// presses in seconds. Presets are numbers in one place (the constants at the top of each voice).
import { type Rng, TAU, clamp, pan, SVF, Biquad, blep, onePoleCoef, gauss } from "./dsp";
import type { Played } from "./perform";
+import { kitVoice, type KitCtx } from "./drums";
+import * as E from "./ensemble";
type Out = { L: Float32Array; R: Float32Array };
type Opts = Record<string, number | boolean | string>;
@@ -66,7 +68,7 @@ export const mallets = (keys: Played[], sr: number, n: number, o: Opts, vibes =
* filter for brightness, an allpass for fine tuning, a pick-position comb on the excitation and a
* velocity low-pass (a softer pluck is darker). Harp rings long and bright; guitar gets a body.
*/
-export const pluck = (keys: Played[], sr: number, n: number, o: Opts, r: Rng, kind: "harp" | "guitar"): Out => {
+const pluckLegacy = (keys: Played[], sr: number, n: number, o: Opts, r: Rng, kind: "harp" | "guitar"): Out => {
const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.6);
for (const k of keys) {
const f = f0(k.p), i0 = Math.round(k.t * sr), P = sr / f, N = Math.floor(P - 0.5), frac = P - N - 0.5;
@@ -98,7 +100,7 @@ export const pluck = (keys: Played[], sr: number, n: number, o: Opts, r: Rng, ki
};
/** Soft string ensemble: 5 detuned PolyBLEP saws per note, slow bow attack, delayed vibrato, low-pass, high-pass 150 Hz. */
-export const strings = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
+const stringsLegacy = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
const out = { L: new Float32Array(n), R: new Float32Array(n) }, atk = num(o, "attack", 0.45), rel = num(o, "release", 0.9), w = num(o, "width", 0.8), bright = num(o, "bright", 1);
const hpL = new SVF(sr, 150, 0.7), hpR = new SVF(sr, 150, 0.7);
for (const k of keys) {
@@ -178,25 +180,31 @@ export const triangle = (keys: Played[], sr: number, n: number): Out => {
}
return out;
};
+/** Drum-lane kinds (grooves.laneKind) to the NES channel's three sounds. */
+const NES_KIND: Record<string, "k" | "s" | "h"> = { k: "k", s: "s", h: "h", o: "s", kick: "k", dum: "k", snare: "s", ghost: "s", clap: "s", cross: "s", brush: "s", sweep: "s", tek: "s", hat: "h", open: "h", pedal: "h", ride: "h", shaker: "h", crash: "h", ka: "h" };
/** NES noise channel: a 15-bit LFSR (long mode for snare/kick, short 93-step mode for hats). */
export const noiseDrum = (keys: Played[], sr: number, n: number): Out => {
const out = { L: new Float32Array(n), R: new Float32Array(n) };
for (const k of keys) {
- const kind = k.kind ?? "s", i0 = Math.round(k.t * sr); let reg = 1, acc = 0;
+ const kind = NES_KIND[k.kind ?? "s"] ?? "s", i0 = Math.round(k.t * sr); let reg = 1, acc = 0;
const rate = kind === "h" ? 32000 : kind === "k" ? 3500 : 11000, dec = kind === "h" ? 0.028 : kind === "k" ? 0.07 : 0.11, short = kind === "h";
const len = Math.min(n - i0, Math.ceil(dec * 6 * sr)); let out1 = 1;
for (let i = 0; i < len; i++) {
acc += rate / sr; while (acc >= 1) { acc -= 1; const bit = (reg ^ (reg >> (short ? 6 : 1))) & 1; reg = (reg >> 1) | (bit << 14); out1 = reg & 1 ? 1 : -1; }
const t = i / sr, e = Math.round(Math.exp(-t / dec) * 15) / 15;
- let y = out1 * e * k.v * (kind === "h" ? 0.07 : 0.14);
- if (kind === "k") { const fq = 55 + 110 * Math.exp(-t / 0.03); y += Math.sin(TAU * fq * t) * Math.exp(-t / 0.09) * k.v * 0.4; }
+ let y = out1 * e * k.v * (kind === "h" ? 0.07 : kind === "k" ? 0.08 : 0.14);
+ if (kind === "k") { const fq = 55 + 110 * Math.exp(-t / 0.03); y += Math.sin(TAU * fq * t) * Math.exp(-t / 0.09) * k.v * 0.22; }
out.L[i0 + i] += y; out.R[i0 + i] += y;
}
}
return out;
};
-// ---------------------------------------------------------------- drums and bass (soft kit)
+// ---------------------------------------------------------------- drums
+/** The kit lanes. New sound: drums.ts (six kit characters). A legacy piece (Piece.legacy, the shipped launch film) or `legacy: true` on the part keeps the original soft kit below, bit for bit. */
+export const drumVoice = (inst: string, keys: Played[], sr: number, n: number, o: Opts, r: Rng, ctx: KitCtx = {}): Out =>
+ ctx.legacy || o.legacy === true ? (inst === "kick" ? kick(keys, sr, n, o) : inst === "snare" ? snare(keys, sr, n, o, r) : hat(keys, sr, n, o, r)) : kitVoice(inst, keys, sr, n, o, r, ctx);
+// ---------------------------------------------------------------- legacy soft kit, and bass
export const kick = (keys: Played[], sr: number, n: number, o: Opts): Out => {
const out = { L: new Float32Array(n), R: new Float32Array(n) }, soft = num(o, "soft", 1);
for (const k of keys) { const i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil(0.5 * sr)); let ph = 0;
@@ -218,7 +226,7 @@ export const hat = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out
return out;
};
/** Warm bass: sine + harmonics, a pluck envelope, and a little saturation so phones hear the line (phone rule). */
-export const bass = (keys: Played[], sr: number, n: number, o: Opts): Out => {
+const bassLegacy = (keys: Played[], sr: number, n: number, o: Opts): Out => {
const out = { L: new Float32Array(n), R: new Float32Array(n) }, drive = num(o, "drive", 1.6);
for (const k of keys) { const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.1) * sr));
for (let i = 0; i < len; i++) { const t = i / sr, e = Math.min(1, t * 300) * (0.55 + 0.45 * Math.exp(-t / 0.25)) * (t < dur ? 1 : Math.exp(-(t - dur) / 0.03));
@@ -232,3 +240,10 @@ export const vinyl = (keys: Played[], sr: number, n: number, _o: Opts, r: Rng):
for (let i = 0; i < len; i++) { const pop = r() < 7 / sr ? (r() - 0.5) * 0.5 * k.v : 0; const hiss = gauss(r) * 0.004 * k.v; zl += lp * (hiss + pop - zl); zr += lp * (hiss * 0.8 + pop - zr); out.L[i0 + i] += zl; out.R[i0 + i] += zr; } }
return out;
};
+
+// ---------------------------------------------------------------- v2 ensemble voices (ensemble.ts)
+// `opts.legacy: true` keeps the v1 voice bit-for-bit (shipped films); everything else gets v2.
+const legacy = (o: Opts) => o.legacy === true;
+export const pluck = (keys: Played[], sr: number, n: number, o: Opts, r: Rng, kind: "harp" | "guitar"): Out => (legacy(o) ? pluckLegacy(keys, sr, n, o, r, kind) : E.pluck(keys, sr, n, o, r, kind));
+export const strings = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => (legacy(o) ? stringsLegacy(keys, sr, n, o, r) : E.strings(keys, sr, n, o, r));
+export const bass = (keys: Played[], sr: number, n: number, o: Opts): Out => (legacy(o) ? bassLegacy(keys, sr, n, o) : E.bass(keys, sr, n, o));
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keys.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keys.ts
new file mode 100644
index 0000000..02ba0ad
--- /dev/null
+++ b/plugins/anidoodle/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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysCore.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysCore.ts
new file mode 100644
index 0000000..a125582
--- /dev/null
+++ b/plugins/anidoodle/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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysEP.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysEP.ts
new file mode 100644
index 0000000..4379b24
--- /dev/null
+++ b/plugins/anidoodle/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, I3 = 0.5 + 0.7 * v, I2 = Math.min(0.2 + 3.2 * Math.pow(v, 1.6), Math.max(0, (0.42 * sr / f - 1) / 14 - 1)); // the 14:1 bark's sidebands stay under Nyquist (no aliasing up high)
+ 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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysMallets.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysMallets.ts
new file mode 100644
index 0000000..ea66f15
--- /dev/null
+++ b/plugins/anidoodle/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) * clamp(Math.pow(262 / f0, 0.6), 0.15, 2) * (1 + 0.1 * clamp(gauss(nv.r), -2, 2)) / nv.bright; // shorter, stiffer bars up high: shorter contact
+ 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 = Math.max(0.3, pulseW(f0, tc)); // never divide by a spectral zero of the pulse (contact ~1.5 periods): that blew a mode up 20 dB
+ 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)) * (Math.max(0.02, 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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysOrgan.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysOrgan.ts
new file mode 100644
index 0000000..2380492
--- /dev/null
+++ b/plugins/anidoodle/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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysPiano.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysPiano.ts
new file mode 100644
index 0000000..f351f31
--- /dev/null
+++ b/plugins/anidoodle/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 = { noiseHz: number; 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: { noiseHz: 2200, 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: { noiseHz: 650, 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: { noiseHz: 1800, 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: { noiseHz: 2600, 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), V.noiseHz * (1 + 0.9 * 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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysTables.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/keysTables.ts
new file mode 100644
index 0000000..098dd05
--- /dev/null
+++ b/plugins/anidoodle/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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/lofiFx.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/lofiFx.ts
new file mode 100644
index 0000000..82193fc
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/lofiFx.ts
@@ -0,0 +1,318 @@
+// LO-FI, DONE AS PRODUCTION (research doc section 4). The old "lo-fi" was a darker clean mix plus a
+// pure-sine vibrato: Alex heard "bad 80s MIDI". Real lo-fi is a chain of machines, in this order:
+// instrument -> SAMPLER (SP-1200 / MPC: rate reduction with no anti-alias filter, 12-bit, the output
+// filter, a gain push, pads pitched down and choked on retrigger) -> TAPE (random band-limited wow
+// shared by both channels, flutter that differs L/R, head bump, HF loss, saturation with a
+// hysteresis loop, hiss) -> VINYL (Poisson crackle with power-law sizes, pops that ring, a scratch
+// that ticks once per turn, surface noise swelling with the rotation, rumble, the 33 1/3 wobble)
+// -> BUS (the kick pump, a low-pass tilt, a quiet room tone).
+// Keys get their own warbly cassette (their own wow, a two-tap chorus, a slow stereo tremolo), drums
+// a dusty bus (mono-ish like a sampled break, saturated, a short small room).
+// Everything is a pure function of (audio, sr, options, seed): the same piece renders the same bytes.
+// Legacy: pieces with `legacy: true` (the shipped launch films) never reach this file (render.ts).
+import { TAU, Biquad, onePoleCoef, clamp, db } from "./dsp";
+import { rng as mkRng } from "../core";
+import type { Played } from "./perform";
+import { smallRoom } from "./roomSmall";
+
+type Buf = Float32Array;
+type R = () => number;
+
+export type TapeFx = {
+ /** wow: peak pitch drift in cents (random, 0.3-1.5 Hz band); wowHz = the band's centre */ wowCents?: number; wowHz?: number;
+ /** flutter: peak cents in the 6-12 Hz band (L and R differ a little) */ flutterCents?: number; flutterHz?: number;
+ /** saturation drive (1 = clean) */ drive?: number;
+ /** head bump: dB at bumpHz (60-90 Hz) */ bumpDb?: number; bumpHz?: number;
+ /** HF loss: the tape's 1-pole corner (Hz) plus a -2 dB shelf at 6 kHz; omit for no loss */ hfHz?: number;
+ /** hiss level in dB under the program (e.g. -44) */ hissDb?: number;
+ /** hysteresis width 0..1 (the magnetic loop: memory in the saturation) */ hyst?: number;
+ /** a loop's length in s: every modulation completes whole cycles in it (renderLoop sets it) */ period?: number;
+};
+export type VinylFx = {
+ /** crackle clicks per second (5-40) */ crackle?: number; /** pops per second (0.2-1) */ pops?: number;
+ /** surface noise and rumble, dB under the program */ surfaceDb?: number; rumbleDb?: number;
+ /** scratches: clicks that repeat once per turn */ scratches?: number; /** 33 1/3 rpm wobble, cents */ wobbleCents?: number;
+ /** overall crackle level, dB under the program's peak */ crackleDb?: number;
+};
+export type SamplerFx = {
+ /** the sampler's rate in Hz (SP-1200 26040, MPC60 40000) with NO anti-alias filter */ rate?: number;
+ bits?: number; /** output filter corner (SSM2044-ish 4-pole) */ lp?: number;
+ /** the gain push into the converter's soft clip (1 = none) */ drive?: number;
+ /** pads sampled fast and played back pitched down, in semitones (e.g. -2); each retrigger chokes the last */ pitch?: number;
+ /** how far under full scale the sample was recorded (a quiet sample is grittier), dB */ headroomDb?: number;
+};
+export type LofiFx = {
+ drums?: { parts: string[]; sampler?: SamplerFx; /** stereo width 0 (mono break) .. 1 */ width?: number; sat?: number; room?: number };
+ keys?: { parts: string[]; warbleCents?: number; chorus?: number; tremolo?: number; lp?: number; sampler?: SamplerFx };
+ tape?: TapeFx; vinyl?: VinylFx;
+ /** master low-pass (Hz, 12 dB/oct) and the tilt (dB of high-shelf cut) */ tilt?: { lp?: number; tiltDb?: number };
+ /** room tone (the air of the room the record plays in), dB under the program */ roomToneDb?: number;
+};
+
+// ------------------------------------------------------------------------------------ helpers
+const clone = (x: Buf) => Float32Array.from(x);
+const rms = (L: Buf, R: Buf) => { let s = 0, c = 0; for (let i = 0; i < L.length; i++) { const e = L[i] * L[i] + R[i] * R[i]; if (e > 1e-10) { s += e; c++; } } return Math.sqrt(s / Math.max(1, c * 2)); };
+const peak = (...cs: Buf[]) => { let p = 0; for (const c of cs) for (let i = 0; i < c.length; i++) { const a = Math.abs(c[i]); if (a > p) p = a; } return p; };
+const run = (c: Buf, ...fs: Biquad[]) => { for (let i = 0; i < c.length; i++) { let v = c[i]; for (const f of fs) v = f.tick(v); c[i] = v; } };
+/** Pink noise (Paul Kellet), roughly unit RMS. */
+const pinkInto = (o: Float32Array, r: R, g: number) => {
+ let b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0;
+ for (let i = 0; i < o.length; i++) {
+ const w = r() * 2 - 1;
+ b0 = 0.99886 * b0 + w * 0.0555179; b1 = 0.99332 * b1 + w * 0.0750759; b2 = 0.969 * b2 + w * 0.153852; b3 = 0.8665 * b3 + w * 0.3104856; b4 = 0.55 * b4 + w * 0.5329522; b5 = -0.7616 * b5 - w * 0.016898;
+ o[i] += (b0 + b1 + b2 + b3 + b4 + b5 + b6 + w * 0.5362) * 0.11 * g * 2.6; b6 = w * 0.115926;
+ }
+ return o;
+};
+
+/**
+ * A random, band-limited control signal (unit RMS): many sinusoids at random frequencies inside
+ * [lo, hi] Hz, 1/sqrt(f) weights, Rayleigh amplitudes, random phases. That is filtered noise by
+ * spectral synthesis: it never repeats like an LFO, and with `period` every component snaps to a
+ * whole number of cycles, so a loop's modulation meets itself at the seam. Sampled every 32 samples.
+ */
+export const wander = (n: number, sr: number, lo: number, hi: number, r: R, comps = 14, period?: number) => {
+ const step = 32, m = Math.ceil(n / step) + 2, out = new Float32Array(m);
+ const f: number[] = [], a: number[] = [], ph: number[] = [];
+ for (let k = 0; k < comps; k++) {
+ let fk = lo * Math.pow(hi / lo, (k + r()) / comps);
+ if (period) fk = Math.max(1, Math.round(fk * period)) / period;
+ f.push(fk); a.push(Math.sqrt(-2 * Math.log(Math.max(1e-9, r()))) / Math.sqrt(fk)); ph.push(r() * TAU);
+ }
+ const norm = Math.sqrt(a.reduce((s, x) => s + x * x, 0) / 2);
+ for (let j = 0; j < m; j++) { const t = (j * step) / sr; let s = 0; for (let k = 0; k < comps; k++) s += a[k] * Math.sin(TAU * f[k] * t + ph[k]); out[j] = s / norm; }
+ return (i: number) => { const x = i / step, j = Math.floor(x), fr = x - j; return out[j] + (out[j + 1] - out[j]) * fr; };
+};
+
+/** Read `src` at fractional positions: 4-point cubic Hermite (no zipper, little HF loss). */
+const hermite = (src: Buf, x: number) => {
+ const j = Math.floor(x), f = x - j, n = src.length, g = (k: number) => (k >= 0 && k < n ? src[k] : 0);
+ const y0 = g(j - 1), y1 = g(j), y2 = g(j + 1), y3 = g(j + 2), c1 = 0.5 * (y2 - y0), c2 = y0 - 2.5 * y1 + 2 * y2 - 0.5 * y3, c3 = 0.5 * (y3 - y0) + 1.5 * (y1 - y2);
+ return ((c3 * f + c2) * f + c1) * f + y1;
+};
+
+/** Pitch-modulate a stereo pair by a cents trajectory per channel: the read head's delay is the integral
+ * of (1 - ratio). ONE constant offset for both channels (every read >= 3 samples behind the write), so
+ * the channels never slip apart by a fixed delay (that would comb the highs when summed to mono). */
+const pitchMod2 = (L: Buf, R: Buf, cL: (i: number) => number, cR: (i: number) => number) => {
+ const n = L.length, dL = new Float64Array(n), dR = new Float64Array(n); let aL = 0, aR = 0, mn = 0;
+ for (let i = 0; i < n; i++) { aL += 1 - Math.pow(2, cL(i) / 1200); aR += 1 - Math.pow(2, cR(i) / 1200); dL[i] = aL; dR[i] = aR; mn = Math.min(mn, aL, aR); }
+ const off = 3 - mn;
+ for (const [c, d] of [[L, dL], [R, dR]] as const) { const src = clone(c); for (let i = 0; i < n; i++) c[i] = hermite(src, i - (d[i] + off)); }
+};
+
+// ------------------------------------------------------------------------------------ tape
+/**
+ * The magnetic stage at 2x oversampling. A play operator (the classic building block of a
+ * Preisach hysteresis model: the state follows the input only once it moves more than `w` away)
+ * gives the loop its memory, a small bias makes the curve asymmetric (even harmonics), tanh the
+ * saturation. The signal is normalised to a reference peak first so `drive` means the same at any
+ * level, then put back; a 10 Hz DC blocker removes what the bias leaves.
+ */
+const magnetic = (c: Buf, sr: number, drive: number, hyst: number) => {
+ if (drive <= 1.0001 && hyst <= 0) return;
+ const pk = peak(c); if (pk < 1e-9) return;
+ const ref = 0.5 / pk, n = c.length, w = 0.04 * hyst, bias = 0.06 * (drive - 1 + hyst * 0.5), m = 0.35 * Math.min(1, hyst * 2), off = Math.tanh(drive * bias);
+ const up1 = Biquad.make(sr * 2, "lp", sr * 0.45, 0.5412), up2 = Biquad.make(sr * 2, "lp", sr * 0.45, 1.3066), dn1 = Biquad.make(sr * 2, "lp", sr * 0.45, 0.5412), dn2 = Biquad.make(sr * 2, "lp", sr * 0.45, 1.3066);
+ let p = 0; const dc = onePoleCoef(sr, 10); let z = 0;
+ const sat = (x: number) => { p = clamp(p, x - w, x + w); const u = (1 - m) * x + m * p; return (Math.tanh(drive * (u + bias)) - off) / drive; };
+ for (let i = 0; i < n; i++) {
+ const x = c[i] * ref, a = up2.tick(up1.tick(x * 2)), b = up2.tick(up1.tick(0)); // zero-stuff, image filter (gain 2 restores level)
+ dn2.tick(dn1.tick(sat(a))); const y = dn2.tick(dn1.tick(sat(b)));
+ z += dc * (y - z); c[i] = (y - z) / ref;
+ }
+};
+
+/** Tape: wow + flutter (modulated read), head bump, HF loss, magnetic saturation, hiss. In place. */
+export const tape2 = (L: Buf, R: Buf, sr: number, o: TapeFx & { wobble?: { cents: number; hz: number } }, seed: number) => {
+ const n = L.length, r = mkRng((seed ^ 0x7a9e) >>> 0);
+ const wc = o.wowCents ?? 5, wf = o.wowHz ?? 0.7, fc = o.flutterCents ?? 1, ff = o.flutterHz ?? 8;
+ // wow: one transport, both channels (0.43x..2.1x the centre: ~0.3-1.5 Hz at 0.7); flutter: 70 % shared, 30 % per channel
+ const wow = wander(n, sr, wf * 0.43, wf * 2.1, r, 14, o.period), fl = wander(n, sr, ff * 0.75, ff * 1.5, r, 10, o.period);
+ const flL = wander(n, sr, ff * 0.75, ff * 1.5, r, 6, o.period), flR = wander(n, sr, ff * 0.75, ff * 1.5, r, 6, o.period), skew = wander(n, sr, 0.1, 0.5, r, 6, o.period);
+ const wb = o.wobble, wbPh = r() * TAU, wbHz = wb ? (o.period ? Math.max(1, Math.round(wb.hz * o.period)) / o.period : wb.hz) : 0;
+ const cents = (side: number) => (i: number) => {
+ const t = i / sr;
+ return (wc / 2.8) * (wow(i) + 0.012 * skew(i) * side) + (fc / 2.2) * (0.84 * fl(i) + 0.55 * (side > 0 ? flR(i) : flL(i))) + (wb ? wb.cents * Math.sin(TAU * wbHz * t + wbPh) : 0);
+ };
+ if (wc > 0 || fc > 0 || wb) pitchMod2(L, R, cents(-1), cents(1));
+ for (const c of [L, R]) {
+ const fs: Biquad[] = [];
+ if (o.bumpDb) fs.push(Biquad.make(sr, "peak", o.bumpHz ?? 75, 0.9, o.bumpDb), Biquad.make(sr, "peak", (o.bumpHz ?? 75) * 2.3, 1.2, -o.bumpDb * 0.35));
+ if (o.hfHz) fs.push(Biquad.make(sr, "highshelf", 6000, 0.7, -2));
+ if (fs.length) run(c, ...fs);
+ if (o.hfHz) { const k = onePoleCoef(sr, o.hfHz); let z = 0; for (let i = 0; i < n; i++) { z += k * (c[i] - z); c[i] = z; } }
+ magnetic(c, sr, o.drive ?? 1.2, o.hyst ?? 0);
+ }
+ if (o.hissDb !== undefined) {
+ const g = rms(L, R) * db(o.hissDb), common = pinkInto(new Float32Array(n), r, 1), hL = pinkInto(new Float32Array(n), r, 1), hR = pinkInto(new Float32Array(n), r, 1);
+ for (const [h, c] of [[hL, L], [hR, R]] as const) {
+ for (let i = 0; i < n; i++) h[i] = 0.35 * common[i] + 0.94 * h[i];
+ run(h, Biquad.make(sr, "hp", 1000, 0.6), Biquad.make(sr, "lp", 12000, 0.6));
+ for (let i = 0; i < n; i++) c[i] += h[i] * g;
+ }
+ }
+};
+
+// ------------------------------------------------------------------------------------ vinyl
+/**
+ * The record: crackle (Poisson arrivals, Pareto sizes: a few loud ticks over many faint ones, each a
+ * 0.1-1 ms burst high-passed at 1 kHz, mostly in one groove wall so L and R differ), pops (rarer,
+ * bigger, ringing through a resonant low-pass), scratches (one tick per turn at a fixed angle, for a
+ * stretch of turns), surface noise swelling with the rotation, and rumble (below 40 Hz, mostly
+ * vertical = anti-phase). Adds into L, R.
+ */
+export const vinyl2 = (L: Buf, R: Buf, sr: number, o: VinylFx, seed: number) => {
+ const n = L.length, r = mkRng((seed ^ 0x51f3) >>> 0), turn = 60 / (100 / 3), prog = rms(L, R), pk = Math.max(peak(L, R), 1e-6);
+ const cL = new Float32Array(n), cR = new Float32Array(n);
+ const click = (at: number, amp: number, lenS: number, side: number) => {
+ const len = Math.max(2, Math.round(lenS * sr)), sgn = r() < 0.5 ? -1 : 1, gL = side < 0 ? 1 : 0.25 + 0.5 * r(), gR = side > 0 ? 1 : 0.25 + 0.5 * r();
+ for (let k = 0; k < len && at + k < n; k++) { const v = sgn * amp * Math.exp(-k / (len / 3)) * (k === 0 ? 1 : (r() * 2 - 1)); cL[at + k] += v * gL; cR[at + k] += v * gR; }
+ };
+ const a0 = pk * db(o.crackleDb ?? -34);
+ // crackle
+ for (let t = 0, rate = o.crackle ?? 14; rate > 0;) { t += -Math.log(Math.max(1e-9, r())) / rate; if (t >= n / sr) break; click(Math.round(t * sr), Math.min(a0 * Math.pow(Math.max(1e-3, r()), -1 / 2.3), a0 * 25) * 0.4, 0.0001 + 0.0009 * r() * r(), r() < 0.5 ? -1 : 1); }
+ run(cL, Biquad.make(sr, "hp", 1000, 0.7)); run(cR, Biquad.make(sr, "hp", 1000, 0.7));
+ // scratches: a tick at the same angle every turn, for a stretch of the record
+ for (let s = 0; s < (o.scratches ?? 1); s++) {
+ const ph = r() * turn, amp = a0 * (1.5 + 2 * r()), from = r() * 0.5, span = 0.3 + 0.5 * r(), side = r() < 0.5 ? -1 : 1;
+ for (let t = ph; t < n / sr; t += turn) { const u = t / (n / sr); if (u >= from && u <= from + span && r() < 0.85) click(Math.round(t * sr), amp * (0.6 + 0.4 * r()), 0.0004, side); }
+ }
+ // pops: bigger, with a ringing low-passed body
+ const popL = new Float32Array(n), popR = new Float32Array(n);
+ for (let t = 0, rate = o.pops ?? 0.4; rate > 0;) {
+ t += -Math.log(Math.max(1e-9, r())) / rate; if (t >= n / sr) break;
+ const at = Math.round(t * sr), f = 500 + 1400 * r(), tau = 0.0015 + 0.003 * r(), amp = a0 * (2 + 4 * r()), sgn = r() < 0.5 ? -1 : 1, bal = r() * 0.6 - 0.3;
+ for (let k = 0; k < tau * 6 * sr && at + k < n; k++) { const v = sgn * amp * Math.exp(-k / (tau * sr)) * Math.cos((TAU * f * k) / sr); popL[at + k] += v * (1 - bal); popR[at + k] += v * (1 + bal); }
+ }
+ run(popL, Biquad.make(sr, "lp", 3500, 1.4), Biquad.make(sr, "hp", 120, 0.7)); run(popR, Biquad.make(sr, "lp", 3500, 1.4), Biquad.make(sr, "hp", 120, 0.7));
+ // surface: band-passed pink noise that swells with the rotation (the groove wall is not uniform)
+ const sfL = pinkInto(new Float32Array(n), r, 1), sfR = pinkInto(new Float32Array(n), r, 1), sp = r() * TAU, sg = prog * db(o.surfaceDb ?? -46);
+ run(sfL, Biquad.make(sr, "hp", 400, 0.6), Biquad.make(sr, "lp", 5500, 0.6)); run(sfR, Biquad.make(sr, "hp", 400, 0.6), Biquad.make(sr, "lp", 5500, 0.6));
+ // rumble: < 40 Hz, mostly vertical groove motion = anti-phase
+ const ru = new Float32Array(n), rg = prog * db(o.rumbleDb ?? -44); { let z1 = 0, z2 = 0; const k = onePoleCoef(sr, 28); for (let i = 0; i < n; i++) { z1 += k * ((r() * 2 - 1) - z1); z2 += k * (z1 - z2); ru[i] = z2 * 9; } }
+ run(ru, Biquad.make(sr, "hp", 12, 0.7));
+ for (let i = 0; i < n; i++) {
+ const rot = 1 + 0.35 * Math.sin((TAU * i) / (turn * sr) + sp) + 0.15 * Math.sin((2 * TAU * i) / (turn * sr) + sp * 1.7);
+ L[i] += cL[i] + popL[i] + sfL[i] * sg * rot + ru[i] * rg; R[i] += cR[i] + popR[i] + sfR[i] * sg * rot - ru[i] * rg * 0.7;
+ }
+};
+
+// ------------------------------------------------------------------------------------ sampler
+/**
+ * SP-1200 / MPC emulation on one stem, in place. Optional chops: every onset retriggers the pad
+ * pitched down (read slower), choking the previous one after a 1.5 ms crossfade. Then the
+ * converter: sample-and-hold at `rate` with no anti-alias filter (highs fold back: the grit), a
+ * 12-bit quantiser with plain rounding against the stem's own peak (recorded `headroomDb` under
+ * full scale), the output filter (two 2-pole sections), and the gain push into a soft clip.
+ */
+export const sampler = (c: Buf, sr: number, o: SamplerFx, onsets: number[] = []) => {
+ const n = c.length, pk = peak(c); if (pk < 1e-9) return;
+ if (o.pitch && onsets.length) {
+ const ratio = Math.pow(2, o.pitch / 12), src = clone(c), xf = Math.max(1, Math.round(0.0015 * sr)), on = [...new Set(onsets.map((t) => Math.round(t * sr)))].filter((i) => i >= 0 && i < n).sort((a, b) => a - b);
+ for (let k = 0; k < on.length; k++) {
+ const a = on[k], b = k + 1 < on.length ? on[k + 1] : n, pa = k > 0 ? on[k - 1] : -1;
+ const at = (st: number, i: number) => { const x = st + (i - st) * ratio, j = Math.floor(x), f = x - j, y0 = j < n ? src[j] : 0, y1 = j + 1 < n ? src[j + 1] : 0; return y0 + (y1 - y0) * f; }; // linear: the MPC's interpolation
+ for (let i = a; i < b; i++) { const v = at(a, i); c[i] = pa >= 0 && i - a < xf ? v * ((i - a) / xf) + at(pa, i) * (1 - (i - a) / xf) : v; }
+ }
+ }
+ const rate = o.rate ?? 26040, q = Math.pow(2, (o.bits ?? 12) - 1), full = pk * db(o.headroomDb ?? 6), drive = o.drive ?? 1.6;
+ let ph = 1, hold = 0;
+ for (let i = 0; i < n; i++) {
+ ph += rate / sr; if (ph >= 1) { ph -= 1; hold = Math.round((c[i] / full) * q) / q; }
+ c[i] = hold;
+ }
+ run(c, Biquad.make(sr, "lp", o.lp ?? 12000, 0.5412), Biquad.make(sr, "lp", o.lp ?? 12000, 1.3066));
+ const k = Math.tanh(drive * 0.7);
+ for (let i = 0; i < n; i++) c[i] = (Math.tanh(drive * c[i] * 0.7) / k) * full * 0.7;
+};
+
+// ------------------------------------------------------------------------------------ pump
+/**
+ * The kick pump as a sidechain compressor would draw it: per kick, gain falls by `depth` (scaled by
+ * the kick's velocity) over a 5 ms raised-cosine attack, holds 15 ms, and breathes back over
+ * `release` (default 60 % of a beat, synced to the tempo) along a squared curve; overlapping kicks
+ * take the deeper dip, and a 3 ms smoother rounds the corners.
+ */
+export const pumpCurve = (kicks: Played[], tempo: number, sr: number, n: number, depth = 0.4, release?: number): Float32Array => {
+ const g = new Float32Array(n).fill(1), rel = Math.max(release ?? 0, 0.6 * (60 / tempo)), att = 0.005, hold = 0.015;
+ for (const k of kicks) {
+ const i0 = Math.round(k.t * sr), dd = depth * Math.pow(clamp(k.v / 0.85, 0.3, 1.2), 0.7), len = Math.min(n - i0, Math.ceil((att + hold + rel) * sr));
+ for (let i = Math.max(0, -i0); i < len; i++) {
+ const s = i / sr, a = s < att ? 0.5 - 0.5 * Math.cos((Math.PI * s) / att) : s < att + hold ? 1 : Math.pow(1 - (s - att - hold) / rel, 2);
+ const v = 1 - clamp(dd, 0, 0.95) * a; if (v < g[i0 + i]) g[i0 + i] = v;
+ }
+ }
+ const k = onePoleCoef(sr, 1 / (TAU * 0.003)); let z = 1; for (let i = 0; i < n; i++) { z += k * (g[i] - z); g[i] = z; }
+ return g;
+};
+
+// ------------------------------------------------------------------------------------ buses
+/** Dusty drums, one lane at a time (like pads on a sampler): chops + converter, bus saturation, a
+ * low-mid box, the break's narrow stereo, and a short small room. In place. */
+export const dustyDrums = (L: Buf, R: Buf, sr: number, o: NonNullable<LofiFx["drums"]>, onsets: number[], seed: number) => {
+ const n = L.length, w = o.width ?? 0.35;
+ for (let i = 0; i < n; i++) { const m = (L[i] + R[i]) * 0.5, s = (L[i] - R[i]) * 0.5 * w; L[i] = m + s; R[i] = m - s; }
+ if (o.sampler) { sampler(L, sr, o.sampler, onsets); sampler(R, sr, o.sampler, onsets); }
+ for (const c of [L, R]) run(c, Biquad.make(sr, "hp", 38, 0.7), Biquad.make(sr, "peak", 190, 0.8, 1.5), Biquad.make(sr, "peak", 3200, 0.9, -1.5), Biquad.make(sr, "lp", 11000, 0.6));
+ const sat = o.sat ?? 1.4, pk = peak(L, R);
+ if (sat > 1 && pk > 1e-9) { const ref = 0.6 / pk, k = Math.tanh(sat * 0.6); for (const c of [L, R]) for (let i = 0; i < n; i++) c[i] = ((Math.tanh(sat * c[i] * ref) / k) * 0.6) / ref; }
+ if (o.room) { const [wL, wR] = smallRoom(L, R, sr, { rt60: 0.35, size: 0.55, er: 0.9, late: 0.35, hp: 180, lp: 6500, predelay: 0.003, damp: 4200, seed }); for (let i = 0; i < n; i++) { L[i] += wL[i] * o.room; R[i] += wR[i] * o.room; } }
+};
+
+/** The keys' own cassette: a slow random warble (its own wow), a two-tap chorus with random drift
+ * (L and R taps differ), a slow stereo tremolo, a darker top, and optionally the sampler. The
+ * warble is seeded by the piece, so every keys part shares one "tape": per part == on the bus. */
+export const warblyKeys = (L: Buf, R: Buf, sr: number, o: NonNullable<LofiFx["keys"]>, seed: number, period?: number) => {
+ const n = L.length, r = mkRng((seed ^ 0x3c6e) >>> 0), wc = o.warbleCents ?? 7;
+ const wow = wander(n, sr, 0.18, 1.1, r, 12, period), cents = (i: number) => (wc / 2.2) * wow(i);
+ pitchMod2(L, R, cents, cents);
+ const ch = o.chorus ?? 0.3;
+ if (ch > 0) {
+ const mL = wander(n, sr, 0.25, 0.9, r, 6, period), mR = wander(n, sr, 0.25, 0.9, r, 6, period), sL = clone(L), sR = clone(R), mono = new Float32Array(n);
+ for (let i = 0; i < n; i++) mono[i] = (sL[i] + sR[i]) * 0.5;
+ for (let i = 0; i < n; i++) {
+ const dL = (0.0085 + 0.0016 * mL(i)) * sr, dR = (0.0115 + 0.0016 * mR(i)) * sr;
+ L[i] = sL[i] * (1 - ch * 0.4) + hermite(mono, i - dL) * ch; R[i] = sR[i] * (1 - ch * 0.4) + hermite(mono, i - dR) * ch;
+ }
+ }
+ const tr = o.tremolo ?? 0.1, th = period ? Math.max(1, Math.round(3.6 * period)) / period : 3.6, tp = r() * TAU;
+ if (tr > 0) for (let i = 0; i < n; i++) { const t = (TAU * th * i) / sr + tp; L[i] *= 1 - tr * (0.5 + 0.5 * Math.sin(t)); R[i] *= 1 - tr * (0.5 + 0.5 * Math.sin(t + Math.PI / 2)); }
+ for (const c of [L, R]) run(c, Biquad.make(sr, "lp", o.lp ?? 7000, 0.6));
+ if (o.sampler) { sampler(L, sr, o.sampler); sampler(R, sr, o.sampler); }
+};
+
+// ------------------------------------------------------------------------------------ entry points (render.ts)
+/** The dusty profile the lo-fi vocabulary uses (and any lofi-style piece without its own). */
+export const LOFI_DUSTY: LofiFx = {
+ drums: { parts: ["kick", "snare", "ghost", "hat", "perc"], sampler: { rate: 26040, bits: 12, lp: 11000, drive: 1.7, pitch: -2, headroomDb: 9 }, width: 0.3, sat: 1.5, room: 0.28 },
+ keys: { parts: ["chords", "lead", "counter", "arp"], warbleCents: 8, chorus: 0.32, tremolo: 0.1, lp: 8000 },
+ tape: { bumpDb: 2, bumpHz: 72, hfHz: 12000, hissDb: -42, hyst: 0.5 },
+ vinyl: { crackle: 16, pops: 0.35, surfaceDb: -44, rumbleDb: -46, scratches: 1, wobbleCents: 2, crackleDb: -30 },
+ tilt: { lp: 11500, tiltDb: -1.5 },
+ roomToneDb: -50,
+};
+
+/** Per stem, before the pump and the mix: the part's bus treatment, if the profile names it. */
+export const lofiStem = (fx: LofiFx, partId: string, L: Buf, R: Buf, sr: number, onsets: number[], seed: number, period?: number) => {
+ if (fx.drums?.parts.includes(partId)) dustyDrums(L, R, sr, fx.drums, onsets, seed + partId.length);
+ else if (fx.keys?.parts.includes(partId)) warblyKeys(L, R, sr, fx.keys, seed, period);
+};
+
+/** The master side, in place, after the room: tape (with the record's wobble riding the same
+ * transport), vinyl, room tone, then the low-pass tilt. `dusty` = the lo-fi colour is on. */
+export const lofiMaster = (L: Buf, R: Buf, sr: number, tapeFx: TapeFx | undefined, fx: LofiFx | undefined, seed: number) => {
+ const vy = fx?.vinyl, tp = { ...(fx?.tape ?? {}), ...(tapeFx ?? {}) };
+ if (tapeFx || fx) tape2(L, R, sr, { ...tp, wobble: vy?.wobbleCents ? { cents: vy.wobbleCents, hz: 100 / 3 / 60 } : undefined }, seed);
+ if (vy) vinyl2(L, R, sr, vy, seed);
+ if (fx?.roomToneDb !== undefined) {
+ const n = L.length, r = mkRng((seed ^ 0x2b1d) >>> 0), g = rms(L, R) * db(fx.roomToneDb), a = pinkInto(new Float32Array(n), r, 1), b = pinkInto(new Float32Array(n), r, 1);
+ for (const h of [a, b]) run(h, Biquad.make(sr, "hp", 70, 0.6), Biquad.make(sr, "lp", 2400, 0.5), Biquad.make(sr, "peak", 180, 1.2, 4));
+ const fade = Math.min(n, Math.round(0.5 * sr)); for (let i = 0; i < n; i++) { const e = Math.min(1, i / fade); L[i] += a[i] * g * e; R[i] += (0.6 * b[i] + 0.4 * a[i]) * g * e; }
+ }
+ if (fx?.tilt) for (const c of [L, R]) {
+ const fs = [Biquad.make(sr, "highshelf", 2200, 0.6, fx.tilt.tiltDb ?? -2), Biquad.make(sr, "lowshelf", 250, 0.7, 1)];
+ if (fx.tilt.lp) fs.push(Biquad.make(sr, "lp", fx.tilt.lp, 0.6));
+ run(c, ...fs);
+ }
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/meter.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/meter.ts
index 9581955..5dfed0a 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/meter.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/meter.ts
@@ -104,8 +104,26 @@ export const measure = (chans: Float32Array[], sr: number): Meters => {
return { durationS: dur, lufs: l.integrated, lra: l.lra, shortMax: l.shortMax, dbtp: tp.dbtp, samplePeakDb: tp.samplePeakDb, onsetsPerS: on.length / dur, onsetCount: on.length, centroidHz: c.mean, centroidEnergyHz: c.energyWeighted, lastOnsetS: on.length ? on[on.length - 1] : 0, shortTerm: l.shortTerm };
};
-/** RMS of a stem over its active samples (|x| > 1e-4), left channel, dBFS: the level a part plays at when it plays. */
-export const stemRms = (x: Float32Array, floor = 1e-4) => { let s = 0, c = 0; for (let i = 0; i < x.length; i++) { const v = x[i]; if (Math.abs(v) > floor) { s += v * v; c++; } } return c ? 10 * Math.log10(s / c + 1e-12) : -Infinity; };
+/**
+ * The level a part plays at when it plays, dBFS: the RMS of its MID ((L + R) / 2, after its pan: what a phone's one
+ * speaker plays, and a centred mono part reads exactly its own level), high-passed at 30 Hz, over the 20 ms blocks where it
+ * is really playing.
+ * Gated like BS.1770 loudness: blocks under -70 dBFS never count, then blocks more than 20 dB under the part's own
+ * level drop out, so a reverb tail, a pedal ring or a noise floor does not dilute it. (v1 read the LEFT channel only,
+ * sample by sample above a -80 dB floor: a hat panned right read low, a ride panned left read high, and every long
+ * tail pulled a part down; the targets were converted at the sound-v2 merge on the renders they were set on.)
+ */
+export const stemRms = (L: Float32Array, R: Float32Array = L, sr = 48000) => {
+ const B = Math.max(1, Math.round(0.02 * sr)), n = Math.min(L.length, R.length), pw: number[] = [];
+ // audible band only (a 30 Hz high-pass, like loudness's RLB stage): a voice's DC or subsonic drift is not level (a harp's DC offset swung it 4.8 dB)
+ const w = Math.tan(Math.PI * Math.min(30, 0.45 * sr) / sr), k = 1 / (1 + Math.SQRT2 * w + w * w), b0 = k, a1 = 2 * (w * w - 1) * k, a2 = (1 - Math.SQRT2 * w + w * w) * k;
+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
+ const mid = new Float64Array(n); for (let i = 0; i < n; i++) { const x = (L[i] + R[i]) * 0.5, y = b0 * (x - 2 * x1 + x2) - a1 * y1 - a2 * y2; x2 = x1; x1 = x; y2 = y1; y1 = y; mid[i] = y; }
+ for (let a = 0; a < n; a += B) { const e = Math.min(n, a + B); let s = 0; for (let i = a; i < e; i++) s += mid[i] * mid[i]; pw.push(s / (e - a)); }
+ const abs = pw.filter((p) => p > 1e-7); if (!abs.length) return -Infinity;
+ const rel = (abs.reduce((a, p) => a + p, 0) / abs.length) * 0.01, gated = abs.filter((p) => p >= rel);
+ return 10 * Math.log10(gated.reduce((a, p) => a + p, 0) / gated.length);
+};
export type StemRow = { id: string; rmsDb: number; targetDb: number | null; offDb: number | null; ok: boolean };
/**
* Stem balance: each part's active RMS against its target; a part more than `tolDb` off is flagged.
@@ -114,7 +132,7 @@ export type StemRow = { id: string; rmsDb: number; targetDb: number | null; offD
*/
/** Guards win over stem targets: the melody must clear the masking guard, so the lead may sit up to `LEAD_HEADROOM_DB` above its target before it is flagged. */
export const LEAD_HEADROOM_DB = 3;
-export const stemBalance = (stems: Record<string, [Float32Array, Float32Array]>, targets: Record<string, number>, tolDb = 3, headroom: Record<string, number> = { lead: LEAD_HEADROOM_DB }) => {
- const rows: StemRow[] = Object.entries(stems).map(([id, [L]]) => { const rmsDb = stemRms(L), t = targets[id] ?? null, off = t === null ? null : rmsDb - t; return { id, rmsDb, targetDb: t, offDb: off, ok: off === null || (off >= -tolDb && off <= tolDb + (headroom[id] ?? 0)) }; });
+export const stemBalance = (stems: Record<string, [Float32Array, Float32Array]>, targets: Record<string, number>, tolDb = 3, headroom: Record<string, number> = { lead: LEAD_HEADROOM_DB }, sr = 48000) => {
+ const rows: StemRow[] = Object.entries(stems).map(([id, [L, R]]) => { const rmsDb = stemRms(L, R, sr), t = targets[id] ?? null, off = t === null ? null : rmsDb - t; return { id, rmsDb, targetDb: t, offDb: off, ok: off === null || (off >= -tolDb && off <= tolDb + (headroom[id] ?? 0)) }; });
return { rows, pass: rows.every((r) => r.ok), tolDb, headroom };
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixDsp.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixDsp.ts
new file mode 100644
index 0000000..9f051ac
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixDsp.ts
@@ -0,0 +1,195 @@
+// Mix-chain building blocks (sound v2). Pure functions over whole float buffers, deterministic,
+// no rng. Written from the textbook forms: RBJ cookbook EQ (dsp.ts), feed-forward soft-knee
+// compressor (Giannoulis, Massberg and Reiss, JAES 2012), halfband 2x oversampling, Linkwitz-Riley
+// crossovers, the Web Audio "StereoPannerNode" equal-power law for stereo sources, and a
+// hold + box-filter look-ahead limiter (the Signalsmith "smooth limiter" construction).
+import { Biquad, db } from "./dsp";
+
+const lin2db = (x: number) => 20 * Math.log10(Math.max(x, 1e-12));
+
+// ---------------------------------------------------------------- EQ
+/** A stem's EQ: 12 dB/oct high-pass and low-pass, a tilt around 1 kHz (dB from the low end to the high end), bells [f, q, dB]. */
+export type StemEq = { hp?: number; lp?: number; tilt?: number; bells?: [number, number, number][]; air?: number };
+export const eqChain = (sr: number, e: StemEq): Biquad[] => {
+ const fs: Biquad[] = [], ny = sr * 0.45;
+ if (e.hp && e.hp > 10) fs.push(Biquad.make(sr, "hp", e.hp, 0.7071));
+ if (e.tilt) { fs.push(Biquad.make(sr, "lowshelf", 1000, 0.5, -e.tilt / 2)); fs.push(Biquad.make(sr, "highshelf", 1000, 0.5, e.tilt / 2)); }
+ for (const [f, q, g] of e.bells ?? []) if (f < ny && g) fs.push(Biquad.make(sr, "peak", f, q, g));
+ if (e.air && 10000 < ny) fs.push(Biquad.make(sr, "highshelf", 10000, 0.7, e.air));
+ if (e.lp && e.lp < ny) fs.push(Biquad.make(sr, "lp", e.lp, 0.7071));
+ return fs;
+};
+export const runEq = (buf: Float32Array, fs: Biquad[]) => { for (const f of fs) f.run(buf); return buf; };
+
+// ---------------------------------------------------------------- pan
+/** True stereo pan (Web Audio StereoPanner, equal power): pan 0 is the identity; a panned stereo source keeps its power. */
+export const stereoPan = (L: Float32Array, R: Float32Array, p: number) => {
+ if (!p) return;
+ const q = Math.max(-1, Math.min(1, p)), x = q <= 0 ? q + 1 : q, gl = Math.cos((x * Math.PI) / 2), gr = Math.sin((x * Math.PI) / 2);
+ for (let i = 0; i < L.length; i++) {
+ const l = L[i], r = R[i];
+ if (q <= 0) { L[i] = l + r * gl; R[i] = r * gr; } else { L[i] = l * gl; R[i] = r + l * gr; }
+ }
+};
+
+// ---------------------------------------------------------------- oversampled saturation
+/** Halfband FIR (odd taps only + centre 0.5), 2x up/down. Kaiser-ish window, ~80 dB image rejection above 0.6 Nyquist. */
+const HB = (() => { const M = 15, h: number[] = []; for (let k = 1; k <= M; k += 2) { const w = 0.42 + 0.5 * Math.cos((Math.PI * k) / (M + 1)) + 0.08 * Math.cos((2 * Math.PI * k) / (M + 1)); h.push((0.5 * Math.sin((Math.PI * k) / 2)) / ((Math.PI * k) / 2) * w); } return h; })(); // h[j] is the tap at k = 2j+1 (and -k)
+/** Run `f` on a 2x-oversampled copy of x (in place). */
+export const oversample2 = (x: Float32Array, f: (v: number) => number) => {
+ const n = x.length, H = HB.length, up = new Float64Array(2 * n);
+ for (let i = 0; i < n; i++) {
+ up[2 * i] = f(x[i]);
+ let s = 0; for (let j = 0; j < H; j++) { const k = 2 * j + 1, a = i + ((1 - k) >> 1), b = i + ((1 + k) >> 1); s += HB[j] * ((a >= 0 && a < n ? x[a] : 0) + (b >= 0 && b < n ? x[b] : 0)); }
+ up[2 * i + 1] = f(2 * s);
+ }
+ for (let i = 0; i < n; i++) {
+ const m = 2 * i; let s = 0.5 * up[m];
+ for (let j = 0; j < H; j++) { const k = 2 * j + 1; s += HB[j] * ((m - k >= 0 ? up[m - k] : 0) + (m + k < 2 * n ? up[m + k] : 0)); }
+ x[i] = s;
+ }
+ return x;
+};
+/** Asymmetric tanh saturation, unity small-signal gain; `bias` adds even harmonics (tape/tube). DC removed after. */
+export const saturate = (x: Float32Array, sr: number, drive: number, bias = 0, mix = 1) => {
+ if (drive <= 0 || mix <= 0) return x;
+ const d = drive, t0 = Math.tanh(d * bias), g0 = d * (1 - t0 * t0), dry = mix < 1 ? Float32Array.from(x) : null;
+ oversample2(x, (v) => (Math.tanh(d * (v + bias)) - t0) / g0);
+ // DC blocker (5 Hz)
+ const R = Math.exp((-2 * Math.PI * 5) / 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; }
+ if (dry) for (let i = 0; i < x.length; i++) x[i] = dry[i] + (x[i] - dry[i]) * mix;
+ return x;
+};
+
+/**
+ * Guitar amp + cab, in place on a stereo stem (a part with `opts.amp` = drive, 1 clean .. 8 high gain). The DI is
+ * normalised so the playing peak hits the same point of the curve whatever the fader, then: a tube-screamer style
+ * pre-EQ (HP 110 Hz, +3 dB at 750 Hz), 2x oversampled asymmetric saturation (even harmonics), a 4x12 cab curve
+ * (HP 80 Hz, +2 dB at 2.4 kHz, 12 dB/oct low-pass at 5 kHz) and the stem's energy matched back: the fader keeps the balance.
+ */
+export const ampSim = (L: Float32Array, R: Float32Array, sr: number, drive: number) => {
+ let pk = 0, e0 = 0; for (let i = 0; i < L.length; i++) { pk = Math.max(pk, Math.abs(L[i]), Math.abs(R[i])); e0 += L[i] * L[i] + R[i] * R[i]; }
+ if (pk < 1e-9 || drive <= 0) return;
+ const ref = 0.5 / pk;
+ for (const c of [L, R]) {
+ for (let i = 0; i < c.length; i++) c[i] *= ref;
+ for (const b of [Biquad.make(sr, "hp", 110, 0.7071), Biquad.make(sr, "peak", 750, 0.8, 3)]) b.run(c);
+ saturate(c, sr, drive, 0.12);
+ for (const b of [Biquad.make(sr, "hp", 80, 0.7071), Biquad.make(sr, "peak", 2400, 1.1, 2), Biquad.make(sr, "lp", 5000, 0.7071)]) b.run(c);
+ }
+ let e1 = 0; for (let i = 0; i < L.length; i++) e1 += L[i] * L[i] + R[i] * R[i];
+ if (e1 > 0) { const k = Math.sqrt(e0 / e1); for (let i = 0; i < L.length; i++) { L[i] *= k; R[i] *= k; } }
+};
+
+/**
+ * Transient-aware gain for one stem (gentle styles: the plucks, plucked basses and piano, whose picks and hammers
+ * pin a static master at the -1 dBTP ceiling 2-3 dB short of -16 LUFS). A fast peak envelope (instant attack, 5 ms
+ * release) against the note's own body (a 20 ms / 150 ms mean level) says how far a sample stands above its body;
+ * only that excess comes down (above `thrDb`, at `ratio`, at most `maxDb`), with a 2 ms look-ahead so the dip lands
+ * on the pick, a 40 ms recovery, and the stem's energy matched back. The body, the decay and the balance between
+ * stems do not move: only the crest of each attack does. Not a compressor on the master (spec 08 forbids that on
+ * gentle styles); gentleGlue stays a separate, default-off decision. Returns the p99 gain reduction in dB.
+ */
+export const transientGain = (L: Float32Array, R: Float32Array, sr: number, o: { maxDb?: number; thrDb?: number; ratio?: number } = {}) => {
+ const n = L.length, maxDb = o.maxDb ?? 6, thr = o.thrDb ?? 4, k = 1 - 1 / (o.ratio ?? 3);
+ let e0 = 0; for (let i = 0; i < n; i++) e0 += L[i] * L[i] + R[i] * R[i];
+ if (e0 <= 0) return 0;
+ const rF = Math.exp(-1 / (0.005 * sr)), aS = Math.exp(-1 / (0.02 * sr)), rS = Math.exp(-1 / (0.15 * sr)), want = new Float32Array(n);
+ let fast = 0, slow = 0;
+ for (let i = 0; i < n; i++) {
+ const a = Math.max(Math.abs(L[i]), Math.abs(R[i]));
+ fast = a > fast ? a : rF * fast; slow = fast > slow ? aS * slow + (1 - aS) * fast : rS * slow + (1 - rS) * fast;
+ const over = slow > 1e-7 ? 20 * Math.log10(fast / slow) - thr : 0;
+ want[i] = over > 0 ? Math.min(maxDb, over * k) : 0;
+ }
+ // look-ahead: the reduction starts 2 ms before the peak it answers (running max over the next window), then a smooth recovery
+ const la = Math.max(1, Math.round(0.002 * sr)), rec = Math.exp(-1 / (0.04 * sr)), g = new Float32Array(n), q: number[] = [];
+ for (let i = n - 1; i >= 0; i--) { while (q.length && want[q[q.length - 1]] <= want[i]) q.pop(); q.push(i); while (q[0] > i + la) q.shift(); g[i] = want[q[0]]; }
+ let cur = 0; const grs: number[] = [];
+ for (let i = 0; i < n; i++) { cur = g[i] > cur ? g[i] : rec * cur + (1 - rec) * g[i]; const m = Math.pow(10, -cur / 20); L[i] *= m; R[i] *= m; if (cur > 0.05 && (i & 63) === 0) grs.push(cur); }
+ let e1 = 0; for (let i = 0; i < n; i++) e1 += L[i] * L[i] + R[i] * R[i];
+ if (e1 > 0) { const m = Math.sqrt(e0 / e1); for (let i = 0; i < n; i++) { L[i] *= m; R[i] *= m; } }
+ grs.sort((a, b) => a - b); return grs.length ? grs[Math.floor(grs.length * 0.99)] : 0;
+};
+
+// ---------------------------------------------------------------- compressor
+export type CompOpts = { ratio: number; attackMs: number; releaseMs: number; kneeDb?: number; /** target gain reduction on the loud passages (p90 of GR while active); the threshold is solved for it */ targetGrDb: number; maxGrDb?: number };
+/** Stereo-linked feed-forward compressor with auto threshold (solved so the loud passages see `targetGrDb`) and RMS makeup. Returns the measured GR stats. */
+export const compress = (L: Float32Array, R: Float32Array, sr: number, o: CompOpts) => {
+ const n = L.length, W = o.kneeDb ?? 6, slope = 1 / o.ratio - 1;
+ // detector: peak-ish level in dB (fast 1 ms attack, 40 ms release on the absolute value)
+ const det = new Float32Array(n), aA = Math.exp(-1 / (0.001 * sr)), aR = Math.exp(-1 / (0.04 * sr)); let e = 0, mx = -200;
+ for (let i = 0; i < n; i++) { const a = Math.max(Math.abs(L[i]), Math.abs(R[i])); e = a > e ? aA * e + (1 - aA) * a : aR * e + (1 - aR) * a; det[i] = lin2db(e); if (det[i] > mx) mx = det[i]; }
+ if (mx < -80) return { thresholdDb: 0, p90GrDb: 0, maxGrDb: 0 };
+ const gc = (x: number, T: number) => { const ov = x - T; if (2 * ov < -W) return 0; if (2 * Math.abs(ov) <= W) return (slope * (ov + W / 2) ** 2) / (2 * W); return slope * ov; };
+ const ga = Math.exp(-1 / ((o.attackMs / 1000) * sr)), gr = Math.exp(-1 / ((o.releaseMs / 1000) * sr));
+ const run = (T: number, out?: Float32Array, step = 1) => {
+ let g = 0; const act: number[] = [], ga2 = Math.pow(ga, step), gr2 = Math.pow(gr, step);
+ for (let i = 0; i < n; i += step) { const c = gc(det[i], T); g = c < g ? ga2 * g + (1 - ga2) * c : gr2 * g + (1 - gr2) * c; if (out) out[i] = g; if (det[i] > mx - 30) act.push(-g); }
+ act.sort((a, b) => a - b); return act.length ? act[Math.floor(act.length * 0.9)] : 0;
+ };
+ // bisection on the threshold: p90 GR is monotone in T
+ let lo = mx - 40, hi = mx + 1; const step = Math.max(1, Math.floor(sr / 6000));
+ for (let it = 0; it < 22; it++) { const mid = (lo + hi) / 2; if (run(mid, undefined, step) > o.targetGrDb) lo = mid; else hi = mid; }
+ const T = (lo + hi) / 2, gcurve = new Float32Array(n), p90 = run(T, gcurve);
+ let e0 = 0, e1 = 0, maxGr = 0;
+ for (let i = 0; i < n; i++) { const gg = Math.max(gcurve[i], -(o.maxGrDb ?? 12)); if (-gg > maxGr) maxGr = -gg; const k = db(gg); e0 += L[i] * L[i] + R[i] * R[i]; L[i] *= k; R[i] *= k; e1 += L[i] * L[i] + R[i] * R[i]; }
+ const mk = e1 > 0 ? Math.sqrt(e0 / e1) : 1; for (let i = 0; i < n; i++) { L[i] *= mk; R[i] *= mk; }
+ return { thresholdDb: T, p90GrDb: p90, maxGrDb: maxGr };
+};
+
+// ---------------------------------------------------------------- width
+/** Linkwitz-Riley 4th-order split of x into [low, high] at f. */
+export const lr4 = (x: Float32Array, sr: number, f: number): [Float32Array, Float32Array] => {
+ const lo = Float32Array.from(x), hi = Float32Array.from(x);
+ for (let k = 0; k < 2; k++) { Biquad.make(sr, "lp", f, 0.7071).run(lo); Biquad.make(sr, "hp", f, 0.7071).run(hi); }
+ return [lo, hi];
+};
+/** Per-band M/S width: the side below `monoHz` is removed (mono lows), `mid` scales the side from monoHz to `splitHz`, `high` above it. */
+export const bandWidth = (L: Float32Array, R: Float32Array, sr: number, o: { monoHz: number; splitHz: number; mid: number; high: number }) => {
+ const n = L.length, M = new Float32Array(n), S = new Float32Array(n);
+ for (let i = 0; i < n; i++) { M[i] = 0.5 * (L[i] + R[i]); S[i] = 0.5 * (L[i] - R[i]); }
+ const [, above] = lr4(S, sr, o.monoHz), [sMid, sHigh] = lr4(above, sr, o.splitHz);
+ for (let i = 0; i < n; i++) { const s = sMid[i] * o.mid + sHigh[i] * o.high; L[i] = M[i] + s; R[i] = M[i] - s; }
+};
+
+// ---------------------------------------------------------------- limiter
+/** Inter-sample peak estimate per sample (4x windowed sinc, same kernel as meter.truePeak), skipped where the sample itself is far below `floor`. */
+const TP = (() => { const O = 4, T = 16, h: number[][] = []; for (let ph = 1; ph < O; ph++) { const row: number[] = []; for (let t = 0; t < T; t++) { const x = t - T / 2 + 1 - ph / O, w = 0.5 + 0.5 * Math.cos((Math.PI * x) / (T / 2)); row.push(x === 0 ? 1 : (Math.sin(Math.PI * x) / (Math.PI * x)) * w); } h.push(row); } return h; })();
+const ispPeak = (c: Float32Array, out: Float32Array, floor: number) => {
+ const n = c.length;
+ for (let i = 0; i < n; i++) {
+ let p = Math.abs(c[i]);
+ if (p > floor || (i + 1 < n && Math.abs(c[i + 1]) > floor)) for (const row of TP) { let s = 0; for (let t = 0; t < 16; t++) { const j = i + t - 7; if (j >= 0 && j < n) s += c[j] * row[t]; } const v = Math.abs(s); if (v > p) p = v; }
+ if (p > out[i]) out[i] = p;
+ }
+};
+/**
+ * Smooth true-peak limiter: 4x inter-sample detection, look-ahead hold (`lookMs`), instant-attack
+ * release (`releaseMs`), then a box filter the length of the look-ahead so the gain ramps in with no
+ * corners (no clicks, no brickwall buzz). The ramp is provably at or under the needed gain at every
+ * peak. Offline, so no output delay. Returns the maximum gain reduction in dB.
+ */
+export const smoothLimiter = (L: Float32Array, R: Float32Array, sr: number, ceil: number, lookMs = 5, releaseMs = 90) => {
+ const n = L.length, D = Math.max(2, Math.round((lookMs / 1000) * sr)), pk = new Float32Array(n);
+ ispPeak(L, pk, ceil * 0.5); ispPeak(R, pk, ceil * 0.5);
+ const need = new Float32Array(n); for (let i = 0; i < n; i++) need[i] = pk[i] > ceil ? ceil / pk[i] : 1;
+ // hold: m[j] = min(need[j-D .. j]) via a monotone deque
+ const m = new Float32Array(n), dq = new Int32Array(n); let h = 0, t = 0;
+ for (let j = 0; j < n; j++) { while (t > h && need[dq[t - 1]] >= need[j]) t--; dq[t++] = j; while (dq[h] < j - D) h++; m[j] = need[dq[h]]; }
+ // release (instant attack): never above m
+ const rc = 1 - Math.exp(-1 / ((releaseMs / 1000) * sr)); let r = 1;
+ for (let j = 0; j < n; j++) { r = Math.min(m[j], r + (1 - r) * rc); m[j] = r; }
+ // box filter over D, read D ahead: s at sample i averages m[i+1 .. i+D], all <= need[i]
+ let acc = 0, maxGr = 0; const at = (j: number) => (j < n ? m[j] : 1);
+ for (let j = 1; j <= D; j++) acc += at(j);
+ for (let i = 0; i < n; i++) { const g = acc / D; L[i] *= g; R[i] *= g; if (g < 1) maxGr = Math.max(maxGr, -lin2db(g)); acc += at(i + 1 + D) - at(i + 1); }
+ return maxGr;
+};
+
+/** RMS of a stereo pair over its samples above -70 dBFS (the active part). */
+export const activeRms = (L: Float32Array, R: Float32Array) => {
+ let e = 0, k = 0; const th = 1e-7;
+ for (let i = 0; i < L.length; i++) { const v = L[i] * L[i] + R[i] * R[i]; if (v > th) { e += v; k++; } }
+ return k ? Math.sqrt(e / (2 * k)) : 0;
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
new file mode 100644
index 0000000..d9f5145
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
@@ -0,0 +1,140 @@
+// Each style's MIX and SPACE profile and its FEEL (sound v2). Data, like tables.ts: a style names a
+// profile, a piece may override any field (Material.mix / Piece.mix). The engine reads these in
+// render.ts (EQ per stem, drum bus, glue, width, space, limiter) and perform.ts (feel).
+// Numbers come from the research doc (anidoodle-research/launch-film/research/music-synthesis-research.md
+// sections 3-5) and common mixing practice; every profile is `unconfirmed` until a human listen.
+import type { InstId, Role } from "./plan";
+import type { StyleId } from "./tables";
+import type { StemEq } from "./mixDsp";
+import type { Space } from "./mixReverb";
+
+/** What an instrument IS for the mixer. */
+export type EqClass = "kick" | "snare" | "hat" | "chipDrum" | "boom" | "bass" | "chip" | "piano" | "keys" | "pad" | "lead" | "pluck" | "bell" | "fx";
+export const EQ_CLASS: Record<InstId, EqClass> = {
+ kick: "kick", snare: "snare", hat: "hat", noiseDrum: "chipDrum", timpani: "boom", bass: "bass", sub: "bass", triangle: "chip", pulse: "chip",
+ piano: "piano", ePiano: "keys", organ: "keys", warmPad: "pad", strings: "pad", choir: "pad", brass: "lead", woodwind: "lead", leadSynth: "lead", bowedSolo: "lead",
+ guitar: "pluck", harp: "pluck", softPluck: "pluck", musicBox: "bell", bell: "bell", celesta: "bell", marimba: "bell", vibes: "bell", fmBell: "bell", glockenspiel: "bell", wurlitzer: "keys", pipeOrgan: "keys", vinyl: "fx",
+};
+/** Corrective EQ per class: clear the mud (200-500 Hz), give each thing its own band, roll off what it doesn't use. */
+export const CLASS_EQ: Record<EqClass, StemEq> = {
+ kick: { hp: 28, bells: [[62, 1.1, 1.5], [330, 1.3, -3], [3800, 1.2, 1.5]] },
+ snare: { hp: 90, bells: [[210, 1.2, 1], [850, 1.4, -1.5], [5500, 0.8, 1.5]] },
+ hat: { hp: 320, bells: [[9000, 0.9, 1]], lp: 17500 },
+ chipDrum: { hp: 60 },
+ boom: { hp: 26, bells: [[300, 1.2, -2]] },
+ bass: { hp: 30, bells: [[240, 1.1, -1.5], [900, 1.2, 1]], lp: 9000 },
+ chip: { hp: 40 },
+ piano: { hp: 30, bells: [[320, 1.0, -1], [3200, 0.9, 0.8]], air: 0.8 },
+ keys: { hp: 70, bells: [[330, 1.1, -1.5], [2400, 1, 0.8]], lp: 14000 },
+ pad: { hp: 110, bells: [[380, 1.0, -2], [3000, 0.8, 0.5]], lp: 13000 },
+ lead: { hp: 110, bells: [[300, 1.2, -1], [2600, 1.0, 1.2]] },
+ pluck: { hp: 85, bells: [[260, 1.2, -1.5], [4500, 0.8, 1.2]] },
+ bell: { hp: 170, bells: [[600, 1.0, -0.8]], lp: 15000 },
+ fx: { hp: 200 },
+};
+/** Default reverb send when a part names none (the legacy default was 1 for everything, bass included). */
+export const ROLE_SEND: Record<Role, number> = { melody: 0.5, inner: 0.5, accomp: 0.6, color: 0.7, bass: 0.1, drum: 0.25 };
+
+export type Lane = "kick" | "snare" | "ghost" | "hat" | "perc" | "bass" | "chords" | "lead" | "counter" | "arp";
+/**
+ * FEEL. `lanes`: a systematic offset per lane in ms (+ = late): the groove's shape, the same every
+ * bar. `humanize`: a phrase-correlated drift (AR(1), sigma ms, correlation per onset): the player
+ * leaning ahead or behind over a phrase. `jitter`: small uncorrelated error per note (sigma ms): the
+ * hand. Drums and pitched parts get their own. `hatDriftMs`: 1/f-ish wander of the hats (lo-fi).
+ * `velHumanize`/`velJitter`: the same split for velocity, relative (0.06 = +-6 %, about +-0.5 dB). `toneGamma`: Played.tone = v^gamma, the
+ * timbre hook every voice may read (brightness, attack, partial mix follow velocity).
+ */
+export type Feel = {
+ lanes: Partial<Record<Lane, number>>;
+ drum: { humanizeMs: number; corr: number; jitterMs: number }; pitched: { humanizeMs: number; corr: number; jitterMs: number };
+ hatDriftMs?: number; velHumanize: number; velJitter: number; toneGamma: number;
+};
+const F = (lanes: Feel["lanes"], drum: [number, number, number], pitched: [number, number, number], x: Partial<Feel> = {}): Feel => ({ lanes, drum: { humanizeMs: drum[0], corr: drum[1], jitterMs: drum[2] }, pitched: { humanizeMs: pitched[0], corr: pitched[1], jitterMs: pitched[2] }, velHumanize: 0.06, velJitter: 0.04, toneGamma: 0.8, ...x });
+export const FEELS = {
+ /** acoustic, rubato-led music: the performance rules carry it, a light human drift on top */
+ natural: F({}, [3, 0.8, 1.5], [6, 0.85, 1.2]),
+ /** a band that locks: snare a hair late, hats a hair early */
+ tight: F({ kick: 0, snare: 4, ghost: 3, hat: -3, perc: -2, bass: 2 }, [2.2, 0.8, 1.2], [3.5, 0.85, 1]),
+ /** electronic drive: hats pushed ahead, everything else on the grid */
+ pushed: F({ kick: 0, snare: 2, ghost: 2, hat: -6, perc: -4, bass: 1, arp: -1 }, [1.2, 0.7, 0.6], [2, 0.8, 0.6], { velJitter: 0.03 }),
+ /** lo-fi / hip-hop: snare late, ghosts late, hats early and wandering, bass behind the kick, keys lazy */
+ laidBack: F({ kick: 0, snare: 18, ghost: 12, hat: -5, perc: 6, bass: 9, chords: 12, lead: 7, counter: 9 }, [3.5, 0.9, 1.8], [5, 0.9, 1.5], { hatDriftMs: 4, velHumanize: 0.08 }),
+ /** swing: ride pushed, backbeat late, walking bass on top of the beat, comping behind */
+ swing: F({ kick: 0, snare: 10, ghost: 8, hat: -8, perc: -4, bass: -3, chords: 12, lead: 4 }, [3.5, 0.85, 2], [5, 0.85, 1.5], { velHumanize: 0.08 }),
+ /** orchestras speak late in the low and slow sections; players drift together */
+ orchestral: F({ bass: 8, chords: 10, counter: 6, perc: 0, kick: 0 }, [4, 0.9, 2.5], [8, 0.9, 2.5]),
+ /** machines: nothing moves (chiptune, grid parts) */
+ grid: F({}, [0, 0, 0], [0, 0, 0], { velHumanize: 0, velJitter: 0 }),
+} satisfies Record<string, Feel>;
+export type FeelId = keyof typeof FEELS;
+
+/** The whole mix profile of a style. */
+export type MixProfile = {
+ /** scales every class-EQ gain (0 = flat, 1 = as tabled) */ eq: number;
+ /** extra EQ per class for this style (merged over CLASS_EQ) */ classEq?: Partial<Record<EqClass, StemEq>>;
+ drumBus: { ratio: number; targetGrDb: number; attackMs: number; releaseMs: number; drive: number; satMix: number } | null;
+ /** mix-bus glue: 2:1, slow attack, auto release-ish; `targetGrDb` 1-2 dB for dense. Gentle styles: only with RenderOpts.gentleGlue (<= 1 dB), a decision for Alex. */
+ glue: { ratio: number; targetGrDb: number; attackMs: number; releaseMs: number } | null;
+ /** mix-bus tilt (dB low end to high end) and light saturation (dense styles) */ tilt: number; busDrive: number;
+ width: { monoHz: number; splitHz: number; mid: number; high: number };
+ space: Space | null; /** a short room for the drums (sends of role "drum"); null = drums share the main space */ drumRoom: Space | null;
+ feel: FeelId;
+ /** default sends per role for parts that name none (over ROLE_SEND) */ sends?: Partial<Record<Role, number>>;
+ /** gentle masters only: the transient-aware gain on plucked stems (mixDsp.transientGain; null = off) */ transient?: { maxDb: number; thrDb: number; ratio: number } | null;
+};
+/** The struck stems whose attacks pin a static gentle master at the true-peak ceiling: plucks, plucked basses, piano, mallets and bells, timpani. */
+export const isStruck = (inst: InstId, opts?: Record<string, number | boolean | string>) => ["pluck", "piano", "bell", "boom"].includes(EQ_CLASS[inst]) || (inst === "bass" && opts?.kind !== "synth");
+export const TRANSIENT_DEFAULT = { maxDb: 6, thrDb: 4, ratio: 3 };
+const conv = (rt60: number, predelayMs: number, o: Partial<Space> = {}): Space => ({ kind: "conv", rt60, predelayMs, hp: 220, lp: 8000, er: 0.45, late: 0.32, size: 0.55, highMult: 0.5, lowMult: 1.1, ...o });
+const fdn = (rt60: number, predelayMs: number, o: Partial<Space> = {}): Space => ({ kind: "fdn", rt60, predelayMs, hp: 250, lp: 7500, er: 0.4, late: 0.3, size: 0.5, highMult: 0.45, lowMult: 1.1, mod: 1, ...o });
+const plate = (rt60: number, predelayMs: number, o: Partial<Space> = {}): Space => ({ kind: "plate", rt60, predelayMs, hp: 300, lp: 9000, er: 0, late: 0.3, size: 0.5, highMult: 0.6, mod: 1, ...o });
+const kitRoom = (rt60 = 0.7): Space => fdn(rt60, 6, { size: 0.2, er: 0.55, late: 0.22, hp: 180, lp: 9000, highMult: 0.5 });
+
+const W = (mid: number, high: number, monoHz = 120) => ({ monoHz, splitHz: 2000, mid, high });
+const intimate: MixProfile = { eq: 0.8, drumBus: { ratio: 3, targetGrDb: 2, attackMs: 15, releaseMs: 120, drive: 1.2, satMix: 0.5 }, glue: null, tilt: 0, busDrive: 0, width: W(1.0, 1.08), space: conv(1.5, 18), drumRoom: null, feel: "natural" };
+const band: MixProfile = { eq: 1, drumBus: { ratio: 4, targetGrDb: 3.5, attackMs: 10, releaseMs: 100, drive: 1.6, satMix: 0.6 }, glue: { ratio: 2, targetGrDb: 1.5, attackMs: 20, releaseMs: 200 }, tilt: 0, busDrive: 1.1, width: W(1.05, 1.15), space: conv(1.3, 15, { size: 0.45 }), drumRoom: kitRoom(0.7), feel: "tight" };
+const electronic: MixProfile = { eq: 1, drumBus: { ratio: 4, targetGrDb: 4, attackMs: 10, releaseMs: 90, drive: 2, satMix: 0.7 }, glue: { ratio: 2, targetGrDb: 1.8, attackMs: 15, releaseMs: 180 }, tilt: 0, busDrive: 1.2, width: W(1.1, 1.25), space: plate(1.6, 22), drumRoom: kitRoom(0.6), feel: "pushed" };
+const cinematicP: MixProfile = { eq: 0.9, drumBus: { ratio: 3, targetGrDb: 2.5, attackMs: 20, releaseMs: 150, drive: 1.3, satMix: 0.4 }, glue: null, tilt: 0, busDrive: 0, width: W(1.1, 1.2), space: conv(2.4, 30, { size: 0.9, late: 0.34, er: 0.35, hp: 200, lp: 7500 }), drumRoom: null, feel: "orchestral" };
+const P = (base: MixProfile, o: Partial<MixProfile>): MixProfile => ({ ...base, ...o });
+
+export const MIX_PROFILES: Record<StyleId, MixProfile> = {
+ nocturne: P(intimate, { sends: { melody: 0.5, accomp: 0.35, inner: 0.35, bass: 0.3, color: 0.5 }, space: conv(1.7, 24, { size: 0.6, late: 0.17, er: 0.4, hp: 300, lp: 6500 }), /* hp 300: the left hand's low-mids stay out of the room (masking guard 75 -> 81 %) */ width: W(1.0, 1.1, 150), classEq: { piano: { hp: 28 } } }),
+ lullaby: P(intimate, { space: conv(1.5, 18, { size: 0.5 }), tilt: -0.8 }),
+ musicBox: P(intimate, { space: null /* the recipe: one reflection, handled in render */, width: W(1.0, 1.05) }),
+ folk: P(intimate, { space: conv(1.2, 12, { size: 0.4, late: 0.28 }), width: W(1.05, 1.15), feel: "natural" }),
+ minimalist: P(intimate, { space: conv(1.3, 14, { size: 0.5 }), feel: "tight" }),
+ jazz: P(intimate, { space: conv(1.2, 12, { size: 0.45 }), drumRoom: kitRoom(0.8), feel: "swing" }),
+ world: P(band, { space: conv(1.4, 16), glue: null, busDrive: 0, feel: "natural" }),
+ playful: P(band, { space: fdn(1.0, 12, { size: 0.35 }), glue: null, busDrive: 0 }),
+ rock: P(band, { space: plate(1.4, 20) }),
+ cinematic: cinematicP,
+ orchestral: P(cinematicP, { space: conv(2.6, 32, { size: 1, late: 0.34, er: 0.35, hp: 200, lp: 7000 }) }),
+ choral: P(cinematicP, { space: conv(3.0, 35, { size: 1, late: 0.36, er: 0.3, hp: 180, lp: 7000 }), feel: "natural" }),
+ suspense: P(cinematicP, { space: fdn(2.8, 25, { size: 0.9, late: 0.34, mod: 1.5 }) }),
+ ambient: P(cinematicP, { space: fdn(4.0, 40, { size: 1, late: 0.36, er: 0.25, mod: 2, highMult: 0.55 }), width: W(1.15, 1.3), feel: "natural" }),
+ drive: P(electronic, { space: plate(1.8, 25, { size: 0.7 }) }),
+ house: P(electronic, { space: plate(1.3, 18) }),
+ synthwave: P(electronic, { space: plate(2.2, 28, { size: 0.8, late: 0.34 }), feel: "tight" }),
+ hipHop: P(electronic, { space: fdn(1.1, 14, { size: 0.35 }), feel: "laidBack", width: W(1.0, 1.15) }),
+ lofiElectronic: P(electronic, { space: fdn(1.4, 20, { size: 0.45 }), drumBus: { ratio: 3, targetGrDb: 3, attackMs: 12, releaseMs: 110, drive: 1.5, satMix: 0.5 }, feel: "laidBack", width: W(1.05, 1.15) }),
+ // lofi: the sampler crunch, the drums' small room and the tape/vinyl tilt are lofiFx's (LOFI_DUSTY), so the mix adds none of them twice: bus comp only, no bus drive, no mix tilt, no kit room
+ lofi: P(electronic, { space: fdn(1.2, 16, { size: 0.35, lp: 6000, highMult: 0.35 }), drumBus: { ratio: 4, targetGrDb: 4, attackMs: 8, releaseMs: 100, drive: 1, satMix: 0 }, tilt: 0, drumRoom: null, width: W(0.9, 0.95, 150), feel: "laidBack" }),
+ chiptune: { eq: 0.3, drumBus: null, glue: { ratio: 2, targetGrDb: 1, attackMs: 20, releaseMs: 150 }, tilt: 0, busDrive: 0, width: W(1.0, 1.0), space: null, drumRoom: null, feel: "grid" },
+};
+
+/** The profile a piece plays with: its style's, with the piece's own overrides. */
+export const mixProfile = (style: StyleId, over?: Partial<MixProfile>): MixProfile => ({ ...MIX_PROFILES[style], ...(over ?? {}) });
+/** The EQ a part gets: class EQ (+ style extra), scaled by the profile's `eq`, with role rules (a bass-role part keeps its lows). */
+export const partEq = (prof: MixProfile, inst: InstId, role: Role): StemEq => {
+ const c = EQ_CLASS[inst], base = { ...CLASS_EQ[c], ...(prof.classEq?.[c] ?? {}) }, k = prof.eq;
+ const e: StemEq = { ...base, bells: (base.bells ?? []).map(([f, q, g]) => [f, q, g * k] as [number, number, number]), air: (base.air ?? 0) * k, tilt: (base.tilt ?? 0) * k };
+ if (role === "bass" && c !== "kick" && c !== "boom") e.hp = Math.min(e.hp ?? 30, 32);
+ if (role === "accomp" && e.hp && c !== "bass" && c !== "piano") e.hp *= 1.15;
+ if (role === "melody" && c !== "bass") e.bells = [...(e.bells ?? []), [2800, 1.1, 0.8 * k]];
+ return e;
+};
+/** A one-line summary for tools/music.mjs vocab. */
+export const describeMix = (style: StyleId) => {
+ const p = MIX_PROFILES[style], s = p.space;
+ return `space ${s ? `${s.kind} ${s.rt60}s, predelay ${s.predelayMs} ms` : style === "musicBox" ? "one early reflection" : "none"}${p.drumRoom ? `, kit room ${p.drumRoom.rt60}s` : ""}; drum bus ${p.drumBus ? `${p.drumBus.ratio}:1 ~${p.drumBus.targetGrDb} dB + sat x${p.drumBus.drive}` : "none"}; glue ${p.glue ? `${p.glue.ratio}:1 ~${p.glue.targetGrDb} dB` : "none (gentle)"}; width mid x${p.width.mid} high x${p.width.high}, mono < ${p.width.monoHz} Hz; feel ${p.feel}`;
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts
new file mode 100644
index 0000000..64e6d12
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts
@@ -0,0 +1,159 @@
+// Reverbs (sound v2). Three spaces, all deterministic from a seed, all returning the wet signal as
+// [full L, full R, late L, late R] (late = the diffuse tail only, which the reverb guard measures):
+// fdn diffuser (4 steps of random delays, random polarity, Hadamard mix) into a 16-line
+// Householder feedback network, each line delay-modulated (+-0.3 ms, 0.1-1 Hz) with
+// frequency-dependent loss (low T60 x lowMult, high T60 x highMult). After Signalsmith's
+// "Let's Write a Reverb" (design re-implemented, no code copied).
+// plate Dattorro 1997 (AES "Effect Design, Part 1"): 4 input allpasses into a modulated
+// figure-of-eight tank, the paper's output taps. Implemented from the published algorithm.
+// conv convolution with a SYNTHESIZED impulse response: decorrelated L/R noise in 8 octave
+// bands, each with its own exponential decay (T60 falls above 4 kHz), a sparse early-
+// reflection pattern and a 20 ms fade-in; FFT overlap-add. No recorded IR.
+import { Biquad, onePoleCoef, gauss, type Rng } from "./dsp";
+import { fft } from "./meter";
+
+export type SpaceKind = "fdn" | "plate" | "conv";
+export type Space = { kind: SpaceKind; rt60: number; predelayMs: number; /** send filter */ hp: number; lp: number; /** early reflections level (0..1) and the late tail level (0..1) */ er: number; late: number; /** room size 0..1 (fdn/conv delay spread) */ size?: number; /** HF / LF decay multipliers */ highMult?: number; lowMult?: number; /** tank modulation depth 0..1 */ mod?: number };
+type Wet = readonly [Float32Array, Float32Array, Float32Array, Float32Array];
+
+const sendFilter = (L: Float32Array, R: Float32Array, sr: number, s: Space) => {
+ const a = Float32Array.from(L), b = Float32Array.from(R);
+ for (const c of [a, b]) { Biquad.make(sr, "hp", s.hp, 0.7071).run(c); Biquad.make(sr, "lp", s.lp, 0.7071).run(c); }
+ return [a, b] as const;
+};
+/** A delay line with a fractional (cubic Hermite) read. */
+class Line {
+ buf: Float64Array; w = 0; mask: number;
+ constructor(len: number) { let s = 1; while (s < len + 8) s <<= 1; this.buf = new Float64Array(s); this.mask = s - 1; }
+ push(x: number) { this.buf[this.w] = x; this.w = (this.w + 1) & this.mask; }
+ at(d: number) { return this.buf[(this.w - 1 - d) & this.mask]; } // integer delay d >= 0 (0 = last pushed)
+ frac(d: number) { const i = Math.floor(d), f = d - i, y0 = this.at(i - 1), y1 = this.at(i), y2 = this.at(i + 1), y3 = this.at(i + 2); const c1 = 0.5 * (y2 - y0), c2 = y0 - 2.5 * y1 + 2 * y2 - 0.5 * y3, c3 = 0.5 * (y3 - y0) + 1.5 * (y1 - y2); return ((c3 * f + c2) * f + c1) * f + y1; }
+}
+const hadamard = (h: Float64Array) => { const N = h.length; for (let s = 1; s < N; s <<= 1) for (let j = 0; j < N; j += s << 1) for (let q = j; q < j + s; q++) { const a = h[q], b = h[q + s]; h[q] = a + b; h[q + s] = a - b; } const k = 1 / Math.sqrt(N); for (let j = 0; j < N; j++) h[j] *= k; };
+
+// ---------------------------------------------------------------- FDN
+export const fdnReverb = (L: Float32Array, R: Float32Array, sr: number, s: Space, rng: Rng): Wet => {
+ const n = L.length, [inL, inR] = sendFilter(L, R, sr, s), size = s.size ?? 0.6, pd = Math.round((s.predelayMs / 1000) * sr);
+ const wL = new Float32Array(n), wR = new Float32Array(n), tL = new Float32Array(n), tR = new Float32Array(n);
+ // diffuser: 4 steps x 8 channels, each step's delays random inside a range that halves each step
+ const DC = 8, steps = 4, dif: { lines: Line[]; d: number[]; flip: number[] }[] = [];
+ let range = (0.012 + 0.03 * size) * sr;
+ for (let k = 0; k < steps; k++) { const d = Array.from({ length: DC }, (_, c) => Math.max(1, Math.round((range * (c + rng())) / DC))); dif.push({ lines: d.map((x) => new Line(x + 2)), d, flip: d.map(() => (rng() < 0.5 ? -1 : 1)) }); range /= 2; }
+ // feedback network: 16 lines, 0.6-1.6 x base, base 45-110 ms by size
+ const N = 16, base = (0.045 + 0.065 * size) * sr, lens = Array.from({ length: N }, (_, j) => Math.round(base * Math.pow(2, (j / N) * 1.3) * (0.92 + 0.16 * rng())));
+ const lines = lens.map((l) => new Line(l + 64)), rate = lens.map(() => 0.1 + 0.9 * rng()), phase = lens.map(() => rng() * Math.PI * 2), depth = (s.mod ?? 1) * 0.0003 * sr;
+ const rtH = s.rt60 * (s.highMult ?? 0.45), rtL = s.rt60 * (s.lowMult ?? 1.15);
+ // per line: Jot's absorptive one-pole, DC gain from the low T60 and Nyquist gain from the high T60 (monotone, so always stable)
+ const gDc = lens.map((l) => Math.pow(10, (-3 * l) / (sr * rtL))), gNy = lens.map((l) => Math.pow(10, (-3 * l) / (sr * rtH * 0.7)));
+ const pa = lens.map((_, j) => (gDc[j] - gNy[j]) / (gDc[j] + gNy[j])), pb = lens.map((_, j) => gDc[j] * (1 - pa[j])), zf = new Float64Array(N);
+ const x8 = new Float64Array(DC), fb = new Float64Array(N), out = new Float64Array(N), twoPi = Math.PI * 2;
+ const erG = s.er * 0.75, lateG = s.late * 1.6; // calibrated: at late 0.3 the tail sits where the legacy hall's did (same input, -19.5 dB)
+ for (let i = 0; i < n; i++) {
+ const xl = i >= pd ? inL[i - pd] : 0, xr = i >= pd ? inR[i - pd] : 0;
+ for (let c = 0; c < DC; c++) x8[c] = c % 2 ? xr : xl;
+ for (const st of dif) { for (let c = 0; c < DC; c++) { st.lines[c].push(x8[c]); x8[c] = st.lines[c].at(st.d[c]) * st.flip[c]; } hadamard(x8); }
+ // early: the diffuser output, alternate channels to each side
+ const el = x8[0] - x8[2] + x8[4] - x8[6], er = x8[1] - x8[3] + x8[5] - x8[7];
+ for (let j = 0; j < N; j++) { const md = depth * Math.sin(twoPi * rate[j] * (i / sr) + phase[j]); out[j] = lines[j].frac(lens[j] + md); }
+ // Householder: y = x - 2/N sum(x)
+ let sum = 0; for (let j = 0; j < N; j++) sum += out[j]; sum *= 2 / N;
+ for (let j = 0; j < N; j++) {
+ const v = out[j] - sum;
+ zf[j] = pb[j] * v + pa[j] * zf[j]; fb[j] = zf[j];
+ lines[j].push(fb[j] + x8[j % DC] * 0.5);
+ }
+ let ll = 0, rr = 0; for (let j = 0; j < N; j++) { const sg = (j >> 1) % 2 ? -1 : 1; if (j % 2) rr += out[j] * sg; else ll += out[j] * sg; }
+ tL[i] = ll * lateG * 0.25; tR[i] = rr * lateG * 0.25;
+ wL[i] = tL[i] + el * erG * 0.35; wR[i] = tR[i] + er * erG * 0.35;
+ }
+ return [wL, wR, tL, tR];
+};
+
+// ---------------------------------------------------------------- Dattorro plate
+export const plateReverb = (L: Float32Array, R: Float32Array, sr: number, s: Space, rng: Rng): Wet => {
+ const n = L.length, [inL, inR] = sendFilter(L, R, sr, s), k = sr / 29761, S = (x: number) => Math.max(1, Math.round(x * k * (0.6 + 0.8 * (s.size ?? 0.5))));
+ const wL = new Float32Array(n), wR = new Float32Array(n), tL = new Float32Array(n), tR = new Float32Array(n), pd = Math.round((s.predelayMs / 1000) * sr);
+ const bw = onePoleCoef(sr, s.lp * 0.9);
+ const ap = (len: number) => ({ l: new Line(len + 40), len });
+ const ind = [ap(S(142)), ap(S(107)), ap(S(379)), ap(S(277))], indG = [0.75, 0.75, 0.625, 0.625];
+ const mA = ap(S(672)), dA = new Line(S(4453) + 4), aA2 = ap(S(1800)), dA2 = new Line(S(3720) + 4);
+ const mB = ap(S(908)), dB = new Line(S(4217) + 4), aB2 = ap(S(2656)), dB2 = new Line(S(3163) + 4);
+ const lA = S(4453), lA2 = S(3720), lB = S(4217), lB2 = S(3163);
+ const half = (S(672) + lA + S(1800) + lA2) / sr, decay = Math.min(0.97, Math.pow(10, (-3 * half) / s.rt60));
+ const dampF = onePoleCoef(sr, Math.min(sr * 0.45, 2500 + 6000 * (s.highMult ?? 0.5))), exc = 16 * k * (s.mod ?? 1), rA = 0.5 + 0.4 * rng(), rB = 0.6 + 0.4 * rng();
+ let bwz = 0, zA = 0, zB = 0, fbA = 0, fbB = 0;
+ const apTick = (a: { l: Line; len: number }, x: number, g: number, d = a.len) => { const z = d === a.len ? a.l.at(a.len - 1) : a.l.frac(d - 1); const v = x - g * z; a.l.push(v); return z + g * v; };
+ const tap = (l: Line, d: number) => l.at(Math.max(0, S(d) - 1));
+ const tapAp = (a: { l: Line }, d: number) => a.l.at(Math.max(0, S(d) - 1));
+ for (let i = 0; i < n; i++) {
+ const x = i >= pd ? 0.5 * (inL[i - pd] + inR[i - pd]) : 0;
+ bwz += bw * (x - bwz); let v = bwz;
+ for (let j = 0; j < 4; j++) v = apTick(ind[j], v, indG[j]);
+ const t = i / sr;
+ // branch A
+ let a = apTick(mA, v + fbB * decay, -0.7, mA.len + exc * Math.sin(2 * Math.PI * rA * t)); dA.push(a); a = dA.at(lA - 1);
+ zA += dampF * (a - zA); a = zA * decay; a = apTick(aA2, a, 0.5); dA2.push(a); const outA = dA2.at(lA2 - 1);
+ // branch B
+ let b = apTick(mB, v + fbA * decay, -0.7, mB.len + exc * Math.sin(2 * Math.PI * rB * t + 1.3)); dB.push(b); b = dB.at(lB - 1);
+ zB += dampF * (b - zB); b = zB * decay; b = apTick(aB2, b, 0.5); dB2.push(b); const outB = dB2.at(lB2 - 1);
+ fbA = outA; fbB = outB;
+ const yl = tap(dB, 266) + tap(dB, 2974) - tapAp(aB2, 1913) + tap(dB2, 1996) - tap(dA, 1990) - tapAp(aA2, 187) - tap(dA2, 1066);
+ const yr = tap(dA, 353) + tap(dA, 3627) - tapAp(aA2, 1228) + tap(dA2, 2673) - tap(dB, 2111) - tapAp(aB2, 335) - tap(dB2, 121);
+ tL[i] = yl * 0.62 * s.late; tR[i] = yr * 0.62 * s.late; wL[i] = tL[i]; wR[i] = tR[i];
+ }
+ return [wL, wR, tL, tR];
+};
+
+// ---------------------------------------------------------------- synthesized IR + convolution
+/** A stereo IR: [er L, er R, late L, late R], each normalized so the late tail has unit energy per channel. */
+export const synthIR = (sr: number, s: Space, rng: Rng) => {
+ const len = Math.min(Math.round(Math.max(0.3, s.rt60 * 1.25) * sr), Math.round(8 * sr)), size = s.size ?? 0.6;
+ const erL = new Float32Array(len), erR = new Float32Array(len), lL = new Float32Array(len), lR = new Float32Array(len);
+ // sparse early reflections, 4-60 ms scaled by size, falling gain, random sign, each side its own pattern
+ const nEr = 10, erEnd = (0.02 + 0.045 * size) * sr;
+ for (const [buf, off] of [[erL, 0], [erR, 0.3]] as const) for (let t = 0; t < nEr; t++) { const d = Math.round(0.004 * sr + erEnd * Math.pow((t + rng() * 0.8 + off) / nEr, 1.4)); if (d < len) buf[d] += (rng() < 0.5 ? -1 : 1) * Math.pow(0.82, t) * (0.6 + 0.4 * rng()); }
+ // late: 8 octave bands (63 Hz .. 8 kHz), per band T60, onset fade over 20 ms from the end of the early part
+ const bands = [63, 125, 250, 500, 1000, 2000, 4000, 8000], fadeA = Math.round(0.006 * sr + erEnd * 0.4), fade = Math.round(0.02 * sr);
+ const t60 = (f: number) => s.rt60 * (f <= 250 ? (s.lowMult ?? 1.15) : f >= 4000 ? (s.highMult ?? 0.5) * (f >= 8000 ? 0.75 : 1) : f >= 2000 ? 0.5 + 0.5 * (s.highMult ?? 0.5) : 1);
+ for (const [buf] of [[lL], [lR]] as const) {
+ for (const f of bands) {
+ if (f > sr * 0.45) continue;
+ const noise = new Float32Array(len); for (let i = 0; i < len; i++) noise[i] = gauss(rng);
+ const q = 1.2; Biquad.make(sr, "bp", f, q).run(noise); Biquad.make(sr, "bp", f, q).run(noise);
+ const tau = t60(f) / 6.91; // exp(-t/tau) reaches -60 dB at T60
+ for (let i = 0; i < len; i++) { const env = i < fadeA ? 0 : i < fadeA + fade ? (i - fadeA) / fade : 1; buf[i] += noise[i] * env * Math.exp(-i / sr / tau); }
+ }
+ }
+ const norm = (a: Float32Array, b: Float32Array) => { let e = 0; for (let i = 0; i < len; i++) e += a[i] * a[i] + b[i] * b[i]; const g = e > 0 ? Math.sqrt(2 / e) : 0; for (let i = 0; i < len; i++) { a[i] *= g; b[i] *= g; } };
+ norm(lL, lR); norm(erL, erR);
+ return { erL, erR, lL, lR, len };
+};
+/** Linear convolution of x with h by FFT overlap-add (block = the FFT size minus the IR). */
+export const convolve = (x: Float32Array, h: Float32Array, out: Float32Array, gain = 1) => {
+ const n = x.length, m = h.length; let N = 1; while (N < 2 * m) N <<= 1; N = Math.max(N, 1 << 15); const B = N - m + 1;
+ const Hr = new Float64Array(N), Hi = new Float64Array(N); Hr.set(h); fft(Hr, Hi);
+ const re = new Float64Array(N), im = new Float64Array(N);
+ for (let a = 0; a < n; a += B) {
+ re.fill(0); im.fill(0); let any = false;
+ for (let i = 0; i < B && a + i < n; i++) { re[i] = x[a + i]; if (x[a + i] !== 0) any = true; }
+ if (!any) continue;
+ fft(re, im);
+ for (let k = 0; k < N; k++) { const r = re[k] * Hr[k] - im[k] * Hi[k], ii = re[k] * Hi[k] + im[k] * Hr[k]; re[k] = r; im[k] = -ii; } // conjugate for the inverse via forward fft
+ fft(re, im);
+ for (let i = 0; i < N && a + i < out.length; i++) out[a + i] += (re[i] / N) * gain;
+ }
+};
+export const convReverb = (L: Float32Array, R: Float32Array, sr: number, s: Space, rng: Rng): Wet => {
+ const n = L.length, [inL, inR] = sendFilter(L, R, sr, s), ir = synthIR(sr, s, rng), pd = Math.round((s.predelayMs / 1000) * sr);
+ const xL = new Float32Array(n), xR = new Float32Array(n); for (let i = pd; i < n; i++) { xL[i] = inL[i - pd]; xR[i] = inR[i - pd]; }
+ const wL = new Float32Array(n), wR = new Float32Array(n), tL = new Float32Array(n), tR = new Float32Array(n), eL = new Float32Array(n), eR = new Float32Array(n);
+ // true stereo: L feeds both sides through decorrelated responses (the cross path 6 dB down)
+ const lateG = s.late * 0.36, erG = s.er * 0.51; // calibrated against the legacy room (see fdn)
+ convolve(xL, ir.lL, tL, lateG); convolve(xR, ir.lR, tR, lateG); convolve(xR, ir.lL, tL, lateG * 0.5); convolve(xL, ir.lR, tR, lateG * 0.5);
+ convolve(xL, ir.erL, eL, erG); convolve(xR, ir.erR, eR, erG);
+ for (let i = 0; i < n; i++) { wL[i] = tL[i] + eL[i]; wR[i] = tR[i] + eR[i]; }
+ return [wL, wR, tL, tR];
+};
+
+export const reverb = (L: Float32Array, R: Float32Array, sr: number, s: Space, rng: Rng): Wet =>
+ s.kind === "plate" ? plateReverb(L, R, sr, s, rng) : s.kind === "conv" ? convReverb(L, R, sr, s, rng) : fdnReverb(L, R, sr, s, rng);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/orchestra.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/orchestra.ts
index 1dd887b..cbca657 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/orchestra.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/orchestra.ts
@@ -4,6 +4,8 @@
// DECISION B). Each voice states the physics it borrows.
import { type Rng, TAU, clamp, pan, SVF, blep, gauss } from "./dsp";
import type { Played } from "./perform";
+import * as E from "./ensemble";
+import { timpani as kitTimpani } from "./drums";
type Out = { L: Float32Array; R: Float32Array };
type Opts = Record<string, number | boolean | string>;
@@ -27,7 +29,7 @@ export const organ = (keys: Played[], sr: number, n: number, o: Opts): Out => {
};
/** Brass: a PolyBLEP saw whose low-pass opens with loudness (the brass "bite"), the pitch rising ~25 cents into the note, vibrato delayed. `attack`, `bright`. */
-export const brass = (keys: Played[], sr: number, n: number, o: Opts): Out => {
+const brassLegacy = (keys: Played[], sr: number, n: number, o: Opts): Out => {
const out = out0(n), atk = num(o, "attack", 0.06), bright = num(o, "bright", 1), w = num(o, "width", 0.5);
for (const k of keys) {
const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.3) * sr)), lp = new SVF(sr, 800, 0.8), [gl, gr] = byPitch(k.p, w); let ph = 0;
@@ -39,7 +41,7 @@ export const brass = (keys: Played[], sr: number, n: number, o: Opts): Out => {
};
/** Woodwind: flute (sine + weak 2nd/3rd + breath noise at the pitch) or `reed: true` clarinet (odd harmonics, darker). Delayed vibrato. */
-export const woodwind = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
+const woodwindLegacy = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
const out = out0(n), reed = o.reed === true, breath = num(o, "breath", reed ? 0.02 : 0.08), w = num(o, "width", 0.3);
for (const k of keys) {
const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.2) * sr)), bp = new SVF(sr, f, 4), [gl, gr] = byPitch(k.p, w); let ph = 0;
@@ -53,7 +55,7 @@ export const woodwind = (keys: Played[], sr: number, n: number, o: Opts, r: Rng)
const VOWELS: Record<string, [number, number, number]> = { a: [700, 1220, 2600], o: [450, 800, 2830], u: [325, 700, 2530], e: [530, 1840, 2480], i: [300, 2200, 3000] };
/** Choir: three detuned saws per note through the formants of a vowel (`vowel`: a o u e i), slow attack. Texture and pads; never a lead. */
-export const choir = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
+const choirLegacy = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
const out = out0(n), fm = VOWELS[String(o.vowel ?? "a")] ?? VOWELS.a, atk = num(o, "attack", 0.35), w = num(o, "width", 0.8);
for (const k of keys) {
const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.8) * sr));
@@ -68,7 +70,7 @@ export const choir = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): O
};
/** Timpani (`pitch`: a MIDI note to tune it when it plays a drum lane): a tuned membrane (modal partials 1, 1.5, 1.99, 2.44, 2.97 with their own decays), a small downward pitch settle, a felt-mallet thump. Pitched on the note. */
-export const timpani = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
+const timpaniLegacy = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
const out = out0(n), dec = num(o, "decay", 1.6), P = [[1, 1, 1], [1.5, 0.5, 0.7], [1.99, 0.35, 0.5], [2.44, 0.2, 0.35], [2.97, 0.12, 0.25]];
for (const k of keys) {
const f = f0(typeof o.pitch === "number" ? (o.pitch as number) : k.p), i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil(dec * 4 * sr)), lp = new SVF(sr, 400, 0.7);
@@ -97,7 +99,7 @@ export const leadSynth = (keys: Played[], sr: number, n: number, o: Opts): Out =
};
/** Bowed solo (violin / cello): one saw with delayed vibrato and bow noise through body resonances (~280, 450, 2800 Hz), a bowed attack. */
-export const bowedSolo = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
+const bowedSoloLegacy = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
const out = out0(n), atk = num(o, "attack", 0.09), vibC = num(o, "vibrato", 22), [gl, gr] = pan(num(o, "pan", -0.1));
const body = o.cello === true ? [140, 300, 1600] : [280, 450, 2800];
for (const k of keys) {
@@ -108,3 +110,14 @@ export const bowedSolo = (keys: Played[], sr: number, n: number, o: Opts, r: Rng
}
return out;
};
+
+// ---------------------------------------------------------------- v2 ensemble voices (ensemble.ts)
+// `opts.legacy: true` keeps the v1 voice bit-for-bit (shipped films); everything else gets v2.
+const legacy = (o: Opts) => o.legacy === true;
+export const brass = (keys: Played[], sr: number, n: number, o: Opts): Out => (legacy(o) ? brassLegacy(keys, sr, n, o) : E.brass(keys, sr, n, o));
+export const woodwind = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => (legacy(o) ? woodwindLegacy(keys, sr, n, o, r) : E.woodwind(keys, sr, n, o, r));
+export const choir = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => (legacy(o) ? choirLegacy(keys, sr, n, o, r) : E.choir(keys, sr, n, o, r));
+export const bowedSolo = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => (legacy(o) ? bowedSoloLegacy(keys, sr, n, o, r) : E.bowedSolo(keys, sr, n, o, r));
+/** Timpani: the kit's concert timpani (drums.ts: 7 measured membrane modes, velocity pitch glide, stick click, real rolls), 3.7x faster than v1
+ * (4.5 s vs 16.9 s for a 30 s part at 48 kHz, measured at the sound-v2 merge). v1 (5 sines, recomputed with Math.sin per sample, no rolls) stays for legacy only. */
+export const timpani = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => (legacy(o) ? timpaniLegacy(keys, sr, n, o, r) : kitTimpani(keys, sr, n, o, r));
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/perform.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/perform.ts
index 3b0aa62..af165fe 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/perform.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/perform.ts
@@ -6,11 +6,26 @@ import { beatsPerBar, type Piece, type Note, type Role } from "./plan";
import { clamp, gauss } from "./dsp";
import type { KeyPress, PedalSpan } from "./piano";
import { rng as mkRng } from "../core";
+import { FEELS, mixProfile, type Lane } from "./mixProfiles";
-export type Played = KeyPress & { role: Role; kind?: string; w: number /* written velocity */ };
+/**
+ * Sound-v2 hooks every voice may read (legacy pieces never get them): `tone` 0..1 = velocity through
+ * the style's tone curve (brightness, attack hardness, partial mix should follow it, not only level);
+ * `vary` = this note's own seeded micro-variation (anti-clone): cents, dB, brightness and decay
+ * factors, a start phase 0..1 and an integer seed for the voice's own noise.
+ */
+export type NoteVary = { cents: number; db: number; bright: number; decay: number; phase: number; seed: number };
+export type Played = KeyPress & { role: Role; kind?: string; w: number /* written velocity */; tone?: number; vary?: NoteVary; lane?: Lane };
export type PerformOpts = { expressive: boolean; flatVelocity?: number };
export type Performance = { parts: { id: string; keys: Played[] }[]; pedal: PedalSpan[]; sec: (beat: number) => number; lastOnset: number; meanLeadMs: number };
+/** Which feel lane a part plays: the compose slot name when it is one, else from the instrument and role. */
+export const laneOf = (id: string, inst: string, role: Role, rim = false): Lane => {
+ const slots: Lane[] = ["kick", "snare", "ghost", "hat", "perc", "bass", "chords", "lead", "counter", "arp"];
+ if ((slots as string[]).includes(id)) return id as Lane;
+ if (inst === "kick") return "kick"; if (inst === "snare") return rim ? "ghost" : "snare"; if (inst === "hat" || inst === "noiseDrum") return "hat";
+ return role === "bass" ? "bass" : role === "melody" ? "lead" : role === "accomp" || role === "inner" ? "chords" : role === "drum" ? "perc" : "counter";
+};
const arch = (x: number) => Math.sin(Math.PI * Math.pow(clamp(x, 0, 1), 1.45)); // peaks near 0.62 of the phrase
export const perform = (p: Piece, tempo: number, o: PerformOpts): Performance => {
@@ -43,18 +58,33 @@ export const perform = (p: Piece, tempo: number, o: PerformOpts): Performance =>
const swing = plan.swing ?? 0.5;
const sw = (b: number) => { if (swing === 0.5) return b; const fl = Math.floor(b), fr = b - fl; return fl + (fr <= 0.5 ? fr * (swing / 0.5) : swing + (fr - 0.5) * ((1 - swing) / 0.5)); };
+ // sound v2: the style's FEEL (mixProfiles.ts). Legacy pieces (the shipped launch score) keep the old single AR(1) drift, bit for bit.
+ const v2 = !p.legacy, feel = FEELS[mixProfile(plan.style, p.mix).feel];
const RoleGain: Record<Role, number> = { melody: 1, inner: 0.55, bass: 0.68, accomp: 0.52, color: 0.7, drum: 1 }; // voicing: melody 6-10 dB over the rest
let leadSum = 0, leadN = 0;
const parts = p.parts.map((pt, pi) => {
const hr = mkRng(p.seed * 131 + pi * 17 + 1), grid = pt.opts?.grid === true, isPiano = pt.inst === "piano";
let tDev = 0, vDev = 0; // AR(1) states
+ // v2: humanize (phrase-correlated drift) and jitter (per-note error) are separate, per lane, drums apart from pitched parts
+ const lane = laneOf(pt.id, pt.inst, pt.role, pt.opts?.rim === true), drum = pt.role === "drum", hz = drum ? feel.drum : feel.pitched;
+ const laneOff = v2 && !isPiano ? (feel.lanes[lane] ?? 0) / 1000 : 0, /* grid parts keep the programmed nudge, never the human drift */ vr = mkRng(p.seed * 977 + pi * 31 + 7), jr = mkRng(p.seed * 613 + pi * 43 + 3);
+ let drift = 0, noteIdx = 0, vRel = 0;
const notes = pt.notes.slice().sort((a, b) => a.t - b.t || a.p - b.p);
// group simultaneous onsets (chords) for spread/roll
const keys: Played[] = [];
const melodyNext = (n: Note, i: number) => { for (let j = i + 1; j < notes.length; j++) if (notes[j].t > n.t + 1e-6) return notes[j].t; return Infinity; };
let lastT = -1e9, chordIdx = 0;
notes.forEach((n, i) => {
- if (Math.abs(n.t - lastT) > 1e-6) { chordIdx = 0; lastT = n.t; if (o.expressive && !grid) { tDev = 0.85 * tDev + Math.sqrt(1 - 0.85 * 0.85) * gauss(hr) * 0.007; vDev = 0.7 * vDev + Math.sqrt(1 - 0.49) * gauss(hr) * 0.035; } } else chordIdx++;
+ if (Math.abs(n.t - lastT) > 1e-6) {
+ chordIdx = 0; lastT = n.t;
+ if (o.expressive && !grid) {
+ if (!v2 || isPiano) { tDev = 0.85 * tDev + Math.sqrt(1 - 0.85 * 0.85) * gauss(hr) * 0.007; vDev = 0.7 * vDev + Math.sqrt(1 - 0.49) * gauss(hr) * 0.035; }
+ else {
+ const c = hz.corr; tDev = c * tDev + Math.sqrt(1 - c * c) * gauss(hr) * (hz.humanizeMs / 1000); vRel = 0.7 * vRel + Math.sqrt(1 - 0.49) * gauss(hr) * feel.velHumanize; // relative: a soft ghost moves as many dB as an accent
+ if (lane === "hat" && feel.hatDriftMs) drift = 0.97 * drift + Math.sqrt(1 - 0.97 * 0.97) * gauss(hr) * (feel.hatDriftMs / 1000);
+ }
+ }
+ } else chordIdx++;
let t = sec(sw(n.t)), end = sec(sw(n.t + n.d));
let v: number;
if (!o.expressive) { v = o.flatVelocity ?? 0.6; }
@@ -66,13 +96,16 @@ export const perform = (p: Piece, tempo: number, o: PerformOpts): Performance =>
v = (n.v / 0.7) * (0.25 + 0.6 * lv) * (0.92 + 0.16 * arch(x)) * (grid ? 1 : metric * hi) * (isPiano ? RoleGain[n.role] : 1 / (0.25 + 0.6 * 0.75)) + vDev;
if (n.t > ritFrom && !plan.loop) v *= 1 - 0.18 * clamp((n.t - ritFrom) / ritBeats, 0, 1); // the cadence relaxes
t += tDev;
+ if (v2 && !isPiano) { t += laneOff; if (!grid) { t += drift + gauss(jr) * (hz.jitterMs / 1000); v *= 1 + vRel + gauss(jr) * feel.velJitter; } }
if (n.role === "melody" && isPiano) { const ld = 0.012 + 0.016 * clamp(v, 0, 1); t -= ld; leadSum += ld; leadN++; }
if (n.roll !== undefined) t += chordIdx * n.roll; else if (chordIdx > 0 && !grid) t += chordIdx * 0.004;
// legato: melody keys overlap the next note by ~35 ms; accompaniment keys lift a little early (the pedal holds)
if (n.role === "melody" && isPiano) { const nx = melodyNext(n, i); if (Number.isFinite(nx) && Math.abs(nx - (n.t + n.d)) < 1e-6) end = sec(sw(nx)) + 0.035; }
else if (isPiano) end = t + (end - t) * 0.92;
}
- keys.push({ t: Math.max(0, t), off: Math.max(t + 0.03, end), p: n.p, v: clamp(v, 0.03, 1), role: n.role, kind: n.kind, w: n.v });
+ const key: Played = { t: Math.max(0, t), off: Math.max(t + 0.03, end), p: n.p, v: clamp(v, 0.03, 1), role: n.role, kind: n.kind, w: n.v };
+ if (v2) { key.tone = Math.pow(key.v, feel.toneGamma); key.lane = lane; key.vary = { cents: gauss(vr) * 3, db: gauss(vr) * 0.7, bright: 1 + gauss(vr) * 0.06, decay: 1 + gauss(vr) * 0.1, phase: vr(), seed: (p.seed * 7919 + pi * 104729 + noteIdx * 31) >>> 0 }; noteIdx++; }
+ keys.push(key);
});
return { id: pt.id, keys };
});
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
index 65ea174..85752c3 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
+++ b/plugins/anidoodle/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]];
@@ -75,7 +76,7 @@ export const LAUNCH3_BARS = 29;
export const launchLofi3Material = (): Material => {
const hk = (i: number) => `hook${i}`, sp = (i: number) => `spark${i}`;
return {
- style: "lofiElectronic", title: "anidoodle launch, cut 3", seed: 2027, mood: "calm", bpm: LAUNCH_BPM, key: "C", mode: "major", swing: 0.54, tail: 3.2,
+ style: "lofiElectronic", title: "anidoodle launch, cut 3", seed: 2027, legacy: true, mood: "calm", bpm: LAUNCH_BPM, key: "C", mode: "major", swing: 0.54, tail: 3.2,
chords: { Dm9: { voicing: PAD[0], bass: SUB[0] }, G13: { voicing: PAD[1], bass: SUB[1] }, Cmaj9: { voicing: PAD[2], bass: SUB[2] }, Am9: { voicing: PAD[3], bass: SUB[3] } },
motifs: Object.fromEntries([...HOOK.map((h, i) => [hk(i), h]), ...SPARK.map((x, i) => [sp(i), x])]),
grooves: {
@@ -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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts
index c7fd979..ac9ec1b 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts
@@ -2,7 +2,9 @@
// writes real lines instead of arrays of numbers, the plan validator, and `arrange`, which fits
// a piece to ANY film duration (tempo inside the style's range, then repeat or drop sections).
import { midi, type ModeId, MODES, detectMode, pcOf, modeFit } from "./theory";
+import type { LofiFx, TapeFx } from "./lofiFx";
import { MOODS, STYLES, REFUSED_BLENDS, type MoodId, type StyleId, type MelodyType } from "./tables";
+import type { MixProfile } from "./mixProfiles";
export type Meter = "2/4" | "3/4" | "4/4" | "5/4" | "6/8" | "7/8" | "9/8" | "12/8";
/** Beats per bar. Simple meters count quarters (7/8 = 3.5 quarters, write eighths as .5); compound meters (6/8, 9/8, 12/8) count dotted quarters (write eighths as 1/3). */
@@ -12,7 +14,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[];
@@ -27,8 +29,10 @@ export type MusicPlan = { style: StyleId; tempo: number; meter: Meter; sections:
/** room override (the guards' bad fixture uses it; films normally take the style's room) */ space?: { er?: number; late?: number; rt60?: number; hp?: number } };
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 PieceFx = { clean?: boolean /* skip the lo-fi colour (sampler, vinyl, tilt: lofiFx.ts) */; duck?: { by: string; parts: string[]; depth?: number; release?: number }; tape?: TapeFx; /** the lo-fi production chain (lofiFx.ts); a lofi-style piece without one gets LOFI_DUSTY */ lofi?: LofiFx };
export type Piece = { title: string; plan: MusicPlan; parts: Part[]; harmony: Chord[]; tail: number; seed: number; fx?: PieceFx;
+ /** a shipped score frozen on the old sound (bit-identical): render takes the legacy voices and fx paths */ legacy?: boolean;
+ /** override any field of the style's mix/space/feel profile (mixProfiles.ts) */ mix?: Partial<MixProfile>;
/** 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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
index f9fa296..df06efb 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
@@ -5,20 +5,29 @@
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 { chokeTimes, type KitCtx } from "./drums";
import { room, Biquad, db } from "./dsp";
import { warmPad, softPluck, sub, duckCurve, tape } from "./lofiKit";
+import { pumpCurve, lofiStem, lofiMaster, LOFI_DUSTY } from "./lofiFx";
import { loudness, truePeak, stemBalance } from "./meter";
import { STYLES } from "./tables";
import { rng as mkRng } from "../core";
+import { eqChain, runEq, stereoPan, compress, saturate, bandWidth, smoothLimiter, ampSim, transientGain } from "./mixDsp";
+import { reverb, type Space } from "./mixReverb";
+import { mixProfile, partEq, ROLE_SEND, isStruck, TRANSIENT_DEFAULT, type MixProfile } from "./mixProfiles";
-export type RenderOpts = { expressive?: boolean; piano?: PianoOpts; flatVelocity?: number; seconds?: number; tempo?: number; master?: "auto" | "gentle" | "dense" | "none"; stems?: boolean; only?: (p: Part) => boolean };
+export type RenderOpts = { /** sound v2, gentle styles only: a <= 1 dB 2:1 glue on the mix bus (spec 08 forbids a compressor on gentle masters; Alex decides) */ gentleGlue?: boolean; expressive?: boolean; piano?: PianoOpts; flatVelocity?: number; seconds?: number; tempo?: number; master?: "auto" | "gentle" | "dense" | "none"; stems?: boolean; only?: (p: Part) => boolean };
/** 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] };
+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];
+ /** sound v2: what the chain did (gain reduction in dB) */ mixReport?: { drumBusGr?: number; glueGr?: number; limiterGr?: number; transientGr?: number; space?: string } };
-const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) => {
- const o = pt.opts ?? {}, r = mkRng(seed);
+const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number, ctx: KitCtx = {}) => {
+ // Piece.legacy is the one freeze flag: legacy pieces hand every voice `legacy: true` so a rebuilt voice keeps its old path for them
+ const o = ctx.legacy ? { ...(pt.opts ?? {}), legacy: true } : pt.opts ?? {}, r = mkRng(seed);
+ if (!ctx.legacy) { const kv = keysVoice(pt.inst, keys, sr, n, o, seed); if (kv) return kv; } // keys rebuild (keys.ts)
switch (pt.inst) {
case "musicBox": return I.musicBox(keys, sr, n, o);
case "bell": return I.bell(keys, sr, n, o);
@@ -33,11 +42,12 @@ const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) =>
case "pulse": return I.pulse(keys, sr, n, o);
case "triangle": return I.triangle(keys, sr, n);
case "noiseDrum": return I.noiseDrum(keys, sr, n);
- case "kick": return I.kick(keys, sr, n, o);
- case "snare": return I.snare(keys, sr, n, o, r);
- case "hat": return I.hat(keys, sr, n, o, r);
+ case "kick": case "snare": case "hat": return I.drumVoice(pt.inst, keys, sr, n, o, r, ctx);
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);
@@ -45,14 +55,17 @@ const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) =>
case "brass": return O.brass(keys, sr, n, o);
case "woodwind": return O.woodwind(keys, sr, n, o, r);
case "choir": return O.choir(keys, sr, n, o, r);
- case "timpani": return O.timpani(keys, sr, n, o, r);
+ case "timpani": return O.timpani(keys, sr, n, o, r); // v2: the kit timpani (drums.ts); legacy opts: v1
case "leadSynth": return O.leadSynth(keys, sr, n, o);
case "bowedSolo": return O.bowedSolo(keys, sr, n, o, r);
default: throw new Error(`no instrument ${pt.inst}`);
}
};
-export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
+export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => (piece.legacy ? renderLegacy(piece, sr, o) : renderV2(piece, sr, o));
+
+/** The pre-v2 render, frozen: the shipped launch score renders through this bit for bit. */
+const renderLegacy = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
const expressive = o.expressive ?? true, tempo = o.tempo ?? piece.plan.tempo, style = STYLES[piece.plan.style];
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);
@@ -66,7 +79,7 @@ export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rende
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; }
+ else { const r = voice(pt, keys, sr, n, piece.seed * 101 + pi, { legacy: true }); 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; } }
@@ -100,8 +113,104 @@ export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rende
return { L, R, perf, tempo, gainDb, masterMode, stems, piece, dry, wet };
};
+/**
+ * Sound v2 (mixProfiles.ts per style): voice -> pump -> corrective EQ per stem (level-matched, so
+ * the calibrated balance holds) -> fader -> true stereo pan -> drum bus (comp + 2x oversampled
+ * saturation) / music bus -> sends per part to the style's space (and a short kit room) -> mix bus:
+ * tilt, glue (dense; gentle only with `gentleGlue`), light saturation (dense), per-band width with
+ * mono lows -> master (gentle: static gain; dense: the smooth true-peak limiter).
+ */
+const energy = (L: Float32Array, R: Float32Array) => { let e = 0; for (let i = 0; i < L.length; i++) e += L[i] * L[i] + R[i] * R[i]; return e; };
+/** Audible energy: above 40 Hz, so a voice's DC or subsonic drift never counts as level (the EQ's high-pass removes it, and the makeup must not replace it with audible gain). */
+const audible = (L: Float32Array, R: Float32Array, sr: number) => energy(Biquad.make(sr, "hp", 40, 0.7071).run(Float32Array.from(L)), Biquad.make(sr, "hp", 40, 0.7071).run(Float32Array.from(R)));
+const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
+ const expressive = o.expressive ?? true, tempo = o.tempo ?? piece.plan.tempo, style = STYLES[piece.plan.style], prof: MixProfile = mixProfile(style.id, piece.mix);
+ 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]> = {};
+ const dL = new Float32Array(n), dR = new Float32Array(n); // drum bus
+ const mS = [new Float32Array(n), new Float32Array(n)], rS = [new Float32Array(n), new Float32Array(n)]; // main space send, kit room send
+ let anyDrum = false, anyRoom = false;
+ const dk = piece.fx?.duck, byIdx = dk ? piece.parts.findIndex((p) => p.id === dk.by) : -1;
+ const pump = dk && byIdx >= 0 ? pumpCurve(perf.parts[byIdx].keys, tempo, sr, n, dk.depth ?? 0.4, dk.release) : null;
+ // lo-fi production (lofiFx.ts): a lofi-style piece without its own profile gets the dusty one; a loop's modulations close on its length
+ const lofi = piece.fx?.lofi ?? (style.id === "lofi" && !piece.fx?.clean ? LOFI_DUSTY : undefined), period = piece.plan.loop ? (piece.plan.sections.reduce((a, s) => a + s.bars * beatsPerBar(piece.plan.meter), 0) * 60) / tempo : undefined;
+ const report: NonNullable<Rendered["mixReport"]> = {};
+ const kitCtx: KitCtx = { legacy: false, style: piece.plan.style, choke: chokeTimes(piece.parts.map((pt, pi) => ({ inst: pt.inst, opts: pt.opts, keys: perf.parts[pi].keys }))) };
+ piece.parts.forEach((pt, pi) => {
+ if (o.only && !o.only(pt)) return;
+ const keys = perf.parts[pi].keys; if (!keys.length) return;
+ let sL: Float32Array, sR: Float32Array;
+ // piano v2 (keysPiano.ts) unless the caller asks for the v1 model by passing RenderOpts.piano
+ if (pt.inst === "piano") { const old = !!o.piano, r = old ? renderPiano(keys, perf.pedal, sr, n, o.piano!, piece.seed + pi) : renderPianoV2(keys, perf.pedal, sr, n, pt.opts ?? {}, piece.seed + pi); sL = r.L; sR = r.R; if (old ? o.piano!.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, kitCtx); sL = r.L; sR = r.R; }
+ if (lofi) lofiStem(lofi, pt.id, sL, sR, sr, keys.map((k) => k.t), piece.seed, period);
+ if (typeof pt.opts?.amp === "number") ampSim(sL, sR, sr, pt.opts.amp); // a guitar (or any DI) through the amp + cab
+ // gentle masters are one static gain: a pick or hammer spike would hold the whole mix under the ceiling, so struck stems lose their crest, not their level
+ const tg = prof.transient === undefined ? TRANSIENT_DEFAULT : prof.transient;
+ if (style.master === "gentle" && tg && isStruck(pt.inst, pt.opts)) report.transientGr = Math.max(report.transientGr ?? 0, transientGain(sL, sR, sr, tg));
+ if (pump && dk!.parts.includes(pt.id)) for (let i = 0; i < n; i++) { sL[i] *= pump[i]; sR[i] *= pump[i]; }
+ // corrective EQ, then match the stem's RMS back (+-3 dB cap): EQ shapes the tone, the fader keeps the calibrated balance
+ // the stem meter reads the part as the fader set it (pre-EQ, after its pan): the EQ is energy-neutral in the audible band
+ const pre = o.stems ? [Float32Array.from(sL), Float32Array.from(sR)] as [Float32Array, Float32Array] : null;
+ const before = audible(sL, sR, sr), e = partEq(prof, pt.inst, pt.role); runEq(sL, eqChain(sr, e)); runEq(sR, eqChain(sr, e));
+ const after = audible(sL, sR, sr), mk = after > 0 && before > 0 ? Math.min(db(3), Math.max(db(-3), Math.sqrt(before / after))) : 1;
+ const g = db(pt.gainDb ?? 0) * mk;
+ for (let i = 0; i < n; i++) { sL[i] *= g; sR[i] *= g; }
+ stereoPan(sL, sR, pt.pan ?? 0);
+ if (pre) { const k = db(pt.gainDb ?? 0); for (let i = 0; i < n; i++) { pre[0][i] *= k; pre[1][i] *= k; } stereoPan(pre[0], pre[1], pt.pan ?? 0); stems[pt.id] = pre; }
+ const isDrum = pt.role === "drum";
+ for (let i = 0; i < n; i++) { if (isDrum) { dL[i] += sL[i]; dR[i] += sR[i]; } else { L[i] += sL[i]; R[i] += sR[i]; } }
+ if (isDrum) anyDrum = true;
+ const send = pt.send ?? prof.sends?.[pt.role] ?? ROLE_SEND[pt.role], toRoom = isDrum && prof.drumRoom !== null, dst = toRoom ? rS : mS;
+ if (toRoom) anyRoom = true;
+ if (send > 0) for (let i = 0; i < n; i++) { dst[0][i] += sL[i] * send; dst[1][i] += sR[i] * send; }
+ });
+ // ---- drum bus: glue the kit (4:1-ish, 3-4 dB on the hits), then oversampled saturation in parallel
+ if (anyDrum && prof.drumBus) {
+ const b = prof.drumBus; report.drumBusGr = compress(dL, dR, sr, { ratio: b.ratio, attackMs: b.attackMs, releaseMs: b.releaseMs, targetGrDb: b.targetGrDb }).p90GrDb;
+ if (b.drive > 1) { const before = energy(dL, dR); saturate(dL, sr, b.drive, 0.08, b.satMix); saturate(dR, sr, b.drive, 0.08, b.satMix); const after = energy(dL, dR); if (after > 0) { const k = Math.sqrt(before / after); for (let i = 0; i < n; i++) { dL[i] *= k; dR[i] *= k; } } }
+ }
+ for (let i = 0; i < n; i++) { L[i] += dL[i]; R[i] += dR[i]; }
+ // ---- space
+ const rng = mkRng(piece.seed * 7 + 5), dry: [Float32Array, Float32Array] = [Float32Array.from(L), Float32Array.from(R)];
+ let wet: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)];
+ const sp = piece.plan.space;
+ if (style.id === "musicBox" && !sp && !piece.mix?.space) { // the recipe: ONE early reflection, 30 ms late, 14 dB down, no tail
+ const d = Math.round(0.03 * sr), g = db(-14); for (let i = d; i < n; i++) { wet[0][i] = dry[0][i - d] * g; wet[1][i] = dry[1][i - d] * g * 0.9; L[i] += wet[0][i]; R[i] += wet[1][i]; }
+ } else {
+ const main: Space | null = prof.space || sp ? { ...(prof.space ?? { kind: "fdn", rt60: 1.5, predelayMs: 20, hp: 300, lp: 7000, er: 0.4, late: 0.25 }), ...(sp ?? {}) } : null;
+ if (main) {
+ for (let i = 0; i < n; i++) { mS[0][i] += haloL[i] * 0.35; mS[1][i] += haloL[i] * 0.35; } // pedal halo: undamped strings ring into the room
+ if (!prof.drumRoom) for (let i = 0; i < n; i++) { mS[0][i] += rS[0][i]; mS[1][i] += rS[1][i]; }
+ const [wL, wR, tL, tR] = reverb(mS[0], mS[1], sr, main, rng);
+ for (let i = 0; i < n; i++) { L[i] += wL[i]; R[i] += wR[i]; }
+ wet = [tL, tR]; report.space = `${main.kind} ${main.rt60}s`;
+ }
+ if (prof.drumRoom && anyRoom) {
+ const [wL, wR, tL, tR] = reverb(rS[0], rS[1], sr, prof.drumRoom, mkRng(piece.seed * 11 + 3));
+ for (let i = 0; i < n; i++) { L[i] += wL[i]; R[i] += wR[i]; wet[0][i] += tL[i]; wet[1][i] += tR[i]; }
+ report.space = `${report.space ?? "no main space"} + kit room ${prof.drumRoom.rt60}s`;
+ }
+ }
+ // ---- mix bus
+ if (prof.tilt) for (const c of [L, R]) { Biquad.make(sr, "lowshelf", 1000, 0.5, -prof.tilt / 2).run(c); Biquad.make(sr, "highshelf", 1000, 0.5, prof.tilt / 2).run(c); }
+ const glue = style.master === "dense" ? prof.glue : o.gentleGlue ? { ratio: 2, targetGrDb: 0.8, attackMs: 30, releaseMs: 250 } : null;
+ if (glue) report.glueGr = compress(L, R, sr, { ...glue, kneeDb: 8, maxGrDb: 4 }).p90GrDb;
+ if (style.master === "dense" && prof.busDrive > 1) { saturate(L, sr, prof.busDrive, 0.03); saturate(R, sr, prof.busDrive, 0.03); }
+ bandWidth(L, R, sr, prof.width);
+ // ---- master: DC/rumble high-pass (4th-order Butterworth at 30 Hz), the lo-fi machines (lofiFx: tape, vinyl, room tone, tilt), end fade
+ for (const q of [0.5412, 1.3066]) { Biquad.make(sr, "hp", 30, q).run(L); Biquad.make(sr, "hp", 30, q).run(R); }
+ if (lofi || piece.fx?.tape) lofiMaster(L, R, sr, piece.fx?.tape && { ...piece.fx.tape, period }, lofi, piece.seed);
+ const fade = Math.min(n, Math.round(0.25 * sr)); for (let i = 0; i < fade; i++) { const g = 0.5 - 0.5 * Math.cos((Math.PI * i) / fade); L[n - 1 - i] *= g; R[n - 1 - i] *= g; }
+ let masterMode = o.master ?? "auto";
+ if (masterMode === "auto") masterMode = style.master;
+ const gainDb = masterMode === "none" ? 0 : master(L, R, sr, masterMode as "gentle" | "dense", true);
+ return { L, R, perf, tempo, gainDb, masterMode, stems, piece, dry, wet, mixReport: report };
+};
+
/** The master stage, in place. Gentle: one static gain to -16 LUFS, pulled down if the true peak passes -1 dBTP. Dense: -14 LUFS through the look-ahead limiter. Returns the gain in dB. */
-export const master = (L: Float32Array, R: Float32Array, sr: number, masterMode: "gentle" | "dense"): number => {
+export const master = (L: Float32Array, R: Float32Array, sr: number, masterMode: "gentle" | "dense", v2 = false): number => {
const n = L.length, target = masterMode === "dense" ? -14 : -16;
let gainDb = target - loudness([L, R], sr).integrated;
for (let i = 0; i < n; i++) { L[i] *= db(gainDb); R[i] *= db(gainDb); }
@@ -109,7 +218,8 @@ export const master = (L: Float32Array, R: Float32Array, sr: number, masterMode:
if (tp > -1) {
if (masterMode === "gentle") { const cut = tp + 1.05; gainDb -= cut; for (let i = 0; i < n; i++) { L[i] *= db(-cut); R[i] *= db(-cut); } }
else {
- limiter(L, R, sr, db(-1.3)); const again = target - loudness([L, R], sr).integrated; if (again > 0) { const g = db(Math.min(again, 1)); for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } limiter(L, R, sr, db(-1.3)); }
+ const lim = v2 ? (a: Float32Array, b: Float32Array) => smoothLimiter(a, b, sr, db(-1.15)) : (a: Float32Array, b: Float32Array) => limiter(a, b, sr, db(-1.3));
+ lim(L, R); const again = target - loudness([L, R], sr).integrated; if (again > 0) { const g = db(Math.min(again, 1)); for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } lim(L, R); }
const tp2 = truePeak([L, R]).dbtp; // harsh waveforms (pulses) can still overshoot between samples: a last static trim
if (tp2 > -1) { const cut = tp2 + 1.05; gainDb -= cut; for (let i = 0; i < n; i++) { L[i] *= db(-cut); R[i] *= db(-cut); } }
}
@@ -128,7 +238,7 @@ export const renderLoop = (piece: Piece, sr: number): Rendered & { loopS: number
const p: Piece = { ...piece, plan: { ...piece.plan, loop: true, ritard: 1 }, fx: piece.fx && { ...piece.fx, tape: tp && { ...tp, wowHz: snap(tp.wowHz ?? 0.45), flutterHz: snap(tp.flutterHz ?? 6.2) } } };
const r = renderPiece(p, sr, { seconds: loopS + piece.tail, master: "none" }), n = Math.round(loopS * sr), L = r.L.slice(0, n), R = r.R.slice(0, n);
for (let i = n; i < r.L.length; i++) { L[i - n] += r.L[i]; R[i - n] += r.R[i]; }
- const mode = STYLES[piece.plan.style].master, gainDb = master(L, R, sr, mode);
+ const mode = STYLES[piece.plan.style].master, gainDb = master(L, R, sr, mode, !piece.legacy);
return { ...r, L, R, gainDb, masterMode: mode, loopS };
};
@@ -138,7 +248,7 @@ export const fitScore = (piece: Piece, seconds: number) => fitToDuration(piece.r
/** Each part's stem level against the piece's targets (unmastered, pre-room: the mix as the parts were set). */
export const measureStems = (piece: Piece, sr: number, o: RenderOpts = {}, tolDb = 3) => {
const r = renderPiece(piece, sr, { ...o, stems: true, master: "none" });
- return stemBalance(r.stems, piece.stemTargets ?? {}, tolDb);
+ return stemBalance(r.stems, piece.stemTargets ?? {}, tolDb, undefined, sr);
};
/** Look-ahead peak limiter (1.5 ms look-ahead, 120 ms release), used by dense styles only; `ceil` is linear. */
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/roomSmall.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/roomSmall.ts
new file mode 100644
index 0000000..d5e9878
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/roomSmall.ts
@@ -0,0 +1,73 @@
+// A SMALL ROOM that does not ring. The old room (dsp.room) is 8 short static delay lines with 7
+// hard early taps: its tail has a comb "tinniness" (research doc section 1.6). This one is the
+// structure from Geraint Luff's "Let's Write a Reverb" (Signalsmith Audio, described there, written
+// here from the description): a 4-step multichannel DIFFUSER (8 channels, each step = random delays
+// inside a doubling window, random polarity, a Hadamard mix) builds dense early reflections, then an
+// 8-channel FEEDBACK network (Householder mix, per-line damping, slowly modulated delay reads so no
+// mode stays still) builds the tail. The two outputs take different channel sums, so L and R
+// decorrelate like two ears. Pure in (input, sr, opts, seed).
+import { Biquad, onePoleCoef, TAU } from "./dsp";
+import { rng as mkRng } from "../core";
+
+export type SmallRoomOpts = {
+ /** decay time of the tail in seconds */ rt60: number;
+ /** room size: the diffusion window and the feedback delays scale with it (1 = a ~4 x 5 m room) */ size?: number;
+ /** early (diffused reflections) and late (tail) gains */ er?: number; late?: number;
+ predelay?: number; hp?: number; lp?: number;
+ /** high-frequency damping inside the tail, Hz (walls absorb highs first) */ damp?: number;
+ seed?: number;
+};
+
+const hadamard8 = (x: Float64Array) => {
+ for (let s = 1; s < 8; s <<= 1) for (let j = 0; j < 8; j += s << 1) for (let q = j; q < j + s; q++) { const a = x[q], b = x[q + s]; x[q] = a + b; x[q + s] = a - b; }
+ for (let j = 0; j < 8; j++) x[j] *= 0.35355339059327373; // 1/sqrt(8): energy preserving
+};
+
+/** Returns the WET signal only: [L, R, lateL, lateR] (the late tail alone, for measurements). */
+export const smallRoom = (L: ArrayLike<number>, R: ArrayLike<number>, sr: number, o: SmallRoomOpts) => {
+ const n = L.length, r = mkRng((o.seed ?? 1) * 2654435761 >>> 0), size = o.size ?? 1;
+ const inL = Float64Array.from(L), inR = Float64Array.from(R);
+ for (const c of [inL, inR]) { const h = Biquad.make(sr, "hp", o.hp ?? 200, 0.7), l = Biquad.make(sr, "lp", o.lp ?? 8000, 0.7); for (let i = 0; i < n; i++) c[i] = l.tick(h.tick(c[i])); }
+ const pd = Math.round((o.predelay ?? 0.006) * sr);
+ // ---- diffuser: 4 steps, windows 3, 6, 12, 24 ms x size
+ const steps = [0.003, 0.006, 0.012, 0.024].map((w) => {
+ const lens = Array.from({ length: 8 }, (_, c) => Math.max(1, Math.round(((w * size * (c + r())) / 8) * sr)));
+ return { lens, bufs: lens.map((l) => new Float64Array(l + 1)), idx: new Array(8).fill(0), flip: Array.from({ length: 8 }, () => (r() < 0.5 ? -1 : 1)), perm: shuffle(r) };
+ });
+ // ---- feedback network: 8 lines between 18 and 55 ms x size, exponentially spread, modulated
+ const N = 8, base = Array.from({ length: N }, (_, c) => 0.018 * size * Math.pow(55 / 18, (c + 0.5 * r()) / N));
+ const maxMod = 0.0006 * sr, lens = base.map((s) => Math.round(s * sr)), fb = lens.map((l) => new Float64Array(l + Math.ceil(maxMod) + 4)), w = new Array(N).fill(0);
+ const gain = base.map((s) => Math.pow(10, (-3 * s) / Math.max(0.05, o.rt60))), dk = onePoleCoef(sr, o.damp ?? 5200), lp = new Float64Array(N);
+ const modHz = Array.from({ length: N }, () => 0.35 + 0.9 * r()), modPh = Array.from({ length: N }, () => r() * TAU), modAmt = Array.from({ length: N }, () => maxMod * (0.4 + 0.6 * r()));
+ const outL = new Float32Array(n), outR = new Float32Array(n), tL = new Float32Array(n), tR = new Float32Array(n);
+ const x = new Float64Array(N), y = new Float64Array(N), er = o.er ?? 0.5, late = o.late ?? 0.6;
+ for (let i = 0; i < n; i++) {
+ const a = i >= pd ? inL[i - pd] : 0, b = i >= pd ? inR[i - pd] : 0;
+ for (let c = 0; c < N; c++) x[c] = c & 1 ? b : a;
+ // diffuse
+ for (const st of steps) {
+ for (let c = 0; c < N; c++) { const buf = st.bufs[c], L0 = buf.length, wi = st.idx[c]; buf[wi] = x[c]; y[c] = buf[(wi + 1) % L0] * st.flip[c]; st.idx[c] = (wi + 1) % L0; }
+ for (let c = 0; c < N; c++) x[c] = y[st.perm[c]];
+ hadamard8(x);
+ }
+ let eL = 0, eR = 0; for (let c = 0; c < N; c++) { if (c & 1) eR += x[c] * (c & 2 ? -1 : 1); else eL += x[c] * (c & 2 ? -1 : 1); }
+ // feedback: read (modulated, linear interp), Householder mix, damp, write input + feedback
+ let sum = 0;
+ for (let c = 0; c < N; c++) {
+ const buf = fb[c], L0 = buf.length, d = lens[c] + modAmt[c] * Math.sin(modPh[c] + (TAU * modHz[c] * i) / sr), rp = w[c] - d, j = Math.floor(rp), f = rp - j;
+ const i0 = ((j % L0) + L0) % L0, i1 = (i0 + 1) % L0; y[c] = buf[i0] + (buf[i1] - buf[i0]) * f; sum += y[c];
+ }
+ const h = (2 / N) * sum;
+ let lL = 0, lR = 0;
+ for (let c = 0; c < N; c++) {
+ const v = (y[c] - h) * gain[c]; lp[c] += dk * (v - lp[c]);
+ const buf = fb[c]; buf[w[c]] = lp[c] + x[c] * 0.5; w[c] = (w[c] + 1) % buf.length;
+ if (c & 1) lR += y[c] * (c & 2 ? -1 : 1); else lL += y[c] * (c & 2 ? -1 : 1);
+ }
+ tL[i] = lL * late * 0.5; tR[i] = lR * late * 0.5;
+ outL[i] = eL * er * 0.5 + tL[i]; outR[i] = eR * er * 0.5 + tR[i];
+ }
+ return [outL, outR, tL, tR] as const;
+};
+
+function shuffle(r: () => number) { const p = [0, 1, 2, 3, 4, 5, 6, 7]; for (let i = 7; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [p[i], p[j]] = [p[j], p[i]]; } return p; }
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts
index 78b48c1..ae7acc8 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts
@@ -5,7 +5,35 @@
import { rng as mkRng } from "../core";
import { pcOf } from "./theory";
import { clamp, db, type Rng } from "./dsp";
-import { Bus, modal, chirp, burst, white, pink, filt, sweep, shape, ad, smooth, space, finish, secs, buf, kWeight, winLufs, speakingWindow, type Mode, type SfxStereo } from "./sfxCore";
+import { Bus, modal, chirp, burst, white, pink, filt, sweep, shape, ad, smooth, finish, secs, buf, kWeight, winLufs, speakingWindow, type Mode, type SfxStereo } from "./sfxCore";
+import { smallRoom } from "./roomSmall";
+
+/**
+ * The space every sound sits in: a diffused small room (roomSmall.ts: dense early reflections and a
+ * modulated, damped tail that does not ring like the old 8-line FDN). The room's size follows the
+ * decay asked for, and every trigger gets its own room seed and +-8 % decay and level, so a repeated
+ * cue never has the identical tail.
+ */
+const space = (b: Bus, r: Rng, o: { rt60: number; mix: number; er?: number; predelay?: number; hp?: number; lp?: number }) => {
+ const rt = o.rt60 * (0.92 + 0.16 * r()), mix = o.mix * (0.92 + 0.16 * r()), seed = Math.floor(r() * 0xffffffff);
+ const [wL, wR] = smallRoom(b.L, b.R, b.sr, { rt60: rt, size: clamp(0.35 + rt * 0.55, 0.35, 1.8), er: (o.er ?? 0.5) * 1.1, late: 0.75, predelay: o.predelay ?? 0.008, hp: o.hp ?? 250, lp: o.lp ?? 7000, damp: (o.lp ?? 7000) * 0.7, seed });
+ for (let i = 0; i < b.n; i++) { b.L[i] += wL[i] * mix; b.R[i] += wR[i] * mix; }
+};
+/**
+ * Transient design (a transient shaper): the ratio of a fast envelope (0.2 ms attack, 6 ms release) to
+ * a slow one (7 ms, 70 ms) is large only on the attack, so `amt` > 0 sharpens the contact and leaves
+ * the body and tail alone. Linked across channels (the image does not shift). Gain capped at +9 dB.
+ */
+const punch = (b: Bus, amt: number) => {
+ const sr = b.sr, ka = (t: number) => 1 - Math.exp(-1 / (t * sr)), fa = ka(0.0002), fr = ka(0.006), sa = ka(0.007), srl = ka(0.07), sm = ka(0.0008);
+ let f = 0, s = 0, g = 1;
+ for (let i = 0; i < b.n; i++) {
+ const x = Math.max(Math.abs(b.L[i]), Math.abs(b.R[i]));
+ f += (x > f ? fa : fr) * (x - f); s += (x > s ? sa : srl) * (x - s);
+ const want = s > 1e-9 ? clamp(Math.pow(f / s, amt), 1, 2.8) : 1; g += sm * (want - g);
+ b.L[i] *= g; b.R[i] *= g;
+ }
+};
export type SfxOpts = {
/** per-hit variation: same seed, same samples; a different seed, a different (but same-family) hit. */
@@ -65,6 +93,7 @@ const tick: Def = {
b.add(burst(sr, r, 0.001, 0.00025, { hp: 4000 }), up, 0.1, p0);
}
if (soft) for (const ch of [b.L, b.R]) filt(ch, sr, { lp: 6000 });
+ punch(b, soft ? 0.25 : 0.4);
space(b, r, { rt60: 0.22, mix: 0.06, hp: 600 });
return { bus: b, hit: 0 };
},
@@ -93,6 +122,7 @@ const press: Def = {
b.add(modal(sr, n, glock(f, 0.35, 1, 0.012)), 0, 0.18, -0.25);
b.add(modal(sr, n, glock(f * 1.5, 0.28, 1, 0.07)), 0, 0.12, 0.3);
}
+ punch(b, soft ? 0.3 : 0.5);
space(b, r, { rt60: v === "confirm" ? 0.9 : 0.4, mix: v === "confirm" ? 0.16 : 0.1, hp: 220 });
return { bus: b, hit: 0 };
},
@@ -109,6 +139,7 @@ const pop: Def = {
b.add(burst(sr, r, 0.005, v === "cork" ? 0.0014 : 0.0008, { bp: v === "tiny" ? 3200 : v === "cork" ? 900 : 1400, q: 1.4 }), 0, nz * 2.2, p0);
if (v !== "tiny") b.add(modal(sr, n, [{ f: c.j(v === "cork" ? 110 : 140, 0.1) * P, tau: 0.01, a: 1, att: 0.0005 }]), 0, 0.3, 0);
if (v === "cork") b.add(shape(filt(pink(r, secs(sr, 0.12)), sr, { hp: 1800 }), sr, ad(0.004, 0.025)), secs(sr, 0.004), 0.25, p0); // the rush of air
+ punch(b, 0.35);
space(b, r, { rt60: 0.35, mix: 0.1 });
return { bus: b, hit: 0 };
},
@@ -124,7 +155,7 @@ const ink: Def = {
variants: ["plip", "double", "bloom"], level: -15, duckDb: 2,
use: "an ink drop landing (plip), a drop and its smaller echo (double), the drop that opens an ink bloom (bloom)",
make(c, v) {
- const { sr, r, P } = c, n = secs(sr, 3), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.3, f0 = c.j(1150, 0.12) * P, tau = c.j(0.04, 0.15);
+ const { sr, r, P } = c, n = secs(sr, 3.5), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.3, f0 = c.j(1150, 0.12) * P, tau = c.j(0.04, 0.15);
drop(c, b, 0, f0, tau, 1, p0);
if (v === "double") drop(c, b, secs(sr, c.j(0.085, 0.2)), f0 * c.j(1.35, 0.06), tau * 0.7, 0.42, p0 + 0.25);
if (v === "bloom") { // the ink spreads: a soft wet swell and a low round note under it
@@ -133,6 +164,7 @@ const ink: Def = {
b.add2(sw, sw2, secs(sr, 0.02), 0.5);
b.add(chirp(sr, secs(sr, 2.2), (t) => c.j(98, 0.04) * P * (1 - 0.06 * smooth(t / 0.6)), ad(0.05, 0.34)), secs(sr, 0.01), 0.22, 0);
}
+ punch(b, 0.3);
space(b, r, { rt60: v === "bloom" ? 1.1 : 0.6, mix: v === "bloom" ? 0.22 : 0.14, hp: 300 });
return { bus: b, hit: 0 };
},
@@ -242,6 +274,9 @@ const passBy = (c: Ctx, b: Bus, len: number, o: { air: number; tone: number; ton
const mono = air[0].map((x, i) => x * 0.75 + air[1][i] * 0.25);
b.add(mono, 0, 3.2, panAt);
b.add2(air[1], air[0], 0, 0.9);
+ // pre-attack air: the thin high edge of the moving air reaches the ear ~3 ms before its body
+ const edgeAir = filt(pink(r, N), sr, { hp: 5200 }); for (let i = 0; i < N; i++) edgeAir[i] *= amp(i / sr) * Math.pow(geo(i / sr).D, 3);
+ b.add(edgeAir, -secs(sr, 0.003), 0.55, panAt);
if (o.toneAmt > 0) { const t = white(r, N); sweep(t, sr, (tt) => o.tone * P * geo(tt).D, o.toneQ, "bp"); for (let i = 0; i < N; i++) t[i] *= amp(i / sr); b.add(t, 0, o.toneAmt, panAt); }
if (o.bodyAmt > 0) { const s = pink(r, N); sweep(s, sr, (t) => o.body * geo(t).D, 0.8, "lp"); for (let i = 0; i < N; i++) s[i] *= amp(i / sr); b.add(s, 0, o.bodyAmt, (i) => panAt(i) * 0.4); }
return secs(sr, tc);
@@ -314,7 +349,7 @@ const impact: Def = {
variants: ["boom", "soft", "bloom"], level: -9, duckDb: 6,
use: "the ONE big reveal (boom), a smaller landing (soft), the reveal with a tuned shimmer and a breath in before it (bloom)",
make(c, v) {
- const { sr, r, P } = c, soft = v === "soft", pre = v === "bloom" ? secs(sr, 0.28) : 0, n = pre + secs(sr, soft ? 3.5 : 5.5), b = new Bus(sr, n);
+ const { sr, r, P } = c, soft = v === "soft", pre = v === "bloom" ? secs(sr, 0.28) : 0, n = pre + secs(sr, soft ? 4.5 : 7.5), b = new Bus(sr, n);
// 1 sub drop, saturated so small speakers still hear its harmonics
const lo = c.j(soft ? 40 : 44, 0.04) * P, subTau = c.j(soft ? 0.32 : 0.6, 0.1), sub = chirp(sr, secs(sr, subTau * 8), (t) => lo + (soft ? 55 : 72) * P * Math.exp(-t / 0.07), ad(0.002, subTau));
b.add(sub.map((x) => Math.tanh(x * 1.8) / Math.tanh(1.8)), pre, 1, 0);
@@ -333,6 +368,7 @@ const impact: Def = {
b.add(modal(sr, n, ms), pre, 0.09, p);
});
}
+ punch(b, soft ? 0.25 : 0.2);
space(b, r, { rt60: soft ? 1.2 : 2.4, mix: soft ? 0.2 : 0.34, hp: 120, lp: 3500, predelay: 0.02, er: 0.35 });
return { bus: b, hit: pre };
},
@@ -342,7 +378,7 @@ const chime: Def = {
variants: ["sparkle", "bell", "glint"], level: -17, duckDb: 1.5,
use: "magic / success, tuned to the film's key: a rising pentatonic sparkle (sparkle), one bell (bell), a tiny glint on a highlight (glint)",
make(c, v) {
- const { sr, r } = c, n = secs(sr, v === "bell" ? 6 : v === "glint" ? 2 : 4), b = new Bus(sr, n), scale = PENTA[c.key!.minor ? "minor" : "major"];
+ const { sr, r } = c, n = secs(sr, v === "bell" ? 7 : v === "glint" ? 2.5 : 5.5), b = new Bus(sr, n), scale = PENTA[c.key!.minor ? "minor" : "major"];
if (v === "bell") {
b.add(modal(sr, n, glock(keyHz(c, 5) * c.P, 1.4, 1)), 0, 1, -0.1);
b.add(modal(sr, n, glock(keyHz(c, 6, 7) * c.P, 0.9, 1, 0.004)), 0, 0.3, 0.3);
@@ -411,6 +447,7 @@ const brick: Def = {
clack(c, b, 0, 0.45, p0, 1.08);
const at = secs(sr, c.j(0.024, 0.2)); clack(c, b, at, 1, p0, 0.94);
b.add(modal(sr, n, [{ f: c.j(380, 0.08) * P, tau: 0.012, a: 1, att: 0.0003 }]), at, 0.5, p0);
+ punch(b, 0.35);
space(b, r, { rt60: 0.35, mix: 0.08 });
return { bus: b, hit: at };
}
@@ -418,6 +455,7 @@ const brick: Def = {
let t = 0, gap = c.j(0.11, 0.2), g = 1; const k = 3 + Math.floor(r() * 3);
for (let q = 0; q < k; q++) { clack(c, b, secs(sr, t), g, clamp(p0 + (r() - 0.5) * 0.4, -1, 1), 0.9 + 0.2 * r()); t += gap; gap *= c.j(0.62, 0.1); g *= c.j(0.6, 0.15); }
} else clack(c, b, 0, 1, p0, 1);
+ punch(b, 0.35);
space(b, r, { rt60: 0.35, mix: 0.08 });
return { bus: b, hit: 0 };
},
@@ -501,7 +539,8 @@ export const renderSfx = (kind: SfxKind, o: SfxOpts = {}, sr = 48000): SfxSound
const need = sfxNeeds(kind, variant, o);
if (need.key && o.key === undefined) throw new Error(`sfx: ${kind}:${variant} is tuned and needs a key (opts.key, or in a plan: plan.key or plan.score = the film's piece); there is no default key`);
if (need.bpm && o.bpm === undefined) throw new Error(`sfx: ${kind}:${variant} is tempo-synced and needs a bpm (opts.bpm, or in a plan: plan.bpm or plan.score); there is no default tempo`);
- const c: Ctx = { sr, r, P: Math.pow(2, (o.pitch ?? 0) / 12), o, dir: o.dir ?? 1, key: o.key === undefined ? null : parseKey(o.key), bpm: o.bpm ?? NaN, j: (x, amt) => x * (1 + (r() * 2 - 1) * amt) };
+ const wobble = need.key ? 1 : 1 + (r() * 2 - 1) * 0.03; // +-3 % per trigger: a repeat never clones (never on a tuned sound)
+ const c: Ctx = { sr, r, P: Math.pow(2, (o.pitch ?? 0) / 12) * wobble, o, dir: o.dir ?? 1, key: o.key === undefined ? null : parseKey(o.key), bpm: o.bpm ?? NaN, j: (x, amt) => x * (1 + (r() * 2 - 1) * amt) };
const made = d.make(c, variant), [L, R] = finish(made.bus, made.hit);
const kL = kWeight(L, sr), kR = kWeight(R, sr), window = speakingWindow(kL, kR, sr), now = winLufs(kL, kR, window[0], window[1]);
let g = d.level + (r() * 2 - 1) + (o.gainDb ?? 0) - now;
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocab.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocab.ts
index 21563ab..3c90c73 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocab.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocab.ts
@@ -69,7 +69,7 @@ export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {
bass: { warm: { inst: "bass", role: "bass", gainDb: -2, opts: { drive: 1.4 } } },
},
fx: { clean: true, duck: { by: "kick", parts: ["chords", "counter"], depth: 0.38, release: 0.24 }, tape: { wowCents: 2.5, wowHz: 0.4, flutterCents: 0, flutterHz: 6, drive: 1.02 } },
- stemTargets: { kick: -14, snare: -20, hat: -28, bass: -18, chords: -21, lead: -16.5, counter: -24 }, calibrated: true,
+ stemTargets: { kick: -14.5, snare: -19, hat: -24.5, bass: -18.5, chords: -22, lead: -15.5, counter: -20 }, calibrated: true,
grooves: ["bounce", "halfTime", "broken", "skip", "pulse", "build"], moods: ["calm", "joy", "hopeful", "nostalgic", "wistful", "curious"],
harmony: { modes: ["major", "dorian", "lydian", "aeolian", "mixolydian"], qualities: "7ths, 9ths, 11ths and 13ths; add9; sus2/sus4 for air; avoid bare triads except on the landing",
tendencies: "loops of 2, 4 or 8 bars; ii-V motion, IV-iii-vi drifts, modal vamps (i-IV in dorian, I-II in lydian), borrowed iv or bVII for a wistful turn; the home chord arrives on a structural beat",
@@ -87,7 +87,7 @@ export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {
chords: { inst: "strings", role: "accomp", gainDb: -8, opts: { attack: 0.25, release: 0.5, bright: 1.3, width: 0.95, grid: true }, send: 0.3 },
lead: { inst: "strings", role: "melody", gainDb: -2, opts: { attack: 0.012, release: 0.15, bright: 1.8, width: 0.4, grid: true }, send: 0.25 },
counter: { inst: "fmBell", role: "color", gainDb: -6, opts: { ratio: 3.5 }, send: 0.4 },
- bass: { inst: "bass", role: "bass", gainDb: -3, opts: { drive: 2.4, grid: true } },
+ bass: { inst: "bass", role: "bass", gainDb: -3, opts: { kind: "synth", drive: 2.4, grid: true } },
kick: { inst: "kick", role: "drum", gainDb: 2, opts: { soft: 0.3, grid: true }, send: 0 },
snare: { inst: "snare", role: "drum", gainDb: 2, opts: { grid: true }, send: 0.4 },
ghost: { inst: "snare", role: "drum", gainDb: -2, opts: { rim: true, grid: true }, send: 0.2 },
@@ -97,7 +97,7 @@ export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {
},
alternates: { lead: { pluck: { inst: "softPluck", role: "melody", gainDb: 5, opts: { decay: 0.3, bright: 7000, delay: bassDelay(0.75), feedback: 0.3, delayMix: 0.25 }, send: 0.25 } }, bass: { sub: { inst: "sub", role: "bass", gainDb: -5, opts: { cut: 160 } } } },
fx: { clean: true, duck: { by: "kick", parts: ["chords", "arp", "counter"], depth: 0.55, release: 0.2 } },
- stemTargets: { kick: -12, snare: -18, hat: -26, perc: -27, bass: -16, chords: -22, lead: -16, arp: -21, counter: -24 }, calibrated: false,
+ stemTargets: { kick: -12.5, snare: -17, hat: -26, perc: -26, bass: -16, chords: -23, lead: -16, arp: -20.5, counter: -19.5 }, calibrated: false,
grooves: ["fourFloor", "broken", "build", "halfTime", "tension"], moods: ["drive", "triumph", "tension", "joy", "awe"],
harmony: { modes: ["aeolian", "dorian", "mixolydian", "major"], qualities: "triads and power voicings, sus2, add9; minor with a major IV (dorian) for lift", tendencies: "i-VI-III-VII, i-v-VI-IV, bVI-bVII-i climbs; long pedal tones under changing chords; a key lift of a step for the last chorus",
rhythm: "one chord per bar or per two bars; stabs on off-beats", voicing: "wide: root-fifth-octave low, tight triads above C4; the bass line is 8ths or offbeat", tension: "a pedal under a moving chord, a build that withholds the kick, a riser into a drop; release on the downbeat with everything" },
@@ -122,7 +122,7 @@ export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {
},
alternates: { lead: { piano: { inst: "piano", role: "melody", gainDb: 0, send: 0.4 }, bell: { inst: "fmBell", role: "melody", gainDb: -4, send: 0.5 }, celesta: { inst: "celesta", role: "melody", gainDb: 0, send: 0.5 } }, counter: { piano: { inst: "piano", role: "color", gainDb: -3, send: 0.4 } } },
fx: {},
- stemTargets: { chords: -18, bass: -19, lead: -17, counter: -22, arp: -21, kick: -16, snare: -24, hat: -32 }, calibrated: false,
+ stemTargets: { chords: -18.5, bass: -19.5, lead: -17, counter: -7.5, arp: -21.5, kick: -16.5, snare: -24, hat: -32 }, calibrated: false,
grooves: ["pulse", "tension", "build", "halfTime"], moods: ["awe", "triumph", "tension", "melancholy", "hopeful", "dread"],
harmony: { modes: ["aeolian", "harmonicMinor", "lydian", "major", "phrygian", "dorian"], qualities: "open fifths, add9, sus2/sus4, minor with a major IV; chromatic mediants (C to E, C to Ab) for awe",
tendencies: "slow harmonic rhythm (1-2 bars per chord); i-bVI-bVII-i for epic, i-iv-V for drama, lydian II for wonder, a pedal bass under moving chords for tension; big arrivals on chromatic mediants",
@@ -148,7 +148,7 @@ export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {
},
alternates: { lead: { pluck: { inst: "softPluck", role: "melody", gainDb: 5, opts: { decay: 0.8, bright: 3800, delay: bassDelay(1.5), feedback: 0.4, delayMix: 0.4 }, send: 0.7 }, vibes: { inst: "vibes", role: "melody", gainDb: 0, send: 0.6 } } },
fx: { clean: true, tape: { wowCents: 4, wowHz: 0.25, flutterCents: 0, flutterHz: 6, drive: 1.0 } },
- stemTargets: { chords: -19, bass: -22, lead: -20, counter: -25, arp: -24, kick: -20, hat: -32 }, calibrated: false,
+ stemTargets: { chords: -20, bass: -22, lead: -17.5, counter: -26.5, arp: -23.5, kick: -20.5, hat: -32 }, calibrated: false,
grooves: ["pulse", "brushes"], moods: ["awe", "calm", "hopeful", "tender", "dread"],
harmony: { modes: ["lydian", "major", "dorian", "majorPentatonic", "aeolian"], qualities: "maj7, add9, maj7#11, sus2, quartal stacks (4ths)", tendencies: "two-chord oscillations (I-II lydian, i-IV dorian), planing (the same shape moved by step), a pedal note held through changes",
rhythm: "slow: one chord per 2-4 bars", voicing: "wide and open, high register, no thirds low; let voices ring", tension: "a #11 or a 9 against the root; release by the melody settling on the fifth or the root" },
@@ -164,7 +164,7 @@ export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {
arp: { inst: "guitar", role: "accomp", gainDb: -4, send: 0.3 },
lead: { inst: "harp", role: "melody", gainDb: 2, send: 0.35 },
counter: { inst: "celesta", role: "color", gainDb: -3, send: 0.4 },
- bass: { inst: "bass", role: "bass", gainDb: -6, opts: { drive: 1.1 } },
+ bass: { inst: "bass", role: "bass", gainDb: -6, opts: { kind: "upright", drive: 1.1 } },
kick: { inst: "kick", role: "drum", gainDb: -4, opts: { soft: 1 }, send: 0.2 },
snare: { inst: "snare", role: "drum", gainDb: -6, opts: { rim: true }, send: 0.4 },
ghost: { inst: "snare", role: "drum", gainDb: -6, opts: { rim: true }, send: 0.4 },
@@ -173,7 +173,7 @@ export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {
},
alternates: { lead: { piano: { inst: "piano", role: "melody", gainDb: 0, send: 0.3 }, guitar: { inst: "guitar", role: "melody", gainDb: 2, send: 0.3 }, strings: { inst: "strings", role: "melody", gainDb: -2, opts: { attack: 0.2, release: 0.8 }, send: 0.4 } }, chords: { strings: { inst: "strings", role: "accomp", gainDb: -8, opts: { attack: 0.8, release: 1.2, bright: 0.7 }, send: 0.4 } } },
fx: {},
- stemTargets: { chords: -20, arp: -21, lead: -16, counter: -24, bass: -21, kick: -20, snare: -26, ghost: -28, hat: -30, perc: -30 }, calibrated: false,
+ stemTargets: { chords: -19.5, arp: -20.5, lead: -13, counter: -19.5, bass: -21, kick: -20.5, snare: -26, ghost: -24.5, hat: -30, perc: -30 }, calibrated: false,
grooves: ["brushes", "pulse", "shuffle"], moods: ["tender", "calm", "wistful", "nostalgic", "hopeful", "romantic"],
harmony: { modes: ["major", "mixolydian", "dorian", "majorPentatonic", "aeolian"], qualities: "triads, add9, sus2, slash chords with a walking bass (I - V/7 - vi)", tendencies: "I-V/7-vi-IV descents, bVII-IV-I (mixolydian), plagal IV-I endings, a relative minor detour",
rhythm: "one chord per bar in 6/8 or 3/4; two per bar in 4/4", voicing: "guitar-shaped: root-fifth-tenth, open strings ringing; piano in the middle, melody on top", tension: "a suspended 4th resolving, a IV minor (iv) borrowed for the ache; release plagal (IV-I)" },
@@ -198,7 +198,7 @@ export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {
},
alternates: { lead: { chip: { inst: "pulse", role: "melody", gainDb: -4, opts: { duty: 0.25 } }, pluck: { inst: "softPluck", role: "melody", gainDb: 5, opts: { decay: 0.2, bright: 6000 } }, bell: { inst: "fmBell", role: "melody", gainDb: -2 } }, bass: { tuba: { inst: "sub", role: "bass", gainDb: -4, opts: { cut: 220 } } } },
fx: { clean: true },
- stemTargets: { lead: -16, chords: -22, arp: -21, counter: -23, bass: -18, kick: -15, snare: -21, ghost: -26, hat: -28, perc: -29 }, calibrated: false,
+ stemTargets: { lead: -13, chords: -21, arp: -20, counter: -18.5, bass: -18, kick: -15.5, snare: -20, ghost: -26, hat: -24, perc: -29.5 }, calibrated: false,
grooves: ["skip", "shuffle", "bounce", "fourFloor"], moods: ["playful", "joy", "curious"],
harmony: { modes: ["major", "mixolydian", "majorPentatonic", "lydian", "blues"], qualities: "triads and 6ths, dominant 7ths, chromatic passing chords (a diminished between I and ii)", tendencies: "fast harmonic rhythm (2 chords a bar), I-vi-ii-V turnarounds, secondary dominants (V/V), a surprise bVI",
rhythm: "two chords per bar, on-beat stabs", voicing: "close, mid-high; the bass bounces root-fifth (oom-pah) or walks", tension: "a chromatic approach note, a held dominant with a pause; release with a cheeky button" },
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts
index 0fd49af..f06adda 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts
@@ -1,6 +1,7 @@
// The rest of the style vocabularies (vocab.ts has the type, the mood mapping and the first six).
// Same rule: sound, grooves, harmony language, melody rules, arrangement grammar. Never notes.
import type { StyleVocab, Voice, Slot } from "./vocab";
+import { LOFI_DUSTY } from "./lofiFx";
const V = (inst: Voice["inst"], role: Voice["role"], gainDb: number, opts?: Voice["opts"], send?: number): Voice => ({ inst, role, gainDb, ...(opts ? { opts } : {}), ...(send !== undefined ? { send } : {}) });
/** a drum kit at a level offset: soft (acoustic), tight (band), hard (electronic) */
@@ -9,20 +10,21 @@ const kit = (o: number, soft: number, extra: Partial<Record<Slot, Voice>> = {}):
hat: V("hat", "drum", 12 + o, { pan: 0.25 }, 0.1), perc: V("hat", "drum", 10 + o, { pan: -0.3 }, 0.15), ...extra,
});
const T = (x: Partial<Record<string, number>>) => x as Record<string, number>;
-const std = T({ kick: -14, snare: -20, ghost: -26, hat: -28, perc: -29, bass: -18, chords: -21, lead: -16.5, counter: -23, arp: -22 });
+// stemTargets are in the v2 stem meter (meter.stemRms: mid, 20 ms blocks, gated): converted at the sound-v2 merge from the v1
+// (left-channel, -80 dB floor) numbers by measuring each style on the legacy render it was set on, so the balance is the same.
export const VOCAB_MORE: StyleVocab[] = [
{ id: "musicBox", name: "music box", atmosphere: "small, bright, clockwork, innocent; plucked and never sustained", tempo: [100, 132], meters: ["12/8", "3/4", "6/8"], swing: [0.5, 0.5],
palette: { lead: V("musicBox", "melody", 0, { grid: true }), arp: V("musicBox", "accomp", -9, { grid: true }), bass: V("musicBox", "bass", -8, { grid: true }), counter: V("bell", "color", -4), chords: V("celesta", "accomp", -10) },
alternates: { lead: { celesta: V("celesta", "melody", 0), bell: V("fmBell", "melody", -4) } }, fx: {},
- stemTargets: T({ lead: -16, arp: -26, bass: -24, counter: -22, chords: -27 }), calibrated: false, grooves: [], moods: ["joy", "curious", "tender", "playful", "wistful", "eerie"],
+ stemTargets: T({ lead: -13.5, arp: -25, bass: -26, counter: -19.5, chords: -26.5 }), calibrated: false, grooves: [], moods: ["joy", "curious", "tender", "playful", "wistful", "eerie"],
harmony: { modes: ["major", "lydian", "dorian", "aeolian", "majorPentatonic"], qualities: "triads and sus2; a minor music box is a real (and uncanny) sound", tendencies: "any functional progression you write; plagal and deceptive turns read well; a whole-step lift for the payoff", rhythm: "one chord per bar", voicing: "melody C5-C7, bass C3-G3, arpeggio figures in between (you choose the figure)", tension: "an unresolved 4th or a borrowed iv; release on a clean tonic" },
melody: { range: "C5-C7", contour: "hooky, skipping", density: "more notes, never longer notes (no sustain)", motif: "a 3-5 note hook with a distinctive rhythm; restate it, answer it" },
arrangement: { shape: "melody -> +bass -> +arpeggio -> +octave sparkle -> bell on the final downbeat", transitions: "add a layer each phrase", endings: "a bell or a single plucked tonic" },
avoid: "sustained pads, long reverb tails, slow attacks (the ghost failure); see styles/music-box.md for the old recipe's numbers" },
{ id: "nocturne", name: "nocturne / solo piano", atmosphere: "intimate, expressive, late-night: one piano, rubato, pedal", tempo: [50, 76], meters: ["3/4", "6/8", "4/4"], swing: [0.5, 0.5],
palette: { lead: V("piano", "melody", 0), chords: V("piano", "accomp", 0), bass: V("piano", "bass", 0), counter: V("strings", "color", -10, { attack: 0.9, release: 1.4 }) },
- alternates: {}, fx: {}, stemTargets: T({ lead: -17, chords: -24, bass: -23, counter: -30 }), calibrated: false, grooves: [], moods: ["tender", "melancholy", "wistful", "romantic", "grief"],
+ alternates: {}, fx: {}, stemTargets: T({ lead: -15, chords: -23.5, bass: -24.5, counter: -30.5 }), calibrated: false, grooves: [], moods: ["tender", "melancholy", "wistful", "romantic", "grief"],
harmony: { modes: ["major", "aeolian", "harmonicMinor", "dorian"], qualities: "triads, 7ths, secondary dominants, borrowed iv, Neapolitan for grief", tendencies: "descending bass lines, circle-of-fifths sequences, deceptive V-vi before the last cadence", rhythm: "one chord per bar, two at cadences", voicing: "left hand broken chords spanning a 10th, no close thirds below C3", tension: "suspensions (4-3, 9-8), appoggiaturas on strong beats" },
melody: { range: "C4-C6", contour: "arch per phrase, peak about 2/3 through", density: "0.5-2 notes per beat", motif: "a leap then stepwise return; transform it (octave up, in the bass) at the climax" },
arrangement: { shape: "intro -> theme (question, answer) -> build -> hush -> coda", transitions: "a breath (caesura) before a sudden hush", endings: "a rolled tonic into the pedal" },
@@ -30,91 +32,94 @@ export const VOCAB_MORE: StyleVocab[] = [
{ id: "minimalist", name: "minimalist / pulse", atmosphere: "hypnotic, curious, clean: interlocking ostinatos that change slowly", tempo: [96, 144], meters: ["4/4", "12/8", "5/4", "7/8"], swing: [0.5, 0.5],
palette: { arp: V("marimba", "accomp", -3), lead: V("marimba", "melody", 1), bass: V("marimba", "bass", -1), counter: V("vibes", "color", -8, { trem: 4.5 }), chords: V("piano", "accomp", -8), kick: V("kick", "drum", -6, { soft: 1 }, 0.2), ghost: V("snare", "drum", -6, { rim: true }, 0.2), perc: V("hat", "drum", 0, undefined, 0.2) },
alternates: { arp: { piano: V("piano", "accomp", -4), pluck: V("softPluck", "accomp", 3, { decay: 0.2, bright: 4000 }) } }, fx: {},
- stemTargets: T({ arp: -20, lead: -17, bass: -21, counter: -27, chords: -26 }), calibrated: false, grooves: ["pulse"], moods: ["curious", "tension", "awe", "calm"],
+ stemTargets: T({ arp: -19, lead: -14, bass: -24, counter: -21, chords: -25.5 }), calibrated: false, grooves: ["pulse"], moods: ["curious", "tension", "awe", "calm"],
harmony: { modes: ["dorian", "lydian", "aeolian", "major", "mixolydian"], qualities: "open 5ths, add9, quartal stacks", tendencies: "a two-chord cycle for 8-16 bars, then one note changes", rhythm: "slow; the ostinato is the rhythm", voicing: "mid-register, interlocking; no doubled roots", tension: "phase shifts, added beats, a new bass note under the same pattern" },
melody: { range: "C4-C6", contour: "cells, not tunes", density: "2-4 onsets per beat in the ostinato", motif: "a 5-8 note cell; change ONE thing every 8-16 bars (add, drop, rotate)" },
arrangement: { shape: "additive: one layer at a time", transitions: "a change at least every 16 bars", endings: "subtractive, or a hard stop" }, avoid: "a big climax; a change more often than every 4 bars" },
{ id: "jazz", name: "jazz / swing", atmosphere: "loose, warm, clever: swing ride, walking bass, comping piano", tempo: [80, 200], meters: ["4/4", "3/4"], swing: [0.6, 0.67],
- palette: { chords: V("piano", "accomp", -4), lead: V("vibes", "melody", 0, { trem: 4 }), bass: V("bass", "bass", -2, { drive: 1.1 }), counter: V("woodwind", "color", -2, { reed: true }), ...kit(-3, 1) },
+ palette: { chords: V("piano", "accomp", -4), lead: V("vibes", "melody", 0, { trem: 4 }), bass: V("bass", "bass", -2, { kind: "upright", drive: 1.1 }), counter: V("woodwind", "color", -2, { reed: true }), ...kit(-3, 1) },
alternates: { lead: { piano: V("piano", "melody", 0), clarinet: V("woodwind", "melody", 0, { reed: true }), flute: V("woodwind", "melody", 0), brass: V("brass", "melody", -3, { bright: 0.8 }) } }, fx: {},
- stemTargets: T({ ...std, chords: -22, lead: -16, counter: -21, bass: -18, kick: -24, snare: -26, ghost: -28, hat: -26, perc: -30 }), calibrated: false, grooves: ["swing", "brushes", "shuffle"], moods: ["playful", "nostalgic", "romantic", "curious", "sensual", "mischief"],
+ stemTargets: T({ kick: -24.5, snare: -26, ghost: -24.5, hat: -23, perc: -30, bass: -18, chords: -21.5, lead: -13, counter: -18.5, arp: -22 }), calibrated: false, grooves: ["swing", "brushes", "shuffle"], moods: ["playful", "nostalgic", "romantic", "curious", "sensual", "mischief"],
harmony: { modes: ["major", "dorian", "mixolydian", "melodicMinor", "blues"], qualities: "7ths required; 9ths, 13ths, altered dominants (7b9, 7#11)", tendencies: "ii-V-I, iii-VI-ii-V turnarounds, tritone substitutions, backdoor bVII7-I", rhythm: "two chords a bar at turnarounds", voicing: "rootless shell voicings (3-7, 7-3) in the middle; the walking bass owns roots", tension: "altered dominants, chromatic approach chords; release on a 6/9 or maj7" },
melody: { range: "A3-C6", contour: "bebop lines: chord tones on beats, approach notes between", density: "swung 8ths with rests", motif: "a riff restated over changing chords (the chords change under it)" },
arrangement: { shape: "head (theme) -> solos -> head out", transitions: "a 2-bar break, trading 4s", endings: "a tag (the last 2 bars three times) or a ritard on a 6/9" }, avoid: "straight 8ths, triads only" },
{ id: "lullaby", name: "lullaby", atmosphere: "soft, rocking, safe", tempo: [56, 78], meters: ["3/4", "6/8"], swing: [0.5, 0.5],
palette: { lead: V("celesta", "melody", 0), arp: V("harp", "accomp", -8), bass: V("harp", "bass", -6), counter: V("musicBox", "color", -8), chords: V("strings", "accomp", -12, { attack: 1.0, release: 1.4, bright: 0.6 }) },
alternates: { lead: { musicBox: V("musicBox", "melody", 0), piano: V("piano", "melody", 0), flute: V("woodwind", "melody", -2) } }, fx: {},
- stemTargets: T({ lead: -17, arp: -24, bass: -25, counter: -27, chords: -28 }), calibrated: false, grooves: [], moods: ["tender", "calm"],
+ stemTargets: T({ lead: -15, arp: -23.5, bass: -27, counter: -20.5, chords: -28.5 }), calibrated: false, grooves: [], moods: ["tender", "calm"],
harmony: { modes: ["major", "majorPentatonic", "mixolydian"], qualities: "triads, add9, sus2", tendencies: "I-IV-I rocking, plagal cadences, a gentle ii", rhythm: "one chord per bar", voicing: "close, mid-high", tension: "almost none; a minor lullaby is flagged for the human check (tips into eerie)" },
melody: { range: "C4-C6", contour: "rocking stepwise, falling phrase ends", density: "1-2 notes per beat", motif: "a 2-bar rocking figure repeated with a changed ending" },
arrangement: { shape: "melody + gentle arpeggio, nothing percussive", transitions: "none needed", endings: "the tonic, soft, rolled" }, avoid: "drums, surprise, bright highs" },
{ id: "chiptune", name: "chiptune", atmosphere: "8-bit, bright, game-like: two pulses, a triangle, noise drums", tempo: [110, 170], meters: ["4/4", "6/8"], swing: [0.5, 0.56],
palette: { lead: V("pulse", "melody", 0, { duty: 0.25, grid: true }), arp: V("pulse", "accomp", -5, { duty: 0.125, pan: 0.25, grid: true }), bass: V("triangle", "bass", 1, { grid: true }), kick: V("noiseDrum", "drum", -2, { grid: true }), snare: V("noiseDrum", "drum", -4, { grid: true }), hat: V("noiseDrum", "drum", -10, { grid: true }) },
alternates: { lead: { square: V("pulse", "melody", -2, { duty: 0.5, grid: true }) } }, fx: {},
- stemTargets: T({ lead: -16, arp: -22, bass: -18, kick: -18, snare: -20, hat: -28 }), calibrated: false, grooves: ["fourFloor", "bounce", "shuffle", "skip"], moods: ["joy", "playful", "drive", "tension", "mischief"],
+ stemTargets: T({ lead: -16, arp: -20, bass: -18, kick: -17.5, snare: -20.5, hat: -28 }), calibrated: false, grooves: ["fourFloor", "bounce", "shuffle", "skip"], moods: ["joy", "playful", "drive", "tension", "mischief"],
harmony: { modes: ["major", "aeolian", "dorian", "mixolydian"], qualities: "triads; chords are faked by fast arpeggios", tendencies: "I-vi-IV-V, i-bVI-bVII, key changes up a step", rhythm: "one chord per bar", voicing: "arpeggio 16ths across an octave", tension: "a held dominant arpeggio, a pitch-bend-free chromatic climb" },
melody: { range: "C4-C7", contour: "hooky, leaping", density: "8ths and 16ths", motif: "a 1-bar hook, answered, sequenced" },
arrangement: { shape: "4 voices max: lead, arp, triangle bass, noise", transitions: "a drum fill, a key change", endings: "a fanfare button" }, avoid: "reverb, more than 4 voices, pads" },
{ id: "lofi", name: "dusty lo-fi hip-hop", atmosphere: "hazy, nostalgic, crackly: FM e-piano, vinyl, a lazy swung beat (the dusty cousin of lo-fi electronic)", tempo: [68, 90], meters: ["4/4"], swing: [0.55, 0.62],
- palette: { chords: V("ePiano", "accomp", -5, { detune: 5 }), lead: V("ePiano", "melody", 4, { detune: 6, width: 0.2 }), bass: V("bass", "bass", -2), counter: V("fmBell", "color", -8), ...kit(-6, 1, { hat: V("hat", "drum", -8, { pan: 0.25 }, 0.2) }) },
- alternates: { lead: { guitar: V("guitar", "melody", 2), flute: V("woodwind", "melody", -2) } }, fx: {},
- stemTargets: T({ ...std, chords: -20, lead: -17, bass: -19, kick: -17, snare: -22, hat: -30 }), calibrated: false, grooves: ["bounce", "halfTime", "shuffle"], moods: ["nostalgic", "calm", "wistful", "sensual"],
+ palette: { chords: V("ePiano", "accomp", -3.2, { detune: 5 }, 0.45), lead: V("ePiano", "melody", 5.4, { detune: 6, width: 0.2 }, 0.35), bass: V("bass", "bass", -1.3, undefined, 0.05), counter: V("fmBell", "color", -5.1, undefined, 0.6), ...kit(-6, 1, { hat: V("hat", "drum", -5.1, { pan: 0.25 }, 0.2) }) },
+ alternates: { lead: { guitar: V("guitar", "melody", 2, undefined, 0.35), flute: V("woodwind", "melody", -2, undefined, 0.35) } },
+ // the record: keys, counter and bass breathe with the kick; tape wow/flutter/drive (mood-scaled); the dusty chain (lofiFx.ts: sampler drums, warbly keys, tape colour, vinyl, tilt, room tone)
+ fx: { duck: { by: "kick", parts: ["chords", "counter", "bass"], depth: 0.35 }, tape: { wowCents: 6, wowHz: 0.7, flutterCents: 1.2, flutterHz: 8, drive: 1.35 }, lofi: LOFI_DUSTY },
+ stemTargets: T({ kick: -17.5, snare: -21, ghost: -22, hat: -26.5, perc: -29, bass: -19, chords: -19.5, lead: -16.5, counter: -18.5, arp: -22 }), calibrated: false, grooves: ["bounce", "halfTime", "shuffle"], moods: ["nostalgic", "calm", "wistful", "sensual"],
harmony: { modes: ["major", "dorian", "aeolian"], qualities: "maj9, m9, 13, m11", tendencies: "2-4 chord loops, ii-V drifts", rhythm: "1-2 chords a bar", voicing: "e-piano 4-note voicings", tension: "a borrowed iv" },
melody: { range: "C4-C6", contour: "lazy, behind the beat", density: "sparse", motif: "a 2-bar sampled-sounding phrase" },
arrangement: { shape: "4 or 8 bar loop with variations", transitions: "a filter or a drop-out", endings: "fade or tape stop" }, avoid: "using it when the brief says clean or upbeat (then use lofiElectronic)" },
{ id: "orchestral", name: "orchestral / epic", atmosphere: "big and heroic: brass theme, string ostinato engine, choir, timpani", tempo: [70, 140], meters: ["4/4", "3/4", "6/8"], swing: [0.5, 0.5],
palette: { lead: V("brass", "melody", 0, { attack: 0.06 }, 0.45), chords: V("strings", "accomp", -4, { attack: 0.5, release: 1.2 }, 0.5), arp: V("strings", "accomp", -3, { attack: 0.01, release: 0.1, bright: 1.2 }, 0.35), bass: V("strings", "bass", -2, { attack: 0.2, release: 0.8, bass: true, bright: 0.6 }, 0.35), counter: V("choir", "color", -2, { vowel: "a" }, 0.6), perc: V("timpani", "drum", 0, { pitch: 38 }, 0.5), kick: V("kick", "drum", 0, { soft: 1 }, 0.5), snare: V("snare", "drum", -3, undefined, 0.6), hat: V("hat", "drum", 4, undefined, 0.4) },
alternates: { lead: { strings: V("strings", "melody", 0, { attack: 0.15, release: 0.9, width: 0.4 }, 0.45), horn: V("brass", "melody", -2, { attack: 0.1, bright: 0.6 }, 0.5), flute: V("woodwind", "melody", -2, undefined, 0.5) }, counter: { flute: V("woodwind", "color", -3, undefined, 0.5), harp: V("harp", "color", 0, undefined, 0.5) } }, fx: {},
- stemTargets: T({ lead: -16, chords: -19, arp: -20, bass: -19, counter: -22, perc: -17, kick: -17, snare: -24, hat: -32 }), calibrated: false, grooves: ["epic", "build", "tension", "pulse"], moods: ["heroic", "triumph", "awe", "tension", "grief"],
+ stemTargets: T({ lead: -13, chords: -19.5, arp: -21, bass: -20, counter: -23, perc: -17.5, kick: -17.5, snare: -23, hat: -32 }), calibrated: false, grooves: ["epic", "build", "tension", "pulse"], moods: ["heroic", "triumph", "awe", "tension", "grief"],
harmony: { modes: ["major", "aeolian", "dorian", "mixolydian", "harmonicMinor"], qualities: "triads and power 5ths, sus4 resolving, major IV in minor", tendencies: "i-bVI-bIII-bVII, I-bVII-IV-I (mixolydian heroism), chromatic mediants for arrivals, a pedal under the build", rhythm: "one chord per 1-2 bars, faster into cadences", voicing: "brass in the middle in 3rds and 5ths, strings octaves above, bass in octaves", tension: "a long dominant pedal with the ostinato rising, sus4 held; release to the tonic major with everything" },
melody: { range: "brass G3-C5 (heroic), strings up to A6", contour: "a rising 4th or 5th then steps; big arcs", density: "long notes over a busy ostinato", motif: "a fanfare cell (rising 4th/5th + rhythm) developed: fragment it in the build, augment it at the climax" },
arrangement: { shape: "intro (ostinato alone) -> theme (strings) -> theme (brass) -> build -> tutti climax -> quiet coda", transitions: "timpani roll or snare build into downbeats; a bar of silence before the last statement", endings: "a big held chord with timpani, or a hard cut" }, avoid: "all families at once all the time; a brass lead above C6" },
{ id: "suspense", name: "suspense / horror", atmosphere: "unsettling, cold, withheld: low drones, heartbeat pulse, high bowed harmonics, stingers", tempo: [50, 110], meters: ["4/4", "5/4", "3/4"], swing: [0.5, 0.5],
palette: { chords: V("strings", "accomp", -6, { attack: 2.0, release: 2.5, bright: 0.5 }, 0.6), bass: V("sub", "bass", -6, { cut: 110 }), lead: V("bowedSolo", "melody", 0, { vibrato: 8 }, 0.6), counter: V("celesta", "color", -4, undefined, 0.7), arp: V("strings", "accomp", -6, { attack: 0.005, release: 0.08, bright: 0.8 }, 0.3), kick: V("kick", "drum", 0, { soft: 1 }, 0.4), ghost: V("snare", "drum", -4, { rim: true }, 0.5), perc: V("timpani", "drum", -2, { pitch: 33 }, 0.6), hat: V("hat", "drum", 0, undefined, 0.5) },
alternates: { counter: { choir: V("choir", "color", -4, { vowel: "u" }, 0.7), bell: V("fmBell", "color", -8, { ratio: 1.41 }, 0.7) }, lead: { choir: V("choir", "melody", -2, { vowel: "o" }, 0.6), cello: V("bowedSolo", "melody", 0, { cello: true, vibrato: 12 }, 0.5) } }, fx: {},
- stemTargets: T({ chords: -21, bass: -20, lead: -19, counter: -24, arp: -22, kick: -17, ghost: -27, perc: -18, hat: -32 }), calibrated: false, grooves: ["pulse", "tension", "epic"], moods: ["tension", "dread", "eerie"],
+ stemTargets: T({ chords: -21.5, bass: -20, lead: -19.5, counter: -19, arp: -23, kick: -17.5, ghost: -27, perc: -18.5, hat: -32 }), calibrated: false, grooves: ["pulse", "tension", "epic"], moods: ["tension", "dread", "eerie"],
harmony: { modes: ["phrygian", "locrian", "harmonicMinor", "wholeTone", "aeolian"], qualities: "clusters, minor 2nds, tritones, minor-major 7th, augmented triads", tendencies: "a pedal that never resolves, chromatic crawl up or down by semitone, i-bII (phrygian), sudden major chord a tritone away", rhythm: "static: one sound for 4-8 bars, then a jolt", voicing: "very low and very high with an empty middle", tension: "withhold resolution; a stinger (all voices, one hit) on the scare; silence right before it" },
melody: { range: "extremes: below C3 or above C6", contour: "a 2-3 note cell, often a semitone", density: "sparse, irregular", motif: "a semitone sigh or a tritone leap, repeated slower each time" },
arrangement: { shape: "drone -> pulse enters -> rising ostinato -> stinger on the hit -> silence -> aftermath drone", transitions: "cut to silence; a slow crescendo that stops short", endings: "unresolved: a held cluster, or a single low hit" }, avoid: "a major cadence, melody in the middle register, busy drums" },
{ id: "rock", name: "rock / band", atmosphere: "live-band energy: driven guitars, bass locked to the kick, a tight kit, maybe organ", tempo: [90, 160], meters: ["4/4", "6/8"], swing: [0.5, 0.52],
- palette: { chords: V("strings", "accomp", -6, { attack: 0.005, release: 0.08, bright: 2.0, width: 0.9, grid: true }, 0.2), lead: V("leadSynth", "melody", -2, { cut: 1400, env: 3000, square: 0.8, glide: 0.02 }, 0.25), bass: V("bass", "bass", -2, { drive: 2.2 }), counter: V("organ", "color", -6, { bright: 1.2 }, 0.3), ...kit(0, 0.5) },
- alternates: { chords: { organ: V("organ", "accomp", -4, { bright: 1.3 }, 0.25), piano: V("piano", "accomp", -3, undefined, 0.2) }, lead: { guitar: V("guitar", "melody", 2, undefined, 0.2) } }, fx: {},
- stemTargets: T({ ...std, chords: -19, lead: -16, bass: -17, counter: -23, kick: -13, snare: -17, hat: -27, perc: -26 }), calibrated: false, grooves: ["rock", "halfTime", "shuffle", "fourFloor"], moods: ["drive", "anger", "triumph", "joy", "heroic"],
+ // chords: an electric guitar (ensemble.ts, bridge pickup, clean DI) driven through the mix chain's amp + cab (mixDsp ampSim), not string stabs
+ palette: { chords: V("guitar", "accomp", 4, { kind: "electric", pickup: "bridge", drive: 1, amp: 5, width: 0.8, grid: true }, 0.2), lead: V("leadSynth", "melody", -2, { cut: 1400, env: 3000, square: 0.8, glide: 0.02 }, 0.25), bass: V("bass", "bass", -2, { kind: "pick", drive: 2.2 }), counter: V("organ", "color", -6, { bright: 1.2 }, 0.3), ...kit(0, 0.5) },
+ alternates: { chords: { strings: V("strings", "accomp", -6, { attack: 0.005, release: 0.08, bright: 2.0, width: 0.9, grid: true }, 0.2), organ: V("organ", "accomp", -4, { bright: 1.3 }, 0.25), piano: V("piano", "accomp", -3, undefined, 0.2) }, lead: { guitar: V("guitar", "melody", 17, { kind: "electric", pickup: "neck", drive: 1, amp: 3.5 }, 0.3) } }, fx: {},
+ stemTargets: T({ kick: -13.5, snare: -16.5, ghost: -26, hat: -23.5, perc: -25.5, bass: -17, chords: -15.5, lead: -16, counter: -18.5, arp: -22 }), calibrated: false, grooves: ["rock", "halfTime", "shuffle", "fourFloor"], moods: ["drive", "anger", "triumph", "joy", "heroic"],
harmony: { modes: ["mixolydian", "aeolian", "major", "blues", "dorian"], qualities: "power chords (root-5th-octave), triads, sus4", tendencies: "I-bVII-IV, i-bVI-bVII, riffs on the pentatonic, a chorus a 4th up", rhythm: "one chord per bar in verses, two in choruses", voicing: "power chords low (E2-E4), the bass doubling the root in 8ths", tension: "a riff held on the V, a stop before the chorus" },
melody: { range: "E3-A5", contour: "riff-based, pentatonic, strong beats", density: "8ths", motif: "a 1-2 bar riff that IS the song; the vocal-like lead answers it" },
arrangement: { shape: "riff intro -> verse -> pre -> chorus -> verse -> chorus -> bridge -> chorus x2", transitions: "a drum fill and a crash into every section", endings: "a big held last chord with a fill, or a stop on 1" }, avoid: "swing, soft attacks, long pads; the guitar tone here is an approximation: say so" },
{ id: "hipHop", name: "hip-hop / trap", atmosphere: "head-nod or dark trap: heavy 808, crisp clap, rolling hats, a moody loop on top", tempo: [70, 100], meters: ["4/4"], swing: [0.52, 0.6],
palette: { bass: V("sub", "bass", -4, { cut: 180 }), chords: V("piano", "accomp", -6, undefined, 0.3), lead: V("softPluck", "melody", 4, { decay: 0.5, bright: 3000, delay: "beats:0.75", feedback: 0.25, delayMix: 0.2 }, 0.3), counter: V("strings", "color", -8, { attack: 0.6, release: 1.0, bright: 0.7 }, 0.4), ...kit(0, 0.4, { hat: V("hat", "drum", 14, { pan: 0.15 }, 0.05) }) },
alternates: { lead: { bell: V("fmBell", "melody", -2, undefined, 0.3), flute: V("woodwind", "melody", -2, undefined, 0.3), choir: V("choir", "melody", -4, { vowel: "o" }, 0.5) }, chords: { pad: V("warmPad", "accomp", -3, { cut: 2000, attack: 0.4, release: 1.2 }, 0.3) } }, fx: { clean: true, duck: { by: "kick", parts: ["chords", "counter"], depth: 0.3, release: 0.2 } },
- stemTargets: T({ ...std, bass: -15, kick: -13, snare: -18, hat: -26, chords: -22, lead: -18, counter: -25 }), calibrated: false, grooves: ["trap", "bounce", "halfTime", "broken"], moods: ["drive", "calm", "nostalgic", "sensual", "anger", "tension"],
+ stemTargets: T({ kick: -13.5, snare: -17, ghost: -26, hat: -23, perc: -29.5, bass: -15, chords: -21.5, lead: -17.5, counter: -25.5, arp: -22 }), calibrated: false, grooves: ["trap", "bounce", "halfTime", "broken"], moods: ["drive", "calm", "nostalgic", "sensual", "anger", "tension"],
harmony: { modes: ["aeolian", "phrygian", "harmonicMinor", "dorian"], qualities: "minor triads, m7, dim, a single dark chord for 2 bars", tendencies: "2-chord minor loops, i-bVI, i-bII (phrygian menace), a melody over one chord", rhythm: "one chord per 1-2 bars", voicing: "piano or bells high, the 808 low with nothing between", tension: "the 808 sliding or dropping out; a switch-up after 8 bars" },
melody: { range: "C4-C6", contour: "short repeated figures", density: "sparse over busy hats", motif: "a 1-2 bar loop that repeats (the loop is the hook); vary it every 8 bars" },
arrangement: { shape: "intro (loop alone) -> 8-bar blocks with drops, switch-ups -> outro loop", transitions: "drop the drums for a bar, a hat roll into the downbeat", endings: "the loop alone, or a cut" }, avoid: "an 808 that owns everything below 150 Hz with no harmonics (phones): check stems" },
{ id: "house", name: "house / EDM", atmosphere: "euphoric, dancing, bright: four-on-the-floor, offbeat bass, stabs, a big pad", tempo: [118, 128], meters: ["4/4"], swing: [0.5, 0.54],
- palette: { chords: V("organ", "accomp", -6, { bright: 1.4, trem: 0 }, 0.3), bass: V("bass", "bass", -3, { drive: 2.0, grid: true }), lead: V("softPluck", "melody", 5, { decay: 0.25, bright: 7000, delay: "beats:0.75", feedback: 0.3, delayMix: 0.25, grid: true }, 0.25), counter: V("warmPad", "color", -4, { cut: 4000, attack: 0.3, release: 1.0 }, 0.4), arp: V("softPluck", "accomp", 3, { decay: 0.15, bright: 5000, grid: true }, 0.2), ...kit(1, 0.3, { hat: V("hat", "drum", 12, { pan: 0.2, grid: true }, 0.1) }) },
+ palette: { chords: V("organ", "accomp", -6, { bright: 1.4, trem: 0 }, 0.3), bass: V("bass", "bass", -3, { kind: "synth", drive: 2.0, grid: true }), lead: V("softPluck", "melody", 5, { decay: 0.25, bright: 7000, delay: "beats:0.75", feedback: 0.3, delayMix: 0.25, grid: true }, 0.25), counter: V("warmPad", "color", -4, { cut: 4000, attack: 0.3, release: 1.0 }, 0.4), arp: V("softPluck", "accomp", 3, { decay: 0.15, bright: 5000, grid: true }, 0.2), ...kit(1, 0.3, { hat: V("hat", "drum", 12, { pan: 0.2, grid: true }, 0.1) }) },
alternates: { chords: { pad: V("warmPad", "accomp", -3, { cut: 3000, attack: 0.2, release: 0.8 }, 0.35), piano: V("piano", "accomp", -3, undefined, 0.25) }, lead: { synth: V("leadSynth", "melody", -2, { cut: 2000, env: 5000 }, 0.3) } }, fx: { clean: true, duck: { by: "kick", parts: ["chords", "counter", "arp"], depth: 0.6, release: 0.18 } },
- stemTargets: T({ ...std, kick: -12, snare: -18, hat: -26, perc: -27, bass: -16, chords: -21, lead: -17, counter: -23, arp: -22 }), calibrated: false, grooves: ["fourFloor", "build", "broken"], moods: ["joy", "drive", "sensual", "hopeful"],
+ stemTargets: T({ kick: -12.5, snare: -17, ghost: -26, hat: -26, perc: -27, bass: -16, chords: -20, lead: -16.5, counter: -23.5, arp: -22 }), calibrated: false, grooves: ["fourFloor", "build", "broken"], moods: ["joy", "drive", "sensual", "hopeful"],
harmony: { modes: ["aeolian", "dorian", "major", "mixolydian"], qualities: "m7, m9, maj7 stabs; piano house triads", tendencies: "i-VI-III-VII, vi-IV-I-V, 2-chord dorian vamps; a long pedal in the build", rhythm: "one chord per bar or per 2 bars; stabs on offbeats", voicing: "stabs mid-register, the bass on the offbeat 8th", tension: "filter build + snare build + one beat of silence; release = the drop" },
melody: { range: "C4-C6", contour: "repetitive riffs", density: "8ths and 16ths", motif: "a 1-bar riff repeated 4-8 times with one change" },
arrangement: { shape: "intro (kick + hats) -> groove -> breakdown (pad + motif) -> build -> drop -> outro (kick)", transitions: "16- or 32-bar blocks; builds of 8", endings: "DJ-friendly: strip back to kick and hats" }, avoid: "swing, busy harmony, a quiet drop" },
{ id: "synthwave", name: "synthwave / retro", atmosphere: "neon-nostalgic, cinematic 80s: big gated snare, pulsing 8th bass, lush pads, a soaring lead", tempo: [80, 118], meters: ["4/4"], swing: [0.5, 0.5],
- palette: { chords: V("strings", "accomp", -6, { attack: 0.4, release: 1.4, bright: 1.1, width: 1 }, 0.5), bass: V("bass", "bass", -3, { drive: 1.8, grid: true }), lead: V("leadSynth", "melody", 0, { glide: 0.06, cut: 2200, env: 4000, square: 0.3 }, 0.4), arp: V("softPluck", "accomp", 3, { decay: 0.18, bright: 4500, delay: "beats:0.75", feedback: 0.35, delayMix: 0.3, grid: true }, 0.3), counter: V("fmBell", "color", -8, undefined, 0.5), ...kit(0, 0.5, { snare: V("snare", "drum", 5, undefined, 0.7) }) },
+ palette: { chords: V("strings", "accomp", -6, { attack: 0.4, release: 1.4, bright: 1.1, width: 1 }, 0.5), bass: V("bass", "bass", -3, { kind: "synth", drive: 1.8, grid: true }), lead: V("leadSynth", "melody", 0, { glide: 0.06, cut: 2200, env: 4000, square: 0.3 }, 0.4), arp: V("softPluck", "accomp", 3, { decay: 0.18, bright: 4500, delay: "beats:0.75", feedback: 0.35, delayMix: 0.3, grid: true }, 0.3), counter: V("fmBell", "color", -8, undefined, 0.5), ...kit(0, 0.5, { snare: V("snare", "drum", 5, undefined, 0.7) }) },
alternates: { chords: { pad: V("warmPad", "accomp", -2, { cut: 3200, attack: 0.6, release: 1.6, spread: 0.9 }, 0.5) }, lead: { brass: V("brass", "melody", -2, { bright: 1.3 }, 0.4) } }, fx: { clean: true, duck: { by: "kick", parts: ["chords", "arp"], depth: 0.35, release: 0.25 } },
- stemTargets: T({ ...std, kick: -13, snare: -17, hat: -28, bass: -17, chords: -21, lead: -16, arp: -22, counter: -25 }), calibrated: false, grooves: ["fourFloor", "halfTime", "rock", "build"], moods: ["nostalgic", "drive", "heroic", "romantic", "tension"],
+ stemTargets: T({ kick: -13.5, snare: -16.5, ghost: -26, hat: -28, perc: -29.5, bass: -17, chords: -22, lead: -16, counter: -20.5, arp: -22 }), calibrated: false, grooves: ["fourFloor", "halfTime", "rock", "build"], moods: ["nostalgic", "drive", "heroic", "romantic", "tension"],
harmony: { modes: ["aeolian", "dorian", "major", "lydian"], qualities: "minor triads, add9, maj7, sus2", tendencies: "i-bVI-bIII-bVII, vi-IV-I-V, a lydian II for the neon lift", rhythm: "one chord per bar", voicing: "wide pads, bass in driving 8ths on the root", tension: "a long build on the V with the arp rising; release with the gated snare" },
melody: { range: "A3-E6", contour: "soaring, long notes with glide", density: "long lead notes over a busy arp", motif: "a 2-bar singable lead phrase, stated then lifted an octave" },
arrangement: { shape: "pad intro -> bass + drums -> lead theme -> breakdown -> lead an octave up -> outro pad", transitions: "a tom-like fill (build), a drop-out bar", endings: "the pad alone, long tail" }, avoid: "trap hats, acoustic instruments, a dry mix" },
{ id: "world", name: "world / modal folk", atmosphere: "rooted, spacious, rhythmic: a drone, a modal melody on plucked strings or a flute, hand percussion cycles (write your own melody; name the tradition you draw on)", tempo: [60, 150], meters: ["7/8", "9/8", "12/8", "6/8", "4/4", "5/4"], swing: [0.5, 0.56],
palette: { lead: V("woodwind", "melody", 0, { breath: 0.1 }, 0.4), counter: V("harp", "color", -2, undefined, 0.35), arp: V("guitar", "accomp", -4, undefined, 0.3), chords: V("warmPad", "accomp", -8, { cut: 1600, attack: 1.2, release: 2.0, spread: 0.4 }, 0.4), bass: V("sub", "bass", -8, { cut: 180 }), kick: V("timpani", "drum", -2, { pitch: 43, decay: 0.5 }, 0.2), ghost: V("snare", "drum", -2, { rim: true }, 0.25), perc: V("hat", "drum", 8, { pan: -0.3 }, 0.2), hat: V("hat", "drum", 6, { pan: 0.3 }, 0.15) },
alternates: { lead: { pluck: V("guitar", "melody", 2, undefined, 0.3), marimba: V("marimba", "melody", 1, undefined, 0.3), reed: V("woodwind", "melody", 0, { reed: true }, 0.4), bowed: V("bowedSolo", "melody", 0, undefined, 0.4) } }, fx: {},
- stemTargets: T({ lead: -16, counter: -21, arp: -21, chords: -25, bass: -22, kick: -17, ghost: -24, perc: -28, hat: -30 }), calibrated: false, grooves: ["hand", "pulse", "brushes"], moods: ["calm", "joy", "curious", "mischief", "awe", "sensual"],
+ stemTargets: T({ lead: -14.5, counter: -7.5, arp: -20.5, chords: -25.5, bass: -22, kick: -17, ghost: -20, perc: -28, hat: -30 }), calibrated: false, grooves: ["hand", "pulse", "brushes"], moods: ["calm", "joy", "curious", "mischief", "awe", "sensual"],
harmony: { modes: ["dorian", "phrygian", "mixolydian", "aeolian", "majorPentatonic", "minorPentatonic", "harmonicMinor"], qualities: "a drone (tonic + 5th) more than chords; modal colour chords sparingly", tendencies: "modal: stay on the tonic drone, move the melody through the mode; a second drone a step away for contrast", rhythm: "the percussion cycle carries it; harmony changes rarely", voicing: "open 5ths, the drone low and wide", tension: "the mode's colour note held against the drone; release on the tonic" },
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: {},
- stemTargets: T({ chords: -19, lead: -17, bass: -21, counter: -26, arp: -24, perc: -20 }), calibrated: false, grooves: ["pulse"], moods: ["awe", "grief", "hopeful", "tender", "heroic"],
+ 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: -20, lead: -17, bass: -23, counter: -21.5, arp: -23.5, 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" },
arrangement: { shape: "a single voice -> full parts -> a swell -> a hush -> the final chord", transitions: "a fermata (breath) between phrases", endings: "a plagal amen or a picardy third, long tail" }, avoid: "fast rhythms, drums, choir as a lead above G5" },
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabTrim.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabTrim.ts
index d207919..baab5f7 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabTrim.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabTrim.ts
@@ -1,247 +1,234 @@
// GENERATED by `node tools/music.mjs calibrate`: per style, the gain trim (dB) that brings each palette
-// voice's stem to its target on a neutral test phrase. Calibrated styles (listened) are never trimmed.
+// voice's stem to its target on a neutral test phrase (stem meter v2: mid, gated). Calibrated (listened) styles keep their targets and get trims only; legacy scores never take a trim.
import type { Slot } from "./vocab";
export const VOCAB_TRIM: Record<string, Partial<Record<Slot, number>>> = {
+ lofiElectronic: {
+ chords: 2.4,
+ lead: -1.1,
+ counter: 5.5,
+ bass: 0.4,
+ kick: -3.1,
+ snare: -1.6,
+ hat: -0.5
+ },
drive: {
- chords: 5.3,
- lead: 7.4,
- counter: 12,
- bass: 3.1,
- kick: 0.5,
- snare: 8.5,
- arp: 1.2,
- perc: 8.3
+ chords: 6.7,
+ lead: 10.7,
+ counter: 16.8,
+ bass: 3,
+ kick: -1,
+ snare: 6.5,
+ arp: 1.8,
+ perc: 5.5
},
cinematic: {
- chords: 5.2,
- lead: 4.5,
- counter: 12,
- bass: 4.3,
- kick: -4.4,
- arp: 7.4
+ chords: 6.1,
+ lead: 6.9,
+ counter: 18,
+ bass: 2.4,
+ kick: -1.8,
+ arp: 8.5
},
ambient: {
chords: 2.5,
- lead: 1.3,
- counter: 0.8,
+ lead: 1.6,
+ counter: 1.2,
bass: -0.3,
- kick: -2.4,
- arp: 3.1
+ kick: -3,
+ arp: 1.6
},
folk: {
- chords: 12,
- lead: 12,
- counter: 11.2,
- bass: 1.6,
+ chords: 18,
+ lead: 14.7,
+ counter: 12.7,
+ bass: -1.2,
kick: -0.5,
- ghost: 9.4,
- arp: 12,
- perc: 12
+ ghost: 8.3,
+ arp: 16.5,
+ perc: 17.4
},
playful: {
- chords: 1.7,
- lead: 2.1,
- counter: 12,
- bass: 1.4,
- kick: 0.3,
- snare: 5.1,
- hat: 10.2,
- arp: 12,
- perc: 9.7
+ chords: 3.8,
+ lead: 4,
+ counter: 12.8,
+ bass: -1.4,
+ kick: -1.8,
+ snare: 3.2,
+ hat: 10.3,
+ arp: 13.3,
+ perc: 11.5
},
musicBox: {
- chords: 4.7,
- lead: 3.5,
- counter: 4.3,
- bass: 5,
- arp: 3
+ chords: 2.3,
+ lead: 2.9,
+ counter: 5,
+ bass: 6.3,
+ arp: 3.9
},
nocturne: {
- chords: 12,
- lead: 12,
- counter: 12,
- bass: 6.3
+ chords: 17.7,
+ lead: 14.1,
+ counter: 14.6,
+ bass: 6.5
},
minimalist: {
- chords: 12,
- lead: 2.1,
- counter: 11.7,
- bass: -3.9,
- arp: 2.5
+ chords: 18,
+ lead: 4,
+ counter: 15.9,
+ bass: -4.3,
+ arp: 3.1
},
jazz: {
- chords: 12,
- lead: 3.8,
- counter: 10.5,
- bass: 0.7,
- kick: 2.8,
- ghost: 10.5,
- hat: 12,
- perc: 11
+ chords: 18,
+ lead: 3.5,
+ counter: 12.7,
+ bass: -2,
+ kick: 0.2,
+ ghost: 10,
+ hat: 17.2,
+ perc: 8.5
},
lullaby: {
- chords: 3.5,
- lead: 5.3,
- counter: 12,
- bass: 12,
- arp: 12
+ chords: 4,
+ lead: 4.7,
+ counter: 18,
+ bass: 13,
+ arp: 16.4
},
chiptune: {
lead: 7.4,
- bass: -0.8,
- kick: 9.6,
+ bass: -0.7,
+ kick: 9.2,
snare: 10.7,
- arp: 12
+ arp: 13.2
},
lofi: {
- chords: 10.2,
- lead: 3.5,
- counter: 12,
- bass: -0.1,
- kick: 3.4,
- snare: 9.2,
- ghost: 12,
- hat: 12
+ chords: 9.3,
+ lead: 3.6,
+ counter: 18,
+ bass: -0.5,
+ kick: 0.2,
+ snare: 5.2,
+ ghost: 14.5,
+ hat: 18
},
orchestral: {
- chords: 3.6,
- lead: 9.2,
- counter: 0.3,
- bass: 2.9,
- kick: -3.3,
- snare: 8.2,
- arp: 7.4,
- perc: 4.2
+ chords: 4.5,
+ lead: 14.7,
+ counter: 0,
+ bass: 2.4,
+ kick: -5.6,
+ snare: 5.3,
+ arp: 7.7,
+ perc: 2.9
},
suspense: {
- chords: 5.2,
- lead: 7.3,
- counter: 12,
- bass: -0.1,
- kick: -3.4,
- arp: 8.7,
- perc: 10.4
+ chords: 5.8,
+ lead: 7.2,
+ counter: 13.5,
+ bass: 0,
+ kick: -0.3,
+ arp: 8.9,
+ perc: 8.2
},
rock: {
- chords: 5.1,
+ chords: 11.5,
lead: 11.9,
- counter: 12,
- bass: 1.2,
- kick: 1.2,
- snare: 8.2,
- hat: 8.6,
- perc: 7
+ counter: 18,
+ bass: 0.7,
+ kick: -1,
+ snare: 5.8,
+ hat: 8.4,
+ perc: 5.7
},
hipHop: {
- chords: 12,
- lead: -1.3,
- counter: 12,
- bass: 1.5,
- kick: 1.4,
- snare: 7.2,
- hat: 9.6,
- perc: 9.9
+ chords: 18,
+ lead: -1.1,
+ counter: 17.6,
+ bass: 1.6,
+ kick: -2.7,
+ snare: 5.7,
+ hat: 9.2,
+ perc: 7.7
},
house: {
- chords: 11.2,
+ chords: 12.7,
lead: -0.7,
- counter: 10.9,
- bass: 3.3,
- kick: 1.6,
- snare: 6.7,
- arp: 1.5,
- perc: 7.3
+ counter: 11.5,
+ bass: 3.5,
+ kick: 0.3,
+ snare: 4.8,
+ arp: 2,
+ perc: 4.1
},
synthwave: {
- chords: 3.9,
+ chords: 4.9,
lead: 11.7,
- counter: 12,
- bass: 2.7,
- kick: 1.4,
- snare: 6.7,
- arp: 1.1,
- perc: 6.2
+ counter: 16.7,
+ bass: 2.8,
+ kick: 1.2,
+ snare: 4.3,
+ arp: 1.2,
+ perc: 3.5
},
world: {
chords: 4.9,
- lead: 8.7,
- counter: 12,
- bass: -1.6,
- kick: 2.3,
- ghost: 11.5,
- arp: 12
+ lead: 9.5,
+ counter: 18,
+ bass: -1.5,
+ kick: 0.5,
+ ghost: 12.5,
+ arp: 16.7
},
choral: {
- chords: -7.9,
- lead: -3.1,
- counter: 12,
- bass: 12,
- arp: 12,
- perc: 9.5
+ chords: -7.7,
+ lead: -3.8,
+ counter: 16.8,
+ bass: 9.6,
+ arp: 14,
+ perc: 9.2
}
};
-/** Where a 12 dB trim could not reach the target (long-decaying plucks read low as active RMS), the target moves to where the voice sits. */
+/** Where an 18 dB trim could not reach the target (long-decaying plucks read low as active RMS), the target moves to where the voice sits. */
export const VOCAB_TARGET_FIX: Record<string, Partial<Record<Slot, number>>> = {
- drive: {
- counter: -3.3
- },
+ lofiElectronic: {},
+ drive: {},
cinematic: {
- counter: -14.7
+ counter: -8.9
},
ambient: {},
folk: {
- chords: -13,
- lead: -2.8,
- arp: -1.9,
- perc: -5.8
- },
- playful: {
- arp: -1.4
+ chords: -6.5
},
+ playful: {},
musicBox: {},
- nocturne: {
- chords: -6.3
- },
+ nocturne: {},
minimalist: {
- chords: -11.1
+ chords: -4.6
},
jazz: {
- chords: -10.5
+ chords: -4
},
lullaby: {
- counter: -4.7,
- bass: -1,
- arp: -4.3
- },
- chiptune: {
- arp: -1.1
+ counter: -1.2
},
+ chiptune: {},
lofi: {
- counter: -7.1,
- ghost: -1.1,
- hat: -13
+ counter: -2.4,
+ hat: -6.3
},
orchestral: {},
- suspense: {
- counter: -3
- },
+ suspense: {},
rock: {
- counter: -7.4
+ counter: -8.6
},
hipHop: {
- chords: -14.8,
- counter: -4.2
+ chords: -9.4
},
house: {},
- synthwave: {
- counter: -4.1
- },
+ synthwave: {},
world: {
- counter: -17.1,
- arp: -3.2
+ counter: -10.7
},
- choral: {
- counter: -4.5,
- arp: -2.3
- }
+ choral: {}
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/drums.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/drums.test.ts
new file mode 100644
index 0000000..71a28cd
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/drums.test.ts
@@ -0,0 +1,76 @@
+// DRUM KIT TESTS (music/drums.ts): the anti-MIDI checks from the music research (section 9) that a
+// kit can fail on its own, with no human: determinism, no two hits alike, velocity changes the
+// timbre (not just the level), open hats choke, pieces sit where the stage puts them, the low end
+// stays mono, GM notes and lane kinds pick the right piece, and the legacy kit is untouched.
+import { kitVoice, timpani, pieceOf, chokeTimes, KITS, type KitId } from "../src/canvas-core/music/drums";
+import { drumVoice, kick as legacyKick } from "../src/canvas-core/music/instruments";
+import { laneKind } from "../src/canvas-core/music/grooves";
+import type { Played } from "../src/canvas-core/music/perform";
+import { rng } from "../src/canvas-core/core";
+
+export const name = "drums";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const SR = 24000, hit = (t: number, v: number, p = 60, kind?: string): Played => ({ t, off: t + 0.2, p, v, role: "drum", kind, w: v });
+ const render = (inst: string, keys: Played[], kit: KitId, seed = 1, secs = 3, extra: Record<string, number | boolean | string> = {}) => kitVoice(inst, keys, SR, Math.round(secs * SR), { kit, grid: true, ...extra }, rng(seed), { choke: chokeTimes([{ inst, opts: { kit, ...extra }, keys }]) });
+ const seg = (x: Float32Array, t: number, ms: number) => x.subarray(Math.round(t * SR), Math.round(t * SR) + Math.round((ms / 1000) * SR));
+ const corr = (a: Float32Array, b: Float32Array) => { let ab = 0, aa = 0, bb = 0; for (let i = 0; i < a.length; i++) { ab += a[i] * b[i]; aa += a[i] * a[i]; bb += b[i] * b[i]; } return ab / Math.sqrt(aa * bb + 1e-30); };
+ const rms = (x: Float32Array) => { let s = 0; for (const v of x) s += v * v; return Math.sqrt(s / Math.max(1, x.length)); };
+ // spectral centroid by zero-crossing-free proxy: the share of energy in the first difference (a tilt meter)
+ const bright = (x: Float32Array) => { let d = 0, e = 0; for (let i = 1; i < x.length; i++) { d += (x[i] - x[i - 1]) ** 2; e += x[i] ** 2; } return d / (e + 1e-30); };
+ const finite = (o: { L: Float32Array; R: Float32Array }) => { let m = 0; for (const x of [o.L, o.R]) for (const v of x) { if (!Number.isFinite(v)) return false; m = Math.max(m, Math.abs(v)); } return m < 4; };
+
+ // 1. determinism, finite output, every piece of every kit sounds
+ const GM = [36, 38, 37, 40, 39, 42, 44, 46, 41, 45, 48, 49, 51, 53, 54, 56, 70, 61, 62, 64];
+ let silent: string[] = [], same = true, sane = true;
+ for (const kit of KITS) {
+ const keys = GM.map((p, i) => hit(i * 0.35, 0.8, p)), a = render("snare", keys, kit, 7, GM.length * 0.35 + 2), b = render("snare", keys, kit, 7, GM.length * 0.35 + 2);
+ same &&= a.L.every((v, i) => v === b.L[i]) && a.R.every((v, i) => v === b.R[i]); sane &&= finite(a);
+ GM.forEach((p, i) => { if (rms(seg(a.L, i * 0.35 + 0.02, 60)) + rms(seg(a.R, i * 0.35 + 0.02, 60)) < 1e-5) silent.push(`${kit}:${p}`); });
+ }
+ ok(same, "same keys + seed = identical samples, every kit");
+ ok(sane, "every kit renders finite, bounded output");
+ ok(silent.length === 0, `every GM piece of every kit sounds${silent.length ? ` (silent: ${silent.join(", ")})` : ""}`);
+
+ // 2. no clones: the same piece at the same velocity, eight times, never repeats a waveform. Clone score (research sec. 9):
+ // the mean correlation of a repeat with the first hit < 0.98 per piece, and no pair ever near-identical (< 0.998)
+ let worstMean = 0, worstMax = 0, worstAt = "";
+ for (const kit of KITS) for (const [inst, p] of [["kick", 60], ["snare", 60], ["hat", 60], ["hat", 46], ["snare", 39], ["snare", 45], ["hat", 51], ["hat", 70]] as [string, number][]) {
+ const keys = Array.from({ length: 8 }, (_, i) => hit(i * 0.5, 0.75, p)), o = render(inst, keys, kit, 3, 4.6), cs: number[] = [];
+ for (let i = 1; i < 8; i++) cs.push(corr(seg(o.L, 0, 80), seg(o.L, i * 0.5, 80)));
+ const mean = cs.reduce((a, b) => a + b, 0) / cs.length; if (mean > worstMean) { worstMean = mean; worstAt = `${kit} ${inst}/${p}`; } worstMax = Math.max(worstMax, ...cs);
+ }
+ ok(worstMean < 0.98 && worstMax < 0.998, `repeated hits never clone: worst mean correlation ${worstMean.toFixed(3)} (${worstAt}) < 0.98, closest pair ${worstMax.toFixed(3)} < 0.998`);
+
+ // 3. velocity changes the timbre: a hard snare / hat is brighter than a soft one (level-independent measure)
+ const vb = (inst: string, kit: KitId) => { const S = 48000, o = kitVoice(inst, [hit(0, 0.25), hit(1, 1)], S, S * 2, { kit, grid: true }, rng(5)), at = (t: number) => o.L.subarray(t * S, t * S + 0.12 * S); return [bright(at(0)), bright(at(1))]; };
+ const vbad = KITS.flatMap((kit) => (["snare", "hat", "kick"] as const).filter((i) => { const [s, h] = vb(i, kit); return !(h > s * 1.03); }).map((i) => `${kit} ${i}`));
+ ok(vbad.length === 0, `velocity -> brightness on kick, snare, hat of every kit${vbad.length ? ` (flat: ${vbad.join(", ")})` : ""}`);
+
+ // 4. choke: a closed hat stops an open hat
+ { const open = render("hat", [hit(0, 0.8, 46)], "acoustic", 2, 1.5), choked = render("hat", [hit(0, 0.8, 46), hit(0.3, 0.05, 44)], "acoustic", 2, 1.5);
+ const tail = (o: { L: Float32Array }) => rms(seg(o.L, 0.4, 300));
+ ok(tail(choked) < tail(open) * 0.05, `an open hat is choked by the pedal hat (tail ${(20 * Math.log10(tail(choked) / tail(open))).toFixed(0)} dB)`); }
+
+ // 5. the stage: hats right, ride and floor tom left, kick centred and mono in the lows
+ { const side = (inst: string, p: number) => { const o = render(inst, [hit(0, 0.8, p)], "acoustic", 4, 1.2); return 20 * Math.log10(rms(o.R) / rms(o.L)); };
+ const hr = side("hat", 42), rd = side("hat", 51), ft = side("snare", 41), kk = side("kick", 36);
+ ok(hr > 2 && rd < -2 && ft < -2 && Math.abs(kk) < 1, `stage: hat R ${hr.toFixed(1)} dB, ride ${rd.toFixed(1)}, floor tom ${ft.toFixed(1)}, kick ${kk.toFixed(1)}`);
+ const k = render("kick", [hit(0, 0.9, 36)], "acoustic", 4, 1), lo = (x: Float32Array) => { const y = new Float32Array(x.length); let z = 0; const a = 1 - Math.exp((-2 * Math.PI * 120) / SR); for (let i = 0; i < x.length; i++) { z += a * (x[i] - z); y[i] = z; } return y; };
+ const icc = corr(lo(k.L), lo(k.R)); ok(icc > 0.95, `kick below 120 Hz stays mono (ICC ${icc.toFixed(3)})`);
+ const cr = render("hat", [hit(0, 0.9, 49)], "acoustic", 4, 2.5), hi = corr(seg(cr.L, 0.05, 800), seg(cr.R, 0.05, 800)); ok(hi < 0.9, `a crash is wide (L/R correlation ${hi.toFixed(2)} < 0.9)`); }
+
+ // 6. notes pick pieces: GM pitch > the part's piece > the lane kind > the inst's own piece
+ ok(pieceOf({ p: 60 }, "hat", {}) === "hat" && pieceOf({ p: 60 }, "snare", { rim: true }) === "cross" && pieceOf({ p: 60, kind: "o" }, "hat", {}) === "open" && pieceOf({ p: 49 }, "snare", {}) === "crash" && pieceOf({ p: 60, kind: "ride" }, "hat", { piece: "shaker" }) === "shaker", "pieceOf: GM notes, part piece, kinds, inst defaults");
+ ok(laneKind({ family: "fourFloor" }, "snare") === "clap" && laneKind({ family: "swing" }, "hat") === "ride" && laneKind({ kick: ["C4:4"] }, "hat") === "hat", "lane kinds: a fourFloor snare lane is a clap, a swing hat lane a ride, written grooves keep their lanes");
+
+ // 7. timpani: pitched (energy peaks near the written note), a roll is many strokes, deterministic
+ { const t = timpani([hit(0, 0.8, 43)], SR, SR * 3, {}, rng(1)), f = 440 * Math.pow(2, (43 - 69) / 12), x = seg(t.L, 0.1, 500);
+ const mag = (hz: number) => { let c = 0, s = 0; for (let i = 0; i < x.length; i++) { c += x[i] * Math.cos((2 * Math.PI * hz * i) / SR); s += x[i] * Math.sin((2 * Math.PI * hz * i) / SR); } return Math.hypot(c, s); };
+ ok(mag(f) > 3 * mag(f * 1.25) && mag(f) > 3 * mag(f * 0.8), `timpani rings at its note (${f.toFixed(0)} Hz)`);
+ const a = timpani([{ ...hit(0, 0.8, 43), off: 2, kind: "roll" }], SR, SR * 3, {}, rng(1)), b = timpani([{ ...hit(0, 0.8, 43), off: 2, kind: "roll" }], SR, SR * 3, {}, rng(1));
+ ok(a.L.every((v, i) => v === b.L[i]) && rms(seg(a.L, 1.5, 200)) > 4 * rms(seg(t.L, 1.5, 200)), "a timpani roll sustains (many strokes), deterministically"); }
+
+ // 8. legacy: the frozen launch film's kit is the old voice, bit for bit
+ { const keys = [hit(0, 0.8), hit(0.5, 0.6)], a = drumVoice("kick", keys, SR, SR, { legacy: true }, rng(1)), b = legacyKick(keys, SR, SR, {});
+ ok(a.L.every((v, i) => v === b.L[i]), "legacy: true renders the original soft kit"); }
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/ensemble-check.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/ensemble-check.mjs
new file mode 100644
index 0000000..0911a72
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/ensemble-check.mjs
@@ -0,0 +1,178 @@
+#!/usr/bin/env node
+// Ensemble voices v2 (music/ensemble.ts): objective checks and the before/after listening set.
+// node tools/ensemble-check.mjs check tuning (cents), anti-clone, determinism, stereo, legacy bit-identity
+// node tools/ensemble-check.mjs calibrate stem RMS of every vocabulary slot that uses an ensemble voice, v2 vs legacy
+// node tools/ensemble-check.mjs track <voice> [opts-json] per-note pitch through a legato phrase (octave slips, level)
+// node tools/ensemble-check.mjs ref <voice> <opts-json> <midi> <file.wav> harmonic spectrum + decay vs a CC0 recording, v1 and v2
+// node tools/ensemble-check.mjs render <dir> before-*.mp3 (legacy) / after-*.mp3 (v2): a phrase per instrument + an ensemble passage
+import { strict as assert } from "node:assert";
+import { build } from "esbuild";
+import { join } from "node:path";
+import { writeFileSync, mkdirSync, unlinkSync } from "node:fs";
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+
+const dir = join(import.meta.dirname, "../src/canvas-core/music");
+const js = (await build({ stdin: { contents: 'export * from "./index"; export * as E from "./ensemble"; export { rng } from "../core";', resolveDir: dir, loader: "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 I = M.instruments, O = M.orchestra;
+const md5 = (L, R) => createHash("md5").update(Buffer.from(L.buffer, L.byteOffset, L.byteLength)).update(Buffer.from(R.buffer, R.byteOffset, R.byteLength)).digest("hex");
+const cmd = process.argv[2] ?? "check";
+
+// the voices by name: (keys, sr, n, opts, seed) -> {L, R}
+const VOICE = {
+ strings: (k, sr, n, o, s) => I.strings(k, sr, n, o, M.rng(s)), pizz: (k, sr, n, o, s) => I.strings(k, sr, n, { ...o, pizz: true }, M.rng(s)),
+ guitar: (k, sr, n, o, s) => I.pluck(k, sr, n, o, M.rng(s), "guitar"), harp: (k, sr, n, o, s) => I.pluck(k, sr, n, o, M.rng(s), "harp"),
+ bass: (k, sr, n, o) => I.bass(k, sr, n, o), brass: (k, sr, n, o) => O.brass(k, sr, n, o),
+ woodwind: (k, sr, n, o, s) => O.woodwind(k, sr, n, o, M.rng(s)), choir: (k, sr, n, o, s) => O.choir(k, sr, n, o, M.rng(s)), bowedSolo: (k, sr, n, o, s) => O.bowedSolo(k, sr, n, o, M.rng(s)),
+};
+const key = (t, p, d, v = 0.7) => ({ t, off: t + d, p, v, role: "melody", w: v });
+
+/** f0 by normalised autocorrelation around the expected period, parabolic peak; also flags an octave error. */
+const pitchOf = (x, sr, fExp, from, to) => {
+ const a = Math.round(from * sr), b = Math.round(to * sr), P = sr / fExp; let best = -1, bl = 0; const ac = (l) => { let s = 0, e1 = 0, e2 = 0; for (let i = a; i < b; i++) { s += x[i] * x[i + l]; e1 += x[i] * x[i]; e2 += x[i + l] * x[i + l]; } return s / Math.sqrt(e1 * e2 + 1e-20); };
+ for (let l = Math.floor(P * 0.85); l <= Math.ceil(P * 1.18); l++) { const c = ac(l); if (c > best) { best = c; bl = l; } }
+ const y0 = ac(bl - 1), y1 = best, y2 = ac(bl + 1), d = (y0 - y2) / (2 * (y0 - 2 * y1 + y2)), lag = bl + (Number.isFinite(d) ? d : 0);
+ const half = ac(Math.round(P / 2));
+ return { cents: 1200 * Math.log2(sr / lag / fExp), corr: best, octaveUp: half > best + 0.02 };
+};
+
+if (cmd === "check") {
+ const sr = 48000, rows = [];
+ // 1. tuning: sustained notes, vibrato off, mono mid (L+R)
+ const tune = [["strings", { vibrato: 0, attack: 0.1 }, [43, 55, 69, 81]], ["pizz", {}, [48, 60, 72]], ["bowedSolo", { vibrato: 0, attack: 0.08 }, [55, 62, 69, 76, 88]], ["bowedSolo", { vibrato: 0, cello: true }, [36, 43, 50, 57, 64]],
+ ["brass", { vibrato: 0 }, [48, 60, 70]], ["woodwind", { vibrato: 0 }, [62, 74, 86]], ["woodwind", { reed: true }, [52, 62, 74]], ["choir", { vibrato: 0, vowel: "a" }, [45, 57, 64, 72]],
+ ["guitar", {}, [40, 52, 64, 76]], ["guitar", { kind: "steel" }, [40, 64]], ["guitar", { kind: "electric" }, [45, 69]], ["harp", {}, [36, 60, 84]],
+ ["bass", {}, [28, 40, 52]], ["bass", { kind: "pick" }, [33, 45]], ["bass", { kind: "upright" }, [28, 43]], ["bass", { kind: "synth" }, [28, 40]]];
+ let worst = 0;
+ for (const [name, o, ps] of tune) for (const p of ps) {
+ const n = Math.round(1.6 * sr), r = VOICE[name]([key(0.05, p, 1.3, 0.7)], sr, n, o, 11), mid = new Float32Array(n); for (let i = 0; i < n; i++) mid[i] = r.L[i] + r.R[i];
+ const f = 440 * Math.pow(2, (p - 69) / 12), pl = name === "pizz" || name === "harp" || name === "guitar" || (name === "bass" && o.kind !== "synth"), m = pitchOf(mid, sr, f, pl ? 0.15 : 0.6, pl ? 0.45 : 1.1);
+ rows.push(`${name}${o.kind ? "/" + o.kind : o.cello ? "/cello" : o.reed ? "/reed" : ""} ${p}: ${m.cents >= 0 ? "+" : ""}${m.cents.toFixed(1)} c (r ${m.corr.toFixed(3)})${m.octaveUp ? " OCTAVE?" : ""}`);
+ worst = Math.max(worst, Math.abs(m.cents)); if (Math.abs(m.cents) > 10 || m.octaveUp) console.log(" TUNING " + rows[rows.length - 1]);
+ }
+ console.log(` tuning: ${rows.length} notes, worst |error| ${worst.toFixed(1)} c`); rows.forEach((x) => console.log(" " + x));
+ // 2. anti-clone: the same key twice, 2 s apart -> the two renders must differ (correlation < 0.98)
+ for (const [name, o] of [["strings", {}], ["pizz", {}], ["bowedSolo", {}], ["brass", {}], ["woodwind", {}], ["woodwind", { reed: true }], ["choir", {}], ["guitar", {}], ["harp", {}], ["bass", {}], ["bass", { kind: "upright" }], ["bass", { kind: "synth" }]]) {
+ const n = Math.round(4.2 * sr), W = Math.round(0.8 * sr), r = VOICE[name]([key(0.1, 60 - (name === "bass" ? 24 : 0), 0.8), key(2.1, 60 - (name === "bass" ? 24 : 0), 0.8)], sr, n, o, 5);
+ const a = r.L.subarray(Math.round(0.1 * sr), Math.round(0.1 * sr) + W), b = r.L.subarray(Math.round(2.1 * sr), Math.round(2.1 * sr) + W);
+ let s = 0, e1 = 0, e2 = 0; for (let i = 0; i < W; i++) { s += a[i] * b[i]; e1 += a[i] * a[i]; e2 += b[i] * b[i]; } const c = s / Math.sqrt(e1 * e2 + 1e-20);
+ const d1 = VOICE[name]([key(0.1, 60, 0.8)], sr, Math.round(1.5 * sr), o, 5), d2 = VOICE[name]([key(0.1, 60, 0.8)], sr, Math.round(1.5 * sr), o, 5);
+ assert.equal(md5(d1.L, d1.R), md5(d2.L, d2.R), `${name}: not deterministic`);
+ let bad = false; for (let i = 0; i < n; i++) if (!Number.isFinite(r.L[i]) || !Number.isFinite(r.R[i]) || Math.abs(r.L[i]) > 8) { bad = true; break; }
+ assert(!bad, `${name}: non-finite or runaway samples`);
+ console.log(` anti-clone ${name}${o.kind ? "/" + o.kind : o.reed ? "/reed" : ""}: repeat correlation ${c.toFixed(3)} ${c < 0.98 ? "ok" : "CLONE"}; deterministic; finite`);
+ assert(c < 0.98, `${name}: repeated notes are clones`);
+ }
+ // 3. per-band stereo (research doc section 9): decorrelated above 500 Hz (< 0.9), near-mono below 120 Hz (> 0.95) for the section voices
+ const band = (x, f, hp) => { const a = Math.exp(-2 * Math.PI * f / sr), y = new Float32Array(x.length); let z1 = 0, z2 = 0; for (let i = 0; i < x.length; i++) { z1 = (1 - a) * x[i] + a * z1; z2 = (1 - a) * z1 + a * z2; y[i] = hp ? x[i] - z2 : z2; } return y; };
+ const corr = (a, b) => { let s = 0, e1 = 0, e2 = 0; for (let i = 0; i < a.length; i++) { s += a[i] * b[i]; e1 += a[i] * a[i]; e2 += b[i] * b[i]; } return s / Math.sqrt(e1 * e2 + 1e-20); };
+ for (const [name, o, ps] of [["strings", {}, [48, 55, 64, 67, 72]], ["strings", { bass: true }, [36, 43]], ["choir", {}, [48, 55, 64, 72]], ["brass", {}, [55, 60, 64]]]) {
+ const n = Math.round(3 * sr), r = VOICE[name](ps.map((p) => key(0.1, p, 2.4, 0.7)), sr, n, o, 9), hi = corr(band(r.L, 500, true), band(r.R, 500, true)), lo = corr(band(r.L, 120, false), band(r.R, 120, false));
+ console.log(` stereo ${name}${o.bass ? "/bass" : ""}: corr >500 Hz ${hi.toFixed(2)} ${hi < 0.9 ? "ok" : "NARROW"}, <120 Hz ${lo.toFixed(2)} ${lo > 0.95 ? "ok" : "WIDE LOWS"}`);
+ }
+ // 4. legacy path: bit-identical to v1 for every voice (the v1 functions are unchanged; the flag routes to them)
+ { const k = [key(0.1, 60, 0.8), key(0.9, 64, 0.8)], mk = (legacy) => ({ title: "t", seed: 3, tail: 1, harmony: [], ...(legacy ? { legacy: true } : {}), plan: { style: "cinematic", tempo: 90, meter: "4/4", sections: [{ id: "a", bars: 1, mood: "calm", key: "C", mode: "major", melody: ["stepwise"], dyn: [0.6, 0.6] }] }, parts: Object.keys(VOICE).filter((x) => x !== "pizz").map((inst, i) => ({ id: inst + i, inst, role: "melody", notes: M.line(0, "C4:2 E4:2", { role: "melody", v: 0.7, bpb: 4 }) })) });
+ const a = M.renderPiece(mk(true), 24000, { stems: true, master: "none" }), b = M.renderPiece(mk(false), 24000, { stems: true, master: "none" });
+ for (const [id, [L]] of Object.entries(a.stems)) { assert.notEqual(md5(L, L), md5(b.stems[id][0], b.stems[id][0]), `${id}: piece.legacy must change the voice`); }
+ console.log(` legacy: Piece.legacy routes all ${Object.keys(a.stems).length} ensemble voices to v1 (launchLofi3 md5 is guarded by tools/music-unit.mjs)`); }
+}
+
+if (cmd === "calibrate") {
+ const SR = 24000, ENS = new Set(["strings", "guitar", "harp", "bass", "brass", "woodwind", "choir", "bowedSolo"]), out = [];
+ for (const v of Object.values(M.VOCAB)) {
+ const combos = [[null, null]]; for (const [slot, alts] of Object.entries(v.alternates ?? {})) for (const [nm, a] of Object.entries(alts)) if (ENS.has(a.inst)) combos.push([slot, nm]);
+ for (const [slot, nm] of combos) {
+ const mat = { ...M.testMaterial(v, { bars: 4 }), ...(slot ? { voices: { [slot]: nm } } : {}) };
+ let p; try { p = M.composePiece(mat); } catch { continue; }
+ const parts = p.parts.filter((x) => ENS.has(x.inst) && (!slot || x.id === slot)); if (!parts.length) continue;
+ const only = (x) => parts.some((q) => q.id === x.id);
+ const a = M.renderPiece(p, SR, { stems: true, master: "none", only }), b = M.renderPiece({ ...p, legacy: true }, SR, { stems: true, master: "none", only });
+ for (const x of parts) { const nw = M.stemRms(...a.stems[x.id], SR), old = M.stemRms(...b.stems[x.id], SR); out.push({ style: v.id, slot: x.id, alt: nm, inst: x.inst, kind: x.opts?.kind ?? (x.opts?.reed ? "reed" : x.opts?.cello ? "cello" : ""), d: nw - old });
+ console.log(` ${v.id.padEnd(15)} ${x.id.padEnd(8)} ${(nm ?? "").padEnd(9)} ${x.inst.padEnd(10)} ${String(out[out.length - 1].kind).padEnd(8)} v2-legacy ${(nw - old >= 0 ? "+" : "") + (nw - old).toFixed(1)} dB`); }
+ }
+ }
+ const by = {}; for (const r of out) (by[r.inst + (r.kind ? "/" + r.kind : "")] ??= []).push(r.d);
+ console.log(" median per voice:"); for (const [k, ds] of Object.entries(by)) { ds.sort((a, b) => a - b); console.log(` ${k.padEnd(18)} ${ds[Math.floor(ds.length / 2)].toFixed(1)} dB (n ${ds.length}, ${ds[0].toFixed(1)}..${ds[ds.length - 1].toFixed(1)})`); }
+}
+
+if (cmd === "render") {
+ const outDir = process.argv[3]; if (!outDir) throw new Error("render <dir>"); mkdirSync(outDir, { recursive: true });
+ const SR = 48000, L = (t, s, role = "melody", v = 0.7, bpb = 4) => M.line(t, s, { role, v, bpb });
+ const piece = (title, style, tempo, parts, bars, tail = 2.5) => ({ title, seed: 7, tail, harmony: [], plan: { style, tempo, meter: "4/4", sections: [{ id: "a", bars, mood: "calm", key: "C", mode: "major", melody: ["stepwise"], dyn: [0.62, 0.7] }] }, parts });
+ const P = (id, inst, notes, opts = {}, extra = {}) => ({ id, inst, role: notes[0]?.role ?? "melody", notes, opts, send: 0.5, ...extra });
+ const chords = (v = 0.6) => L(0, "[C4 E4 G4]:4 | [A3 C4 E4]:4 | [F3 A3 C4 F4]:4 | [G3 B3 D4 G4]:4", "accomp", v);
+ const mel = (oct = 5, v = 0.72) => L(0, `E${oct}:1.5 D${oct}:.5 C${oct}:1 G${oct - 1}:1 | A${oct - 1}:2 C${oct}:1 E${oct}:1 | F${oct}:1.5 E${oct}:.5 D${oct}:1 C${oct}:1 | D${oct}:3 r:1`, "melody", v);
+ const legato = (oct = 5, v = 0.7) => L(0, `G${oct - 1}:1 C${oct}:1 E${oct}:1 G${oct}:1 | F${oct}:2 E${oct}:1 D${oct}:1 | C${oct}:1.5 D${oct}:.5 E${oct}:1 A${oct - 1}:1 | B${oct - 1}:3 r:1`, "melody", v);
+ const bassLine = (v = 0.8) => L(0, "C2:1 C2:.5 G2:.5 C3:1 B2:1 | A1:1 A1:.5 E2:.5 A2:1 G2:1 | F1:1 F1:.5 C2:.5 F2:1 E2:1 | G1:1 G1:.5 D2:.5 G2:1 B1:1", "bass", v);
+ const walk = (v = 0.75) => L(0, "C2:1 E2:1 G2:1 A2:1 | A1:1 C2:1 E2:1 G2:1 | F1:1 A1:1 C2:1 D2:1 | G1:1 B1:1 D2:1 F2:1", "bass", v);
+ const arp = (v = 0.6) => L(0, ["C3 G3 C4 E4 G4 E4 C4 G3", "A2 E3 A3 C4 E4 C4 A3 E3", "F2 C3 F3 A3 C4 A3 F3 C3", "G2 D3 G3 B3 D4 B3 G3 D3"].map((b) => b.split(" ").map((x) => x + ":.5").join(" ")).join(" | "), "accomp", v);
+ const strum = (v = 0.65) => { const out = []; ["C3 E3 G3 C4 E4", "A2 E3 A3 C4 E4", "F2 C3 F3 A3 C4", "G2 D3 G3 B3 D4"].forEach((c, b) => [0, 1.5, 2, 3].forEach((beat, j) => c.split(" ").forEach((nm, s) => out.push({ ...L(0, `${nm}:4`, "accomp", v * (j ? 0.8 : 1))[0], t: b * 4 + beat + s * 0.035, d: j === 3 ? 1 : j === 0 ? 1.5 : 1 })))); return out; };
+ const stacc = (v = 0.6) => L(0, ["C4 E4 G4 E4 C4 E4 G4 C5", "A3 C4 E4 C4 A3 C4 E4 A4", "F3 A3 C4 A3 F3 A3 C4 F4", "G3 B3 D4 B3 G3 B3 D4 G4"].map((b) => b.split(" ").map((x) => x + ":.5").join(" ")).join(" | "), "accomp", v);
+ const SET = [
+ ["strings-section", "orchestral", 72, [P("chords", "strings", chords(), { attack: 0.5, release: 1.2 }, { gainDb: -4 }), P("low", "strings", L(0, "C3:4 | A2:4 | F2:4 | G2:4", "bass", 0.65), { attack: 0.5, release: 1.2, bass: true, bright: 0.6 }, { gainDb: -4 }), P("lead", "strings", mel(5), { attack: 0.15, release: 0.9, width: 0.4 })]],
+ ["strings-spiccato", "orchestral", 96, [P("arp", "strings", stacc(), { attack: 0.005, release: 0.08, bright: 1.2 })]],
+ ["strings-pizzicato", "orchestral", 96, [P("arp", "strings", stacc(), { attack: 0.005, release: 0.08, pizz: true })], { beforeOpts: { pizz: false } }],
+ ["solo-violin", "suspense", 66, [P("lead", "bowedSolo", legato(5), { vibrato: 22 })]],
+ ["solo-cello", "suspense", 60, [P("lead", "bowedSolo", legato(3), { cello: true, vibrato: 12 })]],
+ ["brass-trumpet", "orchestral", 88, [P("lead", "brass", mel(5, 0.78), { attack: 0.06 })]],
+ ["brass-horns", "orchestral", 72, [P("chords", "brass", chords(0.62), { attack: 0.1, bright: 0.6 }), P("low", "brass", L(0, "C3:4 | A2:4 | F2:4 | G2:4", "bass", 0.7), { attack: 0.08 })]],
+ ["flute", "orchestral", 80, [P("lead", "woodwind", legato(5), {})]],
+ ["clarinet", "jazz", 96, [P("lead", "woodwind", mel(4), { reed: true })]],
+ ["choir-ah", "choral", 60, [P("chords", "choir", L(0, "[C3 G3 E4 C5]:4 | [A2 E3 C4 A4]:4 | [F2 C3 A3 F4]:4 | [G2 D3 B3 G4]:4", "accomp", 0.62), { vowel: "a", attack: 0.5 })]],
+ ["choir-lead-oh", "choral", 66, [P("lead", "choir", legato(5, 0.66), { vowel: "o", attack: 0.25, width: 0.3 })]],
+ ["choir-morph-uoa", "choral", 60, [P("chords", "choir", L(0, "[C3 G3 E4 C5]:8 | [F2 C3 A3 F4]:8", "accomp", 0.6, 8), { vowel: "uoa", attack: 0.6 })], { beforeOpts: { vowel: "u" } }],
+ ["guitar-nylon", "world", 84, [P("arp", "guitar", arp(), {})]],
+ ["guitar-steel", "world", 90, [P("chords", "guitar", strum(), { kind: "steel" })]],
+ ["guitar-electric", "lofi", 84, [P("lead", "guitar", mel(4, 0.7), { kind: "electric" }), P("chords", "guitar", L(0, "[C3 G3 B3 E4]:2 r:2 | [A2 G3 C4 E4]:2 r:2 | [F2 E3 A3 C4]:2 r:2 | [G2 F3 B3 D4]:2 r:2", "accomp", 0.55), { kind: "electric" }, { gainDb: -5 })]],
+ ["harp", "cinematic", 72, [P("arp", "harp", arp(0.62), {})]],
+ ["bass-finger", "lofi", 88, [P("bass", "bass", bassLine(), {})]],
+ ["bass-pick", "rock", 104, [P("bass", "bass", L(0, "C2:.5 C2:.5 C2:.5 C2:.5 G1:.5 G1:.5 A1:.5 B1:.5 | A1:.5 A1:.5 A1:.5 A1:.5 E2:.5 E2:.5 G2:.5 E2:.5 | F1:.5 F1:.5 F1:.5 F1:.5 C2:.5 C2:.5 D2:.5 E2:.5 | G1:.5 G1:.5 G1:.5 G1:.5 D2:.5 B1:.5 A1:.5 G1:.5", "bass", 0.8), { kind: "pick", drive: 2.2 })]],
+ ["bass-upright", "jazz", 120, [P("bass", "bass", walk(), { kind: "upright" })]],
+ ["bass-synth", "synthwave", 100, [P("bass", "bass", L(0, ["C2 C2 C3 C2 G1 G1 A1 B1", "A1 A1 A2 A1 E2 E2 G2 E2", "F1 F1 F2 F1 C2 C2 D2 E2", "G1 G1 G2 G1 D2 B1 A1 G1"].map((b) => b.split(" ").map((x) => x + ":.5").join(" ")).join(" | "), "bass", 0.8), { kind: "synth", drive: 2.0 })]],
+ ["ensemble", "cinematic", 72, [
+ P("pad", "strings", chords(0.55), { attack: 0.7, release: 1.4 }, { gainDb: -6 }), P("low", "strings", L(0, "C3:4 | A2:4 | F2:4 | G2:4", "bass", 0.6), { attack: 0.6, release: 1.4, bass: true, bright: 0.6 }, { gainDb: -5 }),
+ P("lead", "woodwind", mel(5, 0.7), {}, { gainDb: -1 }), P("horns", "brass", L(0, "r:2 [E4 G4]:2 | r:2 [E4 A4]:2 | r:2 [F4 A4]:2 | [D4 G4]:3 r:1", "color", 0.55), { attack: 0.12, bright: 0.6 }, { gainDb: -7 }),
+ P("harp", "harp", arp(0.5), {}, { gainDb: -6 }), P("choir", "choir", L(0, "r:4 | r:4 | [A4 C5]:4 | [B4 D5]:4", "color", 0.5), { vowel: "o", attack: 0.6 }, { gainDb: -8 })]],
+ ];
+ const wav = (path, a, b) => { const n = a.length, d = Buffer.alloc(n * 8), h = Buffer.alloc(44); for (let i = 0; i < n; i++) { d.writeFloatLE(a[i], i * 8); d.writeFloatLE(b[i], i * 8 + 4); }
+ h.write("RIFF", 0); h.writeUInt32LE(36 + d.length, 4); h.write("WAVEfmt ", 8); h.writeUInt32LE(16, 16); h.writeUInt16LE(3, 20); h.writeUInt16LE(2, 22); h.writeUInt32LE(SR, 24); h.writeUInt32LE(SR * 8, 28); h.writeUInt16LE(8, 32); h.writeUInt16LE(32, 34); h.write("data", 36); h.writeUInt32LE(d.length, 40); writeFileSync(path, Buffer.concat([h, d])); };
+ const only = process.argv[4] ? new Set(process.argv[4].split(",")) : null;
+ for (const [name, style, tempo, parts, extra = {}] of SET) {
+ if (only && !only.has(name)) continue;
+ const bars = 4, pc = piece(name, style, tempo, parts, bars);
+ for (const which of ["before", "after"]) {
+ const p = which === "after" ? pc : { ...pc, legacy: true, parts: pc.parts.map((x) => ({ ...x, opts: { ...x.opts, ...(extra.beforeOpts ?? {}) } })) };
+ const t0 = Date.now(), r = M.renderPiece(p, SR), f = join(outDir, `${which}-${name}`);
+ wav(f + ".wav", r.L, r.R); execFileSync("ffmpeg", ["-v", "error", "-y", "-i", f + ".wav", "-c:a", "libmp3lame", "-b:a", "224k", f + ".mp3"]); unlinkSync(f + ".wav");
+ console.log(` ${which}-${name}.mp3 ${(r.L.length / SR).toFixed(1)} s ${M.loudness([r.L, r.R], SR).integrated.toFixed(1)} LUFS (${Date.now() - t0} ms)`);
+ }
+ }
+}
+
+if (cmd === "track") {
+ const sr = 48000, b = 60 / 66, name = process.argv[3] ?? "bowedSolo", o = JSON.parse(process.argv[4] ?? "{}"), oct = o.cello ? 3 : 5;
+ const keys = M.line(0, `G${oct - 1}:1 C${oct}:1 E${oct}:1 G${oct}:1 | F${oct}:2 E${oct}:1 D${oct}:1 | C${oct}:1.5 D${oct}:.5 E${oct}:1 A${oct - 1}:1 | B${oct - 1}:3 r:1`, { role: "melody", v: 0.7, bpb: 4 }).map((x) => key(0.2 + x.t * b, x.p, x.d * b, x.v));
+ const n = Math.round((keys[keys.length - 1].off + 1) * sr), r = VOICE[name](keys.map((k) => ({ ...k, v: o._v ?? k.v })), sr, n, o, o._seed ?? 3), x = new Float32Array(n); for (let i = 0; i < n; i++) x[i] = r.L[i] + r.R[i];
+ for (const k of keys) {
+ const a = Math.round((k.t + Math.min(0.12, (k.off - k.t) * 0.3)) * sr), e = Math.round((k.off - 0.03) * sr), P = sr / (440 * 2 ** ((k.p - 69) / 12));
+ const ac = (l) => { let s = 0, e1 = 0, e2 = 0; for (let i = a; i < e; i++) { s += x[i] * x[i + l]; e1 += x[i] ** 2; e2 += x[i + l] ** 2; } return s / Math.sqrt(e1 * e2 + 1e-20); };
+ let best = -2, bl = 0; for (let l = Math.floor(P / 2.3); l <= Math.ceil(P * 2.3); l++) { const c = ac(l); if (c > best + 0.03) { best = c; bl = l; } }
+ let rms = 0; for (let i = a; i < e; i++) rms += x[i] ** 2; rms = Math.sqrt(rms / (e - a));
+ console.log(` ${name} p ${k.p}: period ${bl} vs ${P.toFixed(1)} (${(1200 * Math.log2(bl / P)).toFixed(0)} c) r ${best.toFixed(2)} ${(20 * Math.log10(rms)).toFixed(1)} dB`);
+ }
+}
+
+if (cmd === "ref") {
+ const [name, oj, midiS, file] = process.argv.slice(3), o = JSON.parse(oj), p = Number(midiS), sr = 48000, f = 440 * 2 ** ((p - 69) / 12);
+ const raw = execFileSync("ffmpeg", ["-v", "error", "-i", file, "-ac", "1", "-ar", String(sr), "-f", "f32le", "-"], { maxBuffer: 1 << 28 }), ref = new Float32Array(raw.buffer, raw.byteOffset, raw.length / 4);
+ const n = Math.round(3 * sr), mk = (legacy) => { const r = VOICE[name]([key(0.05, p, 2.5, 0.6)], sr, n, { ...o, ...(legacy ? { legacy: true } : {}) }, 4), x = new Float32Array(n); for (let i = 0; i < n; i++) x[i] = r.L[i] + r.R[i]; return x; };
+ const prof = (x) => { let pk = 0; for (const v of x) pk = Math.max(pk, Math.abs(v)); let i0 = 0; while (i0 < x.length && Math.abs(x[i0]) < pk * 0.03) i0++;
+ const amp = (h, a, b) => { let re = 0, im = 0; const w = (2 * Math.PI * f * h) / sr; for (let i = a; i < b && i < x.length; i++) { const hn = 0.5 - 0.5 * Math.cos((2 * Math.PI * (i - a)) / (b - a)); re += x[i] * hn * Math.cos(w * i); im += x[i] * hn * Math.sin(w * i); } return Math.hypot(re, im) + 1e-12; };
+ const a = i0 + Math.round(0.05 * sr), b = i0 + Math.round(0.35 * sr), h1 = amp(1, a, b), spec = Array.from({ length: 10 }, (_, k) => 20 * Math.log10(amp(k + 1, a, b) / h1));
+ const e = (t0) => 20 * Math.log10(amp(1, i0 + Math.round(t0 * sr), i0 + Math.round((t0 + 0.2) * sr))), decay = (e(0.1) - e(0.9)) / 0.8;
+ return { spec, decay }; };
+ const R = prof(ref), A = prof(mk(true)), B = prof(mk(false)), dist = (X) => X.spec.slice(1).reduce((s, v, i) => s + Math.abs(Math.max(v, -60) - Math.max(R.spec[i + 1], -60)), 0) / 9;
+ const row = (nm, X) => console.log(` ${nm.padEnd(6)} h2..h10 dB ${X.spec.slice(1).map((v) => Math.max(-60, v).toFixed(0).padStart(4)).join("")} fundamental decay ${X.decay.toFixed(1)} dB/s${X === R ? "" : ` |spectrum - ref| ${dist(X).toFixed(1)} dB`}`);
+ console.log(` ${name} ${oj} midi ${p} vs ${file.split("/").pop()}`); row("ref", R); row("v1", A); row("v2", B);
+}
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/keys-compare.py b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-compare.py
new file mode 100644
index 0000000..978e765
--- /dev/null
+++ b/plugins/anidoodle/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/plugins/anidoodle/skills/anidoodle/engine/tools/keys-demo.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-demo.mjs
new file mode 100644
index 0000000..aaf6cb0
--- /dev/null
+++ b/plugins/anidoodle/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], 24000) - M.stemRms(...a.stems[pt.id], 24000); 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/plugins/anidoodle/skills/anidoodle/engine/tools/keys-fit.py b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-fit.py
new file mode 100644
index 0000000..c2b7856
--- /dev/null
+++ b/plugins/anidoodle/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)
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/keys-metrics.py b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-metrics.py
new file mode 100644
index 0000000..d4088a2
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-metrics.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Anti-MIDI metrics for the keys phrases (research sec. 9.2): per-band inter-channel correlation
+(< 0.9 above 500 Hz = real width; ~1 below 120 Hz = mono lows), click detector (sample steps far above the
+local signal), spectral flux in sustains (a static oscillator is ~flat). numpy only.
+ python3 tools/keys-metrics.py <dir with before-*.wav / after-*.wav>
+"""
+import os, sys, wave, numpy as np
+
+def load(p):
+ w = wave.open(p); x = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(float).reshape(-1, 2) / 32768
+ return x[:, 0], x[:, 1], w.getframerate()
+
+def band(x, sr, lo, hi):
+ X = np.fft.rfft(x); f = np.fft.rfftfreq(len(x), 1 / sr); X[(f < lo) | (f >= hi)] = 0; return np.fft.irfft(X, len(x))
+
+def corr(a, b):
+ return float(np.dot(a, b) / (np.sqrt(np.dot(a, a) * np.dot(b, b)) + 1e-20))
+
+def clicks(x, sr):
+ """Impulsive steps: |2nd difference| more than 12x its own local RMS (10 ms). Steady bright tones do not count."""
+ d2 = np.abs(np.diff(x, 2)); w = int(0.01 * sr)
+ loc = np.sqrt(np.convolve(d2 * d2, np.ones(w) / w, mode="same")) + 1e-6
+ hits = np.where((d2 > 12 * loc) & (d2 > 1e-3))[0]
+ return int(np.sum(np.diff(hits) > int(0.005 * sr)) + (1 if len(hits) else 0))
+
+def flux(x, sr):
+ n = 2048; fr = [np.abs(np.fft.rfft(x[i:i + n] * np.hanning(n))) for i in range(0, len(x) - n, 1024)]
+ fr = np.array(fr); fr /= fr.sum(axis=1, keepdims=True) + 1e-12
+ return float(np.mean(np.abs(np.diff(fr, axis=0)).sum(axis=1)))
+
+d = sys.argv[1]
+print(f"{'phrase':28} {'ICC<120':>8} {'ICC.5-2k':>9} {'ICC>2k':>8} {'clicks':>7} {'flux':>6}")
+for fn in sorted(os.listdir(d)):
+ if not fn.endswith(".wav") or not (fn.startswith("before-") or fn.startswith("after-")): continue
+ L, R, sr = load(os.path.join(d, fn))
+ row = [corr(band(L, sr, a, b), band(R, sr, a, b)) for a, b in [(20, 120), (500, 2000), (2000, 16000)]]
+ print(f"{fn[:-4]:28} {row[0]:8.2f} {row[1]:9.2f} {row[2]:8.2f} {clicks((L + R) / 2, sr):7d} {flux((L + R) / 2, sr):6.3f}")
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs
index a60c314..69a711c 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs
@@ -122,8 +122,12 @@ for (const secs of [70, 90, 110]) {
assert(M.detectMode(M.line(0, src, { role: "melody", bpb: 4 }), ["lydian", "major", "aeolian", "dorian", "mixolydian"])[0].tonic !== "Db", "fixture must fool the raw detector");
assert.deepEqual(M.planProblems(lp("Db", "lydian", src)), []); assert(M.planProblems(lp("E", "major", src)).length > 0);
pass("Db lydian leaning on Ab is accepted (scale fits, tonic heard); a wrong key is still flagged");
- const st = { lead: [new Float32Array([0.3 * 10 ** ((-16.5 + 5) / 20) / 0.3]), new Float32Array(1)] };
- assert(M.stemBalance(st, { lead: -16.5 }).pass); assert(!M.stemBalance({ lead: [new Float32Array([10 ** ((-16.5 + 7) / 20)]), new Float32Array(1)] }, { lead: -16.5 }).pass); pass("stems: the lead may sit +3 dB over tolerance (guards win), not more");
+ const cen = (x) => { const a = new Float32Array([x]); return [a, a]; }; // a centred part: the stem meter reads its mid
+ assert(M.stemBalance({ lead: cen(10 ** ((-16.5 + 5) / 20)) }, { lead: -16.5 }).pass); assert(!M.stemBalance({ lead: cen(10 ** ((-16.5 + 7) / 20)) }, { lead: -16.5 }).pass); pass("stems: the lead may sit +3 dB over tolerance (guards win), not more");
+ { const n = 48000, x = new Float32Array(n).map((_, i) => 0.1 * Math.sin(i / 7)), z = new Float32Array(n), lo = new Float32Array(n).map((_, i) => 0.001 * Math.sin(i / 7));
+ const left = M.stemRms(x, z), right = M.stemRms(z, x), tail = M.stemRms(Float32Array.from([...x.slice(0, n / 2), ...lo.slice(0, n / 2)]), Float32Array.from([...x.slice(0, n / 2), ...lo.slice(0, n / 2)]));
+ assert(Math.abs(left - right) < 1e-9 && Math.abs(tail - M.stemRms(x, x)) < 0.1, `mid meter: L ${left} R ${right}, tail ${tail}`);
+ pass(`stem meter: a part panned hard left reads as hard right (${left.toFixed(1)} dB both; v1 read the left channel only), a -40 dB tail does not dilute it (${tail.toFixed(2)} vs ${M.stemRms(x, x).toFixed(2)})`); }
const w = M.composePiece(M.testMaterial(M.VOCAB.world, { bars: 4 })), wr = M.renderPiece(w, SR), g = M.guardReport(wr, SR, wr.L.length / SR);
assert(Number.isFinite(g.lufs) && g.ghost.windows > 0); pass(`guards run on a 7/8 score (${g.ghost.windows} windows)`); }
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
index 47f1f14..d8d316d 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
@@ -214,17 +214,18 @@ const main = async () => {
const calibrate = (M) => {
const trim = {}, fix = {};
for (const v of Object.values(M.VOCAB)) {
- if (v.calibrated) continue; trim[v.id] = {}; fix[v.id] = {}; M.VOCAB_TARGET_FIX[v.id] = {};
+ // calibrated (listened) styles: the targets never move, the voices are trimmed to them (sound v2 changed their levels); no target fix
+ trim[v.id] = {}; fix[v.id] = {}; M.VOCAB_TARGET_FIX[v.id] = {};
for (let pass = 0; pass < 3; pass++) {
M.VOCAB_TRIM[v.id] = trim[v.id];
const b = M.measureStems(M.composePiece(M.testMaterial(v)), STEM_SR);
- for (const r of b.rows) if (r.offDb !== null && Number.isFinite(r.offDb)) trim[v.id][r.id] = +Math.max(-12, Math.min(12, (trim[v.id][r.id] ?? 0) - r.offDb)).toFixed(1); // capped: past 12 dB the gain is not the problem
- if (pass === 2) { for (const r of b.rows) if (r.offDb !== null && Math.abs(r.offDb) > 1) fix[v.id][r.id] = +r.offDb.toFixed(1);
+ for (const r of b.rows) if (r.offDb !== null && Number.isFinite(r.offDb)) trim[v.id][r.id] = +Math.max(-18, Math.min(18, (trim[v.id][r.id] ?? 0) - r.offDb)).toFixed(1); // capped: past 18 dB the gain is not the problem (12 under the v1 meter, whose tails read sparse parts low)
+ if (pass === 2) { if (!v.calibrated) for (const r of b.rows) if (r.offDb !== null && Math.abs(r.offDb) > 1) fix[v.id][r.id] = +r.offDb.toFixed(1);
console.log(v.id.padEnd(14), b.rows.filter((r) => r.offDb !== null).map((r) => `${r.id} ${r.offDb >= 0 ? "+" : ""}${r.offDb.toFixed(1)}`).join(" ")); }
}
}
const file = join(here, "../src/canvas-core/music/vocabTrim.ts"), head = readFileSync(file, "utf8").split("export const VOCAB_TRIM")[0], j = (x) => JSON.stringify(x, null, 1).replace(/"(\w+)":/g, "$1:");
- writeFileSync(file, `${head}export const VOCAB_TRIM: Record<string, Partial<Record<Slot, number>>> = ${j(trim)};\n/** Where a 12 dB trim could not reach the target (long-decaying plucks read low as active RMS), the target moves to where the voice sits. */\nexport const VOCAB_TARGET_FIX: Record<string, Partial<Record<Slot, number>>> = ${j(fix)};\n`);
+ writeFileSync(file, `${head}export const VOCAB_TRIM: Record<string, Partial<Record<Slot, number>>> = ${j(trim)};\n/** Where an 18 dB trim could not reach the target (long-decaying plucks read low as active RMS), the target moves to where the voice sits. */\nexport const VOCAB_TARGET_FIX: Record<string, Partial<Record<Slot, number>>> = ${j(fix)};\n`);
console.log(`wrote ${file}`);
};
@@ -242,6 +243,7 @@ const printVocab = (M, id) => {
for (const [k, x] of Object.entries(v.harmony)) console.log(`harmony.${k}: ${Array.isArray(x) ? x.join(", ") : x}`);
for (const [k, x] of Object.entries(v.melody)) console.log(`melody.${k}: ${x}`);
for (const [k, x] of Object.entries(v.arrangement)) console.log(`arrangement.${k}: ${x}`);
+ console.log(`mix: ${M.describeMix(v.id)}`);
console.log(`avoid: ${v.avoid}`);
};
@@ -289,11 +291,11 @@ const printNovelty = (M, name, v, what) => {
return v.pass;
};
-/** Stem balance: each part's unmastered stem RMS (active samples) vs piece.stemTargets. Measured at 24 kHz, as the targets were. */
+/** Stem balance: each part's unmastered stem level (mid, gated 20 ms blocks: meter.stemRms) vs piece.stemTargets. Measured at 24 kHz, as the targets were. */
const STEM_SR = 24000;
const printStems = (M, piece, tempo, seconds) => {
const b = M.measureStems(piece, STEM_SR, { tempo, seconds });
- console.log(`stem balance: ${piece.title} (unmastered stem RMS over active samples vs target, +-${b.tolDb} dB; the lead may sit up to +${b.headroom.lead ?? 0} dB more for the masking guard; targets already include your mood controls' shifts)`);
+ console.log(`stem balance: ${piece.title} (unmastered stem RMS of the mid over the blocks where it plays, vs target, +-${b.tolDb} dB; the lead may sit up to +${b.headroom.lead ?? 0} dB more for the masking guard; targets already include your mood controls' shifts)`);
for (const r of b.rows) console.log(` ${r.id.padEnd(9)} ${fmt(r.rmsDb).padStart(6)} dB ${r.targetDb === null ? "(no target)" : `target ${fmt(r.targetDb).padStart(6)} off ${(r.offDb >= 0 ? "+" : "") + fmt(r.offDb)} ${r.ok ? "ok" : `FLAG: ${r.offDb > 0 ? "too hot" : "too quiet"}`}`}`);
if (!Object.keys(piece.stemTargets ?? {}).length) console.log(" (this piece declares no stemTargets)");
const cal = M.VOCAB[piece.plan.style]?.calibrated !== false;
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/README.md b/plugins/anidoodle/skills/anidoodle/references/music/README.md
index 7ff0b0a..1bd22ab 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/README.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/README.md
@@ -67,29 +67,36 @@ MusicPlan + notes (you write) -> perform -> instruments (one stem per part)
| `piano` | Modal, physics-shaped: inharmonic partials, 2-3 detuned strings with two-stage decay, velocity-dependent hammer brightness and strike comb, knock, soundboard modes, dampers, sustain pedal with sympathetic strings, stereo by pitch. See ADVISORY 4.1. |
| `musicBox`, `bell` | The recipe's numbers |
| `celesta`, `marimba`, `vibes` | Modal bars |
- | `harp`, `guitar` | Extended Karplus-Strong |
- | `strings` | Detuned PolyBLEP saws, slow bow, delayed vibrato |
+ | `harp`, `guitar` | Extended Karplus-Strong: pick position, two polarisations, a commuted body (harp fitted to CC0 recordings). `kind`: nylon (default), steel, electric (`pickup`: neck or bridge, `drive` into a clean amp) |
+ | `strings` | A section of `players` (default 10, divided across chords), each with its own timing, tuning, drift, vibrato and bow noise, through measured violin, viola and cello bodies. `pizz: true` plucks |
| `fmBell`, `ePiano` | 2-operator FM |
| `pulse`, `triangle`, `noiseDrum` | NES-style chip voices |
- | `kick`, `snare`, `hat`, `bass`, `vinyl` | Drums, bass and texture |
+ | `kick`, `snare`, `hat`, `vinyl` | Drums and texture |
+ | `bass` | `kind`: finger (default, electric through an amp, `drive`), pick, upright (body, pitch settle, thump), synth (saw + sub into a 24 dB filter, glide) |
| `warmPad`, `softPluck`, `sub` | The lo-fi electronic kit (`lofiKit.ts`): detuned-saw pad, filtered pluck with ping-pong delay, sine sub |
| `organ` | Drawbar ranks (harmonics 1 2 3 4 6 8), chorus, tremulant |
- | `brass` | PolyBLEP saw, a low-pass that opens with loudness, a pitch scoop, delayed vibrato |
- | `woodwind` | Flute (sine + breath noise) or `reed: true` clarinet (odd harmonics) |
- | `choir` | Detuned saws through vowel formants (`vowel`: a o u e i). Texture, never a lead |
+ | `brass` | Section of `players` (default 3): harmonics that brighten with loudness, a lip scoop, breath, bell formants (`type`: trumpet, trombone or horn; `bright` < 0.75 = horn) |
+ | `woodwind` | Flute (chiff, jet and breath noise, breath vibrato) or `reed: true` clarinet (odd harmonics, reed noise). Touching notes slur |
+ | `choir` | Singers (`singers`, default 8) with a glottal source, jitter, shimmer and breath, through 5 formants per vowel. `vowel`: a e i o u, or a sequence (`"uoa"`) that morphs across each note |
| `timpani` | Tuned membrane modes, a pitch settle, a mallet thump (`pitch` tunes it in a drum lane) |
| `leadSynth` | Mono saw + square, portamento, a filter envelope, blooming vibrato |
- | `bowedSolo` | One bowed voice (violin, or `cello: true`): vibrato, bow noise, body resonances |
+ | `bowedSolo` | A bowed waveguide string (violin, or `cello: true`): touching notes are one bow with a finger slide, delayed vibrato, measured body |
- The acoustic voices are procedural approximations. A human listens before one carries a film.
+ The acoustic voices are procedural approximations: cinematic and stylized, never "realistic". Every note varies
+ (seeded), so repeats never clone. A human listens before one carries a film. A shipped score sets
+ `legacy: true` on its piece to keep the sound it shipped with.
4. **Room.** The style chooses it:
- music box: one reflection, no tail;
- nocturne and lullaby: a small room;
- cinematic and drive: a hall;
- chiptune: nothing.
5. **Master.**
- - **Gentle styles:** one static gain to **-16 LUFS**, true peak <= -1 dBTP, never a compressor.
- If the peak blocks the gain, the loudness goes down. The cure is musical (see "Peaks" below).
+ - **Gentle styles:** one static gain to **-16 LUFS**, true peak <= -1 dBTP, never a compressor on the master.
+ Struck stems (plucks, plucked basses, piano, mallets and bells, timpani) first go through a transient-aware
+ gain in the mix (only the pick or hammer spike above the note's own body comes down, up to 6 dB, the stem's
+ level unchanged), so their attacks don't hold the master under the ceiling. `RenderOpts.gentleGlue` (a <= 1 dB
+ 2:1 bus glue) exists but is off by default: Alex's call. If the peak still blocks the gain, the loudness goes
+ down. The cure is musical (see "Peaks" below): a solo piano with a 10 LU range (the nocturne demo) masters at -17.5.
- **Dense styles** (lofiElectronic, lofi, drive, house, synthwave, hipHop, rock, chiptune): **-14 LUFS** through a look-ahead true-peak limiter, then a static trim if an inter-sample peak still passes -1 dBTP.
A film's `audio` is `filmAudio(piece, seconds)`, which returns `(sampleRate) => [L, R]` at exactly
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md b/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md
index 9a5763f..3fde11d 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md
@@ -26,11 +26,11 @@ Those read as dusty lo-fi hip-hop (the `lofi` style), not clean electronic.
| Slot | Voice | How it's made | Stem RMS target |
|---|---|---|---|
-| chords | `warmPad` | 7 PolyBLEP saws, spread 0.55 x +-14 cents, slow per-voice drift, 12 dB low-pass at 2.6 kHz, 0.5 s attack, 1.4 s release | -21 dB |
-| lead | `softPluck` | triangle + square an octave down, filter snaps open, 0.42 s decay, dotted-eighth ping-pong (feedback 0.28, mix 0.24) | -16.5 dB |
-| counter | `softPluck` | brighter, panned 0.35, more delay and room | -24 dB |
-| bass | `sub` | sine + a whisper of the 2nd harmonic, low-passed at 150 Hz | -18 dB |
-| kick / snare / ghost / hat | kit | a bouncy kick, a snare, rim ghosts about 11 dB under, 16th hats | -14 / -20 / - / -28 dB |
+| chords | `warmPad` | 7 PolyBLEP saws, spread 0.55 x +-14 cents, slow per-voice drift, 12 dB low-pass at 2.6 kHz, 0.5 s attack, 1.4 s release | -22 dB |
+| lead | `softPluck` | triangle + square an octave down, filter snaps open, 0.42 s decay, dotted-eighth ping-pong (feedback 0.28, mix 0.24) | -15.5 dB |
+| counter | `softPluck` | brighter, panned 0.35, more delay and room | -20 dB |
+| bass | `sub` | sine + a whisper of the 2nd harmonic, low-passed at 150 Hz | -18.5 dB |
+| kick / snare / ghost / hat | kit | a bouncy kick, a snare, rim ghosts about 11 dB under, 16th hats | -14.5 / -19 / - / -24.5 dB |
| arp, perc | `softPluck`, `hat` | optional extra layers | - |
Alternates:
@@ -100,7 +100,10 @@ node tools/music.mjs render <file>.ts#<export> out.mp3 --stems
A stem is a part's own signal:
- unmastered, pre-room, after its gain and the duck;
-- measured as RMS over its **active** samples (|x| > 1e-4), left channel, at 24 kHz.
+- measured on its **mid** ((L + R) / 2, after its pan, 30 Hz high-passed) as the RMS of the 20 ms blocks where it
+ plays: blocks under -70 dBFS never count, then blocks more than 20 dB under the part's own level drop out (gated
+ like loudness), at 24 kHz. (The v1 meter read the left channel sample by sample above -80 dB; every target was
+ converted at the sound-v2 merge on the render it was set on, so the balance did not move.)
Fix a flagged part with `levels`, never with the master.
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md b/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md
index 6f24f48..2b02602 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md
@@ -71,14 +71,14 @@ warm, chill but upbeat, clean: a breathing pad, a plucked hook through ping-pong
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `warmPad` | -3 | -21 | strings (`strings`, -6 dB), piano (`piano`, -4 dB) |
-| lead | `softPluck` | 6 | -16.5 | bell (`fmBell`, 0 dB), mallet (`marimba`, 2 dB), guitar (`guitar`, 2 dB) |
-| counter | `softPluck` | 8 | -24 | - |
-| bass | `sub` | -6 | -18 | warm (`bass`, -2 dB) |
-| kick | `kick` | 0.5 | -14 | - |
-| snare | `snare` | 8 | -20 | - |
+| chords | `warmPad` | -0.6 | -22 | strings (`strings`, -6 dB), piano (`piano`, -4 dB) |
+| lead | `softPluck` | 4.9 | -15.5 | bell (`fmBell`, 0 dB), mallet (`marimba`, 2 dB), guitar (`guitar`, 2 dB) |
+| counter | `softPluck` | 13.5 | -20 | - |
+| bass | `sub` | -5.6 | -18.5 | warm (`bass`, -2 dB) |
+| kick | `kick` | -2.6 | -14.5 | - |
+| snare | `snare` | 6.4 | -19 | - |
| ghost | `snare` | 4 | - | - |
-| hat | `hat` | 20 | -28 | - |
+| hat | `hat` | 19.5 | -24.5 | - |
| arp | `softPluck` | 4 | - | - |
| perc | `hat` | 14 | - | - |
@@ -95,16 +95,16 @@ forward, bright, confident: four-on-the-floor, a pumping supersaw bed, a gritty
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `strings` | -2.7 | -22 | - |
-| lead | `strings` | 5.4 | -16 | pluck (`softPluck`, 5 dB) |
-| counter | `fmBell` | 6 | -27.3 | - |
-| bass | `bass` | 0.1 | -16 | sub (`sub`, -5 dB) |
-| kick | `kick` | 2.5 | -12 | - |
-| snare | `snare` | 10.5 | -18 | - |
+| chords | `strings` | -1.3 | -23 | - |
+| lead | `strings` | 8.7 | -16 | pluck (`softPluck`, 5 dB) |
+| counter | `fmBell` | 10.8 | -19.5 | - |
+| bass | `bass` | 0 | -16 | sub (`sub`, -5 dB) |
+| kick | `kick` | 1 | -12.5 | - |
+| snare | `snare` | 8.5 | -17 | - |
| ghost | `snare` | -2 | - | - |
| hat | `hat` | 12 | -26 | - |
-| arp | `softPluck` | 4.2 | -21 | - |
-| perc | `hat` | 18.3 | -27 | - |
+| arp | `softPluck` | 4.8 | -20.5 | - |
+| perc | `hat` | 15.5 | -26 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -119,12 +119,12 @@ wide and emotional: string swells, low ostinatos for tension, harp and bell colo
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `strings` | 1.2 | -18 | - |
-| lead | `strings` | 4.5 | -17 | piano (`piano`, 0 dB), bell (`fmBell`, -4 dB), celesta (`celesta`, 0 dB) |
-| counter | `harp` | 12 | -36.7 | piano (`piano`, -3 dB) |
-| bass | `strings` | 1.3 | -19 | - |
-| arp | `strings` | 3.4 | -21 | - |
-| kick | `kick` | -2.4 | -16 | - |
+| chords | `strings` | 2.1 | -18.5 | - |
+| lead | `strings` | 6.9 | -17 | piano (`piano`, 0 dB), bell (`fmBell`, -4 dB), celesta (`celesta`, 0 dB) |
+| counter | `harp` | 18 | -16.4 | piano (`piano`, -3 dB) |
+| bass | `strings` | -0.6 | -19.5 | - |
+| arp | `strings` | 4.5 | -21.5 | - |
+| kick | `kick` | 0.2 | -16.5 | - |
| snare | `snare` | -2 | -24 | - |
| ghost | `snare` | -4 | - | - |
| hat | `hat` | 6 | -32 | - |
@@ -143,12 +143,12 @@ floating, spacious, luminous: long pads, bells and plucks with space around them
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `warmPad` | 1.5 | -19 | - |
-| lead | `fmBell` | 1.3 | -20 | pluck (`softPluck`, 5 dB), vibes (`vibes`, 0 dB) |
-| counter | `softPluck` | 6.8 | -25 | - |
+| chords | `warmPad` | 1.5 | -20 | - |
+| lead | `fmBell` | 1.6 | -17.5 | pluck (`softPluck`, 5 dB), vibes (`vibes`, 0 dB) |
+| counter | `softPluck` | 7.2 | -26.5 | - |
| bass | `sub` | -8.3 | -22 | - |
-| arp | `celesta` | -0.9 | -24 | - |
-| kick | `kick` | -6.4 | -20 | - |
+| arp | `celesta` | -2.4 | -23.5 | - |
+| kick | `kick` | -7 | -20.5 | - |
| ghost | `snare` | -6 | - | - |
| hat | `hat` | 6 | -32 | - |
| perc | `hat` | 4 | - | - |
@@ -166,16 +166,16 @@ intimate and warm: fingerpicked guitar, soft piano, a harp or celesta line, brus
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `piano` | 7 | -33 | strings (`strings`, -8 dB) |
-| arp | `guitar` | 8 | -22.9 | - |
-| lead | `harp` | 14 | -18.8 | piano (`piano`, 0 dB), guitar (`guitar`, 2 dB), strings (`strings`, -2 dB) |
-| counter | `celesta` | 8.2 | -24 | - |
-| bass | `bass` | -4.4 | -21 | - |
-| kick | `kick` | -4.5 | -20 | - |
+| chords | `piano` | 13 | -26 | strings (`strings`, -8 dB) |
+| arp | `guitar` | 12.5 | -20.5 | - |
+| lead | `harp` | 16.7 | -13 | piano (`piano`, 0 dB), guitar (`guitar`, 2 dB), strings (`strings`, -2 dB) |
+| counter | `celesta` | 9.7 | -19.5 | - |
+| bass | `bass` | -7.2 | -21 | - |
+| kick | `kick` | -4.5 | -20.5 | - |
| snare | `snare` | -6 | -26 | - |
-| ghost | `snare` | 3.4 | -28 | - |
+| ghost | `snare` | 2.3 | -24.5 | - |
| hat | `hat` | 2 | -30 | - |
-| perc | `hat` | 14 | -35.8 | - |
+| perc | `hat` | 19.4 | -30 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -190,16 +190,16 @@ light, cheeky, springy: marimba and pizzicato-like plucks, a bouncy bass, a skip
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| lead | `marimba` | 4.1 | -16 | chip (`pulse`, -4 dB), pluck (`softPluck`, 5 dB), bell (`fmBell`, -2 dB) |
-| chords | `vibes` | -4.3 | -22 | - |
-| arp | `harp` | 8 | -22.4 | - |
-| counter | `celesta` | 10 | -23 | - |
-| bass | `bass` | -1.6 | -18 | tuba (`sub`, -4 dB) |
-| kick | `kick` | 0.3 | -15 | - |
-| snare | `snare` | 8.1 | -21 | - |
+| lead | `marimba` | 6 | -13 | chip (`pulse`, -4 dB), pluck (`softPluck`, 5 dB), bell (`fmBell`, -2 dB) |
+| chords | `vibes` | -2.2 | -21 | - |
+| arp | `harp` | 9.3 | -20 | - |
+| counter | `celesta` | 10.8 | -18.5 | - |
+| bass | `bass` | -4.4 | -18 | tuba (`sub`, -4 dB) |
+| kick | `kick` | -1.8 | -15.5 | - |
+| snare | `snare` | 6.2 | -20 | - |
| ghost | `snare` | 0 | -26 | - |
-| hat | `hat` | 22.2 | -28 | - |
-| perc | `hat` | 19.7 | -29 | - |
+| hat | `hat` | 22.3 | -24 | - |
+| perc | `hat` | 21.5 | -29.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -214,11 +214,11 @@ small, bright, clockwork, innocent; plucked and never sustained. Tempo 100-132 b
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| lead | `musicBox` | 3.5 | -16 | celesta (`celesta`, 0 dB), bell (`fmBell`, -4 dB) |
-| arp | `musicBox` | -6 | -26 | - |
-| bass | `musicBox` | -3 | -24 | - |
-| counter | `bell` | 0.3 | -22 | - |
-| chords | `celesta` | -5.3 | -27 | - |
+| lead | `musicBox` | 2.9 | -13.5 | celesta (`celesta`, 0 dB), bell (`fmBell`, -4 dB) |
+| arp | `musicBox` | -5.1 | -25 | - |
+| bass | `musicBox` | -1.7 | -26 | - |
+| counter | `bell` | 1 | -19.5 | - |
+| chords | `celesta` | -7.7 | -26.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -233,10 +233,10 @@ intimate, expressive, late-night: one piano, rubato, pedal. Tempo 50-76 bpm, met
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| lead | `piano` | 12 | -17 | - |
-| chords | `piano` | 12 | -30.3 | - |
-| bass | `piano` | 6.3 | -23 | - |
-| counter | `strings` | 2 | -30 | - |
+| lead | `piano` | 14.1 | -15 | - |
+| chords | `piano` | 17.7 | -23.5 | - |
+| bass | `piano` | 6.5 | -24.5 | - |
+| counter | `strings` | 4.6 | -30.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -251,11 +251,11 @@ hypnotic, curious, clean: interlocking ostinatos that change slowly. Tempo 96-14
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| arp | `marimba` | -0.5 | -20 | piano (`piano`, -4 dB), pluck (`softPluck`, 3 dB) |
-| lead | `marimba` | 3.1 | -17 | - |
-| bass | `marimba` | -4.9 | -21 | - |
-| counter | `vibes` | 3.7 | -27 | - |
-| chords | `piano` | 4 | -37.1 | - |
+| arp | `marimba` | 0.1 | -19 | piano (`piano`, -4 dB), pluck (`softPluck`, 3 dB) |
+| lead | `marimba` | 5 | -14 | - |
+| bass | `marimba` | -5.3 | -24 | - |
+| counter | `vibes` | 7.9 | -21 | - |
+| chords | `piano` | 10 | -30.1 | - |
| kick | `kick` | -6 | - | - |
| ghost | `snare` | -6 | - | - |
| perc | `hat` | 0 | - | - |
@@ -273,15 +273,15 @@ loose, warm, clever: swing ride, walking bass, comping piano. Tempo 80-200 bpm,
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `piano` | 8 | -32.5 | - |
-| lead | `vibes` | 3.8 | -16 | piano (`piano`, 0 dB), clarinet (`woodwind`, 0 dB), flute (`woodwind`, 0 dB), brass (`brass`, -3 dB) |
-| bass | `bass` | -1.3 | -18 | - |
-| counter | `woodwind` | 8.5 | -21 | - |
-| kick | `kick` | -0.2 | -24 | - |
+| chords | `piano` | 14 | -25.5 | - |
+| lead | `vibes` | 3.5 | -13 | piano (`piano`, 0 dB), clarinet (`woodwind`, 0 dB), flute (`woodwind`, 0 dB), brass (`brass`, -3 dB) |
+| bass | `bass` | -4 | -18 | - |
+| counter | `woodwind` | 10.7 | -18.5 | - |
+| kick | `kick` | -2.8 | -24.5 | - |
| snare | `snare` | 0 | -26 | - |
-| ghost | `snare` | 7.5 | -28 | - |
-| hat | `hat` | 21 | -26 | - |
-| perc | `hat` | 18 | -30 | - |
+| ghost | `snare` | 7 | -24.5 | - |
+| hat | `hat` | 26.2 | -23 | - |
+| perc | `hat` | 15.5 | -30 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -296,11 +296,11 @@ soft, rocking, safe. Tempo 56-78 bpm, meters 3/4, 6/8, swing 0.5-0.5.
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| lead | `celesta` | 5.3 | -17 | musicBox (`musicBox`, 0 dB), piano (`piano`, 0 dB), flute (`woodwind`, -2 dB) |
-| arp | `harp` | 4 | -28.3 | - |
-| bass | `harp` | 6 | -26 | - |
-| counter | `musicBox` | 4 | -31.7 | - |
-| chords | `strings` | -8.5 | -28 | - |
+| lead | `celesta` | 4.7 | -15 | musicBox (`musicBox`, 0 dB), piano (`piano`, 0 dB), flute (`woodwind`, -2 dB) |
+| arp | `harp` | 8.4 | -23.5 | - |
+| bass | `harp` | 7 | -27 | - |
+| counter | `musicBox` | 10 | -21.7 | - |
+| chords | `strings` | -8 | -28.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -316,10 +316,10 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
| lead | `pulse` | 7.4 | -16 | square (`pulse`, -2 dB) |
-| arp | `pulse` | 7 | -23.1 | - |
-| bass | `triangle` | 0.2 | -18 | - |
-| kick | `noiseDrum` | 7.6 | -18 | - |
-| snare | `noiseDrum` | 6.7 | -20 | - |
+| arp | `pulse` | 8.2 | -20 | - |
+| bass | `triangle` | 0.3 | -18 | - |
+| kick | `noiseDrum` | 7.2 | -17.5 | - |
+| snare | `noiseDrum` | 6.7 | -20.5 | - |
| hat | `noiseDrum` | -10 | -28 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -335,14 +335,14 @@ hazy, nostalgic, crackly: FM e-piano, vinyl, a lazy swung beat (the dusty cousin
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `ePiano` | 5.2 | -20 | - |
-| lead | `ePiano` | 7.5 | -17 | guitar (`guitar`, 2 dB), flute (`woodwind`, -2 dB) |
-| bass | `bass` | -2.1 | -19 | - |
-| counter | `fmBell` | 4 | -30.1 | - |
-| kick | `kick` | -2.6 | -17 | - |
-| snare | `snare` | 6.2 | -22 | - |
-| ghost | `snare` | 6 | -27.1 | - |
-| hat | `hat` | 4 | -43 | - |
+| chords | `ePiano` | 6.1 | -19.5 | - |
+| lead | `ePiano` | 9 | -16.5 | guitar (`guitar`, 2 dB), flute (`woodwind`, -2 dB) |
+| bass | `bass` | -1.8 | -19 | - |
+| counter | `fmBell` | 12.9 | -20.9 | - |
+| kick | `kick` | -5.8 | -17.5 | - |
+| snare | `snare` | 2.2 | -21 | - |
+| ghost | `snare` | 8.5 | -22 | - |
+| hat | `hat` | 12.9 | -32.8 | - |
| perc | `hat` | 4 | -29 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -358,14 +358,14 @@ big and heroic: brass theme, string ostinato engine, choir, timpani. Tempo 70-14
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| lead | `brass` | 9.2 | -16 | strings (`strings`, 0 dB), horn (`brass`, -2 dB), flute (`woodwind`, -2 dB) |
-| chords | `strings` | -0.4 | -19 | - |
-| arp | `strings` | 4.4 | -20 | - |
-| bass | `strings` | 0.9 | -19 | - |
-| counter | `choir` | -1.7 | -22 | flute (`woodwind`, -3 dB), harp (`harp`, 0 dB) |
-| perc | `timpani` | 4.2 | -17 | - |
-| kick | `kick` | -3.3 | -17 | - |
-| snare | `snare` | 5.2 | -24 | - |
+| lead | `brass` | 14.7 | -13 | strings (`strings`, 0 dB), horn (`brass`, -2 dB), flute (`woodwind`, -2 dB) |
+| chords | `strings` | 0.5 | -19.5 | - |
+| arp | `strings` | 4.7 | -21 | - |
+| bass | `strings` | 0.4 | -20 | - |
+| counter | `choir` | -2 | -23 | flute (`woodwind`, -3 dB), harp (`harp`, 0 dB) |
+| perc | `timpani` | 2.9 | -17.5 | - |
+| kick | `kick` | -5.6 | -17.5 | - |
+| snare | `snare` | 2.3 | -23 | - |
| hat | `hat` | 4 | -32 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -381,14 +381,14 @@ unsettling, cold, withheld: low drones, heartbeat pulse, high bowed harmonics, s
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `strings` | -0.8 | -21 | - |
-| bass | `sub` | -6.1 | -20 | - |
-| lead | `bowedSolo` | 7.3 | -19 | choir (`choir`, -2 dB), cello (`bowedSolo`, 0 dB) |
-| counter | `celesta` | 8 | -27 | choir (`choir`, -4 dB), bell (`fmBell`, -8 dB) |
-| arp | `strings` | 2.7 | -22 | - |
-| kick | `kick` | -3.4 | -17 | - |
+| chords | `strings` | -0.2 | -21.5 | - |
+| bass | `sub` | -6 | -20 | - |
+| lead | `bowedSolo` | 7.2 | -19.5 | choir (`choir`, -2 dB), cello (`bowedSolo`, 0 dB) |
+| counter | `celesta` | 9.5 | -19 | choir (`choir`, -4 dB), bell (`fmBell`, -8 dB) |
+| arp | `strings` | 2.9 | -23 | - |
+| kick | `kick` | -0.3 | -17.5 | - |
| ghost | `snare` | -4 | -27 | - |
-| perc | `timpani` | 8.4 | -18 | - |
+| perc | `timpani` | 6.2 | -18.5 | - |
| hat | `hat` | 0 | -32 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -404,15 +404,15 @@ live-band energy: driven guitars, bass locked to the kick, a tight kit, maybe or
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `strings` | -0.9 | -19 | organ (`organ`, -4 dB), piano (`piano`, -3 dB) |
-| lead | `leadSynth` | 9.9 | -16 | guitar (`guitar`, 2 dB) |
-| bass | `bass` | -0.8 | -17 | - |
-| counter | `organ` | 6 | -30.4 | - |
-| kick | `kick` | 1.2 | -13 | - |
-| snare | `snare` | 11.2 | -17 | - |
+| chords | `guitar` | 15.5 | -15.5 | strings (`strings`, -6 dB), organ (`organ`, -4 dB), piano (`piano`, -3 dB) |
+| lead | `leadSynth` | 9.9 | -16 | guitar (`guitar`, 17 dB) |
+| bass | `bass` | -1.3 | -17 | - |
+| counter | `organ` | 12 | -27.1 | - |
+| kick | `kick` | -1 | -13.5 | - |
+| snare | `snare` | 8.8 | -16.5 | - |
| ghost | `snare` | 0 | -26 | - |
-| hat | `hat` | 20.6 | -27 | - |
-| perc | `hat` | 17 | -26 | - |
+| hat | `hat` | 20.4 | -23.5 | - |
+| perc | `hat` | 15.7 | -25.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -427,15 +427,15 @@ head-nod or dark trap: heavy 808, crisp clap, rolling hats, a moody loop on top.
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| bass | `sub` | -2.5 | -15 | - |
-| chords | `piano` | 6 | -36.8 | pad (`warmPad`, -3 dB) |
-| lead | `softPluck` | 2.7 | -18 | bell (`fmBell`, -2 dB), flute (`woodwind`, -2 dB), choir (`choir`, -4 dB) |
-| counter | `strings` | 4 | -29.2 | - |
-| kick | `kick` | 1.4 | -13 | - |
-| snare | `snare` | 10.2 | -18 | - |
+| bass | `sub` | -2.4 | -15 | - |
+| chords | `piano` | 12 | -30.9 | pad (`warmPad`, -3 dB) |
+| lead | `softPluck` | 2.9 | -17.5 | bell (`fmBell`, -2 dB), flute (`woodwind`, -2 dB), choir (`choir`, -4 dB) |
+| counter | `strings` | 9.6 | -25.5 | - |
+| kick | `kick` | -2.7 | -13.5 | - |
+| snare | `snare` | 8.7 | -17 | - |
| ghost | `snare` | 0 | -26 | - |
-| hat | `hat` | 23.6 | -26 | - |
-| perc | `hat` | 19.9 | -29 | - |
+| hat | `hat` | 23.2 | -23 | - |
+| perc | `hat` | 17.7 | -29.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -450,16 +450,16 @@ euphoric, dancing, bright: four-on-the-floor, offbeat bass, stabs, a big pad. Te
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `organ` | 5.2 | -21 | pad (`warmPad`, -3 dB), piano (`piano`, -3 dB) |
-| bass | `bass` | 0.3 | -16 | - |
-| lead | `softPluck` | 4.3 | -17 | synth (`leadSynth`, -2 dB) |
-| counter | `warmPad` | 6.9 | -23 | - |
-| arp | `softPluck` | 4.5 | -22 | - |
-| kick | `kick` | 2.6 | -12 | - |
-| snare | `snare` | 10.7 | -18 | - |
+| chords | `organ` | 6.7 | -20 | pad (`warmPad`, -3 dB), piano (`piano`, -3 dB) |
+| bass | `bass` | 0.5 | -16 | - |
+| lead | `softPluck` | 4.3 | -16.5 | synth (`leadSynth`, -2 dB) |
+| counter | `warmPad` | 7.5 | -23.5 | - |
+| arp | `softPluck` | 5 | -22 | - |
+| kick | `kick` | 1.3 | -12.5 | - |
+| snare | `snare` | 8.8 | -17 | - |
| ghost | `snare` | 1 | -26 | - |
| hat | `hat` | 12 | -26 | - |
-| perc | `hat` | 18.3 | -27 | - |
+| perc | `hat` | 15.1 | -27 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -474,16 +474,16 @@ neon-nostalgic, cinematic 80s: big gated snare, pulsing 8th bass, lush pads, a s
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `strings` | -2.1 | -21 | pad (`warmPad`, -2 dB) |
-| bass | `bass` | -0.3 | -17 | - |
+| chords | `strings` | -1.1 | -22 | pad (`warmPad`, -2 dB) |
+| bass | `bass` | -0.2 | -17 | - |
| lead | `leadSynth` | 11.7 | -16 | brass (`brass`, -2 dB) |
-| arp | `softPluck` | 4.1 | -22 | - |
-| counter | `fmBell` | 4 | -29.1 | - |
-| kick | `kick` | 1.4 | -13 | - |
-| snare | `snare` | 11.7 | -17 | - |
+| arp | `softPluck` | 4.2 | -22 | - |
+| counter | `fmBell` | 8.7 | -20.5 | - |
+| kick | `kick` | 1.2 | -13.5 | - |
+| snare | `snare` | 9.3 | -16.5 | - |
| ghost | `snare` | 0 | -26 | - |
| hat | `hat` | 12 | -28 | - |
-| perc | `hat` | 16.2 | -29 | - |
+| perc | `hat` | 13.5 | -29.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -498,13 +498,13 @@ rooted, spacious, rhythmic: a drone, a modal melody on plucked strings or a flut
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| lead | `woodwind` | 8.7 | -16 | pluck (`guitar`, 2 dB), marimba (`marimba`, 1 dB), reed (`woodwind`, 0 dB), bowed (`bowedSolo`, 0 dB) |
-| counter | `harp` | 10 | -38.1 | - |
-| arp | `guitar` | 8 | -24.2 | - |
-| chords | `warmPad` | -3.1 | -25 | - |
-| bass | `sub` | -9.6 | -22 | - |
-| kick | `timpani` | 0.3 | -17 | - |
-| ghost | `snare` | 9.5 | -24 | - |
+| lead | `woodwind` | 9.5 | -14.5 | pluck (`guitar`, 2 dB), marimba (`marimba`, 1 dB), reed (`woodwind`, 0 dB), bowed (`bowedSolo`, 0 dB) |
+| counter | `harp` | 16 | -18.2 | - |
+| arp | `guitar` | 12.7 | -20.5 | - |
+| chords | `warmPad` | -3.1 | -25.5 | - |
+| bass | `sub` | -9.5 | -22 | - |
+| kick | `timpani` | -1.5 | -17 | - |
+| ghost | `snare` | 10.5 | -20 | - |
| perc | `hat` | 8 | -28 | - |
| hat | `hat` | 6 | -30 | - |
@@ -521,12 +521,12 @@ vast, human, reverent: voices in parts, organ, bells, a slow swell. Tempo 50-90
| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
|---|---|---|---|---|
-| chords | `choir` | -9.9 | -19 | organ (`organ`, -4 dB), strings (`strings`, -4 dB) |
-| lead | `choir` | -3.1 | -17 | bowed (`bowedSolo`, 0 dB), flute (`woodwind`, -2 dB) |
-| bass | `organ` | 8 | -21 | - |
-| counter | `fmBell` | 4 | -30.5 | - |
-| arp | `harp` | 6 | -26.3 | - |
-| perc | `timpani` | 5.5 | -20 | - |
+| chords | `choir` | -9.7 | -20 | organ (`organ`, -4 dB), strings (`strings`, -4 dB) |
+| lead | `choir` | -3.8 | -17 | bowed (`bowedSolo`, 0 dB), flute (`woodwind`, -2 dB) |
+| bass | `organ` | 5.6 | -23 | - |
+| counter | `fmBell` | 8.8 | -21.5 | - |
+| arp | `harp` | 8 | -23.5 | - |
+| perc | `timpani` | 5.2 | -20 | - |
| kick | `timpani` | -6 | - | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).