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.

feat(render): --poster-frame N/--poster-fade for the platform thumbnail; page-side bake store + poster; verify-export audio/duration/peak checks, --frame N, --delivery thumbnail guard, --width refused on MP4

Alex Greenshpunecc19eb321ef
diff --git a/skills/anidoodle/engine/src/hosts/page.ts b/skills/anidoodle/engine/src/hosts/page.ts
index 5c216ea..0d4f726 100644
--- a/skills/anidoodle/engine/src/hosts/page.ts
+++ b/skills/anidoodle/engine/src/hosts/page.ts
@@ -4,15 +4,40 @@
import type { Ctx, Env, Layer } from "../canvas-core/core";
import { Film, renderFrame, validate } from "../canvas-core/film";
-declare global { interface Window { FILM: unknown; __ASSETS__?: Record<string, string> } }
+declare global { interface Window { FILM: unknown; __ASSETS__?: Record<string, string>; __BAKE_SRC__?: Record<string, string>; __ANIDOODLE_SRC__?: WeakMap<object, string> } }
+
+// THE BAKE STORE (Env.bake). A finished plate frame, keyed by the hash of the source that draws it
+// (build-page.mjs hashes each film module's whole import closure, plus the engine's own renderer),
+// the frame and the pixel size. The adapter loads matching PNGs from disk before frame 0 and saves
+// the fresh ones after; the page never touches a file. Only fully opaque frames are kept, because
+// only those survive a PNG round trip bit for bit.
+const bakeStore = () => {
+ const loaded = new Map<string, HTMLImageElement>(), fresh = new Map<string, HTMLCanvasElement>(), stats = { hits: 0, misses: 0, kept: 0, skipped: 0 };
+ let on = false; // off until an adapter loads the store: a shipped player keeps no copies
+ const keyOf = (film: object, frame: number, w: number, h: number) => { const mod = window.__ANIDOODLE_SRC__?.get(film), hash = mod ? window.__BAKE_SRC__?.[mod] : undefined; return hash ? `${hash}.${frame}.${w}x${h}` : null; };
+ const bake: NonNullable<Env["bake"]> = {
+ get: (film, frame, w, h) => { if (!on) return undefined; const k = keyOf(film, frame, w, h), img = k ? loaded.get(k) : undefined; if (img) stats.hits++; else stats.misses++; return img; },
+ put: (film, frame, layer) => {
+ if (!on) return;
+ const { width: w, height: h } = layer.canvas, k = keyOf(film, frame, w, h); if (!k || loaded.has(k) || fresh.has(k)) return;
+ const d = layer.ctx.getImageData(0, 0, w, h).data; for (let i = 3; i < d.length; i += 4) if (d[i] !== 255) { stats.skipped++; return; }
+ const c = document.createElement("canvas"); c.width = w; c.height = h; c.getContext("2d")!.drawImage(layer.canvas, 0, 0); fresh.set(k, c); stats.kept++;
+ },
+ };
+ const load = async (entries: Record<string, string>) => { on = true; await Promise.all(Object.entries(entries).map(async ([k, b64]) => { const img = new Image(); img.src = "data:image/png;base64," + b64; try { await img.decode(); if (`${img.naturalWidth}x${img.naturalHeight}` === k.split(".").pop()) loaded.set(k, img); } catch { /* unreadable: draw it cold */ } })); return loaded.size; };
+ const take = () => { const out: Record<string, string> = {}; for (const [k, c] of fresh) out[k] = c.toDataURL("image/png").slice(22); fresh.clear(); return out; };
+ const hashes = () => [...new Set(Object.values(window.__BAKE_SRC__ ?? {}))];
+ return { bake, load, take, hashes, stats };
+};
export const mountFilm = (film: Film) => {
const canvas = document.getElementById("film") as HTMLCanvasElement, images = new Map<string, CanvasImageSource>();
let env: Env, ctx: Ctx, current = 0;
+ const bakes = bakeStore();
// Safari before 16.4 has no 2D OffscreenCanvas: fall back to a detached <canvas>. The core cannot tell the difference.
const opts = film.meta.raster === "cpu" ? { willReadFrequently: true } : undefined; // see Film.meta.raster
const surface = (w: number, h: number): Layer => { const c = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(w, h) : Object.assign(document.createElement("canvas"), { width: w, height: h }); return { canvas: c, ctx: c.getContext("2d", opts) as unknown as Ctx } as Layer; };
- const mount = (scale = 1) => { canvas.width = Math.round(film.meta.W * scale); canvas.height = Math.round(film.meta.H * scale); ctx = canvas.getContext("2d", opts) as CanvasRenderingContext2D; env = { W: film.meta.W, H: film.meta.H, scale, cache: new Map(), canvas: surface, image: (n) => images.get(n) }; return film.meta; };
+ const mount = (scale = 1) => { canvas.width = Math.round(film.meta.W * scale); canvas.height = Math.round(film.meta.H * scale); ctx = canvas.getContext("2d", opts) as CanvasRenderingContext2D; env = { W: film.meta.W, H: film.meta.H, scale, cache: new Map(), canvas: surface, image: (n) => images.get(n), bake: bakes.bake }; return film.meta; };
// contract rule 4: every asset is loaded AND decoded before frame 0, or the film refuses to start
const ready = (async () => {
const problems = validate(film); if (problems.length) throw new Error("timeline: " + problems.join("; "));
@@ -55,7 +80,22 @@ export const mountFilm = (film: Film) => {
};
const audio = (sr: number) => { if (!film.audio) return null; const [L, R] = film.audio(sr); if (L.length !== R.length) throw new Error("audio channels have different lengths"); const pcm = new Float32Array(L.length * 2); for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; } return { sampleRate: sr, frames: L.length, float32: b64(new Uint8Array(pcm.buffer)) }; };
const warm = () => film.shots.forEach((s) => { seek(s.start); seek(s.start + ((s.end - s.start) >> 1)); }); // first + middle frame of every shot: builds tiles, pre-allocates the layer pool
- window.FILM = { meta: { ...film.meta, shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };
+ // POSTER. Platforms show frame 0 as the thumbnail, so a delivery may open on a chosen frame (the
+ // wall of styles, the logo) and dissolve into the film's real opening over `fade` frames. The
+ // poster frame is drawn once into its own surface; frame n < fade is the real frame n with the
+ // poster laid over it at 1 - n/fade. Frame 0 IS the poster. Nothing else changes, not the score.
+ let posterOf: { key: string; img: CanvasImageSource } | null = null;
+ const poster = (frame: number, posterFrame: number, fade: number, samples = 1) => {
+ const n = Math.round(frame), u = fade > 0 ? 1 - n / fade : n === 0 ? 1 : 0, key = `${posterFrame}/${samples}/${canvas.width}x${canvas.height}`;
+ if (u > 0 && posterOf?.key !== key) {
+ samples > 1 ? blur(posterFrame, samples) : seek(posterFrame);
+ const c = document.createElement("canvas"); c.width = canvas.width; c.height = canvas.height; c.getContext("2d")!.drawImage(canvas, 0, 0); posterOf = { key, img: c };
+ }
+ const r = samples > 1 ? blur(n, samples) : seek(n);
+ if (u > 0 && posterOf) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = Math.min(1, u); ctx.globalCompositeOperation = "source-over"; if (u >= 1) ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(posterOf.img, 0, 0); ctx.restore(); }
+ current = n; return r;
+ };
+ window.FILM = { meta: { ...film.meta, hasAudio: typeof film.audio === "function", shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, poster, bakes: { load: bakes.load, take: bakes.take, hashes: bakes.hashes, stats: () => bakes.stats }, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };
// ---- the player: click or space to play, arrows to step, ?frame=N to open on a frame
ready.then(() => {
diff --git a/skills/anidoodle/engine/tools/adapters/playwright.mjs b/skills/anidoodle/engine/tools/adapters/playwright.mjs
index 110fbb7..be46717 100644
--- a/skills/anidoodle/engine/tools/adapters/playwright.mjs
+++ b/skills/anidoodle/engine/tools/adapters/playwright.mjs
@@ -2,25 +2,33 @@
// canvas pixels. Frame accuracy comes from the pull model (frame N is a pure function of N),
// not from anything Playwright does.
import { pathToFileURL } from "node:url";
+import { bakeCacheOn, loadBakes, saveBakes } from "../bake-cache.mjs";
export const name = "playwright";
-export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workers = 1 } = {}) => {
+// bakeCache (default on): finished plate frames come from and go to .cache/bakes (see bake-cache.mjs)
+export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workers = 1, bakeCache } = {}) => {
const browser = await pw.lib.chromium.launch({ executablePath: found.executablePath, args: ["--disable-background-timer-throttling"] });
+ const useBakes = bakeCacheOn(bakeCache), bv = browser.version(); let loadedBakes = 0;
const context = await browser.newContext({ viewport: { width: 640, height: 640 }, deviceScaleFactor: 1 });
const pages = [];
- for (let i = 0; i < workers; i++) { const page = await context.newPage(); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.goto(pathToFileURL(pagePath).href + "?adapter=playwright"); await page.evaluate(async (s) => { await window.FILM.ready; window.FILM.mount(s); window.FILM.warm(); }, scale); /* warm = build texture tiles once, outside the timed frames */ if (errors.length) throw new Error("page failed: " + errors.join("; ")); pages.push(page); }
+ for (let i = 0; i < workers; i++) { const page = await context.newPage(); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.goto(pathToFileURL(pagePath).href + "?adapter=playwright"); await page.evaluate(async (s) => { await window.FILM.ready; window.FILM.mount(s); }, scale); if (useBakes) loadedBakes = await loadBakes(page, bv); await page.evaluate(() => window.FILM.warm()); /* warm = build texture tiles once, outside the timed frames */ if (errors.length) throw new Error("page failed: " + errors.join("; ")); pages.push(page); }
const pick = (n) => pages[n % pages.length];
return {
workers: pages.length,
+ bakes: () => ({ on: useBakes, loaded: loadedBakes }),
info: () => pages[0].evaluate(() => window.FILM.meta),
// -> { png: Buffer, shot, drawMs, captureMs }
frame: async (n, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate((f) => { const s = window.FILM.seek(f); const t = performance.now(); const png = window.FILM.png(); return { ...s, png, enc: performance.now() - t }; }, n); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },
hash: (n, w = 0) => pick(w).evaluate((f) => { window.FILM.seek(f); return window.FILM.hash(); }, n),
// motion-blurred frame: `samples` subframes averaged in the page (see hosts/page.ts blur)
blur: async (n, samples, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, s]) => { const r = window.FILM.blur(f, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },
+ // a frame of the poster dissolve (see hosts/page.ts poster): frame n with poster frame p over it
+ poster: async (n, p, fade, samples = 1, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, pf, fd, s]) => { const r = window.FILM.poster(f, pf, fd, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, p, fade, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },
+ posterHash: (n, p, fade, samples = 1, w = 0) => pick(w).evaluate(([f, pf, fd, s]) => { window.FILM.poster(f, pf, fd, s); return window.FILM.hash(); }, [n, p, fade, samples]),
// hash of the motion-blurred frame: what a --blur render actually writes, so the probe checks THAT
blurHash: (n, samples, w = 0) => pick(w).evaluate(([f, s]) => { window.FILM.blur(f, s); return window.FILM.hash(); }, [n, samples]),
audio: (sr) => pages[0].evaluate((s) => window.FILM.audio(s), sr),
- close: () => browser.close(),
+ // keeps the fresh bakes, then closes; returns how many plate frames were stored
+ close: async () => { let saved = 0; if (useBakes) for (const p of pages) saved += await saveBakes(p, bv).catch(() => 0); await browser.close(); return saved; },
};
};
diff --git a/skills/anidoodle/engine/tools/render.mjs b/skills/anidoodle/engine/tools/render.mjs
index ab7cee6..54ce37a 100644
--- a/skills/anidoodle/engine/tools/render.mjs
+++ b/skills/anidoodle/engine/tools/render.mjs
@@ -8,6 +8,10 @@
// --from/--to render only frames [from, to): for checking a passage, not for shipping. A range
// render is silent (the score would not line up), says so, and by default writes
// out/<film>.<from>-<to>.<ext> so it can never overwrite the finished film.
+// --poster-frame N [--poster-fade 6] platforms show frame 0 as the thumbnail: open on frame N (the
+// wall of styles, the logo) and dissolve into the real opening by frame 6. The frame
+// count and the score are unchanged. A delivery whose frame 0 is near-blank gets a
+// warning after the encode (verify-export --delivery makes it a failure).
// Auto-detects a backend, renders every frame through it, encodes with ffmpeg, then VERIFIES.
// .mp4 the film, with its score
// .gif loops and README heroes: silent, loops forever, ONE palette built from the whole piece
@@ -25,6 +29,7 @@ import { detect } from "./detect.mjs";
import * as playwright from "./adapters/playwright.mjs";
import { defaultOutput } from "./names.mjs";
import { float32Wav } from "./audio.mjs";
+import { firstFrameBlank } from "./thumb.mjs";
const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };
const film = process.argv[2] && !process.argv[2].startsWith("--") ? process.argv[2] : "fixtures";
@@ -32,6 +37,9 @@ const BLUR = Number(arg("blur", 1));
if (!Number.isInteger(BLUR) || BLUR < 1) { console.error(`--blur wants a whole number of subframes >= 1, got '${arg("blur")}'`); process.exit(2); }
const scale = Number(arg("scale", 1)), fmt = (arg("out", "").match(/\.(gif|webm|apng)$/i)?.[1] ?? "mp4").toLowerCase(), workers = Number(arg("workers", Math.max(1, Math.min(4, Math.floor(cpus().length / 2)))));
const RANGE_ASKED = process.argv.includes("--from") || process.argv.includes("--to");
+const POSTER = arg("poster-frame", null) === null ? null : Number(arg("poster-frame")), FADE = Number(arg("poster-fade", 6));
+if (POSTER !== null && (!Number.isInteger(POSTER) || POSTER < 0)) { console.error(`--poster-frame wants a frame number >= 0, got '${arg("poster-frame")}'`); process.exit(2); }
+if (!Number.isInteger(FADE) || FADE < 0) { console.error(`--poster-fade wants a whole number of frames >= 0, got '${arg("poster-fade")}'`); process.exit(2); }
const env = detect();
console.log("backends found:"); for (const [k, v] of Object.entries(env.report)) console.log(` ${k.padEnd(11)} ${v}`);
@@ -49,6 +57,10 @@ const full = resolve(defaultOutput(film).replace(/\.mp4$/, `.${fmt}`));
const out = resolve(arg("out", ranged ? `out/${film}.${FROM}-${TO}.${fmt}` : full));
if (ranged && out === resolve(defaultOutput(film))) { console.error(`refusing to write a range render over the finished film ${out}; pick another --out or drop --from/--to`); process.exit(2); }
if (RANGE_ASKED && !ranged) console.log("range covers the whole film: rendering it complete, with its score");
+if (POSTER !== null && POSTER >= N) { console.error(`--poster-frame ${POSTER} is past the film's last frame ${N - 1}`); process.exit(2); }
+if (POSTER !== null) console.log(`poster: frame 0 is frame ${POSTER}, dissolving into the opening by frame ${Math.max(1, FADE)}`);
+const posterAt = (n) => POSTER !== null && n < Math.max(1, FADE); // frames the poster dissolve touches
+const drawAt = (n, w) => (posterAt(n) ? session.poster(n, POSTER, FADE, BLUR, w) : BLUR > 1 ? session.blur(n, BLUR, w) : session.frame(n, w));
console.log(`film: "${meta.title}" ${meta.W}x${meta.H} @ ${meta.fps} fps, ${N} frames, ${meta.bpm} bpm, scale ${scale}, ${session.workers} page(s)`);
if (BLUR > 1) console.log(`motion blur: ${BLUR} subframes per frame, one-frame shutter, linear light`);
if (ranged) console.log(`range render: frames [${FROM}, ${TO}) of ${N}, silent by design`);
@@ -74,7 +86,7 @@ const done = new Promise((res, rej) => ff.on("close", (c) => (c ? rej(new Error(
const cost = [], pending = new Map(); let next, write;
const pump = async () => { while (pending.has(write)) { const b = pending.get(write); pending.delete(write); if (!ff.stdin.write(b)) await new Promise((r) => ff.stdin.once("drain", r)); write++; } };
next = FROM; write = FROM;
-await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = BLUR > 1 ? await session.blur(n, BLUR, w) : await session.frame(n, w); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs }); pending.set(n, f.png); await pump(); } }));
+await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = await drawAt(n, w); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs }); pending.set(n, f.png); await pump(); } }));
await pump(); ff.stdin.end(); await done;
const wall = (Date.now() - t0) / 1000;
@@ -89,10 +101,11 @@ console.log(` wall clock: ${wall.toFixed(1)} s for ${TO - FROM} frames = ${((TO
// ---- verify: same frame, different order, different page. Standard = visually identical; hash equality is the cheap first test.
const probe = [...new Set([0, ...meta.shots.flatMap((s) => [s.start, s.end - 1]), ...((k) => Array.from({ length: k }, (_, i) => Math.round(i * (N - 1) / (k - 1 || 1))))(Math.min(6, N)), N - 1])].filter((n) => n >= FROM && n < TO).sort((a, b) => a - b), fwd = [], rev = [];
if (!probe.length) probe.push(FROM);
-const hashOf = (n, w) => (BLUR > 1 ? session.blurHash(n, BLUR, w) : session.hash(n, w)); // probe what was WRITTEN: the blurred frame when --blur
+const hashOf = (n, w) => (posterAt(n) ? session.posterHash(n, POSTER, FADE, BLUR, w) : BLUR > 1 ? session.blurHash(n, BLUR, w) : session.hash(n, w)); // probe what was WRITTEN: poster dissolve, blurred frame
for (const n of probe) fwd.push(await hashOf(n, 0)); for (const n of [...probe].reverse()) rev.unshift(await hashOf(n, session.workers - 1));
const same = probe.filter((_, i) => fwd[i] === rev[i]).length;
console.log(`\ndeterminism: ${same}/${probe.length} probe frames${BLUR > 1 ? ` (blurred, ${BLUR} subframes)` : ""} hash-identical (forward on page 0 vs reversed on page ${session.workers - 1})${same === probe.length ? "" : " -> fall back to PSNR > 45 dB in the Phase 2 gate"}`);
await session.close();
const pr = execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,codec_name,width,height,nb_frames,duration", "-of", "csv=p=0", out]).toString().trim().split("\n");
console.log(`\noutput: ${out}`); pr.forEach((l) => console.log(` ${l}`));
+if (fmt === "mp4" && !ranged) { const t = firstFrameBlank(out); if (t.blank) console.log(`\nWARNING frame 0 is near-blank (${t.detail}). Platforms use frame 0 as the thumbnail: re-render with --poster-frame N (a legible frame: the wall, the logo).`); }
diff --git a/skills/anidoodle/engine/tools/thumb.mjs b/skills/anidoodle/engine/tools/thumb.mjs
new file mode 100644
index 0000000..9814699
--- /dev/null
+++ b/skills/anidoodle/engine/tools/thumb.mjs
@@ -0,0 +1,17 @@
+// THUMBNAIL GUARD. Platforms show a video's first frame as its thumbnail, so a delivery that opens
+// on a blank page, a flat colour or a fade from black shows up as an empty rectangle in the feed.
+// This reads decoded frame 0 of a file (what the platform will actually show) at thumbnail size
+// and calls it near-blank when it is one flat tone: tiny spread of luma, or almost every pixel
+// within a few levels of the median. A small logo or a line of text on a blank ground still
+// counts as blank on purpose: that is not a thumbnail anyone can read at feed size.
+import { spawnSync } from "node:child_process";
+
+const W = 96, H = 54;
+export const firstFrameBlank = (file, { frame = 0 } = {}) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `select=eq(n\\,${frame}),scale=${W}:${H}:flags=area`, "-vsync", "0", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"], { maxBuffer: 1 << 20 });
+ if (r.status !== 0 || r.stdout.length !== W * H) return { blank: false, unknown: true, detail: `could not decode frame ${frame}: ${r.stderr?.toString().trim() || "short read"}` };
+ const px = [...r.stdout], n = px.length, mean = px.reduce((a, b) => a + b, 0) / n;
+ const sd = Math.sqrt(px.reduce((a, b) => a + (b - mean) ** 2, 0) / n), med = [...px].sort((a, b) => a - b)[n >> 1];
+ const flat = px.filter((v) => Math.abs(v - med) <= 6).length / n;
+ return { blank: sd < 3 || flat >= 0.985, sd, flat, mean, detail: `luma spread ${sd.toFixed(1)}, ${(flat * 100).toFixed(1)}% of pixels within 6 levels of ${med}` };
+};
diff --git a/skills/anidoodle/engine/tools/verify-export.mjs b/skills/anidoodle/engine/tools/verify-export.mjs
index c797e5a..8c46e2a 100644
--- a/skills/anidoodle/engine/tools/verify-export.mjs
+++ b/skills/anidoodle/engine/tools/verify-export.mjs
@@ -5,19 +5,27 @@
// colour to assert, and a one-shot film has no seam to hide.
//
// node tools/verify-export.mjs <film> [--file out/x.mp4] [--adapter html-player]
-// [--width W] expected pixel width (default: the film's own; height follows the aspect)
+// [--width W] expected pixel width of a .gif/.webm/.apng made with render --width
+// (default: the film's own; height follows the aspect). Not for .mp4:
+// render always writes the MP4 at the film's size (x --scale), so
+// --width on an MP4 is refused rather than silently ignored
// [--first-frame #rrggbb] the average colour the decoded first frame must have (tol: --tol N, default 8)
// [--loop] the last-to-first seam must read like any other step of the loop
-// [--fidelity-psnr N] decoded frame 0 must sit within N dB of the source frame (renders it once)
+// [--fidelity-psnr N] a decoded frame must sit within N dB of the source frame (renders it once)
+// [--frame N] which frame --fidelity-psnr compares (default 0)
+// [--delivery] this file ships: a near-blank frame 0 (the platform thumbnail) FAILS
+// instead of warning; fix with render --poster-frame N
//
-// Always checked: the file decodes, its pixel size, its exact frame count, and its duration
-// against the film's meta. Everything else is asked for explicitly.
+// Always checked: the file decodes, its pixel size, its exact frame count, its duration against
+// the film's meta, and for an MP4 the score: an audio stream exactly when the film has a score,
+// as long as the picture, and not silent. Everything else is asked for explicitly.
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { defaultOutput } from "./names.mjs";
+import { firstFrameBlank } from "./thumb.mjs";
-const VAL = new Set(["file", "adapter", "width", "first-frame", "tol", "fidelity-psnr", "scale"]);
+const VAL = new Set(["file", "adapter", "width", "first-frame", "tol", "fidelity-psnr", "scale", "frame"]);
const pos = [], opt = {};
for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }
const film = pos[0] ?? "fixtures";
@@ -51,6 +59,10 @@ const N = meta.durationFrames, FW = Math.round(meta.W * SCALE), FH = Math.round(
const file = resolve(opt.file ?? defaultOutput(film));
console.log(`VERIFY-EXPORT film "${meta.title}" file ${file}`);
if (!existsSync(file)) die(`${file} not found`);
+const isMp4 = /\.(mp4|m4v|mov)$/i.test(file);
+if (opt.width && isMp4) die(`--width does not apply to an MP4: render writes it at the film's own size (x --scale); use --scale to check a scaled render`);
+const FRAME = opt.frame === undefined ? 0 : Number(opt.frame);
+if (!Number.isInteger(FRAME) || FRAME < 0 || FRAME >= N) die(`--frame wants a frame number in [0, ${N - 1}], got '${opt.frame}'`);
// ---------------------------------------------------------------- 1. the container
head(1, "CONTAINER the file is the film's size, length and duration");
@@ -64,8 +76,30 @@ const dur = Number(ffprobe(["-show_entries", "format=duration", "-of", "csv=p=0"
const wantDur = N / meta.fps, slack = 1 / meta.fps + 0.05;
say(Math.abs(dur - wantDur) <= slack, `duration ${dur.toFixed(3)} s`, `expected ${wantDur.toFixed(3)} s +/- ${slack.toFixed(3)} (container rounding)`);
+// ---------------------------------------------------------------- 1b. the score, in an MP4
+if (isMp4) {
+ head("1b", "SOUND the score is in the file, as long as the picture, and audible");
+ const a = ffprobe(["-select_streams", "a", "-show_entries", "stream=codec_name,duration,sample_rate,channels", "-of", "csv=p=0", file]).split("\n").filter(Boolean);
+ const hasAudio = meta.hasAudio ?? Boolean(await s.audio?.(48000)); // older pages / other adapters: ask the score itself
+ if (!hasAudio) say(a.length === 0, "no audio stream (the film has no score)", a.length ? `found ${a.length}: ${a.join(" | ")}` : "");
+ else if (!a.length) say(false, "an audio stream (the film has a score)", "none found: was it a range render?");
+ else {
+ const [acodec, rate, ch, adur] = a[0].split(","), ad = Number(adur);
+ say(a.length === 1, `one audio stream (${acodec}, ${rate} Hz, ${ch} ch)`, a.length > 1 ? `found ${a.length}` : "");
+ say(Math.abs(ad - wantDur) <= slack + 0.05, `audio duration ${ad.toFixed(3)} s`, `picture is ${wantDur.toFixed(3)} s +/- ${(slack + 0.05).toFixed(3)} (AAC priming)`);
+ const vd = spawnSync("ffmpeg", ["-v", "info", "-i", file, "-map", "0:a:0", "-af", "volumedetect", "-f", "null", "-"], { encoding: "utf8" });
+ const mx = Number(((vd.stdout + vd.stderr).match(/max_volume:\s*(-?[0-9.]+|-inf) dB/) ?? [])[1]);
+ say(Number.isFinite(mx) && mx > -40 && mx <= 0, `audio peak ${Number.isFinite(mx) ? mx.toFixed(1) : "-inf"} dBFS`, "audible (> -40 dBFS) and not clipped past 0");
+ }
+}
+
// ---------------------------------------------------------------- 2. the first frame's colour
head(2, "FIRST FRAME what the audience's first instant actually looks like");
+const thumb = firstFrameBlank(file);
+if (thumb.unknown) note("thumbnail check skipped", thumb.detail);
+else if (opt.delivery) say(!thumb.blank, "frame 0 (the platform thumbnail) is legible, not near-blank", thumb.detail + (thumb.blank ? " -> render --poster-frame N" : ""));
+else if (thumb.blank) note("WARNING frame 0 is near-blank", `${thumb.detail}; platforms show frame 0 as the thumbnail: render --poster-frame N (pass --delivery to fail on this)`);
+else note("frame 0 is not blank", thumb.detail);
const avg = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "select=eq(n\\,0),scale=1:1", "-vsync", "0", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 1 << 16 });
if (avg.status !== 0 || avg.stdout.length < 3) die(`ffmpeg could not average frame 0: ${avg.stderr.toString().trim()}`);
const hex = `#${[...avg.stdout.subarray(0, 3)].map((v) => v.toString(16).padStart(2, "0")).join("")}`;
@@ -80,13 +114,13 @@ if (opt["first-frame"]) {
// ---------------------------------------------------------------- 3. fidelity to the source, if asked
if (opt["fidelity-psnr"]) {
head(3, "FIDELITY the decoded frame is the frame the source drew");
- const src = resolve(TMP, "source-0.png"), dec = resolve(TMP, "decoded-0.png");
- writeFileSync(src, (await s.frame(0, 0)).png);
- const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "select=eq(n\\,0)", "-vsync", "0", "-frames:v", "1", "-y", dec], { encoding: "utf8" });
- if (r.status !== 0) die(`ffmpeg could not lift frame 0: ${r.stderr.trim()}`);
+ const src = resolve(TMP, `source-${FRAME}.png`), dec = resolve(TMP, `decoded-${FRAME}.png`);
+ writeFileSync(src, (await s.frame(FRAME, 0)).png);
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `select=eq(n\\,${FRAME})`, "-vsync", "0", "-frames:v", "1", "-y", dec], { encoding: "utf8" });
+ if (r.status !== 0) die(`ffmpeg could not lift frame ${FRAME}: ${r.stderr.trim()}`);
const ps = spawnSync("ffmpeg", ["-v", "error", "-i", dec, "-i", src, "-lavfi", "psnr=stats_file=-", "-f", "null", "-"], { encoding: "utf8" });
const m = (ps.stdout + ps.stderr).match(/psnr_avg:([0-9.]+|inf)/), v = m ? (m[1] === "inf" ? Infinity : Number(m[1])) : NaN;
- say(v >= +opt["fidelity-psnr"], `decoded frame 0 vs source frame 0: ${v === Infinity ? "inf" : v.toFixed(2)} dB`, `bar ${opt["fidelity-psnr"]} dB`);
+ say(v >= +opt["fidelity-psnr"], `decoded frame ${FRAME} vs source frame ${FRAME}: ${v === Infinity ? "inf" : v.toFixed(2)} dB`, `bar ${opt["fidelity-psnr"]} dB`);
}
// ---------------------------------------------------------------- 4. the seam, if it loops