Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.
TypeScript agent-skillsanimationcanvasclaude-codeclaude-pluginclaude-skillscodex-plugincreative-codecreative-codingcreative-toolsdeterministicgenerative-arthand-drawnillustrationlaunch-videomotion-designmotion-graphicspluginprocedural-generationskill
tools/music.mjs: --module scores (path.ts#export), vocab, novelty (fails on similarity or a reused fragment), calibrate; music-unit rewritten for the vocabulary design
Alex Greenshpun72cf792fd552
diff --git a/skills/anidoodle/engine/tools/music-unit.mjs b/skills/anidoodle/engine/tools/music-unit.mjsindex 9e88f65..26c627a 100644--- a/skills/anidoodle/engine/tools/music-unit.mjs+++ b/skills/anidoodle/engine/tools/music-unit.mjs@@ -1,9 +1,12 @@#!/usr/bin/env node-// Lo-fi electronic unit test: the style API, the approved launch score, the loop and the meters.+// Music unit test: styles are vocabularies, the composer writes the notes.// node tools/music-unit.mjs-// Asserts: launchLofi3 audio unchanged (md5), determinism (same md5 twice), no clipping (true peak-// <= -1 dBTP), loudness -14 LUFS +-1, stem balance within +-3 dB of target, the stem meter catches a-// sub 9 dB hot that LUFS alone passes, a seamless loop seam, and a film fit that ends on its phrase.+// Asserts: the approved launch score is bit-identical as composed material (md5); neutral mood is the+// calibrated palette exactly; missing material is an error, never a default; every groove family+// parses in every meter and varies with the seed; every style vocabulary composes, renders (true peak+// <= -1 dBTP, loudness at its master target) and meets its stem targets; the stem meter catches a sub+// 9 dB hot that LUFS alone passes; a seamless loop; a film fit that ends on its phrase; the score+// scaffold is empty; and the novelty gate hears the copy Alex heard (Daylight vs the launch score).import { strict as assert } from "node:assert";import { createHash } from "node:crypto";import { build } from "esbuild";@@ -16,61 +19,87 @@ const md5 = (r) => { const h = createHash("md5"); h.update(Buffer.from(r.L.buffeconst ok = []; const t0 = Date.now();const pass = (s) => { ok.push(s); console.log(` ok ${s}`); };-// 1. The approved launch score is bit-identical to the hand-written v6 it was refactored from.+// 1. The approved launch score, now composed material on the lo-fi electronic vocabulary: bit-identical.const LAUNCH3_MD5_48K = "d20789f2344e6fff0d2a380c7c7825d2";const launch = M.renderPiece(M.launchLofi3(), 48000);assert.equal(md5(launch), LAUNCH3_MD5_48K, "launchLofi3 audio changed");-pass(`launchLofi3 md5 ${LAUNCH3_MD5_48K} (48 kHz, ${launch.L.length} frames)`);+{ const tp = M.truePeak([launch.L, launch.R]).dbtp, lu = M.loudness([launch.L, launch.R], 48000).integrated; assert(tp <= -1 && Math.abs(lu + 14) <= 1);+ pass(`launchLofi3 md5 ${LAUNCH3_MD5_48K} (48 kHz), ${lu.toFixed(2)} LUFS, ${tp.toFixed(2)} dBTP`); }-// 2. Determinism + master: the example loop and arranged piece, the launch score.-const SR = 48000, loopA = M.renderLoop(M.lofiDaylightLoop(), SR), loopB = M.renderLoop(M.lofiDaylightLoop(), SR);-assert.equal(md5(loopA), md5(loopB), "loop render not deterministic");-pass(`lofiDaylightLoop deterministic, md5 ${md5(loopA)} twice`);-const arranged = M.renderPiece(M.lofiDaylight(), SR);-assert.equal(md5(arranged), md5(M.renderPiece(M.lofiDaylight(), SR)), "arranged render not deterministic");-pass(`lofiDaylight deterministic, md5 ${md5(arranged)} twice`);-for (const [name, r] of [["launchLofi3", launch], ["lofiDaylightLoop", loopA], ["lofiDaylight", arranged]]) {- const tp = M.truePeak([r.L, r.R]).dbtp, lu = M.loudness([r.L, r.R], SR).integrated;- assert(tp <= -1, `${name}: true peak ${tp.toFixed(2)} dBTP > -1`);- assert(Math.abs(lu + 14) <= 1, `${name}: ${lu.toFixed(2)} LUFS, want -14 +-1`);- pass(`${name}: ${lu.toFixed(2)} LUFS, true peak ${tp.toFixed(2)} dBTP`);-}+// 2. Mood controls: all at 0.5 = the calibrated palette exactly; moved, the sound changes.+const SR = 24000, launchMd5_24 = md5(M.renderPiece(M.launchLofi3(), SR));+assert.equal(md5(M.renderPiece(M.composePiece({ ...M.launchLofi3Material(), moodControls: { energy: 0.5, warmth: 0.5, brightness: 0.5, tension: 0.5, space: 0.5 } }), SR)), launchMd5_24, "neutral mood must be identity");+assert.notEqual(md5(M.renderPiece(M.composePiece({ ...M.launchLofi3Material(), moodControls: { warmth: 0.9, space: 0.8 } }), SR)), launchMd5_24);+pass("mood controls: 0.5 on all five = identical audio; warmth/space moved = different audio");++// 3. No defaults: missing material is an error that says what to compose.+const base = M.launchLofi3Material();+for (const [what, m] of [+ ["harmony", { ...base, sections: base.sections.map((s, i) => (i === 1 ? { ...s, harmony: [] } : s)) }],+ ["melody", { ...base, sections: base.sections.map((s) => ({ ...s, lead: undefined })) }],+ ["chord voicing", { ...base, chords: { Dm9: base.chords.Dm9 } }],+ ["groove", { ...base, grooves: {} }],+ ["form", { ...base, sections: [] }],+ ["seed/mood", { ...base, mood: undefined }],+]) assert.throws(() => M.composePiece(m), /compose/, `missing ${what} must throw`);+{ const sjs = (await build({ entryPoints: [join(import.meta.dirname, "../src/canvas-core/score.ts")], bundle: true, write: false, platform: "neutral", format: "esm", logLevel: "error" })).outputFiles[0].text;+ const S = await import("data:text/javascript;base64," + Buffer.from(sjs).toString("base64")); assert.throws(() => S.filmScore(S.scoreSkeleton(), 30, 300), /skeleton/); }+pass("missing harmony, melody, voicing, groove, form, mood: each throws; the score scaffold is empty and refuses to play");++// 4. Groove families: every family parses in every meter, deterministic, and the seed varies the bars.+{ const meters = ["2/4", "3/4", "4/4", "5/4", "6/8", "7/8", "9/8", "12/8"]; let n = 0;+ for (const family of Object.keys(M.GROOVE_FAMILIES)) for (const meter of meters) for (let b = 0; b < 4; b++) {+ const g = { family, density: 0.8, variation: 0.8, fill: true }, bar = M.grooveBar(g, meter, 7, b, b, 4), again = M.grooveBar(g, meter, 7, b, b, 4);+ assert.deepEqual(bar, again); for (const x of Object.values(bar)) if (x) { M.line(0, x, { role: "drum", bpb: M.beatsPerBar(meter) }); n++; }+ }+ const bars = (seed) => Array.from({ length: 8 }, (_, b) => JSON.stringify(M.grooveBar({ family: "bounce", density: 0.7, variation: 0.8 }, "4/4", seed, b, b, 8)));+ assert.notDeepEqual(bars(1), bars(2)); assert(new Set(bars(1)).size > 1);+ pass(`${Object.keys(M.GROOVE_FAMILIES).length} groove families x ${meters.length} meters: ${n} bars parse, deterministic, seed-varied`); }-// 3. Stem balance: every part within 3 dB of its target (24 kHz, as the targets were measured).-for (const name of ["launchLofi3", "lofiDaylightLoop", "lofiDaylight"]) {- const b = M.measureStems(M.PIECES[name](), 24000);- assert(b.pass, `${name}: stems off target: ${b.rows.filter((r) => !r.ok).map((r) => `${r.id} ${r.offDb.toFixed(1)}`).join(", ")}`);- const worst = b.rows.filter((r) => r.offDb !== null).reduce((a, r) => (Math.abs(r.offDb) > Math.abs(a.offDb) ? r : a));- pass(`${name}: stems within +-3 dB (worst ${worst.id} ${worst.offDb >= 0 ? "+" : ""}${worst.offDb.toFixed(1)} dB)`);+// 5. Every style vocabulary: a neutral test signal composes, renders, masters and meets its stem targets.+for (const v of Object.values(M.VOCAB)) {+ const p = M.composePiece(M.testMaterial(v, { bars: 4 })), r = M.renderPiece(p, SR), tp = M.truePeak([r.L, r.R]).dbtp, lu = M.loudness([r.L, r.R], SR).integrated;+ const target = M.STYLES[v.id].master === "dense" ? -14 : -16, b = M.measureStems(p, SR);+ assert(tp <= -1, `${v.id}: ${tp} dBTP`); assert(lu <= target + 1 && lu >= target - 6, `${v.id}: ${lu} LUFS vs ${target}`);+ if (!v.calibrated) assert(b.pass, `${v.id}: stems ${b.rows.filter((x) => !x.ok).map((x) => `${x.id} ${x.offDb.toFixed(1)}`).join(", ")}`);+ assert(!p.parts.some((x) => ["ePiano", "vinyl"].includes(x.inst)) || v.id === "lofi", `${v.id}: ePiano/vinyl only in the dusty lofi style`);}+pass(`${Object.keys(M.VOCAB).length} style vocabularies compose, render (true peak <= -1 dBTP), master; uncalibrated palettes meet their stem targets on the test signal`);-// 4. The lesson: a sub 9 dB hot still masters to -14 LUFS; only the stem meter sees it.-{ const hot = M.lofiElectronic({ ...M.lofiDaylightLoopSpec(), levels: { ...M.lofiDaylightLoopSpec().levels, sub: 3 } });- const r = M.renderLoop(hot, 24000), lu = M.loudness([r.L, r.R], 24000).integrated, b = M.measureStems(hot, 24000), sub = b.rows.find((x) => x.id === "sub");- assert(Math.abs(lu + 14) <= 1 && !b.pass && !sub.ok && sub.offDb > 7, "the stem meter must flag a hot sub that LUFS passes");- pass(`hot sub: mix ${lu.toFixed(1)} LUFS (passes), stem meter flags sub +${sub.offDb.toFixed(1)} dB`); }+{ const b = M.measureStems(M.launchLofi3(), SR); assert(b.pass); const w = b.rows.filter((x) => x.offDb !== null).reduce((a, x) => (Math.abs(x.offDb) > Math.abs(a.offDb) ? x : a));+ pass(`lofiElectronic (calibrated on the listened launch score): stems within +-3 dB, worst ${w.id} ${w.offDb.toFixed(1)} dB`); }-// 5. The loop seam: the jump from the last sample to the first is an ordinary step, not a click.-{ const n = loopA.L.length, steps = []; for (let i = 1; i < n; i += 3) steps.push(Math.abs(loopA.L[i] - loopA.L[i - 1])); steps.sort((a, b) => a - b);- const p999 = steps[Math.floor(steps.length * 0.999)], seam = Math.max(Math.abs(loopA.L[0] - loopA.L[n - 1]), Math.abs(loopA.R[0] - loopA.R[n - 1]));- assert.equal(n, Math.round(30 * SR), "96 bpm x 12 bars = 30 s exactly"); assert(seam <= p999, `seam step ${seam} > p99.9 ${p999}`);- pass(`loop seam step ${seam.toFixed(4)} <= p99.9 step ${p999.toFixed(4)}; length ${n / SR} s`); }+// 6. The lesson: a sub 9 dB hot still masters to -14 LUFS; only the stem meter sees it.+{ const hot = M.composePiece({ ...base, levels: { bass: 3 } }), r = M.renderPiece(hot, SR), lu = M.loudness([r.L, r.R], SR).integrated, b = M.measureStems(hot, SR), sub = b.rows.find((x) => x.id === "bass");+ assert(Math.abs(lu + 14) <= 1 && !b.pass && sub.offDb > 7, "the stem meter must flag a hot sub that LUFS passes");+ pass(`hot sub: mix ${lu.toFixed(1)} LUFS (passes), stem meter flags bass +${sub.offDb.toFixed(1)} dB`); }-// 6. Style API: landing, film fit ends on the phrase, no ePiano, bar-checked notation.-{ const p3 = M.launchLofi3(); assert.equal(p3.harmony[26].name, "Cmaj9", "bar 26 (the claim) must land on Cmaj9"); assert.equal(p3.plan.style, "lofiElectronic");- const d = M.lofiDaylight(), drop = d.arrangement.find((a) => a.kind === "drop"); assert.equal(d.harmony[drop.from].name, "Dmaj9", "the drop lands home");- pass("landing: launch bar 26 = Cmaj9, Daylight drop = Dmaj9"); }-for (const secs of [45, 60, 95]) {- const f = M.fitScore(M.lofiDaylight(), secs), perf = M.perform(f.piece, f.tempo, { expressive: true }), p = f.piece, lastBar = p.harmony[p.harmony.length - 1];- const leadNotes = p.parts.find((x) => x.id === "lead").notes, final = leadNotes[leadNotes.length - 1];- assert.equal(lastBar.name, "Dmaj9"); assert.equal(M.nameOf(final.p), "D5"); assert.equal(f.form, "full");- assert(Math.abs(perf.lastOnset - (secs - p.tail)) < 0.05, `fit ${secs}: last onset ${perf.lastOnset} vs ${secs - p.tail}`);- assert(f.tempo >= 96 * 0.9 && f.tempo <= 96 * 1.1, `fit ${secs}: tempo ${f.tempo}`);- pass(`fit ${secs} s: ${p.plan.sections[0].bars} bars at ${f.tempo.toFixed(1)} bpm, last note D5 on Dmaj9 at ${perf.lastOnset.toFixed(2)} s`);+// 7. A seamless loop (composer's material, loop: true): the seam is an ordinary sample step.+{ const lp = M.renderLoop(M.composePiece(M.testMaterial(M.VOCAB.lofiElectronic, { loop: true })), SR), n = lp.L.length, steps = [];+ for (let i = 1; i < n; i += 3) steps.push(Math.abs(lp.L[i] - lp.L[i - 1])); steps.sort((a, b) => a - b);+ const p999 = steps[Math.floor(steps.length * 0.999)], seam = Math.max(Math.abs(lp.L[0] - lp.L[n - 1]), Math.abs(lp.R[0] - lp.R[n - 1]));+ assert(seam <= p999, `seam ${seam} > ${p999}`); assert.equal(md5(lp), md5(M.renderLoop(M.composePiece(M.testMaterial(M.VOCAB.lofiElectronic, { loop: true })), SR)));+ pass(`loop: seam step ${seam.toFixed(4)} <= p99.9 ${p999.toFixed(4)}, deterministic`); }++// 8. Film fit: the composition is re-formed (stretch section repeated or dropped) and ends on its phrase.+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);+ 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.lofiDaylight(), 40)(16000); assert.equal(a[0].length, 40 * 16000); pass("filmAudio: exactly the film's length"); }-for (const name of ["launchLofi3", "lofiDaylightLoop", "lofiDaylight"]) assert(!M.PIECES[name]().parts.some((p) => ["ePiano", "vinyl"].includes(p.inst)), `${name}: no ePiano, no vinyl`);-assert.throws(() => M.lofiElectronic({ ...M.lofiDaylightLoopSpec(), progression: [{ ...M.DAYLIGHT_PROGRESSION[0], hook: "D5:5" }, ...M.DAYLIGHT_PROGRESSION.slice(1)] }), /beats/);-assert.deepEqual(M.planProblems(M.lofiDaylight()), []); assert.deepEqual(M.planProblems(M.lofiDaylightLoop()), []);-pass("no ePiano/vinyl; a wrong bar throws; planProblems clean");+{ const a = M.filmAudio(M.launchLofi3(), 40)(16000); assert.equal(a[0].length, 40 * 16000); pass("filmAudio: exactly the film's length"); }++// 9. 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}`);+ pass(`novelty: Daylight vs ${d.worst.name} = ${d.worst.score} (threshold ${d.threshold}): FAIL, as Alex heard it`);+ let worst = { score: 0 };+ for (const n of Object.keys(M.DEMOS)) { const fam = Object.values(M.DEMO_FAMILIES).find((f) => f.includes(n)) ?? [n], v = M.novelty(M.DEMOS[n](), M.DEMOS, fam); assert(v.pass, `${n} vs ${v.worst.name} ${v.worst.score}`); if (v.worst.score > worst.score) worst = { ...v.worst, of: n }; }+ pass(`novelty: every demo vs every other demo passes (closest: ${worst.of} vs ${worst.name} ${worst.score})`);+ 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)`); }+console.log(`music unit: ${ok.length} checks PASS in ${((Date.now() - t0) / 1000).toFixed(0)} s`);diff --git a/skills/anidoodle/engine/tools/music.mjs b/skills/anidoodle/engine/tools/music.mjsindex a83fc45..b52951f 100644--- a/skills/anidoodle/engine/tools/music.mjs+++ b/skills/anidoodle/engine/tools/music.mjs@@ -3,7 +3,12 @@// clipping on the way) and meters the DECODED file: integrated LUFS (BS.1770-4), LRA (EBU 3342),// true peak (4x), onsets/s (spectral flux), spectral centroid; plus note-data numbers.//-// node tools/music.mjs list+// <piece> is YOUR score, a module: path/to/score.ts#exportName (a Material, a Piece, or a function+// returning either); or the name of a shipped demo (listening references, never a film's score).+//+// node tools/music.mjs vocab [style] # the style vocabularies: palette, grooves, harmony, melody, arrangement+// node tools/music.mjs novelty <piece> # similarity to every shipped piece; 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 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. lofiElectronic adds loop cycles so it still ends on its outro;@@ -26,6 +31,23 @@ const load = async () => {return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));};+/** A piece by demo name, or from a module: "path.ts#export" (default export if no #). Material is composed. */+const getPiece = async (M, ref) => {+ if (!ref) throw new Error("name a piece: path/to/score.ts#export, or a demo (node tools/music.mjs list)");+ const fromDemo = M.DEMOS[ref] ?? M.FIXTURES[ref];+ let v;+ if (fromDemo) v = fromDemo;+ else {+ const [file, exp = "default"] = ref.split("#");+ if (!existsSync(resolve(file))) throw new Error(`no demo or module "${ref}" (demos: node tools/music.mjs list)`);+ const r = await build({ entryPoints: [resolve(file)], bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });+ const mod = await import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));+ v = mod[exp]; if (v === undefined) throw new Error(`${file} has no export "${exp}" (exports: ${Object.keys(mod).join(", ")})`);+ }+ const make = () => { const x = typeof v === "function" ? v() : v; return x && x.sections && x.chords ? M.composePiece(x) : x; };+ return { make, name: ref, demo: Boolean(fromDemo) };+};+export const writeWavFloat = (path, L, R, sr = SR) => {const n = L.length, data = Buffer.alloc(n * 8), h = Buffer.alloc(58);for (let i = 0; i < n; i++) { data.writeFloatLE(L[i], i * 8); data.writeFloatLE(R[i], i * 8 + 4); }@@ -61,7 +83,7 @@ const onsetsFromData = (rendered) => {};const renderOne = (M, spec) => {- let piece = M.PIECES[spec.piece]();+ 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(", ")}`; }@@ -92,9 +114,19 @@ const main = async () => {const [cmd, ...args] = process.argv.slice(2);const M = await load();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(Object.keys(M.PIECES).join("\n")); return; }+ 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") { printVocab(M, args[0]); return; }+ if (cmd === "calibrate") { calibrate(M); return; }+ if (cmd === "novelty") {+ const pc = await getPiece(M, args[0]), fam = Object.values(M.DEMO_FAMILIES).find((f) => f.includes(args[0])) ?? [args[0]];+ const v = M.novelty(pc.make(), M.DEMOS, fam, val("--threshold", undefined));+ console.log(`novelty: ${args[0]} vs ${v.rows.length} shipped pieces (fail above ${v.threshold}, or on any reused 6-note 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 rhythm of the lead, the groove, the chord colours, the form), not just the key.`);+ if (!v.pass) process.exitCode = 1; return;+ }if (cmd === "render") {- const [name, out] = args; const { r, tempo, ms, deterministic, piece } = renderOne(M, { piece: name, seconds: val("--seconds", undefined), tempo: val("--tempo", undefined), flat: flag("--flat"), fit: flag("--fit") });+ 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;writeWavFloat(wav, r.L, r.R);if (mp3) { execFileSync("ffmpeg", ["-v", "error", "-y", "-i", wav, "-c:a", "libmp3lame", "-b:a", "256k", out]); unlinkSync(wav); }@@ -104,12 +136,12 @@ const main = async () => {return;}if (cmd === "stems") {- const [name] = args; let piece = M.PIECES[name](), tempo = piece.plan.tempo, seconds = val("--seconds", undefined);+ 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;}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(M.PIECES[args[0]]())); return; }+ if (cmd === "score") { console.log(M.scoreText((await getPiece(M, args[0])).make())); return; }if (cmd === "probe") { console.log(JSON.stringify(probe(M), null, 1)); return; }if (cmd === "samples") {const dir = resolve(args[0]);@@ -163,6 +195,38 @@ const main = async () => {}};+const calibrate = (M) => {+ const trim = {}, fix = {};+ for (const v of Object.values(M.VOCAB)) {+ if (v.calibrated) continue; trim[v.id] = {}; fix[v.id] = {}; M.VOCAB_TARGET_FIX[v.id] = {};+ for (let pass = 0; pass < 3; pass++) {+ M.VOCAB_TRIM[v.id] = trim[v.id];+ const b = M.measureStems(M.composePiece(M.testMaterial(v)), STEM_SR);+ for (const r of b.rows) if (r.offDb !== null && Number.isFinite(r.offDb)) trim[v.id][r.id] = +Math.max(-12, Math.min(12, (trim[v.id][r.id] ?? 0) - r.offDb)).toFixed(1); // capped: past 12 dB the gain is not the problem+ if (pass === 2) { for (const r of b.rows) if (r.offDb !== null && Math.abs(r.offDb) > 1) fix[v.id][r.id] = +r.offDb.toFixed(1);+ console.log(v.id.padEnd(14), b.rows.filter((r) => r.offDb !== null).map((r) => `${r.id} ${r.offDb >= 0 ? "+" : ""}${r.offDb.toFixed(1)}`).join(" ")); }+ }+ }+ const file = join(here, "../src/canvas-core/music/vocabTrim.ts"), head = readFileSync(file, "utf8").split("export const VOCAB_TRIM")[0], j = (x) => JSON.stringify(x, null, 1).replace(/"(\w+)":/g, "$1:");+ writeFileSync(file, `${head}export const VOCAB_TRIM: Record<string, Partial<Record<Slot, number>>> = ${j(trim)};\n/** Where a 12 dB trim could not reach the target (long-decaying plucks read low as active RMS), the target moves to where the voice sits. */\nexport const VOCAB_TARGET_FIX: Record<string, Partial<Record<Slot, number>>> = ${j(fix)};\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(", ")}`);+ console.log("palette (slot: instrument, gain dB, stem target):"); for (const [slot, x] of Object.entries(v.palette)) console.log(` ${slot.padEnd(8)} ${x.inst.padEnd(10)} ${String(x.gainDb).padStart(5)} ${v.stemTargets[slot] ?? "-"} dB${Object.keys(v.alternates[slot] ?? {}).length ? ` alternates: ${Object.keys(v.alternates[slot]).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}`);+ for (const [k, x] of Object.entries(v.melody)) console.log(`melody.${k}: ${x}`);+ for (const [k, x] of Object.entries(v.arrangement)) console.log(`arrangement.${k}: ${x}`);+ console.log(`avoid: ${v.avoid}`);+};+/** Stem balance: each part's unmastered stem RMS (active samples) vs piece.stemTargets. Measured at 24 kHz, as the targets were. */const STEM_SR = 24000;const printStems = (M, piece, tempo, seconds) => {@@ -170,8 +234,9 @@ const printStems = (M, piece, tempo, seconds) => {console.log(`stem balance: ${piece.title} (unmastered stem RMS over active samples vs target, tolerance +-${b.tolDb} dB)`);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)");- console.log(b.pass ? "stems PASS" : "stems FAIL: fix the part gains (Part.gainDb / LofiSpec.levels), then master. LUFS alone once hid a sub 7-10 dB too hot.");- if (!b.pass) process.exitCode = 1;+ const cal = M.VOCAB[piece.plan.style]?.calibrated !== false;+ console.log(b.pass ? "stems PASS" : `stems ${cal ? "FAIL" : "OFF TARGET (advisory: this style's targets are uncalibrated starting numbers)"}: fix the part gains (Material.levels), then master. LUFS alone once hid a sub 7-10 dB too hot.`);+ if (!b.pass && cal) process.exitCode = 1;return b;};