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.

Carve the lead band in recorded support stems

Alex Greenshpuneddaf9454f9a
diff --git a/skills/anidoodle/engine/src/canvas-core/music/guards.ts b/skills/anidoodle/engine/src/canvas-core/music/guards.ts
index 667a2eb..41d9474 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/guards.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/guards.ts
@@ -96,7 +96,7 @@ export const maskingPlan = (piece: Piece, o: { seconds?: number; tempo?: number;
const spans: [number, number][] = []; for (let b = 0; b < total; b += bpb) spans.push([perf.sec(b), perf.sec(b + bpb)]);
const melNotes = piece.parts.flatMap((p) => p.notes.filter((n) => n.role === "melody"));
const sounding = spans.map((_, i) => melNotes.some((n) => n.t < (i + 1) * bpb && n.t + n.d > i * bpb));
- return { roles, spans, sounding, opts: (r: Role): RenderOpts => ({ seconds: o.seconds, tempo: o.tempo, master: "none", cache: o.cache, perf: played(r) }) };
+ return { roles, spans, sounding, opts: (r: Role): RenderOpts => ({ seconds: o.seconds, tempo: o.tempo, master: "none", cache: o.cache, perf: played(r), mixKeys: perf.parts.map(p => p.keys) }) };
};
export type MaskingPlan = NonNullable<ReturnType<typeof maskingPlan>>;
export const roleBandDb = (piece: Piece, sr: number, opts: RenderOpts, spans: [number, number][]) => { const x = renderPiece(piece, sr, opts); return bandDb(x.L, x.R, sr, spans); };
diff --git a/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts b/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
index 5b3db0f..3517326 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
@@ -133,6 +133,14 @@ export const partEq = (prof: MixProfile, inst: InstId, role: Role): StemEq => {
if (role === "melody" && c !== "bass") e.bells = [...(e.bells ?? []), [2800, 1.1, 0.8 * k]];
return e;
};
+/** Leave the lead band open on recorded support parts, without changing faders or the voice. */
+export const recordedEq = (e: StemEq, role: Role, excessDb: number, fractionDb: number): StemEq => {
+ if (role !== "bass" && role !== "accomp") return e;
+ // A reference can itself be bright. Also limit absolute band occupancy toward 6% (-12 dB).
+ // One broad bell spans the guard's 500 Hz-4 kHz band; the existing makeup stage holds level.
+ const depth = Math.min(role === "bass" ? 12 : 6, Math.max(0, excessDb, fractionDb + 12) * (role === "bass" ? 0.8 : 0.6));
+ return depth > 0 ? { ...e, bells: [...(e.bells ?? []), [1400, 0.45, -depth]] } : e;
+};
/** A one-line summary for tools/music.mjs vocab. */
export const describeMix = (style: StyleId) => {
const p = MIX_PROFILES[style], s = p.space;
diff --git a/skills/anidoodle/engine/src/canvas-core/music/render.ts b/skills/anidoodle/engine/src/canvas-core/music/render.ts
index f6ac0fc..e79fbb1 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/render.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/render.ts
@@ -6,7 +6,7 @@ import { type Piece, type Part, resequence, beatsPerBar } from "./plan";
import { perform, type Performance, type Played } from "./perform";
import { renderPiano, PIANO_REAL, type PianoOpts } from "./piano";
import { keysVoice, renderPianoV2 } from "./keys";
-import { bankFor, samplerVoice, registerBank, type SampleBank, type SampleTrim } from "./sampler";
+import { bankFor, samplerVoice, sampleZones, registerBank, type SampleBank, type SampleTrim } from "./sampler";
import * as I from "./instruments";
import * as O from "./orchestra";
import { chokeTimes, type KitCtx } from "./drums";
@@ -18,10 +18,11 @@ 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, effectiveSpace, type Space } from "./mixReverb";
-import { mixProfile, partEq, ROLE_SEND, isStruck, TRANSIENT_DEFAULT, type MixProfile } from "./mixProfiles";
+import { mixProfile, partEq, recordedEq, ROLE_SEND, isStruck, TRANSIENT_DEFAULT, type MixProfile } from "./mixProfiles";
export type RenderOpts = { /** sound v2, gentle styles only: a <= 1 dB 2:1 glue on the mix bus (spec 08 forbids a compressor on gentle masters; Alex decides) */ gentleGlue?: boolean; expressive?: boolean; piano?: PianoOpts; flatVelocity?: number; seconds?: number; tempo?: number; master?: "auto" | "gentle" | "dense" | "none"; stems?: boolean; only?: (p: Part) => boolean;
/** play this performance instead of performing the piece (the guards render one role of the SAME performance the mix plays) */ perf?: Performance;
+ /** Complete part strikes keep recorded EQ fixed when a guard isolates one note role. */ mixKeys?: Played[][];
/** reuse synthesized voices by their exact inputs (tools/music.mjs check: each part is synthesized once for the mix, the guards and the stems); output is bit-identical */ cache?: VoiceCache };
/**
@@ -255,7 +256,16 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
// 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 before = audible(sL, sR, sr);
+ let e = partEq(prof, pt.inst, pt.role);
+ if (job.kind === "sampled" && (pt.role === "bass" || pt.role === "accomp")) {
+ const bank = bankFor(pt.inst, typeof pt.opts?.variant === "string" ? pt.opts.variant : undefined)!;
+ const selected = sampleZones(bank, (o.mixKeys?.[pi] ?? keys).slice().sort((a, b) => a.t - b.t || a.p - b.p), job.seed, pt.opts?.pedal === false ? [] : perf.pedal);
+ const spectra = selected.map(z => bank.trim?.find(t => t.file === z.zone.file));
+ const median = (xs: number[], fallback: number) => xs.length ? xs.sort((a, b) => a - b)[Math.floor(xs.length / 2)] : fallback;
+ e = recordedEq(e, pt.role, median(spectra.map(t => t?.bandExcessDb ?? 0), 0), median(spectra.map(t => t?.bandFractionDb ?? -Infinity), -Infinity));
+ }
+ runEq(sL, eqChain(sr, e)); runEq(sR, eqChain(sr, e));
const after = audible(sL, sR, sr), mk = after > 0 && before > 0 ? Math.min(db(3), Math.max(db(-3), Math.sqrt(before / after))) : 1;
const g = db(pt.gainDb ?? 0) * mk;
for (let i = 0; i < n; i++) { sL[i] *= g; sR[i] *= g; }
diff --git a/skills/anidoodle/engine/test/recordedMix.test.ts b/skills/anidoodle/engine/test/recordedMix.test.ts
new file mode 100644
index 0000000..aa03cff
--- /dev/null
+++ b/skills/anidoodle/engine/test/recordedMix.test.ts
@@ -0,0 +1,54 @@
+import { registerBank, clearBanks, type SampleBank } from '../src/canvas-core/music/sampler';
+import { calibrateBank, renderPiece } from '../src/canvas-core/music/render';
+import { maskingPlan, roleBandDb } from '../src/canvas-core/music/guards';
+import { perform } from '../src/canvas-core/music/perform';
+import { Biquad } from '../src/canvas-core/music/dsp';
+import { hz } from '../src/canvas-core/music/theory';
+import { marimbaCurious } from '../src/canvas-core/music/pieces/families';
+import type { Piece, Role } from '../src/canvas-core/music/plan';
+
+export const name = 'recorded support mix';
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const sr = 24000, frames = 48000, pitches = [48, 60, 72];
+ const zones = pitches.map((midi, i) => {
+ const pcm = Float32Array.from({ length: frames }, (_, n) => {
+ const t = n / 48000, f = hz(midi);
+ return 0.2 * Math.exp(-t * 3) * (Math.sin(2 * Math.PI * f * t) + (i < 2 ? 0.8 * Math.sin(2 * Math.PI * f * 5 * t) : 0));
+ });
+ return { zone: { file: `${midi}.flac`, midi, layer: 1, rr: 1, frames, channels: 1, peakDb: -6, rmsDb: -18, sha256: String(i + 1).repeat(64) }, channels: [pcm] };
+ });
+ const bank: SampleBank = { entry: { title: 'spectral fixture', source: 'synthetic', license: 'CC0-1.0', kind: 'struck', range: [48, 72], layers: 1, damped: false, normalized: false, zones: zones.map(z => z.zone) }, zones };
+ const source = marimbaCurious();
+ const part = source.parts[0];
+ const piece = (role: Role, mixed = false): Piece => ({ ...source, tail: 0.2,
+ plan: { ...source.plan, space: undefined }, mix: { ...source.mix, eq: 0, transient: null, space: null, drumRoom: null, tilt: 0, busDrive: 0, glue: null, width: { mid: 1, high: 1, monoHz: 0, splitHz: 800 } },
+ parts: [{ ...part, inst: 'marimba', role, pan: 0, gainDb: 0, notes: mixed
+ ? [{ t: 0, d: 0.4, p: 48, v: 0.5, role: 'bass' }, { t: 0.5, d: 0.4, p: 72, v: 0.5, role: 'accomp' }, { t: 1, d: 0.4, p: 72, v: 0.5, role: 'accomp' }]
+ : [{ t: 0, d: 0.4, p: role === 'bass' ? 48 : 60, v: 0.5, role }] }] });
+ const fraction = (a: Float32Array) => {
+ const x = Biquad.make(sr, 'hp', 40, Math.SQRT1_2).run(Float32Array.from(a));
+ const total = x.reduce((s, v) => s + v * v, 0);
+ Biquad.make(sr, 'hp', 500, Math.SQRT1_2).run(x); Biquad.make(sr, 'lp', 4000, Math.SQRT1_2).run(x);
+ return 10 * Math.log10(x.reduce((s, v) => s + v * v, 0) / total);
+ };
+ const rms = (a: Float32Array) => Math.sqrt(a.reduce((s, v) => s + v * v, 0) / a.length);
+ clearBanks();
+ try {
+ registerBank('marimba', bank); const calibrated = calibrateBank('marimba');
+ const neutral = { ...calibrated, trim: calibrated.trim!.map(t => ({ ...t, bandFractionDb: -40, bandExcessDb: 0 })) };
+ const render = (role: Role) => renderPiece(piece(role), sr, { seconds: 2, master: 'none', expressive: false }).dry[0];
+ registerBank('marimba', neutral); const unchanged = render('melody'), bassBefore = render('bass'), accompBefore = render('accomp');
+ registerBank('marimba', calibrated); const lead = render('melody'), bass = render('bass'), accomp = render('accomp');
+ ok(lead.every((v, i) => v === unchanged[i]), 'recorded melody keeps every sample when support EQ measurements change');
+ ok(fraction(bass) < fraction(bassBefore) - 2 && fraction(accomp) < fraction(accompBefore) - 1, 'load-measured recorded bass and accompaniment lose masking-band energy');
+ ok(Math.abs(20 * Math.log10(rms(bass) / rms(bassBefore))) < 2.5 && Math.abs(20 * Math.log10(rms(accomp) / rms(accompBefore))) < 2.5, 'support EQ retains broadband balance through the existing makeup stage');
+ const p = piece('accomp', true);
+ // Include one melody note so the guard has a melody role; keep the complete accompaniment context.
+ p.parts[0].notes[2].role = 'melody';
+ const complete = perform(p, p.plan.tempo, { expressive: false }), plan = maskingPlan(p, { seconds: 2, perf: complete })!;
+ const isolated = { ...complete, parts: complete.parts.map(q => ({ ...q, keys: q.keys.filter(k => k.role === 'bass') })) };
+ const expected = roleBandDb(p, sr, { seconds: 2, master: 'none', perf: isolated, mixKeys: complete.parts.map(q => q.keys) }, plan.spans);
+ const actual = roleBandDb(p, sr, plan.opts('bass'), plan.spans);
+ ok(actual.every((v, i) => Math.abs(v - expected[i]) < 1e-8), 'role-isolated guard uses the complete part spectral choice, including mixed-role parts');
+ } finally { clearBanks(); }
+};
diff --git a/work/S7a/mix-regression-proof.mjs b/work/S7a/mix-regression-proof.mjs
new file mode 100644
index 0000000..c6c4ba4
--- /dev/null
+++ b/work/S7a/mix-regression-proof.mjs
@@ -0,0 +1,23 @@
+import { build } from '../../skills/anidoodle/engine/node_modules/esbuild/lib/main.js';
+import { readFileSync } from 'node:fs';
+import assert from 'node:assert/strict';
+const engine = new URL('../../skills/anidoodle/engine/', import.meta.url).pathname;
+for (const mode of ['current', 'without-support-eq', 'without-guard-context']) {
+ const plugins = [{ name: mode, setup(b) {
+ b.onLoad({ filter: /(?:mixProfiles|guards)\.ts$/ }, ({ path }) => {
+ let contents = readFileSync(path, 'utf8');
+ if (mode === 'without-support-eq' && path.endsWith('/mixProfiles.ts'))
+ contents = contents.replace('if (role !== "bass" && role !== "accomp") return e;', 'return e;');
+ if (mode === 'without-guard-context' && path.endsWith('/guards.ts'))
+ contents = contents.replace(', mixKeys: perf.parts.map(p => p.keys)', '');
+ return { contents, loader: 'ts' };
+ });
+ } }];
+ const js = (await build({ entryPoints: [engine + 'test/recordedMix.test.ts'], bundle: true, format: 'esm', write: false, plugins })).outputFiles[0].text;
+ const test = await import('data:text/javascript;base64,' + Buffer.from(js).toString('base64') + '#' + mode);
+ const failed = [];
+ test.run((pass, label) => { if (!pass) failed.push(label); });
+ console.log(`${mode}: ${failed.length} failures${failed.length ? '\n ' + failed.join('\n ') : ''}`);
+ assert.equal(failed.length, mode === 'current' ? 0 : 1);
+}
+console.log('MIX REGRESSION PROOF PASS');