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
soundcheck: a film-sound scorecard and a listening sheet
Alex Greenshpunc446840d92cb
diff --git a/skills/anidoodle/engine/src/canvas-core/music/soundcheck.ts b/skills/anidoodle/engine/src/canvas-core/music/soundcheck.tsnew file mode 100644index 0000000..5744f32--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/soundcheck.ts@@ -0,0 +1,271 @@+// SOUNDCHECK. The film-sound scorecard as pure functions over a decoded stereo mix, so the tool+// (tools/soundcheck.mjs) and the tests read the same numbers. Nothing here needs a model or ears:+// level BS.1770 integrated / LRA / true peak from meter.ts; 10 ms K-weighted powers for the rest+// shape first sound, holes, dead tail, fade, final moment, an 11-point arc, hits, stop-downs+// spectrum six band shares of the mid, centroid, the loudest third-octave in a band (to name a fix)+// stereo side vs mid, L/R correlation overall and per band, mono-fold loss beyond the expected 3 dB+// picture frame-difference events against onsets, with a chance baseline from shifted events+// Then evaluate() holds every number to a profile and writes the fix a mixer would make.+import { loudness, truePeak, onsetsDetail, centroid, fft } from "./meter";+import { kWeight } from "./sfxCore";++export const BANDS: Record<string, [number, number]> = { sub: [20, 60], low: [60, 250], lowmid: [250, 1000], mid: [1000, 4000], presence: [4000, 8000], air: [8000, 16000] };+/** Where a stereo mix's body sits: decorrelation here is what a phone's one speaker combs away. */+export const BODY: [number, number] = [150, 2000];+const HOP = 0.01, BLK = 0.05;+const lufsOf = (z: number) => -0.691 + 10 * Math.log10(Math.max(z, 1e-20));+const meanOf = (p: ArrayLike<number>, a: number, b: number) => { const lo = Math.max(0, a), hi = Math.min(p.length, b); let s = 0; for (let i = lo; i < hi; i++) s += p[i]; return hi > lo ? s / (hi - lo) : 0; };+const median = (xs: number[]) => { if (!xs.length) return NaN; const s = [...xs].sort((a, b) => a - b), m = s.length >> 1; return s.length & 1 ? s[m] : 0.5 * (s[m - 1] + s[m]); };+const r1 = (x: number, d = 1) => (Number.isFinite(x) ? +x.toFixed(d) : null);++/** K-weighted power per 10 ms hop, channels summed (BS.1770 weights L and R at 1). */+const hopPowers = (k: Float64Array[], sr: number) => {+ const h = Math.round(HOP * sr), n = Math.floor(k[0].length / h), p = new Float64Array(n);+ for (let i = 0; i < n; i++) { let s = 0; for (const c of k) for (let j = i * h; j < (i + 1) * h; j++) s += c[j] * c[j]; p[i] = s / h; }+ return p;+};+/** Gated integrated loudness from hop powers: 400 ms blocks every 100 ms, -70 absolute, -10 relative (meter.ts's gates). */+export const gatedLufs = (p: ArrayLike<number>) => {+ const per = Math.round(0.4 / HOP), step = Math.round(0.1 / HOP), bl: number[] = [];+ for (let a = 0; a + per <= p.length; a += step) bl.push(meanOf(p, a, a + per));+ const abs = bl.filter((z) => lufsOf(z) > -70); if (!abs.length) return -Infinity;+ const rel = lufsOf(abs.reduce((a, b) => a + b, 0) / abs.length) - 10, g = abs.filter((z) => lufsOf(z) > rel);+ return lufsOf(g.reduce((a, b) => a + b, 0) / g.length);+};++/** Welch-averaged auto and cross spectra of L and R (Hann, 50 % overlap). */+const spectra = (L: Float32Array, R: Float32Array, N = 8192) => {+ const bins = N / 2 + 1, ll = new Float64Array(bins), rr = new Float64Array(bins), lr = new Float64Array(bins), w = Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));+ const n = L.length, starts: number[] = []; for (let a = 0; a + N <= n; a += N / 2) starts.push(a); if (!starts.length) starts.push(0); // shorter than one frame: zero-padded+ for (const a of starts) {+ const lr_ = new Float64Array(N), li = new Float64Array(N), rre = new Float64Array(N), ri = new Float64Array(N);+ for (let i = 0; i < N && a + i < n; i++) { lr_[i] = L[a + i] * w[i]; rre[i] = R[a + i] * w[i]; }+ fft(lr_, li); fft(rre, ri);+ for (let k = 0; k < bins; k++) { ll[k] += lr_[k] * lr_[k] + li[k] * li[k]; rr[k] += rre[k] * rre[k] + ri[k] * ri[k]; lr[k] += lr_[k] * rre[k] + li[k] * ri[k]; }+ }+ return { ll, rr, lr, N };+};++export type Gap = { at: number; len: number; allowed: boolean };+export type Measures = {+ durationS: number; lufs: number; lra: number; truePeak: number; samplePeak: number; crest: number; peakPos: number;+ introLu: number; endLu: number; arc: (number | null)[]; arcDip: number; arcDipAt: number;+ firstSound: number | null; insideGap: number; insideGapAt: number | null; gaps: Gap[]; endSilence: number; endSilenceFrom: number;+ fade: number; finalLu: number; tailLu: number; quietAt: number | null; loudAt: number;+ onsetRate: number; hitRate: number; stopDowns: { at: number; len: number }[];+ bands: Record<string, number>; centroid: number; peakHz: Record<string, number>;+ sideMid: number; corr: number; bandCorr: Record<string, number>; bodyCorr: number; monoDrop: number; monoLoss: number;+ silent: boolean;+};+export type Curves = { momentary: number[]; shortTerm: number[]; hopS: number; levels50: number[]; onsets: number[]; hits: number[] };++/** Every model-free number for one decoded stereo mix. `allow` lists [from, to] seconds where a hole is meant (a declared stop-down). */+export const analyze = (L: Float32Array, R: Float32Array, sr: number, { allow = [] as [number, number][] } = {}): { measures: Measures; curves: Curves } => {+ const dur = L.length / sr, chans = [L, R];+ const lo = loudness(chans, sr), tp = truePeak(chans), I = lo.integrated, silent = !(I > -70);+ const kL = kWeight(L, sr), kR = kWeight(R, sr), p10 = hopPowers([kL, kR], sr);+ // mono fold: K-weighting is linear, so the mid's K-weighted signal is the mean of the channels'+ const kM = new Float64Array(kL.length); for (let i = 0; i < kM.length; i++) kM[i] = 0.5 * (kL[i] + kR[i]);+ const pM = hopPowers([kM], sr), monoDrop = gatedLufs(p10) - gatedLufs(pM);+ // 50 ms block levels: fine enough to time a 0.25 s hole, coarse enough that one quiet cycle is not a gap.+ // Unweighted, against the same gating on unweighted power: K-weighting rings for ~30 ms past an abrupt+ // cut, which would move every hole and every dead tail by a block.+ const pRaw = hopPowers([Float64Array.from(L), Float64Array.from(R)], sr), Iraw = gatedLufs(pRaw);+ const per = Math.round(BLK / HOP), nb = Math.floor(pRaw.length / per), lv: number[] = [];+ for (let j = 0; j < nb; j++) lv.push(lufsOf(meanOf(pRaw, j * per, (j + 1) * per)));+ const body = (j: number) => lv[j] >= Iraw - 20, alive = (j: number) => lv[j] > Iraw - 30 && lv[j] > -70;+ let first = -1, last = -1, lastBody = -1;+ for (let j = 0; j < nb; j++) { if (first < 0 && body(j)) first = j; if (alive(j)) last = j; if (body(j)) lastBody = j; }+ const aliveFirst = lv.findIndex((_, j) => alive(j));+ const gaps: Gap[] = [];+ if (aliveFirst >= 0) for (let j = aliveFirst, run = -1; j <= last + 1; j++) {+ if (j <= last && !alive(j)) { if (run < 0) run = j; continue; }+ if (run >= 0) { const at = run * BLK, len = (j - run) * BLK; gaps.push({ at, len, allowed: allow.some(([a, b]) => at >= a - 0.05 && at + len <= b + 0.05) }); run = -1; }+ }+ const open = gaps.filter((g) => !g.allowed).sort((a, b) => b.len - a.len);+ const endFrom = last >= 0 ? (last + 1) * BLK : 0;+ // the arc: each point the energy mean of the tenth of the film around it, against the whole+ const nh = p10.length, arc: (number | null)[] = [];+ for (let q = 0; q <= 10; q++) { const c = (q / 10) * nh, half = nh / 20, l = lufsOf(meanOf(p10, Math.floor(c - half), Math.ceil(c + half))); arc.push(l > -70 ? r1(l - I) : null); }+ let arcDip = 0, arcDipAt = 0; for (let q = 1; q <= 9; q++) { const v = arc[q] ?? -70 - I; if (v < arcDip) { arcDip = v; arcDipAt = (q / 10) * dur; } } // ends are first sound and end silence's job+ const tenth = Math.max(1, Math.round(nh / 10));+ const introLu = lufsOf(meanOf(p10, 0, tenth)) - I, endLu = lufsOf(meanOf(p10, nh - tenth, nh)) - I;+ // the final moment: the loudest 400 ms block centred in the last 3 s+ const fin = lo.momentary.filter((_, i) => i * lo.hopS + 0.2 >= dur - 3);+ const st = lo.shortTerm; let si = 0; st.forEach((v, i) => { if (v > st[si]) si = i; });+ let qi = -1; st.forEach((v, i) => { if (v > I - 40 && (qi < 0 || v < st[qi])) qi = i; });+ // hits and stop-downs on a 100 ms level every 10 ms+ const S = Array.from({ length: nh }, (_, i) => lufsOf(meanOf(p10, i - 5, i + 5)));+ const hits: number[] = [];+ for (let i = 8; i < nh; i++) if (S[i] - S[i - 8] >= 6 && S[i] >= I - 8 && (!hits.length || i * HOP - hits[hits.length - 1] > 0.3)) hits.push(i * HOP);+ const stopDowns: { at: number; len: number }[] = [];+ for (let i = 50; i < nh; i++) {+ const ref = lufsOf(meanOf(p10, i - 50, i)); if (ref < I - 10 || S[i] >= ref - 10 || S[i - 1] < ref - 10) continue;+ let j = i; while (j < nh && S[j] < ref - 10) j++;+ const len = (j - i) * HOP; let back = false; for (let k = j; k < Math.min(nh, j + 30); k++) if (S[k] >= ref - 6) { back = true; break; }+ if (len >= 0.15 && len <= 1.5 && back) stopDowns.push({ at: i * HOP, len: +len.toFixed(2) });+ i = j;+ }+ const on = silent ? [] : onsetsDetail(chans, sr).times;+ // spectrum and stereo+ const sp = spectra(L, R), df = sr / sp.N, bins = sp.ll.length, mid = new Float64Array(bins), side = new Float64Array(bins);+ for (let k = 0; k < bins; k++) { mid[k] = (sp.ll[k] + sp.rr[k] + 2 * sp.lr[k]) / 4; side[k] = Math.max(0, (sp.ll[k] + sp.rr[k] - 2 * sp.lr[k]) / 4); }+ const sum = (a: Float64Array, f0: number, f1: number) => { let s = 0; for (let k = Math.ceil(f0 / df); k < Math.min(bins, Math.ceil(f1 / df)); k++) s += a[k]; return s; };+ const tot = sum(mid, 20, 16000) || 1e-30, bands: Record<string, number> = {}, bandCorr: Record<string, number> = {}, peakHz: Record<string, number> = {};+ const corrIn = (f0: number, f1: number) => { const d = Math.sqrt(sum(sp.ll, f0, f1) * sum(sp.rr, f0, f1)); return d > 1e-20 ? sum(sp.lr, f0, f1) / d : NaN; };+ const thirds = Array.from({ length: 28 }, (_, i) => 1000 * Math.pow(2, (i - 15) / 3));+ for (const [b, [f0, f1]] of Object.entries(BANDS)) {+ bands[b] = 10 * Math.log10(Math.max(sum(mid, f0, f1), 1e-30) / tot); bandCorr[b] = corrIn(f0, f1);+ let best = -1, bc = 0; for (const c of thirds) if (c >= f0 && c < f1) { const e = sum(mid, c / Math.pow(2, 1 / 6), c * Math.pow(2, 1 / 6)); if (e > best) { best = e; bc = c; } }+ peakHz[b] = Math.round(bc);+ }+ let sl = 0, sr_ = 0, slr = 0, ml = 0, mr = 0; for (let i = 0; i < L.length; i++) { ml += L[i]; mr += R[i]; } ml /= L.length || 1; mr /= L.length || 1;+ for (let i = 0; i < L.length; i++) { const a = L[i] - ml, b = R[i] - mr; sl += a * a; sr_ += b * b; slr += a * b; }+ const sm = sum(side, 20, 20000), mm = sum(mid, 20, 20000);+ const measures: Measures = {+ durationS: dur, lufs: I, lra: lo.lra, truePeak: tp.dbtp, samplePeak: tp.samplePeakDb, crest: lo.shortMax - I, peakPos: Math.min(1, (si * lo.hopS + 1.5) / dur),+ introLu, endLu, arc, arcDip, arcDipAt,+ firstSound: first >= 0 ? first * BLK : null, insideGap: open[0]?.len ?? 0, insideGapAt: open[0]?.at ?? null, gaps, endSilence: Math.max(0, dur - endFrom), endSilenceFrom: endFrom,+ fade: lastBody >= 0 && last >= lastBody ? (last - lastBody) * BLK : 0, finalLu: fin.length ? Math.max(...fin) - I : NaN, tailLu: lv.length ? Math.max(lv[lv.length - 1] - Iraw, -70 - I) : NaN,+ quietAt: qi >= 0 ? qi * lo.hopS + 1.5 : null, loudAt: si * lo.hopS + 1.5,+ onsetRate: on.length / dur, hitRate: hits.length / dur, stopDowns,+ bands, centroid: silent ? 0 : centroid(chans, sr).energyWeighted, peakHz,+ sideMid: 10 * Math.log10(Math.max(sm, 1e-30) / Math.max(mm, 1e-30)), corr: sl > 0 && sr_ > 0 ? slr / Math.sqrt(sl * sr_) : NaN,+ bandCorr, bodyCorr: corrIn(BODY[0], BODY[1]), monoDrop, monoLoss: monoDrop - 10 * Math.log10(2), silent,+ };+ return { measures, curves: { momentary: lo.momentary, shortTerm: lo.shortTerm, hopS: lo.hopS, levels50: lv, onsets: on, hits } };+};++// ---------------------------------------------------------------- picture against sound+/** Frame-difference spikes: a frame whose changed area is 4x the median of the second around it (and at least 2 %), or 15 % outright. `changed[i]` compares frame i with i - 1. */+export const visualEvents = (changed: number[], fps: number) => {+ const ev: number[] = [], win = Math.max(1, Math.round(fps));+ for (let i = 1; i < changed.length; i++) {+ const ctx: number[] = []; for (let k = Math.max(1, i - win); k <= Math.min(changed.length - 1, i + win); k++) if (k !== i) ctx.push(changed[k]);+ const c = median(ctx), d = changed[i];+ if (((d >= 4 * Math.max(c || 0, 0.005) && d >= 0.02) || d >= 0.15) && (!ev.length || i / fps - ev[ev.length - 1] > 0.2)) ev.push(i / fps);+ }+ return ev;+};+/** Share of events with an onset within `tol`, against the same events shifted off their frames (chance), the unanswered ones, and the nearest-onset offsets. */+export const visualSync = (events: number[], onsets: number[], dur: number, tol = 0.1) => {+ const near = (e: number) => onsets.reduce((b, o) => (Math.abs(o - e) < Math.abs(b - e) ? o : b), Infinity);+ const share = (evs: number[]) => (evs.length && onsets.length ? evs.filter((e) => Math.abs(near(e) - e) <= tol).length / evs.length : NaN);+ const shifts = [0.23, 0.31, 0.43, 0.57, 0.71, 0.87, -0.29, -0.41, -0.53, -0.67];+ const chance = median(shifts.map((s) => share(events.map((e) => e + s).filter((e) => e > 0 && e < dur))).filter(Number.isFinite));+ const offsets = events.map((e) => near(e) - e).filter((d) => Math.abs(d) <= 0.25).map((d) => Math.round(d * 1000));+ return { events: events.length, share: share(events), chance, unanswered: events.filter((e) => !(Math.abs(near(e) - e) <= tol)), medianOffsetMs: offsets.length ? median(offsets) : NaN, offsets };+};++// ---------------------------------------------------------------- holding the numbers to a profile+export type Range = { min?: number; max?: number; tol?: number };+export type Status = "PASS" | "WARN" | "FAIL" | "INFO";+export type Profile = { name: string; ranges: Record<string, Range>; allow?: [number, number][] };+/** Drawing films, from the study's pro-reference column, tightened where a drawing film should be (no dead tail, no hole, sound from frame 0). */+export const DEFAULT_PROFILE: Profile = {+ name: "built-in: drawing film",+ ranges: {+ lufs: { min: -16, max: -13, tol: 1 }, truePeak: { max: -1, tol: 0 }, lra: { max: 9, tol: 3 },+ firstSound: { max: 0.5, tol: 0.5 }, insideGap: { max: 0.25, tol: 0.25 }, endSilence: { max: 0.5, tol: 0.5 }, arcDip: { min: -10, tol: 6 }, tailLu: { max: -20, tol: 10 },+ bodyCorr: { min: 0.3, tol: 0.15 }, monoLoss: { max: 1.5, tol: 0.5 }, corr: { min: 0.3, tol: 0.3 }, sideMid: { min: -15, max: -4, tol: 3 },+ sub: { max: -6, tol: 2 }, lowmid: { max: -3, tol: 1.5 },+ },+};+/** Delivery limits a reference set never loosens: a profile built from films can only move the taste ranges. */+export const HARD = ["truePeak", "firstSound", "insideGap", "endSilence", "monoLoss"];+const TOL: Record<string, number> = { lufs: 1, lra: 3, crest: 2, introLu: 3, endLu: 3, arcDip: 4, tailLu: 6, fade: 0.5, finalLu: 4, onsetRate: 1, hitRate: 0.3, corr: 0.2, bodyCorr: 0.15, sideMid: 3, centroid: 400, sub: 2, low: 2, lowmid: 2, mid: 2, presence: 2, air: 2 };++export type Row = { key: string; label: string; value: number | null; text: string; status: Status; range?: Range; fix?: string; at?: number; covered?: boolean };+const fmtT = (s: number) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`;+export { fmtT };+const f1 = (x: number | null, d = 1) => (x === null || !Number.isFinite(x) ? "n/a" : x.toFixed(d));+const sign = (x: number, d = 1) => (x > 0 ? "+" : "") + x.toFixed(d);+export const grade = (v: number | null, r?: Range): Status => {+ if (!r) return "INFO"; if (v === null || !Number.isFinite(v)) return "FAIL";+ const tol = r.tol ?? 0, over = Math.max(r.min !== undefined ? r.min - v : 0, r.max !== undefined ? v - r.max : 0);+ return over <= 1e-9 ? "PASS" : over <= tol + 1e-9 ? "WARN" : "FAIL";+};+const rangeText = (r?: Range) => (!r ? "" : r.min !== undefined && r.max !== undefined ? `${r.min}..${r.max}` : r.min !== undefined ? `>= ${r.min}` : r.max !== undefined ? `<= ${r.max}` : "");++type Def = { key: string; label: string; get: (m: Measures) => number | null; show: (v: number, m: Measures) => string; fix?: (v: number, m: Measures, r: Range) => string; at?: (m: Measures) => number | undefined };+const BAND_LABEL: Record<string, string> = { sub: "sub 20-60 Hz", low: "low 60-250 Hz", lowmid: "low-mid 250-1k", mid: "mid 1-4k", presence: "presence 4-8k", air: "air 8-16k" };+const bandFix = (b: string, v: number, m: Measures, r: Range) => {+ const hot = r.max !== undefined && v > r.max, pk = m.peakHz[b];+ if (b === "sub") return hot ? `too much 20-60 Hz (${f1(v)} dB of the energy, it eats the headroom): high-pass the effects at 30-40 Hz and pull the sub voice down` : `no weight under 60 Hz (${f1(v)} dB): let a low voice or the impact reach 40-60 Hz`;+ if (b === "lowmid") return hot ? `boxy (${f1(v)} dB in 250-1k, loudest around ${pk} Hz): cut ${pk >= 250 && pk <= 800 ? `${Math.round(pk * 0.08) * 10}-${Math.round(pk * 0.125) * 10}` : "300-500"} Hz by 2-3 dB` : `thin (${f1(v)} dB in 250-1k): the body is missing, lift 250-500 Hz 1-2 dB`;+ if (b === "low") return hot ? `boomy (${f1(v)} dB in 60-250, around ${pk} Hz): cut ${pk} Hz 2-3 dB or high-pass the pads at 80-100 Hz` : `no low end (${f1(v)} dB in 60-250): bring the bass or the low pad up`;+ if (b === "mid") return hot ? `honky (${f1(v)} dB in 1-4k, around ${pk} Hz): cut ${pk} Hz 2 dB` : `recessed mids (${f1(v)} dB in 1-4k): the melody needs 1-3 kHz, lift the lead`;+ if (b === "presence") return hot ? `harsh (${f1(v)} dB in 4-8k): cut 4-6 kHz 2 dB or soften the transients` : `dull (${f1(v)} dB in 4-8k): lift 5 kHz 1-2 dB on the lead or the effects' transients`;+ return hot ? `fizzy (${f1(v)} dB in 8-16k): a shelf down 2 dB above 10 kHz` : `no air (${f1(v)} dB in 8-16k): a gentle shelf up above 10 kHz`;+};+const DEFS: Def[] = [+ { key: "lufs", label: "integrated loudness", get: (m) => m.lufs, show: (v) => `${f1(v)} LUFS`, fix: (v, m, r) => v < (r.min ?? -99) ? `plays at ${f1(v)} LUFS, ${f1(-14 - v)} LU under the web target: master the mix to -14 LUFS (or -16 for a gentle film), a static gain then the limiter` : `too loud at ${f1(v)} LUFS: turn the master down to -14 LUFS` },+ { key: "truePeak", label: "true peak", get: (m) => m.truePeak, show: (v) => `${f1(v)} dBTP`, fix: (v) => `true peak ${f1(v)} dBTP: set the limiter ceiling to -1.5 dBTP before the encode, so the AAC overshoot stays under -1` },+ { key: "lra", label: "loudness range", get: (m) => m.lra, show: (v) => `${f1(v)} LU`, fix: (v, m) => `level swings ${f1(v)} LU (loudest at ${fmtT(m.loudAt)}${m.quietAt !== null ? `, quietest at ${fmtT(m.quietAt)}` : ""}): lift the quiet passages or keep a bed under them`, at: (m) => m.quietAt ?? undefined },+ { key: "firstSound", label: "first sound", get: (m) => m.firstSound, show: (v) => `${f1(v, 2)} s`, fix: (v) => `nothing reaches body level until ${fmtT(v)}: start the bed or a sound on frame 0`, at: (m) => m.firstSound ?? 0 },+ { key: "insideGap", label: "longest hole inside", get: (m) => m.insideGap, show: (v, m) => `${f1(v, 2)} s${m.insideGapAt !== null ? ` at ${fmtT(m.insideGapAt)}` : ""}`, fix: (v, m) => `${f1(v)} s hole at ${fmtT(m.insideGapAt ?? 0)}: keep the bed under it, or if it is a deliberate stop-down pass --allow ${f1(m.insideGapAt ?? 0, 2)}:${f1((m.insideGapAt ?? 0) + v, 2)}`, at: (m) => m.insideGapAt ?? undefined },+ { key: "endSilence", label: "dead air at the end", get: (m) => m.endSilence, show: (v) => `${f1(v, 2)} s`, fix: (v, m) => `${f1(v)} s of dead air at the end (from ${fmtT(m.endSilenceFrom)}): carry the bed or a tail to the last frame, or end the film sooner`, at: (m) => m.endSilenceFrom },+ { key: "arcDip", label: "deepest dip in the arc", get: (m) => (m.silent ? null : m.arcDip), show: (v, m) => `${sign(v)} LU at ${fmtT(m.arcDipAt)}`, fix: (v, m) => `the sound drops ${f1(-v)} LU under the film at ${fmtT(m.arcDipAt)} (${Math.round((100 * m.arcDipAt) / m.durationS)} %): keep the bed or room tone under it`, at: (m) => m.arcDipAt },+ { key: "tailLu", label: "level of the last 50 ms", get: (m) => (m.silent ? null : m.tailLu), show: (v, m) => (v + m.lufs <= -70 + 1e-6 ? "silent" : `${sign(v)} LU`), fix: (v) => `ends on a cut (the last 50 ms still at ${sign(v)} LU): end on a tail or fade the last 0.3 s`, at: (m) => m.durationS - 0.05 },+ { key: "bodyCorr", label: "L/R correlation 150-2k", get: (m) => m.bodyCorr, show: (v) => f1(v, 2), fix: (v) => `mids decorrelated (150-2k correlation ${f1(v, 2)}): narrow the stereo width below 2 kHz (mixDsp.bandWidth mid at 1.0, or a mono room send)` },+ { key: "monoLoss", label: "mono fold, extra loss", get: (m) => m.monoLoss, show: (v) => `${f1(v)} dB`, fix: (v) => `folded to mono it loses ${f1(v)} dB more than a centred mix: phones will comb it; narrow the width or check the stereo pair's phase` },+ { key: "corr", label: "L/R correlation", get: (m) => m.corr, show: (v) => f1(v, 2), fix: (v) => `L and R barely agree (correlation ${f1(v, 2)}): pan the lead and bass to the centre, keep width for pads and room` },+ { key: "sideMid", label: "side vs mid", get: (m) => m.sideMid, show: (v) => `${f1(v)} dB`, fix: (v, m, r) => v > (r.max ?? 99) ? `too wide (side ${f1(v)} dB against the mid): narrow the overall width` : `very narrow (side ${f1(v)} dB): widen the pads or the room a little` },+ ...Object.keys(BANDS).map((b): Def => ({ key: b, label: `${BAND_LABEL[b]} share`, get: (m) => (m.silent ? null : m.bands[b]), show: (v) => `${f1(v)} dB`, fix: (v, m, r) => bandFix(b, v, m, r) })),+ { key: "centroid", label: "brightness (centroid)", get: (m) => m.centroid, show: (v) => `${Math.round(v)} Hz`, fix: (v, m, r) => v > (r.max ?? 1e9) ? `brighter than the references (${Math.round(v)} Hz): soften the top` : `darker than the references (${Math.round(v)} Hz): lift the top` },+ { key: "crest", label: "loudest 3 s over integrated", get: (m) => m.crest, show: (v) => `${sign(v)} LU` },+ { key: "introLu", label: "intro level (first 10 %)", get: (m) => m.introLu, show: (v) => `${sign(v)} LU` },+ { key: "endLu", label: "end level (last 10 %)", get: (m) => m.endLu, show: (v) => `${sign(v)} LU` },+ { key: "peakPos", label: "loudest moment", get: (m) => m.peakPos, show: (v, m) => `${Math.round(v * 100)} % (${fmtT(v * m.durationS)})` },+ { key: "fade", label: "fade / ring-out", get: (m) => m.fade, show: (v) => `${f1(v, 2)} s` },+ { key: "finalLu", label: "final moment (last 3 s)", get: (m) => m.finalLu, show: (v) => `${sign(v)} LU` },+ { key: "onsetRate", label: "onsets per second", get: (m) => m.onsetRate, show: (v) => f1(v, 2) },+ { key: "hitRate", label: "salient hits per second", get: (m) => m.hitRate, show: (v) => f1(v, 2) },+ { key: "stopDowns", label: "stop-downs", get: (m) => m.stopDowns.length, show: (v, m) => `${v}${m.stopDowns.length ? ` (${m.stopDowns.slice(0, 4).map((s) => fmtT(s.at)).join(", ")})` : ""}` },+];+/** Fix order: what most makes a film read unfinished goes first. */+const ORDER = ["lufs", "endSilence", "insideGap", "firstSound", "arcDip", "truePeak", "lra", "bodyCorr", "monoLoss", "sub", "lowmid", "sideMid", "corr", "tailLu"];++export const evaluate = (m: Measures, profile: Profile = DEFAULT_PROFILE): Row[] =>+ DEFS.map((d) => {+ const v = d.get(m), r = profile.ranges[d.key], status = m.silent && d.key === "lufs" ? "FAIL" : grade(v, r);+ const row: Row = { key: d.key, label: d.label, value: v === null ? null : r1(v, 3), text: v === null ? "n/a" : d.show(v, m), status, range: r };+ if ((status === "FAIL" || status === "WARN") && r) { row.fix = m.silent ? "the file is silent: there is no sound to check" : v === null ? `${d.label}: not measurable` : d.fix ? d.fix(v, m, r) : `${d.label} ${d.show(v, m)} is outside ${rangeText(r)}`; const at = d.at?.(m); if (at !== undefined) row.at = at; }+ // a dip that sits in a hole or the dead tail is that fault again: one fix, not two+ if (d.key === "arcDip" && row.fix && (m.gaps.some((g) => !g.allowed && g.len > (profile.ranges.insideGap?.max ?? 0.25) && m.arcDipAt >= g.at - m.durationS / 20 && m.arcDipAt <= g.at + g.len + m.durationS / 20) || (m.endSilence > (profile.ranges.endSilence?.max ?? 0.5) && m.arcDipAt >= m.endSilenceFrom - m.durationS / 20))) row.covered = true;+ return row;+ });+/** One fix per cause: the stereo numbers all point at the width, so they fold into the first of them that is out. */+const GROUP: Record<string, string> = { bodyCorr: "stereo", monoLoss: "stereo", corr: "stereo", sideMid: "stereo" };+export const fixFirst = (rows: Row[]) => {+ const out: Row[] = [], seen = new Map<string, Row>();+ for (const r of rows.filter((x) => x.fix && !x.covered).sort((a, b) => (a.status === b.status ? 0 : a.status === "FAIL" ? -1 : 1) || rank(a.key) - rank(b.key))) {+ const g = GROUP[r.key], lead = g && seen.get(g);+ if (lead) { lead.fix += `${lead.fix!.includes("(also ") ? "; " : " (also "}${r.label} ${r.text}`; continue; }+ const copy = { ...r }; if (g) seen.set(g, copy); out.push(copy);+ }+ for (const r of seen.values()) if (r.fix!.includes("(also ")) r.fix += ")";+ return out;+};+const rank = (k: string) => { const i = ORDER.indexOf(k); return i < 0 ? 99 : i; };+export { rangeText };++/** Ranges from films Alex picked: min, max and median of every number, per metric. */+export const buildProfile = (name: string, sets: { file: string; measures: Measures }[]) => {+ const metrics: Record<string, { min: number; max: number; median: number }> = {};+ for (const d of DEFS) {+ const vs = sets.map((s) => d.get(s.measures)).filter((v): v is number => v !== null && Number.isFinite(v));+ if (vs.length) metrics[d.key] = { min: r1(Math.min(...vs), 2)!, max: r1(Math.max(...vs), 2)!, median: r1(median(vs), 2)! };+ }+ return { name, built: "soundcheck profile", from: sets.map((s) => s.file), metrics };+};+/** A built profile as ranges: the references' own span, padded by half a tolerance, over the defaults; HARD limits stay. */+export const profileFrom = (built: { name: string; metrics: Record<string, { min: number; max: number }>; allow?: [number, number][] }): Profile => {+ const ranges: Record<string, Range> = { ...DEFAULT_PROFILE.ranges };+ for (const [k, v] of Object.entries(built.metrics ?? {})) {+ if (HARD.includes(k) || k === "stopDowns" || k === "peakPos") continue;+ const tol = TOL[k] ?? DEFAULT_PROFILE.ranges[k]?.tol ?? 1, pad = tol / 2;+ ranges[k] = { min: +(v.min - pad).toFixed(2), max: +(v.max + pad).toFixed(2), tol };+ }+ return { name: built.name, ranges, allow: built.allow };+};diff --git a/skills/anidoodle/engine/test/soundcheck.test.ts b/skills/anidoodle/engine/test/soundcheck.test.tsnew file mode 100644index 0000000..47dd464--- /dev/null+++ b/skills/anidoodle/engine/test/soundcheck.test.ts@@ -0,0 +1,101 @@+// SOUNDCHECK TESTS. Each fault the scorecard exists to catch, built on purpose in code (a hole, a+// dead tail, a late start, a decorrelated pair, a sub-heavy mix, a boxy mix, a quiet master, a cut+// ending), and each must show up in its own metric, with a fix that names the time or the band.+import { analyze, evaluate, fixFirst, visualEvents, visualSync, buildProfile, profileFrom, grade, DEFAULT_PROFILE } from "../src/canvas-core/music/soundcheck";+import { loudness } from "../src/canvas-core/music/meter";++export const name = "soundcheck";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const sr = 48000;+ // mulberry32: a plain LCG's interleaved outputs are correlated per band (it read as a -0.99 low-band correlation)+ let seed = 9; const rnd = () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return (((t ^ (t >>> 14)) >>> 0) / 4294967296) * 2 - 1; };+ /** A plucked chord every 0.25 s over a soft pad: music-like, steady, correlated (the same in both ears). */+ const music = (secs: number, { from = 0, to = secs, amp = 0.2 } = {}) => {+ const n = Math.round(secs * sr), L = new Float32Array(n), R = new Float32Array(n);+ for (let i = Math.round(from * sr); i < Math.min(n, Math.round(to * sr)); i++) {+ const t = i / sr, ph = t % 0.25, env = Math.exp(-ph * 10);+ const v = amp * (0.5 * Math.sin(2 * Math.PI * 330 * t) + 0.3 * Math.sin(2 * Math.PI * 495 * t) * env + 0.3 * Math.sin(2 * Math.PI * 1320 * t) * env + 0.15 * Math.sin(2 * Math.PI * 110 * t) + 0.05 * rnd());+ L[i] = v; R[i] = v;+ }+ return [L, R] as [Float32Array, Float32Array];+ };+ const at = (L: Float32Array, R: Float32Array, opts?: { allow?: [number, number][] }) => analyze(L, R, sr, opts).measures;+ const row = (m: ReturnType<typeof at>, k: string) => evaluate(m).find((r) => r.key === k)!;++ // a clean, steady, centred mix: no holes, no tail, sound from frame 0, nothing lost in mono+ const clean = at(...music(6));+ ok(clean.firstSound === 0 && clean.insideGap === 0 && clean.endSilence < 0.06, `clean mix: first sound ${clean.firstSound} s, longest hole ${clean.insideGap} s, end silence ${clean.endSilence.toFixed(2)} s`);+ ok(Math.abs(clean.monoLoss) < 0.1 && clean.bodyCorr > 0.99 && clean.corr > 0.99, `identical channels fold to mono with ${clean.monoLoss.toFixed(2)} dB extra loss, 150-2k correlation ${clean.bodyCorr.toFixed(2)}`);+ ok(["insideGap", "endSilence", "firstSound", "bodyCorr", "monoLoss", "sub"].every((k) => row(clean, k).status === "PASS"), "clean mix passes the shape, stereo and sub checks");++ // the loudness number agrees with the meter, and a -27 LUFS master fails with the gain it needs+ const [qL, qR] = music(6, { amp: 0.02 }), q = at(qL, qR), ref = loudness([qL, qR], sr).integrated;+ ok(Math.abs(q.lufs - ref) < 1e-9, `integrated loudness is meter.ts's own (${q.lufs.toFixed(2)} LUFS)`);+ ok(row(q, "lufs").status === "FAIL" && /LU under the web target/.test(row(q, "lufs").fix ?? ""), `a ${q.lufs.toFixed(1)} LUFS master fails: "${row(q, "lufs").fix?.slice(0, 60)}..."`);+ const gain = Math.pow(10, (-14 - ref) / 20), [tL, tR] = [qL.map((x) => x * gain), qR.map((x) => x * gain)], tgt = at(tL, tR);+ ok(Math.abs(tgt.lufs + 14) < 0.05 && row(tgt, "lufs").status === "PASS", `mastered to ${tgt.lufs.toFixed(2)} LUFS: PASS`);++ // a 1 s hole at 2.0 s: caught, timed, and its fix names the time; --allow over it clears it+ const [hL, hR] = music(6); for (let i = 2 * sr; i < 3 * sr; i++) { hL[i] = 0; hR[i] = 0; }+ const hole = at(hL, hR);+ ok(Math.abs(hole.insideGap - 1) <= 0.06 && Math.abs((hole.insideGapAt ?? 0) - 2) <= 0.06, `a 1 s hole at 2.0 s reads ${hole.insideGap.toFixed(2)} s at ${hole.insideGapAt?.toFixed(2)} s`);+ const hf = fixFirst(evaluate(hole)).find((r) => r.key === "insideGap");+ ok(row(hole, "insideGap").status === "FAIL" && /1\.0 s hole at 0:02\.0/.test(hf?.fix ?? ""), `the fix says where: "${hf?.fix?.slice(0, 40)}..."`);+ ok(!fixFirst(evaluate(hole)).some((r) => r.key === "arcDip"), "the arc dip inside that hole is the same fault: one fix, not two");+ ok(at(hL, hR, { allow: [[1.9, 3.1]] }).insideGap === 0, "a declared stop-down (--allow 1.9:3.1) is not a hole");+ const [sL, sR] = music(6); for (let i = 2 * sr; i < 2.15 * sr; i++) { sL[i] = 0; sR[i] = 0; }+ ok(row(at(sL, sR), "insideGap").status === "PASS", `a 0.15 s breath is not a hole (${at(sL, sR).insideGap.toFixed(2)} s)`);++ // a dead tail and a late start+ const tail = at(...music(6, { to: 3 }));+ ok(Math.abs(tail.endSilence - 3) <= 0.06 && row(tail, "endSilence").status === "FAIL" && /from 0:03\.0/.test(row(tail, "endSilence").fix ?? ""), `3 s of dead tail: ${tail.endSilence.toFixed(2)} s from ${tail.endSilenceFrom.toFixed(2)} s, FAIL`);+ const late = at(...music(6, { from: 1.5 }));+ ok(Math.abs((late.firstSound ?? 0) - 1.5) <= 0.06 && row(late, "firstSound").status === "FAIL", `sound starting at 1.5 s: first sound ${late.firstSound} s, FAIL`);++ // a cut ending against a faded one+ const cut = at(...music(4));+ const [fL, fR] = music(4); for (let i = 3.5 * sr; i < 4 * sr; i++) { const g = Math.max(0, 1 - (i - 3.5 * sr) / (0.45 * sr)); fL[i] *= g; fR[i] *= g; }+ ok(row(cut, "tailLu").status === "FAIL" && row(at(fL, fR), "tailLu").status === "PASS", `a film that stops mid-note fails the tail (${cut.tailLu.toFixed(1)} LU); faded, it passes`);++ // a decorrelated pair: independent noise in each ear+ const n = 4 * sr, dL = new Float32Array(n), dR = new Float32Array(n); for (let i = 0; i < n; i++) { dL[i] = 0.1 * rnd(); dR[i] = 0.1 * rnd(); }+ const dec = at(dL, dR), df = fixFirst(evaluate(dec));+ ok(Math.abs(dec.bodyCorr) < 0.1 && Math.abs(dec.monoLoss - 3) < 0.3, `decorrelated pair: 150-2k correlation ${dec.bodyCorr.toFixed(2)}, mono loses ${dec.monoLoss.toFixed(2)} dB past the expected 3`);+ ok(row(dec, "bodyCorr").status === "FAIL" && row(dec, "monoLoss").status === "FAIL" && df.filter((r) => ["bodyCorr", "monoLoss", "corr", "sideMid"].includes(r.key)).length === 1 && /below 2 kHz/.test(df.find((r) => r.key === "bodyCorr")?.fix ?? ""), "it fails, and the four stereo numbers make one fix: narrow the width below 2 kHz");+ // decorrelated only in the body: a 600 Hz tone a quarter-turn apart, a centred 5 kHz tone+ const bL = new Float32Array(n), bR = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr, c = 0.1 * Math.sin(2 * Math.PI * 5000 * t); bL[i] = 0.2 * Math.sin(2 * Math.PI * 600 * t) + c; bR[i] = 0.2 * Math.cos(2 * Math.PI * 600 * t) + c; }+ const body = at(bL, bR);+ ok(Math.abs(body.bodyCorr) < 0.1 && body.bandCorr.presence > 0.95, `body-only decorrelation is seen per band (150-2k ${body.bodyCorr.toFixed(2)}, presence ${body.bandCorr.presence.toFixed(2)})`);++ // a sub-heavy mix and a boxy one, each with a band-specific fix+ const [uL, uR] = music(4, { amp: 0.05 }); for (let i = 0; i < uL.length; i++) { const v = 0.4 * Math.sin(2 * Math.PI * 40 * (i / sr)); uL[i] += v; uR[i] += v; }+ const sub = at(uL, uR);+ ok(sub.bands.sub > -3 && row(sub, "sub").status === "FAIL" && /30-40 Hz/.test(row(sub, "sub").fix ?? ""), `sub-heavy: ${sub.bands.sub.toFixed(1)} dB of the energy under 60 Hz, FAIL, "high-pass ... 30-40 Hz"`);+ ok(clean.bands.sub < -20, `the clean mix keeps ${clean.bands.sub.toFixed(1)} dB under 60 Hz`);+ const [xL, xR] = music(4, { amp: 0.03 }); for (let i = 0; i < xL.length; i++) { const v = 0.3 * Math.sin(2 * Math.PI * 630 * (i / sr)); xL[i] += v; xR[i] += v; }+ const box = at(xL, xR);+ ok(row(box, "lowmid").status === "FAIL" && box.peakHz.lowmid === 630 && /630 Hz/.test(row(box, "lowmid").fix ?? ""), `boxy: low-mid ${box.bands.lowmid.toFixed(1)} dB, loudest third-octave ${box.peakHz.lowmid} Hz named in the fix`);++ // a stop-down: a steady bed that dips 15 dB for 0.4 s and snaps back+ const [pL, pR] = music(6); for (let i = 3 * sr; i < 3.4 * sr; i++) { pL[i] *= 0.18; pR[i] *= 0.18; }+ const sd = at(pL, pR);+ ok(sd.stopDowns.length === 1 && Math.abs(sd.stopDowns[0].at - 3) < 0.1, `a 0.4 s, 15 dB dip reads as one stop-down at ${sd.stopDowns[0]?.at.toFixed(2)} s`);++ // the profile: ranges grade PASS / WARN / FAIL, and a built profile moves taste ranges but never the delivery limits+ ok(grade(-14, { min: -16, max: -13, tol: 1 }) === "PASS" && grade(-16.5, { min: -16, max: -13, tol: 1 }) === "WARN" && grade(-18, { min: -16, max: -13, tol: 1 }) === "FAIL" && grade(5, undefined) === "INFO", "grade: inside PASS, within tolerance WARN, beyond FAIL, no range INFO");+ const built = buildProfile("test", [{ file: "a", measures: clean }, { file: "b", measures: tgt }]), prof = profileFrom(built);+ ok(built.metrics.lufs.min <= built.metrics.lufs.median && built.metrics.lufs.median <= built.metrics.lufs.max && built.from.length === 2, `built profile: lufs ${built.metrics.lufs.min}..${built.metrics.lufs.max}, median ${built.metrics.lufs.median}`);+ ok(JSON.stringify(prof.ranges.endSilence) === JSON.stringify(DEFAULT_PROFILE.ranges.endSilence) && prof.ranges.lufs.min !== DEFAULT_PROFILE.ranges.lufs.min && prof.ranges.presence !== undefined, "a built profile sets the taste ranges (loudness, bands) and keeps the hard ones (end silence)");++ // picture against sound+ const changed = Array.from({ length: 300 }, (_, i) => (i === 30 || i === 120 || i === 210 ? 0.5 : 0.01));+ const ev = visualEvents(changed, 30);+ ok(ev.length === 3 && Math.abs(ev[0] - 1) < 1e-9, `three cuts in a slow-changing picture read as events at ${ev.map((e) => e.toFixed(2)).join(", ")} s`);+ const vs = visualSync([1, 4, 7], [1.03, 5.5, 6.95], 10);+ ok(Math.abs(vs.share - 2 / 3) < 1e-9 && vs.unanswered.length === 1 && vs.unanswered[0] === 4 && vs.medianOffsetMs === -10, `2 of 3 events have an onset within 100 ms (+30 and -50 ms, median ${vs.medianOffsetMs}); the one at 4 s has none`);+ ok(Number.isFinite(vs.chance) && vs.chance <= 2 / 3, `chance baseline from shifted events: ${Math.round(vs.chance * 100)} %`);++ // silence: everything fails cleanly, never NaN-passes+ const z = at(new Float32Array(sr * 2), new Float32Array(sr * 2)), zr = evaluate(z);+ ok(z.silent && zr.find((r) => r.key === "lufs")!.status === "FAIL" && zr.every((r) => r.status !== "PASS" || r.value !== null), "a silent file fails loudness and passes nothing it could not measure");+};diff --git a/skills/anidoodle/engine/tools/soundcheck.mjs b/skills/anidoodle/engine/tools/soundcheck.mjsnew file mode 100644index 0000000..48acb8c--- /dev/null+++ b/skills/anidoodle/engine/tools/soundcheck.mjs@@ -0,0 +1,109 @@+// SOUNDCHECK. A film-sound scorecard for an agent that cannot hear: every model-free number on a+// film's decoded mix, each held to a range, then the fixes in the order that matters, with times.+// node tools/soundcheck.mjs <film|file.mp4|file.wav> [--profile references/music/sound-profile.json]+// [--allow 3.1:3.6,...] [--video | --no-video] [--json] [--out f.json]+// node tools/soundcheck.mjs profile <files...> -o references/music/sound-profile.json [--name "drawing film"]+// Decodes what a player would (ffmpeg, stereo float at 48 kHz). The metrics are pure functions in+// src/canvas-core/music/soundcheck.ts (unit-tested on synthetic signals); visual sync reuses+// motion.mjs changedArea and is INFO only (not every picture change is meant to be a cue).+// Exit 1 on any FAIL, 2 on bad input.+import { build } from "esbuild";+import { execFileSync } from "node:child_process";+import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { basename, dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { changedArea } from "./motion.mjs";+import { isMain } from "./is-main.mjs";++const here = dirname(fileURLToPath(import.meta.url)), SR = 48000;+export const loadCheck = async () => {+ const r = await build({ entryPoints: [join(here, "../src/canvas-core/music/soundcheck.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"));+};+/** A film name is out/<name>.mp4, as the other tools read it. */+export const resolveInput = (a) => { const f = resolve(/\.[a-z0-9]{2,4}$/i.test(a) ? a : `out/${a}.mp4`); if (!existsSync(f)) throw new Error(`no such file: ${f}`); return f; };+export const probe = (file) => {+ const j = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,avg_frame_rate,width,height:format=duration", "-of", "json", file]).toString());+ const v = j.streams.find((s) => s.codec_type === "video" && s.width), a = j.streams.find((s) => s.codec_type === "audio");+ const [n, d] = (v?.avg_frame_rate ?? "0/1").split("/").map(Number);+ return { audio: !!a, video: v ? { width: v.width, height: v.height, fps: d ? n / d : 0 } : null, duration: Number(j.format?.duration) };+};+export const decode = (file) => {+ const buf = execFileSync("ffmpeg", ["-v", "error", "-i", file, "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ac", "2", "-ar", String(SR), "pipe:1"], { maxBuffer: 1 << 30 });+ const f = new Float32Array(buf.buffer, buf.byteOffset, buf.length / 4), n = f.length / 2, L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = f[2 * i]; R[i] = f[2 * i + 1]; }+ return [L, R];+};+export const parseAllow = (s) => (s ? String(s).split(",").filter(Boolean).map((p) => { const [a, b] = p.split(":").map(Number); if (!(b > a)) throw new Error(`--allow wants from:to seconds, got '${p}'`); return [a, b]; }) : []);+export const loadProfile = (C, path) => {+ if (!path) return C.DEFAULT_PROFILE;+ const j = JSON.parse(readFileSync(resolve(path), "utf8"));+ return j.metrics ? C.profileFrom(j) : { ...C.DEFAULT_PROFILE, ...j, ranges: { ...C.DEFAULT_PROFILE.ranges, ...(j.ranges ?? {}) } };+};++/** Everything for one file: measures, curves, visual sync (when there is a picture and `video`), rows and the fix list. */+export const check = async (C, file, { profile, allow = [], video = "auto" } = {}) => {+ const p = probe(file);+ if (!p.audio) throw new Error(`${basename(file)} has no audio stream`);+ const [L, R] = decode(file), prof = profile ?? C.DEFAULT_PROFILE;+ const { measures, curves } = C.analyze(L, R, SR, { allow: [...allow, ...(prof.allow ?? [])] });+ let sync = null;+ if (p.video && video !== false && p.video.fps > 0) {+ const W = 160, H = Math.max(2, Math.round((W * p.video.height) / p.video.width)), changed = await changedArea(file, W, H, 4);+ const events = C.visualEvents(changed, p.video.fps);+ sync = { ...C.visualSync(events, curves.onsets, measures.durationS), times: events, fps: p.video.fps };+ }+ const rows = C.evaluate(measures, prof);+ return { file, profile: prof.name, measures, curves, sync, rows, fixes: C.fixFirst(rows), video: p.video, L, R };+};++const pad = (s, n) => String(s).padEnd(n);+export const report = (C, r) => {+ const m = r.measures, fails = r.rows.filter((x) => x.status === "FAIL").length, warns = r.rows.filter((x) => x.status === "WARN").length;+ const o = [`SOUNDCHECK ${r.file}`, ` ${m.durationS.toFixed(2)} s, profile: ${r.profile}`, ""];+ const head = !fails && !warns ? "Sound is within every range." : `${fails} fail, ${warns} warn. ${r.fixes[0] ? `Worst: ${r.fixes[0].fix.split(":")[0]}.` : ""}`;+ o.push(` ${head}`, "", ` ${pad("status", 7)}${pad("metric", 31)}${pad("value", 24)}range`);+ const graded = r.rows.filter((x) => x.status !== "INFO"), info = r.rows.filter((x) => x.status === "INFO");+ for (const x of [...graded, ...info]) o.push(` ${pad(x.status, 7)}${pad(x.label, 31)}${pad(x.text, 24)}${C.rangeText(x.range)}`);+ if (r.sync) {+ const s = r.sync, pct = (v) => (Number.isFinite(v) ? `${Math.round(v * 100)} %` : "n/a");+ o.push(` ${pad("INFO", 7)}${pad("visual events with an onset", 31)}${pad(`${pct(s.share)} of ${s.events}`, 24)}chance ${pct(s.chance)}`);+ o.push(` ${pad("INFO", 7)}${pad("median onset offset", 31)}${pad(Number.isFinite(s.medianOffsetMs) ? `${s.medianOffsetMs > 0 ? "+" : ""}${s.medianOffsetMs} ms` : "n/a", 24)}pros: -45..+75 ms`);+ if (s.unanswered.length) o.push(` ${pad("INFO", 7)}${pad("events with no sound", 31)}${s.unanswered.slice(0, 8).map(C.fmtT).join(", ")}${s.unanswered.length > 8 ? ` (+${s.unanswered.length - 8})` : ""}`);+ }+ o.push("", r.fixes.length ? "FIX FIRST" : "FIX FIRST: nothing");+ r.fixes.forEach((x, i) => o.push(` ${i + 1}. [${x.status}] ${x.fix}`));+ o.push("", "DETAIL", ` arc (LU vs integrated, 0..100 %): ${m.arc.map((v) => (v === null ? "silent" : (v > 0 ? "+" : "") + v.toFixed(1))).join(" ")}`);+ o.push(` bands (dB share): ${Object.entries(m.bands).map(([k, v]) => `${k} ${v.toFixed(1)}`).join(" ")}`);+ o.push(` band correlation: ${Object.entries(m.bandCorr).map(([k, v]) => `${k} ${Number.isFinite(v) ? v.toFixed(2) : "n/a"}`).join(" ")} 150-2k ${Number.isFinite(m.bodyCorr) ? m.bodyCorr.toFixed(2) : "n/a"}`);+ o.push(` mono fold: -${m.monoDrop.toFixed(1)} dB (3.0 expected) sample peak ${m.samplePeak.toFixed(1)} dBFS`);+ const holes = m.gaps.filter((g) => g.len >= 0.1); if (holes.length) o.push(` holes: ${holes.map((g) => `${C.fmtT(g.at)} ${g.len.toFixed(2)} s${g.allowed ? " (allowed)" : ""}`).join(", ")}`);+ o.push("", `VERDICT: ${fails ? "FAIL" : warns ? "PASS with warnings" : "PASS"}`);+ return o.join("\n");+};+/** The JSON form: no sample buffers, curves trimmed to what a reader can use. */+export const asJson = (r) => ({ file: r.file, profile: r.profile, verdict: r.rows.some((x) => x.status === "FAIL") ? "FAIL" : "PASS", measures: r.measures, sync: r.sync, rows: r.rows, fixes: r.fixes.map((x) => ({ key: x.key, status: x.status, fix: x.fix, at: x.at })), onsets: r.curves.onsets.map((t) => +t.toFixed(3)), hits: r.curves.hits });++if (isMain(import.meta.url)) {+ const argv = process.argv.slice(2), flag = (k) => argv.includes(`--${k}`), opt = (...ks) => { for (const k of ks) { const i = argv.indexOf(k); if (i >= 0) return argv[i + 1]; } return undefined; };+ const VAL = new Set(["--profile", "--out", "--allow", "-o", "--name"]), pos = argv.filter((a, i) => !a.startsWith("-") && !VAL.has(argv[i - 1]));+ const die = (msg, code = 2) => { console.error(msg); process.exit(code); };+ if (!pos.length) die("usage: node tools/soundcheck.mjs <film|file.mp4|file.wav> [--profile p.json] [--allow a:b] [--video|--no-video] [--json] [--out f.json]\n node tools/soundcheck.mjs profile <files...> -o references/music/sound-profile.json [--name \"drawing film\"]");+ const C = await loadCheck();+ try {+ if (pos[0] === "profile") {+ const out = opt("-o", "--out"); if (!out || pos.length < 2) die("profile wants films and -o <path.json>");+ const sets = [];+ for (const a of pos.slice(1)) { const f = resolveInput(a), [L, R] = decode(f); sets.push({ file: basename(f), measures: C.analyze(L, R, SR).measures }); console.log(` measured ${basename(f)}`); }+ const p = C.buildProfile(opt("--name") ?? "picked films", sets);+ mkdirSync(dirname(resolve(out)), { recursive: true }); writeFileSync(resolve(out), JSON.stringify(p, null, 1) + "\n");+ console.log(`profile of ${sets.length} film(s) -> ${out}`); for (const [k, v] of Object.entries(p.metrics)) console.log(` ${pad(k, 12)} ${v.min} .. ${v.max} median ${v.median}`);+ process.exit(0);+ }+ const file = resolveInput(pos[0]), r = await check(C, file, { profile: loadProfile(C, opt("--profile")), allow: parseAllow(opt("--allow")), video: flag("no-video") ? false : "auto" });+ const j = asJson(r);+ if (opt("--out")) { mkdirSync(dirname(resolve(opt("--out"))), { recursive: true }); writeFileSync(resolve(opt("--out")), JSON.stringify(j, null, 1) + "\n"); }+ console.log(flag("json") ? JSON.stringify(j, null, 1) : report(C, r));+ process.exit(j.verdict === "FAIL" ? 1 : 0);+ } catch (e) { die(`soundcheck: ${e.message}`); }+}diff --git a/skills/anidoodle/engine/tools/soundsheet.mjs b/skills/anidoodle/engine/tools/soundsheet.mjsnew file mode 100644index 0000000..1cfed57--- /dev/null+++ b/skills/anidoodle/engine/tools/soundsheet.mjs@@ -0,0 +1,103 @@+// SOUNDSHEET. A listening sheet for an agent that cannot hear: one PNG on one time axis with the+// picture (a frame strip), the spectrogram, the waveform, momentary and short-term loudness against+// the integrated level and the -14 LUFS target, onset ticks, salient hits, visual events, and every+// hole and the dead tail shaded. The hole, the dead tail and a late hit are visible before anyone+// listens. Same analysis as soundcheck.mjs (its verdict and first fixes head the sheet).+// node tools/soundsheet.mjs <film|file.mp4|file.wav> -o out/<name>-sound.png [--profile p.json] [--allow a:b] [--width 1600]+import { execFileSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, mkdirSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { basename, dirname, join, resolve } from "node:path";+import { detect } from "./detect.mjs";+import { loadCheck, resolveInput, check, loadProfile, parseAllow } from "./soundcheck.mjs";++const argv = process.argv.slice(2), opt = (...ks) => { for (const k of ks) { const i = argv.indexOf(k); if (i >= 0) return argv[i + 1]; } return undefined; };+const VAL = new Set(["-o", "--out", "--profile", "--allow", "--width"]), pos = argv.filter((a, i) => !a.startsWith("-") && !VAL.has(argv[i - 1]));+const die = (m) => { console.error(m); process.exit(2); };+if (!pos[0]) die("usage: node tools/soundsheet.mjs <film|file.mp4|file.wav> -o out/<name>-sound.png [--profile p.json] [--allow a:b] [--width 1600]");+const env = detect();+if (!env.pw.ok || !env.browser.ok) die(`no browser to draw the sheet in.\n playwright: ${env.report.playwright}\n browser: ${env.report.browser}\n fix: npm install, then npx playwright-core install chromium`);++let file; try { file = resolveInput(pos[0]); } catch (e) { die(e.message); }+const out = resolve(opt("-o", "--out") ?? `out/${basename(file).replace(/\.[^.]+$/, "")}-sound.png`);+const WIDTH = Number(opt("--width") ?? 1600), LEFT = 92, RIGHT = 24, PW = WIDTH - LEFT - RIGHT;+const C = await loadCheck(), r = await check(C, file, { profile: loadProfile(C, opt("--profile")), allow: parseAllow(opt("--allow")) });+const m = r.measures, dur = m.durationS, tmp = mkdtempSync(join(tmpdir(), "soundsheet-"));+const png64 = (f) => "data:image/png;base64," + readFileSync(f).toString("base64");+try {+ // the picture: ten frames, each at the middle of its tenth, so tile k sits over its own stretch of the axis+ let strip = null;+ if (r.video) {+ const K = 10, tw = Math.floor(PW / K), th = Math.max(2, 2 * Math.round((tw * r.video.height) / r.video.width / 2));+ execFileSync("ffmpeg", ["-v", "error", "-y", "-ss", String(dur / K / 2), "-i", file, "-vf", `fps=${K / dur},scale=${tw}:${th},tile=${K}x1`, "-frames:v", "1", join(tmp, "strip.png")]);+ strip = { src: png64(join(tmp, "strip.png")), w: tw * K, h: th };+ }+ // the spectrogram from ffmpeg, log frequency, both channels combined; drawn across the whole duration+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", file, "-lavfi", `showspectrumpic=s=${PW}x240:legend=0:mode=combined:fscale=log:scale=log:color=intensity:gain=2`, "-frames:v", "1", join(tmp, "spec.png")]);+ // waveform envelope: min/max of the mid per pixel column+ const env_ = []; const n = r.L.length, per = n / PW;+ for (let x = 0; x < PW; x++) { let lo = 0, hi = 0; for (let i = Math.floor(x * per); i < Math.min(n, Math.floor((x + 1) * per)); i++) { const v = 0.5 * (r.L[i] + r.R[i]); if (v < lo) lo = v; if (v > hi) hi = v; } env_.push([+lo.toFixed(4), +hi.toFixed(4)]); }+ const fails = r.rows.filter((x) => x.status === "FAIL").length, warns = r.rows.filter((x) => x.status === "WARN").length;+ const data = {+ title: basename(file), dur, I: m.lufs, verdict: fails ? `FAIL: ${fails} fail, ${warns} warn` : warns ? `PASS with ${warns} warning${warns > 1 ? "s" : ""}` : "PASS",+ stats: `${m.lufs.toFixed(1)} LUFS · LRA ${m.lra.toFixed(1)} LU · ${m.truePeak.toFixed(1)} dBTP · 150-2k corr ${Number.isFinite(m.bodyCorr) ? m.bodyCorr.toFixed(2) : "n/a"} · sub ${m.bands.sub.toFixed(1)} dB`,+ fixes: r.fixes.slice(0, 4).map((x) => `${x.status} ${x.fix}`),+ strip, spec: png64(join(tmp, "spec.png")), env: env_,+ momentary: r.curves.momentary.map((v, i) => [i * r.curves.hopS + 0.2, v]), shortTerm: r.curves.shortTerm.map((v, i) => [i * r.curves.hopS + 1.5, v]),+ onsets: r.curves.onsets, hits: r.curves.hits, events: r.sync?.times ?? [], unanswered: r.sync?.unanswered ?? [],+ shade: [...m.gaps.filter((g) => g.len >= 0.1).map((g) => ({ a: g.at, b: g.at + g.len, label: g.allowed ? "allowed hole" : `hole ${g.len.toFixed(1)} s` })), ...(m.endSilence >= 0.1 ? [{ a: m.endSilenceFrom, b: dur, label: `dead tail ${m.endSilence.toFixed(1)} s` }] : []), ...(m.firstSound && m.firstSound >= 0.1 ? [{ a: 0, b: m.firstSound, label: "before body level" }] : [])],+ LEFT, PW, WIDTH,+ };+ const html = `<!doctype html><html><head><meta charset="utf-8"><style>+ :root { --ink: #1d1b18; --paper: #f7f5f0; --line: #d9d4ca; --fail: #c0392b; --warn: #b9770e; --accent: #ca4901; --blue: #2c6e9b; }+ * { margin: 0; box-sizing: border-box; } body { background: var(--paper); color: var(--ink); font-family: Poppins, "Helvetica Neue", Arial, sans-serif; width: ${WIDTH}px; }+ header { padding: 22px ${RIGHT}px 12px ${LEFT}px; } h1 { font-size: 22px; font-weight: 600; } .v { font-size: 15px; font-weight: 600; margin-top: 4px; } .s { font-size: 13px; margin-top: 2px; }+ ol { margin: 8px 0 0 18px; font-size: 13px; line-height: 1.45; } canvas { display: block; }+ </style></head><body><header><h1></h1><div class="v"></div><div class="s"></div><ol></ol></header><canvas id="c"></canvas>+ <script>+ const D = ${JSON.stringify(data)};+ document.querySelector("h1").textContent = D.title; const v = document.querySelector(".v"); v.textContent = D.verdict; v.style.color = D.verdict.startsWith("FAIL") ? "var(--fail)" : D.verdict.includes("warn") ? "var(--warn)" : "#1e7d4f";+ document.querySelector(".s").textContent = D.stats; for (const f of D.fixes) { const li = document.createElement("li"); li.textContent = f; document.querySelector("ol").appendChild(li); }+ const css = (k) => getComputedStyle(document.documentElement).getPropertyValue(k).trim();+ const load = (src) => new Promise((ok) => { if (!src) return ok(null); const i = new Image(); i.onload = () => ok(i); i.src = src; });+ Promise.all([load(D.strip && D.strip.src), load(D.spec), document.fonts.ready]).then(([strip, spec]) => {+ const rows = [["picture", strip ? D.strip.h : 0], ["spectrogram", 240], ["waveform", 130], ["loudness", 210], ["onsets / hits / picture", 64]].filter((r) => r[1]);+ const GAP = 14, H = rows.reduce((a, r) => a + r[1] + GAP, 0) + 40, cv = document.getElementById("c"); cv.width = D.WIDTH; cv.height = H;+ const g = cv.getContext("2d"), X = (t) => D.LEFT + (t / D.dur) * D.PW; let y = 4; const top = {};+ g.font = "500 12px Poppins, Arial, sans-serif"; g.textBaseline = "middle";+ for (const [name, h] of rows) { top[name] = [y, h]; g.fillStyle = css("--ink"); g.textAlign = "right"; g.fillText(name === "onsets / hits / picture" ? "onsets" : name, D.LEFT - 10, name === "onsets / hits / picture" ? y + h / 6 : y + h / 2); if (name === "spectrogram") { g.font = "10px Poppins, Arial, sans-serif"; g.fillText("log Hz", D.LEFT - 10, y + h / 2 + 16); g.font = "500 12px Poppins, Arial, sans-serif"; } g.strokeStyle = css("--line"); g.strokeRect(D.LEFT + 0.5, y + 0.5, D.PW - 1, h - 1); y += h + GAP; }+ const bottom = y - GAP;+ // shading first, through every panel: holes, the dead tail, the silent start+ for (const s of D.shade) { g.fillStyle = "rgba(192,57,43,0.13)"; g.fillRect(X(s.a), 4, Math.max(2, X(s.b) - X(s.a)), bottom - 4); g.fillStyle = css("--fail"); g.textAlign = "left"; g.fillText(s.label, Math.min(X(s.a) + 4, D.LEFT + D.PW - g.measureText(s.label).width), bottom + 12); }+ if (strip) { const [t, h] = top.picture; g.drawImage(strip, D.LEFT, t, D.strip.w, h); }+ { const [t, h] = top.spectrogram; g.drawImage(spec, D.LEFT, t, D.PW, h); }+ { const [t, h] = top.waveform, mid = t + h / 2; g.fillStyle = css("--blue"); D.env.forEach(([lo, hi], x) => g.fillRect(D.LEFT + x, mid - hi * h / 2, 1, Math.max(1, (hi - lo) * h / 2))); }+ { const [t, h] = top.loudness, lo = -60, hi = 0, Y = (l) => t + h - ((Math.max(lo, Math.min(hi, l)) - lo) / (hi - lo)) * h;+ g.textAlign = "right"; g.fillStyle = css("--ink"); g.font = "11px Poppins, Arial, sans-serif";+ for (const l of [-50, -40, -30, -20, -10]) { g.strokeStyle = css("--line"); g.beginPath(); g.moveTo(D.LEFT, Y(l)); g.lineTo(D.LEFT + D.PW, Y(l)); g.stroke(); g.fillText(String(l), D.LEFT + D.PW - 4, Y(l) - 7); }+ g.setLineDash([6, 4]); g.strokeStyle = css("--accent"); g.beginPath(); g.moveTo(D.LEFT, Y(-14)); g.lineTo(D.LEFT + D.PW, Y(-14)); g.stroke(); g.textAlign = "left"; g.fillStyle = css("--accent"); g.fillText("target -14", D.LEFT + 6, Y(-14) - 8);+ if (D.I > -70) { g.strokeStyle = css("--ink"); g.beginPath(); g.moveTo(D.LEFT, Y(D.I)); g.lineTo(D.LEFT + D.PW, Y(D.I)); g.stroke(); g.fillStyle = css("--ink"); g.fillText("integrated " + D.I.toFixed(1), D.LEFT + 90, Y(D.I) - 8); }+ g.setLineDash([]);+ const curve = (pts, col, w) => { g.strokeStyle = col; g.lineWidth = w; g.beginPath(); let pen = false; for (const [tt, l] of pts) { if (!(l > -70)) { pen = false; continue; } pen ? g.lineTo(X(tt), Y(l)) : g.moveTo(X(tt), Y(l)); pen = true; } g.stroke(); g.lineWidth = 1; };+ curve(D.momentary, "rgba(44,110,155,0.55)", 1); curve(D.shortTerm, css("--ink"), 2);+ g.fillStyle = css("--ink"); g.textAlign = "left"; g.fillText("momentary (thin), short-term (thick), LUFS", D.LEFT + 6, t + 12); }+ { const [t, h] = top["onsets / hits / picture"], third = h / 3;+ g.strokeStyle = css("--ink"); for (const o of D.onsets) { g.beginPath(); g.moveTo(X(o) + 0.5, t + 2); g.lineTo(X(o) + 0.5, t + third); g.stroke(); }+ g.fillStyle = css("--accent"); for (const o of D.hits) { g.beginPath(); g.arc(X(o), t + third * 1.5, 4, 0, 7); g.fill(); }+ for (const e of D.events) { const miss = D.unanswered.includes(e); g.strokeStyle = miss ? css("--fail") : "#1e7d4f"; g.lineWidth = 2; g.beginPath(); g.moveTo(X(e), t + third * 2 + 2); g.lineTo(X(e), t + h - 2); g.stroke(); g.lineWidth = 1;+ g.strokeStyle = miss ? "rgba(192,57,43,0.35)" : "rgba(30,125,79,0.3)"; g.setLineDash([2, 3]); g.beginPath(); g.moveTo(X(e), 4); g.lineTo(X(e), t); g.stroke(); g.setLineDash([]); }+ g.font = "10px Poppins, Arial, sans-serif"; g.fillStyle = css("--ink"); g.textAlign = "right"; g.fillText("hits", D.LEFT - 10, t + third * 1.5); g.fillText("picture events", D.LEFT - 10, t + third * 2.5); }+ // the time axis+ g.font = "11px Poppins, Arial, sans-serif"; g.fillStyle = css("--ink"); g.textAlign = "center"; const step = D.dur > 40 ? 5 : D.dur > 12 ? 2 : 1;+ for (let s = 0; s <= D.dur + 1e-6; s += step) g.fillText(Math.floor(s / 60) + ":" + String(s % 60).padStart(2, "0"), X(s), bottom + 28);+ document.body.dataset.done = "1";+ });+ </script></body></html>`;+ const browser = await env.pw.lib.chromium.launch({ executablePath: env.browser.executablePath });+ try {+ const page = await browser.newPage({ viewport: { width: WIDTH, height: 600 }, deviceScaleFactor: 1 });+ await page.setContent(html); await page.waitForSelector("body[data-done]", { timeout: 20000 });+ mkdirSync(dirname(out), { recursive: true }); await page.screenshot({ path: out, fullPage: true });+ } finally { await browser.close(); }+ console.log(`${out}\n ${data.verdict} ${data.stats}`);+} finally { rmSync(tmp, { recursive: true, force: true }); }diff --git a/skills/anidoodle/references/music/README.md b/skills/anidoodle/references/music/README.mdindex ddca2be..e702fbb 100644--- a/skills/anidoodle/references/music/README.md+++ b/skills/anidoodle/references/music/README.md@@ -11,6 +11,7 @@ without the pack, is synthesized in code exactly as before. See[Recorded instruments](#recorded-instruments-the-optional-sound-pack) below.Code: `engine/src/canvas-core/music/`. Tools: `engine/tools/music.mjs`, `engine/tools/soundfetch.mjs`.+To check a finished film's sound: `engine/tools/soundcheck.mjs` and `soundsheet.mjs` ([how](sound-design.md#checking-the-finished-films-sound)).**Start here: [`compose.md`](compose.md).** It takes you from a brief to an original score. A styleis a vocabulary: sound, grooves, harmony language, melody rules, arrangement grammar. It is neverdiff --git a/skills/anidoodle/references/music/sound-design.md b/skills/anidoodle/references/music/sound-design.mdindex 5cdf9b6..c63ef50 100644--- a/skills/anidoodle/references/music/sound-design.md+++ b/skills/anidoodle/references/music/sound-design.md@@ -121,6 +121,52 @@ music, and its test only checked that they existed.)- Hear it in context before it ships. Render the kit page (`node tools/sfx.mjs kit <dir>`) and ademo over the real score, and check the audibility table.+## Checking the finished film's sound++You cannot hear the film, so measure the delivered mix before anyone listens. Two tools read the+rendered file (a film name means `out/<name>.mp4`; a `.wav` or `.m4a` works too):++```+node tools/soundcheck.mjs <film|file> # the scorecard; exit 1 on any FAIL+node tools/soundcheck.mjs <film> --json --out x.json # the same, as data+node tools/soundcheck.mjs <film> --allow 3.1:3.6 # a hole there is a declared stop-down+node tools/soundsheet.mjs <film> -o out/<film>-sound.png # one picture of it all+```++`soundcheck` prints a status for every metric (PASS, WARN, FAIL against a range, or INFO), then a+**FIX FIRST** list in the order that matters, each with its time and the concrete fix: "3.4 s hole+at 0:03.4", "boxy: cut 500-790 Hz by 2-3 dB", "mids decorrelated: narrow the stereo width below+2 kHz". It measures:++- level: integrated LUFS, true peak, loudness range, loudest 3 s, intro and end level, an+ 11-point arc, the loudest moment;+- shape: first sound, holes inside the film, dead air at the end, fade, the final moment, a cut+ ending, onsets, salient hits, stop-downs;+- spectrum: six band shares (sub 20-60 Hz up to air 8-16 kHz) and the centroid;+- stereo: side vs mid, L/R correlation overall and per band (150 Hz-2 kHz is where phones comb+ the body away), and how much more than the expected 3 dB the mix loses folded to mono;+- picture (any file with video): frame-difference events, the share with an onset within 100 ms+ against a chance baseline, the events with no sound, and the median onset offset. INFO only:+ not every picture change is meant to be a cue.++The built-in ranges are for drawing films: -16 to -13 LUFS (web target -14, gentle films -16),+true peak at or under -1 dBTP, LRA at most 9 LU, sound by 0.5 s, no hole over 0.25 s, at most+0.5 s of silence at the end, 150 Hz-2 kHz correlation at least 0.3, at most 1.5 dB of extra mono+loss, and the sub at or under -6 dB of the energy.++To grade against films the user loves, build a profile from them:+`node tools/soundcheck.mjs profile <films...> -o references/music/sound-profile.json`, then pass+`--profile references/music/sound-profile.json`. A profile moves the taste ranges (loudness,+bands, width); the delivery limits (true peak, first sound, holes, end silence, mono loss) stay.++`soundsheet` draws a frame strip, the spectrogram, the waveform, momentary and short-term+loudness against the integrated level and -14, onset ticks, hits and picture events (red when no+sound answers them), with every hole and the dead tail shaded. Read it before handing the film+over: the hole, the dead tail and a late hit are visible in it.++The metrics live in `engine/src/canvas-core/music/soundcheck.ts`, tested on synthetic faults in+`engine/test/soundcheck.test.ts`.+## Tools and checks```@@ -128,6 +174,7 @@ node tools/sfx.mjs list # kinds, variants, levels,node tools/sfx.mjs one whoosh soft 3 out.mp3 # one soundnode tools/sfx.mjs kit <dir> # every variant x3 + demo + page + meters.json + spectra/node tools/sfx.mjs test # the gate+node tools/soundcheck.mjs <film> # the finished film's sound (see above)```The test checks every kind and variant for:diff --git a/skills/anidoodle/references/workflows/review.md b/skills/anidoodle/references/workflows/review.mdindex 8f95c12..81b1a89 100644--- a/skills/anidoodle/references/workflows/review.md+++ b/skills/anidoodle/references/workflows/review.md@@ -18,7 +18,7 @@ Freeze a copy of the file and note its hash first. Every reading is of that copy| **Director** | the contact sheet at one tile per beat, sound off; then each seam as a before/after pair | Whether someone who has never seen the brief could say what the film is about, and feel the payoff. | point, first second, pacing, seams || **Illustrator** | full-size stills of the hardest frames; crops of faces, hands, feet and joins at `--scale 2` | Whether a proud illustrator would sign it, or it is shapes assembled (`craft-bar.md`). | drawing, style || **Motion and finish** | `popscan.mjs`, `gate.mjs`, strips of consecutive frames across every seam and every fast move | Whether anything pops, stalls, jumps or smears that was not meant to. | motion, finish |-| **Sound and sync** | `music.mjs check` (with its ARC line), `verify-export.mjs`, the cue table against the picture | Whether the sound is one piece with a shape, and lands on the picture. | sound |+| **Sound and sync** | `music.mjs check` (with its ARC line), `verify-export.mjs`, `soundcheck.mjs` and its `soundsheet.mjs` picture, the cue table against the picture | Whether the sound is one piece with a shape, and lands on the picture. | sound |Rules that make a reading worth having: