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.

Correct recorded room timing and level

Alex Greenshpun7b26ef890cca
diff --git a/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts b/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
index c1bebda..5b3db0f 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
@@ -98,7 +98,7 @@ const cinematicP: MixProfile = { eq: 0.9, drumBus: { ratio: 3, targetGrDb: 2.5,
const P = (base: MixProfile, o: Partial<MixProfile>): MixProfile => ({ ...base, ...o });
export const MIX_PROFILES: Record<StyleId, MixProfile> = {
- nocturne: P(intimate, { sends: { melody: 0.5, accomp: 0.35, inner: 0.35, bass: 0.3, color: 0.5 }, space: conv(1.7, 24, { room: "rymer", size: 0.6, late: 0.17, er: 0.4, hp: 300, lp: 6500 }), /* optional treated-room recording; hp 300 keeps the left hand's low-mids out of the send */ width: W(1.0, 1.1, 150), classEq: { piano: { hp: 28 } } }),
+ nocturne: P(intimate, { sends: { melody: 0.5, accomp: 0.35, inner: 0.35, bass: 0.3, color: 0.5 }, space: conv(1.7, 24, { room: "small-room", size: 0.6, late: 0.17, er: 0.4, hp: 300, lp: 6500 }), /* optional treated-room recording; hp 300 keeps the left hand's low-mids out of the send */ width: W(1.0, 1.1, 150), classEq: { piano: { hp: 28 } } }),
lullaby: P(intimate, { space: conv(1.5, 18, { size: 0.5 }), tilt: -0.8 }),
musicBox: P(intimate, { space: null /* the recipe: one reflection, handled in render */, width: W(1.0, 1.05) }),
folk: P(intimate, { space: conv(1.2, 12, { size: 0.4, late: 0.28 }), width: W(1.05, 1.15), feel: "natural" }),
diff --git a/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts b/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts
index dc930d8..81ba530 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts
@@ -16,13 +16,21 @@ import { fft } from "./meter";
export type SpaceKind = "fdn" | "plate" | "conv";
export type Space = { kind: SpaceKind; room?: string; rt60: number; predelayMs: number; /** send filter */ hp: number; lp: number; /** early reflections level (0..1) and the late tail level (0..1) */ er: number; late: number; /** room size 0..1 (fdn/conv delay spread) */ size?: number; /** HF / LF decay multipliers */ highMult?: number; lowMult?: number; /** tank modulation depth 0..1 */ mod?: number };
type Wet = readonly [Float32Array, Float32Array, Float32Array, Float32Array];
-export type RecordedRoom = { L: Float32Array; R: Float32Array; rt60: number; sha256: string };
+export type RecordedRoom = { L: Float32Array; R: Float32Array; rt60: number; sha256: string; directFrames?: number };
const rooms = new Map<string, RecordedRoom>();
export const roomFor = (id?: string) => id ? rooms.get(id) : undefined;
export const clearRooms = () => rooms.clear();
export const registerRoom = (id: string, room: RecordedRoom) => {
if (!id || !(room.L instanceof Float32Array) || !(room.R instanceof Float32Array) || !room.L.length || room.L.length !== room.R.length || !room.L.every(Number.isFinite) || !room.R.every(Number.isFinite) || !(room.rt60 > 0) || !Number.isFinite(room.rt60) || !/^[a-f0-9]{64}$/i.test(room.sha256)) throw new Error(`${id}: invalid recorded room`);
- const r = { ...room, sha256: room.sha256.toLowerCase() }; rooms.set(id, r); return r;
+ const directFrames = room.directFrames ?? 0;
+ if (!Number.isInteger(directFrames) || directFrames < 0 || directFrames > room.L.length) throw new Error(`${id}: invalid directFrames`);
+ const r = { ...room, directFrames, sha256: room.sha256.toLowerCase() }; rooms.set(id, r); return r;
+};
+/** A missing room-only override must not create a space on styles that have none. */
+export const effectiveSpace = (s?: Partial<Space>): Partial<Space> | undefined => {
+ if (!s?.room || roomFor(s.room)) return s;
+ const { room: _room, ...rest } = s;
+ return Object.keys(rest).length ? rest : undefined;
};
const sendFilter = (L: Float32Array, R: Float32Array, sr: number, s: Space) => {
@@ -169,13 +177,20 @@ export const convReverb = (L: Float32Array, R: Float32Array, sr: number, s: Spac
const recordedReverb = (L: Float32Array, R: Float32Array, sr: number, s: Space, room: RecordedRoom): Wet => {
const n = L.length, [a, b] = sendFilter(L, R, sr, s), pd = Math.round(s.predelayMs * sr / 1000), xL = new Float32Array(n), xR = new Float32Array(n);
for (let i = pd; i < n; i++) { xL[i] = a[i - pd]; xR[i] = b[i - pd]; }
- const rate = 48000 / sr, len = Math.ceil(room.L.length / rate), split = Math.round(0.04 * sr);
+ const rate = 48000 / sr, len = Math.ceil(room.L.length / rate), split = Math.round(0.04 * sr), direct = Math.round((room.directFrames ?? 0) / rate);
const responses = [room.L, room.R].map((src) => {
const pcm = Float32Array.from(src); if (rate > 1) for (let j = 0; j < 2; j++) Biquad.make(48000, "lp", sr * 0.45, 0.7071).run(pcm);
const early = new Float32Array(len), late = new Float32Array(len);
- for (let i = 0; i < len; i++) { const x = i * rate, j = Math.floor(x), f = x - j; (i < split ? early : late)[i] = (pcm[j] + f * ((pcm[j + 1] ?? 0) - pcm[j])) * rate; }
+ for (let i = direct; i < len; i++) { const x = i * rate, j = Math.floor(x), f = x - j; (i < split ? early : late)[i] = (pcm[j] + f * ((pcm[j + 1] ?? 0) - pcm[j])) * rate; }
return { early, late };
});
+ // synthIR normalizes each stereo component to total energy 2, preserving channel balance.
+ for (const key of ['early', 'late'] as const) {
+ const a = responses[0][key], b = responses[1][key]; let e = 0;
+ for (let i = 0; i < len; i++) e += a[i] * a[i] + b[i] * b[i];
+ const g = e > 0 ? Math.sqrt(2 / e) : 0;
+ for (let i = 0; i < len; i++) { a[i] *= g; b[i] *= g; }
+ }
const wL = new Float32Array(n), wR = new Float32Array(n), tL = new Float32Array(n), tR = new Float32Array(n);
convolve(xL, responses[0].late, tL, s.late * 0.36); convolve(xR, responses[1].late, tR, s.late * 0.36);
convolve(xR, responses[0].late, tL, s.late * 0.18); convolve(xL, responses[1].late, tR, s.late * 0.18);
diff --git a/skills/anidoodle/engine/src/canvas-core/music/render.ts b/skills/anidoodle/engine/src/canvas-core/music/render.ts
index 7df5a87..7717ce2 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/render.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/render.ts
@@ -17,7 +17,7 @@ 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, roomFor, type Space } from "./mixReverb";
+import { reverb, roomFor, effectiveSpace, type Space } from "./mixReverb";
import { mixProfile, partEq, ROLE_SEND, isStruck, TRANSIENT_DEFAULT, type MixProfile } from "./mixProfiles";
export type RenderOpts = { /** sound v2, gentle styles only: a <= 1 dB 2:1 glue on the mix bus (spec 08 forbids a compressor on gentle masters; Alex decides) */ gentleGlue?: boolean; expressive?: boolean; piano?: PianoOpts; flatVelocity?: number; seconds?: number; tempo?: number; master?: "auto" | "gentle" | "dense" | "none"; stems?: boolean; only?: (p: Part) => boolean;
@@ -35,10 +35,10 @@ type StemPost = { lofi?: LofiFx; id: string; seed: number; period?: number; amp?
export type VoiceJob = (
| { kind: "sampled"; bank: string; bankHash: string; inst: Part["inst"]; opts?: Part["opts"]; keys: Played[]; pedal: Performance["pedal"]; sr: number; n: number; seed: number; post?: StemPost }
| { kind: "voice"; inst: Part["inst"]; opts?: Part["opts"]; keys: Played[]; sr: number; n: number; seed: number; ctx: KitCtx; post?: StemPost }
- | { kind: "piano"; keys: Played[]; pedal: Performance["pedal"]; sr: number; n: number; seed: number; opts?: Part["opts"]; v1?: PianoOpts; post?: StemPost }) & { roomHashes?: [string, string, number][] };
+ | { kind: "piano"; keys: Played[]; pedal: Performance["pedal"]; sr: number; n: number; seed: number; opts?: Part["opts"]; v1?: PianoOpts; post?: StemPost }) & { roomHashes?: [string, string, number, number][] };
export type VoiceCache = Map<string, VoiceOut>;
export const runVoiceJob = (j: VoiceJob): VoiceOut => {
- for (const [id, sha, rt60] of j.roomHashes ?? []) { const r = roomFor(id); if (!r || r.sha256 !== sha || r.rt60 !== rt60) throw new Error(`recorded room missing or changed: ${id} (${sha})`); }
+ for (const [id, sha, rt60, directFrames] of j.roomHashes ?? []) { const r = roomFor(id); if (!r || r.sha256 !== sha || r.rt60 !== rt60 || (r.directFrames ?? 0) !== directFrames) throw new Error(`recorded room missing or changed: ${id} (${sha})`); }
let out: VoiceOut;
if (j.kind === "sampled") {
const b = bankFor(j.inst, typeof j.opts?.variant === "string" ? j.opts.variant : undefined);
@@ -67,7 +67,7 @@ const v2Job = (piece: Piece, pt: Part, pi: number, keys: Played[], perf: Perform
const base = bank ? { kind: "sampled" as const, bank: bank.id, bankHash: bank.hash, inst: pt.inst, keys, pedal: perf.pedal, sr, n, seed: pt.inst === "piano" ? piece.seed + pi : piece.seed * 101 + pi, opts: pt.opts }
: pt.inst === "piano" ? (o.piano ? { kind: "piano" as const, keys, pedal: perf.pedal, sr, n, seed: piece.seed + pi, v1: o.piano } : { kind: "piano" as const, keys, pedal: perf.pedal, sr, n, seed: piece.seed + pi, opts: pt.opts ?? {} })
: { kind: "voice" as const, inst: pt.inst, opts: pt.opts, keys, sr, n, seed: piece.seed * 101 + pi, ctx };
- const roomHashes: [string, string, number][] = [piece.plan.space?.room ?? prof.space?.room, prof.drumRoom?.room].flatMap((id) => { const r = roomFor(id); return r && id ? [[id, r.sha256, r.rt60] as [string, string, number]] : []; });
+ const roomHashes: [string, string, number, number][] = [effectiveSpace(piece.plan.space)?.room ?? prof.space?.room, prof.drumRoom?.room].flatMap((id) => { const r = roomFor(id); return r && id ? [[id, r.sha256, r.rt60, r.directFrames ?? 0] as [string, string, number, number]] : []; });
const job = post ? { ...base, post } : base;
return roomHashes.length ? { ...job, roomHashes } : job;
};
@@ -185,7 +185,7 @@ const renderLegacy = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered =>
// ---- 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;
+ const sp = effectiveSpace(piece.plan.space);
if (style.id === "musicBox" && !sp) { // 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 if (style.reverb !== "none" || sp) {
@@ -267,7 +267,7 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
// ---- 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;
+ const sp = effectiveSpace(piece.plan.space);
if (style.id === "musicBox" && !sp && !piece.mix?.space) { // the recipe: ONE early reflection, 30 ms late, 14 dB down, no 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 {
diff --git a/skills/anidoodle/engine/test/rooms.test.ts b/skills/anidoodle/engine/test/rooms.test.ts
index 35954ed..aee11cb 100644
--- a/skills/anidoodle/engine/test/rooms.test.ts
+++ b/skills/anidoodle/engine/test/rooms.test.ts
@@ -3,12 +3,19 @@ import { registerRoom, roomFor, clearRooms, reverb, type Space } from "../src/ca
import { renderPiece, voiceJobs, voiceJobKey, runVoiceJob } from "../src/canvas-core/music/render";
import { nocturne } from "../src/canvas-core/music/pieces/nocturne";
import { rng } from "../src/canvas-core/core";
+import { MIX_PROFILES } from '../src/canvas-core/music/mixProfiles';
+import { musicBoxJoy, chiptunePlayful } from '../src/canvas-core/music/pieces/samplers';
+import { Biquad } from '../src/canvas-core/music/dsp';
+const fsModule = 'node:fs', { readFileSync } = await import(fsModule);
export const name = "recorded rooms";
export const run = (ok: (cond: boolean, label: string) => void) => {
const same = (a: Float32Array, b: Float32Array) => a.length === b.length && a.every((v, i) => v === b[i]);
const throws = (f: () => unknown) => { try { f(); return false; } catch { return true; } };
clearRooms();
try {
+ const builder = readFileSync('tools/soundpack.mjs', 'utf8').match(/const ROOMS = \[([\s\S]*?)\n\];/)[1];
+ const roomIds = new Set([...builder.matchAll(/id: "([^"]+)"/g)].map((m: any) => m[1]));
+ ok(Object.values(MIX_PROFILES).every(p => [p.space?.room, p.drumRoom?.room].every(id => !id || roomIds.has(id))), 'every profile room is present in the pack builder room list');
const L = new Float32Array(9600), R = new Float32Array(9600); L[0] = 0.6; R[0] = 0.5; L[3840] = 0.4; R[4320] = -0.4;
const p = nocturne(), roomPiece = { ...p, plan: { ...p.plan, space: { ...p.plan.space, room: "test" } } }, o = { seconds: 0.7, master: "none" as const, stems: true }, before = renderPiece(p, 48000, o), missing = renderPiece(roomPiece, 48000, o), jobs = voiceJobs(roomPiece, 48000, o);
ok(same(before.L, missing.L) && same(before.R, missing.R), "unregistered room falls back bit for bit");
@@ -34,5 +41,28 @@ export const run = (ok: (cond: boolean, label: string) => void) => {
const a = reverb(impulse, impulse, 48000, { ...s, kind, room: undefined }, rng(3)), b = reverb(impulse, impulse, 48000, { ...s, kind }, rng(3));
ok(a.every((c, i) => same(c, b[i])), `${kind}: missing room preserves every wet channel bit for bit`);
}
+ for (const make of [musicBoxJoy, chiptunePlayful]) {
+ const p = make(), before = renderPiece(p, 24000, o), unknown = renderPiece({ ...p, plan: { ...p.plan, space: { room: 'not-installed' } } }, 24000, o);
+ ok(same(before.L, unknown.L) && same(before.R, unknown.R), `${make.name}: an unavailable room-only override retains the original no-pack recipe`);
+ }
+ const ir = new Float32Array(4800); ir[0] = 0.8; ir[119] = 0.2; ir[240] = 0.1; ir[2400] = 0.01;
+ const recordedRoom = { L: ir, R: Float32Array.from(ir), rt60: 0.1, sha256: 'd'.repeat(64), directFrames: 120 };
+ registerRoom('trimmed', recordedRoom);
+ const roomSpace = { ...s, room: 'trimmed', predelayMs: 0, er: 1, late: 1 };
+ for (const rate of [48000, 24000]) {
+ const input = new Float32Array(rate / 2); input[0] = 1;
+ const a = reverb(input, input, rate, roomSpace, rng(1));
+ ok(a[0].slice(0, Math.round(120 * rate / 48000)).every(x => Math.abs(x) < 1e-7), `${rate} Hz: directFrames is removed before the wet reflections`);
+ }
+ const a = reverb(impulse, impulse, 48000, roomSpace, rng(1));
+ const filtered = Float32Array.from(impulse); Biquad.make(48000, 'hp', s.hp, 0.7071).run(filtered); Biquad.make(48000, 'lp', s.lp, 0.7071).run(filtered);
+ const energy = (x: Float32Array) => x.reduce((sum, v) => sum + v * v, 0);
+ const early = reverb(impulse, impulse, 48000, { ...roomSpace, late: 0 }, rng(1));
+ ok(Math.abs(energy(a[2]) / energy(filtered) - (1.5 * 0.36) ** 2) < 1e-6 && Math.abs(energy(early[0]) / energy(filtered) - 0.51 ** 2) < 1e-6, 'recorded early and late each use synthIR unit-per-channel energy');
+ registerRoom('trimmed', { ...recordedRoom, directFrames: 121 });
+ const named = { ...p, plan: { ...p.plan, space: { room: 'trimmed' } } }, oldJobs = voiceJobs(named, 48000, o);
+ registerRoom('trimmed', { ...recordedRoom, directFrames: 122 });
+ ok(voiceJobKey(oldJobs[0]) !== voiceJobKey(voiceJobs(named, 48000, o)[0]) && throws(() => runVoiceJob(oldJobs[0])), 'directFrames participates in room cache identity and stale-job rejection');
+ ok(throws(() => registerRoom('bad-direct', { ...recordedRoom, directFrames: -1 })), 'invalid directFrames is rejected');
} finally { clearRooms(); }
};