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.

music v2: render through the mix chain (per-stem EQ level-matched, drum bus, sends to the style's space + kit room, glue on dense masters, gentle glue behind RenderOpts.gentleGlue, width with mono lows, smooth limiter); per-lane feel in perform (lane offsets, humanize vs jitter, relative velocity, Played.tone/vary hooks); Piece.legacy freezes the launch scores (launchLofi3 md5 unchanged)

Alex Greenshpun70b7055e8eb8
diff --git a/skills/anidoodle/engine/src/canvas-core/music/compose.ts b/skills/anidoodle/engine/src/canvas-core/music/compose.ts
index dc1b9dd..f6404da 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/compose.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/compose.ts
@@ -11,6 +11,7 @@ import { perform } from "./perform";
import { drumBar, 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. */
@@ -144,10 +147,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/skills/anidoodle/engine/src/canvas-core/music/index.ts b/skills/anidoodle/engine/src/canvas-core/music/index.ts
index d8bfe6e..6984beb 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/index.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/index.ts
@@ -17,6 +17,7 @@ export * from "./calibration";
export * as instruments from "./instruments";
export * from "./sfx";
export * as orchestra from "./orchestra";
+export { MIX_PROFILES, FEELS, mixProfile, describeMix, type MixProfile, type Feel } from "./mixProfiles";
import { nocturne, pianoPhrase8 } from "./pieces/nocturne";
import { launchLofi, launchLofi2, launchLofi3, launchLofi3Material } from "./pieces/launch";
import { musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic } from "./pieces/samplers";
diff --git a/skills/anidoodle/engine/src/canvas-core/music/perform.ts b/skills/anidoodle/engine/src/canvas-core/music/perform.ts
index 3b0aa62..af165fe 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/perform.ts
+++ b/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/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts b/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
index 65ea174..66526d8 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
@@ -75,7 +75,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: {
@@ -113,7 +113,7 @@ export const launchLofi = (): Piece => {
const sparkle = byBar("color", 0.5, (b, ci) => (inRanges(b, [[11, 13], [23, 25], [30, 35]]) ? SPARK[ci] : null));
const harmony = Array.from({ length: LAUNCH_BARS }, (_, b) => ({ t: b * 4, name: b < 2 ? ["Cmaj9", "Am9"][b] : b === last ? "Cmaj9" : ["Dm9", "G13", "Cmaj9", "Am9"][(b - 2) % 4] }));
return {
- title: "anidoodle launch, upbeat chill electronic", seed: 2027, tail: 3.2, harmony,
+ title: "anidoodle launch, upbeat chill electronic", seed: 2027, tail: 3.2, harmony, legacy: true,
plan: { style: "lofi", tempo: LAUNCH_BPM, meter: "4/4", swing: 0.54, ritard: 0.92, sections: [{ id: "a", bars: LAUNCH_BARS, mood: "calm", key: "C", mode: "major", melody: ["stepwise", "hook"], dyn: [0.62, 0.66], ending: "tail", repeatable: false }] },
parts: [
{ id: "pad", inst: "warmPad", role: "accomp", notes: pad, gainDb: -3, opts: { cut: 2600, attack: 0.5, release: 1.4, spread: 0.55 }, send: 0.35 },
diff --git a/skills/anidoodle/engine/src/canvas-core/music/plan.ts b/skills/anidoodle/engine/src/canvas-core/music/plan.ts
index c7fd979..dd76bb3 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/plan.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/plan.ts
@@ -3,6 +3,7 @@
// 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 { 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). */
@@ -29,6 +30,8 @@ export type Chord = { t: number; name: string };
/** Bus moves (lofiKit): `duck` pumps the named parts on every onset of the `by` part; `tape` wobbles and saturates the master. */
export type PieceFx = { clean?: boolean /* skip the lo-fi master tone (low-pass, shelf, saturation) */; duck?: { by: string; parts: string[]; depth?: number; release?: number }; tape?: { wowCents?: number; wowHz?: number; flutterCents?: number; flutterHz?: number; drive?: number } };
export type Piece = { title: string; plan: MusicPlan; parts: Part[]; harmony: Chord[]; tail: number; seed: number; fx?: PieceFx;
+ /** 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/skills/anidoodle/engine/src/canvas-core/music/render.ts b/skills/anidoodle/engine/src/canvas-core/music/render.ts
index f9fa296..3cc205f 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/render.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/render.ts
@@ -12,13 +12,18 @@ import { warmPad, softPluck, sub, duckCurve, tape } from "./lofiKit";
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) => {
- const o = pt.opts ?? {}, r = mkRng(seed);
+const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number, legacy = false) => {
+ // legacy pieces hand every voice `legacy: true` so a rebuilt voice can keep its old path for them
+ const o = legacy ? { ...(pt.opts ?? {}), legacy: true } : pt.opts ?? {}, r = mkRng(seed);
switch (pt.inst) {
case "musicBox": return I.musicBox(keys, sr, n, o);
case "bell": return I.bell(keys, sr, n, o);
@@ -52,7 +57,10 @@ const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) =>
}
};
-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 +74,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, 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 +108,97 @@ 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 ? duckCurve(perf.parts[byIdx].keys.map((k) => k.t), sr, n, dk.depth ?? 0.4, dk.release ?? 0.28) : null;
+ 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); }
+ else { const r = voice(pt, keys, sr, n, piece.seed * 101 + pi); 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]; }
+ // 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), lo-fi tone, 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 (style.id === "lofi" && !piece.fx?.clean) { for (const c of [L, R]) { Biquad.make(sr, "lp", 8500, 0.6).run(c); Biquad.make(sr, "highshelf", 5000, 0.7, -3).run(c); for (let i = 0; i < n; i++) c[i] = Math.tanh(c[i] * 1.2) / 1.2; } }
+ if (piece.fx?.tape) tape(L, R, sr, piece.fx.tape);
+ 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 +206,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 +226,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 };
};