// The variant ladder's cache rule (ladder-chunks.mjs): a rung chunk's key is // the master chunk's key, the rung's settings and ffmpeg -- nothing else; the // key -> file function encodes only what is not on disk; and a master is // recognised as made of its chunks by content, not by a record's say-so. // // Run with: node --test umtool/report-to-video/ladder-chunks.test.mjs import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { concatList, encodeChunkCached, isLadderChunkFile, masterFromChunks, parseStreamHash, rungAudioKey, rungChunkArgs, rungChunkKey, rungJoinArgs, } from "./ladder-chunks.mjs"; import { CHUNKS_DIR } from "./chunked-encode.mjs"; import { concatWithXfade, setProgressMode, xfadeConcatArgs } from "./build-video.mjs"; import { scheduleFrom } from "./deck.mjs"; const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); test("rungChunkKey: the master chunk, the rung's pixels and ffmpeg -- not a name, not a size cap", () => { const rung = { kind: "crf", height: 720, srcHeight: 1080, crf: 23, preset: "medium" }; const k = rungChunkKey({ chunkKey: "abc", rung, ffmpeg: "ff1" }); assert.match(k, /^[0-9a-f]{24}$/); assert.equal(rungChunkKey({ chunkKey: "abc", rung: { ...rung, name: "720p", maxMiB: 9 }, ffmpeg: "ff1" }), k); assert.equal(rungChunkKey({ chunkKey: "abc", rung: { ...rung, preset: undefined }, ffmpeg: "ff1" }), k, "medium is the default preset"); for (const other of [ { chunkKey: "abd", rung, ffmpeg: "ff1" }, { chunkKey: "abc", rung: { ...rung, crf: 22 }, ffmpeg: "ff1" }, { chunkKey: "abc", rung: { ...rung, height: 480 }, ffmpeg: "ff1" }, { chunkKey: "abc", rung: { ...rung, preset: "slow" }, ffmpeg: "ff1" }, { chunkKey: "abc", rung, ffmpeg: "ff2" }, { chunkKey: "abc", rung: { kind: "abr", height: 720, srcHeight: 1080, videoKbps: 900 }, ffmpeg: "ff1" }, ]) assert.notEqual(rungChunkKey(other), k, JSON.stringify(other)); const abr = { kind: "abr", height: 480, srcHeight: 1080, videoKbps: 200 }; assert.notEqual(rungChunkKey({ chunkKey: "abc", rung: abr, ffmpeg: "f" }), rungChunkKey({ chunkKey: "abc", rung: { ...abr, videoKbps: 188 }, ffmpeg: "f" })); assert.throws(() => rungChunkKey({ chunkKey: "", rung, ffmpeg: "f" }), /master chunk's key/); assert.notEqual(rungAudioKey({ audioHash: "h", audio: { kbps: 48, channels: 1 }, ffmpeg: "f" }), rungAudioKey({ audioHash: "h", audio: { kbps: 96, channels: 2 }, ffmpeg: "f" })); }); test("the argvs: scaled only below the source; crf or bitrate; the join copies, the master's sound unless given one", () => { const crf = rungChunkArgs({ input: "in.mp4", out: "o.mp4", rung: { kind: "crf", height: 720, srcHeight: 1080, crf: 23 } }); assert.ok(crf.includes("scale=-2:720:flags=lanczos")); assert.deepEqual(crf.slice(crf.indexOf("-crf"), crf.indexOf("-crf") + 2), ["-crf", "23"]); assert.ok(crf.includes("-an") && crf.at(-1) === "o.mp4"); const abr = rungChunkArgs({ input: "in.mp4", out: "o.mp4", rung: { kind: "abr", height: 1080, srcHeight: 1080, videoKbps: 900, preset: "fast" } }); assert.ok(!abr.includes("-vf")); assert.ok(abr.includes("900k") && abr.includes("fast") && !abr.includes("-crf")); const join = rungJoinArgs({ listFile: "l.txt", master: "m.mp4", out: "x.mp4" }); assert.ok(join.includes("1:a?") && join.includes("copy") && join.includes("+faststart")); assert.ok(rungJoinArgs({ listFile: "l.txt", master: "m.mp4", audio: "a.m4a", out: "x.mp4" }).includes("2:a:0")); assert.equal(concatList(["/a/b c.mp4", "/a/it's.mp4"]), "file '/a/b c.mp4'\nfile '/a/it'\\''s.mp4'\n"); assert.ok(isLadderChunkFile("rung-FAKE-TEST-VALUE01234567.mp4") && isLadderChunkFile("audio-FAKE-TEST-VALUE01234567.m4a")); assert.ok(!isLadderChunkFile("rung-0123.mp4") && !isLadderChunkFile(".rung-FAKE-TEST-VALUE01234567.1.partial.mp4")); assert.deepEqual(parseStreamHash("0,v,SHA256=aa\n1,a,SHA256=bb\n"), { v: "aa", a: "bb" }); }); test("encodeChunkCached: encoded once, then found; a wrong frame count is never kept", async () => { const dir = mkdtempSync(path.join(tmpdir(), "ladder-cache-")); try { let calls = 0; const encode = async (tmp) => { calls += 1; writeFileSync(tmp, "pixels"); }; const countFrames = async (f) => (existsSync(f) ? 12 : null); const a = await encodeChunkCached({ dir, key: "k".repeat(24), frames: 12, encode, countFrames }); assert.equal(a.reused, false); assert.equal(path.basename(a.file), `rung-${"k".repeat(24)}.mp4`); const b = await encodeChunkCached({ dir, key: "k".repeat(24), frames: 12, encode, countFrames }); assert.equal(b.reused, true); assert.equal(calls, 1); await assert.rejects(encodeChunkCached({ dir, key: "j".repeat(24), frames: 13, encode, countFrames }), /encoded 12 frames, expected 13/); assert.deepEqual(readdirSync(dir), [`rung-${"k".repeat(24)}.mp4`], "nothing half-made left"); } finally { rmSync(dir, { recursive: true, force: true }); } }); function run(argv) { const r = spawnSync("ffmpeg", argv); assert.equal(r.status, 0, String(r.stderr)); } function segment(dir, i, frames, fps, name = `s${i}`, size = "128x72") { const out = path.join(dir, `${name}.mp4`); run([ "-v", "error", "-y", "-f", "lavfi", "-i", `testsrc2=s=${size}: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; } test("masterFromChunks: a chunked master is its chunks; one built another way since is not", { skip: !have && "needs ffmpeg" }, async () => { const fps = 10; const render = { width: 128, height: 72, fps, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0 }; const root = mkdtempSync(path.join(tmpdir(), "ladder-master-")); const env = process.env.REPORT_VIDEO_CHUNK_FRAMES; process.env.REPORT_VIDEO_CHUNK_FRAMES = "24"; setProgressMode(() => {}); try { const work = path.join(root, "sourced"); mkdirSync(work, { recursive: true }); const segments = [25, 40, 33].map((f, i) => segment(root, i, f, fps)); const master = path.join(root, "demo.mp4"); await concatWithXfade(segments, render, master, null, null, null, { workDir: work }); const chunksDir = path.join(work, CHUNKS_DIR); const listFile = path.join(root, "list.txt"); const m = await masterFromChunks({ master, chunksDir, listFile }); assert.equal(m.ok, true, m.why); assert.ok(m.chunks.length >= 3); assert.equal(m.frames, Math.round(scheduleFrom([2.5, 4, 3.3], 0.5).total * fps)); assert.ok(m.memo.videoHash && m.memo.audioHash && m.memo.id); // The memo answers for the same master and record without hashing. const again = await masterFromChunks({ master, chunksDir, listFile, memo: { ...m.memo, videoHash: "memoised" } }); assert.equal(again.ok && again.memo.videoHash, "memoised"); // The same cut built in one pass (the record still on disk): not these chunks. const durs = [2.5, 4, 3.3]; run(xfadeConcatArgs({ segments, durs, render: { ...render, crf: 30 }, outPath: path.join(root, "one.mp4"), chrome: null, joins: null }).slice(0)); rmSync(master); writeFileSync(master, ""); run(["-v", "error", "-y", "-i", path.join(root, "one.mp4"), "-c", "copy", master]); const other = await masterFromChunks({ master, chunksDir, listFile, memo: m.memo }); assert.equal(other.ok, false); assert.match(other.why, /not these chunks/); // A chunk gone; no record. rmSync(path.join(chunksDir, m.chunks[1].file)); assert.match((await masterFromChunks({ master, chunksDir, listFile })).why, /is gone/); rmSync(chunksDir, { recursive: true }); assert.match((await masterFromChunks({ master, chunksDir, listFile })).why, /no chunk record/); } finally { setProgressMode("human"); if (env === undefined) delete process.env.REPORT_VIDEO_CHUNK_FRAMES; else process.env.REPORT_VIDEO_CHUNK_FRAMES = env; rmSync(root, { recursive: true, force: true }); } });