Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 13453a2542ca552fd81b5e96b04e92f8a30244c3
parent 9443a9bf1810037fa644d30567d2b467065b0471
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 10:47:05 -0400

report video: quality variants of a finished cut -- variants.mjs and its CLI

render.variants, the encode ladder (default master, 1080p crf 22, 720p
crf 23, fit24 maxMiB 24). master is the build's own <slug>.mp4; the others
<slug>.<name>.mp4 beside it: crf ones re-encode the picture at their height
(sound copied, chapters kept); a maxMiB one is two-pass x264 at the largest
of 1080/720/480 whose picture keeps 100 kb/s per 480p of pixels, AAC 48 kb/s
mono under 300 kb/s in all (else 96 stereo), and is encoded again 6 % lower
while it lands over. variants.json records {at, source, items: [{name, path,
width, height, bytes, kbps}]}; --only remakes some and keeps the rest.
encodeVariants(outDir, {slug, variants, only, source, onLog}) for umtool's
job runner; validateVariants for its writers. The CLI (node
umtool/report-to-video/variants.mjs <take out dir> [--slug] [--only]
[--source]) reads the slug and ladder from the take's manifest and takes the
heavy slot. Exports: ./variants, ./clip-audio, ./sync-report.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/report-to-video/package.json | 6+++++-
Aumtool/report-to-video/variants.mjs | 301+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/variants.test.mjs | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 440 insertions(+), 1 deletion(-)

diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -13,7 +13,8 @@ "report-check-availability": "./check-availability.mjs", "report-verify-build": "./verify-build.mjs", "report-compose-chrome": "./compose-chrome.mjs", - "report-shoot-page": "./shoot-page.mjs" + "report-shoot-page": "./shoot-page.mjs", + "report-variants": "./variants.mjs" }, "exports": { "./attribution": "./attribution.mjs", @@ -21,6 +22,7 @@ "./brand-ids": "./brand-ids.mjs", "./build-video": "./build-video.mjs", "./check-availability": "./check-availability.mjs", + "./clip-audio": "./clip-audio.mjs", "./compose-chrome": "./compose-chrome.mjs", "./cues": "./cues.mjs", "./deck": "./deck.mjs", @@ -49,7 +51,9 @@ "./shoot-page": "./shoot-page.mjs", "./social": "./social.mjs", "./sources": "./sources.mjs", + "./sync-report": "./sync-report.mjs", "./transition": "./transition.mjs", + "./variants": "./variants.mjs", "./verify-build": "./verify-build.mjs", "./youtube": "./youtube.mjs" } diff --git a/umtool/report-to-video/variants.mjs b/umtool/report-to-video/variants.mjs @@ -0,0 +1,301 @@ +#!/usr/bin/env node +// Quality variants of a finished cut: the encode ladder for sharing it +// elsewhere -- the build's own file, smaller re-encodes at a height and a +// quality, and ones made to fit under a size (a chat app's upload limit). +// +// render.variants: [{ name: "master" }, +// { name: "1080p", height: 1080, crf: 22 }, +// { name: "720p", height: 720, crf: 23 }, +// { name: "fit24", maxMiB: 24 }] (the default) +// +// Each is `<take out>/<slug>.<name>.mp4` beside the cut, `master` excepted: +// it IS the build's `<slug>.mp4`, not a copy. `<take out>/variants.json` +// says what was made: `{ at, source, items: [{ name, path, width, height, +// bytes, kbps }] }`. +// +// A `maxMiB` variant is two-pass x264 at the largest of 1080/720/480 (no +// larger than the cut) whose picture keeps at least 100 kb/s per 480p's worth +// of pixels; its sound AAC 48 kb/s mono when the whole is under 300 kb/s, +// else 96 kb/s stereo; and it is encoded again 6 % lower while it lands over +// (x264 overshoots: 24.3 MiB at a 23.1 target, measured). +// +// node umtool/report-to-video/variants.mjs <take out dir> [--slug s] [--only name,…] [--source file] +// +// The CLI takes the machine's heavy slot (heavy-gate.mjs); encodeVariants +// itself does not -- umtool's job runner holds it for the UI. +import { execFile } from "node:child_process"; +import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { promisify } from "node:util"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; + +/** The ladder when `render.variants` is absent. */ +export const DEFAULT_VARIANTS = Object.freeze([ + Object.freeze({ name: "master" }), + Object.freeze({ name: "1080p", height: 1080, crf: 22 }), + Object.freeze({ name: "720p", height: 720, crf: 23 }), + Object.freeze({ name: "fit24", maxMiB: 24 }), +]); + +export const VARIANTS_FILE = "variants.json"; + +/** The heights a size-capped variant picks from, largest first. */ +export const FIT_HEIGHTS = Object.freeze([1080, 720, 480]); + +/** A size-capped variant's picture floor: kb/s per 480p's worth of pixels. */ +export const FIT_FLOOR_KBPS = 100; + +/** Re-encode this much lower each time a size-capped variant lands over. */ +export const FIT_RETRY_STEP = 0.06; + +const NAME_RE = /^[a-z0-9][a-z0-9-]{0,23}$/; +/** Names a cut variant's final already takes beside the cut (`<slug>.<variant>.mp4`). */ +const RESERVED = new Set(["sourced", "article", "preview", "prerail", "partial"]); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi; + +/** + * Every reason a `render.variants` list cannot be made, as sentences (empty: + * it can). `undefined` is the default ladder. + * + * @returns {string[]} + */ +export function validateVariants(list, where = "render.variants") { + if (list === undefined) return []; + if (!Array.isArray(list)) return [`${where} must be a list of { name, height?, crf?, maxMiB?, preset? }`]; + const errors = []; + if (list.length > 12) errors.push(`${where} has ${list.length} variants (at most 12)`); + const seen = new Set(); + list.forEach((v, i) => { + const at = `${where}[${i}]`; + if (!isObj(v)) { errors.push(`${at} must be { name, height?, crf?, maxMiB?, preset? }`); return; } + for (const k of Object.keys(v)) { + if (!["name", "height", "crf", "maxMiB", "preset"].includes(k)) errors.push(`${at}.${k} is not a variant setting (name, height, crf, maxMiB, preset)`); + } + if (typeof v.name !== "string" || !NAME_RE.test(v.name)) { + errors.push(`${at}.name must be lower-case letters, digits or dashes (at most 24)`); + } else if (RESERVED.has(v.name)) { + errors.push(`${at}.name "${v.name}" is taken (${[...RESERVED].join(", ")})`); + } else if (seen.has(v.name)) errors.push(`${at}.name "${v.name}" is used twice`); + else seen.add(v.name); + if (v.name === "master" && Object.keys(v).length > 1) errors.push(`${at}: master is the build's own file -- it takes no settings`); + if (v.height !== undefined && !(Number.isInteger(v.height) && v.height % 2 === 0 && numIn(v.height, 144, 2160))) { + errors.push(`${at}.height must be an even whole number of pixels from 144 to 2160`); + } + if (v.crf !== undefined && !(Number.isInteger(v.crf) && numIn(v.crf, 0, 51))) errors.push(`${at}.crf must be a whole number from 0 to 51`); + if (v.maxMiB !== undefined && !numIn(v.maxMiB, 0.01, 4096)) errors.push(`${at}.maxMiB must be from 0.01 to 4096`); + if (v.maxMiB !== undefined && v.crf !== undefined) errors.push(`${at}: a maxMiB variant is sized by its bitrate -- it takes no crf`); + const presets = ["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"]; + if (v.preset !== undefined && !presets.includes(v.preset)) errors.push(`${at}.preset must be one of ${presets.join(", ")}`); + }); + return errors; +} + +/** The ladder for a render: `render.variants`, else DEFAULT_VARIANTS. */ +export function variantsOf(render) { + return Array.isArray(render?.variants) ? render.variants : DEFAULT_VARIANTS; +} + +/** A file's duration (s), picture size and bytes. */ +export async function probeOut(file) { + const { stdout } = await execFileP(FFPROBE(), [ + "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:format=duration", "-of", "json", file, + ]); + const doc = JSON.parse(stdout); + const v = doc.streams?.[0] ?? {}; + const st = await stat(file); + return { duration: Number(doc.format?.duration), width: Number(v.width), height: Number(v.height), bytes: st.size }; +} + +/** + * A size-capped variant's plan: its height, picture and sound bitrates (kb/s) + * for `maxMiB` over `seconds` of a cut `srcHeight` tall. `scale` < 1 is a + * retry's: the picture's share lowered by that much. + */ +export function fitPlan({ maxMiB, seconds, srcHeight, maxHeight = null, scale = 1 }) { + const totalKbps = (maxMiB * 1024 * 1024 * 8) / seconds / 1000; + const audio = totalKbps < 300 ? { kbps: 48, channels: 1 } : { kbps: 96, channels: 2 }; + // A container's own bytes: about 2 % of the whole at these rates. + const videoKbps = Math.max(1, Math.floor((totalKbps * 0.98 - audio.kbps) * scale)); + const cap = Math.min(srcHeight, maxHeight ?? Infinity); + const heights = FIT_HEIGHTS.filter((h) => h <= cap); + const options = heights.length ? heights : [cap - (cap % 2)]; + const floor = (h) => FIT_FLOOR_KBPS * (h / 480) ** 2; + const height = options.find((h) => videoKbps >= floor(h)) ?? options[options.length - 1]; + return { height, videoKbps, audio, totalKbps }; +} + +const scaleArgs = (height, srcHeight) => (height < srcHeight ? ["-vf", `scale=-2:${height}:flags=lanczos`] : []); + +/** One crf variant's argv: picture re-encoded at its height and quality; the sound copied. */ +export function crfArgs({ source, out, height, srcHeight, crf, preset = "medium" }) { + return [ + "-nostdin", "-v", "error", "-y", "-i", source, + "-map", "0:v:0", "-map", "0:a?", "-map_metadata", "0", "-map_chapters", "0", + ...scaleArgs(height, srcHeight), + "-c:v", "libx264", "-preset", preset, "-crf", String(crf), "-pix_fmt", "yuv420p", + "-c:a", "copy", "-movflags", "+faststart", out, + ]; +} + +/** A two-pass variant's argv for `pass` (1 or 2). */ +export function fitArgs({ source, out, plan, srcHeight, pass, logBase, preset = "medium" }) { + const common = [ + "-nostdin", "-v", "error", "-y", "-i", source, + ...scaleArgs(plan.height, srcHeight), + "-c:v", "libx264", "-preset", preset, "-b:v", `${plan.videoKbps}k`, "-pix_fmt", "yuv420p", + "-pass", String(pass), "-passlogfile", logBase, + ]; + if (pass === 1) return [...common, "-map", "0:v:0", "-an", "-f", "null", "-"]; + return [ + ...common, "-map", "0:v:0", "-map", "0:a?", "-map_metadata", "0", "-map_chapters", "0", + "-c:a", "aac", "-b:a", `${plan.audio.kbps}k`, "-ac", String(plan.audio.channels), + "-movflags", "+faststart", out, + ]; +} + +const itemOf = (name, file, p) => ({ + name, path: file, width: p.width, height: p.height, bytes: p.bytes, + kbps: Number.isFinite(p.duration) && p.duration > 0 ? Math.round((p.bytes * 8) / p.duration / 1000) : null, +}); + +/** + * Make the variants of `<outDir>/<slug>.mp4` (or `source`). `variants` is the + * ladder (validated here); `only` names the ones to make now -- the others' + * rows in variants.json are kept. Each is written under a temporary name and + * renamed, so a half-made file is never taken for one. + * + * @param {string} outDir + * @param {{ slug: string, variants?: object[], only?: string[] | null, source?: string | null, + * onLog?: (line: string) => void }} opts + * @returns {Promise<{ at: string, source: string, items: Array<{ name: string, path: string, + * width: number, height: number, bytes: number, kbps: number | null }> }>} + */ +export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS, only = null, source = null, onLog = () => {} } = {}) { + const errors = validateVariants(variants); + if (errors.length) throw new Error(errors.join("; ")); + if (!slug) throw new Error("variants: no slug"); + const src = source ?? path.join(outDir, `${slug}.mp4`); + const sp = await probeOut(src).catch(() => null); + if (!sp) throw new Error(`variants: no cut at ${src} -- build it first`); + if (only?.length) { + const unknown = only.filter((n) => !variants.some((v) => v.name === n)); + if (unknown.length) throw new Error(`variants: no variant named ${unknown.join(", ")} (${variants.map((v) => v.name).join(", ")})`); + } + const todo = variants.filter((v) => !only?.length || only.includes(v.name)); + const made = []; + const work = path.join(outDir, ".variants"); + await mkdir(work, { recursive: true }); + try { + for (const v of todo) { + if (v.name === "master") { + made.push(itemOf("master", src, sp)); + onLog(`variant master: ${path.basename(src)} (${(sp.bytes / 2 ** 20).toFixed(1)} MiB)`); + continue; + } + const out = path.join(outDir, `${slug}.${v.name}.mp4`); + const tmp = path.join(work, `${slug}.${v.name}.partial.mp4`); + if (v.maxMiB === undefined) { + const height = Math.min(v.height ?? sp.height, sp.height); + onLog(`variant ${v.name}: ${height}p, crf ${v.crf ?? 23}…`); + await execFileP(FFMPEG(), crfArgs({ source: src, out: tmp, height, srcHeight: sp.height, crf: v.crf ?? 23, preset: v.preset }), { maxBuffer: 1 << 26 }); + } else { + const limit = v.maxMiB * 2 ** 20; + let scale = 1; + for (let tries = 0; ; tries += 1) { + const plan = fitPlan({ maxMiB: v.maxMiB, seconds: sp.duration, srcHeight: sp.height, maxHeight: v.height ?? null, scale }); + onLog(`variant ${v.name}: ${plan.height}p, ${plan.videoKbps} kb/s picture + ${plan.audio.kbps} kb/s ${plan.audio.channels === 1 ? "mono" : "stereo"}, two passes…`); + const logBase = path.join(work, `${slug}.${v.name}.pass`); + for (const pass of [1, 2]) { + await execFileP(FFMPEG(), fitArgs({ source: src, out: tmp, plan, srcHeight: sp.height, pass, logBase, preset: v.preset }), { maxBuffer: 1 << 26, cwd: work }); + } + const got = (await stat(tmp)).size; + if (got <= limit) break; + if (tries >= 3) { + onLog(`variant ${v.name}: still ${(got / 2 ** 20).toFixed(2)} MiB over ${v.maxMiB} after ${tries + 1} tries — kept`); + break; + } + scale *= 1 - FIT_RETRY_STEP; + onLog(`variant ${v.name}: ${(got / 2 ** 20).toFixed(2)} MiB is over ${v.maxMiB} — again ${Math.round(FIT_RETRY_STEP * 100)} % lower`); + } + } + await rename(tmp, out); + const p = await probeOut(out); + made.push(itemOf(v.name, out, p)); + onLog(`variant ${v.name}: ${path.basename(out)} ${p.width}x${p.height}, ${(p.bytes / 2 ** 20).toFixed(2)} MiB`); + } + } finally { + await rm(work, { recursive: true, force: true }); + } + // The record: this run's rows over any earlier ones of the same source, in ladder order. + let prev = null; + try { + prev = JSON.parse(await readFile(path.join(outDir, VARIANTS_FILE), "utf8")); + } catch { + prev = null; + } + const keep = prev?.source === src && Array.isArray(prev.items) ? prev.items.filter((it) => !made.some((m) => m.name === it.name)) : []; + const rank = (n) => { + const i = variants.findIndex((v) => v.name === n); + return i < 0 ? variants.length : i; + }; + const items = [...keep.filter((it) => variants.some((v) => v.name === it.name)), ...made].sort((a, b) => rank(a.name) - rank(b.name)); + const doc = { at: new Date().toISOString(), source: src, items }; + await writeFile(path.join(outDir, VARIANTS_FILE), JSON.stringify(doc, null, 2) + "\n"); + return doc; +} + +// ---- the CLI --------------------------------------------------------------- + +/** argv after the script: `<take out dir> [--slug s] [--only a,b] [--source file]`. */ +export function parseVariantArgs(argv) { + const out = { outDir: null, slug: null, only: null, source: null }; + for (let i = 0; i < argv.length; i += 1) { + const a = argv[i]; + if (a === "--slug") out.slug = argv[++i] ?? null; + else if (a === "--only") out.only = String(argv[++i] ?? "").split(",").map((s) => s.trim()).filter(Boolean); + else if (a === "--source") out.source = argv[++i] ?? null; + else if (a.startsWith("--")) throw new Error(`variants: unknown option ${a}`); + else if (!out.outDir) out.outDir = a; + else throw new Error(`variants: one take out dir, got ${a} too`); + } + if (!out.outDir) throw new Error("usage: variants.mjs <take out dir> [--slug s] [--only name,…] [--source file]"); + return out; +} + +async function main() { + const args = parseVariantArgs(process.argv.slice(2)); + const outDir = path.resolve(args.outDir); + // The take's manifest is beside its out dir: its slug and its ladder. + let manifest = null; + try { + manifest = JSON.parse(await readFile(path.join(path.dirname(outDir), "video.manifest.json"), "utf8")); + } catch { + manifest = null; + } + const slug = args.slug ?? manifest?.slug; + if (!slug) throw new Error(`variants: no --slug and no video.manifest.json beside ${outDir}`); + const variants = variantsOf(manifest?.render); + const run = () => encodeVariants(outDir, { + slug, variants, only: args.only, source: args.source ? path.resolve(args.source) : null, + onLog: (line) => process.stderr.write(`${line}\n`), + }); + // By a URL made from the script's own path at run time, as build-video's + // CLI loads it: never a module the umtool app's bundle traces. + const gate = new URL("./heavy-gate.mjs", pathToFileURL(process.argv[1])).href; + const { withRenderSlot } = await import(/* webpackIgnore: true */ gate); + const doc = await withRenderSlot(["variants", outDir], run); + process.stdout.write(JSON.stringify(doc, null, 2) + "\n"); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + main().catch((err) => { + process.stderr.write(`${err?.message ?? err}\n`); + process.exit(1); + }); +} diff --git a/umtool/report-to-video/variants.test.mjs b/umtool/report-to-video/variants.test.mjs @@ -0,0 +1,134 @@ +// Quality variants of a finished cut (variants.mjs): the ladder validated, +// the size-capped plan, and real (tiny) encodes -- master is the build's own +// file, a crf variant is at its height, a maxMiB one lands under its size. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { + DEFAULT_VARIANTS, encodeVariants, fitPlan, parseVariantArgs, validateVariants, VARIANTS_FILE, variantsOf, +} from "./variants.mjs"; + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); + +test("validateVariants: the default ladder is valid; a bad one is refused in sentences", () => { + assert.deepEqual(validateVariants(undefined), []); + assert.deepEqual(validateVariants(DEFAULT_VARIANTS), []); + assert.deepEqual(variantsOf({}), DEFAULT_VARIANTS); + assert.deepEqual(validateVariants("x"), ["render.variants must be a list of { name, height?, crf?, maxMiB?, preset? }"]); + const errs = validateVariants([ + { name: "Big" }, { name: "article" }, { name: "a", height: 1081 }, { name: "a", crf: 60 }, + { name: "fit", maxMiB: 0 }, { name: "both", maxMiB: 8, crf: 20 }, { name: "master", crf: 20 }, { name: "p", preset: "warp" }, + { name: "q", fps: 60 }, + ]); + for (const want of [ + /\[0\]\.name must be lower-case letters/, /\[1\]\.name "article" is taken/, /\[2\]\.height must be an even whole number/, + /\[3\]\.name "a" is used twice/, /\[3\]\.crf must be a whole number from 0 to 51/, /\[4\]\.maxMiB must be from 0\.01 to 4096/, + /\[5\]: a maxMiB variant is sized by its bitrate/, /\[6\]: master is the build's own file/, /\[7\]\.preset must be one of/, + /\[8\]\.fps is not a variant setting/, + ]) assert.ok(errs.some((e) => want.test(e)), `${want} in ${errs.join("\n")}`); +}); + +test("fitPlan: the Huck cut at 24 MiB is 480p with mono sound; a short cut gets 1080p and stereo", () => { + // 20:10 at 24 MiB: ~166 kb/s in all -- under 300, so 48 kb/s mono; ~115 kb/s picture: 480p. + const huck = fitPlan({ maxMiB: 24, seconds: 1210, srcHeight: 1080 }); + assert.equal(huck.audio.kbps, 48); + assert.equal(huck.audio.channels, 1); + assert.equal(huck.height, 480); + assert.ok(huck.videoKbps > 100 && huck.videoKbps < 125, String(huck.videoKbps)); + // Two minutes at 24 MiB: ~1678 kb/s -- stereo, and enough for 1080p (≥ 506 kb/s). + const short = fitPlan({ maxMiB: 24, seconds: 120, srcHeight: 1080 }); + assert.equal(short.audio.channels, 2); + assert.equal(short.height, 1080); + // 720p when 1080p's floor is missed but 720p's (225) is met. + assert.equal(fitPlan({ maxMiB: 24, seconds: 500, srcHeight: 1080 }).height, 720); + // Never taller than the cut, or than the variant's own height. + assert.equal(fitPlan({ maxMiB: 24, seconds: 60, srcHeight: 720 }).height, 720); + assert.equal(fitPlan({ maxMiB: 24, seconds: 60, srcHeight: 1080, maxHeight: 720 }).height, 720); + assert.equal(fitPlan({ maxMiB: 1, seconds: 2, srcHeight: 180 }).height, 180); + // A retry's scale lowers the picture only. + const r = fitPlan({ maxMiB: 24, seconds: 1210, srcHeight: 1080, scale: 0.94 }); + assert.ok(r.videoKbps < huck.videoKbps && r.audio.kbps === huck.audio.kbps); +}); + +test("parseVariantArgs", () => { + assert.deepEqual(parseVariantArgs(["out", "--slug", "s", "--only", "720p, fit24"]), { outDir: "out", slug: "s", only: ["720p", "fit24"], source: null }); + assert.throws(() => parseVariantArgs([]), /usage/); + assert.throws(() => parseVariantArgs(["a", "--wat"]), /unknown option --wat/); +}); + +function cut(dir, slug) { + const out = path.join(dir, `${slug}.mp4`); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=640x360:r=30:d=3", + "-f", "lavfi", "-i", "sine=f=440:r=48000:d=3", + "-c:v", "libx264", "-preset", "ultrafast", "-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ac", "2", "-b:a", "160k", "-shortest", out, + ]); + assert.equal(r.status, 0, String(r.stderr)); + return out; +} + +test("encodeVariants: master is the cut itself; a crf variant at its height; a maxMiB one under its size; the record", { skip: !have && "needs ffmpeg" }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "variants-")); + try { + const src = cut(dir, "demo"); + const variants = [ + { name: "master" }, + { name: "small", height: 180, crf: 30, preset: "ultrafast" }, + { name: "fit", maxMiB: 0.06, preset: "ultrafast" }, + ]; + const logs = []; + const doc = await encodeVariants(dir, { slug: "demo", variants, onLog: (l) => logs.push(l) }); + assert.equal(doc.source, src); + assert.deepEqual(doc.items.map((i) => i.name), ["master", "small", "fit"]); + assert.equal(doc.items[0].path, src, "master is the build's own file"); + const small = doc.items[1]; + assert.equal(small.path, path.join(dir, "demo.small.mp4")); + assert.equal(small.height, 180); + assert.equal(small.width, 320); + const fit = doc.items[2]; + assert.ok(fit.bytes <= 0.06 * 2 ** 20, `${fit.bytes} bytes over 0.06 MiB`); + assert.ok(fit.kbps > 0); + // The sound of a size-capped variant at this rate is mono. + const ch = spawnSync("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=channels", "-of", "csv=p=0", fit.path]); + assert.equal(String(ch.stdout).trim(), "1"); + assert.deepEqual(JSON.parse(readFileSync(path.join(dir, VARIANTS_FILE), "utf8")).items.map((i) => i.name), ["master", "small", "fit"]); + assert.ok(!existsSync(path.join(dir, ".variants")), "the work dir is gone"); + assert.ok(logs.some((l) => /variant fit: \d+p, \d+ kb\/s picture \+ 48 kb\/s mono, two passes/.test(l)), logs.join("\n")); + + // `only`: one remade, the others' rows kept. + const again = await encodeVariants(dir, { slug: "demo", variants, only: ["small"] }); + assert.deepEqual(again.items.map((i) => i.name), ["master", "small", "fit"]); + await assert.rejects(encodeVariants(dir, { slug: "demo", variants, only: ["huge"] }), /no variant named huge/); + await assert.rejects(encodeVariants(dir, { slug: "nope", variants }), /no cut at/); + assert.deepEqual(readdirSync(dir).filter((f) => f.endsWith(".mp4")).sort(), ["demo.fit.mp4", "demo.mp4", "demo.small.mp4"]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("the CLI: the take's manifest names the slug and the ladder", { skip: !have && "needs ffmpeg" }, () => { + const take = mkdtempSync(path.join(tmpdir(), "variants-take-")); + try { + const out = path.join(take, "out"); + spawnSync("mkdir", ["-p", out]); + cut(out, "demo"); + writeFileSync(path.join(take, "video.manifest.json"), JSON.stringify({ + slug: "demo", render: { variants: [{ name: "master" }, { name: "tiny", height: 144, crf: 35, preset: "ultrafast" }] }, + })); + const script = path.join(path.dirname(fileURLToPath(import.meta.url)), "variants.mjs"); + const r = spawnSync(process.execPath, [script, out, "--only", "tiny"], { env: { ...process.env, HEAVY: "0" }, encoding: "utf8" }); + assert.equal(r.status, 0, r.stderr); + const doc = JSON.parse(r.stdout); + assert.deepEqual(doc.items.map((i) => [i.name, i.height]), [["tiny", 144]]); + assert.ok(existsSync(path.join(out, "demo.tiny.mp4"))); + } finally { + rmSync(take, { recursive: true, force: true }); + } +});