// The chunked final encode (chunked-encode.mjs, build-video's // chunkedConcat): the spans a cut is cut into, what a chunk's key covers // (and that a MOVED chunk keys as it did while a changed input does not), and // real ffmpeg runs -- a chunked build of a small cut with joins, a hold, a dip, // a whole-cut chrome sequence and a posts window, losslessly encoded, frame for // frame against the single-pass graph; then a rebuild after one segment // changes, which re-encodes only the chunks that segment is in. // // Run with: node --test umtool/report-to-video/chunked-encode.test.mjs import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { CHUNKS_DIR, CHUNKS_RECORD, HashMemo, chunkKey, chunkSpans, framesRead, spanSegments, whyRebuilt, } from "./chunked-encode.mjs"; import { applyChromeArgs, chunkVideoArgs, chunkedConcat, concatListText, concatWithXfade, dipWindows, hardCutFilterArgs, setProgressMode, withCutEdits, xfadeConcatArgs, } from "./build-video.mjs"; import { scheduleFrom } from "./deck.mjs"; test("chunkSpans: anchored where each segment is fully in, long spans cut from the anchor", () => { // Segments of 100, 60, 400 frames at 10 fps, a 5-frame crossfade. const fps = 10; const durs = [10, 6, 40]; const { starts, total } = scheduleFrom(durs, 0.5); assert.deepEqual(starts.map((s) => Math.round(s * fps)), [0, 95, 150]); const spans = chunkSpans({ starts, durs, D: 0.5, fps, total, max: 1000 }); assert.deepEqual(spans, [{ a: 0, b: 100 }, { a: 100, b: 155 }, { a: 155, b: 550 }]); // Cut every 120 from the anchor; a tail under max/4 (30) joins the piece before. const cut = chunkSpans({ starts, durs, D: 0.5, fps, total, max: 120 }); assert.deepEqual(cut, [{ a: 0, b: 100 }, { a: 100, b: 155 }, { a: 155, b: 275 }, { a: 275, b: 395 }, { a: 395, b: 515 }, { a: 515, b: 550 }]); // Consecutive and complete. for (const s of [spans, cut]) { assert.equal(s[0].a, 0); assert.equal(s.at(-1).b, Math.round(total * fps)); for (let k = 1; k < s.length; k += 1) assert.equal(s[k].a, s[k - 1].b); } // Never inside a dip. const dodged = chunkSpans({ starts, durs, D: 0.5, fps, total, max: 120, avoid: [[270, 290]] }); assert.deepEqual(dodged.map((x) => x.a), [0, 100, 155, 290, 410]); }); test("chunkSpans: an earlier segment growing MOVES the later spans without reshaping them", () => { const fps = 30; const a = [5.5, 20, 31.4, 12, 64]; const b = [7.2, 20, 31.4, 12, 64]; // the intro 1.7 s longer const sa = scheduleFrom(a, 0.5); const sb = scheduleFrom(b, 0.5); const A = chunkSpans({ ...sa, durs: a, D: 0.5, fps, max: 900 }); const B = chunkSpans({ ...sb, durs: b, D: 0.5, fps, max: 900 }); assert.equal(A.length, B.length); const shift = B[1].a - A[1].a; assert.equal(shift, 51); for (let k = 1; k < A.length; k += 1) { assert.equal(B[k].a - A[k].a, shift); assert.equal(B[k].b - A[k].b, shift); } }); test("spanSegments / framesRead", () => { const fps = 10; const durs = [10, 6, 40]; const { starts } = scheduleFrom(durs, 0.5); assert.deepEqual(spanSegments({ a: 0, b: 100 }, starts, durs, fps), { first: 0, last: 1 }); assert.deepEqual(spanSegments({ a: 100, b: 155 }, starts, durs, fps), { first: 1, last: 2 }); assert.deepEqual(spanSegments({ a: 160, b: 300 }, starts, durs, fps), { first: 2, last: 2 }); // A whole-cut layer: frames a+1..b, one more each side. assert.deepEqual(framesRead({ a: 100, b: 155 }, { count: 550 }), [100, 156]); assert.deepEqual(framesRead({ a: 0, b: 100 }, { count: 550 }), [1, 101]); assert.deepEqual(framesRead({ a: 500, b: 550 }, { count: 550 }), [500, 550]); // A window of 40 frames laid at cut frame 120: its frames 1..40 are cut 120..159. assert.deepEqual(framesRead({ a: 100, b: 155 }, { offsetFrames: 120, count: 40 }), [1, 36]); assert.deepEqual(framesRead({ a: 155, b: 300 }, { offsetFrames: 120, count: 40 }), [35, 40]); assert.equal(framesRead({ a: 200, b: 300 }, { offsetFrames: 120, count: 40 }), null); }); test("HashMemo: the bytes, memoised by inode; a hard link is a hit, a rewrite is not", async () => { const dir = mkdtempSync(path.join(tmpdir(), "chunk-memo-")); try { const f = path.join(dir, "a.bin"); writeFileSync(f, "one"); const memo = await HashMemo.open(path.join(dir, "memo.json")); const h1 = await memo.hash(f); linkSync(f, path.join(dir, "b.bin")); assert.equal(await memo.hash(path.join(dir, "b.bin")), h1); assert.equal(memo.hashed, 1, "the link was not read again"); writeFileSync(f, "two"); utimesSync(f, new Date(), new Date(Date.now() + 5000)); const h2 = await memo.hash(f); assert.notEqual(h2, h1); await memo.save(); const again = await HashMemo.open(path.join(dir, "memo.json")); assert.equal(await again.hash(f), h2); assert.equal(again.hashed, 0, "read back from the memo"); assert.equal(await memo.hash(path.join(dir, "missing")), null); } finally { rmSync(dir, { recursive: true, force: true }); } }); const R30 = { width: 64, height: 36, fps: 30, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0 }; test("chunkVideoArgs: a chunk keys the same after the cut before it grew; its own inputs change it", () => { const segs = ["/x/intro.mp4", "/x/c1.mp4", "/x/c2.mp4", "/x/c3.mp4"]; const regions = [{ name: "deck", frames: "/x/chrome/deck-frames", x: 0, y: 20, width: 64, height: 16 }]; const at = (durs) => { const { starts, total } = scheduleFrom(durs, 0.5); const spans = chunkSpans({ starts, durs, D: 0.5, fps: 30, total }); return { durs, starts, spans, N: Math.round(total * 30) }; }; const A = at([5.5, 20, 31.4, 12]); const B = at([7.2, 20, 31.4, 12]); const args = (c, k) => chunkVideoArgs({ segments: segs, durs: c.durs, starts: c.starts, span: c.spans[k], D: 0.5, render: R30, chrome: { regions }, totalFrames: c.N, outPath: "/x/out.mp4", }); for (const k of [1, 2, 3]) { const a = args(A, k); const b = args(B, k); assert.deepEqual(b.keyArgv, a.keyArgv, `chunk ${k}: the same argv in key form`); assert.notDeepEqual(b.argv, a.argv, "the real argv reads other deck frames"); assert.deepEqual(b.inputs.map((x) => x.kind), a.inputs.map((x) => x.kind)); // The deck frames it reads moved with it. const da = a.inputs.find((x) => x.kind === "seq").range; const db = b.inputs.find((x) => x.kind === "seq").range; assert.equal(db[0] - da[0], 51); assert.equal(db[1] - da[1], 51); } // The chunk holding the intro changed. assert.notDeepEqual(args(B, 0).keyArgv, args(A, 0).keyArgv); // Same key form, other contents: other keys. const a1 = args(A, 1); const ids = a1.inputs.map((x, k) => (x.kind === "seg" ? { seg: `s${k}` } : { seq: "d" })); const k0 = chunkKey({ keyArgv: a1.keyArgv, inputs: ids, ffmpeg: "ff" }); assert.equal(chunkKey({ keyArgv: a1.keyArgv, inputs: structuredClone(ids), ffmpeg: "ff" }), k0); assert.notEqual(chunkKey({ keyArgv: a1.keyArgv, inputs: ids.map((x) => (x.seq ? { seq: "e" } : x)), ffmpeg: "ff" }), k0, "a deck frame changed"); assert.notEqual(chunkKey({ keyArgv: a1.keyArgv, inputs: ids.map((x) => (x.seg === "s0" ? { seg: "t" } : x)), ffmpeg: "ff" }), k0, "a segment changed"); assert.notEqual(chunkKey({ keyArgv: a1.keyArgv, inputs: ids, ffmpeg: "ff2" }), k0, "another ffmpeg"); assert.notEqual(chunkKey({ keyArgv: args(A, 1).keyArgv.map((x) => (x === "0" ? "1" : x)), inputs: ids, ffmpeg: "ff" }), k0, "another crf"); }); test("whyRebuilt names what changed", () => { const rec = (seg2, deck) => ({ a: 0, b: 10, anchor: "c1.mp4@15", parts: { segments: [{ name: "c1", id: "1" }, { name: "c2", id: seg2 }], layers: { deck }, graph: "g" }, }); assert.equal(whyRebuilt(rec("2", "d"), []), "first chunked build"); assert.equal(whyRebuilt(rec("2", "d"), [rec("3", "d")]), "segment c2 changed"); assert.equal(whyRebuilt(rec("2", "d"), [rec("2", "e")]), "deck frames changed"); assert.match(whyRebuilt({ ...rec("2", "d"), anchor: "c9.mp4@0" }, [rec("2", "d")]), /new span/); }); // ---- real ffmpeg ------------------------------------------------------------- const have = spawnSync("ffmpeg", ["-version"]).status === 0; const COLOURS = ["red", "green", "blue", "yellow", "magenta", "cyan"]; function run(argv) { const r = spawnSync("ffmpeg", argv, { maxBuffer: 1 << 26 }); assert.equal(r.status, 0, String(r.stderr)); } /** A segment: a moving test pattern tinted per index, a tone. */ 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=64x36: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; } /** A PNG sequence with alpha: `n` frames, each different (testsrc2's counter). */ function sequence(dir, n, fps, w, h) { mkdirSync(dir, { recursive: true }); run([ "-v", "error", "-y", "-f", "lavfi", "-i", `testsrc2=s=${w}x${h}:r=${fps}:d=${n / fps + 1},format=rgba,colorchannelmixer=aa=0.6`, "-frames:v", String(n), path.join(dir, "frame_%06d.png"), ]); } /** Every frame's md5, decoded. */ function frameMd5(file) { const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-map", "0:v", "-f", "framemd5", "-"], { maxBuffer: 1 << 26 }); assert.equal(r.status, 0, String(r.stderr)); return r.stdout.toString().split("\n").filter((l) => l && !l.startsWith("#")).map((l) => l.split(",").pop().trim()); } const probeFrames = (file) => Number(spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]).stdout.toString().trim()); const audioSeconds = (file) => Number(spawnSync("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=duration", "-of", "default=nw=1:nk=1", file]).stdout.toString().trim()); test("a chunked build is the single-pass graph, frame for frame; a changed segment re-encodes only its chunks", { skip: !have }, async () => { const fps = 10; const render = { width: 64, height: 36, fps, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0, palette: { bg: "#101820" } }; const dir = mkdtempSync(path.join(tmpdir(), "chunked-")); const events = []; setProgressMode((e) => events.push(e)); const env = { ...process.env }; process.env.REPORT_VIDEO_CHUNK_FRAMES = "24"; try { const lens = [25, 40, 33, 30, 52]; const segments = lens.map((f, i) => segment(dir, i, f, fps)); const durs0 = lens.map((f) => f / fps); // A hold on segment 1 (its last frame held 0.8 s), a dip at the end of // segment 2 (into "a teaser"), the end fade on the last. const joins = withCutEdits([null, { hold: 0.8, move: null }, null, null, null], 5, { dips: new Map([[2, { seconds: 0.6, lastFrame: 32, black: 0.3 }]]), fade: { seconds: 0.5, lastFrame: 51 }, }); const durs = durs0.map((d, i) => d + (joins?.[i]?.hold ?? 0)); const { starts, total } = scheduleFrom(durs, 0.5); const N = Math.round(total * fps); // Chrome: a whole-cut "deck" and a posts window of 30 frames at frame 40. sequence(path.join(dir, "chrome", "deck-frames"), N, fps, 64, 12); sequence(path.join(dir, "chrome", "posts-s1-frames"), 30, fps, 20, 20); const regions = [ { name: "deck", frames: path.join(dir, "chrome", "deck-frames"), x: 0, y: 24, width: 64, height: 12 }, { name: "posts", segment: "s1", frames: path.join(dir, "chrome", "posts-s1-frames"), x: 40, y: 0, width: 20, height: 20, offset: 4.0, frameCount: 30 }, ]; const chrome = { regions, outLabel: "[hfout]" }; const single = path.join(dir, "single.mp4"); run(xfadeConcatArgs({ segments, durs, render, outPath: single, chrome, joins })); const chunked = path.join(dir, "chunked.mp4"); await concatWithXfade(segments, render, chunked, null, chrome, joins, { workDir: dir }); assert.equal(probeFrames(chunked), N); const want = frameMd5(single); const got = frameMd5(chunked); assert.equal(got.length, want.length); const diff = got.map((h, f) => (h === want[f] ? null : f)).filter((f) => f != null); assert.deepEqual(diff, [], "every frame of the chunked build is the single pass's"); assert.ok(Math.abs(audioSeconds(chunked) - total) < 0.05, `the sound runs the cut (${audioSeconds(chunked)} vs ${total})`); const record = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); assert.ok(record.chunks.length >= 6, `cut into ${record.chunks.length} chunks`); assert.ok(dipWindows(joins, durs, 0.5, fps).length === 1); // Again: everything reused. events.length = 0; await concatWithXfade(segments, render, chunked, null, chrome, joins, { workDir: dir }); assert.ok(events.some((e) => /0 to encode/.test(e.message ?? "")), "nothing encoded the second time"); assert.ok(events.some((e) => /sound unchanged/.test(e.message ?? ""))); assert.deepEqual(frameMd5(chunked), want); // Segment 3 re-made with other pixels (same length): only its chunks. segment(dir, 5, 30, fps, "s3"); events.length = 0; await concatWithXfade(segments, render, chunked, null, chrome, joins, { workDir: dir }); const record2 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); const changed = record2.chunks.filter((c, k) => c.key !== record.chunks[k].key); assert.ok(changed.length >= 1 && changed.length < record.chunks.length, `${changed.length} of ${record.chunks.length} re-encoded`); for (const c of changed) assert.ok(c.parts.segments.some((s) => s.name === "s3"), `a re-encoded chunk holds s3 (${c.anchor})`); for (const c of record2.chunks.filter((x) => !changed.includes(x))) assert.ok(!c.parts.segments.some((s) => s.name === "s3")); assert.ok(events.some((e) => /segment s3 changed/.test(e.message ?? "")), "the note says why"); // And the result is the single pass over the new segments. const single2 = path.join(dir, "single2.mp4"); run(xfadeConcatArgs({ segments, durs, render, outPath: single2, chrome, joins })); assert.deepEqual(frameMd5(chunked), frameMd5(single2)); // A deck frame changed: only the chunks that read it. const f = path.join(dir, "chrome", "deck-frames", "frame_000070.png"); const bytes = readFileSync(path.join(dir, "chrome", "deck-frames", "frame_000010.png")); rmSync(f); writeFileSync(f, bytes); await concatWithXfade(segments, render, chunked, null, chrome, joins, { workDir: dir }); const record3 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); const moved = record3.chunks.filter((c, k) => c.key !== record2.chunks[k].key); assert.ok(moved.length >= 1 && moved.length <= 2, `${moved.length} chunk(s) read frame 70`); for (const c of moved) assert.ok(c.a <= 70 && c.b >= 69, `chunk ${c.a}–${c.b} reads frame 70`); const single3 = path.join(dir, "single3.mp4"); run(xfadeConcatArgs({ segments, durs, render, outPath: single3, chrome, joins })); assert.deepEqual(frameMd5(chunked), frameMd5(single3)); // The chunks dir holds this cut's chunks and nothing else. const files = readdirSync(path.join(dir, CHUNKS_DIR)).filter((n) => n.startsWith("chunk-")); assert.equal(files.length, record3.chunks.length); } finally { setProgressMode("human"); for (const k of Object.keys(process.env)) if (!(k in env)) delete process.env[k]; rmSync(dir, { recursive: true, force: true }); } }); test("at 30 fps the chunks hold exactly the cut's frames (offsets to the microsecond)", { skip: !have }, async () => { const fps = 30; const dir = mkdtempSync(path.join(tmpdir(), "chunked30-")); setProgressMode(() => {}); process.env.REPORT_VIDEO_CHUNK_FRAMES = "40"; try { // Lengths whose offsets round UP at three decimals (k/30 with k mod 3 = 2). const lens = [62, 47, 53, 71]; const segments = lens.map((f, i) => segment(dir, i, f, fps)); const durs = lens.map((f) => f / fps); const { total } = scheduleFrom(durs, 0.5); const out = path.join(dir, "cut.mp4"); await concatWithXfade(segments, R30, out, null, null, null, { workDir: dir }); assert.equal(probeFrames(out), Math.round(total * fps)); } finally { setProgressMode("human"); delete process.env.REPORT_VIDEO_CHUNK_FRAMES; rmSync(dir, { recursive: true, force: true }); } }); test("two spans that key alike are encoded once and joined twice", { skip: !have }, async () => { const fps = 10; const render = { width: 64, height: 36, fps, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0 }; const dir = mkdtempSync(path.join(tmpdir(), "chunked-dup-")); const events = []; setProgressMode((e) => events.push(e)); try { // The same segment four times: the middle spans are the same pixels. const one = segment(dir, 1, 30, fps, "same"); const segments = [0, 1, 2, 3].map((k) => { const f = path.join(dir, `s${k}.mp4`); writeFileSync(f, readFileSync(one)); return f; }); const out = path.join(dir, "cut.mp4"); await concatWithXfade(segments, render, out, null, null, null, { workDir: dir }); const rec = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); const keys = rec.chunks.map((c) => c.key); assert.ok(new Set(keys).size < keys.length, `some spans key alike (${keys.join(" ")})`); const encoded = events.filter((e) => /^final encode: chunk \d+\/\d+/.test(e.message ?? "")).length; assert.equal(encoded, new Set(keys).size, "each key encoded once"); assert.equal(probeFrames(out), Math.round(scheduleFrom([3, 3, 3, 3], 0.5).total * fps)); } finally { setProgressMode("human"); rmSync(dir, { recursive: true, force: true }); } }); // ---- the hard-cut deck build (a take's --no-xfade) ---------------------------- /** A segment whose sound runs `extra` seconds past its picture (as an AAC-padded one does). */ function longSoundSegment(dir, i, frames, fps, extra) { const out = path.join(dir, `l${i}.mp4`); run([ "-v", "error", "-y", "-f", "lavfi", "-i", `testsrc2=s=64x36: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 + extra}`, "-map", "0:v", "-map", "1:a", "-ac", "2", "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac", out, ]); return out; } /** A sequence directory made of other frames (hard links), with frame keys when `keys` is given. */ function linkedSequence(dir, files, keys = null) { rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); files.forEach((f, k) => linkSync(f, path.join(dir, `frame_${String(k + 1).padStart(6, "0")}.png`))); if (keys) { writeFileSync(path.join(dir, ".frame-keys"), keys.join("\n") + "\n"); writeFileSync(path.join(dir, ".key"), "k\n"); } } const R10 = { width: 64, height: 36, fps: 10, transition: 0, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0, palette: { bg: "#101820" } }; test("a chunked hard-cut deck build is the hard-cut concat and its overlay pass, frame for frame, with NO drift: each segment at its own frame, its sound with it", { skip: !have }, async () => { const fps = 10; const dir = mkdtempSync(path.join(tmpdir(), "chunked-hc-")); const events = []; setProgressMode((e) => events.push(e)); process.env.REPORT_VIDEO_CHUNK_FRAMES = "24"; try { // Each segment's sound runs past its picture (0.15 s): a stream-copied // concat laid each next segment that much late. const lens = [25, 40, 33, 30]; const segments = lens.map((f, i) => longSoundSegment(dir, i, f, fps, 0.15)); const N = lens.reduce((a, b) => a + b, 0); sequence(path.join(dir, "chrome", "deck-frames"), N, fps, 64, 12); const chrome = { regions: [{ name: "deck", frames: path.join(dir, "chrome", "deck-frames"), x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" }; // The old path's drift: the copied concat is longer than the segments' frames. const list = path.join(dir, "list.txt"); writeFileSync(list, concatListText(segments)); const copied = path.join(dir, "copied.mp4"); run(["-v", "error", "-y", "-f", "concat", "-safe", "0", "-fflags", "+genpts", "-i", list, "-c", "copy", copied]); assert.ok(audioSeconds(copied) > N / fps + 0.4, `the copy laid each segment by its sound (${audioSeconds(copied)} vs ${N / fps})`); // Frame-exact: the segments' pictures end to end (lossless; a silent // track for the overlay pass to copy), then one overlay pass. const prerail = path.join(dir, "prerail.mp4"); run([ "-v", "error", "-y", ...segments.flatMap((f) => ["-i", f]), "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-filter_complex", `${segments.map((_, i) => `[${i}:v]`).join("")}concat=n=${segments.length}:v=1:a=0[v]`, "-map", "[v]", "-map", `${segments.length}:a`, "-shortest", "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac", prerail, ]); assert.equal(probeFrames(prerail), N); const single = path.join(dir, "single.mp4"); run(applyChromeArgs(prerail, single, R10, chrome).slice(1)); const chunked = path.join(dir, "chunked.mp4"); await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true }); assert.equal(probeFrames(chunked), N); const want = frameMd5(single); const got = frameMd5(chunked); assert.equal(got.length, want.length); assert.deepEqual(got.map((h, f) => (h === want[f] ? null : f)).filter((f) => f != null), [], "every frame is the overlay pass's"); // The sound pinned to the picture: as long as the cut, every segment's at its own frame. assert.ok(Math.abs(audioSeconds(chunked) - N / fps) < 0.03, `the sound runs the cut (${audioSeconds(chunked)} vs ${N / fps})`); // NO DRIFT (lane/join-continuity: mid-7's master ran 0.33-0.385 s late on its schedule by the end, // the concat demuxer placing each file by its longer stream). The master is the segments' // pictures summed, frame for frame; each segment's first frame is at its schedule's frame and // its own tone is playing just after it -- where the copied concat had the one before still. const starts = lens.map((_, i) => lens.slice(0, i).reduce((a, b) => a + b, 0)); // (Without the deck -- whose overlay converts every pixel through RGB -- the lossless master is the // segments' own frames, exactly.) const bareDir = path.join(dir, "bare"); mkdirSync(bareDir); const bare = path.join(bareDir, "bare.mp4"); await chunkedConcat({ segments, render: R10, outPath: bare, workDir: bareDir, hardCut: true }); const master = frameMd5(bare); assert.equal(master.length, lens.reduce((a, b) => a + b, 0), "the master is the sum of the segments' pictures"); segments.forEach((f, i) => { assert.deepEqual(master.slice(starts[i], starts[i] + lens[i]), frameMd5(f), `segment ${i} is the master's frames ${starts[i]}-${starts[i] + lens[i] - 1}, exactly`); }); const toneAt = (file, at) => { const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(at), "-t", "0.2", "-i", file, "-map", "0:a", "-ac", "1", "-ar", "48000", "-f", "s16le", "-"], { maxBuffer: 1 << 24 }); const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, r.stdout.length >> 1); let z = 0; for (let k = 1; k < pcm.length; k += 1) if ((pcm[k - 1] < 0) !== (pcm[k] < 0)) z += 1; return z / 2 / (pcm.length / 48000); }; starts.forEach((s, i) => { const hz = toneAt(chunked, s / fps + 0.05); assert.ok(Math.abs(hz - (300 + 100 * i)) < 40, `segment ${i}'s sound starts with its picture (${hz.toFixed(0)} Hz, want ${300 + 100 * i})`); }); // (The copied concat, for contrast, is still playing segment 2's tone where segment 3's picture starts.) assert.ok(Math.abs(toneAt(copied, starts[3] / fps + 0.05) - 600) >= 40, "the copy drifted"); const record = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); // Anchored at each segment's start, a long one cut every 24 frames from it. assert.deepEqual(record.chunks.map((c) => [c.a, c.b]), [[0, 25], [25, 49], [49, 65], [65, 89], [89, 98], [98, 122], [122, 128]]); for (const c of record.chunks) assert.equal(c.parts.segments.length, 1, "a hard-cut chunk is one segment's run"); // Again: nothing encoded. events.length = 0; await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true }); assert.ok(events.some((e) => /0 to encode/.test(e.message ?? "")), "nothing encoded the second time"); assert.ok(events.some((e) => /sound unchanged/.test(e.message ?? ""))); // Segment 2's picture made again, its sound the same packets (a caption // fixed): its chunks are encoded, the cut's sound is not. const other = longSoundSegment(dir, 5, 33, fps, 0.15); const remade = path.join(dir, "remade.mp4"); run(["-v", "error", "-y", "-i", other, "-i", segments[2], "-map", "0:v", "-map", "1:a", "-c", "copy", remade]); rmSync(segments[2]); linkSync(remade, segments[2]); events.length = 0; await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true }); assert.ok(events.some((e) => /5\/7 chunk\(s\) unchanged/.test(e.message ?? "")), events.map((e) => e.message).join("\n")); assert.ok(events.some((e) => /sound unchanged/.test(e.message ?? "")), "a new picture over the same sound keeps the cut's sound"); } finally { setProgressMode("human"); delete process.env.REPORT_VIDEO_CHUNK_FRAMES; rmSync(dir, { recursive: true, force: true }); } }); test("a chunked hard-cut build with joins (a hold, a dip, the end fade) is hardCutFilterArgs and the overlay, frame for frame", { skip: !have }, async () => { const fps = 10; const dir = mkdtempSync(path.join(tmpdir(), "chunked-hcj-")); setProgressMode(() => {}); process.env.REPORT_VIDEO_CHUNK_FRAMES = "24"; try { const lens = [25, 40, 33, 30]; const segments = lens.map((f, i) => segment(dir, i, f, fps)); const joins = withCutEdits([null, { hold: 0.8, move: null }, null, null], 4, { dips: new Map([[2, { seconds: 0.6, lastFrame: 32, black: 0.3 }]]), fade: { seconds: 0.5, lastFrame: 29 }, }); const durs = lens.map((f, i) => f / fps + (joins?.[i]?.hold ?? 0)); const N = Math.round(scheduleFrom(durs, 0).total * fps); sequence(path.join(dir, "chrome", "deck-frames"), N, fps, 64, 12); const chrome = { regions: [{ name: "deck", frames: path.join(dir, "chrome", "deck-frames"), x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" }; const prerail = path.join(dir, "prerail.mp4"); run(hardCutFilterArgs(segments, joins, R10, prerail).slice(1)); const single = path.join(dir, "single.mp4"); run(applyChromeArgs(prerail, single, R10, chrome, null, dipWindows(joins, durs, 0, fps)).slice(1)); const chunked = path.join(dir, "chunked.mp4"); await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, joins, workDir: dir, hardCut: true }); assert.equal(probeFrames(chunked), N); assert.deepEqual(frameMd5(chunked), frameMd5(single)); assert.ok(Math.abs(audioSeconds(chunked) - N / fps) < 0.05, `the sound runs the cut (${audioSeconds(chunked)} vs ${N / fps})`); } finally { setProgressMode("human"); delete process.env.REPORT_VIDEO_CHUNK_FRAMES; rmSync(dir, { recursive: true, force: true }); } }); test("a post that grew re-encodes its own chunks only: the deck after it MOVED, keyed by bytes or by its frame keys", { skip: !have }, async () => { const fps = 10; const dir = mkdtempSync(path.join(tmpdir(), "chunked-hcs-")); const events = []; setProgressMode((e) => events.push(e)); try { const lens = [25, 30, 33, 30]; const segments = lens.map((f, i) => segment(dir, i, f, fps)); const N = lens.reduce((a, b) => a + b, 0); // The deck: one frame per cut frame, and its frame keys (here: the frame's own number). const pool = path.join(dir, "pool"); sequence(pool, N + 20, fps, 64, 12); const poolFile = (n) => path.join(pool, `frame_${String(n).padStart(6, "0")}.png`); const deck = path.join(dir, "chrome", "deck-frames"); const framesA = Array.from({ length: N }, (_, k) => poolFile(k + 1)); linkedSequence(deck, framesA, framesA.map((_, k) => `f${k + 1}`)); const chrome = { regions: [{ name: "deck", frames: deck, x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" }; const out = path.join(dir, "cut.mp4"); await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true }); const rec1 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); assert.equal(rec1.chunks.length, 4); // Segment 1 made 7 frames longer; the deck holds its last frame 7 frames more // and is otherwise the same frames, later. segments[1] = segment(dir, 7, 37, fps, "s1"); const grown = [...framesA.slice(0, 55), ...Array(7).fill(framesA[54]), ...framesA.slice(55)]; const grownKeys = [...Array.from({ length: 55 }, (_, k) => `f${k + 1}`), ...Array(7).fill("f55"), ...Array.from({ length: N - 55 }, (_, k) => `f${k + 56}`)]; linkedSequence(deck, grown, grownKeys); events.length = 0; await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true }); const rec2 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); assert.deepEqual(rec2.chunks.map((c) => c.a), [0, 25, 62, 95]); const enc = rec2.chunks.filter((c, k) => c.key !== rec1.chunks[k].key).map((c) => c.anchor); assert.deepEqual(enc, ["s1.mp4@0"], "only the grown segment's chunk is encoded"); assert.ok(events.some((e) => /3\/4 chunk\(s\) unchanged/.test(e.message ?? "")), events.map((e) => e.message).join("\n")); assert.equal(probeFrames(out), N + 7); // The deck captured again, a hair different (other bytes), drawing the same: by its keys, nothing to encode. const other = Array.from({ length: N + 7 }, (_, k) => poolFile(((k + 3) % (N + 20)) + 1)); linkedSequence(deck, other, grownKeys); events.length = 0; await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true }); assert.ok(events.some((e) => /0 to encode/.test(e.message ?? "")), "recaptured frames with the same keys reuse every chunk"); // Without frame keys the same frames are other bytes: every chunk again. linkedSequence(deck, other); events.length = 0; await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true }); assert.ok(events.some((e) => /0\/4 chunk\(s\) unchanged/.test(e.message ?? "")), "by bytes, other frames are other chunks"); } finally { setProgressMode("human"); rmSync(dir, { recursive: true, force: true }); } });