Archilyzer · Source

archilyzer

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

commit 77b7a4eb4dde4e4708a2ae3cf4a75630b9f96d16
parent d0de22133672dbf7264bcfb3df1204d2804a2937
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 14:20:03 -0500

umtool: a take's hard-cut deck build is encoded in keyed chunks, one segment's run each -- a post that grew moves the chunks after it without changing them, so a fix re-encodes only its own

mid-6 (a take, so --no-xfade) spent 12.6 of its 30 minutes in ONE overlay
pass over the stream-copied concat: the chunked keyed encode only ran on the
crossfade path. Measured offline on its schedule, a post made 3 s longer
draws no deck frame key the cut did not have -- the rail is already
shift-invariant -- so chunks anchored at segment starts reuse everything but
the touched segment's.

- chunkVideoArgs: with D = 0 a run is each input's join chain and `concat`
  (hardCutVideoGraph); chunkedConcat (was chunkedXfadeConcat) takes
  `hardCut`; the hard-cut deck branch of a build and of --chrome-only use it
  (REPORT_VIDEO_CHUNKED=0 keeps prerail + applyChrome).
- The picture is frame-exact. The copied concat laid each next segment at
  the longer of its picture and sound: 0.30 s (9 frames) by the end of
  mid-6, its last 9 frames cut off by the deck's length.
- The sound: each segment's pinned to its picture's length as PCM, end to
  end, one AAC encode (hardCutSoundArgs / hardCutSound), keyed by the
  segments' contents and begun beside the deck's capture. One graph over 84
  inputs took 241 s; the pins and one encode, 93 s.
- A chunk's chrome layer keys by its `.frame-keys` when it has them: a deck
  recaptured after a prune draws a hair differently per worker, which by
  bytes made every chunk new.

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

Diffstat:
Mumtool/docs/report-video.md | 9+++++++++
Mumtool/report-to-video/README.md | 22+++++++++++++++++++++-
Mumtool/report-to-video/build-video.mjs | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/report-to-video/chunked-encode.mjs | 30++++++++++++++++++++++++++++++
Mumtool/report-to-video/chunked-encode.test.mjs | 184++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/compose-chrome.mjs | 5+++--
6 files changed, 421 insertions(+), 25 deletions(-)

diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1685,6 +1685,15 @@ pruning them, where a `--from` twin finds them. The blur is in the segments' pic twin rebuilds the blurred clips, their crossfade batches and the final overlay pass, and reuses the rest. +**A small fix is a few minutes, not a whole render.** A take renders hard cuts (`--no-xfade`, unless it sets a transition), and +its final picture is encoded in keyed CHUNKS, one segment's run each (report-to-video +`chunked-encode.mjs`): a chunk is encoded again only when its segment or the deck frames over it +changed. A post that grew or shrank moves every later chunk without changing it -- the deck's frames +after it are the same frames, later -- so `--from` the take before re-encodes only the touched +post's chunks. The deck's frames themselves are keyed by what they draw, so a twin of a pruned take +captures them again (about 90 s for a 31-minute cut) and still reuses every chunk. The cut's sound +is one pass (about 90 s, begun beside the capture), reused when no segment changed. + A layer whose page changed reuses its frames FRAME BY FRAME (report-to-video `frame-keys.mjs`, each module's `frameKeys`: the deck, the stamps, the feed, the finale, the thread rail, the flips, the stats, the effects and a teaser): every frame's key is the page's static part and what is on screen diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -1953,6 +1953,26 @@ parsing — wrapping the expression in single quotes is what protects them. 2) encodes that many at once; `REPORT_VIDEO_CHUNKED=0` or `render.chunkedEncode: false` goes back to the batched single pass. It needs no crossfade batches: no chunk opens more than a few segments. +- **A hard-cut deck build is chunked too** (lane fast-fix-render): a take's + `--no-xfade` render, and `--chrome-only` with `transition: 0`. Before, its + picture was the stream-copied concat and then ONE overlay pass over the whole + cut -- 12.6 minutes of mid-6's 30 -- on every take, however small the change. + Now each chunk is one segment's run (a long one cut every 1800 frames from its + first frame), its join chain on it, the deck over it; a post that grew MOVES + the chunks after it without changing their keys (the deck's frame keys are + the same frames, later: measured on mid-6, a post 3 s longer draws no frame + key the cut did not have), so a fix re-encodes the chunks of the segment it + touched. The picture is frame-exact, where the copied concat laid each next + segment at the longer of its picture and its sound (0.30 s, 9 frames, by the + end of mid-6, its last 9 frames cut off); the sound is pinned the same way + (`hardCutSoundArgs`: each segment's sound as PCM exactly as long as its + picture, end to end, encoded once -- begun beside the deck's capture, reused + when no segment changed). +- **A chunk's chrome layers key by their frame keys** when a sequence carries + `.frame-keys` (every keyed layer does): what its frames DRAW, not their bytes. + A layer captured again after a prune draws "a hair differently" per renderer + worker, which by bytes made every chunk of the cut new; by keys, a recaptured + deck is the deck it was. A sequence without them keys by its bytes. - **Chrome frames are reused by their keys** (`frame-keys.mjs`). The deck, the stamps, the feed and the finale are cue-interpreter pages, so what a frame draws is the page less its cue list plus every element's value at that frame @@ -2965,7 +2985,7 @@ container. It is encoded again 6 % lower while it lands over (x264 overshoots: 24.3 MiB at a 23.1 target, measured), four tries at most. **From the master's chunks** (`ladder-chunks.mjs`). When the cut is a chunked -build (`chunked-encode.mjs`, the default with a transition) whose chunks are +build (`chunked-encode.mjs`, the default with a transition or a deck) whose chunks are still in `out/sourced/chunks/`, and the master's video packets are those chunks' (checked by content: the sha256 of the master's packets against the chunks' as the build's mux writes them -- a few seconds, no decode, memoised diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -229,7 +229,7 @@ import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mj import { keepFramesAsked, keptFramesDir, pruneChromeFrames } from "./prune-frames.mjs"; import { encodeSegmentCached, ffmpegIdentity } from "./segment-cache.mjs"; import { - CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, chunkKey, chunkSpans, framesRead, sequenceIdentity, spanSegments, whyRebuilt, + CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, chunkKey, chunkSpans, frameKeysIdentity, framesRead, readFrameKeys, sequenceIdentity, spanSegments, whyRebuilt, } from "./chunked-encode.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. @@ -4552,7 +4552,7 @@ export async function concatWithXfade(segments, render, outPath, railPlan, chrom const D = render.transition ?? 0.5; // The cut itself (dips drawn, no rail): in keyed chunks (chunked-encode.mjs). if (!railPlan && dip && D > 0 && chunkedEncodeOn(render)) { - await chunkedXfadeConcat({ segments, render, outPath, chrome, joins, workDir }); + await chunkedConcat({ segments, render, outPath, chrome, joins, workDir }); return; } const { durs } = await cutOffsets(segments, D, render.fps, joins); @@ -4888,7 +4888,9 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins const { a, b } = span; const { first, last } = spanSegments(span, starts, durs, fps); const segs = segments.slice(first, last + 1); - const g = xfadeGraph(durs.slice(first, last + 1), D, joins ? joins.slice(first, last + 1) : null, render, { + // A hard-cut cut (D = 0, a take's): the run joined as hardCutFilterArgs + // joins the whole cut -- each input's join chain, then `concat`. + const g = D === 0 ? hardCutVideoGraph(segs.length, joins ? joins.slice(first, last + 1) : null, render) : xfadeGraph(durs.slice(first, last + 1), D, joins ? joins.slice(first, last + 1) : null, render, { audio: false, ctx: { hasPrev: first > 0, prevJoin: joins?.[first - 1] ?? null, hasNext: last < segments.length - 1 }, // Offsets to the microsecond: one rounded UP past its frame's timestamp @@ -4964,6 +4966,131 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins } /** + * A run of a hard-cut cut's segments as one picture: each input's join chain + * (its picture half), then `concat` -- hardCutFilterArgs' video side, for a + * chunk of the final encode. One input is its own chain. Pure. + * + * @returns {{ parts: string[], vlab: string }} + */ +export function hardCutVideoGraph(n, joins, render) { + const parts = []; + const vs = []; + for (let i = 0; i < n; i += 1) { + const c = joinInputChain(i, joins?.[i] ?? null, render, { only: "v" }); + parts.push(...c.parts); + vs.push(c.v); + } + if (n === 1) return { parts, vlab: vs[0] }; + parts.push(`${vs.join("")}concat=n=${n}:v=1:a=0[hcv]`); + return { parts, vlab: "[hcv]" }; +} + +/** + * A hard-cut cut's sound (D = 0), as two kinds of ffmpeg run. Pure. + * + * pin(i, seg, out) segment i's sound alone (`-vn`), its join's sound on + * it, laid on its own clock (AUDIO_ON_CLOCK) and PINNED + * to its picture's length in the cut (`durs[i]`, frames + * ÷ fps, hold included) -- as the crossfade's graph pins + * it -- as PCM: an exact number of samples + * encode(list, out) the pins end to end (the concat demuxer: every pin is + * exactly as long as its picture, so each starts on its + * segment's first frame), encoded once + * + * Pinned because a segment's sound routinely ends a few ms off its picture + * (AAC frames do not end on video frames), and the stream-copied concat the + * hard-cut build used to make laid each next segment at the LONGER of the + * two: 34 of mid-6's 84 segments, 0.30 s (9 frames) by the end of its cut, + * the footage and its sound that much behind the deck and its last 9 frames + * cut off. The chunks lay every picture frame-exact; the sound is laid the same. + * + * In pins rather than one graph over every segment: one ffmpeg holding the + * 84 segments open took 241 s for mid-6's sound; the pins, a few at a time, + * and one encode of their PCM take the encode's time (~75 s, native aac). + */ +export function hardCutSoundArgs({ durs, joins = null, render }) { + const head = ["-nostdin", "-v", "error", "-y"]; + const pcm = ["-c:a", "pcm_s16le", "-ar", String(render.audioRate), "-ac", String(render.audioChannels)]; + return { + pin: (i, seg, out) => { + const c = joinInputChain(0, joins?.[i] ?? null, render, { only: "a" }); + const len = durs[i].toFixed(6); + const graph = [...c.parts, `${c.a}${AUDIO_ON_CLOCK},apad=whole_dur=${len},atrim=end=${len},asetpts=PTS-STARTPTS[pa]`].join(";"); + return [...head, "-vn", "-i", seg, "-filter_complex", graph, "-map", "[pa]", ...pcm, "-f", "wav", out]; + }, + encode: (list, out) => [ + ...head, "-f", "concat", "-safe", "0", "-i", list, "-map", "0:a", ...cutAudioEncodeArgs(render), out, + ], + }; +} + +/** The hard-cut sound passes in flight, by their file: the early start and the encode share one. */ +const SOUND_IN_FLIGHT = new Map(); + +/** + * Make (or find) a hard-cut cut's sound: `<dir>/audio-<key>.m4a`, keyed by + * the segments' contents and every argv that makes it (hardCutSoundArgs). + * Started by the build as soon as the segments and joins are known -- beside + * the deck's capture -- and awaited by the chunked encode, which calls it + * again with the same arguments (one pass, shared). Resolves to the file. + * + * @param {{ segments: string[], durs: number[], joins?: Array<object|null>|null, render: object, dir: string, workDir: string, hashes?: string[]|null, ffmpeg?: string|null }} job + */ +export function hardCutSound(job) { + const run = (async () => { + const { segments, durs, joins = null, render, dir, workDir } = job; + const hashes = job.hashes ?? (await new HashMemo(null).hashAll(segments)); + const ffmpeg = job.ffmpeg ?? (await ffmpegIdentity(FFMPEG)); + const a = hardCutSoundArgs({ durs, joins, render }); + const keyArgv = [...segments.map((_, i) => a.pin(i, `<in:${i}>`, "<pin>")), a.encode("<list>", "<out>")]; + const audio = path.join(dir, `audio-${chunkKey({ keyArgv: keyArgv.flat(), inputs: hashes.map((h) => ({ seg: h })), ffmpeg })}.m4a`); + return audio; + })(); + return run.then((audio) => { + if (!SOUND_IN_FLIGHT.has(audio)) { + const made = makeHardCutSound(job, audio).finally(() => SOUND_IN_FLIGHT.delete(audio)); + SOUND_IN_FLIGHT.set(audio, made); + } + return SOUND_IN_FLIGHT.get(audio); + }); +} + +/** + * Begin a hard-cut build's sound (hardCutSound) without waiting for it: its + * failure is the chunked encode's to report, when it asks for the same sound. + */ +export async function startHardCutSound({ segments, render, joins = null, outDir }) { + const { durs } = await cutOffsets(segments, 0, render.fps, joins); + hardCutSound({ segments, durs, joins, render, dir: path.join(outDir, CHUNKS_DIR), workDir: outDir }).catch(() => {}); +} + +async function makeHardCutSound({ segments, durs, joins = null, render, dir, workDir }, audio) { + if (await exists(audio)) { + EMIT("note", { message: "final encode: the cut's sound unchanged — reused" }); + return { audio, reused: true }; + } + const t0 = Date.now(); + const a = hardCutSoundArgs({ durs, joins, render }); + const pins = path.join(workDir, `work-sound-${process.pid}`); + await rm(pins, { recursive: true, force: true }); + await mkdir(pins, { recursive: true }); + try { + const files = segments.map((_, i) => path.join(pins, `pin-${String(i).padStart(4, "0")}.wav`)); + await runPool(segments.map((seg, i) => () => execFileP(FFMPEG, a.pin(i, seg, files[i]), { maxBuffer: 1 << 26 })), 4); + const list = path.join(pins, "pins.txt"); + await writeFile(list, concatListText(files), "utf8"); + await mkdir(dir, { recursive: true }); + const tmp = audio.replace(/\.m4a$/, `.${process.pid}.partial.m4a`); + await execFileP(FFMPEG, a.encode(list, tmp), { maxBuffer: 1 << 26 }); + await rename(tmp, audio); + } finally { + await rm(pins, { recursive: true, force: true }); + } + EMIT("note", { message: `final encode: the cut's sound encoded in ${((Date.now() - t0) / 1000).toFixed(1)}s` }); + return { audio, reused: false }; +} + +/** * The cut's sound in one pass: every segment's audio alone (`-vn`), joined * exactly as xfadeGraph joins it (each pinned to its picture's length, the * mutes, holds, fades and dips on their inputs, the acrossfades), encoded @@ -5030,15 +5157,21 @@ export async function logRebuild(workDir, entry) { } /** - * concatWithXfade's chunked encode (chunked-encode.mjs): plan the chunks, - * key each by its inputs' contents, encode only the ones whose key is not on - * disk (REPORT_VIDEO_CHUNK_JOBS at once), encode the sound once (reused when - * its key matches), and join them into `outPath`. Every chunk's frame count - * is checked, and so is the cut's. + * The chunked final encode (chunked-encode.mjs): plan the chunks, key each by + * its inputs' contents, encode only the ones whose key is not on disk + * (REPORT_VIDEO_CHUNK_JOBS at once), encode the sound once (reused when its + * key matches), and join them into `outPath`. Every chunk's frame count is + * checked, and so is the cut's. + * + * Two callers: concatWithXfade (the crossfaded cut, `D` its transition) and + * the hard-cut deck build (`hardCut`, a take's `--no-xfade`: D = 0, each chunk + * one segment's run, the sound the segments' own, stream-copied when nothing + * is joined) -- which before this re-encoded the whole cut in one overlay + * pass on every build, ~12 minutes for a 31-minute cut. */ -async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, joins = null, workDir }) { +export async function chunkedConcat({ segments, render, outPath, chrome = null, joins = null, workDir, hardCut = false }) { const t0 = Date.now(); - const D = render.transition ?? 0.5; + const D = hardCut ? 0 : render.transition ?? 0.5; const fps = render.fps; const { durs, starts, total } = await cutOffsets(segments, D, fps, joins); const N = Math.round(total * fps); @@ -5060,6 +5193,13 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo if (!h) throw new Error(`chunked encode: segment ${segments[i]} is not a file`); }); + // Each chrome sequence's frame keys, when it carries them (chunked-encode.mjs): + // a chunk then keys by what its frames draw, not by their bytes. + const frameKeysByDir = new Map(); + for (const r of chrome?.regions ?? []) { + const count = WINDOW_REGIONS.has(r.name) ? Number(r.frameCount) : N; + if (!frameKeysByDir.has(r.frames)) frameKeysByDir.set(r.frames, await readFrameKeys(r.frames, count)); + } const plan = []; for (const span of spans) { const proto = chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: "" }); @@ -5068,7 +5208,8 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo for (const inp of proto.inputs) { if (inp.kind === "seg") ids.push({ seg: segHash[inp.index] }); else { - const id = inp.range ? await sequenceIdentity(memo, inp.dir, inp.range) : "none"; + const fk = frameKeysByDir.get(inp.dir); + const id = !inp.range ? "none" : fk ? frameKeysIdentity(fk, inp.range) : await sequenceIdentity(memo, inp.dir, inp.range); ids.push({ seq: id }); layers[inp.region] = id; } @@ -5112,11 +5253,13 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo EMIT("note", { message: ` encode ${ps.length} chunk(s) — ${w} (at ${at})` }); } - // The sound: one pass, keyed by the segments' contents and its argv. - const audioProto = cutAudioArgs({ segments: segments.map((_, i) => `<in:${i}>`), durs, D, render, joins, outPath: "" }).slice(0, -1); - const audioKey = chunkKey({ keyArgv: audioProto, inputs: segHash.map((h) => ({ seg: h })), ffmpeg }); - const audio = path.join(dir, `audio-${audioKey}.m4a`); - const audioJob = async () => { + // The sound: one pass, keyed by the segments' contents and its argv (a + // hard cut's pinned end to end, hardCutSound -- perhaps begun already). + const audioProto = D === 0 ? null : cutAudioArgs({ segments: segments.map((_, i) => `<in:${i}>`), durs, D, render, joins, outPath: "" }).slice(0, -1); + let audio = D === 0 ? null : path.join(dir, `audio-${chunkKey({ keyArgv: audioProto, inputs: segHash.map((h) => ({ seg: h })), ffmpeg })}.m4a`); + const audioJob = D === 0 ? async () => { + audio = (await hardCutSound({ segments, durs, joins, render, dir, workDir, hashes: segHash, ffmpeg })).audio; + } : async () => { if (await exists(audio)) { EMIT("note", { message: "final encode: the cut's sound unchanged — reused" }); return; @@ -6685,6 +6828,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // inputs (null without any). const joins = await cutJoins({ schedule, entries, segments: segs, render }); const prerail = prerailPath(outDir, manifest.slug, D); + if (D === 0 && !opts.chromePreview && chunkedEncodeOn(render)) await startHardCutSound({ segments: segs, render, joins, outDir }); if (opts.chromePreview) { const at = Math.max(0, Math.min(opts.chromePreview.at, schedule.total - 1 / render.fps)); @@ -6710,7 +6854,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const plan = await renderDeck({ manifestPath, render, outDir, variant, schedule }); EMIT("chrome", { phase: "overlay" }); EMIT("concat", { mode: D === 0 ? "hardcut" : "xfade", n: segs.length }); - if (D === 0) { + if (D === 0 && chunkedEncodeOn(render)) { + // In keyed chunks, as the full build's (chunkedConcat). + await chunkedConcat({ segments: segs, render, outPath: dirs.final, chrome: plan, joins, workDir: outDir, hardCut: true }); + } else if (D === 0) { // The hard-cut concat is a stream copy of these very segments; when // nothing changed since it was made it is reused, and the overlay is // the only encode. @@ -6811,6 +6958,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const joins = await cutJoins({ schedule: deck ? schedule : null, entries, segments, render }); const railPlan = opts.noRail ? null : await buildRailPlan(manifest, render, entries, segments, D, outDir); + // A hard-cut deck build's sound needs only the segments and the joins: it + // is begun now, beside the deck's capture, and the chunked encode awaits it. + if (D === 0 && deck && !opts.noChrome && !railPlan && chunkedEncodeOn(render)) await startHardCutSound({ segments, render, joins, outDir }); // The rendered chrome, if this manifest asks for it. Absent, `chromePlan` is // null and every line below behaves exactly as it did -- which is the claim @@ -6857,10 +7007,16 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly await concatHardCut(segments, outDir, prerail, { joins, render }); await assertConcatLength(prerail, railPlan.total, render.fps, "hard-cut concat"); await applyRail(prerail, final, render, railPlan, null, await cutDips(segments, joins)); - } else if (chromePlan) { + } else if (chromePlan && chunkedEncodeOn(render)) { // Only the deck reaches here (the band refused above, and the deck - // refuses a rail). Hard-cut concat to the prerail, then ONE overlay - // re-encode to the final. + // refuses a rail): in keyed chunks, each a segment's run with the deck + // over it, so a take re-encodes only the chunks whose segment or deck + // frames changed -- a post that grew moves the chunks after it, it does + // not change them (chunkedConcat). + await chunkedConcat({ segments, render, outPath: final, chrome: chromePlan, joins, workDir: outDir, hardCut: true }); + } else if (chromePlan) { + // REPORT_VIDEO_CHUNKED=0: hard-cut concat to the prerail, then ONE + // overlay re-encode to the final. await concatHardCut(segments, outDir, prerail, { record: true, joins, render }); await assertConcatLength(prerail, schedule.total, render.fps, "hard-cut concat"); await applyChrome(prerail, final, render, chromePlan, null, await cutDips(segments, joins)); diff --git a/umtool/report-to-video/chunked-encode.mjs b/umtool/report-to-video/chunked-encode.mjs @@ -30,6 +30,16 @@ // different is a new key. Nothing is keyed by a name or a time that could // say "same" about different pixels. // +// A chrome sequence that carries its FRAME KEYS (`.frame-keys`, written by +// compose-chrome beside its `.key`: what each frame draws, frame-keys.mjs) is +// identified by the keys of the frames a chunk reads rather than by their +// bytes. Those keys are the contract the capture already reuses frames by; +// and a layer captured again (its frames pruned after the last mux) draws +// "a hair differently" per renderer worker -- a few pixels, a few levels -- +// which by bytes made every chunk of the cut new. By keys, a recaptured deck +// is the deck it was, and only a chunk whose frames DRAW something else is +// encoded again. A sequence without them is keyed by its bytes, as before. +// // Plain node; every path is a parameter. import { createHash } from "node:crypto"; @@ -213,6 +223,26 @@ export class HashMemo { } } +/** Beside a chrome sequence's `.key`: each frame's key, frame 1 on line 1 (compose-chrome writes it). */ +export const FRAME_KEYS_FILE = ".frame-keys"; + +/** + * A sequence's frame keys, when it has them for exactly `count` frames and is + * complete (its `.key` is written last); else null, and it is keyed by bytes. + */ +export async function readFrameKeys(dir, count) { + if (!(await stat(path.join(dir, ".key")).catch(() => null))?.isFile()) return null; + const text = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").catch(() => null); + if (!text) return null; + const keys = text.split("\n").filter(Boolean); + return keys.length === count ? keys : null; +} + +/** What a run `[lo, hi]` (1-based) of a sequence contributes to a key, by its frame keys. */ +export function frameKeysIdentity(keys, [lo, hi]) { + return `fk:${createHash("sha1").update(keys.slice(lo - 1, hi).join("\n")).digest("hex")}`; +} + /** A frame sequence's file name for 1-based frame `n` (frame_%06d.png). */ export const frameFile = (dir, n) => path.join(dir, `frame_${String(n).padStart(6, "0")}.png`); diff --git a/umtool/report-to-video/chunked-encode.test.mjs b/umtool/report-to-video/chunked-encode.test.mjs @@ -1,5 +1,5 @@ // The chunked final encode (chunked-encode.mjs, build-video's -// chunkedXfadeConcat): the spans a cut is cut into, what a chunk's key covers +// 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 @@ -17,7 +17,9 @@ import test from "node:test"; import { CHUNKS_DIR, CHUNKS_RECORD, HashMemo, chunkKey, chunkSpans, framesRead, spanSegments, whyRebuilt, } from "./chunked-encode.mjs"; -import { chunkVideoArgs, concatWithXfade, dipWindows, setProgressMode, withCutEdits, xfadeConcatArgs } from "./build-video.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", () => { @@ -335,3 +337,181 @@ test("two spans that key alike are encoded once and joined twice", { skip: !have 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; the sound pinned to the picture", { 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})`); + 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 ?? ""))); + } 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 }); + } +}); diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -44,6 +44,7 @@ import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, sha256, t import { GSAP_FILE } from "./chrome-deck.mjs"; import { fxGeometry, threadShotOf } from "./deck.mjs"; import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; +import { FRAME_KEYS_FILE } from "./chunked-encode.mjs"; import { regionCaching, regionModule } from "./modules/index.mjs"; const run = promisify(execFile); @@ -1050,8 +1051,8 @@ export async function composeChrome({ // ---- frame reuse (frame-keys.mjs) -------------------------------------------- -/** Beside a sequence's `.key`: each frame's key, frame 1 on line 1. */ -export const FRAME_KEYS_FILE = ".frame-keys"; +/** Beside a sequence's `.key`: each frame's key, frame 1 on line 1 (the final encode keys its chunks by them). */ +export { FRAME_KEYS_FILE }; const frameName = (n) => `frame_${String(n).padStart(6, "0")}.png`;