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 Greenshpun7970552c1a7a
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/calibration.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/calibration.ts
index 45183e2..ff2f6af 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/calibration.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/calibration.ts
@@ -6,7 +6,7 @@ import { MODES, nameOf, type ModeId } from "./theory";
import type { Material } from "./compose";
import type { StyleVocab } from "./vocab";
-export const testMaterial = (v: StyleVocab, o: { loop?: boolean; bars?: number; key?: string; tonic?: number; mode?: ModeId } = {}): Material => {
+export const testMaterial = (v: StyleVocab, o: { loop?: boolean; bars?: number; key?: string; tonic?: number; mode?: ModeId; /** write the counter / arp line even when the palette has no voice there (to measure an alternate or your own voice) */ lines?: ("counter" | "arp")[] } = {}): Material => {
const mode = o.mode ?? v.harmony.modes.find((x) => MODES[x].intervals.length === 7) ?? "major", iv = MODES[mode].intervals, meter = v.meters[0], bpb = beatsPerBar(meter), comp = isCompound(meter), bars = o.bars ?? 8;
const deg = (d: number, oct: number) => 12 * (oct + 1) + (o.tonic ?? 0) + iv[((d % 7) + 7) % 7] + 12 * Math.floor(d / 7), unit = comp ? "1/3" : ".5", count = Math.round(bpb * (comp ? 3 : 2));
const degs = [0, 3, 4, 5], chords: Material["chords"] = {};
@@ -16,6 +16,6 @@ export const testMaterial = (v: StyleVocab, o: { loop?: boolean; bars?: number;
return { style: v.id, title: `test signal: ${v.id}`, seed: 1, mood: v.moods[0], bpm: Math.round((v.tempo[0] + v.tempo[1]) / 2), key: o.key ?? "C", mode, meter, chords, loop: o.loop,
grooves: v.grooves.length ? { main: { family: v.grooves[0], density: 0.5, variation: 0.35 } } : {},
sections: [{ kind: "hook", bars, harmony: ["c0", "c1", "c2", "c3"], groove: v.grooves.length ? "main" : null,
- lead: bar((d, j) => deg(d + (j % 5), 5)), ...(v.palette.arp ? { arp: bar((d, j) => deg(d + [0, 2, 4, 2][j % 4], 4)) } : {}),
- ...(v.palette.counter ? { counter: Array.from({ length: bars }, (_, b) => `${nameOf(deg(degs[b % 4] + 4, 6))}:${half} ${nameOf(deg(degs[b % 4] + 2, 6))}:${half}`) } : {}) }] };
+ lead: bar((d, j) => deg(d + (j % 5), 5)), ...(v.palette.arp || o.lines?.includes("arp") ? { arp: bar((d, j) => deg(d + [0, 2, 4, 2][j % 4], 4)) } : {}),
+ ...(v.palette.counter || o.lines?.includes("counter") ? { counter: Array.from({ length: bars }, (_, b) => `${nameOf(deg(degs[b % 4] + 4, 6))}:${half} ${nameOf(deg(degs[b % 4] + 2, 6))}:${half}`) } : {}) }] };
};
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 086a8bb..95c0c1f 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
@@ -10,22 +10,40 @@ import { pcOf } from "./theory";
import { perform } from "./perform";
import { drumBar, laneKind, type Groove, type Lane } from "./grooves";
import { VOCAB_TRIM, VOCAB_TARGET_FIX } from "./vocabTrim";
+import { VOCAB_ALT_TRIM, VOCAB_ALT_TARGET_FIX, INST_LEVEL, INST_REGISTER, SLOT_REF_PITCH } from "./vocabVoices";
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. */
+/**
+ * One chord of YOUR harmony: its voicing and a one-bar bass line you wrote for it. The voicing is a
+ * notation chord ("[C3 G3 E4]"), one note ("E4"), or "r": the chord part rests while the chord is
+ * still the harmony (named for the key check, craft, novelty and the bass), for a bar the bass or an
+ * arp states alone.
+ */
export type ComposedChord = { voicing: string; bass?: string };
/** A line = notation bars, or names of your motifs, joined in order from the section's first bar. */
export type LineSpec = string | string[];
export type ComposedSection = {
id?: string; kind: SectionKind; bars: number;
- /** chord names per bar (keys of `chords`), cycled to fill the section; a bar may hold two: "Dm9 G13" splits it */
+ /**
+ * chord names per bar (keys of `chords`), cycled to fill the section. A bar may hold several: "Dm9 G13"
+ * splits it where the meter splits (splitBar: 4/4 2+2, 3/4 2+1, 5/4 3+2, 6/8 3+3 eighths, 7/8 4+3
+ * eighths, or your `grouping`), or give each chord its beats: "Dm9:1 G13:2". "~" holds the chord before
+ * it: tied over the bar line, no restrike ("Cmaj9", "~" = one chord for two bars; "~ G13" holds into
+ * the bar, then changes).
+ */
harmony: string[];
+ /**
+ * the chord part's rhythm, one bar per item (or bars joined with "|"), cycled over the section:
+ * "x:DUR[@VEL]" strikes the chord sounding at that point, "r:DUR" rests, "~:DUR" (a bar's first token)
+ * holds the last strike over the bar line. Without it, each chord is held for its whole span.
+ */
+ comp?: string | string[];
/** lines play ONCE from the section's first bar (harmony cycles, lines do not); a shorter line leaves rests, unless `loopLines` */
lead?: LineSpec; counter?: LineSpec; arp?: LineSpec;
/** repeat each line to fill the section (a 2-bar motif in an 8-bar section plays 4 times) */ loopLines?: boolean;
/** modulate: this section's key and mode (default the piece's); the key check reads each key region separately */ key?: string; mode?: ModeId;
- /** override the chords' bass lines for this section (one bar of notation, or one per bar) */ bass?: string | string[];
+ /** override the chords' bass lines for this section (one bar of notation, or one per bar; "~" ties the bass over that bar line) */ bass?: string | string[];
/** a key of `grooves`, or null for no drums; default by kind (main / half / build / none) */ groove?: string | null;
/** chord velocity scale (0..1.2), e.g. 0.8 for a softer intro */ chordVel?: number;
/** 0..1 (0.5 = as written): the section's dynamics for EVERY part (velocity x 0.55..1.45, about -5..+3 dB) and the density of generated grooves */ energy?: number;
@@ -35,22 +53,59 @@ export type Material = {
style: StyleId; title: string; seed: number; mood: MoodId; bpm: number; key: string; mode: ModeId; meter?: Meter;
chords: Record<string, ComposedChord>; motifs?: Record<string, string>; grooves?: Record<string, Groove>;
sections: ComposedSection[];
- /** swap a slot's voice for one of the style's alternates by name, or give your own Voice */ voices?: Partial<Record<Slot, string | Voice>>;
+ /**
+ * swap a slot's voice for one of the style's alternates by name, or give your own voice. Both are
+ * calibrated to the slot's stem target: an alternate by its measured trim, your own voice from its
+ * instrument's measured level. Your voice's `gainDb` is a dB OFFSET from there (0 or left out = at the
+ * target), the same scale as `levels`.
+ */
+ voices?: Partial<Record<Slot, string | CustomVoice>>;
/** dB OFFSET per slot, added to the voice's calibrated gain (after trims and mood): +2 = two dB louder. Set from the stem meter. */ levels?: Partial<Record<Slot, number>>;
moodControls?: MoodControls;
/** 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;
+ /** how a bar divides into beat groups (in beats, summing to the bar), e.g. [2, 3] for a 5/4 felt 2+3 or [1.5, 1, 1] for a 7/8 felt 3+2+2: where a split bar ("A B", "A B C") changes chord (default: splitBar's table) */ grouping?: number[];
/** 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>;
};
+/** Your own voice for a slot: an instrument, its role, options, send and pan. `gainDb` is a dB offset from the calibrated level (0 = at the slot's stem target). */
+export type CustomVoice = Omit<Voice, "gainDb"> & { gainDb?: number };
+/** An instrument's level against its register (INST_REGISTER, dB, linear between the measured octaves, held past the ends). */
+const regAt = (inst: string, p: number) => { const c = INST_REGISTER[inst]; if (!c?.length) return 0; if (p <= c[0][0]) return c[0][1]; for (let i = 1; i < c.length; i++) if (p <= c[i][0]) return c[i - 1][1] + ((c[i][1] - c[i - 1][1]) * (p - c[i - 1][0])) / (c[i][0] - c[i - 1][0]); return c[c.length - 1][1]; };
+/** Where your own voice sits at gainDb 0: its instrument's measured level on the slot's test line (a drum lane without its own reads its neighbour's), moved to the register your notes play in. */
+const instLevel = (inst: string, slot: Slot, ns: Note[] = []) => {
+ const lv = INST_LEVEL[inst]?.[slot] ?? INST_LEVEL[inst]?.[({ ghost: "snare", perc: "hat", snare: "ghost", hat: "perc" } as Partial<Record<Slot, Slot>>)[slot] ?? slot], ref = SLOT_REF_PITCH[slot];
+ if (lv === undefined || ref === undefined || !ns.length) return lv;
+ const ps = ns.map((n) => n.p).sort((a, b) => a - b); return lv + regAt(inst, ps[Math.floor(ps.length / 2)]) - regAt(inst, ref);
+};
+
/** line() with the composer's context on its error: which section, slot or chord wrote the bad bar. */
const lineIn = (where: string, ...a: Parameters<typeof line>) => { try { return line(...a); } catch (e) { throw new Error(`compose: ${where}: ${(e as Error).message}`); } };
const need = (ok: unknown, msg: string) => { if (!ok) throw new Error(`compose: ${msg} The style supplies sound, never notes: compose it yourself (references/music/compose.md).`); };
const fmt = (x: number) => String(+x.toFixed(4));
const lanes: Lane[] = ["kick", "snare", "ghost", "hat", "perc"];
+/**
+ * Where a bar of `k` chords changes, in beats per chord. Two chords split on the meter's strong
+ * division, not the arithmetic middle: 2/4 1+1, 3/4 2+1 (a waltz changes on beat 3, never on 2.5),
+ * 4/4 2+2, 5/4 3+2, 6/8 1+1 (3+3 eighths), 7/8 2+1.5 (4+3 eighths), 9/8 2+1, 12/8 2+2. Three chords:
+ * 3/4 1+1+1, 4/4 2+1+1, 5/4 2+1+2... see the table. A `grouping` with k groups wins; otherwise a
+ * count the table does not name divides the bar evenly. Explicit beats ("A:1 B:2") override all of it.
+ */
+const SPLITS: Partial<Record<Meter, Record<number, number[]>>> = {
+ "2/4": { 2: [1, 1] }, "3/4": { 2: [2, 1], 3: [1, 1, 1] }, "4/4": { 2: [2, 2], 3: [2, 1, 1], 4: [1, 1, 1, 1] },
+ "5/4": { 2: [3, 2], 3: [2, 1, 2], 5: [1, 1, 1, 1, 1] }, "6/8": { 2: [1, 1] }, "7/8": { 2: [2, 1.5], 3: [1, 1, 1.5] },
+ "9/8": { 2: [2, 1], 3: [1, 1, 1] }, "12/8": { 2: [2, 2], 3: [2, 1, 1], 4: [1, 1, 1, 1] },
+};
+export const splitBar = (meter: Meter, k: number, grouping?: number[]): number[] => {
+ const bpb = beatsPerBar(meter);
+ if (k <= 1) return [bpb];
+ if (grouping && grouping.length === k) return grouping;
+ return SPLITS[meter]?.[k] ?? Array.from({ length: k }, () => bpb / k);
+};
+
/** Expand repeats: the sections as played, with their first bar. */
export const layout = (sections: ComposedSection[]) => {
const out: { s: ComposedSection; id: string; from: number; to: number; pass: number }[] = []; let b = 0;
@@ -70,13 +125,27 @@ export const composePiece = (m: Material): Piece => {
const motif = (x: string) => { const v = m.motifs?.[x]; if (v !== undefined) return v; need(/[:|]/.test(x), `no motif named "${x}": add motifs["${x}"] = "<bars of notation>", or write the notes inline (NOTE:DUR ...).`); return x; };
const lineOf = (spec: LineSpec) => (Array.isArray(spec) ? spec : [spec]).map(motif).join(" | ");
- // ---- harmony per bar (a bar may split into chords: "A B" = two halves)
- const chordAt: string[][] = [];
+ // ---- harmony per bar: chords with their beats; "~" holds the chord before it (tied, no restrike)
+ need(!m.grouping || Math.abs(m.grouping.reduce((a, x) => a + x, 0) - bpb) < 1e-6, `grouping [${m.grouping?.join(", ")}] must add up to the bar (${bpb} beats in ${meter}).`);
+ type Seg = { name: string; at: number; d: number; tie: boolean };
+ const bars: Seg[][] = []; let prev: string | undefined;
for (const x of lay) {
need(x.s.harmony?.length, `section "${x.id}" has no harmony: write the chord names for its bars.`);
- for (let i = 0; i < x.s.bars; i++) { const names = x.s.harmony[i % x.s.harmony.length].trim().split(/\s+/); for (const n of names) need(m.chords[n], `chord "${n}" (section "${x.id}") has no voicing: add chords["${n}"] = { voicing: "[...]", bass: "..." }.`); chordAt.push(names); }
+ for (let i = 0; i < x.s.bars; i++) {
+ const src = x.s.harmony[i % x.s.harmony.length].trim(), toks = src.split(/\s+/).map((t) => { const [name, beats] = t.split(":"); return { name, beats: beats === undefined ? undefined : Number(beats) }; });
+ const given = toks.filter((t) => t.beats !== undefined).length;
+ need(given === 0 || given === toks.length, `harmony bar "${src}" (section "${x.id}"): give every chord its beats ("A:2 B:1") or none ("A B" splits where the meter does).`);
+ const ds = given ? toks.map((t) => t.beats!) : splitBar(meter, toks.length, m.grouping);
+ need(ds.every((d) => Number.isFinite(d) && d > 0) && Math.abs(ds.reduce((a, d) => a + d, 0) - bpb) < 1e-6, `harmony bar "${src}" (section "${x.id}") adds up to ${+ds.reduce((a, d) => a + d, 0).toFixed(4)} beats; a ${meter} bar is ${bpb}.`);
+ let at = 0; const segs: Seg[] = [];
+ toks.forEach((t, j) => { const tie = t.name === "~"; need(!tie || prev, `section "${x.id}": "~" holds the chord before it, but nothing comes before it.`);
+ const name = tie ? prev! : t.name; need(m.chords[name], `chord "${name}" (section "${x.id}") has no voicing: add chords["${name}"] = { voicing: "[...]", bass: "..." }.`);
+ segs.push({ name, at, d: ds[j], tie }); at += ds[j]; prev = name; });
+ bars.push(segs);
+ }
}
- const harmony = chordAt.flatMap((names, b) => names.map((name, j) => ({ t: b * bpb + (j * bpb) / names.length, name })));
+ const chordAt = bars.map((segs) => [...new Set(segs.map((g) => g.name))]);
+ const harmony = bars.flatMap((segs, b) => segs.filter((g) => !g.tie).map((g) => ({ t: b * bpb + g.at, name: g.name })));
const at = (b: number) => lay.find((x) => b >= x.from && b < x.to)!;
// ---- notes
@@ -84,14 +153,36 @@ export const composePiece = (m: Material): Piece => {
const push = (slot: Slot, ns: Note[]) => { (notes[slot] ??= []).push(...ns); };
const vel: Record<Slot, number> = { chords: 0.62, lead: 0.72, counter: 0.5, bass: 0.85, arp: 0.55, kick: 0.85, snare: 0.7, ghost: 0.5, hat: 0.5, perc: 0.45 };
const role = (slot: Slot): Role => (slot === "chords" || slot === "arp" ? "accomp" : slot === "lead" ? "melody" : slot === "counter" ? "color" : slot === "bass" ? "bass" : "drum");
+ /** extend the chord-part notes that end exactly at beat t by d beats: a tie, no restrike */
+ const holdIn = (slot: Slot) => (t: number, d: number) => { for (const n of notes[slot] ?? []) if (Math.abs(n.t + n.d - t) < 1e-9) n.d += d; };
+ /** a tie: the chord part's (hold) or the bass's (hold2) notes that end exactly at beat t sound d beats longer, no restrike */
+ const hold = holdIn("chords"), hold2 = holdIn("bass");
+ const comps = new Map<ComposedSection, string[]>();
+ for (const x of lay) if (x.s.comp !== undefined) comps.set(x.s, (Array.isArray(x.s.comp) ? x.s.comp : [x.s.comp]).join(" | ").split("|").map((z) => z.trim()).filter(Boolean));
for (let b = 0; b < B; b++) {
- const x = at(b), cv = x.s.chordVel, names = chordAt[b], d = bpb / names.length;
- const src = names.map((n) => `${m.chords[n].voicing}:${fmt(d)}${cv !== undefined ? `@${fmt(cv)}` : ""}`).join(" ");
- push("chords", lineIn(`section "${x.id}" chords (bar ${b})`, b * bpb, src, { role: "accomp", v: vel.chords, bpb, roll: 0.03 }));
+ const x = at(b), cv = x.s.chordVel, names = chordAt[b], segs = bars[b], vtok = (name: string, d: number, v?: number) => { const k = v === undefined ? cv : (cv ?? 1) * v; return `${m.chords[name].voicing}:${fmt(d)}${k !== undefined ? `@${fmt(k)}` : ""}`; };
+ const comp = comps.get(x.s);
+ if (comp) { // the chord part's rhythm: x strikes the chord sounding at that point, r rests, ~ holds the last strike over the bar line
+ const cb = comp[(b - x.from) % comp.length], toks: string[] = []; let o = 0;
+ cb.split(/\s+/).forEach((tk, i) => { const q = /^(x|r|~):([0-9./]+)(?:@([0-9.]+))?$/.exec(tk); need(q, `section "${x.id}" comp bar "${cb}": "${tk}" is not x:DUR[@VEL], r:DUR or ~:DUR.`);
+ const d = q![2].includes("/") ? Number(q![2].split("/")[0]) / Number(q![2].split("/")[1]) : Number(q![2]);
+ if (q![1] === "~") { need(i === 0, `section "${x.id}" comp bar "${cb}": "~" holds the last strike over the bar line, so it comes first.`); hold(b * bpb, d); toks.push(`r:${fmt(d)}`); }
+ else if (q![1] === "r") toks.push(`r:${fmt(d)}`);
+ else toks.push(vtok(segs.filter((g) => g.at <= o + 1e-9).pop()!.name, d, q![3] ? Number(q![3]) : undefined));
+ o += d; });
+ need(Math.abs(o - bpb) < 1e-6, `section "${x.id}" comp bar "${cb}" sums to ${+o.toFixed(4)} beats; a ${meter} bar is ${bpb}${o < bpb ? ` (end it with its rest: "${cb} r:${+(bpb - o).toFixed(4)}")` : ""}.`);
+ push("chords", lineIn(`section "${x.id}" comp (bar ${b})`, b * bpb, toks.join(" "), { role: "accomp", v: vel.chords, bpb, roll: 0.03 }));
+ } else {
+ segs.forEach((g) => { if (g.tie) hold(b * bpb + g.at, g.d); });
+ const src = segs.map((g) => (g.tie ? `r:${fmt(g.d)}` : vtok(g.name, g.d))).join(" ");
+ if (segs.some((g) => !g.tie)) push("chords", lineIn(`section "${x.id}" chords (bar ${b})`, b * bpb, src, { role: "accomp", v: vel.chords, bpb, roll: 0.03 }));
+ }
if (KINDS[x.s.kind].bass) {
+ // the bass keeps its own rhythm under a held chord (the chord's bass line plays again); a bass bar "~" ties the bass over the bar line instead
const ov = x.s.bass, bl = ov !== undefined ? (Array.isArray(ov) ? ov[(b - x.from) % ov.length] : ov) : names.length === 1 ? m.chords[names[0]].bass : undefined;
need(bl !== undefined, names.length > 1 ? `bar ${b} splits into ${names.join(" + ")}: give section "${x.id}" a bass override for it.` : `chord "${names[0]}" (section "${x.id}") has no bass line: add chords["${names[0]}"].bass (one bar), or a section bass override.`);
- if (bl) push("bass", lineIn(`section "${x.id}" bass (bar ${b}${names.length === 1 && ov === undefined ? `, chords["${names[0]}"].bass` : ""})`, b * bpb, bl, { role: "bass", v: vel.bass, bpb }));
+ if (bl?.trim() === "~") hold2(b * bpb, bpb);
+ else if (bl) push("bass", lineIn(`section "${x.id}" bass (bar ${b}${names.length === 1 && ov === undefined ? `, chords["${names[0]}"].bass` : ""})`, b * bpb, bl, { role: "bass", v: vel.bass, bpb }));
}
// drums
const def = KINDS[x.s.kind].drums, gname = x.s.groove === undefined ? def : x.s.groove;
@@ -125,17 +216,21 @@ export const composePiece = (m: Material): Piece => {
for (const slot of slots) {
const pick = m.voices?.[slot];
const FALLBACK: Partial<Record<Slot, Slot>> = { perc: "hat", ghost: "snare", snare: "ghost", hat: "perc" }; // a drum lane without its own voice borrows its neighbour's
- let v = typeof pick === "object" ? pick : typeof pick === "string" ? vocab.alternates[slot]?.[pick] : vocab.palette[slot] ?? (notes[slot]?.length && FALLBACK[slot] ? vocab.palette[FALLBACK[slot]!] : undefined);
+ let v = typeof pick === "object" ? { ...pick, gainDb: pick.gainDb ?? 0 } : typeof pick === "string" ? vocab.alternates[slot]?.[pick] : vocab.palette[slot] ?? (notes[slot]?.length && FALLBACK[slot] ? vocab.palette[FALLBACK[slot]!] : undefined);
need(typeof pick !== "string" || v, `style ${vocab.id} has no "${pick}" voice for ${slot} (have: ${Object.keys(vocab.alternates[slot] ?? {}).join(", ") || "none"}).`);
if (!v) { if (slot === "chords") continue; /* a style without a chord voice (chiptune): the harmony still labels bars and feeds the bass */ need(!notes[slot]?.length, `style ${vocab.id} has no ${slot} voice, but your ${slot} has notes: pick a groove family or slot this style has.`); continue; }
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];
- // 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;
+ const lv = m.levels?.[slot], fix = VOCAB_TARGET_FIX[vocab.id]?.[slot] ?? 0, st = vocab.stemTargets[slot];
+ // every voice in a slot is calibrated to the slot's target (the style's number plus its fix): the palette's voice by VOCAB_TRIM, an
+ // alternate by VOCAB_ALT_TRIM, your own voice from its instrument's measured level (INST_LEVEL), its gainDb an offset from there.
+ // A legacy (shipped) score keeps the gains it was listened at: no trim.
+ const lvl = typeof pick === "object" ? instLevel(v.inst, slot, notes[slot]) : undefined, altFix = typeof pick === "string" && !m.legacy ? VOCAB_ALT_TARGET_FIX[vocab.id]?.[slot]?.[pick] ?? 0 : 0;
+ const trim = m.legacy ? 0 : pick === undefined ? VOCAB_TRIM[vocab.id]?.[slot] ?? 0 : typeof pick === "string" ? VOCAB_ALT_TRIM[vocab.id]?.[slot]?.[pick] ?? 0 : lvl !== undefined ? (st !== undefined ? st + fix : -20) - lvl : 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
+ if (st !== undefined) targets[slot] = st + dGain + (pick === undefined || !m.legacy ? fix : 0) + altFix; // a mood that lifts the hats lifts their target too; the slot's target is every voice's (the fix included)
const p: Part = { id: slot, inst: v.inst, role: v.role, notes: notes[slot] ?? [], gainDb };
if (v.opts) p.opts = v.opts; if (v.send !== undefined) p.send = v.send; if (v.pan !== undefined) p.pan = v.pan;
parts.push(p);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craft.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craft.ts
index 566e41c..1074dad 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craft.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craft.ts
@@ -128,12 +128,44 @@ const classifyNct = (prev: Note | undefined, n: Note, next: Note | undefined): N
return "other";
};
+// ------------------------------------------------------------------ tension
+type TensionBar = { harm: number; loud: number; dens: number; reg: number };
+/**
+ * Weights of the per-bar tension blend. Intensity leads (loudness 0.35, onset density 0.25, the top
+ * voice's register 0.15), harmonic lean follows (0.25: the chord root's function 0.15, the
+ * sonority's dissonance 0.10). Calibrated on the craft tests' good and bad fixtures (a home-chord
+ * tutti climax and an EDM drop must read as the peak; a dominant that leans quietly must not).
+ */
+export const TENSION_WEIGHTS = { loudness: 0.35, density: 0.25, register: 0.15, root: 0.15, dissonance: 0.1 };
+/** Loudness range (dB under the piece's loudest bar) that the loudness term spans 1 -> 0. */
+export const TENSION_LOUD_RANGE_DB = 12;
+const tensionBars = (c: Ctx, ch: { t: number; name: string }[]) => {
+ const { bpb, mel } = c, nBars = Math.max(1, Math.ceil(c.end / bpb - E)), targets = c.p.stemTargets ?? {};
+ const top = topVoice(c.notes.filter((n) => n.role !== "drum" && n.role !== "bass")), topR = top.length ? [Math.min(...top.map((n) => n.p)), Math.max(...top.map((n) => n.p))] : [60, 72];
+ const melR = mel.length ? [Math.min(...mel.map((n) => n.p)), Math.max(...mel.map((n) => n.p))] : topR;
+ const raw = Array.from({ length: nBars }, (_, b) => { const a = b * bpb, z = a + bpb, ns = c.notes.filter((n) => n.t >= a - E && n.t < z - E);
+ const h = ch.filter((x) => x.t <= a + E).pop(), k = c.keyAt(a), r = rootAt(c, h ? Math.max(h.t, a) : a), fn = r < 0 ? 0 : ROOT_TENSION[mod12(r - k.tonic)];
+ const pcs = [...new Set(sounding(c, a + 0.01, ["accomp", "inner", "bass", "melody", "color"]).map((n) => mod12(n.p)))]; let ds = 0, pr = 0; for (let i = 0; i < pcs.length; i++) for (let j = i + 1; j < pcs.length; j++) { const ic = Math.min(mod12(pcs[j] - pcs[i]), 12 - mod12(pcs[j] - pcs[i])); ds += IC_DISSONANCE[ic]; pr++; }
+ // loudness: every part sounding in the bar adds power, v^2 x its share of the bar (a hit counts a quarter beat), weighted by the part's stem target when the piece has them
+ const pow = new Map<string, number>();
+ for (const n of c.notes) { const on = Math.min(z, n.t + (n.role === "drum" ? 0.25 : n.d)) - Math.max(a, n.t); if (on <= E) continue; const part = (n as { part?: string }).part ?? "";
+ pow.set(part, Math.max(pow.get(part) ?? 0, n.v * n.v * Math.min(1, on / Math.min(bpb, n.role === "drum" ? 0.25 : bpb)))); }
+ let power = 0; for (const [part, x] of pow) power += x * (targets[part] !== undefined ? 10 ** (targets[part] / 10) : 1e-2);
+ // register: the melody's mean pitch over its range; a bar without melody reads the top voice over its range
+ const mb = mel.filter((n) => n.t >= a - E && n.t < z - E), tb = top.filter((n) => n.t >= a - E && n.t < z - E);
+ const reg = mb.length ? (mean(mb.map((n) => n.p)) - melR[0]) / Math.max(1, melR[1] - melR[0]) : tb.length ? (mean(tb.map((n) => n.p)) - topR[0]) / Math.max(1, topR[1] - topR[0]) : 0;
+ return { fn, diss: pr ? ds / pr : 0, onsets: new Set(ns.map((n) => Math.round(n.t * 48))).size / bpb, power, reg }; });
+ const loudDb = raw.map((x) => (x.power > 0 ? 10 * Math.log10(x.power) : -Infinity)), maxDb = Math.max(...loudDb), md = Math.max(E, ...raw.map((x) => x.onsets)), W = TENSION_WEIGHTS;
+ const out: TensionBar[] = raw.map((x, i) => ({ harm: (W.root * x.fn + W.dissonance * x.diss) / (W.root + W.dissonance), loud: Number.isFinite(loudDb[i]) ? Math.max(0, 1 - (maxDb - loudDb[i]) / TENSION_LOUD_RANGE_DB) : 0, dens: x.onsets / md, reg: x.reg }));
+ return { raw: out, bars: out.map((x) => +((W.root + W.dissonance) * x.harm + W.loudness * x.loud + W.density * x.dens + W.register * x.reg).toFixed(3)) };
+};
+
// ------------------------------------------------------------------ the report
export type CraftReport = {
melody: { phrases: number; contours: Record<string, number>; leaps: number; leapsRecovered: number; stepShare: number; range: [string, string] | null; repetition: number; development: Record<Development, number>; exactBarCopies: number; stableEnds: number; lastNote: string | null; climax: { note: string; at: number; times: number } | null; strongBeatChordTones: number; ncts: Record<NCT, number> };
harmony: { cadences: { id: string; type: string; motion: string }[]; parallels: number; octaveDoublings: number; innerJumps: number; meanMotion: number; leadUnderChords: number; mud: { at: string; notes: string }[] };
rhythm: { syncopation: { melody: number; bass: number; drums: number }; density: { id: string; perBeat: number; layers: number }[]; grooveConsistency: number | null; chordChangesOnBeats: number; repeatedSections: string[] };
- tension: { sections: { id: string; value: number }[]; peakAt: number; bars: number[] };
+ tension: { sections: { id: string; value: number; harmonic: number; loudness: number; density: number; register: number }[]; peakAt: number; bars: number[] };
mood: { mood: MoodId; checks: { what: string; value: string; want: string; ok: boolean }[] };
scores: { melody: number; harmony: number; rhythm: number; tension: number; mood: number };
findings: Finding[];
@@ -260,20 +292,19 @@ export const craftReport = (p: Piece, o: { centroidHz?: number } = {}): CraftRep
for (let i = 1; i < c.spans.length; i++) { const A = c.spans[i - 1], B = c.spans[i]; if (B.b - B.a >= 4 * bpb - E && Math.abs((A.b - A.a) - (B.b - B.a)) < E && sig(A) && sig(A) === sig(B)) repeated.push(B.id); }
if (repeated.length) add({ level: "warn", area: "rhythm", msg: `section(s) ${repeated.join(", ")} repeat the previous section note for note`, fix: "vary the repeat: the motif an octave up, a counter line, thinner or fuller layers, a new last bar" });
- // ---------------- tension curve (per bar)
- const nBars = Math.max(1, Math.ceil(c.end / bpb - E)), melRange = mel.length ? [Math.min(...mel.map((n) => n.p)), Math.max(...mel.map((n) => n.p))] : [60, 72];
- const raw = Array.from({ length: nBars }, (_, b) => { const a = b * bpb, z = a + bpb, ns = c.notes.filter((n) => n.t >= a - E && n.t < z - E);
- const h = ch.filter((x) => x.t <= a + E).pop(), k = c.keyAt(a), r = rootAt(c, h ? Math.max(h.t, a) : a), fn = r < 0 ? 0 : ROOT_TENSION[mod12(r - k.tonic)];
- const pcs = [...new Set(sounding(c, a + 0.01, ["accomp", "inner", "bass", "melody", "color"]).map((n) => mod12(n.p)))]; let ds = 0, pr = 0; for (let i = 0; i < pcs.length; i++) for (let j = i + 1; j < pcs.length; j++) { const ic = Math.min(mod12(pcs[j] - pcs[i]), 12 - mod12(pcs[j] - pcs[i])); ds += IC_DISSONANCE[ic]; pr++; }
- const mb = mel.filter((n) => n.t >= a - E && n.t < z - E), reg = mb.length ? (mean(mb.map((n) => n.p)) - melRange[0]) / Math.max(1, melRange[1] - melRange[0]) : 0;
- return { fn, diss: pr ? ds / pr : 0, dens: new Set(ns.map((n) => Math.round(n.t * 48))).size / bpb, reg, loud: ns.length ? mean(ns.map((n) => n.v)) * Math.min(1, new Set(ns.map((n) => (n as { part?: string }).part)).size / 6) : 0 }; });
- const mx = (f: (x: (typeof raw)[number]) => number) => Math.max(E, ...raw.map(f));
- const md = mx((x) => x.dens), ml = mx((x) => x.loud);
- const bars = raw.map((x) => +(0.25 * x.fn + 0.2 * x.diss + 0.25 * (x.dens / md) + 0.15 * x.reg + 0.15 * (x.loud / ml)).toFixed(3));
- const tsec = c.spans.map((s) => ({ id: s.id, value: +mean(bars.slice(Math.max(0, Math.floor(s.a / bpb + E)), Math.ceil(s.b / bpb - E))).toFixed(2) }));
- const peakBar = bars.indexOf(Math.max(...bars)), peakAt = (peakBar + 0.5) / nBars;
+ // ---------------- tension curve (per bar): harmonic lean AND intensity (loudness, density, register)
+ // Felt tension follows loudness and onset density most, then pitch height, then harmony (Farbood 2012, "A
+ // parametric, temporal model of musical tension", Music Perception 29; Lerdahl & Krumhansl 2007): a home-chord
+ // tutti climax or an EDM drop is the peak even though its chord is at rest, so intensity carries most weight.
+ const tb = tensionBars(c, ch), bars = tb.bars;
+ const tsec = c.spans.map((s) => { const a = Math.max(0, Math.floor(s.a / bpb + E)), z = Math.ceil(s.b / bpb - E), avg = (f: (x: TensionBar) => number) => +mean(tb.raw.slice(a, z).map(f)).toFixed(2);
+ return { id: s.id, value: +mean(bars.slice(a, z)).toFixed(2), harmonic: avg((x) => x.harm), loudness: avg((x) => x.loud), density: avg((x) => x.dens), register: avg((x) => x.reg) }; });
+ const nBars = bars.length, peakBar = bars.indexOf(Math.max(...bars)), peakAt = (peakBar + 0.5) / nBars;
+ // loops and low-arousal pieces stay level on purpose (theory/mood.md: a site loop is low arousal, no sharp accents; ambient and calm pieces
+ // hold one state): a flat curve there is the brief, not a fault, so it is a note
+ const levelOk = loop || p.plan.style === "ambient" || ["calm"].includes(moodId);
if (tsec.length >= 3) { const vs = tsec.map((x) => x.value), rng = Math.max(...vs) - Math.min(...vs);
- if (rng < 0.1) add({ level: "warn", area: "tension", msg: `the tension curve is flat (sections span ${rng.toFixed(2)})`, fix: "plan the arc before the notes: rise (denser, higher, leaning chords), a dip before the peak, then release" });
+ if (rng < 0.1) add({ level: levelOk ? "info" : "warn", area: "tension", msg: `the tension curve is flat (sections span ${rng.toFixed(2)})`, fix: levelOk ? `${loop ? "a loop" : "a calm or ambient piece"} stays level on purpose; keep it if that is the brief (a slow change of colour or register still helps it breathe)` : "plan the arc before the notes: rise (louder, denser, higher, leaning chords), a dip before the peak, then release" });
const peakS = vs.indexOf(Math.max(...vs));
if (!loop && peakS === 0) add({ level: "warn", area: "tension", msg: `the first section (${tsec[0].id}) is the most intense`, fix: "start below the peak so the piece has somewhere to go" });
if (!loop && !openOk && vs[vs.length - 1] >= Math.max(...vs) - 1e-9) add({ level: "warn", area: "tension", msg: `the last section (${tsec[tsec.length - 1].id}) is the most intense: no release`, fix: "after the peak, release: fewer layers, home chord, the motif's last word" }); }
@@ -298,7 +329,7 @@ export const craftReport = (p: Piece, o: { centroidHz?: number } = {}): CraftRep
melody: s01([recShare, Math.min(1, stepShare / 0.6), Math.min(1, rep.index / 0.5), 1 - Math.max(0, rep.exact - 0.4), phrases.length ? stable / phrases.length : 1, sbct]),
harmony: s01([mudList.length ? Math.max(0, 1 - mudList.length / 6) : 1, profile.parallels === "forbid" ? Math.max(0, 1 - parallels / 4) : 1, 1 - leadUnder, meanMotion ? Math.min(1, 3 / meanMotion) : 1]),
rhythm: s01([cob, grooveConsistency ?? 1, repeated.length ? 0.5 : 1, profile.groove && hasDrums ? Math.min(1, (syn.bass + syn.drums + syn.melody) / 0.15) : 1]),
- tension: s01([tsec.length >= 3 ? Math.min(1, (Math.max(...tsec.map((x) => x.value)) - Math.min(...tsec.map((x) => x.value))) / 0.2) : 1, loop || peakAt >= 0.3 ? 1 : 0.5]),
+ tension: s01([tsec.length >= 3 && !levelOk ? Math.min(1, (Math.max(...tsec.map((x) => x.value)) - Math.min(...tsec.map((x) => x.value))) / 0.2) : 1, loop || peakAt >= 0.3 ? 1 : 0.5]),
mood: checks.length ? +(checks.filter((x) => x.ok).length / checks.length).toFixed(2) : 1,
};
return {
@@ -320,6 +351,7 @@ export const craftText = (r: CraftReport) => {
` rhythm syncopation melody ${f2(y.syncopation.melody)} bass ${f2(y.syncopation.bass)} kick/snare ${f2(y.syncopation.drums)} | groove consistency ${y.grooveConsistency === null ? "-" : f2(y.grooveConsistency)} | chord changes on beats ${pct(y.chordChangesOnBeats)}`,
` density (onsets/beat, layers) ${y.density.map((d) => `${d.id} ${d.perBeat.toFixed(1)}/${d.layers}`).join(" ")}`,
` tension ${r.tension.sections.map((s) => `${s.id} ${spark[Math.min(7, Math.floor(s.value * 8))]}${f2(s.value)}`).join(" ")} | bars ${r.tension.bars.map((v) => spark[Math.min(7, Math.floor(v * 8))]).join("")} | peak at ${pct(r.tension.peakAt)}`,
+ ` what drives it (loudness/density/register/harmony, 0..1) ${r.tension.sections.map((s) => `${s.id} ${f2(s.loudness)}/${f2(s.density)}/${f2(s.register)}/${f2(s.harmonic)}`).join(" ")}`,
` mood ${r.mood.mood}: ${r.mood.checks.map((c) => `${c.what} ${c.value} ${c.ok ? "ok" : `(typical ${c.want})`}`).join(" | ")}`];
for (const f of r.findings) o.push(`${f.level === "error" ? "ERROR " : f.level === "warn" ? "CRAFT " : "note "} ${f.area}: ${f.msg}${f.fix ? `\n fix: ${f.fix}` : ""}`);
return o.join("\n");
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 a482c26..93192b0 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
@@ -34,7 +34,12 @@ export class Biquad {
bq.b0 = b0 / a0; bq.b1 = b1 / a0; bq.b2 = b2 / a0; bq.a1 = a1 / a0; bq.a2 = a2 / a0; return bq;
}
tick(x: number) { const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2; this.x2 = this.x1; this.x1 = x; this.y2 = this.y1; this.y1 = y; return y; }
- run(buf: Float32Array) { for (let i = 0; i < buf.length; i++) buf[i] = this.tick(buf[i]); return buf; }
+ /** tick() over a buffer, with the state in locals: the same operations in the same order, so bit-identical, several times faster */
+ run(buf: Float32Array) {
+ const { b0, b1, b2, a1, a2 } = this; let { x1, x2, y1, y2 } = this;
+ for (let i = 0; i < buf.length; i++) { const x = buf[i], y = b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x; y2 = y1; y1 = y; buf[i] = y; }
+ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; return buf;
+ }
}
export const onePoleCoef = (sr: number, f: number) => 1 - Math.exp((-TAU * f) / sr);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts
index be75780..667a2eb 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts
@@ -11,8 +11,9 @@
// Thresholds are calibrated so the loved reference (Kevin Ngo piano) PASSES and the ghost fixture
// (slow pad, long tail, no rhythm, no cadence) FAILS; see tools/music.mjs `guards`.
import { onsets, mono, loudness } from "./meter";
-import { renderPiece, type Rendered } from "./render";
-import { pcOf } from "./theory";
+import { renderPiece, type Rendered, type RenderOpts, type VoiceCache } from "./render";
+import { perform, type Performance } from "./perform";
+import { pcOf, nameOf } from "./theory";
import { beatsPerBar, type Piece, type Role } from "./plan";
export const GHOST = { maxOnsetsPerBeat: 1.0, minSustainedShare: 0.6, reverbWithinDb: -12, windowBars: 4, fallbackWindowS: 8 };
@@ -80,27 +81,57 @@ const bandDb = (L: Float32Array, R: Float32Array, sr: number, spans: [number, nu
return spans.map(([a, b]) => { let e = 0; for (let i = Math.round(a * sr); i < Math.min(z.length, Math.round(b * sr)); i++) e += z[i] * z[i]; return 10 * Math.log10(e / Math.max(1, (b - a) * sr) + 1e-15); });
};
-/** Masking: per bar where the melody sounds, melody band energy minus the loudest other role's (dB). Pass: >= 3 dB in >= 80 % of those bars. */
-export const maskingCheck = (piece: Piece, sr: number, o: { seconds?: number; tempo?: number } = {}) => {
+/**
+ * Masking, in three steps so a pool can render the roles in parallel (tools/music.mjs check):
+ * `maskingPlan` (which roles, which bars; each role plays exactly as it does in the mix: the same key
+ * presses, the same final ritard), `roleBandDb` (one role rendered alone, its 500 Hz-4 kHz energy per
+ * bar), `maskingFromBands` (the verdict). `maskingCheck` runs all three in turn.
+ */
+export const maskingPlan = (piece: Piece, o: { seconds?: number; tempo?: number; perf?: Performance; cache?: VoiceCache } = {}) => {
const roles = [...new Set(piece.parts.flatMap((p) => p.notes.map((n) => n.role)))] as Role[];
if (!roles.includes("melody")) return null;
- const only = (r: Role) => ({ ...piece, parts: piece.parts.map((p) => ({ ...p, notes: p.notes.filter((n) => n.role === r) })) });
- const base = { seconds: o.seconds, tempo: o.tempo, master: "none" as const };
- const mel = renderPiece(only("melody"), sr, base);
+ const perf = o.perf ?? perform(piece, o.tempo ?? piece.plan.tempo, { expressive: true });
+ const played = (r: Role): Performance => ({ ...perf, parts: perf.parts.map((p) => ({ ...p, keys: p.keys.filter((k) => k.role === r) })) });
const bpb = beatsPerBar(piece.plan.meter), total = piece.plan.sections.reduce((a, s) => a + s.bars * bpb, 0);
- const spans: [number, number][] = []; for (let b = 0; b < total; b += bpb) spans.push([mel.perf.sec(b), mel.perf.sec(b + bpb)]);
+ 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));
- const m = bandDb(mel.L, mel.R, sr, spans);
- const others = roles.filter((r) => r !== "melody").map((r) => { const x = renderPiece(only(r), sr, base); return { role: r, db: bandDb(x.L, x.R, sr, spans) }; });
- const margins = spans.map((_, i) => (sounding[i] ? m[i] - Math.max(...others.map((x) => x.db[i]), -300) : NaN)).filter((x) => Number.isFinite(x));
+ return { roles, spans, sounding, opts: (r: Role): RenderOpts => ({ seconds: o.seconds, tempo: o.tempo, master: "none", cache: o.cache, perf: played(r) }) };
+};
+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); };
+export const maskingFromBands = (pl: MaskingPlan, bands: Partial<Record<Role, number[]>>) => {
+ const m = bands.melody!, others = pl.roles.filter((r) => r !== "melody").map((r) => ({ role: r, db: bands[r]! }));
+ const margins = pl.spans.map((_, i) => (pl.sounding[i] ? m[i] - Math.max(...others.map((x) => x.db[i]), -300) : NaN)).filter((x) => Number.isFinite(x));
const ok = margins.filter((x) => x >= 3).length / Math.max(1, margins.length);
return { pass: ok >= 0.8, shareOfBarsClear: ok, worstMarginDb: Math.min(...margins), meanMarginDb: margins.reduce((a, b) => a + b, 0) / Math.max(1, margins.length) };
};
+/** Masking: per bar where the melody sounds, melody band energy minus the loudest other role's (dB). Pass: >= 3 dB in >= 80 % of those bars. */
+export const maskingCheck = (piece: Piece, sr: number, o: { seconds?: number; tempo?: number; perf?: Performance; cache?: VoiceCache } = {}) => {
+ const pl = maskingPlan(piece, o); if (!pl) return null;
+ return maskingFromBands(pl, Object.fromEntries(pl.roles.map((r) => [r, roleBandDb(piece, sr, pl.opts(r), pl.spans)])));
+};
/** Everything at once for a rendered piece. */
-export const guardReport = (r: Rendered, sr: number, seconds: number, o: { masking?: boolean } = {}) => {
+export const guardReport = (r: Rendered, sr: number, seconds: number, o: { masking?: boolean; cache?: VoiceCache; /** each role's band energy, rendered elsewhere (a worker pool) from maskingPlan */ bands?: Partial<Record<Role, number[]>> } = {}) => {
const bpb = beatsPerBar(r.piece.plan.meter);
const ghost = ghostCheck([r.L, r.R], sr, { bpm: r.tempo, beatsPerBar: bpb, wet: r.wet, dry: r.dry, cadences: cadenceTimes(r) });
- return { ghost: { pass: ghost.pass, failures: ghost.failures, windows: ghost.windows.length, minOnsetsPerBeat: Math.min(...ghost.windows.map((w) => w.onsetsPerBeat)), maxSustainedShare: Math.max(...ghost.windows.map((w) => w.sustainedShare)) }, reverb: reverbCheck(r, sr), masking: o.masking === false ? null : maskingCheck(r.piece, sr, { seconds, tempo: r.tempo }), lufs: loudness([r.L, r.R], sr).integrated };
+ return { ghost: { pass: ghost.pass, failures: ghost.failures, windows: ghost.windows.length, minOnsetsPerBeat: Math.min(...ghost.windows.map((w) => w.onsetsPerBeat)), maxSustainedShare: Math.max(...ghost.windows.map((w) => w.sustainedShare)) }, reverb: reverbCheck(r, sr), masking: o.masking === false ? null : o.bands ? maskingFromBands(maskingPlan(r.piece, { seconds, tempo: r.tempo, perf: r.perf })!, o.bands) : maskingCheck(r.piece, sr, { seconds, tempo: r.tempo, perf: r.perf, cache: o.cache }), lufs: loudness([r.L, r.R], sr).integrated };
+};
+
+/**
+ * Where the master's peak is, for the note that the -1 dBTP ceiling capped the gain: the sample peak
+ * of the mastered mix (the true peak sits within a sample of it), its bar and beat, and the parts
+ * piling up there: each stem's peak within 10 ms of it (needs a render with `stems: true`), loudest
+ * first, the ones within 10 dB of the loudest, with the notes they are sounding.
+ */
+export const peakReport = (r: Rendered, sr: number) => {
+ let at = 0, m = 0; for (let i = 0; i < r.L.length; i++) { const a = Math.max(Math.abs(r.L[i]), Math.abs(r.R[i])); if (a > m) { m = a; at = i; } }
+ const t = at / sr, bpb = beatsPerBar(r.piece.plan.meter), total = r.piece.plan.sections.reduce((a, s) => a + s.bars * bpb, 0);
+ let lo = -(r.piece.plan.pickupBeats ?? 0), hi = total + 16; for (let k = 0; k < 40; k++) { const mid = (lo + hi) / 2; if (r.perf.sec(mid) <= t) lo = mid; else hi = mid; }
+ const b = Math.round(lo * 4) / 4, bar = Math.floor(b / bpb + 1e-9), beat = +(b - bar * bpb + 1).toFixed(2), w = Math.round(0.01 * sr);
+ const parts = Object.entries(r.stems).map(([id, [L, R]]) => { let p = 0; for (let i = Math.max(0, at - w); i < Math.min(L.length, at + w); i++) p = Math.max(p, Math.abs(L[i]), Math.abs(R[i]));
+ const pi = r.piece.parts.findIndex((x) => x.id === id), notes = pi < 0 ? [] : [...new Set(r.perf.parts[pi].keys.filter((k) => k.t <= t + 0.01 && k.off + 0.05 >= t).map((k) => nameOf(k.p)))];
+ return { id, db: 20 * Math.log10(p + 1e-12), notes: r.piece.parts[pi]?.role === "drum" ? [] : notes }; }).filter((x) => x.db > -120).sort((a, b) => b.db - a.db);
+ return { sec: t, bar: bar + 1, beat, dbfs: 20 * Math.log10(m + 1e-12), parts: parts.filter((x) => x.db >= (parts[0]?.db ?? 0) - 10).slice(0, 6) };
};
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 fe96de7..9e58b37 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
@@ -5,12 +5,14 @@ export * from "./plan";
export * from "./perform";
export * from "./piano";
export * from "./render";
+export { kth } from "./mixDsp";
export * from "./meter";
export * from "./guards";
export * from "./score-text";
export * from "./grooves";
export * from "./vocab";
export * from "./vocabTrim";
+export * from "./vocabVoices";
export * from "./compose";
export * from "./novelty";
export * from "./craft";
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 5dfed0a..a411eae 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
@@ -4,12 +4,26 @@
// truePeak 4x oversampled (windowed-sinc polyphase), dBTP
// onsets spectral flux with a max-filtered previous frame (SuperFlux-style), adaptive threshold
// centroid magnitude-weighted spectral centroid, averaged over non-silent frames
-export const fft = (re: Float64Array, im: Float64Array) => {
- const n = re.length;
- for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; } }
+/** Per size: the bit-reversal swaps and, per stage, the twiddles exactly as the butterfly loop's recurrence makes them (so the tables change speed, not a single bit). */
+const FFT_PLAN = new Map<number, { swaps: Int32Array; tw: { r: Float64Array; i: Float64Array }[] }>();
+const fftPlan = (n: number) => {
+ let p = FFT_PLAN.get(n); if (p) return p;
+ const sw: number[] = [];
+ for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) sw.push(i, j); }
+ const tw: { r: Float64Array; i: Float64Array }[] = [];
for (let len = 2; len <= n; len <<= 1) {
- const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang);
- for (let i = 0; i < n; i += len) { let cr = 1, ci = 0; for (let j = 0; j < len / 2; j++) { const a = i + j, b = a + len / 2, xr = re[b] * cr - im[b] * ci, xi = re[b] * ci + im[b] * cr; re[b] = re[a] - xr; im[b] = im[a] - xi; re[a] += xr; im[a] += xi; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; } }
+ const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang), h = len / 2, r = new Float64Array(h), im = new Float64Array(h); let cr = 1, ci = 0;
+ for (let j = 0; j < h; j++) { r[j] = cr; im[j] = ci; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; }
+ tw.push({ r, i: im });
+ }
+ p = { swaps: Int32Array.from(sw), tw }; FFT_PLAN.set(n, p); return p;
+};
+export const fft = (re: Float64Array, im: Float64Array) => {
+ const n = re.length, { swaps, tw } = fftPlan(n);
+ for (let s = 0; s < swaps.length; s += 2) { const i = swaps[s], j = swaps[s + 1]; let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
+ for (let len = 2, st = 0; len <= n; len <<= 1, st++) {
+ const h = len / 2, twr = tw[st].r, twi = tw[st].i;
+ for (let i = 0; i < n; i += len) for (let j = 0; j < h; j++) { const cr = twr[j], ci = twi[j], a = i + j, b = a + h, xr = re[b] * cr - im[b] * ci, xi = re[b] * ci + im[b] * cr; re[b] = re[a] - xr; im[b] = im[a] - xi; re[a] += xr; im[a] += xi; }
}
};
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
index 9f051ac..9cde7a6 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixDsp.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixDsp.ts
@@ -115,6 +115,16 @@ export const transientGain = (L: Float32Array, R: Float32Array, sr: number, o: {
// ---------------------------------------------------------------- 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. */
+/** The k-th smallest of a[0..m) (Hoare quickselect, reorders a in place): the value a sort would put at index k. */
+export const kth = (a: Float64Array, m: number, k: number) => {
+ let lo = 0, hi = m - 1;
+ while (lo < hi) {
+ const x = a[(lo + hi) >> 1]; let i = lo, j = hi;
+ while (i <= j) { while (a[i] < x) i++; while (a[j] > x) j--; if (i <= j) { const t = a[i]; a[i] = a[j]; a[j] = t; i++; j--; } }
+ if (k <= j) hi = j; else if (k >= i) lo = i; else return a[k];
+ }
+ return a[k];
+};
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)
@@ -123,10 +133,11 @@ export const compress = (L: Float32Array, R: Float32Array, sr: number, o: CompOp
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 act = new Float64Array(n + 1);
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;
+ let g = 0, m = 0; const 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[m++] = -g; }
+ return m ? kth(act, m, Math.floor(m * 0.9)) : 0; // the 90th percentile: the same value a full sort puts there, in linear time
};
// 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));
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
index 64e6d12..7ec8375 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/mixReverb.ts
@@ -29,7 +29,8 @@ class Line {
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; };
+const HAD_K = new Map<number, number>(); // 1 / sqrt(N), computed once per size (the same double every call)
+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; } let k = HAD_K.get(N); if (k === undefined) { k = 1 / Math.sqrt(N); HAD_K.set(N, k); } 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 => {
@@ -48,13 +49,14 @@ export const fdnReverb = (L: Float32Array, R: Float32Array, sr: number, s: Space
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)
+ const w = rate.map((r) => twoPi * r); // twoPi * rate[j], the same product the per-sample expression starts with
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); }
+ for (let k = 0; k < steps; k++) { const st = dif[k], ln = st.lines, d = st.d, fl = st.flip; for (let c = 0; c < DC; c++) { ln[c].push(x8[c]); x8[c] = ln[c].at(d[c]) * fl[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); }
+ const el = x8[0] - x8[2] + x8[4] - x8[6], er = x8[1] - x8[3] + x8[5] - x8[7], t = i / sr;
+ for (let j = 0; j < N; j++) { const md = depth * Math.sin(w[j] * t + 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++) {
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/novelty.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/novelty.ts
index 611d8b9..9861a5e 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/novelty.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/novelty.ts
@@ -6,8 +6,9 @@
// melody intervals (transposition-free n-grams), other lines' rhythm (counter, bass), drum bars,
// chord function (root vs key + quality) n-grams, chord-quality n-grams, section-kind sequence.
// Each feature is a bag of n-grams; similarity is the cosine of the bags; the score is a weighted
-// mean. `demoReuse` is the stricter gate: any 6-note melody fragment (intervals + durations) taken
-// from a demo fails outright, transposed or not.
+// mean. Two stricter gates fail outright: any 6-note melody fragment (intervals + durations) taken
+// from a shipped piece, transposed or not; and any distinctive 8-note melody shape (intervals only),
+// so a quote re-barred into another meter, stretched or re-rhythmed is caught too.
import type { Piece, Note } from "./plan";
import { beatsPerBar } from "./plan";
import { pcOf } from "./theory";
@@ -56,17 +57,30 @@ export const similarity = (a: Fingerprint, b: Fingerprint) => {
return { score: w ? s / w : 0, by };
};
+const tune = (p: Piece) => voice(p.parts.flatMap((pt) => pt.notes.filter((n) => n.role === "melody" || n.role === "color")));
/** Every melody 6-note fragment as (interval, duration) pairs: transposition-free. */
-const fragments = (p: Piece) => { const mel = voice(p.parts.flatMap((pt) => pt.notes.filter((n) => n.role === "melody" || n.role === "color"))); const out = new Set<string>(); for (let i = 0; i + 6 <= mel.length; i++) { const g = mel.slice(i, i + 6); out.add(g.slice(1).map((n, j) => `${n.p - g[j].p}/${q(n.t - g[j].t)}`).join(" ")); } return out; };
+const fragments = (p: Piece) => { const mel = tune(p), out = new Set<string>(); for (let i = 0; i + 6 <= mel.length; i++) { const g = mel.slice(i, i + 6); out.add(g.slice(1).map((n, j) => `${n.p - g[j].p}/${q(n.t - g[j].t)}`).join(" ")); } return out; };
+/** A quoted tune survives a new key, a new meter and a new rhythm: its intervals do not. The pitch-only fragment gate compares this many notes. */
+export const QUOTE_NOTES = 8;
+/**
+ * Every QUOTE_NOTES-note melody fragment as its interval sequence alone (no rhythm, no key, no meter):
+ * the same tune re-barred into 5/4, stretched or transposed has the same intervals. Only distinctive
+ * shapes count (3+ different intervals, a leap of 3+ semitones, at most 3 repeated notes), so a scale
+ * run or a repeated-note figure, which every tune shares, never fails a piece.
+ */
+export const melodyShapes = (p: Piece) => { const mel = tune(p), out = new Set<string>();
+ for (let i = 0; i + QUOTE_NOTES <= mel.length; i++) { const iv = mel.slice(i + 1, i + QUOTE_NOTES).map((n, j) => n.p - mel[i + j].p);
+ if (new Set(iv).size >= 3 && iv.some((x) => Math.abs(x) >= 3) && iv.filter((x) => x === 0).length <= 3) out.add(iv.join(",")); }
+ return out; };
/** Score a piece against a corpus. `family` names the pieces that ARE this piece (its own cuts) and are skipped. */
export const novelty = (p: Piece, corpus: Record<string, () => Piece>, skip: string[] = [], threshold = NOVELTY_THRESHOLD) => {
- const fp = fingerprint(p), mine = fragments(p);
+ const fp = fingerprint(p), mine = fragments(p), shapes = melodyShapes(p);
const rows = Object.entries(corpus).filter(([name]) => !skip.includes(name)).map(([name, mk]) => {
- const other = mk(), sim = similarity(fp, fingerprint(other)), theirs = fragments(other);
- let reused = 0; for (const f of mine) if (theirs.has(f)) reused++;
- return { name, score: +sim.score.toFixed(3), by: sim.by, reusedFragments: reused };
+ const other = mk(), sim = similarity(fp, fingerprint(other)), theirs = fragments(other), theirShapes = melodyShapes(other);
+ let reused = 0, quoted = 0; for (const f of mine) if (theirs.has(f)) reused++; for (const f of shapes) if (theirShapes.has(f)) quoted++;
+ return { name, score: +sim.score.toFixed(3), by: sim.by, reusedFragments: reused, quotedShapes: quoted };
}).sort((a, b) => b.score - a.score);
const worst = rows[0];
- return { rows, threshold, pass: rows.every((r) => r.score <= threshold && r.reusedFragments === 0), worst };
+ return { rows, threshold, pass: rows.every((r) => r.score <= threshold && r.reusedFragments === 0 && r.quotedShapes === 0), worst };
};
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 df06efb..7b3d021 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
@@ -11,7 +11,7 @@ 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 { pumpCurve, lofiStem, lofiMaster, LOFI_DUSTY, type LofiFx } from "./lofiFx";
import { loudness, truePeak, stemBalance } from "./meter";
import { STYLES } from "./tables";
import { rng as mkRng } from "../core";
@@ -19,7 +19,67 @@ import { eqChain, runEq, stereoPan, compress, saturate, bandWidth, smoothLimiter
import { reverb, 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 };
+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;
+ /** 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 };
+
+/**
+ * Voice synthesis as data: one part's voice, its exact inputs. `runVoiceJob` is the only place a
+ * voice is synthesized, so a cache hit (or a worker that ran the same job) is bit-identical to a
+ * fresh synthesis. Keyed by the whole job, so a different key, option, length or seed never hits.
+ */
+export type VoiceOut = { L: Float32Array; R: Float32Array; halo?: Float32Array; /** the transient gain's reduction (dB), when the job ran it */ transientGr?: number };
+/** Per-stem processing that depends on nothing but the stem (sound v2): the lo-fi stem colour, the amp, the gentle master's transient gain. */
+type StemPost = { lofi?: LofiFx; id: string; seed: number; period?: number; amp?: number; transient?: { maxDb: number; thrDb: number; ratio: number } };
+export type VoiceJob =
+ | { 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 };
+export type VoiceCache = Map<string, VoiceOut>;
+export const runVoiceJob = (j: VoiceJob): VoiceOut => {
+ let out: VoiceOut;
+ if (j.kind === "piano") { const r = j.v1 ? renderPiano(j.keys, j.pedal, j.sr, j.n, j.v1, j.seed) : renderPianoV2(j.keys, j.pedal, j.sr, j.n, j.opts ?? {}, j.seed); out = { L: r.L, R: r.R, halo: r.halo }; }
+ else out = voice({ id: "", role: "accomp", notes: [], inst: j.inst, ...(j.opts ? { opts: j.opts } : {}) }, j.keys, j.sr, j.n, j.seed, j.ctx);
+ const q = j.post; if (!q) return out;
+ if (q.lofi) lofiStem(q.lofi, q.id, out.L, out.R, j.sr, j.keys.map((k) => k.t), q.seed, q.period);
+ if (q.amp !== undefined) ampSim(out.L, out.R, j.sr, q.amp); // a guitar (or any DI) through the amp + cab
+ if (q.transient) out.transientGr = transientGain(out.L, out.R, j.sr, q.transient);
+ return out;
+};
+export const voiceJobKey = (j: VoiceJob) => JSON.stringify(j);
+const copyOut = (v: VoiceOut): VoiceOut => ({ ...v, L: Float32Array.from(v.L), R: Float32Array.from(v.R), ...(v.halo ? { halo: Float32Array.from(v.halo) } : {}) });
+/** A sound-v2 part's job: its voice, then the stem processing (renderV2 and voiceJobs both build jobs here, so their keys agree). */
+const v2Job = (piece: Piece, pt: Part, pi: number, keys: Played[], perf: Performance, sr: number, n: number, o: RenderOpts, ctx: KitCtx): VoiceJob => {
+ const style = STYLES[piece.plan.style], prof = mixProfile(style.id, piece.mix), tempo = o.tempo ?? piece.plan.tempo;
+ 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;
+ // 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, amp = typeof pt.opts?.amp === "number" ? (pt.opts.amp as number) : undefined;
+ const transient = style.master === "gentle" && tg && isStruck(pt.inst, pt.opts) ? tg : undefined;
+ const post: StemPost | undefined = lofi || amp !== undefined || transient ? { id: pt.id, seed: piece.seed, ...(lofi ? { lofi, period } : {}), ...(amp !== undefined ? { amp } : {}), ...(transient ? { transient } : {}) } : undefined;
+ const base = 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 };
+ return post ? { ...base, post } : base;
+};
+/** Synthesize (or reuse) one voice. The caller owns the returned arrays (it mutates them in place). */
+const synth = (j: VoiceJob, cache?: VoiceCache): VoiceOut => {
+ if (!cache) return runVoiceJob(j);
+ const k = voiceJobKey(j); let v = cache.get(k); if (!v) { v = runVoiceJob(j); cache.set(k, v); }
+ return copyOut(v);
+};
+/** The voice jobs a render will run (for a pool that synthesizes them in parallel into a cache first). Mirrors renderLegacy / renderV2 exactly. */
+export const voiceJobs = (piece: Piece, sr: number, o: RenderOpts = {}): VoiceJob[] => {
+ const expressive = o.expressive ?? true, tempo = o.tempo ?? piece.plan.tempo;
+ const perf = o.perf ?? perform(piece, tempo, { expressive, flatVelocity: o.flatVelocity });
+ const n = o.seconds ? Math.round(o.seconds * sr) : Math.ceil((perf.lastOnset + piece.tail) * sr), jobs: VoiceJob[] = [];
+ const kitCtx: KitCtx = piece.legacy ? { legacy: true } : { 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;
+ if (!piece.legacy) jobs.push(v2Job(piece, pt, pi, keys, perf, sr, n, o, kitCtx));
+ else if (pt.inst === "piano") jobs.push({ kind: "piano", keys, pedal: perf.pedal, sr, n, seed: piece.seed + pi, v1: o.piano ?? PIANO_REAL });
+ else jobs.push({ kind: "voice", inst: pt.inst, opts: pt.opts, keys, sr, n, seed: piece.seed * 101 + pi, ctx: kitCtx });
+ });
+ return jobs;
+};
/** 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];
/** sound v2: what the chain did (gain reduction in dB) */ mixReport?: { drumBusGr?: number; glueGr?: number; limiterGr?: number; transientGr?: number; space?: string } };
@@ -67,7 +127,7 @@ export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rende
/** 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 perf = o.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 sends: [Float32Array, Float32Array, number][] = [];
@@ -78,8 +138,8 @@ const renderLegacy = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered =>
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, { legacy: true }); sL = r.L; sR = r.R; }
+ if (pt.inst === "piano") { const r = synth({ kind: "piano", keys, pedal: perf.pedal, sr, n, seed: piece.seed + pi, v1: o.piano ?? PIANO_REAL }, o.cache); 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 = synth({ kind: "voice", inst: pt.inst, opts: pt.opts, keys, sr, n, seed: piece.seed * 101 + pi, ctx: { legacy: true } }, o.cache); 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; } }
@@ -125,7 +185,7 @@ const energy = (L: Float32Array, R: Float32Array) => { let e = 0; for (let i = 0
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 perf = o.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
@@ -142,13 +202,10 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
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));
+ // the voice, then its stem processing (lo-fi colour, amp, transient gain): one job (v2Job), cached as a whole
+ const r = synth(v2Job(piece, pt, pi, keys, perf, sr, n, o, kitCtx), o.cache); sL = r.L; sR = r.R;
+ if (pt.inst === "piano" && (o.piano ? o.piano.pedal : pt.opts?.pedal !== false)) for (let i = 0; i < n; i++) haloL[i] += r.halo![i] * db(pt.gainDb ?? 0);
+ if (r.transientGr !== undefined) report.transientGr = Math.max(report.transientGr ?? 0, r.transientGr);
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
@@ -232,18 +289,33 @@ export const master = (L: Float32Array, R: Float32Array, sr: number, masterMode:
* repeats, pad release) folded back onto the start, then mastered once. Tape wow and flutter are
* snapped to a whole number of cycles per loop so the pitch drift meets itself at the seam.
*/
-export const renderLoop = (piece: Piece, sr: number): Rendered & { loopS: number } => {
+/** What renderLoop renders before it folds the tail: the loop's piece (no ritard, tape cycles snapped) and its length. */
+export const loopSource = (piece: Piece) => {
const beats = piece.plan.sections.reduce((a, s) => a + s.bars * beatsPerBar(piece.plan.meter), 0), loopS = (beats * 60) / piece.plan.tempo;
const snap = (hz: number) => Math.max(1, Math.round(hz * loopS)) / loopS, tp = piece.fx?.tape;
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);
+ return { p, loopS, opts: { seconds: loopS + piece.tail, master: "none" as const } };
+};
+export const renderLoop = (piece: Piece, sr: number, o: { cache?: VoiceCache; stems?: boolean } = {}): Rendered & { loopS: number } => {
+ const { p, loopS, opts } = loopSource(piece);
+ const r = renderPiece(p, sr, { ...opts, cache: o.cache, stems: o.stems }), 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, !piece.legacy);
return { ...r, L, R, gainDb, masterMode: mode, loopS };
};
-/** The score for a film `seconds` long: the piece's own `refit` first (so it still ends on a phrase), then fitToDuration for the tempo. */
-export const fitScore = (piece: Piece, seconds: number) => fitToDuration(piece.refit ? piece.refit(seconds) : piece, seconds);
+/**
+ * Does the piece as written already fit `seconds`? Its last onset plus its tail lands within
+ * max(0.5 s, one beat) of the length, and the tail keeps at least half its ring. Then a fit keeps
+ * the written tempo and form, and the tail takes up the difference: music composed to picture must
+ * not drift off its hits because the final ritard made the last bar a little longer.
+ */
+export const fitsAsWritten = (piece: Piece, seconds: number) => {
+ const slack = seconds - (perform(piece, piece.plan.tempo, { expressive: true }).lastOnset + piece.tail);
+ return Math.abs(slack) <= Math.max(0.5, 60 / piece.plan.tempo) && piece.tail + slack >= 0.5 * piece.tail;
+};
+/** The score for a film `seconds` long: as written when it already fits (fitsAsWritten), else the piece's own `refit` first (so it still ends on a phrase), then fitToDuration for the tempo. */
+export const fitScore = (piece: Piece, seconds: number) => fitToDuration(!fitsAsWritten(piece, seconds) && piece.refit ? piece.refit(seconds) : piece, seconds);
/** 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) => {
@@ -271,6 +343,7 @@ export const limiter = (L: Float32Array, R: Float32Array, sr: number, ceil: numb
export const fitToDuration = (piece: Piece, seconds: number): { piece: Piece; tempo: number; order: number[]; form: string } => {
const st = STYLES[piece.plan.style], T0 = piece.plan.tempo, lo = Math.max(st.tempo[0] * 0.9, T0 * 0.82), hi = Math.min(st.tempo[1] * 1.1, T0 * 1.18);
const secs = piece.plan.sections, want = seconds - piece.tail;
+ if (fitsAsWritten(piece, seconds)) return { piece, tempo: T0, order: secs.map((_, i) => i), form: "full" };
const solve = (p: Piece) => { let tempo = T0; for (let k = 0; k < 5; k++) tempo *= perform(p, tempo, { expressive: true }).lastOnset / want; return tempo; };
const opt = secs.map((s, i) => (s.optional ? i : -1)).filter((i) => i >= 0);
const grp = secs.map((s, i) => (s.repeatable ? i : -1)).filter((i) => i >= 0);
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
index d5e9878..81bf284 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/roomSmall.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/roomSmall.ts
@@ -45,9 +45,10 @@ export const smallRoom = (L: ArrayLike<number>, R: ArrayLike<number>, sr: number
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]];
+ for (let k = 0; k < 4; k++) {
+ const st = steps[k], bufs = st.bufs, idx = st.idx, flip = st.flip, perm = st.perm;
+ for (let c = 0; c < N; c++) { const buf = bufs[c], L0 = buf.length, wi = idx[c], nx = wi + 1 === L0 ? 0 : wi + 1; buf[wi] = x[c]; y[c] = buf[nx] * flip[c]; idx[c] = nx; }
+ for (let c = 0; c < N; c++) x[c] = y[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); }
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabVoices.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabVoices.ts
new file mode 100644
index 0000000..29d41c3
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabVoices.ts
@@ -0,0 +1,410 @@
+// GENERATED by `node tools/music.mjs calibrate --voices`. Do not edit by hand.
+// VOCAB_ALT_TRIM: per style, slot and alternate, the gain trim (dB) that brings the alternate to the
+// slot's stem target (the style's number plus its VOCAB_TARGET_FIX) on the neutral test phrase.
+// INST_LEVEL: each instrument's stem level (dB, the stem meter) at gainDb 0 playing a slot's test line
+// (cinematic test signal, counter line an octave down; drums on the lo-fi electronic kit; default options):
+// a composer's own voice is placed at the slot's target from it, so its gainDb is an offset from
+// calibrated, like `levels`. VOCAB_ALT_TARGET_FIX: where a 30 dB trim cannot reach the target, the
+// target moves to where the alternate sits. INST_REGISTER: each instrument's level against the lead
+// line moved by octaves ([median MIDI pitch, dB vs its lead level]); SLOT_REF_PITCH: the median pitch
+// of each slot's test line. Your own voice is placed for the register it actually plays in.
+import type { Slot } from "./vocab";
+export const VOCAB_ALT_TRIM: Record<string, Partial<Record<Slot, Record<string, number>>>> = {
+ lofiElectronic: {
+ lead: {
+ bell: 2.6,
+ mallet: 2.6,
+ guitar: 16.3
+ },
+ chords: {
+ strings: 4.6,
+ piano: 24.7
+ },
+ bass: {
+ warm: -1.5
+ }
+ },
+ drive: {
+ lead: {
+ pluck: -0.9
+ },
+ bass: {
+ sub: 1.7
+ }
+ },
+ cinematic: {
+ lead: {
+ piano: 10.4,
+ bell: 5.3,
+ celesta: 1.9
+ },
+ counter: {
+ piano: 30
+ }
+ },
+ ambient: {
+ lead: {
+ pluck: -1.8,
+ vibes: 2
+ }
+ },
+ folk: {
+ lead: {
+ piano: 13.1,
+ guitar: 18.1,
+ strings: 13.5
+ },
+ chords: {
+ strings: 2.7
+ }
+ },
+ playful: {
+ lead: {
+ chip: 14.5,
+ pluck: 3.6,
+ bell: 6.3
+ },
+ bass: {
+ tuba: -1.7
+ }
+ },
+ musicBox: {
+ lead: {
+ celesta: 2.9,
+ bell: 6.2
+ }
+ },
+ nocturne: {},
+ minimalist: {
+ arp: {
+ piano: 22.5,
+ pluck: 2.2
+ }
+ },
+ jazz: {
+ lead: {
+ piano: 12.7,
+ clarinet: 11.5,
+ flute: 11.2,
+ brass: 17.8
+ }
+ },
+ lullaby: {
+ lead: {
+ musicBox: 5.2,
+ piano: 14.2,
+ flute: 11.1
+ }
+ },
+ chiptune: {
+ lead: {
+ square: 8.1
+ }
+ },
+ lofi: {
+ lead: {
+ guitar: 17.1,
+ flute: 11.3
+ }
+ },
+ orchestral: {
+ lead: {
+ strings: 10.8,
+ horn: 17.1,
+ flute: 13.1
+ },
+ counter: {
+ flute: 6.7,
+ harp: 11.2
+ }
+ },
+ suspense: {
+ counter: {
+ choir: 8.8,
+ bell: 19
+ },
+ lead: {
+ choir: -2.2,
+ cello: 8.2
+ }
+ },
+ rock: {
+ chords: {
+ strings: 10.8,
+ organ: 19.2,
+ piano: 27
+ },
+ lead: {
+ guitar: -2
+ }
+ },
+ hipHop: {
+ lead: {
+ bell: 2.9,
+ flute: 8.7,
+ choir: 3.6
+ },
+ chords: {
+ pad: -6.3
+ }
+ },
+ house: {
+ chords: {
+ pad: 4.8,
+ piano: 25.6
+ },
+ lead: {
+ synth: 14.6
+ }
+ },
+ synthwave: {
+ chords: {
+ pad: 1.7
+ },
+ lead: {
+ brass: 13.4
+ }
+ },
+ world: {
+ lead: {
+ pluck: 17,
+ marimba: 4.1,
+ reed: 9.8,
+ bowed: 12.7
+ }
+ },
+ choral: {
+ chords: {
+ organ: 4,
+ strings: 4.1
+ },
+ lead: {
+ bowed: 10.3,
+ flute: 9.1
+ }
+ }
+};
+export const VOCAB_ALT_TARGET_FIX: Record<string, Partial<Record<Slot, Record<string, number>>>> = {
+ cinematic: {
+ counter: {
+ piano: -9.1
+ }
+ }
+};
+export const INST_LEVEL: Record<string, Partial<Record<Slot, number>>> = {
+ piano: {
+ chords: -41,
+ lead: -27.4,
+ counter: -45.4,
+ bass: -31.1,
+ arp: -39.8
+ },
+ musicBox: {
+ chords: -22.9,
+ lead: -19.8,
+ counter: -28.8,
+ bass: -25.1,
+ arp: -23.8
+ },
+ bell: {
+ chords: -12.6,
+ lead: -9.6,
+ counter: -18.6,
+ bass: -12.2,
+ arp: -12
+ },
+ celesta: {
+ chords: -20.1,
+ lead: -18.9,
+ counter: -27,
+ bass: -20,
+ arp: -20.2
+ },
+ marimba: {
+ chords: -20.8,
+ lead: -20.3,
+ counter: -32.5,
+ bass: -19.3,
+ arp: -20.5
+ },
+ vibes: {
+ chords: -20.4,
+ lead: -18.3,
+ counter: -26.3,
+ bass: -18.6,
+ arp: -19.4
+ },
+ harp: {
+ chords: -32.5,
+ lead: -30.9,
+ counter: -39.1,
+ bass: -33.8,
+ arp: -30.9
+ },
+ guitar: {
+ chords: -32.1,
+ lead: -34,
+ counter: -38.9,
+ bass: -33.4,
+ arp: -34.7
+ },
+ strings: {
+ chords: -20.5,
+ lead: -26.4,
+ counter: -30.3,
+ bass: -25.7,
+ arp: -28.3
+ },
+ fmBell: {
+ chords: -22.3,
+ lead: -18.3,
+ counter: -27.7,
+ bass: -21.3,
+ arp: -20.1
+ },
+ ePiano: {
+ chords: -22.1,
+ lead: -23.3,
+ counter: -32.7,
+ bass: -21.2,
+ arp: -24.3
+ },
+ pulse: {
+ chords: -21.5,
+ lead: -23.9,
+ counter: -28.4,
+ bass: -24.4,
+ arp: -26.4
+ },
+ triangle: {
+ chords: -13.5,
+ lead: -18.2,
+ counter: -18.3,
+ bass: -18.3,
+ arp: -18.3
+ },
+ noiseDrum: {
+ kick: -25.5,
+ snare: -27.1,
+ hat: -41.6
+ },
+ kick: {
+ kick: -12.1,
+ snare: -25.6,
+ hat: -44.1
+ },
+ snare: {
+ kick: -12.1,
+ snare: -25.6,
+ hat: -44.1
+ },
+ hat: {
+ kick: -12.1,
+ snare: -25.6,
+ hat: -44.1
+ },
+ bass: {
+ chords: -12.6,
+ lead: -13.9,
+ counter: -17.8,
+ bass: -15.2,
+ arp: -14.6
+ },
+ warmPad: {
+ chords: -21.8,
+ lead: -29,
+ counter: -30.9,
+ bass: -23.8,
+ arp: -30.8
+ },
+ softPluck: {
+ chords: -22.2,
+ lead: -20.1,
+ counter: -29.7,
+ bass: -25.6,
+ arp: -21.6
+ },
+ sub: {
+ chords: -25.5,
+ lead: -39.8,
+ counter: -46.5,
+ bass: -12.9,
+ arp: -30.9
+ },
+ organ: {
+ chords: -30.8,
+ lead: -35.3,
+ counter: -38.3,
+ bass: -35.1,
+ arp: -37.7
+ },
+ brass: {
+ chords: -22.7,
+ lead: -27.2,
+ counter: -32.2,
+ bass: -22.1,
+ arp: -30.2
+ },
+ woodwind: {
+ chords: -20,
+ lead: -24.1,
+ counter: -26.6,
+ bass: -23,
+ arp: -25.9
+ },
+ choir: {
+ chords: -10.8,
+ lead: -19.7,
+ counter: -18.1,
+ bass: -21.8,
+ arp: -17.2
+ },
+ timpani: {
+ kick: -13.4,
+ snare: -15,
+ hat: -16.5
+ },
+ leadSynth: {
+ chords: -29.6,
+ lead: -29,
+ counter: -33.2,
+ bass: -28.1,
+ arp: -31.5
+ },
+ bowedSolo: {
+ chords: -20.2,
+ lead: -27.2,
+ counter: -31.3,
+ bass: -27.3,
+ arp: -25.7
+ },
+ glockenspiel: {
+ chords: -22.4,
+ lead: -19.1,
+ counter: -27.8,
+ bass: -21.4,
+ arp: -21.4
+ },
+ wurlitzer: {
+ chords: -25.5,
+ lead: -28.6,
+ counter: -35.9,
+ bass: -22.9,
+ arp: -31.3
+ },
+ pipeOrgan: {
+ chords: -20,
+ lead: -25,
+ counter: -25.6,
+ bass: -24.4,
+ arp: -26
+ }
+};
+export const INST_REGISTER: Record<string, [number, number][]> = {"piano":[[44,5.5],[56,5.3],[68,3.9],[80,0],[92,-5.6],[104,-12.3]],"musicBox":[[44,0.4],[56,0.2],[68,0.2],[80,0],[92,-2.1],[104,-4.7]],"bell":[[44,2.1],[56,1.9],[68,1.1],[80,0],[92,-1.4],[104,-3.1]],"celesta":[[44,2.7],[56,2.7],[68,1.3],[80,0],[92,-2.3],[104,-4.8]],"marimba":[[44,7],[56,5.5],[68,2.7],[80,0],[92,-3.8],[104,-7]],"vibes":[[44,2.2],[56,2.6],[68,1.5],[80,0],[92,-1.4],[104,-2.4]],"harp":[[44,3.8],[56,3.6],[68,3.6],[80,0],[92,0.1],[104,0.8]],"guitar":[[44,4.3],[56,4.7],[68,3],[80,0],[92,-0.4],[104,-3.3]],"strings":[[44,-2.4],[56,1],[68,0.8],[80,0],[92,-4.2],[104,-8.3]],"fmBell":[[44,3],[56,2.3],[68,1],[80,0],[92,-1.3],[104,-2.1]],"ePiano":[[44,3.9],[56,4.8],[68,2.9],[80,0],[92,-3.3],[104,-6]],"pulse":[[44,-0.9],[56,-0.4],[68,-0.1],[80,0],[92,-0.2],[104,-1.1]],"triangle":[[44,0],[56,0],[68,0],[80,0],[92,0],[104,-0.2]],"bass":[[44,2.3],[56,2.4],[68,2.3],[80,0],[92,-0.9],[104,-8.8]],"warmPad":[[44,0.4],[56,1.4],[68,1.3],[80,0],[92,-4],[104,-12.2]],"softPluck":[[44,0.1],[56,0.7],[68,1.1],[80,0],[92,-2],[104,-6.1]],"sub":[[44,25.7],[56,21.1],[68,11.5],[80,0],[92,-11.8],[104,-23.2]],"organ":[[44,-1.6],[56,-0.7],[68,-0.1],[80,0],[92,-0.5],[104,-0.7]],"brass":[[44,-0.2],[56,1.5],[68,1.1],[80,0],[92,-0.8],[104,-3.5]],"woodwind":[[44,-0.4],[56,0.2],[68,0.2],[80,0],[92,-0.2],[104,-0.1]],"choir":[[44,-2.9],[56,0.8],[68,4.5],[80,0],[92,-0.3],[104,4]],"leadSynth":[[44,-1.3],[56,-0.7],[68,-0.2],[80,0],[92,-1.2],[104,-6.2]],"bowedSolo":[[44,0.2],[56,1.8],[68,3.6],[80,0],[92,-7.6],[104,-30.6]],"glockenspiel":[[44,1.7],[56,1.8],[68,0.8],[80,0],[92,-1.3],[104,-2.3]],"wurlitzer":[[44,7],[56,5.1],[68,2.4],[80,0],[92,-3.7],[104,-6.8]],"pipeOrgan":[[44,-1.6],[56,-0.7],[68,-0.2],[80,0],[92,-0.5],[104,-3.1]]};
+export const SLOT_REF_PITCH: Partial<Record<Slot, number>> = {
+ chords: 68,
+ lead: 80,
+ counter: 84,
+ bass: 43,
+ arp: 68
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/craft.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/craft.test.ts
index 0ef6db9..8cac9e3 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/test/craft.test.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/craft.test.ts
@@ -4,7 +4,7 @@ import { craftReport, contourClass, classifyCadence, syncopation, metricWeight,
import { line, type Piece, type Part, type Role, type InstId, type Meter, type Note } from "../src/canvas-core/music/plan";
import type { StyleId, MoodId } from "../src/canvas-core/music/tables";
import type { ModeId } from "../src/canvas-core/music/theory";
-import { DEMOS, FIXTURES, composePiece } from "../src/canvas-core/music/index";
+import { DEMOS, FIXTURES, composePiece, type Material } from "../src/canvas-core/music/index";
import { breach } from "../src/canvas-core/music/blind/breach";
import { stillwater } from "../src/canvas-core/music/blind/stillwater";
import { morningCrumb } from "../src/canvas-core/music/blind/morningCrumb";
@@ -126,6 +126,32 @@ export const run = (ok: (cond: boolean, label: string) => void) => {
{ id: "chords", inst: "piano", role: "accomp", src: [C, C, "[B2 D3 F3 G3]:4", "[B2 D3 F3 G3]:4", C, C].join(" | ") }, { id: "bass", inst: "bass", role: "bass", src: [bassC, bassC, "G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5", "G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5", bassC, bassC].join(" | ") }] }));
ok(!arc.findings.some((f) => f.area === "tension") && arc.tension.sections[1].value > arc.tension.sections[0].value && arc.tension.sections[1].value > arc.tension.sections[2].value, `rise, peak, release (${arc.tension.sections.map((s) => s.value).join(" < > ")}) passes`);
+ // intensity, not only harmony (Farbood 2012): a home-chord tutti climax and an EDM drop are the peak; the same sections thin and quiet are not
+ const mat = (style: StyleId, mood: MoodId, secs: Material["sections"], extra: Partial<Material> = {}): Material => ({ style, title: "t", seed: 2, mood, bpm: style === "house" ? 124 : 76, key: "C", mode: "major", ...extra,
+ chords: { I: { voicing: "[E3 G3 C4]", bass: "C2:4" }, vi: { voicing: "[E3 A3 C4]", bass: "A1:4" }, IV: { voicing: "[F3 A3 C4]", bass: "F1:4" }, V: { voicing: "[D3 G3 B3 F4]", bass: "G1:2 G1:2" }, Vb9: { voicing: "[D3 G3 B3 F4 Ab4]", bass: "G1:2 G1:2" }, Vsus: { voicing: "[D3 G3 C4 F4]", bass: "G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5" } },
+ grooves: { main: { family: style === "house" ? "fourFloor" : "pulse", density: 0.5, variation: 0.3 }, build: { family: "build", density: 0.8, variation: 0.2 }, drop: { family: style === "house" ? "fourFloor" : "pulse", density: 0.95, variation: 0.3, fill: true } }, sections: secs });
+ const climax = (tutti: boolean) => mat("cinematic", "hopeful", [
+ { id: "intro", kind: "intro", bars: 2, harmony: ["I", "vi"], lead: "E4:4 | C4:4", chordVel: 0.6, energy: 0.3 },
+ { id: "verse", kind: "verse", bars: 2, harmony: ["IV", "vi"], lead: "F4:2 A4:2 | G4:2 E4:2", groove: null, energy: 0.45 },
+ { id: "lean", kind: "verse", bars: 2, harmony: ["Vb9", "Vb9"], lead: "G4:.5 A4:.5 B4:.5 D5:.5 F5:.5 D5:.5 B4:.5 D5:.5 | F5:.5 Ab5:.5 F5:.5 D5:.5 B4:.5 D5:.5 F5:1", bass: "G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5", groove: null, energy: 0.6 },
+ tutti ? { id: "climax", kind: "swell", bars: 2, harmony: ["I", "I"], lead: "C6:1 B5:.5 G5:.5 E5:1 G5:1 | C6:2 G5:2", counter: "E5:2 G5:2 | E5:4", arp: "C4:.5 E4:.5 G4:.5 C5:.5 E5:.5 G5:.5 C6:.5 G5:.5 | C4:.5 E4:.5 G4:.5 C5:.5 E5:.5 G5:.5 C6:.5 G5:.5", chordVel: 1.1, energy: 0.95 }
+ : { id: "climax", kind: "breath", bars: 2, harmony: ["I", "I"], lead: "C4:4 | r:4", chordVel: 0.4, energy: 0.2 },
+ { id: "outro", kind: "outro", bars: 2, harmony: ["IV", "I"], lead: "A4:2 G4:2 | E4:4", chordVel: 0.6, energy: 0.3 }]);
+ const drop = (full: boolean) => mat("house", "drive", [
+ { id: "groove", kind: "groove", bars: 2, harmony: ["vi", "IV"], lead: "r:4 | r:4", energy: 0.5 },
+ { id: "build", kind: "build", bars: 2, harmony: ["Vsus", "V"], lead: "G4:.5 G4:.5 A4:.5 A4:.5 B4:.5 B4:.5 C5:.5 D5:.5 | D5:.25 D5:.25 D5:.25 D5:.25 E5:.25 E5:.25 F5:.25 F5:.25 G5:1 r:1", groove: "build", energy: 0.65 },
+ full ? { id: "drop", kind: "drop", bars: 4, harmony: ["I", "vi", "IV", "I"], lead: "C6:.75 G5:.75 E5:.5 G5:1 C6:1 | A5:.75 E5:.75 C5:.5 E5:1 A5:1 | F5:.75 C6:.75 A5:.5 F5:1 A5:1 | G5:.75 E5:.75 C5:.5 C6:2", arp: Array(4).fill("C5:.25 E5:.25 G5:.25 C6:.25 ".repeat(4).trim()), groove: "drop", energy: 0.95 }
+ : { id: "drop", kind: "breakdown", bars: 4, harmony: ["I", "vi", "IV", "I"], lead: "C5:4 | r:4 | r:4 | r:4", groove: null, chordVel: 0.5, energy: 0.3 },
+ { id: "button", kind: "outro", bars: 1, harmony: ["I"], lead: "C5:1 r:3", energy: 0.4 }], { meter: "4/4" });
+ const peakOf = (m: Material) => { const t = craftReport(composePiece(m)).tension.sections; return t.reduce((a, x) => (x.value > a.value ? x : a)); };
+ const cg = peakOf(climax(true)), cb = peakOf(climax(false)), dg = peakOf(drop(true)), dbad = peakOf(drop(false));
+ ok(cg.id === "climax", `a home-chord tutti climax reads as the peak (${craftReport(composePiece(climax(true))).tension.sections.map((x) => `${x.id} ${x.value}`).join(", ")})`);
+ ok(cb.id !== "climax", `the same home chord thin and quiet is not the peak (peak: ${cb.id})`);
+ ok(dg.id === "drop", `an EDM drop reads as the peak over its build (${craftReport(composePiece(drop(true))).tension.sections.map((x) => `${x.id} ${x.value}`).join(", ")})`);
+ ok(dbad.id !== "drop", `a "drop" that thins out is not the peak (peak: ${dbad.id})`);
+ const lvl = (o: { loop?: boolean; mood?: MoodId }) => craftReport(piece({ bars: 6, mood: o.mood ?? "joy", loop: o.loop, sections: [["a", 2], ["b", 2], ["c", 2]], parts: [{ id: "lead", inst: "piano", role: "melody", src: [sec("C4:1 D4:1 E4:1 D4:1"), sec("C4:1 E4:1 D4:1 E4:1"), sec("D4:1 C4:1 E4:1 C4:1")].join(" | ") }, { id: "chords", inst: "piano", role: "accomp", src: Array(6).fill(C).join(" | ") }] })).findings;
+ ok(has(lvl({}), "tension", /flat/, "warn") && has(lvl({ loop: true }), "tension", /flat/, "info") && has(lvl({ mood: "calm" }), "tension", /flat/, "info"), "a flat curve warns, but a loop or a calm piece stays level on purpose (a note, not a warning)");
+
// ---------------- mood fit
const moody = (tempo: number, mode: ModeId) => craftReport(piece({ mood: "calm", tempo, mode, bars: 2, parts: [{ id: "lead", inst: "piano", role: "melody", src: "E5:1 D5:.5 C5:.5 D5:1 E5:1 | D5:1 C5:.5 D5:.5 E5:1 C5:1" }, { id: "chords", inst: "piano", role: "accomp", src: `${C} | ${C}` }, { id: "bass", inst: "bass", role: "bass", src: "C2:4 | C2:4" }] }));
ok(!has(moody(72, "major").findings, "mood", /./), "calm at 72 bpm in major fits");
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs
index 69a711c..2ec2ab8 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs
@@ -94,10 +94,16 @@ pass(`${Object.keys(M.VOCAB).length} style vocabularies compose, render (true pe
for (const secs of [70, 90, 110]) {
const f = M.fitScore(M.launchLofi3(), secs), perf = M.perform(f.piece, f.tempo, { expressive: true }), p = f.piece;
assert.equal(p.harmony[p.harmony.length - 1].name, "Cmaj9"); assert.equal(f.form, "full");
- assert(Math.abs(perf.lastOnset - (secs - p.tail)) < 0.05); assert(f.tempo >= 90 * 0.88 && f.tempo <= 90 * 1.12);
+ assert(Math.abs(perf.lastOnset - (secs - p.tail)) < 0.05 || (f.tempo === 90 && M.fitsAsWritten(p, secs))); assert(f.tempo >= 90 * 0.88 && f.tempo <= 90 * 1.12);
pass(`fit ${secs} s: ${p.plan.sections[0].bars} bars at ${f.tempo.toFixed(1)} bpm, last onset ${perf.lastOnset.toFixed(2)} s on Cmaj9`);
}
{ const a = M.filmAudio(M.launchLofi3(), 40)(16000); assert.equal(a[0].length, 40 * 16000); pass("filmAudio: exactly the film's length"); }
+// composed to length: the fit keeps the written tempo (the final ritard must not move the picture's hits); a form that does not fit is still fitted
+{ const p = M.composePiece({ ...M.testMaterial(M.VOCAB.house, { bars: 8 }), tail: 2 }), natural = M.perform(p, p.plan.tempo, { expressive: true }).lastOnset + p.tail, bar = (4 * 60) / p.plan.tempo;
+ const kept = M.fitScore(p, Math.round(natural)), moved = M.fitScore(p, natural + 2 * bar);
+ assert.equal(kept.tempo, p.plan.tempo); assert.equal(M.perform(kept.piece, kept.tempo, { expressive: true }).sec(4 * 4), M.perform(p, p.plan.tempo, { expressive: true }).sec(4 * 4), "bar 5 lands where it was written");
+ assert(moved.tempo !== p.plan.tempo || moved.piece.plan.sections.length !== p.plan.sections.length);
+ pass(`fit: a score composed to ${Math.round(natural)} s keeps ${p.plan.tempo} bpm (natural end ${natural.toFixed(2)} s: the tail takes the difference); ${(natural + 2 * bar).toFixed(1)} s is refitted`); }
// 9. Composer-facing fixes (from the blind composer's report).
{ const t = M.testMaterial(M.VOCAB.playful, { bars: 4 }), sec = t.sections[0];
@@ -131,6 +137,51 @@ for (const secs of [70, 90, 110]) {
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)`); }
+// 9b. Chords and bars (from the blind composer's report).
+{
+ // chords: a tie holds over the bar line (no restrike), comping gives the chord part a rhythm with rests, "r" voices a silent chord
+ const mat = (meter, sec, extra = {}) => ({ style: "cinematic", title: "t", seed: 3, mood: "tender", bpm: 80, key: "C", mode: "major", meter, grooves: {}, ...extra,
+ chords: { C: { voicing: "[C4 E4 G4]", bass: meter === "3/4" ? "C2:3" : meter === "5/4" ? "C2:5" : meter === "6/8" ? "C2:2" : meter === "7/8" ? "C2:3.5" : "C2:4" }, F: { voicing: "[C4 F4 A4]", bass: "F2:4" }, N: { voicing: "r", bass: "G2:4" } },
+ sections: [{ kind: "verse", groove: null, lead: "r:" + M.beatsPerBar(meter), ...sec }] });
+ const chordsOf = (p) => p.parts.find((x) => x.id === "chords").notes, bassOf = (p) => p.parts.find((x) => x.id === "bass").notes;
+ { const held = M.composePiece(mat("4/4", { bars: 2, harmony: ["C", "~"], lead: "E5:4 | D5:4" })), struck = M.composePiece(mat("4/4", { bars: 2, harmony: ["C", "C"], lead: "E5:4 | D5:4" }));
+ assert.equal(chordsOf(held).length, 3); assert(chordsOf(held).every((n) => n.d === 8)); assert.equal(chordsOf(struck).length, 6); assert.deepEqual(held.harmony.map((h) => h.t), [0]);
+ assert.equal(bassOf(held).length, 2, "the bass keeps its line under a held chord");
+ const tiedBass = M.composePiece(mat("4/4", { bars: 2, harmony: ["C", "~"], bass: ["C2:4", "~"], lead: "E5:4 | D5:4" })); assert.equal(bassOf(tiedBass).length, 1); assert.equal(bassOf(tiedBass)[0].d, 8);
+ const into = M.composePiece(mat("4/4", { bars: 2, harmony: ["C", "~ F"], bass: ["C2:4", "C2:2 F2:2"], lead: "E5:4 | D5:4" })); assert.deepEqual(chordsOf(into).map((n) => [n.t, n.d]).filter(([t]) => t === 0), [[0, 6], [0, 6], [0, 6]]); assert.deepEqual(into.harmony.map((h) => [h.t, h.name]), [[0, "C"], [6, "F"]]);
+ pass("harmony \"~\": the chord holds over the bar line (3 notes of 8 beats, not 6 restrikes), the bass keeps its line unless its bar is \"~\"; \"~ F\" holds into the bar, then changes");
+ const comp = M.composePiece(mat("4/4", { bars: 2, harmony: ["C F"], comp: ["x:1 r:.5 x:[email protected] r:1 x:1", "~:1 r:1 x:2"], bass: "C2:2 F2:2", lead: "E5:4 | D5:4" }));
+ const on = (t) => chordsOf(comp).filter((n) => Math.abs(n.t - t) < 1e-9);
+ assert.deepEqual([...new Set(chordsOf(comp).map((n) => n.t))], [0, 1.5, 3, 6]); assert(on(3).some((n) => n.p === 65), "x on beat 4 strikes the chord sounding there (F)");
+ assert(Math.abs(on(1.5)[0].v - on(0)[0].v * 0.6) < 1e-9, "@VEL scales the strike"); assert.equal(on(3)[0].d, 2, "~:1 holds beat 4's strike over the bar line");
+ assert.throws(() => M.composePiece(mat("4/4", { bars: 1, harmony: ["C"], comp: "x:1 r:1", lead: "E5:4" })), /comp bar .* sums to 2/);
+ pass("comp: x strikes the chord sounding at that point, r rests, @VEL accents, ~ ties a push over the bar line; a comp bar that does not add up throws");
+ const rest = M.composePiece(mat("4/4", { bars: 2, harmony: ["C", "N"], lead: "E5:4 | D5:4" }));
+ assert(chordsOf(rest).every((n) => n.t < 4)); assert.deepEqual(rest.harmony.map((h) => h.name), ["C", "N"]); assert(bassOf(rest).some((n) => n.t === 4 && n.p === 43));
+ pass("voicing \"r\": the chord part rests for that chord, the harmony still names it and its bass plays"); }
+ { const one = (meter, bar, extra) => { const b = M.beatsPerBar(meter); return M.composePiece(mat(meter, { bars: 1, harmony: [bar], bass: `r:${b}`, lead: `r:${b}` }, extra)).harmony.map((h) => h.t); };
+ assert.deepEqual(one("3/4", "C F"), [0, 2], "3/4: 2+1, never beat 2.5"); assert.deepEqual(one("6/8", "C F"), [0, 1]); assert.deepEqual(one("5/4", "C F"), [0, 3]);
+ assert.deepEqual(one("5/4", "C F", { grouping: [2, 3] }), [0, 2]); assert.deepEqual(one("7/8", "C F"), [0, 2]); assert.deepEqual(one("4/4", "C F"), [0, 2]);
+ assert.deepEqual(one("3/4", "C:1 F:2"), [0, 1]); assert.throws(() => one("3/4", "C:1 F:1"), /adds up to 2/);
+ pass("split bars: 3/4 changes on beat 3 (2+1), 6/8 3+3 eighths, 5/4 3+2 or its grouping (2+3), 7/8 4+3 eighths, explicit beats \"C:1 F:2\"; a wrong sum throws"); }
+}
+// 9c. One level scale: alternates and your own voices are calibrated to the slot's target (the style's number plus its fix).
+{ const stem = (p, slot) => { const r = M.renderPiece(p, SR, { stems: true, master: "none", only: (pt) => pt.id === slot }); return M.stemRms(r.stems[slot][0], r.stems[slot][1], SR); };
+ const tm = (v, slot, voice, extra = {}) => M.composePiece({ ...M.testMaterial(v, { bars: 4, lines: slot === "counter" || slot === "arp" ? [slot] : [] }), voices: { [slot]: voice }, ...extra });
+ let worst = 0, n = 0;
+ for (const v of Object.values(M.VOCAB)) for (const [slot, alts] of Object.entries(v.alternates)) for (const name of Object.keys(alts)) {
+ const p = tm(v, slot, name); if (p.stemTargets[slot] === undefined) continue; const off = stem(p, slot) - p.stemTargets[slot]; n++;
+ assert(Math.abs(off) <= 1.5, `${v.id} ${slot} alternate ${name} sits ${off.toFixed(1)} dB off its target`); worst = Math.max(worst, Math.abs(off)); }
+ const pianoLead = stem(tm(M.VOCAB.cinematic, "lead", "piano"), "lead") - M.VOCAB.cinematic.stemTargets.lead, synthLead = stem(tm(M.VOCAB.house, "lead", "synth"), "lead") - M.VOCAB.house.stemTargets.lead;
+ pass(`alternates: all ${n} in every style sit within ${worst.toFixed(2)} dB of their target (cinematic piano lead ${pianoLead.toFixed(1)}, house synth lead ${synthLead.toFixed(1)}; the blind composer needed +14 and +16.5)`);
+ const role = { chords: "accomp", arp: "accomp", lead: "melody", counter: "color", bass: "bass" }, offs = [];
+ for (const [style, slot, inst] of [["cinematic", "lead", "piano"], ["cinematic", "counter", "strings"], ["house", "lead", "leadSynth"], ["world", "arp", "guitar"], ["folk", "chords", "strings"], ["jazz", "bass", "bass"], ["orchestral", "lead", "woodwind"], ["lofiElectronic", "chords", "ePiano"], ["suspense", "lead", "bowedSolo"], ["playful", "arp", "marimba"]]) {
+ const p = tm(M.VOCAB[style], slot, { inst, role: role[slot] }), off = stem(p, slot) - p.stemTargets[slot]; offs.push(`${style} ${slot} ${inst} ${off >= 0 ? "+" : ""}${off.toFixed(1)}`);
+ assert(Math.abs(off) <= 3, `your own ${inst} as ${style} ${slot} sits ${off.toFixed(1)} dB off`); }
+ const cin = M.VOCAB.cinematic, own = tm(cin, "counter", { inst: "strings", role: "color" });
+ assert.equal(own.stemTargets.counter, cin.stemTargets.counter + M.VOCAB_TARGET_FIX.cinematic.counter, "your own counter takes the slot's corrected target (-16.4, not -7.5)");
+ const up = stem(tm(cin, "counter", { inst: "strings", role: "color", gainDb: 2 }), "counter") - stem(own, "counter"); assert(Math.abs(up - 2) < 0.05, `gainDb 2 = +2 dB (got ${up})`);
+ pass(`your own voice (gainDb left out) sits at the slot's target within 3 dB: ${offs.join(", ")}; its target is the corrected one (cinematic counter ${own.stemTargets.counter.toFixed(1)}); gainDb: 2 = ${up.toFixed(2)} dB over`); }
// 10. Novelty: the copy Alex heard scores as a copy; the shipped demos stay apart; a reused fragment fails.
{ const d = M.novelty(M.daylightCopy(), M.DEMOS);
assert(!d.pass && d.worst.name.startsWith("launchLofi") && d.worst.score > 0.6, `daylight copy scored ${d.worst.score} vs ${d.worst.name}`);
@@ -141,6 +192,36 @@ for (const secs of [70, 90, 110]) {
const quoted = M.composePiece({ ...M.testMaterial(M.VOCAB.playful, { bars: 4 }), sections: [{ kind: "hook", bars: 2, harmony: ["c0"], groove: null, lead: ["G5:1 B5:.5 C6:.5 B5:1 G5:1", "E5:1 G5:.5 A5:.5 G5:1 E5:1"] }] });
const src = M.composePiece({ ...M.testMaterial(M.VOCAB.playful, { bars: 4 }), sections: [{ kind: "hook", bars: 2, harmony: ["c0"], groove: null, lead: ["D5:1 F#5:.5 G5:.5 F#5:1 D5:1", "B4:1 D5:.5 E5:.5 D5:1 B4:1"] }] });
const r = M.novelty(quoted, { src: () => src }); assert(!r.pass && r.rows[0].reusedFragments > 0, "a transposed quote must be caught");
- pass(`novelty: a transposed 6-note quote of a shipped line fails (${r.rows[0].reusedFragments} reused fragments)`); }
+ pass(`novelty: a transposed 6-note quote of a shipped line fails (${r.rows[0].reusedFragments} reused fragments)`);
+ // a shipped melody re-barred into 5/4 (each 4/4 bar gains a beat on its last note), transposed up a tone: its rhythm and bar
+ // positions are new, its 6-note (interval, duration) fragments are broken, but its intervals are the tune: it must FAIL
+ const rebar = (name) => { const src = M.DEMOS[name](), bpb = M.beatsPerBar(src.plan.meter), mel = src.parts.flatMap((p) => p.notes.filter((n) => n.role === "melody")).sort((a, b) => a.t - b.t), last = new Map();
+ for (const n of mel) { const k = Math.floor(n.t / bpb + 1e-9); last.set(k, Math.max(last.get(k) ?? -1, n.t)); }
+ const notes = mel.map((n) => { const k = Math.floor(n.t / bpb + 1e-9); return { ...n, p: n.p + 2, t: n.t + k, d: n.d + (n.t === last.get(k) ? 1 : 0) }; }), bars = Math.ceil((Math.max(...notes.map((n) => n.t + n.d)) + 1) / 5);
+ return { title: "re-barred", seed: 5, tail: 1, harmony: [], parts: [{ id: "lead", inst: "piano", role: "melody", notes }], plan: { style: "folk", tempo: 90, meter: "5/4", sections: [{ id: "a", bars, mood: "calm", key: "D", mode: "major", melody: ["stepwise"], dyn: [0.6, 0.6] }] } }; };
+ for (const name of ["launchLofi3", "nocturne"]) { const v = M.novelty(rebar(name), M.DEMOS), row = v.rows.find((x) => x.name === name);
+ assert(!v.pass && row.quotedShapes > 0, `${name} re-barred into 5/4 passed (score ${row.score}, fragments ${row.reusedFragments}, shapes ${row.quotedShapes})`);
+ pass(`novelty: ${name}'s melody re-barred into 5/4 and transposed FAILS (similarity only ${row.score}, 6-note fragments ${row.reusedFragments}, 8-note shapes quoted ${row.quotedShapes})`); } }
+// 11. Speed without a changed bit: the voice cache and the parallel pool render exactly what a serial render does.
+{ const p = M.composePiece(M.testMaterial(M.VOCAB.lofi, { bars: 4 })), cache = new Map(), fresh = md5(M.renderPiece(p, SR));
+ assert.equal(md5(M.renderPiece(p, SR, { cache })), fresh); assert(cache.size > 3); assert.equal(md5(M.renderPiece(p, SR, { cache })), fresh, "a cache hit must be bit-identical");
+ const r = M.renderPiece(p, SR, { cache }), a = M.maskingCheck(p, SR, { seconds: r.L.length / SR, tempo: r.tempo, perf: r.perf }), pl = M.maskingPlan(p, { seconds: r.L.length / SR, tempo: r.tempo, perf: r.perf, cache });
+ assert.deepEqual(M.maskingFromBands(pl, Object.fromEntries(pl.roles.map((x) => [x, M.roleBandDb(p, SR, pl.opts(x), pl.spans)]))), a, "masking from cached role renders must equal the serial guard");
+ const sel = new Float64Array(Array.from({ length: 999 }, (_, i) => Math.sin(i * 7.3) * 5)), sorted = [...sel].sort((x, y) => x - y); assert.equal(M.kth(Float64Array.from(sel), 999, 899), sorted[899]);
+ pass(`voice cache: a hit renders bit-identically (md5 ${fresh.slice(0, 8)}), masking from cached role renders equals the serial guard; quickselect = sort`); }
+// the master note names where its peak is: a spike planted on the lead at bar 3 beat 2 is found there, the lead named first
+{ const p = M.composePiece(M.testMaterial(M.VOCAB.lofiElectronic, { bars: 4 })), r = M.renderPiece(p, SR, { stems: true }), bpb = M.beatsPerBar(p.plan.meter), at = Math.round(r.perf.sec(2 * bpb + 1) * SR);
+ r.L[at] = 1.5; r.stems.lead[0][at] = 1.5; const pk = M.peakReport(r, SR);
+ assert.equal(pk.bar, 3); assert.equal(pk.beat, 2); assert.equal(pk.parts[0].id, "lead"); assert(pk.parts[0].notes.length > 0);
+ pass(`peak report: bar ${pk.bar} beat ${pk.beat}, ${pk.parts.map((x) => `${x.id}${x.notes.length ? ` ${x.notes.join(" ")}` : ""}`).join(", ")}`); }
+{ const { spawnSync } = await import("node:child_process"), { mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync, rmSync } = await import("node:fs");
+ const dir = join(import.meta.dirname, "../out/music-unit"); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "x.wav"), "keep me");
+ const run = spawnSync(process.execPath, [join(import.meta.dirname, "music.mjs"), "render", "lofiNostalgic", join(dir, "x.mp3"), "--seconds", "4", "--verify"], { encoding: "utf8" });
+ const json = JSON.parse(run.stdout.slice(run.stdout.indexOf("{"), run.stdout.indexOf("\n}") + 2));
+ assert.equal(readFileSync(join(dir, "x.wav"), "utf8"), "keep me", "rendering x.mp3 must never touch x.wav");
+ assert(existsSync(join(dir, "x.mp3")) && readdirSync(dir).length === 2, `leftovers: ${readdirSync(dir).join(", ")}`);
+ assert.equal(json.deterministic, true, "the parallel, cached render must equal a serial one bit for bit");
+ pass("render x.mp3 leaves an existing x.wav alone (no temp left behind); the parallel cached render equals a serial one (--verify)"); }
console.log(`music unit: ${ok.length} checks PASS in ${((Date.now() - t0) / 1000).toFixed(0)} s`);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
index 5002272..618aa5e 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
@@ -11,7 +11,8 @@
// node tools/music.mjs craft <piece> [more ...] [--json] # how it is WRITTEN: melody, harmony, rhythm, tension, mood fit (no render, advisory; errors fail)
// node tools/music.mjs novelty <piece> [more ...] # vs every shipped piece (and pairwise when several); FAILS above the threshold or on a reused fragment
// node tools/music.mjs list # shipped demos and fixtures
-// node tools/music.mjs render <piece> <out.wav|out.mp3> [--seconds 45] [--flat] [--tempo 66] [--fit] [--loop] [--stems]
+// node tools/music.mjs render <piece> <out.wav|out.mp3> [--seconds 45] [--flat] [--tempo 66] [--fit] [--loop] [--stems] [--verify]
+// (--verify renders a second time, serially and without the voice cache, and reports whether it is bit-identical)
// node tools/music.mjs stems <piece> [--seconds 45] [--fit] # each part's stem RMS vs its target, flags > 3 dB off
// (--fit uses fitScore: the piece's refit, e.g. a composed score repeats its stretch section so it still ends on its outro;
// --loop renders a seamless loop, automatic for a plan.loop piece. LUFS alone once hid a sub 7-10 dB too hot:
@@ -20,17 +21,78 @@
// node tools/music.mjs samples <outdir> # the whole deliverable set + meters.json + .m4a
// node tools/music.mjs score <piece> # the text score, bar by bar
// node tools/music.mjs probe # piano realism probes
+// node tools/music.mjs calibrate [--voices] # palette trims (vocabTrim.ts); --voices: alternates' trims and your own voices' levels (vocabVoices.ts)
+// (check/render run voices on all but one core; ANIDOODLE_THREADS=1 renders serially, ANIDOODLE_TIMING=1 prints check's stage times)
import { build } from "esbuild";
import { execFileSync } from "node:child_process";
import { writeFileSync, readFileSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
import { dirname, join, resolve, basename } from "node:path";
import { fileURLToPath } from "node:url";
+import { Worker } from "node:worker_threads";
+import { availableParallelism } from "node:os";
const here = dirname(fileURLToPath(import.meta.url));
const SR = 48000;
+let ENGINE_URL = "";
const load = async () => {
const r = await build({ entryPoints: [join(here, "../src/canvas-core/music/index.ts")], bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });
- return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));
+ ENGINE_URL = "data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64");
+ return import(ENGINE_URL);
+};
+
+// ---------------------------------------------------------------- voices in parallel
+// Synthesis is most of a render, and each part's voice is a pure function of its inputs (render.ts
+// VoiceJob). check/render/stems list every voice job they will need (the mix at 48 kHz, each guard
+// role, the stems at 24 kHz), run the distinct ones on a worker pool, and render from that cache:
+// the same code on the same inputs, so the audio is bit-identical to a serial render
+// (tools/music-unit.mjs checks it). ANIDOODLE_THREADS=1 renders serially.
+const WORKER = `const { parentPort, workerData } = require("node:worker_threads");
+import(workerData).then((M) => {
+ parentPort.on("message", ({ id, job, task }) => {
+ if (job) { const o = M.runVoiceJob(job); parentPort.postMessage({ id, o }, [...new Set([o.L.buffer, o.R.buffer, o.halo && o.halo.buffer].filter(Boolean))]); return; }
+ const opts = { ...task.opts, cache: new Map(task.voices) };
+ parentPort.postMessage({ id, out: task.kind === "band" ? M.roleBandDb(task.piece, task.sr, opts, task.spans) : M.measureStems(task.piece, task.sr, opts) });
+ });
+ parentPort.postMessage({ ready: true });
+});`;
+const THREADS = () => Number(process.env.ANIDOODLE_THREADS) || Math.max(1, availableParallelism() - 1);
+/** Run messages on a pool of `threads` workers; resolves to their replies by id, in the order given. */
+const pool = (msgs, threads) => { const queue = msgs.slice(), out = new Map(); return Promise.all(Array.from({ length: Math.min(threads, msgs.length) }, () => new Promise((ok, fail) => {
+ const w = new Worker(WORKER, { eval: true, workerData: ENGINE_URL });
+ const next = () => { const x = queue.shift(); if (!x) { w.terminate(); ok(); return; } w.postMessage(x); };
+ w.on("message", (m) => { if (!m.ready) out.set(m.id, m); next(); }); w.on("error", fail);
+}))).then(() => out); };
+export const prewarm = async (M, cache, jobs) => {
+ const todo = new Map(); for (const j of jobs) { const k = M.voiceJobKey(j); if (!cache.has(k) && !todo.has(k)) todo.set(k, j); }
+ if (Math.min(todo.size, THREADS()) < 2) return; // the render synthesizes on demand
+ const queue = [...todo].sort((a, b) => b[1].n * b[1].keys.length - a[1].n * a[1].keys.length); // biggest first: the slowest voice starts at once
+ for (const [id, m] of await pool(queue.map(([id, job]) => ({ id, job })), THREADS())) cache.set(id, m.o);
+};
+/** What `check` renders besides the mix: the piece the mix plays (a loop's source), its performance, the mix's length, and the masking plan. */
+const checkPlan = (M, piece, tempo, seconds, loop = piece.plan.loop) => {
+ const src = loop ? M.loopSource(piece) : null, p = src ? src.p : piece, o = src ? src.opts : { seconds, tempo };
+ const perf = M.perform(p, o.tempo ?? p.plan.tempo, { expressive: true }), n = src ? Math.round(src.loopS * SR) : o.seconds ? Math.round(o.seconds * SR) : Math.ceil((perf.lastOnset + p.tail) * SR);
+ return { p, o, mask: M.maskingPlan(p, { seconds: n / SR, tempo: o.tempo, perf }) };
+};
+/** Every voice job `check` runs: the mix, each role the masking guard renders from the mix's performance, and the 24 kHz stems. */
+const checkJobs = (M, piece, tempo, seconds, { loop = piece.plan.loop, stems = true } = {}) => {
+ const { p, o, mask } = checkPlan(M, piece, tempo, seconds, loop);
+ return [...M.voiceJobs(p, SR, o), ...(mask ? mask.roles.flatMap((r) => M.voiceJobs(p, SR, mask.opts(r))) : []), ...(stems ? M.voiceJobs(piece, STEM_SR, { tempo, seconds }) : [])];
+};
+/** A piece or a performance as plain data for a worker (its functions stay behind: a refit, the tempo map). */
+const plain = (p) => { const { refit, shortForm, sec, ...rest } = p; void refit; void shortForm; void sec; return rest; };
+/**
+ * The guards' role renders and the stems, started on workers while the caller renders the mix: each
+ * gets the voices it needs from the cache (so nothing is synthesized twice) and returns numbers only.
+ * Resolves to { bands, stems } (either may be undefined: no melody, or stems not asked for).
+ */
+const startGuards = (M, cache, piece, tempo, seconds, { loop = piece.plan.loop, stems = true } = {}) => {
+ if (THREADS() < 2) return Promise.resolve({});
+ const { p, mask } = checkPlan(M, piece, tempo, seconds, loop), voices = (jobs) => jobs.map((j) => { const k = M.voiceJobKey(j); return [k, cache.get(k)]; }).filter(([, v]) => v);
+ const msgs = [];
+ if (mask) for (const r of mask.roles) { const { cache: _c, perf, ...opts } = mask.opts(r); msgs.push({ id: `band:${r}`, task: { kind: "band", piece: plain(p), sr: SR, spans: mask.spans, opts: { ...opts, perf: plain(perf) }, voices: voices(M.voiceJobs(p, SR, mask.opts(r))) } }); }
+ if (stems) msgs.push({ id: "stems", task: { kind: "stems", piece: plain(piece), sr: STEM_SR, opts: { tempo, seconds }, voices: voices(M.voiceJobs(piece, STEM_SR, { tempo, seconds })) } });
+ return pool(msgs, THREADS()).then((out) => ({ bands: mask ? Object.fromEntries(mask.roles.map((r) => [r, out.get(`band:${r}`).out])) : undefined, stems: out.get("stems")?.out }));
};
/** A piece by demo name, or from a module: "path.ts#export" (default export if no #). Material is composed. */
@@ -84,18 +146,20 @@ const onsetsFromData = (rendered) => {
for (const t of ts) if (t - last > 0.03) { c++; last = t; } return c;
};
-const renderOne = (M, spec) => {
+const renderOne = async (M, spec) => {
let piece = spec.make ? spec.make() : (M.DEMOS[spec.piece] ?? M.FIXTURES[spec.piece])();
let tempo = spec.tempo ?? piece.plan.tempo;
let form;
if (spec.fit) { const f = M.fitScore(piece, spec.seconds); piece = f.piece; tempo = f.tempo; form = `${f.form}: ${f.piece.plan.sections.map((x) => x.id).join(", ")}`; }
const opts = { seconds: spec.seconds, tempo };
if (spec.flat) Object.assign(opts, { expressive: false, piano: M.PIANO_FLAT, flatVelocity: 0.6 });
- const loop = spec.loop || piece.plan.loop, go = () => (loop ? M.renderLoop(piece, SR) : M.renderPiece(piece, SR, opts));
- const t0 = Date.now(), r = go(), ms = Date.now() - t0;
- // determinism: a second render must be bit-identical
- const r2 = go(); let same = true; for (let i = 0; i < r.L.length; i += 7) if (r.L[i] !== r2.L[i] || r.R[i] !== r2.R[i]) { same = false; break; }
- return { r, piece, tempo, ms, deterministic: same, form };
+ const loop = spec.loop || piece.plan.loop, go = (cache) => (loop ? M.renderLoop(piece, SR, { cache, stems: true }) : M.renderPiece(piece, SR, { ...opts, cache, stems: true }));
+ const t0 = Date.now(), par = spec.cache && !spec.flat; if (par) await prewarm(M, spec.cache, checkJobs(M, piece, tempo, spec.seconds, { loop, stems: spec.stems }));
+ const guards = par ? startGuards(M, spec.cache, piece, tempo, spec.seconds, { loop, stems: spec.stems }) : Promise.resolve({}); // on workers while the mix renders here
+ const r = go(spec.cache), ms = Date.now() - t0;
+ // determinism (--verify): a second, fully serial render without any cache must be bit-identical
+ let same = null; if (spec.verify) { const r2 = go(undefined); same = r.L.length === r2.L.length && r.L.every((x, i) => x === r2.L[i]) && r.R.every((x, i) => x === r2.R[i]); }
+ return { r, piece, tempo, ms, deterministic: same, form, guards: await guards };
};
const voicing = (M, piece, tempo, seconds, flat) => {
@@ -118,7 +182,7 @@ const main = async () => {
const flag = (k) => args.includes(k), val = (k, d) => { const i = args.indexOf(k); return i >= 0 ? Number(args[i + 1]) : d; };
if (cmd === "list") { console.log("demos (listening references and the novelty corpus, never a film's score):\n " + Object.keys(M.DEMOS).join("\n ") + "\nfixtures (tests):\n " + Object.keys(M.FIXTURES).join("\n ")); return; }
if (cmd === "vocab") { if (args[0] === "--md") vocabMarkdown(M); else printVocab(M, args[0]); return; }
- if (cmd === "calibrate") { calibrate(M); return; }
+ if (cmd === "calibrate") { if (flag("--voices")) calibrateVoices(M); else calibrate(M); return; }
if (cmd === "novelty") {
const refs = args.filter((a) => !a.startsWith("--") && !/^[\d.]+$/.test(a)), pcs = [];
for (const ref of refs) pcs.push(await getPiece(M, ref));
@@ -140,30 +204,36 @@ const main = async () => {
if (cmd === "check") {
const pc = await getPiece(M, args[0]); let piece = pc.make(), tempo = piece.plan.tempo, seconds = val("--seconds", undefined);
if (flag("--fit")) { const f = M.fitScore(piece, seconds); piece = f.piece; tempo = f.tempo; }
- const r = piece.plan.loop ? M.renderLoop(piece, SR) : M.renderPiece(piece, SR, { seconds, tempo });
- const ok = [report(M, r, piece), printStems(M, piece, tempo, seconds)?.ok !== false];
- { const cr = M.craftReport(piece, { centroidHz: M.centroid([r.L, r.R], SR).mean }); console.log(M.craftText(cr)); ok.push(!cr.findings.some((f) => f.level === "error")); }
+ const T = process.env.ANIDOODLE_TIMING ? (l) => console.error(`[timing] ${l} ${((Date.now() - T0) / 1000).toFixed(1)} s`) : () => {}, T0 = Date.now();
+ const cache = new Map(); await prewarm(M, cache, checkJobs(M, piece, tempo, seconds)); T("voices"); // every voice once, in parallel
+ const pending = startGuards(M, cache, piece, tempo, seconds).then((x) => { T("guard renders + stems"); return x; }); // the guards' role renders and the stems, on workers meanwhile
+ const r = piece.plan.loop ? M.renderLoop(piece, SR, { cache, stems: true }) : M.renderPiece(piece, SR, { seconds, tempo, cache, stems: true }); T("mix"); const g = await pending; // stems: the peak note names the parts that pile up
+ const ok = [report(M, r, piece, cache, g.bands), printStems(M, piece, tempo, seconds, cache, g.stems)?.ok !== false];
+ T("report + stems"); { const cr = M.craftReport(piece, { centroidHz: M.centroid([r.L, r.R], SR).mean }); console.log(M.craftText(cr)); ok.push(!cr.findings.some((f) => f.level === "error")); } T("craft");
if (!pc.demo) { const fam = [args[0]]; ok.push(printNovelty(M, args[0], M.novelty(piece, M.DEMOS, fam), "shipped pieces")); }
console.log(ok.every(Boolean) ? "CHECK PASS: now a human listens (an mp3 or wav on a page)" : "CHECK FAIL: fix the items above, then run check again");
if (!ok.every(Boolean)) process.exitCode = 1; return;
}
if (cmd === "render") {
- const [name, out] = args, pc = await getPiece(M, name); const { r, tempo, ms, deterministic, piece } = renderOne(M, { make: pc.make, seconds: val("--seconds", undefined), tempo: val("--tempo", undefined), flat: flag("--flat"), fit: flag("--fit") });
- const mp3 = out.endsWith(".mp3"), wav = mp3 ? out.replace(/\.mp3$/, ".wav") : out;
+ const [name, out] = args, pc = await getPiece(M, name), cache = new Map();
+ const { r, tempo, ms, deterministic, piece, guards } = await renderOne(M, { make: pc.make, seconds: val("--seconds", undefined), tempo: val("--tempo", undefined), flat: flag("--flat"), fit: flag("--fit"), loop: flag("--loop"), cache, verify: flag("--verify"), stems: flag("--stems") });
+ // an mp3 is encoded from a private intermediate next to it (never x.wav: rendering x.mp3 must not touch an x.wav you already have)
+ const mp3 = out.endsWith(".mp3"), wav = mp3 ? join(dirname(resolve(out)), `.${basename(out)}.${process.pid}.tmp.wav`) : out;
if (mp3 && (piece.plan.loop || flag("--loop"))) console.log("NOTE: mp3 is not gapless (encoder padding clicks at the loop point). Ship loops as .wav (or ogg/m4a with gapless metadata).");
writeWavFloat(wav, r.L, r.R);
- if (mp3) { execFileSync("ffmpeg", ["-v", "error", "-y", "-i", wav, "-c:a", "libmp3lame", "-b:a", "256k", out]); unlinkSync(wav); }
+ if (mp3) { try { execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "wav", "-i", wav, "-c:a", "libmp3lame", "-b:a", "256k", out]); } finally { if (existsSync(wav)) unlinkSync(wav); } }
const m = M.measure(decode(out), SR);
console.log(JSON.stringify({ file: out, tempo, renderMs: ms, deterministic, gainDb: r.gainDb, loopS: r.loopS, ...m, shortTerm: undefined }, null, 1));
- let good = report(M, r, piece);
- if (flag("--stems")) good = printStems(M, piece, tempo, val("--seconds", undefined)).ok && good;
+ let good = report(M, r, piece, cache, guards.bands);
+ if (flag("--stems")) good = printStems(M, piece, tempo, val("--seconds", undefined), cache, guards.stems).ok && good;
if (!good) process.exitCode = 1;
return;
}
if (cmd === "stems") {
const [name] = args; let piece = (await getPiece(M, name)).make(), tempo = piece.plan.tempo, seconds = val("--seconds", undefined);
if (flag("--fit")) { const f = M.fitScore(piece, seconds); piece = f.piece; tempo = f.tempo; }
- printStems(M, piece, tempo, seconds); return;
+ const cache = new Map(); await prewarm(M, cache, M.voiceJobs(piece, STEM_SR, { tempo, seconds }));
+ printStems(M, piece, tempo, seconds, cache); return;
}
if (cmd === "meter") { for (const f of args) { const m = M.measure(decode(f), SR), ff = ffmpegEbu(f); console.log(basename(f), `LUFS ${fmt(m.lufs)} (ffmpeg ${fmt(ff.I)}) LRA ${fmt(m.lra)} (ffmpeg ${fmt(ff.LRA)}) TP ${fmt(m.dbtp)} dBTP (ffmpeg ${fmt(ff.TP)}) onsets/s ${fmt(m.onsetsPerS, 2)} centroid ${fmt(m.centroidHz, 0)} Hz (energy-wtd ${fmt(m.centroidEnergyHz, 0)}) dur ${fmt(m.durationS, 2)} lastOnset ${fmt(m.lastOnsetS, 2)}`); } return; }
if (cmd === "score") { console.log(M.scoreText((await getPiece(M, args[0])).make())); return; }
@@ -194,8 +264,8 @@ const main = async () => {
mkdirSync(join(dir, "fixtures"), { recursive: true });
const results = [];
for (const s of set) {
- const { r, piece, tempo, ms, deterministic, form } = renderOne(M, s);
- const g = M.guardReport(r, SR, s.seconds, { masking: !s.noMasking });
+ const cache = new Map(), { r, piece, tempo, ms, deterministic, form } = await renderOne(M, { ...s, verify: true, cache, stems: false });
+ const g = M.guardReport(r, SR, s.seconds, { masking: !s.noMasking, cache });
const wav = join(dir, s.file + ".wav"); writeWavFloat(wav, r.L, r.R);
execFileSync("ffmpeg", ["-v", "error", "-y", "-i", wav, "-c:a", "aac", "-b:a", "192k", join(dir, s.file + ".m4a")]);
const m = M.measure(decode(wav), SR), ff = ffmpegEbu(wav), mm = M.measure(decode(join(dir, s.file + ".m4a")), SR);
@@ -238,15 +308,66 @@ const calibrate = (M) => {
console.log(`wrote ${file}`);
};
+/**
+ * Alternates and your own voices, on the same scale as the palette (src/canvas-core/music/vocabVoices.ts):
+ * each alternate's trim to its slot's stem target (the style's number plus its fix) on the style's
+ * test signal, two passes (drive and amps are not linear), capped at +-30 dB; and each instrument's
+ * stem level at gainDb 0 on each slot's test line (cinematic test signal with the counter line an octave down;
+ * drums on the lo-fi electronic kit; default options), from which
+ * compose places a composer's own voice at the slot's target.
+ */
+const calibrateVoices = (M) => {
+ const stem = (p, slot) => { const r = M.renderPiece(p, STEM_SR, { stems: true, master: "none", only: (pt) => pt.id === slot }), x = r.stems[slot]; return x ? M.stemRms(x[0], x[1], STEM_SR) : -Infinity; };
+ const alt = {}, altFix = {}; for (const T of [M.VOCAB_ALT_TRIM, M.VOCAB_ALT_TARGET_FIX, M.INST_LEVEL, M.INST_REGISTER, M.SLOT_REF_PITCH]) for (const k of Object.keys(T)) delete T[k];
+ for (const v of Object.values(M.VOCAB)) { alt[v.id] = {};
+ for (const [slot, alts] of Object.entries(v.alternates)) for (const name of Object.keys(alts)) {
+ let trim = 0; (M.VOCAB_ALT_TRIM[v.id] ??= {})[slot] ??= {};
+ for (let pass = 0; pass < 2; pass++) {
+ M.VOCAB_ALT_TRIM[v.id][slot][name] = trim;
+ const p = M.composePiece({ ...M.testMaterial(v, { bars: 4, lines: slot === "counter" || slot === "arp" ? [slot] : [] }), voices: { [slot]: name } }), t = p.stemTargets[slot], rms = stem(p, slot);
+ if (t === undefined || !Number.isFinite(rms)) break;
+ trim = +Math.max(-30, Math.min(30, trim + t - rms)).toFixed(1);
+ }
+ (alt[v.id][slot] ??= {})[name] = trim;
+ // where a 30 dB trim cannot reach the target (a piano's top octave on a counter target set for a harp), the target moves to where the voice sits, as for the palette
+ const p = M.composePiece({ ...M.testMaterial(v, { bars: 4, lines: slot === "counter" || slot === "arp" ? [slot] : [] }), voices: { [slot]: name } }), off = p.stemTargets[slot] === undefined ? 0 : stem(p, slot) - p.stemTargets[slot];
+ if (Math.abs(off) > 1) ((altFix[v.id] ??= {})[slot] ??= {})[name] = +off.toFixed(1);
+ console.log(`${v.id.padEnd(14)} ${slot.padEnd(8)} ${name.padEnd(10)} ${trim >= 0 ? "+" : ""}${trim}${Math.abs(off) > 1 ? ` (target moved ${off.toFixed(1)})` : ""}`);
+ } }
+ const inst = {}, reg = {}, refPitch = {};
+ const DRUM = ["kick", "snare", "hat", "noiseDrum", "timpani"], ALL = ["piano", "musicBox", "bell", "celesta", "marimba", "vibes", "harp", "guitar", "strings", "fmBell", "ePiano", "pulse", "triangle", "noiseDrum", "kick", "snare", "hat", "bass", "warmPad", "softPluck", "sub", "organ", "brass", "woodwind", "choir", "timpani", "leadSynth", "bowedSolo", "glockenspiel", "wurlitzer", "pipeOrgan"];
+ const role = { chords: "accomp", arp: "accomp", lead: "melody", counter: "color", bass: "bass", kick: "drum", snare: "drum", hat: "drum" };
+ // pitched voices on the cinematic test signal, the counter line an octave lower than the palette's (octaves 5-6: where a composer's
+ // own counter line usually sits; the register moves some instruments' level by 8 dB); drums on the lo-fi electronic kit's groove
+ const ref = M.testMaterial(M.VOCAB.cinematic, { bars: 4, lines: ["counter", "arp"] }), kit = M.testMaterial(M.VOCAB.lofiElectronic, { bars: 4 });
+ const lower = { ...ref, sections: ref.sections.map((x) => ({ ...x, counter: x.counter.map((b) => b.replace(/([A-G][#b]?)(\d)/g, (_, n, o) => `${n}${+o - 1}`)) })) };
+ const median = (ns) => { const ps = ns.map((n) => n.p).sort((a, b) => a - b); return ps[Math.floor(ps.length / 2)]; };
+ for (const slot of ["chords", "lead", "counter", "bass", "arp"]) refPitch[slot] = median(M.composePiece(lower).parts.find((x) => x.id === slot).notes);
+ // the register curve: the lead line moved by whole octaves (level at each median pitch), so your own voice is placed for the register it plays in
+ const moved = (k) => ({ ...lower, sections: lower.sections.map((x) => ({ ...x, lead: x.lead.map((b) => b.replace(/([A-G][#b]?)(\d)/g, (_, n, o) => `${n}${+o + k}`)) })) });
+ for (const i of ALL) { inst[i] = {};
+ for (const slot of DRUM.includes(i) ? ["kick", "snare", "hat"] : ["chords", "lead", "counter", "bass", "arp"]) {
+ const p = M.composePiece({ ...(DRUM.includes(i) ? kit : lower), voices: { [slot]: { inst: i, role: role[slot], gainDb: 0 } } }), rms = stem(p, slot);
+ if (Number.isFinite(rms)) inst[i][slot] = +rms.toFixed(1);
+ }
+ if (!DRUM.includes(i)) { reg[i] = []; for (const k of [-3, -2, -1, 0, 1, 2]) { const p = M.composePiece({ ...moved(k), voices: { lead: { inst: i, role: "melody", gainDb: 0 } } }), rms = stem(p, "lead");
+ if (Number.isFinite(rms)) reg[i].push([refPitch.lead + 12 * k, +(rms - inst[i].lead).toFixed(1)]); } }
+ console.log(`${i.padEnd(13)} ${Object.entries(inst[i]).map(([k, x]) => `${k} ${x}`).join(" ")}${reg[i] ? ` | register ${reg[i].map(([p, d]) => `${M.nameOf(p)} ${d >= 0 ? "+" : ""}${d}`).join(" ")}` : ""}`); }
+ const file = join(here, "../src/canvas-core/music/vocabVoices.ts"), head = readFileSync(file, "utf8").split("export const VOCAB_ALT_TRIM")[0], j = (x) => JSON.stringify(x, null, 1).replace(/"(\w+)":/g, "$1:");
+ writeFileSync(file, `${head}export const VOCAB_ALT_TRIM: Record<string, Partial<Record<Slot, Record<string, number>>>> = ${j(alt)};\nexport const VOCAB_ALT_TARGET_FIX: Record<string, Partial<Record<Slot, Record<string, number>>>> = ${j(altFix)};\nexport const INST_LEVEL: Record<string, Partial<Record<Slot, number>>> = ${j(inst)};\nexport const INST_REGISTER: Record<string, [number, number][]> = ${JSON.stringify(reg)};\nexport const SLOT_REF_PITCH: Partial<Record<Slot, number>> = ${j(refPitch)};\n`);
+ console.log(`wrote ${file}`);
+};
+
const printVocab = (M, id) => {
if (!id) { for (const v of Object.values(M.VOCAB)) console.log(`${v.id.padEnd(15)} ${v.name}: ${v.atmosphere}\n${"".padEnd(16)}grooves: ${v.grooves.join(", ") || "none (no drums)"} | moods: ${v.moods.join(", ")} | ${v.tempo.join("-")} bpm ${v.meters.join(" ")}`);
console.log("\ngroove families:"); for (const [k, d] of Object.entries(M.GROOVE_FAMILIES)) console.log(` ${k.padEnd(10)} ${d}`);
console.log("\nsection kinds:"); for (const [k, d] of Object.entries(M.KINDS)) console.log(` ${k.padEnd(10)} ${d.what}`); return; }
const v = M.VOCAB[id]; if (!v) throw new Error(`no style "${id}" (have: ${Object.keys(M.VOCAB).join(", ")})`);
console.log(`${v.name} (${v.id}): ${v.atmosphere}\ntempo ${v.tempo.join("-")} bpm, meters ${v.meters.join(" ")}, swing ${v.swing.join("-")}, moods ${v.moods.join(", ")}`);
- const eff = (slot, x) => +(x.gainDb + (M.VOCAB_TRIM[v.id]?.[slot] ?? 0)).toFixed(1), tgt = (slot) => (v.stemTargets[slot] === undefined ? "-" : +(v.stemTargets[slot] + (M.VOCAB_TARGET_FIX[v.id]?.[slot] ?? 0)).toFixed(1));
- console.log("palette (slot: instrument, gain dB, stem target dB):"); for (const [slot, x] of Object.entries(v.palette)) console.log(` ${slot.padEnd(8)} ${x.inst.padEnd(10)} ${String(eff(slot, x)).padStart(5)} ${tgt(slot)} dB${Object.keys(v.alternates[slot] ?? {}).length ? ` alternates: ${Object.entries(v.alternates[slot]).map(([n, a]) => `${n} (${a.inst}, ${a.gainDb} dB)`).join(", ")}` : ""}`);
- for (const [slot, alts] of Object.entries(v.alternates)) if (!v.palette[slot]) console.log(` ${slot.padEnd(8)} (no default) alternates: ${Object.entries(alts).map(([n, a]) => `${n} (${a.inst}, ${a.gainDb} dB)`).join(", ")}`);
+ const tgt = (slot) => (v.stemTargets[slot] === undefined ? "-" : +(v.stemTargets[slot] + (M.VOCAB_TARGET_FIX[v.id]?.[slot] ?? 0)).toFixed(1));
+ console.log("palette (slot: instrument, stem target dB). Every voice, alternate or your own, is calibrated to its slot's target:\n levels.<slot> and your own voice's gainDb are dB offsets from there (0 = at the target)");
+ for (const [slot, x] of Object.entries(v.palette)) console.log(` ${slot.padEnd(8)} ${x.inst.padEnd(10)} ${String(tgt(slot)).padStart(6)} dB${Object.keys(v.alternates[slot] ?? {}).length ? ` alternates: ${Object.entries(v.alternates[slot]).map(([n, a]) => `${n} (${a.inst})`).join(", ")}` : ""}`);
+ for (const [slot, alts] of Object.entries(v.alternates)) if (!v.palette[slot]) console.log(` ${slot.padEnd(8)} (no default) alternates: ${Object.entries(alts).map(([n, a]) => `${n} (${a.inst})`).join(", ")}`);
console.log(`stem targets ${v.calibrated ? "calibrated on a listened score" : "are starting numbers (uncalibrated: flags are advisory until a human listens)"}`);
console.log(`grooves: ${v.grooves.map((g) => `${g} (${M.GROOVE_FAMILIES[g]})`).join("\n ") || "none"}`);
for (const [k, x] of Object.entries(v.harmony)) console.log(`harmony.${k}: ${Array.isArray(x) ? x.join(", ") : x}`);
@@ -259,6 +380,7 @@ const printVocab = (M, id) => {
/** references/music/styles/vocabularies.md, generated from the data so the page never drifts from the code. */
const vocabMarkdown = (M) => {
const o = ["# Style vocabularies", "", "> GENERATED by `node tools/music.mjs vocab --md` from `engine/src/canvas-core/music/vocab.ts` and `vocabMore.ts`. Do not edit by hand.", "> A style is a vocabulary: sound, grooves, harmony language, melody rules, arrangement grammar. It never", "> contains notes. You compose the notes ([../compose.md](../compose.md)).", "",
+ "**Levels are one scale.** Every voice in a slot, the palette's, an alternate or your own, is calibrated to the slot's stem target (the \"Stem target dB\" column: the level the stem meter reads when the part plays). Everything you set is a dB offset from there: `levels: { lead: 2 }` is two dB over the target, and your own voice's `gainDb` works the same way (`voices: { counter: { inst: \"strings\", role: \"color\" } }` sits at the counter target; `gainDb: -3` sits 3 dB under it). Engine gains (`Voice.gainDb` inside vocab.ts) are internal and never on this scale.", "",
"| Style | Atmosphere | Tempo, meters | Moods | Grooves |", "|---|---|---|---|---|"];
for (const v of Object.values(M.VOCAB)) o.push(`| \`${v.id}\` | ${v.atmosphere} | ${v.tempo.join("-")} bpm; ${v.meters.join(", ")} | ${v.moods.join(", ")} | ${v.grooves.join(", ") || "none (no drums)"} |`);
o.push("", "## Groove families", "", "Pick a family and its knobs (`density`, `variation`, `fill`, `accent`); the seed varies every bar. Or write the drum bars yourself.", "");
@@ -266,8 +388,10 @@ const vocabMarkdown = (M) => {
o.push("", "## Section kinds (the arrangement grammar)", "", "A kind decides which layers may sound; your lines sound only where you write them.", "");
for (const [k, d] of Object.entries(M.KINDS)) o.push(`- \`${k}\` (drums: ${d.drums ?? "none"}, bass: ${d.bass ? "yes" : "no"}): ${d.what}`);
for (const v of Object.values(M.VOCAB)) {
- o.push("", `## \`${v.id}\`: ${v.name}`, "", `${v.atmosphere}. Tempo ${v.tempo.join("-")} bpm, meters ${v.meters.join(", ")}, swing ${v.swing.join("-")}.`, "", "| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |", "|---|---|---|---|---|");
- for (const [slot, x] of Object.entries(v.palette)) o.push(`| ${slot} | \`${x.inst}\` | ${+(x.gainDb + (M.VOCAB_TRIM[v.id]?.[slot] ?? 0)).toFixed(1)} | ${v.stemTargets[slot] === undefined ? "-" : +(v.stemTargets[slot] + (M.VOCAB_TARGET_FIX[v.id]?.[slot] ?? 0)).toFixed(1)} | ${Object.entries(v.alternates[slot] ?? {}).map(([n, a]) => `${n} (\`${a.inst}\`, ${a.gainDb} dB)`).join(", ") || "-"} |`);
+ o.push("", `## \`${v.id}\`: ${v.name}`, "", `${v.atmosphere}. Tempo ${v.tempo.join("-")} bpm, meters ${v.meters.join(", ")}, swing ${v.swing.join("-")}.`, "", "| Slot | Voice | Stem target dB | Alternates (name, voice) |", "|---|---|---|---|");
+ const alts = (slot) => Object.entries(v.alternates[slot] ?? {}).map(([n, a]) => `${n} (\`${a.inst}\`)`).join(", ") || "-", tg = (slot) => (v.stemTargets[slot] === undefined ? "-" : +(v.stemTargets[slot] + (M.VOCAB_TARGET_FIX[v.id]?.[slot] ?? 0)).toFixed(1));
+ for (const [slot, x] of Object.entries(v.palette)) o.push(`| ${slot} | \`${x.inst}\` | ${tg(slot)} | ${alts(slot)} |`);
+ for (const slot of Object.keys(v.alternates)) if (!v.palette[slot]) o.push(`| ${slot} | (none) | ${tg(slot)} | ${alts(slot)} |`);
o.push("", `Stem targets: ${v.calibrated ? "calibrated on a listened score." : "starting numbers from a neutral test signal (advisory until a human listens)."}`, "");
o.push(`- **Harmony language.** Modes: ${v.harmony.modes.join(", ")}. Qualities: ${v.harmony.qualities}. Tendencies: ${v.harmony.tendencies}. Harmonic rhythm: ${v.harmony.rhythm}. Voicing: ${v.harmony.voicing}. Tension and release: ${v.harmony.tension}.`);
o.push(`- **Melody.** Range ${v.melody.range}. Contour: ${v.melody.contour}. Density: ${v.melody.density}. Motif: ${v.melody.motif}.`);
@@ -278,14 +402,15 @@ const vocabMarkdown = (M) => {
};
/** Key/mode problems, composer warnings, the master (did the peak cap stop it short?), and the guards. Returns pass. */
-const report = (M, r, piece) => {
+const report = (M, r, piece, cache, bands) => {
let ok = true; const probs = M.planProblems(piece), warn = piece.warnings ?? [];
for (const p of probs) console.log(`PROBLEM ${p}`); ok = ok && !probs.length;
for (const w of warn) console.log(`WARNING ${w}`);
const lu = M.loudness([r.L, r.R], SR).integrated, tp = M.truePeak([r.L, r.R]).dbtp, target = r.masterMode === "dense" ? -14 : r.masterMode === "gentle" ? -16 : NaN;
console.log(`master ${r.masterMode}: ${fmt(lu)} LUFS (target ${fmt(target)}), true peak ${fmt(tp, 2)} dBTP`);
- if (lu < target - 0.5) console.log(`NOTE the master stopped ${fmt(target - lu)} dB short of its target: the true-peak ceiling (-1 dBTP) capped the gain. Peaks are a composing problem: stagger the bass under the loudest downbeat, roll the big chord, don't double the climax note, soften the one loudest hit.`);
- const g = M.guardReport(r, SR, r.L.length / SR);
+ if (lu < target - 0.5) { const pk = M.peakReport(r, SR), who = pk.parts.map((x, i) => `${x.id}${x.notes.length ? ` ${x.notes.join(" ")}` : ""} (${i ? `${fmt(x.db - pk.parts[0].db)} dB` : "loudest"})`).join(", ");
+ console.log(`NOTE the master stopped ${fmt(target - lu)} dB short of its target: the true-peak ceiling (-1 dBTP) capped the gain. The peak is at bar ${pk.bar} beat ${pk.beat} (${fmt(pk.sec, 2)} s)${who ? `, where ${who} pile up` : ""}. Peaks are a composing problem: stagger the bass under that downbeat, roll the big chord, don't double the climax note, soften the one loudest hit.`); }
+ const g = M.guardReport(r, SR, r.L.length / SR, { cache, bands });
console.log(`guards ghost ${g.ghost.pass ? "PASS" : "FAIL"} (${g.ghost.failures}/${g.ghost.windows} windows formless) | reverb ${g.reverb.pass ? "PASS" : "FAIL"} (worst tail ${fmt(g.reverb.worstDb)} dB vs dry) | masking ${g.masking ? `${g.masking.pass ? "PASS" : "FAIL"} (melody clear in ${Math.round(g.masking.shareOfBarsClear * 100)} % of bars, worst ${fmt(g.masking.worstMarginDb)} dB)` : "n/a (no melody)"}`);
if (g.masking && !g.masking.pass) console.log(`FIX masking: the melody must beat every other part in 500 Hz-4 kHz by 3 dB in 80 % of its bars. Guards win over stem targets: raise the lead (levels.lead, up to +${M.LEAD_HEADROOM_DB} dB over its target is allowed), thin or lower what sits in its register, or move it.`);
if (!g.ghost.pass) console.log("FIX ghost: sustained sound with too few onsets and no cadence. Add a rhythmic layer or motif, shorten tails, cadence.");
@@ -293,17 +418,19 @@ const report = (M, r, piece) => {
return ok && g.ghost.pass && g.reverb.pass && (!g.masking || g.masking.pass);
};
const printNovelty = (M, name, v, what) => {
- console.log(`novelty: ${name} vs ${v.rows.length} ${what} (fail above ${v.threshold}, or on any reused 6-note melody fragment)`);
- for (const r of v.rows.slice(0, 5)) console.log(` ${r.name.padEnd(22)} ${r.score.toFixed(3)} ${r.reusedFragments ? `REUSED ${r.reusedFragments} fragment(s) ` : ""}${Object.entries(r.by).map(([k, x]) => `${k} ${x}`).join(" ")}`);
- console.log(v.pass ? "novelty PASS" : `novelty FAIL: too close to ${v.worst.name}. Change what the numbers point at (the lead's rhythm, the contour, the groove, the chord colours, the form), not just the key.`);
+ console.log(`novelty: ${name} vs ${v.rows.length} ${what} (fail above ${v.threshold}, on any reused 6-note melody fragment, or on an 8-note melody shape quoted in any key, meter or rhythm)`);
+ const shown = [...v.rows.slice(0, 5), ...v.rows.slice(5).filter((r) => r.reusedFragments || r.quotedShapes)];
+ for (const r of shown) console.log(` ${r.name.padEnd(22)} ${r.score.toFixed(3)} ${r.reusedFragments ? `REUSED ${r.reusedFragments} fragment(s) ` : ""}${r.quotedShapes ? `QUOTED ${r.quotedShapes} melody shape(s) ` : ""}${Object.entries(r.by).map(([k, x]) => `${k} ${x}`).join(" ")}`);
+ const q = v.rows.find((r) => r.quotedShapes || r.reusedFragments);
+ console.log(v.pass ? "novelty PASS" : q && q.score <= v.threshold ? `novelty FAIL: the melody quotes ${q.name} (the same intervals in a row, whatever the key, meter or rhythm). Write your own line.` : `novelty FAIL: too close to ${v.worst.name}. Change what the numbers point at (the lead's rhythm, the contour, the groove, the chord colours, the form), not just the key.`);
console.log(" (idioms are fine: a ii-V-I, a plagal cadence, a two-chord vamp are vocabulary. What fails is the same music: a multi-bar progression WITH its rhythm, groove, contour and form, or a quoted melody.)");
return v.pass;
};
/** 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 });
+const printStems = (M, piece, tempo, seconds, cache, measured) => {
+ const b = measured ?? M.measureStems(piece, STEM_SR, { tempo, seconds, cache });
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)");
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/README.md b/plugins/anidoodle/skills/anidoodle/references/music/README.md
index 0445045..fac91ff 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/README.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/README.md
@@ -127,6 +127,14 @@ upbeat leads into it.
A hand-written piece with a short form, repeatable sections and optional sections can fit anything
from a quarter of its length to many times it, and it still ends on its cadence.
+A form that already fits keeps its tempo: when the last note plus the tail lands within max(0.5 s,
+one beat) of the length, `fitScore` changes nothing and the tail takes up the difference (the final
+ritard alone would otherwise nudge the tempo). **Music that must hit exact picture moments** (a drop
+on a cut, a sting on a reveal) is composed to the length and rendered without `--fit`, or uses the
+beat-grid mode the launch films use (`gridScore` in `launchTemplate.ts`), where the score plays at
+the film's bpm exactly and every cut sits on a downbeat. A fit that changes the tempo moves every
+hit with it.
+
## Styles (21) and moods (21)
Both are rows of numbers in `tables.ts`. The vocabularies are in `vocab.ts` and `vocabMore.ts`, and
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/compose.md b/plugins/anidoodle/skills/anidoodle/references/music/compose.md
index c3c4656..f774174 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/compose.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/compose.md
@@ -19,7 +19,8 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
> **Never reuse shipped material.** The demos (`node tools/music.mjs list`) and our own film scores
> are listening references and the novelty corpus. They are never a film's score or a template. Don't
> copy them, transpose them or re-rhythm them. `node tools/music.mjs novelty` fails a score that
-> sounds like any shipped piece, or that quotes a 6-note fragment of one (transposed or not).
+> sounds like any shipped piece, or that quotes one: a 6-note fragment (transposed or not), or an
+> 8-note melody shape in any key, meter or rhythm.
>
> **Idioms are fine.** A ii-V-I, a plagal amen, a two-chord vamp, a I-bVII-IV are vocabulary. The
> style pages name them so you can use them. What is not fine is reusing the same music: a
@@ -101,7 +102,7 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
bars yourself as notation, one or more bars per lane: `kick`, `snare`, `ghost`, `hat`, `perc`.
Use a second groove for contrast (`half`, `build`). Keep the kick and backbeat stable, and syncopate on
top of them ([theory/rhythm.md](theory/rhythm.md)).
-7. **Write the form.** Sections are `{ kind, bars, harmony, lead, counter, arp, groove, bass,
+7. **Write the form.** Sections are `{ kind, bars, harmony, lead, counter, arp, comp, groove, bass,
chordVel, energy, repeat, stretch }`.
- The **kind** sets which layers may sound: intro, verse, groove, hook, build, half, breakdown,
drop, bridge, swell, breath, outro. See the arrangement grammar in vocabularies.md.
@@ -110,6 +111,12 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
seconds, and at 30 fps a beat is `1800 / bpm` frames.
- Mark one section `stretch: true`: a film fit repeats or drops it to reach the exact length and
still end on your outro.
+ - **Music that must hit exact picture moments** (a drop on the reveal at 16.0 s): compose it to
+ the length (bars x beats x 60 / bpm) and render without `--fit`, or use the beat-grid mode the
+ launch films use (`gridScore` in `launchTemplate.ts`: the score plays at the film's bpm exactly
+ and the cuts sit on its downbeats). `--fit` keeps your tempo when the form already ends within
+ max(0.5 s, one beat) of the length, and the tail takes up the difference. Past that it changes
+ the tempo, and every hit moves with it.
- Song and cue forms, builds, and orchestration slots: [theory/form.md](theory/form.md).
8. **Revise with craft, before you render.** `craft` reads the notes in milliseconds:
```
@@ -122,7 +129,9 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
finding is one you chose on purpose (an open ending for suspense, parallel fifths in rock). Say
which ones in your note to the person.
- Compare the printed tension curve with your sketch from step 3. If the peak is not where you
- planned it, the arrangement is wrong, not the sketch.
+ planned it, the arrangement is wrong, not the sketch. The line under the curve says what drives
+ each section (loudness, density, register, harmony): loudness and density weigh most, so a
+ home-chord tutti or a drop is the peak ([theory/harmony.md](theory/harmony.md), section 8).
| `craft` says | Usual fix |
|---|---|
@@ -134,7 +143,7 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
| close intervals below their low limit | spread the voicing: 1-5-3', or lift the upper note an octave |
| melody under the chords | voice the chords lower, or the melody higher |
| no syncopation (groove idiom) | anticipate a bass or melody note by an eighth |
- | flat tension curve / no release | change layers, register and harmony by section; release after the peak |
+ | flat tension curve / no release | change layers, loudness (`energy`), register and harmony by section; release after the peak (a loop, ambient or calm piece may stay level: a note, not a warning) |
| mood cues (tempo, mode, register, density) | move the cue toward the mood, or declare the mood you wrote |
9. **Check, render, listen:**
```
@@ -153,21 +162,44 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
- novelty.
It exits non-zero on any failure. `render` prints the same report (stems with `--stems`), except
- novelty.
+ novelty. Both synthesize each voice once, on all but one of your cores, and render the guards and
+ the stems in parallel with the mix: the audio is bit-identical to a serial render (`render
+ --verify` renders again serially and compares; `ANIDOODLE_THREADS=1` turns the pool off).
- **Stems:** fix any part flagged more than 3 dB off with `levels`. `levels` is a **dB offset** per
slot (+2 = two dB louder), added on top of the calibrated gain, the trims and the mood controls'
- shifts. LUFS alone once hid a sub 7-10 dB too hot.
+ shifts, on the same scale as your own voice's `gainDb`. LUFS alone once hid a sub 7-10 dB too hot.
- **When the guards and the stems disagree, the guards win.** If masking fails (the melody isn't
heard), raise the lead. The stem meter lets the lead sit up to +3 dB above its tolerance for
this. You can also lower or thin what sits in the melody's register. Mood controls shift the
stem targets with the sound (for example, brightness lifts the hats and their target); the
printed targets already include that.
- **Master short of target:** a gentle master (-16 LUFS) never compresses. If one peak blocks the
- gain, the whole piece stays quieter, and `check` says by how much. Fix it in the notes: stagger
- the bass under the loudest downbeat, roll the big chord, don't double the climax note.
- - **Novelty:** if it fails, change what the numbers point at. The per-feature scores name it:
- the lead's rhythm, the contour, the groove, the chord colours, the form. Changing the key fixes
- nothing.
+ gain, the whole piece stays quieter, and `check` says by how much, where the peak is (bar, beat
+ and seconds) and which parts pile up there, loudest first, with the notes they are playing.
+ Fix it in the notes at that spot: stagger the bass under that downbeat, roll the big chord, don't
+ double the climax note.
+ - **Novelty:** if it fails, change what the numbers point at. Changing the key fixes nothing.
+ Each feature is a bag of n-grams compared by cosine (0 = nothing shared, 1 = the same); the
+ score is their weighted mean, and it fails above 0.5:
+
+ | Feature | Weight | What it counts |
+ |---|---|---|
+ | `melodyRhythm` | 0.20 | the lead's onset positions in each bar, and its inter-onset-interval trigrams |
+ | `melodyContour` | 0.15 | the lead's up / down / same 4-grams |
+ | `melodyIntervals` | 0.10 | the lead's interval trigrams, in semitones (transposition-free) |
+ | `lineRhythm` | 0.15 | the counter line's rhythm plus the bass's rhythm (bar positions and inter-onset trigrams of each) |
+ | `drums` | 0.15 | each drum part's hit positions per bar |
+ | `chords` | 0.10 | chord-function trigrams: each root against the key, with its quality |
+ | `qualities` | 0.07 | chord-quality trigrams (maj7, min, dom, sus ...) |
+ | `form` | 0.08 | the order of section kinds, in pairs |
+
+ The lead is the top note of each onset of the melody part. Bar positions depend on the meter;
+ the inter-onset trigrams, the contour, the intervals and both quote gates do not. Two gates fail
+ outright whatever the score: a **6-note fragment** of a shipped melody (its intervals and
+ durations, in any key), and an **8-note melody shape** (its intervals alone, in any key, meter
+ or rhythm: a quote re-barred into 5/4 or stretched is still the tune). Only distinctive shapes
+ count (three or more different intervals, a leap of a third or more, at most three repeated
+ notes), so a scale run is never a quote.
- **Listen:** the person hears it before it is used. Meters prove you aren't obviously wrong.
Only an ear says right. For a **loop**, deliver a `.wav`: mp3 adds encoder padding, so it clicks
or gaps at the loop point.
@@ -191,6 +223,7 @@ export const score = (): Material => ({
{ kind: "intro", bars: <n>, harmony: ["<chord>", /* per bar, cycled */], chordVel: <0..1> },
{ kind: "hook", bars: <n>, harmony: [/* ... */], lead: ["<motif>", "<motif variant>", "r:<beats>"], stretch: true, energy: <0..1> },
{ kind: "groove", bars: <n>, harmony: [/* ... */], lead: ["<2-bar motif>"], loopLines: true },
+ { kind: "verse", bars: <n>, harmony: ["<chord>", "~"], comp: ["x:1 r:.5 x:.5 r:2"] }, // held over the bar line; a comped rhythm
{ kind: "bridge", bars: <n>, key: "<new tonic>", mode: "<mode>", harmony: [/* in the new key */], lead: [/* ... */] },
/* ... */
{ kind: "outro", bars: <n>, harmony: ["<home chord>"], lead: ["<the motif's last word>"] },
@@ -202,10 +235,46 @@ A film plays it with `filmScore(score(), fps, frames)` from `canvas-core/score.t
form to the exact length. `score.ts` is an empty skeleton to copy.
- **Voices:** `voices: { lead: "<alternate name>" }` swaps a slot for one of the style's
- alternates. Or give your own `{ inst, role, gainDb, opts }` (instruments: README table).
+ alternates. Or give your own `{ inst, role, opts }` (instruments: README table), with the slot's
+ role: `chords` and `arp` are `"accomp"`, `lead` is `"melody"`, `counter` is `"color"`, `bass` is
+ `"bass"`, drum lanes are `"drum"`. **Levels are one scale.** The palette voice, an alternate and
+ your own voice all sit at the slot's stem target (the column in
+ [styles/vocabularies.md](styles/vocabularies.md), fix included): alternates carry a measured trim,
+ and your own voice is placed from its instrument's measured level in the register your notes
+ play in. So leave your voice's `gainDb` out (0 = at the target) and set it, like `levels`, only
+ as an offset: `gainDb: 2` is two dB over. Then read `check`'s stems and adjust by the dB it
+ prints. Options (`attack`, `bright`, `drive`) move the level a little; a piano far up its range
+ is quiet by nature.
- **Loops:** `loop: true`, and the form length is the loop. `render` makes it seamless.
-- **Split bars:** `harmony: ["<chord> <chord>"]` splits a bar in two. Give that section a `bass`
- override for it.
+- **Split bars:** `harmony: ["<chord> <chord>"]` splits a bar where the meter divides, not at its
+ arithmetic middle. Give that section a `bass` override for it.
+
+ | Meter | 2 chords | 3 chords |
+ |---|---|---|
+ | 2/4 | 1 + 1 | even |
+ | 3/4 | 2 + 1 (the change on beat 3) | 1 + 1 + 1 |
+ | 4/4 | 2 + 2 | 2 + 1 + 1 |
+ | 5/4 | 3 + 2 | 2 + 1 + 2 |
+ | 6/8 | 1 + 1 (3 + 3 eighths) | even |
+ | 7/8 | 2 + 1.5 (4 + 3 eighths) | 1 + 1 + 1.5 (2 + 2 + 3) |
+ | 9/8 | 2 + 1 | 1 + 1 + 1 |
+ | 12/8 | 2 + 2 | 2 + 1 + 1 |
+
+ Beats are the meter's beats (in 6/8, 9/8 and 12/8 a dotted quarter). To feel the bar another
+ way, set the piece's `grouping` (for example `grouping: [2, 3]` for a 5/4 felt 2 + 3): a split
+ into as many chords as it has groups follows it. Or give each chord its beats: `"Dm9:1 G13:2"`.
+- **Held chords:** `"~"` holds the chord before it over the bar line, with no restrike, so a pad
+ never dips at the bar line: `harmony: ["Cmaj9", "~", "Am9", "~"]` is two chords of two bars each.
+ `"~ G13"` holds into the bar, then changes. The bass keeps its own line under a held chord (the
+ chord's bass line plays again). To tie the bass too, write that bar of the section's `bass` as `"~"`.
+- **Comping:** a section's `comp` gives the chord part a rhythm, one bar per item, cycled over the
+ section. `x:DUR` strikes the chord sounding at that point, `r:DUR` rests, `x:[email protected]` accents, and
+ a bar may start with `~:DUR` to hold the last strike over the bar line (a pushed chord):
+ `comp: ["x:1 r:.5 x:.5 r:1 x:1", "r:3.5 x:.5", "~:1 r:1 x:2"]`. A comp bar must add up to the bar.
+ Without `comp`, each chord sounds for its whole span.
+- **A silent chord:** `voicing: "r"` makes the chord part rest while the chord still names the
+ harmony: the key check, `craft`, novelty and the bass all read it. Use it for a bar that the bass
+ or an arp states alone, or a stop-time break.
- **Lines play once.** `lead`, `counter` and `arp` start at the section's first bar and play ONCE,
even though `harmony` cycles. A shorter line leaves rests, and `check` warns. Set
`loopLines: true` to repeat the line until the section is full. `repeat: n` replays the whole
@@ -275,6 +344,6 @@ mid-bar writes its rest, `C2:3 r:1`, never a silent gap):
| masking guard | `check`, `render` | the melody doesn't clear the other parts in 500 Hz-4 kHz |
| stems | `check`, `render --stems`, `stems` | a part is more than 3 dB off target (lead: up to +6 dB allowed); advisory for uncalibrated styles |
| craft | `craft`, `check` | (advisory scores and fixes) melody, harmony, rhythm, tension, mood fit; fails only on a note an acoustic instrument cannot play |
-| novelty | `check`, `novelty` | similarity above 0.5 to a shipped piece (or to each other), or a reused 6-note melody fragment |
+| novelty | `check`, `novelty` | similarity above 0.5 to a shipped piece (or to each other), a reused 6-note melody fragment, or an 8-note melody shape in any key, meter or rhythm |
`tools/music-unit.mjs` keeps the engine honest: determinism, no defaults, every vocabulary renders.
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md b/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md
index 2b02602..f918db4 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md
@@ -4,6 +4,8 @@
> A style is a vocabulary: sound, grooves, harmony language, melody rules, arrangement grammar. It never
> contains notes. You compose the notes ([../compose.md](../compose.md)).
+**Levels are one scale.** Every voice in a slot, the palette's, an alternate or your own, is calibrated to the slot's stem target (the "Stem target dB" column: the level the stem meter reads when the part plays). Everything you set is a dB offset from there: `levels: { lead: 2 }` is two dB over the target, and your own voice's `gainDb` works the same way (`voices: { counter: { inst: "strings", role: "color" } }` sits at the counter target; `gainDb: -3` sits 3 dB under it). Engine gains (`Voice.gainDb` inside vocab.ts) are internal and never on this scale.
+
| Style | Atmosphere | Tempo, meters | Moods | Grooves |
|---|---|---|---|---|
| `lofiElectronic` | warm, chill but upbeat, clean: a breathing pad, a plucked hook through ping-pong echoes, a round sub, a bouncy kit | 80-100 bpm; 4/4 | calm, joy, hopeful, nostalgic, wistful, curious | bounce, halfTime, broken, skip, pulse, build |
@@ -69,18 +71,18 @@ A kind decides which layers may sound; your lines sound only where you write the
warm, chill but upbeat, clean: a breathing pad, a plucked hook through ping-pong echoes, a round sub, a bouncy kit. Tempo 80-100 bpm, meters 4/4, swing 0.52-0.56.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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` | 19.5 | -24.5 | - |
-| arp | `softPluck` | 4 | - | - |
-| perc | `hat` | 14 | - | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `warmPad` | -22 | strings (`strings`), piano (`piano`) |
+| lead | `softPluck` | -15.5 | bell (`fmBell`), mallet (`marimba`), guitar (`guitar`) |
+| counter | `softPluck` | -20 | - |
+| bass | `sub` | -18.5 | warm (`bass`) |
+| kick | `kick` | -14.5 | - |
+| snare | `snare` | -19 | - |
+| ghost | `snare` | - | - |
+| hat | `hat` | -24.5 | - |
+| arp | `softPluck` | - | - |
+| perc | `hat` | - | - |
Stem targets: calibrated on a listened score.
@@ -93,18 +95,18 @@ Stem targets: calibrated on a listened score.
forward, bright, confident: four-on-the-floor, a pumping supersaw bed, a gritty bass line, a plucked arp. Tempo 110-140 bpm, meters 4/4, swing 0.5-0.52.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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.8 | -20.5 | - |
-| perc | `hat` | 15.5 | -26 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `strings` | -23 | - |
+| lead | `strings` | -16 | pluck (`softPluck`) |
+| counter | `fmBell` | -19.5 | - |
+| bass | `bass` | -16 | sub (`sub`) |
+| kick | `kick` | -12.5 | - |
+| snare | `snare` | -17 | - |
+| ghost | `snare` | - | - |
+| hat | `hat` | -26 | - |
+| arp | `softPluck` | -20.5 | - |
+| perc | `hat` | -26 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -117,18 +119,18 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
wide and emotional: string swells, low ostinatos for tension, harp and bell colour, a low boom on the arrival. Tempo 60-120 bpm, meters 4/4, 3/4, 6/8, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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 | - |
-| perc | `fmBell` | -8 | - | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `strings` | -18.5 | - |
+| lead | `strings` | -17 | piano (`piano`), bell (`fmBell`), celesta (`celesta`) |
+| counter | `harp` | -16.4 | piano (`piano`) |
+| bass | `strings` | -19.5 | - |
+| arp | `strings` | -21.5 | - |
+| kick | `kick` | -16.5 | - |
+| snare | `snare` | -24 | - |
+| ghost | `snare` | - | - |
+| hat | `hat` | -32 | - |
+| perc | `fmBell` | - | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -141,17 +143,17 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
floating, spacious, luminous: long pads, bells and plucks with space around them, a soft heartbeat at most. Tempo 50-80 bpm, meters 4/4, 3/4, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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` | -2.4 | -23.5 | - |
-| kick | `kick` | -7 | -20.5 | - |
-| ghost | `snare` | -6 | - | - |
-| hat | `hat` | 6 | -32 | - |
-| perc | `hat` | 4 | - | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `warmPad` | -20 | - |
+| lead | `fmBell` | -17.5 | pluck (`softPluck`), vibes (`vibes`) |
+| counter | `softPluck` | -26.5 | - |
+| bass | `sub` | -22 | - |
+| arp | `celesta` | -23.5 | - |
+| kick | `kick` | -20.5 | - |
+| ghost | `snare` | - | - |
+| hat | `hat` | -32 | - |
+| perc | `hat` | - | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -164,18 +166,18 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
intimate and warm: fingerpicked guitar, soft piano, a harp or celesta line, brushes. Tempo 60-110 bpm, meters 6/8, 3/4, 4/4, swing 0.5-0.54.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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` | 2.3 | -24.5 | - |
-| hat | `hat` | 2 | -30 | - |
-| perc | `hat` | 19.4 | -30 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `piano` | -26 | strings (`strings`) |
+| arp | `guitar` | -20.5 | - |
+| lead | `harp` | -13 | piano (`piano`), guitar (`guitar`), strings (`strings`) |
+| counter | `celesta` | -19.5 | - |
+| bass | `bass` | -21 | - |
+| kick | `kick` | -20.5 | - |
+| snare | `snare` | -26 | - |
+| ghost | `snare` | -24.5 | - |
+| hat | `hat` | -30 | - |
+| perc | `hat` | -30 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -188,18 +190,18 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
light, cheeky, springy: marimba and pizzicato-like plucks, a bouncy bass, a skipping kit. Tempo 100-150 bpm, meters 4/4, 6/8, swing 0.5-0.6.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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.3 | -24 | - |
-| perc | `hat` | 21.5 | -29.5 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| lead | `marimba` | -13 | chip (`pulse`), pluck (`softPluck`), bell (`fmBell`) |
+| chords | `vibes` | -21 | - |
+| arp | `harp` | -20 | - |
+| counter | `celesta` | -18.5 | - |
+| bass | `bass` | -18 | tuba (`sub`) |
+| kick | `kick` | -15.5 | - |
+| snare | `snare` | -20 | - |
+| ghost | `snare` | -26 | - |
+| hat | `hat` | -24 | - |
+| perc | `hat` | -29.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -212,13 +214,13 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
small, bright, clockwork, innocent; plucked and never sustained. Tempo 100-132 bpm, meters 12/8, 3/4, 6/8, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| lead | `musicBox` | -13.5 | celesta (`celesta`), bell (`fmBell`) |
+| arp | `musicBox` | -25 | - |
+| bass | `musicBox` | -26 | - |
+| counter | `bell` | -19.5 | - |
+| chords | `celesta` | -26.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -231,12 +233,12 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
intimate, expressive, late-night: one piano, rubato, pedal. Tempo 50-76 bpm, meters 3/4, 6/8, 4/4, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| lead | `piano` | 14.1 | -15 | - |
-| chords | `piano` | 17.7 | -23.5 | - |
-| bass | `piano` | 6.5 | -24.5 | - |
-| counter | `strings` | 4.6 | -30.5 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| lead | `piano` | -15 | - |
+| chords | `piano` | -23.5 | - |
+| bass | `piano` | -24.5 | - |
+| counter | `strings` | -30.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -249,16 +251,16 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
hypnotic, curious, clean: interlocking ostinatos that change slowly. Tempo 96-144 bpm, meters 4/4, 12/8, 5/4, 7/8, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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 | - | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| arp | `marimba` | -19 | piano (`piano`), pluck (`softPluck`) |
+| lead | `marimba` | -14 | - |
+| bass | `marimba` | -24 | - |
+| counter | `vibes` | -21 | - |
+| chords | `piano` | -30.1 | - |
+| kick | `kick` | - | - |
+| ghost | `snare` | - | - |
+| perc | `hat` | - | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -271,17 +273,17 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
loose, warm, clever: swing ride, walking bass, comping piano. Tempo 80-200 bpm, meters 4/4, 3/4, swing 0.6-0.67.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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 | -24.5 | - |
-| hat | `hat` | 26.2 | -23 | - |
-| perc | `hat` | 15.5 | -30 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `piano` | -25.5 | - |
+| lead | `vibes` | -13 | piano (`piano`), clarinet (`woodwind`), flute (`woodwind`), brass (`brass`) |
+| bass | `bass` | -18 | - |
+| counter | `woodwind` | -18.5 | - |
+| kick | `kick` | -24.5 | - |
+| snare | `snare` | -26 | - |
+| ghost | `snare` | -24.5 | - |
+| hat | `hat` | -23 | - |
+| perc | `hat` | -30 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -294,13 +296,13 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
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` | 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 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| lead | `celesta` | -15 | musicBox (`musicBox`), piano (`piano`), flute (`woodwind`) |
+| arp | `harp` | -23.5 | - |
+| bass | `harp` | -27 | - |
+| counter | `musicBox` | -21.7 | - |
+| chords | `strings` | -28.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -313,14 +315,14 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
8-bit, bright, game-like: two pulses, a triangle, noise drums. Tempo 110-170 bpm, meters 4/4, 6/8, swing 0.5-0.56.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| lead | `pulse` | 7.4 | -16 | square (`pulse`, -2 dB) |
-| 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 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| lead | `pulse` | -16 | square (`pulse`) |
+| arp | `pulse` | -20 | - |
+| bass | `triangle` | -18 | - |
+| kick | `noiseDrum` | -17.5 | - |
+| snare | `noiseDrum` | -20.5 | - |
+| hat | `noiseDrum` | -28 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -333,17 +335,17 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
hazy, nostalgic, crackly: FM e-piano, vinyl, a lazy swung beat (the dusty cousin of lo-fi electronic). Tempo 68-90 bpm, meters 4/4, swing 0.55-0.62.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `ePiano` | -19.5 | - |
+| lead | `ePiano` | -16.5 | guitar (`guitar`), flute (`woodwind`) |
+| bass | `bass` | -19 | - |
+| counter | `fmBell` | -20.9 | - |
+| kick | `kick` | -17.5 | - |
+| snare | `snare` | -21 | - |
+| ghost | `snare` | -22 | - |
+| hat | `hat` | -32.8 | - |
+| perc | `hat` | -29 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -356,17 +358,17 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
big and heroic: brass theme, string ostinato engine, choir, timpani. Tempo 70-140 bpm, meters 4/4, 3/4, 6/8, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| lead | `brass` | -13 | strings (`strings`), horn (`brass`), flute (`woodwind`) |
+| chords | `strings` | -19.5 | - |
+| arp | `strings` | -21 | - |
+| bass | `strings` | -20 | - |
+| counter | `choir` | -23 | flute (`woodwind`), harp (`harp`) |
+| perc | `timpani` | -17.5 | - |
+| kick | `kick` | -17.5 | - |
+| snare | `snare` | -23 | - |
+| hat | `hat` | -32 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -379,17 +381,17 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
unsettling, cold, withheld: low drones, heartbeat pulse, high bowed harmonics, stingers. Tempo 50-110 bpm, meters 4/4, 5/4, 3/4, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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` | 6.2 | -18.5 | - |
-| hat | `hat` | 0 | -32 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `strings` | -21.5 | - |
+| bass | `sub` | -20 | - |
+| lead | `bowedSolo` | -19.5 | choir (`choir`), cello (`bowedSolo`) |
+| counter | `celesta` | -19 | choir (`choir`), bell (`fmBell`) |
+| arp | `strings` | -23 | - |
+| kick | `kick` | -17.5 | - |
+| ghost | `snare` | -27 | - |
+| perc | `timpani` | -18.5 | - |
+| hat | `hat` | -32 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -402,17 +404,17 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
live-band energy: driven guitars, bass locked to the kick, a tight kit, maybe organ. Tempo 90-160 bpm, meters 4/4, 6/8, swing 0.5-0.52.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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.4 | -23.5 | - |
-| perc | `hat` | 15.7 | -25.5 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `guitar` | -15.5 | strings (`strings`), organ (`organ`), piano (`piano`) |
+| lead | `leadSynth` | -16 | guitar (`guitar`) |
+| bass | `bass` | -17 | - |
+| counter | `organ` | -27.1 | - |
+| kick | `kick` | -13.5 | - |
+| snare | `snare` | -16.5 | - |
+| ghost | `snare` | -26 | - |
+| hat | `hat` | -23.5 | - |
+| perc | `hat` | -25.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -425,17 +427,17 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
head-nod or dark trap: heavy 808, crisp clap, rolling hats, a moody loop on top. Tempo 70-100 bpm, meters 4/4, swing 0.52-0.6.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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.2 | -23 | - |
-| perc | `hat` | 17.7 | -29.5 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| bass | `sub` | -15 | - |
+| chords | `piano` | -30.9 | pad (`warmPad`) |
+| lead | `softPluck` | -17.5 | bell (`fmBell`), flute (`woodwind`), choir (`choir`) |
+| counter | `strings` | -25.5 | - |
+| kick | `kick` | -13.5 | - |
+| snare | `snare` | -17 | - |
+| ghost | `snare` | -26 | - |
+| hat | `hat` | -23 | - |
+| perc | `hat` | -29.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -448,18 +450,18 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
euphoric, dancing, bright: four-on-the-floor, offbeat bass, stabs, a big pad. Tempo 118-128 bpm, meters 4/4, swing 0.5-0.54.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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` | 15.1 | -27 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `organ` | -20 | pad (`warmPad`), piano (`piano`) |
+| bass | `bass` | -16 | - |
+| lead | `softPluck` | -16.5 | synth (`leadSynth`) |
+| counter | `warmPad` | -23.5 | - |
+| arp | `softPluck` | -22 | - |
+| kick | `kick` | -12.5 | - |
+| snare | `snare` | -17 | - |
+| ghost | `snare` | -26 | - |
+| hat | `hat` | -26 | - |
+| perc | `hat` | -27 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -472,18 +474,18 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
neon-nostalgic, cinematic 80s: big gated snare, pulsing 8th bass, lush pads, a soaring lead. Tempo 80-118 bpm, meters 4/4, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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.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` | 13.5 | -29.5 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `strings` | -22 | pad (`warmPad`) |
+| bass | `bass` | -17 | - |
+| lead | `leadSynth` | -16 | brass (`brass`) |
+| arp | `softPluck` | -22 | - |
+| counter | `fmBell` | -20.5 | - |
+| kick | `kick` | -13.5 | - |
+| snare | `snare` | -16.5 | - |
+| ghost | `snare` | -26 | - |
+| hat | `hat` | -28 | - |
+| perc | `hat` | -29.5 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -496,17 +498,17 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
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 bpm, meters 7/8, 9/8, 12/8, 6/8, 4/4, 5/4, swing 0.5-0.56.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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 | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| lead | `woodwind` | -14.5 | pluck (`guitar`), marimba (`marimba`), reed (`woodwind`), bowed (`bowedSolo`) |
+| counter | `harp` | -18.2 | - |
+| arp | `guitar` | -20.5 | - |
+| chords | `warmPad` | -25.5 | - |
+| bass | `sub` | -22 | - |
+| kick | `timpani` | -17 | - |
+| ghost | `snare` | -20 | - |
+| perc | `hat` | -28 | - |
+| hat | `hat` | -30 | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
@@ -519,15 +521,15 @@ Stem targets: starting numbers from a neutral test signal (advisory until a huma
vast, human, reverent: voices in parts, organ, bells, a slow swell. Tempo 50-90 bpm, meters 4/4, 3/4, swing 0.5-0.5.
-| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |
-|---|---|---|---|---|
-| 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 | - | - |
+| Slot | Voice | Stem target dB | Alternates (name, voice) |
+|---|---|---|---|
+| chords | `choir` | -20 | organ (`organ`), strings (`strings`) |
+| lead | `choir` | -17 | bowed (`bowedSolo`), flute (`woodwind`) |
+| bass | `organ` | -23 | - |
+| counter | `fmBell` | -21.5 | - |
+| arp | `harp` | -23.5 | - |
+| perc | `timpani` | -20 | - |
+| kick | `timpani` | - | - |
Stem targets: starting numbers from a neutral test signal (advisory until a human listens).
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md
index 63e645a..e687239 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md
@@ -105,19 +105,29 @@ blur the metre (`craft`: "chord changes on beats").
## 8. Tension curve
-`craft` draws a per-bar tension curve. It blends:
+`craft` draws a per-bar tension curve. Felt tension follows intensity first and harmony second
+(Farbood 2012), so the blend is:
-- the chord's distance from home (Lerdahl 2001, simplified);
-- the sonority's dissonance (Huron 1994 interval-class ratings);
-- density;
-- the melody's register;
-- loudness.
+| Term | Weight | What it reads |
+|---|---|---|
+| loudness | 0.35 | every part sounding in the bar, velocity squared (section `energy` and `chordVel` included), weighted by its stem target; 1 at the piece's loudest bar, 0 at 12 dB under it |
+| density | 0.25 | onsets per beat, against the piece's busiest bar |
+| register | 0.15 | the melody's mean pitch within its range (the top voice where the melody rests) |
+| harmonic lean | 0.25 | the chord root's distance from home (Lerdahl 2001, simplified; 0.15) and the sonority's dissonance (Huron 1994 interval-class ratings; 0.10) |
+
+So a home-chord tutti climax or an EDM drop reads as the peak: its chord is at rest, but everything
+plays, loud and high. A dominant that leans quietly does not. `craft` prints each section's four
+terms under the curve, so you can see what drives it.
Plan the curve **before** the notes: rise, a dip just before the peak (a breath or breakdown), the
peak on the key picture moment, then release. It warns on a flat curve, on a first section that is the
-most intense, and on a last section with no release.
+most intense, and on a last section with no release. A loop, an ambient piece or a calm one stays
+level on purpose (a site loop is low arousal: [mood.md](mood.md)), so a flat curve there is a note,
+not a warning.
Sources: Aldwell & Schachter, *Harmony and Voice Leading* (2011); Kostka & Payne, *Tonal Harmony*
(8th ed., 2018); Piston, *Harmony* (1941/1987); Tymoczko, *A Geometry of Music* (2011); Levine, *The
Jazz Theory Book* (1995); Lehman, *Hollywood Harmony* (2018); Lerdahl, *Tonal Pitch Space* (2001);
-Huron, "Interval-class content of equally tempered pitch-class sets", *Music Perception* 11 (1994).
+Huron, "Interval-class content of equally tempered pitch-class sets", *Music Perception* 11 (1994);
+Farbood, "A parametric, temporal model of musical tension", *Music Perception* 29 (2012); Lerdahl &
+Krumhansl, "Modeling tonal tension", *Music Perception* 24 (2007).
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/mood.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/mood.md
index 3f8a14c..2bbf9d9 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/theory/mood.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/mood.md
@@ -69,7 +69,7 @@ because the family is the emotional cue and the exact mode is colour.
|---|---|---|---|
| Product launch film | 30-60 s | intro, build, drop on the reveal, button | one motif, the climax on the logo or claim, a clean ending |
| Explainer | 60-120 s | a steady groove bed, low melody density | leave the voice's band free (1-4 kHz): lead sparse and low-mid |
-| Site / app loop | 20-60 s | 4 or 8 bar loop, no cadence home at the end | low arousal, no sharp accents, seamless |
+| Site / app loop | 20-60 s | 4 or 8 bar loop, no cadence home at the end | low arousal, no sharp accents, seamless (`craft` does not ask a loop for a tension arc) |
| Game menu / trailer | 15-60 s | ostinato + motif, stingers on hits | heroic or playful, strong hook in 2 bars |
| Ad (15-30 s) | 15-30 s | hook in the first 2-4 s, button ending | high arousal, bright, the brand beat on the last downbeat |
| Meditation / sleep | 45 s+ | drone + sparse motif, slow harmonic rhythm | 50-70 bpm, legato, no percussion, open ending allowed |