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.

merge track/S3-keys: keysVoice runs first in voice() unless ctx.legacy; renderV2 plays piano v2 (renderPianoV2) unless RenderOpts.piano asks for the v1 model, renderLegacy keeps renderPiano; the launch pieces use S3's shipped() wrapper (Piece.legacy on refits and short forms too); EQ classes for glockenspiel, wurlitzer, pipeOrgan

Alex Greenshpun8bad15042616
diff --cc skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
index 03614e5,0000000..1b8cc0a
mode 100644,000000..100644
--- a/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
@@@ -1,136 -1,0 +1,136 @@@
+// 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", vinyl: "fx",
++ 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>>;
+};
+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 --cc skills/anidoodle/engine/src/canvas-core/music/render.ts
index b359fa2,87abf0c..59625f2
--- a/skills/anidoodle/engine/src/canvas-core/music/render.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/render.ts
@@@ -5,27 -5,22 +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 { timpani as kitTimpani, 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 } from "./mixDsp";
+import { reverb, type Space } from "./mixReverb";
+import { mixProfile, partEq, ROLE_SEND, 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; space?: string } };
-const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number, legacy = false) => {
- const o = pt.opts ?? {}, r = mkRng(seed);
- if (!legacy) { const kv = keysVoice(pt.inst, keys, sr, n, o, seed); if (kv) return kv; } // S3 keys rebuild
+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);
@@@ -40,9 -35,14 +42,12 @@@
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);
@@@ -108,100 -105,8 +113,101 @@@ const renderLegacy = (piece: Piece, sr
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 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;
- 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); }
++ // 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 (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): the EQ is energy-neutral in the audible band, while stemRms
+ // (left channel, -80 dB floor) also counts subsonic residue the high-pass removes, which read one harp 6.8 dB "hotter"
+ 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; }
+ });
+ const report: NonNullable<Rendered["mixReport"]> = {};
+ // ---- 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); }