// 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 { createHash } from "node:crypto"; import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, 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, seedLadderFit, validateVariants, VARIANTS_FILE, variantsOf, } from "./variants.mjs"; import { CHUNKS_DIR, CHUNKS_RECORD } from "./chunked-encode.mjs"; import { LADDER_CHUNKS_DIR, LADDER_DIR, LADDER_RECORD } from "./ladder-chunks.mjs"; import { concatWithXfade, setProgressMode } from "./build-video.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, chunked: true }); assert.equal(parseVariantArgs(["out", "--whole"]).chunked, false); 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 }); } }); // ---- the ladder from the master's chunks (ladder-chunks.mjs) ----------------- function run(argv) { const r = spawnSync("ffmpeg", argv); assert.equal(r.status, 0, String(r.stderr)); return r; } function segment(dir, i, frames, fps, name = `s${i}`) { const out = path.join(dir, `${name}.mp4`); run([ "-v", "error", "-y", "-f", "lavfi", "-i", `testsrc2=s=320x180:r=${fps}:d=${frames / fps + 1},trim=end_frame=${frames},colorchannelmixer=rr=${0.4 + 0.1 * i}`, "-f", "lavfi", "-i", `sine=f=${300 + 100 * i}:r=48000:d=${frames / fps}`, "-map", "0:v", "-map", "1:a", "-ac", "2", "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac", "-shortest", out, ]); return out; } const md5 = (file) => createHash("md5").update(readFileSync(file)).digest("hex"); const frameMd5 = (file, vf = null) => String(spawnSync("ffmpeg", ["-v", "error", "-i", file, ...(vf ? ["-vf", vf] : []), "-map", "0:v", "-f", "framemd5", "-"]).stdout) .split("\n").filter((l) => l && !l.startsWith("#")).map((l) => l.split(",").at(-1).trim()); const nbFrames = (file) => Number(String(spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]).stdout).trim()); test("the ladder from the master's chunks: each rung chunk encoded once; a second run touches nothing; a changed segment re-encodes only its chunks", { skip: !have && "needs ffmpeg" }, async () => { const fps = 10; const render = { width: 320, height: 180, fps, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0 }; const out = mkdtempSync(path.join(tmpdir(), "variants-chunks-")); const env = process.env.REPORT_VIDEO_CHUNK_FRAMES; process.env.REPORT_VIDEO_CHUNK_FRAMES = "24"; setProgressMode(() => {}); try { const work = path.join(out, "sourced"); const segDir = path.join(out, "segs"); mkdirSync(work, { recursive: true }); mkdirSync(segDir, { recursive: true }); const segments = [25, 40, 33, 30].map((f, i) => segment(segDir, i, f, fps)); const master = path.join(out, "demo.mp4"); await concatWithXfade(segments, render, master, null, null, null, { workDir: work }); const N = nbFrames(master); const chunkCount = JSON.parse(readFileSync(path.join(work, CHUNKS_DIR, CHUNKS_RECORD), "utf8")).chunks.length; assert.ok(chunkCount >= 4, `${chunkCount} chunks`); const variants = [ { name: "master" }, { name: "same", height: 180, crf: 22 }, // Lossless, so the rung is exactly the master scaled, frame for frame. { name: "half", height: 144, crf: 0, preset: "ultrafast" }, { name: "fit", maxMiB: 0.35, preset: "ultrafast" }, ]; const logs = []; const doc1 = await encodeVariants(out, { slug: "demo", variants, onLog: (l) => logs.push(l) }); const by = (doc) => Object.fromEntries(doc.items.map((i) => [i.name, i])); const r1 = by(doc1); // At the master's height: the master, linked. assert.equal(statSync(path.join(out, "demo.same.mp4")).ino, statSync(master).ino); assert.deepEqual(r1.same.encode, { from: "master", linked: true }); assert.equal(r1.half.encode.from, "chunks"); assert.equal(r1.half.encode.encoded, r1.half.encode.chunks); assert.equal(r1.half.height, 144); assert.equal(nbFrames(r1.half.path), N); assert.deepEqual(frameMd5(r1.half.path), frameMd5(master, "scale=-2:144:flags=lanczos"), "the rung is the master at its height, frame for frame"); assert.ok(r1.fit.bytes <= 0.35 * 2 ** 20, `${r1.fit.bytes} bytes`); assert.equal(nbFrames(r1.fit.path), N); const ch = spawnSync("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=channels", "-of", "csv=p=0", r1.fit.path]); assert.equal(String(ch.stdout).trim(), "1", "a size-capped rung's sound is its own"); const rec1 = JSON.parse(readFileSync(path.join(out, LADDER_DIR, LADDER_RECORD), "utf8")); assert.ok(rec1.rungs.fit.fit.scale > 0 && rec1.rungs.fit.fit.scale <= 1); assert.ok(!rec1.rungs.same, "a linked rung has no chunks"); const sums = { half: md5(r1.half.path), fit: md5(r1.fit.path) }; const ids = { half: statSync(r1.half.path).mtimeMs, fit: statSync(r1.fit.path).mtimeMs }; // Again: nothing encoded, nothing joined, the same bytes. const doc2 = await encodeVariants(out, { slug: "demo", variants }); const r2 = by(doc2); for (const n of ["half", "fit"]) { assert.equal(r2[n].encode.unchanged, true, n); assert.equal(r2[n].encode.encoded, 0, n); assert.equal(md5(r2[n].path), sums[n], n); assert.equal(statSync(r2[n].path).mtimeMs, ids[n], `${n} not touched`); } assert.equal(r2.fit.encode.scale, rec1.rungs.fit.fit.scale, "the fit starts where it last landed"); // A twin out/ (what `take --from` makes): the master's chunks and the // ladder's linked, the fit's scale seeded -- its first ladder run encodes nothing. const twin = path.join(out, "twin"); mkdirSync(path.join(twin, "sourced", CHUNKS_DIR), { recursive: true }); mkdirSync(path.join(twin, LADDER_DIR, LADDER_CHUNKS_DIR), { recursive: true }); for (const f of readdirSync(path.join(work, CHUNKS_DIR))) linkSync(path.join(work, CHUNKS_DIR, f), path.join(twin, "sourced", CHUNKS_DIR, f)); for (const f of readdirSync(path.join(out, LADDER_DIR, LADDER_CHUNKS_DIR))) linkSync(path.join(out, LADDER_DIR, LADDER_CHUNKS_DIR, f), path.join(twin, LADDER_DIR, LADDER_CHUNKS_DIR, f)); linkSync(master, path.join(twin, "demo.mp4")); assert.deepEqual(await seedLadderFit(out, twin), ["fit"]); const rt = by(await encodeVariants(twin, { slug: "demo", variants })); assert.equal(rt.half.encode.encoded, 0); assert.equal(rt.fit.encode.encoded, 0, JSON.stringify(rt.fit.encode)); assert.equal(md5(rt.half.path), sums.half); assert.equal(md5(rt.fit.path), sums.fit); rmSync(twin, { recursive: true }); // A rung's file gone: joined again from the cached chunks, to the same bytes. rmSync(r1.half.path); const r3 = by(await encodeVariants(out, { slug: "demo", variants, only: ["half"] })); assert.equal(r3.half.encode.encoded, 0); assert.ok(!r3.half.encode.unchanged); assert.equal(md5(r3.half.path), sums.half, "the join is deterministic"); // One segment re-made with other pixels (the same length): only its chunks, on every rung. segment(segDir, 7, 33, fps, "s2"); await concatWithXfade(segments, render, master, null, null, null, { workDir: work }); const rec = JSON.parse(readFileSync(path.join(work, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); const changed = rec.chunks.filter((c) => c.parts.segments.some((s) => s.name === "s2")).length; assert.ok(changed >= 1 && changed < rec.chunks.length); const r4 = by(await encodeVariants(out, { slug: "demo", variants })); assert.equal(r4.half.encode.encoded, new Set(rec.chunks.filter((c) => c.parts.segments.some((s) => s.name === "s2")).map((c) => c.key)).size); assert.equal(r4.half.encode.reused, r4.half.encode.chunks - r4.half.encode.encoded); assert.deepEqual(frameMd5(r4.half.path), frameMd5(master, "scale=-2:144:flags=lanczos")); assert.ok(r4.fit.encode.encoded < r4.fit.encode.chunks || r4.fit.encode.tries > 1, JSON.stringify(r4.fit.encode)); assert.equal(statSync(path.join(out, "demo.same.mp4")).ino, statSync(master).ino, "the linked rung follows the new master"); // The cache holds what the ladder names, nothing else. const rec4 = JSON.parse(readFileSync(path.join(out, LADDER_DIR, LADDER_RECORD), "utf8")); const named = new Set(Object.values(rec4.rungs).flatMap((r) => r.keys)); const onDisk = readdirSync(path.join(out, LADDER_DIR, LADDER_CHUNKS_DIR)).filter((f) => f.startsWith("rung-")); assert.equal(onDisk.length, named.size); // --whole (chunked: false): the old way, from the whole cut. const r5 = by(await encodeVariants(out, { slug: "demo", variants, only: ["half"], chunked: false })); assert.equal(r5.half.encode.from, "whole"); } finally { setProgressMode("human"); if (env === undefined) delete process.env.REPORT_VIDEO_CHUNK_FRAMES; else process.env.REPORT_VIDEO_CHUNK_FRAMES = env; rmSync(out, { recursive: true, force: true }); } });