import { test } from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { execa } from "execa"; import type { Paths } from "../lib/paths"; import { compactOne, compactSavedVideos, clearKeptFailedEncode, listCompactionReview, listKeptFailedEncodes, listKeptOriginals, sweepCompactingMarkers, planCompaction, type CompactDeps, type Presence, } from "./compactSavedVideos"; import { compareCuts, cutIsOffset, encodeChunkArgs, ffmpegHas, fullDecode, keepMinStep, keptSourceFrames, planChunks, scanVideoPackets, type ChunkPlan, type EncodeSettings, } from "../lib/compactMedia-server"; import { DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, type SavedVideoCompactionSettings } from "../lib/savedVideoCompaction"; import { SavedPointerChangedError, dropSavedVideo, loadSavedVideo, persistSourceVideo, restoreSavedVideoProvenance, savedVideoPointerPath, unpersistSavedVideo, } from "../lib/savedVideo-server"; import { compactedOriginalOf, savedVideoPath } from "../lib/savedVideo"; import { keepDownloadAsAlternate, planSavedContainer } from "../ytdlp/savedAlternates"; import { CLOCK_FILE, CLOCK_VERSION } from "../lib/recordingClock.mjs"; import { decidePlayable } from "../lib/playableMedia"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/compactSavedVideos.test.ts // // The compaction job's flow over a temp store, on a few seconds of lavfi test // pattern and tone made here by ffmpeg. The encoder is STUBBED in most flow // tests (x264 ultrafast, the same seek, end and frame-rate handling), so they // run without libsvtav1 and in seconds; two run the real SVT-AV1 encode, one // of them on the DEFAULT thresholds, skipped where this ffmpeg has no // libsvtav1. Every check but the stubbed ones is real (the whole-file // comparison, the gap and start checks, the stream inventory). The review's // probes (probe1…probe5) are tests here. Skipped without ffmpeg/ffprobe. async function have(bin: string): Promise { return execa(bin, ["-version"]).then( () => true, () => false, ); } const tools = (await have("ffmpeg")) && (await have("ffprobe")); const svt = tools && (await ffmpegHas("ffmpeg", "encoders", "libsvtav1")); const vmaf = tools && (await ffmpegHas("ffmpeg", "filters", "libvmaf")); const NO_TOOLS = !tools && "ffmpeg/ffprobe not installed"; const NO_SVT = NO_TOOLS || (!svt && "this ffmpeg has no libsvtav1"); const ORIGINAL = "source-media.mp4"; type Gen = { gen?: string; seconds?: number; fps?: number | string; gop?: number; offset?: number; ext?: string; bf?: number; size?: string; // A LIVE RECORDING'S DROPPED FRAMES: source frames [from, to] removed, every // other frame keeping its own timestamp (a gap, as a Kick stream has). drop?: [number, number][]; // …or the same as one select expression of n (dropped where true). dropExpr?: string; // A white frame pair at this second, and a click in the sound at the same // second: whether picture and sound still meet after a gap. flash?: number; }; async function makeSource(file: string, g: Gen = {}): Promise { const seconds = g.seconds ?? 6; const fps = g.fps ?? 60; const vf = [ ...(g.flash !== undefined ? [`drawbox=c=white:t=fill:enable='between(t,${g.flash - 0.001},${g.flash + 0.03})'`] : []), ...(g.drop?.length ? [`select='not(${g.drop.map(([a, b]) => `between(n,${a},${b})`).join("+")})'`] : []), ...(g.dropExpr ? [`select='not(${g.dropExpr})'`] : []), ]; const sound = g.flash !== undefined ? `aevalsrc=exprs='0.2*sin(2*PI*440*t)+if(between(t,${g.flash},${g.flash + 0.004}),0.7,0)':s=48000:d=${seconds}` : `sine=frequency=440:duration=${seconds}`; const [num, den] = String(fps).split("/").map(Number); const gop = g.gop ?? Math.round(num / (den || 1)) * 2; await execa("ffmpeg", [ "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `${g.gen ?? "testsrc"}=size=${g.size ?? "320x180"}:rate=${fps}:duration=${seconds}`, "-f", "lavfi", "-i", sound, ...(vf.length ? ["-vf", vf.join(","), "-fps_mode", "passthrough"] : []), "-c:v", "libx264", "-preset", g.bf ? "veryfast" : "ultrafast", ...(g.bf ? ["-bf", String(g.bf)] : []), "-g", String(gop), "-keyint_min", String(gop), "-sc_threshold", "0", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "64k", "-shortest", ...(g.offset ? ["-output_ts_offset", String(g.offset)] : []), file, ]); } const sha = async (file: string) => createHash("sha256").update(await readFile(file)).digest("hex"); type Fx = { root: string; paths: Paths; videoDir: string; storeDir: string; source: string; sourceSha: string; pointerText: () => Promise; }; const sources = new Map(); async function withVideo( opts: { platform?: string; keepReason?: string; slug?: string; id?: string; gen?: Gen } = {}, fn: (f: Fx) => Promise, ): Promise { const root = await mkdtemp(path.join(tmpdir(), "compact-")); const paths = { transcriptsDir: root, channelsDir: path.join(root, "channels"), savedVideosDir: path.join(root, "saved-videos"), ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "", } as Paths; const slug = opts.slug ?? "kick"; const id = opts.id ?? "v1"; const videoDir = path.join(paths.channelsDir, slug, "data", id); const storeDir = path.join(paths.savedVideosDir, slug, id); await mkdir(videoDir, { recursive: true }); await mkdir(storeDir, { recursive: true }); await writeFile( path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ handling: "transcribe", platform: opts.platform ?? "kick", name: slug }), ); const ext = opts.gen?.ext ?? "mp4"; const key = JSON.stringify(opts.gen ?? {}); if (!sources.has(key)) { const f = path.join(await mkdtemp(path.join(tmpdir(), "compact-src-")), `source-media.${ext}`); await makeSource(f, opts.gen); sources.set(key, f); } const file = `source-media.${ext}`; const source = path.join(storeDir, file); await writeFile(source, await readFile(sources.get(key)!)); const bytes = (await stat(source)).size; await writeFile( savedVideoPointerPath(videoDir), JSON.stringify({ storedAt: "2026-11-01T00:00:00.000Z", dir: storeDir, file, bytes, keepReason: opts.keepReason ?? "pin", format: { preset: "original", height: 180, vcodec: "avc1" }, }) + "\n", ); try { await fn({ root, paths, videoDir, storeDir, source, sourceSha: await sha(source), // The pointer as it was, but for the source's sha256 the run records on // it (what the backup step does): that one must be the file's own. pointerText: async () => { const raw = JSON.parse(await readFile(savedVideoPointerPath(videoDir), "utf8")); if (raw.sha256 !== undefined) assert.equal(raw.sha256, await sha(source)); delete raw.sha256; return JSON.stringify(raw); }, }); } finally { await rm(root, { recursive: true, force: true }); } } // Chunks of 2 s (the settings' floor is a minute; the controller takes what // it is given), three spread samples, the original dropped after verify. const SETTINGS: SavedVideoCompactionSettings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3, dropOriginal: "after-verify", }; // SVT-AV1's own parameters, dropped where x264 takes its place. function stripSvt(args: string[]): void { const j = args.indexOf("-svtav1-params"); if (j >= 0) args.splice(j, 2); } // x264 in SVT-AV1's place: the same seek, end, frame-rate handling and clock. async function x264Chunk(o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string }, crf = 18, defect?: string): Promise { const args = encodeChunkArgs(o.src, o.chunk, o.settings, o.out); const i = args.indexOf("libsvtav1"); args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", String(crf)); stripSvt(args); if (defect) { const v = args.indexOf("-vf"); if (v >= 0) args[v + 1] = `${args[v + 1]},${defect}`; else args.splice(args.indexOf("-c:v"), 0, "-vf", defect); } await execa("ffmpeg", args); } const ON: Presence = { onPlatform: true, availability: "public", why: "checked public today" }; const GONE = (availability: Presence["availability"]): Presence => ({ onPlatform: false, availability, why: `availability ${availability ?? "unknown"}` }); function flowDeps(extra: CompactDeps = {}): CompactDeps { return { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15, encodeChunk: (o) => x264Chunk(o), score: async () => 95, cutCompare: async () => ({ ssim: 0.99, earlier: 0.95, later: 0.95 }), hasVmaf: async () => true, ...extra, }; } function logger() { const lines: string[] = []; return { lines, onLog: (l: string) => lines.push(l.trimEnd()) }; } async function listTree(dir: string): Promise { const out: string[] = []; const walk = async (d: string) => { for (const e of await readdir(d, { withFileTypes: true })) { const p = path.join(d, e.name); if (e.isDirectory()) await walk(p); else { const s = await stat(p); out.push(`${path.relative(dir, p)} ${s.size} ${s.mtimeMs}`); } } }; await walk(dir); return out.sort(); } const run = (fx: Fx, deps: CompactDeps, settings: SavedVideoCompactionSettings = SETTINGS, onLog: (l: string) => void = () => {}, extra = {}) => // The fixtures are 180p: below the selector's height, so named with belowThreshold. compactOne({ paths: fx.paths, settings, item: { slug: "kick", id: "v1" }, mode: "explicit", onLog, deps, belowThreshold: true, ...extra }); test("the real encode on the DEFAULT thresholds: every check, swapped, re-checked, the original dropped after", { skip: NO_SVT }, async () => { await withVideo({}, async (fx) => { const log = logger(); const settings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3, dropOriginal: "after-verify" as const }; const r = await run(fx, { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15 }, settings, log.onLog); assert.equal(r.status, "compacted", log.lines.join("\n")); const p = (await loadSavedVideo(fx.videoDir))!; assert.match(p.file, /^source-media\.compact-av1-\d{14}\.mp4$/); assert.equal(p.sha256, await sha(path.join(fx.storeDir, p.file))); const c = p.compacted!; assert.equal(c.checks.passed, true); // 60 -> 30 fps on Kick: 360 source frames give 180. assert.deepEqual(c.checks.frames, [360, 180, 180]); assert.equal(c.checks.audio, "identical"); assert.equal(c.checks.quality.metric, vmaf ? "vmaf" : "ssim"); // Every join and every chunk scored, the spread samples besides. assert.ok(c.checks.quality.samples >= 3 + 3 + 2, String(c.checks.quality.samples)); assert.ok(c.checks.quality.mean >= settings.vmafMinMean && c.checks.quality.min >= settings.vmafMinSample, JSON.stringify(c.checks.quality)); assert.ok(c.checks.wholeFile && c.checks.wholeFile.min >= 0.9 && c.checks.wholeFile.frames >= 11, JSON.stringify(c.checks.wholeFile)); assert.equal(c.checks.cuts.length, 3); assert.deepEqual(c.checks.streams?.source, c.checks.streams?.result); assert.equal(c.result.vcodec, "av1"); assert.equal(c.result.fps, 30); assert.equal(c.source.sha256, fx.sourceSha); assert.equal(c.chunks, 3); assert.equal(c.recheck?.ok, true); assert.equal(c.originalDropped?.sha256, fx.sourceSha); assert.equal(c.originalDropped?.fileRemoved, true); assert.equal(compactedOriginalOf(p), null); await assert.rejects(stat(path.join(fx.storeDir, ORIGINAL))); await assert.rejects(stat(path.join(fx.storeDir, ".compact-scratch"))); await assert.rejects(stat(path.join(fx.storeDir, ".compacting.json"))); const recheckAt = log.lines.findIndex((l) => /re-checked from disk/.test(l)); const dropAt = log.lines.findIndex((l) => /the original source-media\.mp4 dropped/.test(l)); assert.ok(recheckAt > 0 && dropAt > recheckAt, log.lines.join("\n")); }); }); // PROBE 1: a chunk with the right frame count and the wrong picture. test("probe 1: a black chunk, or a chunk of the wrong seconds, fails the whole-file comparison", { skip: NO_TOOLS }, async () => { for (const variant of ["black", "wrong-seconds"]) { await withVideo({ gen: { gen: "testsrc2", seconds: 12, fps: 30, gop: 30 }, platform: "rumble" }, async (fx) => { const before = await fx.pointerText(); const r = await run( fx, flowDeps({ encodeChunk: async (o) => { if (o.chunk.index !== 3) return x264Chunk(o); if (variant === "black") { await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=black:size=320x180:rate=30", "-frames:v", String(o.chunk.expectedFrames), "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-video_track_timescale", "90000", "-f", "mp4", o.out]); } else { const shifted = { ...o.chunk, from: o.chunk.from - 4, to: o.chunk.to - 4 }; await x264Chunk({ ...o, chunk: shifted }); } }, }), ); assert.equal(r.status, "failed", variant); assert.match((r as { reason: string }).reason, /the whole-file comparison: /, variant); assert.equal(await fx.pointerText(), before); await stat(fx.source); }); } }); test("probe 1: a short chunk is caught by counting what the encoder wrote", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const r = await run( fx, flowDeps({ encodeChunk: async (o) => { if (o.chunk.index !== 1) return x264Chunk(o); // An encoder that stops ten frames early. const args = encodeChunkArgs(o.src, o.chunk, o.settings, o.out); const i = args.indexOf("libsvtav1"); args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-frames:v", String(o.chunk.expectedFrames - 10)); stripSvt(args); await execa("ffmpeg", args); }, }), ); assert.equal(r.status, "failed"); assert.match((r as { reason: string }).reason, /chunk 1 holds 50 frames, not the 60 expected \(encoded twice\)/); }); }); // PROBE 1b: the scorer pairs frames by number on the copy's grid, so a chunked // copy scores like the source (a timestamp pairing paired neighbours). test("probe 1b: a chunked 60 -> 30 copy scores as high as it is at every excerpt (frame pairing)", { skip: NO_TOOLS || (!vmaf && "no libvmaf") }, async () => { await withVideo({ gen: { gen: "testsrc2", seconds: 12, fps: 60, gop: 60 } }, async (fx) => { const log = logger(); const r = await run( fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), { ...SETTINGS, dropOriginal: "keep", vmafMinMean: 90, vmafMinSample: 85 }, log.onLog, ); assert.equal(r.status, "compacted", log.lines.join("\n")); const q = (await loadSavedVideo(fx.videoDir))!.compacted!.checks.quality; assert.ok(q.min >= 85, JSON.stringify(q)); }); }); // PROBE 2: compact, attach over it, compact again under after-verify. test("probe 2: an original of an earlier compacted copy is never the one dropped, and is not compacted over", { skip: NO_TOOLS }, async () => { await withVideo({ platform: "rumble" }, async (fx) => { const r1 = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" }); assert.equal(r1.status, "compacted"); const previous = (await loadSavedVideo(fx.videoDir))!; // Attach another recording over it, as attachMedia does. const staging = path.join(path.dirname(fx.storeDir), ".v1.attach-1.part"); await makeSource(`${staging}.mp4`, { gen: "smptebars" }); await rename(`${staging}.mp4`, staging); const landed = await persistSourceVideo({ videoDir: fx.videoDir, sourceFilename: ORIGINAL, sourcePath: staging, storeDir: fx.storeDir, keepReason: "pin", origin: { requestedBy: "attach-media" }, paths: fx.paths }); if (savedVideoPath(previous) !== savedVideoPath(landed)) await rm(savedVideoPath(previous), { force: true }); const p = (await loadSavedVideo(fx.videoDir))!; const former = p.alternates!.find((a) => a.sha256 === fx.sourceSha)!; assert.equal(former.keptAs, "former-original"); const r2 = await run(fx, flowDeps(), SETTINGS); assert.equal(r2.status, "skipped"); assert.match((r2 as { reason: string }).reason, /already keeps an original/); assert.equal(await sha(path.join(fx.storeDir, former.file)), fx.sourceSha); }); }); // PROBE 3: a source whose first timestamp is not 0, with B-frames. test("probe 3: an offset mp4, an offset mkv and an mpegts are cut from the right seconds", { skip: NO_TOOLS }, async () => { for (const ext of ["mp4", "mkv", "ts"]) { await withVideo({ platform: "rumble", gen: { gen: "testsrc2", seconds: 12, fps: 30, gop: 60, offset: 1.5, ext, bf: 2 } }, async (fx) => { const log = logger(); // The REAL scorer and cutter on the default thresholds: a seek that // lands late in any of the three shows as a bad excerpt or a cut a frame off. const r = await run( fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), { ...SETTINGS, chunkMinutes: 4 / 60, dropOriginal: "keep" }, log.onLog, ); assert.equal(r.status, "compacted", `${ext}: ${log.lines.join("\n")}`); const c = (await loadSavedVideo(fx.videoDir))!.compacted!; assert.equal(c.checks.frames[1], c.checks.frames[2], ext); assert.ok(c.checks.wholeFile!.min >= 0.9, `${ext}: ${JSON.stringify(c.checks.wholeFile)}`); assert.ok(Math.abs(c.checks.avOffset![0] - c.checks.avOffset![1]) < 0.02, `${ext}: ${JSON.stringify(c.checks.avOffset)}`); if (vmaf) assert.ok(c.checks.quality.min >= 85, `${ext}: ${JSON.stringify(c.checks.quality)}`); }); } }); // PROBE 4: a download that planned before the compaction writes after it. test("probe 4: a download's plan made on the pointer before a compaction is refused after it", { skip: NO_TOOLS }, async () => { await withVideo({ platform: "rumble" }, async (fx) => { const dl = path.join(fx.videoDir, ORIGINAL); await makeSource(dl, { seconds: 5 }); const deps = { measure: async (f: string) => (f.startsWith(fx.videoDir) ? 5 : 6), height: async () => 180 }; const plan = (await planSavedContainer({ videoDir: fx.videoDir, newContainer: dl, explicit: false, deps }))!; assert.equal(plan.active, "existing"); const r = await run(fx, flowDeps()); assert.equal(r.status, "compacted"); const after = await readFile(savedVideoPointerPath(fx.videoDir), "utf8"); await assert.rejects( keepDownloadAsAlternate(plan, { sourceFilename: ORIGINAL, paths: fx.paths, deps, onLog: () => {} }), (e: Error) => e instanceof SavedPointerChangedError && /changed since this download was planned/.test(e.message), ); assert.equal(await readFile(savedVideoPointerPath(fx.videoDir), "utf8"), after); const p = (await loadSavedVideo(fx.videoDir))!; await stat(savedVideoPath(p)); await stat(dl); }); }); // PROBE 5: a copy whose picture is a frame off the source's. test("probe 5: the cut check catches a copy one frame off, and passes a copy on the frame", { skip: NO_TOOLS }, async () => { const d = await mkdtemp(path.join(tmpdir(), "compact-off-")); try { const src = path.join(d, "src.mp4"); await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30:duration=12", "-c:v", "libx264", "-preset", "ultrafast", "-g", "30", "-pix_fmt", "yuv420p", src]); const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "" }; for (const frames of [0, 1, 5]) { const out = path.join(d, `off${frames}.mp4`); await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-i", src, "-vf", `trim=start_frame=${frames},setpts=PTS-STARTPTS`, "-c:v", "libx264", "-preset", "ultrafast", "-crf", "16", out]); const c = await compareCuts(paths, { compacted: out, source: src, at: 4.9917, seconds: 3, fps: null, sourceFps: 30, scratchDir: d }); assert.equal(cutIsOffset(c) || c.ssim < 0.9, frames !== 0, `${frames} frame(s): ${JSON.stringify(c)}`); } } finally { await rm(d, { recursive: true, force: true }); } }); test("a killed chunk: the run stops, and the next run resumes at the first chunk not done", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const before = await fx.pointerText(); const ac = new AbortController(); const first: number[] = []; const r1 = await run( fx, flowDeps({ encodeChunk: async (o) => { first.push(o.chunk.index); if (o.chunk.index === 1) { await writeFile(o.out, "half a chunk"); ac.abort(); throw new Error("killed"); } await x264Chunk(o); }, }), SETTINGS, () => {}, { signal: ac.signal }, ); assert.deepEqual(r1, { status: "stopped", reason: "cancelled" }); assert.deepEqual(first, [0, 1]); assert.equal(await fx.pointerText(), before, "the pointer is untouched"); const scratch = path.join(fx.storeDir, ".compact-scratch"); const files = await readdir(scratch); assert.ok(files.includes("chunk-0000.mp4")); assert.ok(!files.some((f) => f.endsWith(".part")), files.join(",")); await assert.rejects(stat(path.join(fx.storeDir, ".compacting.json")), "the marker goes with the run"); const state = JSON.parse(await readFile(path.join(scratch, "state.json"), "utf8")); assert.deepEqual(state.chunks.map((c: { done: boolean }) => c.done), [true, false, false]); const second: number[] = []; const log = logger(); const r2 = await run(fx, flowDeps({ encodeChunk: async (o) => { second.push(o.chunk.index); await x264Chunk(o); } }), SETTINGS, log.onLog); assert.equal(r2.status, "compacted", log.lines.join("\n")); assert.deepEqual(second, [1, 2]); assert.ok(log.lines.some((l) => /resuming — 1\/3 chunk\(s\) already encoded/.test(l))); }); }); test("an encoder that dies (not a cancel) keeps the chunks done for the re-run", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const before = await fx.pointerText(); const r = await run(fx, flowDeps({ encodeChunk: async (o) => { if (o.chunk.index === 2) throw new Error("ffmpeg failed (exit 137)"); await x264Chunk(o); } })); assert.equal(r.status, "failed"); assert.equal(await fx.pointerText(), before); const state = JSON.parse(await readFile(path.join(fx.storeDir, ".compact-scratch", "state.json"), "utf8")); assert.deepEqual(state.chunks.map((c: { done: boolean }) => c.done), [true, true, false]); }); }); test("the disk floor: refused before the first chunk, and stopped between chunks with the rest resumable", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const before = await fx.pointerText(); let encoded = 0; const r = await run(fx, flowDeps({ freeBytes: async () => 1000, encodeChunk: async (o) => { encoded += 1; await x264Chunk(o); } })); assert.equal(r.status, "stopped"); assert.match((r as { reason: string }).reason, /the store's disk has 1000 B free; kick\/v1 needs about/); assert.equal(encoded, 0); assert.equal(await fx.pointerText(), before); // Room for the plan, the start and the first chunk only. let calls = 0; const r2 = await run(fx, flowDeps({ freeBytes: async () => (++calls <= 3 ? 1e15 : 1000) })); assert.equal(r2.status, "stopped"); const state = JSON.parse(await readFile(path.join(fx.storeDir, ".compact-scratch", "state.json"), "utf8")); assert.deepEqual(state.chunks.map((c: { done: boolean }) => c.done), [true, false, false]); assert.equal(await fx.pointerText(), before); }); }); test("the source is hashed fresh: one that disagrees with its recorded sha256 is not compacted", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const raw = JSON.parse(await readFile(savedVideoPointerPath(fx.videoDir), "utf8")); raw.sha256 = "9".repeat(64); await writeFile(savedVideoPointerPath(fx.videoDir), JSON.stringify(raw)); const r = await run(fx, flowDeps()); assert.equal(r.status, "failed"); assert.match((r as { reason: string }).reason, /do not match the sha256 recorded on its pointer/); }); }); test("a failed verification leaves the original active and untouched, KEEPS the encode, records every check; a reverify needs no encode", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const before = await fx.pointerText(); const log = logger(); // Two checks fail (the excerpts, the window cuts): both are listed, and the // checks after them still ran and said what they found. const r = await run(fx, flowDeps({ score: async () => 42, cutCompare: async () => ({ ssim: 0.5, earlier: 0.4, later: 0.4 }) }), SETTINGS, log.onLog); assert.equal(r.status, "failed"); assert.match((r as { reason: string }).reason, /verification failed: VMAF 42\.00 mean.*; a window cut at/); assert.equal(await fx.pointerText(), before); assert.equal(await sha(fx.source), fx.sourceSha); const scratch = path.join(fx.storeDir, ".compact-scratch"); const kept = (await readdir(scratch)).sort(); assert.deepEqual(kept, ["chunk-0000.mp4", "chunk-0001.mp4", "chunk-0002.mp4", "chunks.txt", "failed-copy.mp4", "failed.json", "state.json"]); assert.deepEqual((await readdir(fx.storeDir)).sort(), [".compact-scratch", ORIGINAL]); const failed = JSON.parse(await readFile(path.join(scratch, "failed.json"), "utf8")); // The excerpts, and each of the three window cuts. assert.equal(failed.failures.length, 4, JSON.stringify(failed.failures)); assert.ok(/^VMAF/.test(failed.failures[0]) && failed.failures.slice(1).every((f: string) => /^a window cut at/.test(f)), JSON.stringify(failed.failures)); assert.equal(failed.checks.audio, "identical", "the audio check ran and passed though another failed"); assert.ok(failed.checks.timestamps && failed.checks.timestamps.over === 0, JSON.stringify(failed.checks.timestamps)); assert.ok(failed.checks.wholeFile && failed.checks.chunkMeans, "the whole-file comparison ran too"); assert.equal(failed.kept.chunks, 3); assert.equal(failed.kept.copy, "failed-copy.mp4"); assert.ok(log.lines.some((l) => /NOT compacted .*The original stays the active copy, untouched\. The encode is KEPT/.test(l)), log.lines.join("\n")); // The dry run says a kept encode exists, its size, and what to ask. const plan = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], belowThreshold: true, deps: flowDeps() }); assert.equal(plan.items[0].compact, false); assert.match(plan.items[0].reason!, /last compaction failed its checks .*a failed encode is kept \(3 chunk\(s\) and the joined copy, .*"reverify": true checks it again without encoding/); assert.equal(plan.items[0].keptFailedEncode?.chunks, 3); assert.match(plan.lines.at(-1)!, /1 kept failed encode\(s\) hold/); const rows = await listKeptFailedEncodes(fx.paths); assert.equal(rows.length, 1); assert.equal(rows[0].kept?.chunks, 3); // A re-verify with the checks passing: nothing encoded, compacted. const re = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], reverify: true, belowThreshold: true, deps: flowDeps() }); assert.equal(re.items[0].compact, true); assert.match(re.items[0].line, /RE-VERIFIES the kept failed encode \(3 chunk\(s\)/); let encoded = 0; const log2 = logger(); const r2 = await run(fx, flowDeps({ encodeChunk: async (o) => { encoded += 1; await x264Chunk(o); } }), { ...SETTINGS, dropOriginal: "keep" }, log2.onLog, { reverify: true }); assert.equal(r2.status, "compacted", log2.lines.join("\n")); assert.equal(encoded, 0); assert.ok(log2.lines.some((l) => /re-verifying the kept encode .*nothing encoded again/.test(l)), log2.lines.join("\n")); await assert.rejects(stat(scratch), "a success removes the scratch"); }); }); test("a chunk whose own content failed is the only one a reverify encodes again; retryFailed encodes all; clear removes", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { // Chunk 1 comes out short twice: a verdict on that chunk. const r = await run( fx, flowDeps({ encodeChunk: async (o) => { if (o.chunk.index !== 1) return x264Chunk(o); const args = encodeChunkArgs(o.src, o.chunk, o.settings, o.out); const i = args.indexOf("libsvtav1"); args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-frames:v", String(o.chunk.expectedFrames - 10)); stripSvt(args); await execa("ffmpeg", args); }, }), ); assert.equal(r.status, "failed"); const failed = JSON.parse(await readFile(path.join(fx.storeDir, ".compact-scratch", "failed.json"), "utf8")); assert.deepEqual(failed.failedChunks, [1]); assert.equal(failed.kept.chunks, 1); const encoded: number[] = []; const r2 = await run(fx, flowDeps({ encodeChunk: async (o) => { encoded.push(o.chunk.index); await x264Chunk(o); } }), { ...SETTINGS, dropOriginal: "keep" }, () => {}, { reverify: true }); assert.equal(r2.status, "compacted"); assert.deepEqual(encoded, [1, 2], "chunk 0 reused"); }); await withVideo({}, async (fx) => { await run(fx, flowDeps({ score: async () => 42 })); const encoded: number[] = []; const r = await run(fx, flowDeps({ encodeChunk: async (o) => { encoded.push(o.chunk.index); await x264Chunk(o); } }), { ...SETTINGS, dropOriginal: "keep" }, () => {}, { retryFailed: true }); assert.equal(r.status, "compacted"); assert.deepEqual(encoded, [0, 1, 2]); }); await withVideo({}, async (fx) => { await run(fx, flowDeps({ score: async () => 42 })); const c = await clearKeptFailedEncode(fx.paths, { slug: "kick", id: "v1" }); assert.equal(c.cleared, true, c.why); await assert.rejects(stat(path.join(fx.storeDir, ".compact-scratch"))); assert.equal((await clearKeptFailedEncode(fx.paths, { slug: "kick", id: "v1" })).cleared, false); }); }); test("an audio stream that is not the source's fails the check, and the record says so", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const before = await fx.pointerText(); let n = 0; const r = await run(fx, flowDeps({ audioHash: async () => ({ data: `d${n++}`, timing: "t", firstPts: 0, packets: 10 }) })); assert.equal(r.status, "failed"); assert.match((r as { reason: string }).reason, /the audio is not the source's packet for packet/); assert.equal(await fx.pointerText(), before); const failed = JSON.parse(await readFile(path.join(fx.storeDir, ".compact-scratch", "failed.json"), "utf8")); assert.equal(failed.checks.audio, "different"); }); }); test("a stream the copy loses fails the check", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { let n = 0; const r = await run(fx, flowDeps({ inventory: async () => (n++ === 0 ? ["audio:aac:1ch", "subtitle:mov_text"] : ["audio:aac:1ch"]) })); assert.equal(r.status, "failed"); assert.match((r as { reason: string }).reason, /does not carry every stream of the source/); }); }); test("a video gone from its platform (or unknown) is compacted but its original is never dropped automatically", { skip: NO_TOOLS }, async () => { for (const availability of [null, "deleted", "needs_auth"] as const) { await withVideo({}, async (fx) => { const log = logger(); const r = await run(fx, flowDeps({ presence: async () => GONE(availability) }), SETTINGS, log.onLog); assert.equal(r.status, "compacted", log.lines.join("\n")); assert.equal((r as { dropped: boolean }).dropped, false); assert.equal((r as { review: string }).review, "awaiting-review"); const p = (await loadSavedVideo(fx.videoDir))!; assert.equal(compactedOriginalOf(p)?.file, ORIGINAL); await stat(path.join(fx.storeDir, ORIGINAL)); assert.ok(log.lines.some((l) => /is NOT dropped — it waits for a person's review/.test(l))); const rows = await listCompactionReview({ paths: fx.paths, settings: SETTINGS, deps: { presence: async () => GONE(availability) } }); assert.equal(rows.length, 1); assert.equal(rows[0].state, "awaiting-review"); assert.match(rows[0].watch.command, /^smplayer ".*compact-av1.*" ".*source-media\.mp4"$/); const again = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], belowThreshold: true, deps: flowDeps() }); assert.deepEqual([again.items[0].compact, again.items[0].reason], [false, "already compacted"]); }); } }); test("after-verify drops the original only after the swap was written and the copy re-checked from disk", { skip: NO_TOOLS }, async () => { // The re-check reads a different sha256 from disk: the original stays. await withVideo({}, async (fx) => { const log = logger(); let swapHashed = false; const r = await run( fx, flowDeps({ sha256: async (file) => { if (/compact-av1/.test(path.basename(file))) return "0".repeat(64); if (/compacted\.mp4$/.test(file)) swapHashed = true; return sha(file); }, }), SETTINGS, log.onLog, ); assert.ok(swapHashed); assert.equal(r.status, "compacted"); assert.equal((r as { dropped: boolean }).dropped, false); const p = (await loadSavedVideo(fx.videoDir))!; assert.equal(p.compacted?.recheck?.ok, false); assert.match(p.compacted?.recheck?.why ?? "", /sha256/); await stat(path.join(fx.storeDir, ORIGINAL)); assert.ok(log.lines.some((l) => /re-check after the swap FAILED/.test(l))); }); // The re-check holds: when the drop step asks, the pointer already names the // re-encode and the original is still on disk. await withVideo({}, async (fx) => { const seen: { file: string; original: boolean }[] = []; let calls = 0; const r = await run( fx, flowDeps({ presence: async () => { if (++calls > 1) { seen.push({ file: (await loadSavedVideo(fx.videoDir))!.file, original: await stat(path.join(fx.storeDir, ORIGINAL)).then(() => true, () => false), }); } return ON; }, }), ); assert.equal(r.status, "compacted"); assert.equal((r as { dropped: boolean }).dropped, true); assert.equal(seen.length, 1); assert.match(seen[0].file, /compact-av1/); assert.equal(seen[0].original, true); const p = (await loadSavedVideo(fx.videoDir))!; assert.ok(p.compacted?.recheck?.ok); assert.ok(p.compacted!.originalDropped!.at >= p.compacted!.recheck!.at); }); }); test("no automatic drop while a download of the video is queued or running", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const log = logger(); const r = await run(fx, flowDeps({ busy: () => "a persist-videos job (queued, j9) may write this video's saved copy — wait for it to end" }), SETTINGS, log.onLog); assert.equal(r.status, "compacted"); assert.equal((r as { dropped: boolean }).dropped, false); await stat(path.join(fx.storeDir, ORIGINAL)); assert.ok(log.lines.some((l) => /is kept: a persist-videos job/.test(l))); }); }); test("an error after the swap reports the swap as done and drops nothing", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const log = logger(); const r = await run( fx, flowDeps({ sha256: async (file) => { if (/compact-av1/.test(path.basename(file))) throw new Error("EIO reading the new copy"); return sha(file); }, }), SETTINGS, log.onLog, ); assert.equal(r.status, "compacted"); assert.match((r as { afterSwapError?: string }).afterSwapError ?? "", /EIO/); assert.equal((r as { dropped: boolean }).dropped, false); await stat(path.join(fx.storeDir, ORIGINAL)); assert.ok(log.lines.some((l) => /the swap is written .*After it, a step failed: EIO/.test(l)), log.lines.join("\n")); assert.ok(!log.lines.some((l) => /The original stays the active copy/.test(l))); }); }); test('dropOriginal "keep" (the default): the original stays', { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const r = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS.dropOriginal }); assert.deepEqual([r.status, (r as { review: string }).review], ["compacted", "kept"]); await stat(path.join(fx.storeDir, ORIGINAL)); }); }); test("the selector picks only deliberately stored + platform + bitrate; an explicit item below it needs belowThreshold", async () => { const root = await mkdtemp(path.join(tmpdir(), "compact-select-")); try { const paths = { transcriptsDir: root, channelsDir: path.join(root, "channels"), savedVideosDir: path.join(root, "saved-videos"), ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "", } as Paths; const videos: [string, string, string, Record, number][] = [ // slug, platform, id, pointer facts, video kbps ["kick", "kick", "pinned-hi", { keepReason: "pin" }, 5200], ["kick", "kick", "latest-hi", { keepReason: "keep-latest" }, 5200], ["kick", "kick", "kept-catchup", { keepReason: "override" }, 5200], ["kick", "kick", "pinned-lo", { keepReason: "pin" }, 640], ["tube", "youtube", "pinned-hi", { keepReason: "pin" }, 5200], ["rumble", "rumble", "persisted-hi", { keepReason: "override", explicit: true }, 3400], ]; const kbps = new Map(); for (const [slug, platform, id, facts, k] of videos) { const videoDir = path.join(paths.channelsDir, slug, "data", id); const storeDir = path.join(paths.savedVideosDir, slug, id); await mkdir(videoDir, { recursive: true }); await mkdir(storeDir, { recursive: true }); await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ handling: "transcribe", platform })); await writeFile(path.join(storeDir, ORIGINAL), "bytes"); kbps.set(path.join(storeDir, ORIGINAL), k); await writeFile(savedVideoPointerPath(videoDir), JSON.stringify({ storedAt: "x", dir: storeDir, file: ORIGINAL, bytes: 5_000_000_000, ...facts })); } const deps: CompactDeps = { presence: async () => ON, freeBytes: async () => 1e13, probe: async (file) => ({ hasVideo: true, vcodec: "h264", width: 1920, height: 1080, fps: 60, seconds: 7200, videoKbps: kbps.get(file) ?? null, audioKbps: 155, videoStart: 0, audioStart: 0, formatStart: 0, audioStreams: 1, bytes: 5_000_000_000, mainVideoIndex: 0, container: "mp4", }), }; const plan = await planCompaction({ paths, settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, select: true, deps }); const pick = Object.fromEntries(plan.items.map((i) => [`${i.slug}/${i.id}`, i.compact ? "compact" : i.reason])); assert.deepEqual(pick, { "kick/kept-catchup": 'kept as "override" with no record that a person asked for it (persist-kept, the keep-latest catch-up, writes it too): not known to be kept on purpose', "kick/latest-hi": "an automatic keep-latest container (compaction is for deliberately stored videos only)", "kick/pinned-hi": "compact", "kick/pinned-lo": "0.64 Mbit/s video is below minVideoMbps 3", "rumble/persisted-hi": "compact", "tube/pinned-hi": "platform youtube is not selected", }); assert.equal(plan.willCompact, 2); const kickLine = plan.items.find((i) => i.id === "pinned-hi" && i.slug === "kick")!.line; assert.match(kickLine, /^kick\/pinned-hi: 2h00m 1080p60 h264 5\.20 Mbit\/s 4\.66 GB → est\. .* AV1 crf 36 at 30 fps .*est\. .* needs .* free \(.* free\) — would compact$/); assert.doesNotMatch(plan.items.find((i) => i.slug === "rumble")!.line, /at 30 fps/); assert.match(plan.lines.at(-1)!, /^total: 2 container\(s\)/); // Explicitly named, below the selector: refused, saying how little it saves. const items = [{ slug: "tube", id: "pinned-hi" }, { slug: "kick", id: "pinned-lo" }, { slug: "kick", id: "latest-hi" }, { slug: "kick", id: "kept-catchup" }]; const explicit = await planCompaction({ paths, settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, items, deps }); assert.deepEqual(explicit.items.map((i) => i.compact), [false, false, false, false]); assert.match(explicit.items[1].reason!, /below minVideoMbps 3; named explicitly, it is compacted only with "belowThreshold": true \(it would save about .* of 4\.66 GB\)/); const allowed = await planCompaction({ paths, settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, items, belowThreshold: true, deps }); assert.deepEqual(allowed.items.map((i) => i.compact), [true, true, false, false]); assert.match(allowed.items[1].line, /below the selector's thresholds \(0\.64 Mbit\/s video is below minVideoMbps 3\): it would save about/); await writeFile(path.join(paths.channelsDir, "kick", "config.json"), JSON.stringify({ handling: "transcribe", platform: "kick", excludeFromCompaction: true })); const out = await planCompaction({ paths, settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, items: [{ slug: "kick", id: "pinned-hi" }], deps }); assert.match(out.items[0].reason!, /opts out/); } finally { await rm(root, { recursive: true, force: true }); } }); test("a dry run (the plan) writes nothing", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const before = await listTree(fx.root); const plan = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], belowThreshold: true, deps: { presence: async () => GONE(null) } }); assert.equal(plan.items[0].compact, true); assert.match(plan.items[0].line, /0m 180p60 h264 .* → est\. .* needs .* free/); assert.match(plan.items[0].line, /not known to be on its platform \(availability unknown\): its original waits for a review/); assert.deepEqual(await listTree(fx.root), before); }); }); test("the recording clock: re-measured against the re-encode and kept, or a moved map fails the check", { skip: NO_TOOLS }, async () => { for (const shift of [0, 0.5]) { await withVideo({}, async (fx) => { const audio = path.join(fx.videoDir, "audio.mp3"); await writeFile(audio, "cue audio"); const p = (await loadSavedVideo(fx.videoDir))!; const clock = { version: CLOCK_VERSION, id: "c1", createdAt: "2026-11-01T00:00:00.000Z", source: { file: "audio.mp3", bytes: (await stat(audio)).size }, target: { file: ORIGINAL, bytes: p.bytes }, method: "xcorr", params: { tolerance: 0.08 }, anchors: [{ at: 2, offset: 1.25, ok: true }, { at: 4, offset: 1.25, ok: true }], segments: [{ from: 0, to: 6, offset: 1.25, rate: 0 }], gaps: [], residual: { rms: 0.001 }, ok: true, }; await writeFile(path.join(fx.videoDir, CLOCK_FILE), JSON.stringify(clock)); const before = await fx.pointerText(); const r = await run( fx, flowDeps({ measureClock: async (o) => ({ ...clock, id: "c2", target: { file: path.basename(o.container), bytes: o.targetBytes }, segments: [{ from: 0, to: 6, offset: 1.25 + shift, rate: 0 }] }) as never, }), { ...SETTINGS, dropOriginal: "keep" }, ); const written = JSON.parse(await readFile(path.join(fx.videoDir, CLOCK_FILE), "utf8")); if (shift === 0) { assert.equal(r.status, "compacted"); const after = (await loadSavedVideo(fx.videoDir))!; assert.equal(after.compacted?.checks.clock, "kept"); assert.equal(written.target.file, after.file); assert.equal(written.target.bytes, after.bytes); assert.equal(written.id, "c1"); assert.equal(written.retargeted.from.file, ORIGINAL); assert.equal(written.retargeted.measured, "c2"); } else { assert.equal(r.status, "failed"); assert.match((r as { reason: string }).reason, /the recording clock moved/); assert.equal(await fx.pointerText(), before); assert.equal(written.id, "c1"); assert.equal(written.target.file, ORIGINAL); } }); } }); test("compactSavedVideos runs a list one at a time and a drain stops between videos", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const drain = new AbortController(); drain.abort(); const r = await compactSavedVideos({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], mode: "explicit", belowThreshold: true, onLog: () => {}, drainSignal: drain.signal, deps: flowDeps() }); assert.equal(r.stopped, "drained"); assert.equal(r.compacted.length, 0); }); }); test("each chunk goes through the heavy slot's gate with its estimate, niced", { skip: NO_SVT }, async () => { await withVideo({}, async (fx) => { // A stand-in for scripts/queue-lock.mjs: records each argv, runs the rest. const repo = path.join(fx.root, "repo"); await mkdir(path.join(repo, "scripts"), { recursive: true }); const marker = path.join(fx.root, "gate.jsonl"); await writeFile( path.join(repo, "scripts", "queue-lock.mjs"), `import { appendFileSync } from "node:fs";\nimport { spawnSync } from "node:child_process";\n` + `const argv = process.argv.slice(2);\nappendFileSync(${JSON.stringify(marker)}, JSON.stringify(argv) + "\\n");\n` + `const at = argv.indexOf("--");\nconst r = spawnSync(argv[at + 1], argv.slice(at + 2), { stdio: "inherit" });\nprocess.exit(r.status ?? 1);\n`, ); const r = await compactOne({ paths: { ...fx.paths, monorepoRoot: repo } as Paths, settings: { ...SETTINGS, dropOriginal: "keep" }, item: { slug: "kick", id: "v1" }, mode: "explicit", belowThreshold: true, onLog: () => {}, deps: { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15, score: async () => 95, cutCompare: async () => ({ ssim: 0.99, earlier: 0.9, later: 0.9 }) }, }); assert.equal(r.status, "compacted"); const runs = (await readFile(marker, "utf8")).trim().split("\n").map((l) => JSON.parse(l) as string[]); const chunks = runs.filter((a) => a.includes("libsvtav1")); assert.equal(chunks.length, 3); for (const a of chunks) assert.deepEqual(a.slice(0, 7), ["--heavy", "--estimate", "1500", "--", "nice", "-n", "10"]); assert.ok(runs.some((a) => a.includes("-xerror")), "the full decode"); assert.ok(runs.some((a) => a.some((x) => /wf-graph/.test(x))), "the whole-file comparison"); }); }); // --- review round 2 ------------------------------------------------------------ // F2: the defects the first whole-file comparison passed, on the DEFAULT // thresholds, every check real (the reviewer's set: 0.47 s of black between // two ticks, 3 black frames at a chunk join, 2.5 s of heavy noise, a ~3% // region changed for 3 s), and the smaller ones the tiles now catch. test("F2: every listed defect fails the whole-file comparison on the default thresholds", { skip: NO_TOOLS }, async () => { const defects: [string, (c: ChunkPlan) => string | undefined][] = [ ["0.47 s of black", (c) => (c.index === 1 ? "drawbox=c=black:t=fill:enable='between(t,1.1,1.57)'" : undefined)], ["3 black frames at a join", (c) => (c.index === 0 ? `drawbox=c=black:t=fill:enable='gte(n,${c.expectedFrames - 3})'` : undefined)], ["2.5 s of heavy noise", (c) => (c.index === 1 ? "noise=alls=60:allf=t:enable='between(t,0.5,3)'" : undefined)], ["a 3% region for 3 s", (c) => (c.index === 1 ? "drawbox=x=300:y=150:w=110:h=63:c=red:t=fill:enable='between(t,0.5,3.5)'" : undefined)], ["a 1% region for 3 frames", (c) => (c.index === 1 ? "drawbox=x=300:y=150:w=64:h=36:c=red:t=fill:enable='between(n,30,32)'" : undefined)], ["one black frame", (c) => (c.index === 1 ? "drawbox=c=black:t=fill:enable='eq(n,40)'" : undefined)], // D1: colour only — the grey comparison and VMAF do not see these. ["a 3 s hue shift", (c) => (c.index === 1 ? "hue=h=120:s=1:enable='between(t,0.5,3.5)'" : undefined)], ["3 s of chroma-only noise", (c) => (c.index === 1 ? "noise=c1s=80:c1f=t:c2s=80:c2f=t:enable='between(t,0.5,3.5)'" : undefined)], // E2: a plane whose SSIM goes NEGATIVE fails for the right reason. ["1 s of the V plane inverted", (c) => (c.index === 1 ? "lutyuv=v=negval:enable='between(t,1,2)'" : undefined)], ]; for (const [label, defect] of defects) { await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 12, fps: 30, gop: 30 } }, async (fx) => { const before = await fx.pointerText(); const r = await run(fx, flowDeps({ encodeChunk: (o) => x264Chunk(o, 18, defect(o.chunk)) }), { ...SETTINGS, chunkMinutes: 4 / 60 }); assert.equal(r.status, "failed", label); assert.match((r as { reason: string }).reason, /verification failed: the whole-file comparison: /, label); if (/V plane inverted/.test(label)) assert.match((r as { reason: string }).reason, /the colour \(V plane\) of a frame at .* scores -/, label); assert.equal(await fx.pointerText(), before, label); await stat(fx.source); }); } }); test("F2: a GOOD SVT-AV1 crf-36 encode of a detailed 640x360 fixture passes every default threshold, with margin", { skip: NO_SVT }, async () => { await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 6, fps: 30, gop: 60 } }, async (fx) => { const log = logger(); const settings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3 }; const r = await run(fx, { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15 }, settings, log.onLog); assert.equal(r.status, "compacted", log.lines.join("\n")); const w = (await loadSavedVideo(fx.videoDir))!.compacted!.checks.wholeFile!; assert.equal(w.frames, 180); assert.equal(w.grid, 8); // The margins the defaults keep over a good copy (measured 0.996 / 0.949). assert.ok(w.min >= settings.wholeFileSsimMin + 0.05, JSON.stringify(w)); assert.ok(w.min >= w.relativeFloor! + 0.01, JSON.stringify(w)); assert.ok(w.worstTile && w.worstTile.min >= settings.wholeFileTileMin + 0.1 && w.worstTile.longestBelow === 0, JSON.stringify(w)); // The colour planes too (measured 0.991 at their lowest). assert.ok(w.chroma && w.chroma.min >= settings.wholeFileChromaMin + 0.05 && w.chroma.mean >= settings.wholeFileChromaMean + 0.02, JSON.stringify(w.chroma)); // Every chunk against the others (review G2): recorded, none below. const m = (await loadSavedVideo(fx.videoDir))!.compacted!.checks.chunkMeans!; assert.ok(m && m.count >= 3 && m.worst === null && m.margin === settings.wholeFileChunkMargin, JSON.stringify(m)); assert.equal(w.lowerRunSeconds, settings.wholeFileLowerRunSeconds); }); }); test("F3: a stale marker beside an already compacted video is cleared, and every run sweeps the store", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const r1 = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" }); assert.equal(r1.status, "compacted"); // The state a crash between the swap and the marker's removal leaves. const marker = path.join(fx.storeDir, ".compacting.json"); await writeFile(marker, JSON.stringify({ pid: 2 ** 22 + 7, host: "x", startedAt: "2026-11-01T00:00:00Z", token: "t" })); const log = logger(); const r2 = await run(fx, flowDeps(), SETTINGS, log.onLog); assert.equal(r2.status, "skipped"); await assert.rejects(stat(marker)); assert.ok(log.lines.some((l) => /a stale compaction marker removed/.test(l)), log.lines.join("\n")); await writeFile(marker, JSON.stringify({ pid: 2 ** 22 + 7, host: "x", startedAt: "2026-11-01T00:00:00Z", token: "t" })); const swept = await sweepCompactingMarkers(fx.paths); assert.deepEqual(swept.map((x) => [x.id, x.cleared]), [["v1", true]]); await assert.rejects(stat(marker)); }); }); test("F4: the marker is held through the swap, the re-check and the drop; a persist in that window is refused", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { let calls = 0; let during = ""; const r = await run( fx, flowDeps({ presence: async () => { // The second call is afterSwap's, just before the drop. if (++calls === 2) { const dl = path.join(fx.videoDir, "source-media.webm"); await writeFile(dl, "a download"); during = await persistSourceVideo({ videoDir: fx.videoDir, sourceFilename: "source-media.webm", storeDir: fx.storeDir, paths: fx.paths }).then( () => "went through", (e) => (e as Error).name, ); } return ON; }, }), ); assert.equal(during, "CompactionInProgressError"); assert.equal(r.status, "compacted"); assert.equal((r as { dropped: boolean }).dropped, true, "the compaction's own drop passes its marker"); await assert.rejects(stat(path.join(fx.storeDir, ".compacting.json")), "released at the very end"); }); }); test("the swap's compare-and-swap covers keepReason, origin and explicit", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const r = await run( fx, flowDeps({ encodeChunk: async (o) => { await x264Chunk(o); if (o.chunk.index === 1) await restoreSavedVideoProvenance(fx.videoDir, { keepReason: "keep-latest" }); }, }), ); assert.equal(r.status, "failed"); assert.match((r as { reason: string }).reason, /the saved copy changed while it was being compacted/); assert.equal((await loadSavedVideo(fx.videoDir))!.file, ORIGINAL); }); }); test("kept-originals lists every pointer that keeps an original (what a rollback would mistreat)", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { assert.deepEqual(await listKeptOriginals({ paths: fx.paths }), []); await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" }); const rows = await listKeptOriginals({ paths: fx.paths }); assert.equal(rows.length, 1); assert.deepEqual(rows[0].kept.map((k) => [k.file, k.keptAs, k.sha256]), [[ORIGINAL, "original", fx.sourceSha]]); }); }); // E1: a degraded stretch LONGER than the local floor's window looks steady to // that floor; it is caught by the other checks. Scaled down: a 2 s window over // a 12 s file, a 4 s stretch (the same as 3 minutes against 120 s). test("E1: a degraded stretch longer than the window still fails (absolute floor, or the excerpts laid every window)", { skip: NO_TOOLS }, async () => { const cases: [string, (c: ChunkPlan) => string | undefined, RegExp][] = [ ["4 s of heavy blocking", (c) => (c.index === 1 ? "scale=40:-2,scale=640:360:flags=neighbor" : undefined), /no frame may fall below 0\.9/], // Measured: caught by the tile grid (a tile at 0.66 for 29 frames). ["4 s of mild blur", (c) => (c.index === 1 ? "boxblur=3" : undefined), /tile .* is below its floor|VMAF .* at its worst excerpt/], ]; for (const [label, defect, why] of cases) { await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 12, fps: 30, gop: 30 } }, async (fx) => { const log = logger(); const r = await run( fx, flowDeps({ score: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 18, defect(o.chunk)) }), { ...SETTINGS, chunkMinutes: 4 / 60, wholeFileWindowSeconds: 2, qualitySamples: 3 }, log.onLog, ); assert.equal(r.status, "failed", `${label}: ${log.lines.join("\n")}`); assert.match((r as { reason: string }).reason, why, label); }); } }); // THE SOURCE'S TIMESTAMPS (review, the first real run). A live recording drops // frames; the copy keeps them as gaps and stays on the sound's clock after. async function ptsOf(file: string): Promise { const r = await execa("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time", "-of", "csv=p=0", file]); return String(r.stdout).split("\n").map(Number).filter(Number.isFinite).sort((a, b) => a - b); } // The brightest frame's time (the white flash). async function flashAt(file: string): Promise { const r = await execa("ffprobe", [ "-v", "error", "-f", "lavfi", "-i", `movie=${file.replace(/([:,'\\])/g, "\\$1")},signalstats`, "-show_entries", "frame=pts_time:frame_tags=lavfi.signalstats.YAVG", "-of", "csv=p=0", ]); let best = -1; let at = NaN; for (const line of String(r.stdout).split("\n")) { const [t, y] = line.split(",").map(Number); if (Number.isFinite(y) && y > best) { best = y; at = t; } } return at; } // The click's time in the sound: the first sample above 0.5. async function clickAt(file: string): Promise { const start = Number(String((await execa("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=start_time", "-of", "csv=p=0", file])).stdout).trim()) || 0; const r = await execa("ffmpeg", ["-nostdin", "-v", "error", "-i", file, "-map", "0:a:0", "-ac", "1", "-ar", "48000", "-f", "f32le", "-"], { encoding: "buffer" }); const b = Buffer.from(r.stdout as unknown as Uint8Array); for (let i = 0; i + 4 <= b.length; i += 4) if (b.readFloatLE(i) > 0.5) return start + i / 4 / 48000; return NaN; } // 60 fps, 10 s; 31 frames (ODD: the time grid and the index grid part after // it) dropped at 5 s; keyframes every 45 frames (some at odd indexes); a // flash and a click at 7 s. const GAPPED: Gen = { seconds: 10, fps: 60, gop: 45, drop: [[300, 330]], flash: 7 }; test("a live recording's dropped frames: the copy keeps them as gaps, every frame at its source time, the picture on the sound after the gap", { skip: NO_TOOLS }, async () => { await withVideo({ gen: GAPPED }, async (fx) => { const log = logger(); const r = await run(fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), { ...SETTINGS, dropOriginal: "keep" }, log.onLog); assert.equal(r.status, "compacted", log.lines.join("\n")); const p = (await loadSavedVideo(fx.videoDir))!; const c = p.compacted!.checks; assert.equal(c.sourceGaps?.count, 1); assert.ok(Math.abs(c.sourceGaps!.largest - 32 / 60) < 0.002, JSON.stringify(c.sourceGaps)); assert.ok(c.timestamps && c.timestamps.over === 0 && c.timestamps.maxDeviation <= 0.0005, JSON.stringify(c.timestamps)); assert.equal(c.timestamps!.perChunk.length, p.compacted!.chunks); // Every copy frame is a source frame (every other one, by index), AT ITS TIME. const src = await ptsOf(fx.source); const copy = await ptsOf(path.join(fx.storeDir, p.file)); assert.equal(copy.length, Math.ceil(src.length / 2)); assert.ok(copy.every((t, i) => Math.abs(t - src[2 * i]) < 0.0005), "each kept frame keeps its source pts"); assert.ok(copy.some((t, i) => i > 0 && t - copy[i - 1] > 0.5), "the gap is still a gap"); // The flash and the click still meet, 2 s after the gap. const [flash, click] = [await flashAt(path.join(fx.storeDir, p.file)), await clickAt(path.join(fx.storeDir, p.file))]; assert.ok(Math.abs(flash - 7) < 1 / 60 + 0.001 && Math.abs(flash - click) < 1 / 30, `flash ${flash}, click ${click}`); assert.equal(await clickAt(fx.source).then((t) => Math.abs(t - click) < 0.0001), true); // Each chunk starts on a keyframe at an EVEN index of the file. const state = log.lines.find((l) => /dropped frames in 1 place/.test(l)); assert.ok(state, log.lines.join("\n")); // The playable copy (prepare-playable's lossless remux) keeps the times. const decision = decidePlayable({ formatName: "mov,mp4", ext: "mp4", vcodec: "av1", acodec: "aac" }); assert.ok(decision.playable); const remux = path.join(fx.root, "playable.mp4"); await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-i", path.join(fx.storeDir, p.file), ...decision.args, remux]); const rp = await ptsOf(remux); assert.ok(rp.length === copy.length && rp.every((t, i) => Math.abs(t - copy[i]) < 0.0005), "the remux keeps every timestamp"); }); }); test("the copy made the OLD way (a constant rate after the gap) fails the timestamp check", { skip: NO_TOOLS }, async () => { await withVideo({ gen: GAPPED }, async (fx) => { const r = await run( fx, flowDeps({ encodeChunk: async (o) => { // The encode before this round: every other frame RE-TIMED onto 30 fps. await execa("ffmpeg", [ "-nostdin", "-v", "error", "-y", "-ss", Math.max(0, o.chunk.from - 0.001).toFixed(6), ...(o.chunk.last ? [] : ["-to", (o.chunk.to - 0.25 / 60).toFixed(6)]), "-i", o.src, "-map", "0:v:0", "-an", "-vf", "select='not(mod(n,2))',setpts=N/30/TB", "-r", "30", "-c:v", "libx264", "-preset", "ultrafast", "-crf", "18", "-video_track_timescale", "90000", "-f", "mp4", o.out, ]); }, }), ); assert.equal(r.status, "failed"); assert.match((r as { reason: string }).reason, /of the re-encode's frames are not at their source frame's time .* would not stay on its sound's clock/); }); }); test("a tail gap (the first real run's source) and a 59.94 fps source pass", { skip: NO_TOOLS }, async () => { for (const gen of [{ seconds: 6, fps: 60, drop: [[350, 354]] }, { seconds: 6, fps: "60000/1001" }] as Gen[]) { await withVideo({ gen }, async (fx) => { const log = logger(); const r = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" }, log.onLog); assert.equal(r.status, "compacted", `${JSON.stringify(gen)}: ${log.lines.join("\n")}`); const c = (await loadSavedVideo(fx.videoDir))!.compacted!.checks; assert.equal(c.timestamps?.over, 0); assert.equal(c.sourceGaps?.count, gen.drop ? 1 : 0); }); } }); // Review G1: a correct copy of a source with a dropped frame was failed by a // null-muxer line. On the DEFAULT checks, with the real encoder. test("G1: a 59.94 fps source with one dropped frame ends compacted on the default checks", { skip: NO_SVT }, async () => { await withVideo({ gen: { seconds: 8, fps: "60000/1001", drop: [[301, 301]] } }, async (fx) => { const log = logger(); const settings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3, dropOriginal: "keep" as const }; const r = await run(fx, { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15 }, settings, log.onLog); assert.equal(r.status, "compacted", log.lines.join("\n")); const c = (await loadSavedVideo(fx.videoDir))!.compacted!.checks; assert.equal(c.decoded, true); assert.equal(c.sourceGaps?.count, 1); assert.equal(c.timestamps?.over, 0); }); }); test("G1: the full decode keeps each stream's time base; only damage is fatal", { skip: NO_TOOLS }, async () => { const d = await mkdtemp(path.join(tmpdir(), "compact-dec-")); try { // Frames half a tick off the nominal 1001/30000 grid: re-quantised to it, // two land on one tick and the null muxer complains. const f = path.join(d, "ticks.mp4"); await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=30000/1001:d=3", "-vf", "setpts='(N+if(eq(N\\,10)\\,0.5\\,0))*1001/30000/TB'", "-fps_mode", "passthrough", "-c:v", "libx264", "-video_track_timescale", "90000", f]); const old = await execa("ffmpeg", ["-nostdin", "-hide_banner", "-v", "error", "-xerror", "-i", f, "-map", "0:v:0", "-f", "null", "-"], { reject: false }); assert.match(String(old.stderr), /non monotonically increasing dts/, "the old invocation's complaint"); const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "" }; assert.deepEqual(await fullDecode(paths, f), { ok: true }); // A damaged file still fails. const bad = path.join(d, "bad.mp4"); const bytes = await readFile(f); for (let i = Math.floor(bytes.length / 3); i < Math.floor(bytes.length / 3) + 4000; i += 1) bytes[i] = 0; await writeFile(bad, bytes); assert.equal((await fullDecode(paths, bad)).ok, false); } finally { await rm(d, { recursive: true, force: true }); } }); // Review G3: a kept failed encode goes with its video's pointer; one left // behind before this is listed as orphaned and can be cleared. test("G3: unpersist and drop remove a kept failed encode; an orphaned one is listed and cleared", { skip: NO_TOOLS }, async () => { for (const how of ["unpersist", "drop"] as const) { await withVideo({}, async (fx) => { await run(fx, flowDeps({ score: async () => 42 })); const scratch = path.join(fx.storeDir, ".compact-scratch"); await stat(scratch); if (how === "unpersist") assert.equal(await unpersistSavedVideo(fx.videoDir), true); else await dropSavedVideo(fx.videoDir); await assert.rejects(stat(scratch), how); const left = (await readdir(fx.storeDir).catch(() => [] as string[])).join(", "); await assert.rejects(stat(fx.storeDir), `${how}: the store dir goes when empty (left: ${left})`); }); } await withVideo({}, async (fx) => { await run(fx, flowDeps({ score: async () => 42 })); // A pointer removed by hand (as a release before this one left it). await rm(savedVideoPointerPath(fx.videoDir)); const rows = await listKeptFailedEncodes(fx.paths); assert.equal(rows.length, 1); assert.equal(rows[0].orphaned, true); assert.ok((rows[0].bytes ?? 0) > 0); const c = await clearKeptFailedEncode(fx.paths, { slug: "kick", id: "v1" }); assert.equal(c.cleared, true, c.why); assert.match(c.why, /orphaned/); await assert.rejects(stat(path.join(fx.storeDir, ".compact-scratch"))); assert.deepEqual(await listKeptFailedEncodes(fx.paths), []); }); }); // Review G4: a recording that ran at 30 fps for a stretch keeps 30 fps there. test("G4: a 60 fps source with a 30 fps stretch keeps 30 fps throughout, each frame at its source time", { skip: NO_TOOLS }, async () => { // Frames 120–359 at 30 fps (every odd one missing), and an odd gap later. const gen: Gen = { seconds: 10, fps: 60, gop: 45, dropExpr: "between(n,121,359)*mod(n,2)+between(n,450,452)" }; await withVideo({ gen }, async (fx) => { const log = logger(); const r = await run(fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), { ...SETTINGS, dropOriginal: "keep" }, log.onLog); assert.equal(r.status, "compacted", log.lines.join("\n")); const p = (await loadSavedVideo(fx.videoDir))!; const copy = await ptsOf(path.join(fx.storeDir, p.file)); const src = await ptsOf(fx.source); assert.ok(copy.every((x) => src.some((y) => Math.abs(x - y) < 0.0005)), "every copy frame is a source frame at its time"); for (let i = 1; i < copy.length; i += 1) { const d = copy[i] - copy[i - 1]; const acrossGap = copy[i - 1] <= 449 / 60 + 1e-6 && copy[i] >= 453 / 60 - 1e-6; assert.ok(d > 1 / 30 - 0.001 && (acrossGap || d < 1 / 30 + 0.001), `${copy[i - 1]} -> ${copy[i]}`); } const stretch = src.filter((x) => x >= 2 && x < 6); assert.equal(copy.filter((x) => x >= 2 && x < 6).length, stretch.length, "the 30 fps stretch keeps every frame"); assert.equal(p.compacted!.checks.timestamps?.over, 0); }); }); test("G4: a constant 60 fps source decimates to the same frames and times as before", { skip: NO_TOOLS }, async () => { const d = await mkdtemp(path.join(tmpdir(), "compact-cfr-")); try { const src = path.join(d, "src.mp4"); await makeSource(src, { seconds: 4, fps: 60 }); const scan = await scanVideoPackets("ffprobe", src); const chunk = planChunks(scan, 60, 30, 60, { minStep: keepMinStep(30, 60) })[0]; const s = { preset: 8, crf: 36, gopSeconds: 5, pixFmt: "yuv420p", fps: 30, sourceFps: 60, formatStart: 0 }; const hashes: string[] = []; for (const label of ["previous", "now"]) { const out = path.join(d, `${label}.mp4`); const args = encodeChunkArgs(src, label === "now" ? chunk : { ...chunk, select: undefined }, s, out); const i = args.indexOf("libsvtav1"); args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", "18"); stripSvt(args); if (label === "previous") assert.ok(args.includes("select='not(mod(n,2))',setpts=PTS-STARTPTS"), args.join(" ")); await execa("ffmpeg", args); const md = await execa("ffmpeg", ["-v", "error", "-i", out, "-map", "0:v", "-f", "framemd5", "-"]); hashes.push(String(md.stdout).split("\n").filter((l) => l && !l.startsWith("#")).join("\n")); } assert.equal(hashes[1], hashes[0], "the same frames at the same times (framemd5 carries both)"); } finally { await rm(d, { recursive: true, force: true }); } }); // Review H1: a source whose timestamps are rounded to the millisecond (a // Matroska recording: steps of 16 and 17 ms) keeps exactly every other frame, // with a 67 ms gap and with a choppy pattern too; every timing check passes. test("H1: ms-rounded 60 fps sources (plain, a 67 ms gap, choppy) compact with every frame the rule keeps", { skip: NO_TOOLS }, async () => { for (const gen of [ { seconds: 8, fps: 60, ext: "mkv" }, { seconds: 8, fps: 60, ext: "mkv", drop: [[240, 242]] }, { seconds: 8, fps: 60, ext: "mkv", dropExpr: "eq(mod(n,7),3)*gte(n,150)+eq(mod(n,11),5)" }, ] as Gen[]) { await withVideo({ gen }, async (fx) => { const log = logger(); const r = await run(fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), { ...SETTINGS, dropOriginal: "keep" }, log.onLog); assert.equal(r.status, "compacted", `${JSON.stringify(gen)}: ${log.lines.join("\n")}`); const p = (await loadSavedVideo(fx.videoDir))!; const src = await ptsOf(fx.source); const mask = keptSourceFrames(Float64Array.from(src), keepMinStep(30, 60)); const want = src.filter((_, i) => mask[i]); const copy = await ptsOf(path.join(fx.storeDir, p.file)); assert.equal(copy.length, want.length, JSON.stringify(gen)); assert.ok(copy.every((t, i) => Math.abs(t - want[i]) < 0.0005), `${JSON.stringify(gen)}: the copy holds the frames the rule keeps`); if (!gen.drop && !gen.dropExpr) assert.deepEqual(want, src.filter((_, i) => i % 2 === 0), "plain: exactly every other frame"); assert.equal(p.compacted!.checks.timestamps?.over, 0); }); } }); // Review H3: a very choppy source (a frame dropped every 17) has no window // without a gap: the cuts are SKIPPED and say so; a skipped check is never // counted as passed, so the original is not dropped after it. test("H3: on a very choppy source the window cuts are skipped and named, and after-verify does not drop", { skip: NO_TOOLS }, async () => { await withVideo({ gen: { seconds: 10, fps: 60, dropExpr: "eq(mod(n,17),0)*gt(n,0)" } }, async (fx) => { const log = logger(); const r = await run(fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), SETTINGS, log.onLog); assert.equal(r.status, "compacted", log.lines.join("\n")); const p = (await loadSavedVideo(fx.videoDir))!; const c = p.compacted!.checks; assert.ok(c.skipped && c.skipped.some((x) => /window cut/.test(x)), JSON.stringify(c.skipped)); assert.ok(log.lines.some((l) => /SKIPPED/.test(l)), log.lines.join("\n")); assert.equal((r as { dropped: boolean }).dropped, false); assert.ok(log.lines.some((l) => /skipped .* does not drop/.test(l)), log.lines.join("\n")); }); }); // Review H4: the video pass decodes 0:v:0 alone; audio damage the copy does // not share with its source is fatal, damage it carries over from it is not. test("H4: the full decode — video alone, then the audio against the source's own", { skip: NO_TOOLS }, async () => { const d = await mkdtemp(path.join(tmpdir(), "compact-aac-")); try { const v = path.join(d, "v.mp4"); const a = path.join(d, "a.aac"); await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=30:d=4", "-c:v", "libx264", "-preset", "ultrafast", v]); await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=4", "-c:a", "aac", "-b:a", "64k", a]); const bytes = await readFile(a); for (let i = Math.floor(bytes.length / 2); i < Math.floor(bytes.length / 2) + 600; i += 1) bytes[i] ^= 0x5a; const aBad = path.join(d, "abad.aac"); await writeFile(aBad, bytes); const mux = async (out: string, audio: string) => execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-i", v, "-i", audio, "-map", "0:v", "-map", "1:a", "-c", "copy", out]); const clean = path.join(d, "clean.mp4"); const damaged = path.join(d, "damaged.mp4"); await mux(clean, a); await mux(damaged, aBad); const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "" }; // The copy's audio is damaged and its source's is not: fatal. const r1 = await fullDecode(paths, damaged, undefined, clean); assert.equal(r1.ok, false, JSON.stringify(r1)); assert.match(r1.why!, /audio/); // The same damage in the source (the audio is copied packet for packet): a note. const r2 = await fullDecode(paths, damaged, undefined, damaged); assert.equal(r2.ok, true, JSON.stringify(r2)); assert.ok(r2.notes?.some((x) => /the source's own audio/.test(x)), JSON.stringify(r2.notes)); assert.deepEqual(await fullDecode(paths, clean, undefined, clean), { ok: true }); } finally { await rm(d, { recursive: true, force: true }); } });