// COMPACTING A SAVED VIDEO — the ffmpeg/ffprobe half // (controller/compactSavedVideos.ts runs it; lib/savedVideoCompaction.ts is // the pure half: settings, selector, estimate, names). // // Every function here reads or writes one file and answers a number; none of // them knows about pointers. The encoder's runs, the full decode and the // quality scoring each take the HEAVY SLOT (scripts/queue-lock.mjs --heavy // --estimate , which also waits while render mode holds the machine) and // run niced; the probes and the packet scans are demux-only and do not. // // SERVER-ONLY. import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { readFile, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { execa } from "execa"; import type { Paths } from "./paths"; import type { CompactionProbe } from "./savedVideoCompaction"; import { evidenceCutArgs } from "./evidenceClip-server"; import "./childKillGuard"; // Memory each kind of run is admitted to the heavy slot with: one SVT-AV1 // preset 8 1080p60 encode peaked at about 1.0 GB RSS (design note §3). export const CHUNK_ESTIMATE_MB = 1500; export const DECODE_ESTIMATE_MB = 800; export const SCORE_ESTIMATE_MB = 1500; export type GatedPaths = Pick; async function gateOf(paths: Pick): Promise { if (!paths.monorepoRoot) return null; const gate = path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs"); return (await stat(gate).then((s) => s.isFile()).catch(() => false)) ? gate : null; } // One ffmpeg run, behind the heavy slot when the checkout has the gate (a // test's temp root has none: ffmpeg runs directly), niced. The gate forwards a // cancel. Answers stderr; throws with its tail on a non-zero exit. export async function runHeavyFfmpeg( paths: GatedPaths, args: string[], opts: { estimateMB: number; signal?: AbortSignal; nice?: boolean }, ): Promise { const gate = await gateOf(paths); const inner = [...(opts.nice !== false ? ["nice", "-n", "10"] : []), paths.ffmpegBin, ...args]; const [bin, ...argv] = gate ? [process.execPath, gate, "--heavy", "--estimate", String(opts.estimateMB), "--", ...inner] : inner; const r = await execa(bin, argv, { reject: false, ...(opts.signal ? { cancelSignal: opts.signal } : {}) }); if (opts.signal?.aborted) throw new Error("cancelled"); if (r.exitCode !== 0) { const tail = String(r.stderr ?? "").trim().split("\n").slice(-3).join(" | "); throw new Error(`ffmpeg failed (exit ${r.exitCode ?? "?"})${tail ? `: ${tail}` : ""}`); } return String(r.stderr ?? ""); } // --- capability ------------------------------------------------------------- export async function ffmpegVersionLine(ffmpegBin: string): Promise { const r = await execa(ffmpegBin, ["-hide_banner", "-version"], { reject: false }); return String(r.stdout ?? "").split("\n")[0]?.trim() || "ffmpeg (version unknown)"; } export async function ffmpegHas(ffmpegBin: string, kind: "encoders" | "filters", name: string): Promise { const r = await execa(ffmpegBin, ["-hide_banner", `-${kind}`], { reject: false }); return new RegExp(`\\s${name}\\s`).test(String(r.stdout ?? "")); } // --- probing ---------------------------------------------------------------- function rate(v: unknown): number | null { if (typeof v !== "string") return null; const [n, d] = v.split("/").map(Number); const x = d ? n / d : n; return Number.isFinite(x) && x > 0 ? Number(x.toFixed(3)) : null; } function numOr(v: unknown): number | null { const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN; return Number.isFinite(n) ? n : null; } export type SourceProbe = CompactionProbe & { videoStart: number; // The first audio stream's start (seconds), or null with no audio. audioStart: number | null; // The container's own start (seconds): what a plain -ss counts from. formatStart: number; audioStreams: number; bytes: number; // The stream index of the video stream compaction replaces. mainVideoIndex: number; // That stream's time base (seconds per tick), when ffprobe says. timeBase?: number | null; // What the container must keep besides that stream: "mp4" when every other // stream is one an mp4 holds when copied (audio, mov_text, an attached // picture), else "matroska". container: "mp4" | "matroska"; }; // One ffprobe of a container: what the selector, the estimate and the encode // need. Null when ffprobe cannot read it. export async function probeCompactionSource(ffprobeBin: string, file: string): Promise { const r = await execa(ffprobeBin, ["-v", "error", "-show_streams", "-show_format", "-of", "json", file], { reject: false, }); if (r.exitCode !== 0) return null; let doc: { streams?: Record[]; format?: Record; }; try { doc = JSON.parse(String(r.stdout)); } catch { return null; } const streams = doc.streams ?? []; const v = streams.find( (s) => s.codec_type === "video" && !(s.disposition as { attached_pic?: number } | undefined)?.attached_pic, ); const audios = streams.filter((s) => s.codec_type === "audio"); const bytes = numOr(doc.format?.size) ?? (await stat(file).then((s) => s.size).catch(() => 0)); const seconds = numOr(doc.format?.duration); const audioKbps = audios.reduce((n, a) => n + (numOr(a.bit_rate) ?? 0) / 1000, 0) || null; let videoKbps = v ? (numOr(v.bit_rate) ?? null) : null; if (videoKbps !== null) videoKbps /= 1000; else if (v && seconds) { // No per-stream bitrate (an mkv, a webm): the container's, less the audio. videoKbps = Math.max(0, (bytes * 8) / seconds / 1000 - (audioKbps ?? 0)); } const others = streams.filter((x) => x !== v); const mp4Ok = others.every( (x) => x.codec_type === "audio" || (x.codec_type === "subtitle" && x.codec_name === "mov_text") || (x.codec_type === "video" && (x.disposition as { attached_pic?: number } | undefined)?.attached_pic === 1), ); const firstAudio = audios[0]; return { mainVideoIndex: typeof v?.index === "number" ? v.index : 0, timeBase: (() => { const [a, b] = String(v?.time_base ?? "").split("/").map(Number); return a > 0 && b > 0 ? a / b : null; })(), container: mp4Ok ? "mp4" : "matroska", audioStart: firstAudio ? (numOr(firstAudio.start_time) ?? 0) : null, formatStart: numOr(doc.format?.start_time) ?? 0, hasVideo: v !== undefined, vcodec: typeof v?.codec_name === "string" ? v.codec_name : null, width: typeof v?.width === "number" ? v.width : null, height: typeof v?.height === "number" ? v.height : null, fps: v ? (rate(v.avg_frame_rate) ?? rate(v.r_frame_rate)) : null, seconds: seconds && seconds > 0 ? seconds : null, videoKbps: videoKbps !== null ? Number(videoKbps.toFixed(1)) : null, audioKbps: audioKbps !== null ? Number(audioKbps.toFixed(1)) : null, videoStart: (v ? numOr(v.start_time) : null) ?? 0, audioStreams: audios.length, bytes, }; } export type PacketScan = { // Every video packet's pts (seconds), ascending. pts: Float64Array; // The keyframes' pts, ascending. keyframes: number[]; }; // The video stream's packets, demuxed (not decoded): the frame count and the // keyframes a chunk may start on. About a minute on a 12 GB file. export async function scanVideoPackets(ffprobeBin: string, file: string, signal?: AbortSignal): Promise { const all: number[] = []; const keyframes: number[] = []; await new Promise((resolve, reject) => { const child = spawn( ffprobeBin, ["-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time,flags", "-of", "csv=p=0", file], { stdio: ["ignore", "pipe", "pipe"] }, ); let carry = ""; let err = ""; const onAbort = () => child.kill("SIGKILL"); signal?.addEventListener("abort", onAbort, { once: true }); const take = (line: string) => { const [t, flags] = line.split(","); const x = Number(t); if (!Number.isFinite(x)) return; all.push(x); if (flags?.includes("K")) keyframes.push(x); }; child.stdout.setEncoding("utf8"); child.stdout.on("data", (d: string) => { const lines = (carry + d).split("\n"); carry = lines.pop() ?? ""; for (const l of lines) take(l.trim()); }); child.stderr.on("data", (d: Buffer) => (err = (err + d.toString()).slice(-2000))); child.on("error", reject); child.on("close", (code) => { signal?.removeEventListener("abort", onAbort); if (carry.trim()) take(carry.trim()); if (signal?.aborted) reject(new Error("cancelled")); else if (code !== 0) reject(new Error(`ffprobe could not scan ${path.basename(file)}: ${err.trim()}`)); else resolve(); }); }); const pts = Float64Array.from(all).sort(); keyframes.sort((a, b) => a - b); return { pts, keyframes }; } // The number of video packets (frames) in a file, demuxed. export async function countVideoFrames(ffprobeBin: string, file: string): Promise { const r = await execa( ffprobeBin, ["-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", file], { reject: false }, ); const n = Number(String(r.stdout ?? "").trim().split(/[\s,]/)[0]); if (r.exitCode !== 0 || !Number.isFinite(n)) throw new Error(`ffprobe could not count the frames of ${path.basename(file)}`); return n; } // --- chunks ----------------------------------------------------------------- export type ChunkPlan = { index: number; // Source seconds: `from` is a keyframe's pts; `to` the next chunk's, or past // the end for the last. from: number; to: number; // Source frames in [from, to). sourceFrames: number; // Frames the chunk must hold: the source's, or the fps filter's count. expectedFrames: number; // Its source frames by index in the file, [fromIndex, toIndex), and — when // the rate is reduced by a whole ratio — the constant `select` (keepSelect) // that keeps the file's KEPT FRAMES among them. fromIndex?: number; toIndex?: number; select?: string; // The last chunk runs to the end of the source. last?: boolean; }; function countIn(pts: Float64Array, from: number, to: number): number { // pts is sorted: two binary searches. const lower = (x: number) => { let lo = 0; let hi = pts.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (pts[mid] < x) lo = mid + 1; else hi = mid; } return lo; }; return lower(to) - lower(from); } const EDGE = 1e-4; // Chunks of about `chunkSeconds`, each starting on a source keyframe. A chunk // is never shorter than half the asked length unless it is the only one. export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: number | null, sourceFps?: number | null, keep?: KeepRule): ChunkPlan[] { const { pts, keyframes } = scan; if (!pts.length) return []; const first = pts[0]; const end = pts[pts.length - 1] + 1; const starts = [keyframes.length ? Math.min(keyframes[0], first) : first]; // With a frame-rate change, a chunk starts only where the copy's frames // line up with the whole file's: // - a WHOLE ratio m (60 → 30) keeps every m-th source frame WITH ITS OWN // TIMESTAMP, counted from each chunk's first frame, so a chunk starts only // on a keyframe whose INDEX in the file is a multiple of m — by index, not // by time: a live recording drops frames, and after an odd gap the time // grid and the index grid part; // - any other ratio goes through the fps filter, a constant grid from the // chunk's first frame: a keyframe ON THE COPY'S TIME GRID, else each // chunk's rounded count would move the picture by part of a frame. const m = wholeRatio(sourceFps, outFps); const indexOf = (k: number) => countIn(pts, -Infinity, k - EDGE); // With the file's kept frames (keptSourceFrames), a chunk starts only on a // KEPT keyframe: then each chunk's own selection is the file's. const mask = keep && m ? keptSourceFrames(pts, keep.minStep) : null; const onGrid = (k: number) => { if (!outFps) return true; if (mask) return mask[indexOf(k)] === 1; if (m) return indexOf(k) % m === 0; const x = (k - starts[0]) * outFps; return Math.abs(x - Math.round(x)) < 0.02; }; for (const k of keyframes) { if (k - starts[starts.length - 1] >= chunkSeconds - EDGE && onGrid(k)) starts.push(k); } const plans: ChunkPlan[] = []; for (let i = 0; i < starts.length; i += 1) { const from = starts[i]; const to = i + 1 < starts.length ? starts[i + 1] : end; const sourceFrames = countIn(pts, from - EDGE, to - EDGE); const a = indexOf(from); const b = a + sourceFrames; let keptHere = 0; if (mask) for (let j = a; j < b; j += 1) keptHere += mask[j]; plans.push({ index: i, from, to, sourceFrames, expectedFrames: !outFps ? sourceFrames : mask ? keptHere : wholeRatio(sourceFps, outFps) ? Math.ceil(sourceFrames / wholeRatio(sourceFps, outFps)!) : framesAtFps(pts, from, to, outFps, i + 1 === starts.length), fromIndex: a, toIndex: b, ...(mask ? { select: keepSelect(keep!.minStep) } : {}), ...(i + 1 === starts.length ? { last: true } : {}), }); } return plans; } // The fps filter's frame count over a span: one frame per 1/fps step of the // output clock, which starts at the span's first source frame. function framesAtFps(pts: Float64Array, from: number, to: number, fps: number, last: boolean): number { if (!last) return Math.round((to - from) * fps); // The last chunk ends with the source's last frame, which lasts one source // frame: the span is [from, lastPts + 1 source frame). const n = pts.length; const step = n > 1 ? pts[n - 1] - pts[n - 2] : 1 / fps; return Math.round((pts[n - 1] + step - from) * fps); } export type EncodeSettings = { preset: number; crf: number; gopSeconds: number; pixFmt: string; // The output frame rate when the source's is capped, else null. fps: number | null; sourceFps: number; // The source container's start (seconds): a plain -ss counts from it. formatStart?: number; }; // One chunk: an input seek to the chunk's keyframe — RELATIVE TO THE FILE'S // START (the scan's pts are the file's own; a plain -ss counts from the // container's start time, so an offset mp4 or mkv, or an mpegts starting at // 1.4 s, would be cut that much late; `-seek_timestamp 1` would mend that for // mp4 and mkv but not for mpegts, measured) — the video only, ended by TIME, not // by a frame count: what the encoder actually wrote is counted afterwards, so // a short or long chunk shows. Into an mp4 with a 90 kHz track clock (exact for // 24, 25, 30, 50, 60 and the NTSC rates), which the concat demuxer joins // without rounding a frame's time to the millisecond. export const CHUNK_EXT = ".mp4"; // The copy's real rate: the source's nominal one over a whole ratio, else the cap. function outRate(s: EncodeSettings): number { const m = wholeRatio(s.sourceFps, s.fps); return m ? s.sourceFps / m : (s.fps ?? s.sourceFps); } export function encodeChunkArgs(src: string, chunk: ChunkPlan, s: EncodeSettings, out: string): string[] { const outFps = s.fps ?? s.sourceFps; // A keyframe at the first frame at or after every gopSeconds OF TIME (the // frames' own timestamps: a gap does not stretch a GOP); -g, twice that in // frames, only bounds it. const gop = Math.max(1, Math.round(2 * s.gopSeconds * outFps)); // The input read up to a quarter source frame short of the next chunk's // keyframe (an input -to: the decoder, and the fps filter's last frame, are // flushed at it); the last chunk reads to the end. const start = s.formatStart ?? 0; const to = chunk.last ? null : chunk.to - start - 0.25 / s.sourceFps; return [ "-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-ss", Math.max(0, chunk.from - start - 0.001).toFixed(6), ...(to !== null ? ["-to", to.toFixed(6)] : []), "-i", src, "-map", "0:v:0", "-an", "-sn", "-dn", // THE SOURCE'S TIMESTAMPS KEPT (review, the first real run): every frame // keeps its own pts, relative to the chunk's first (the mux puts each chunk // at its source time), so a frame the live recording dropped stays a gap // and the picture stays on the sound's clock after it. A whole ratio keeps // every m-th frame BY INDEX (`select`, passed through; not `framestep`, // which re-times what it keeps — measured: after an odd gap it wrote a // frame at 6.000 s that the source does not have); any other ratio, the // fps filter's constant grid, which repeats a frame across a gap (sync // kept, the gap filled). The encoder is told the copy's rate itself // (`select` leaves the source's on the link). ...(s.fps && !wholeRatio(s.sourceFps, s.fps) ? ["-vf", `${decimateTo(s.sourceFps, s.fps)}setpts=PTS-STARTPTS`] : [ "-vf", `${chunk.select ? `select='${chunk.select}',` : decimateTo(s.sourceFps, s.fps)}setpts=PTS-STARTPTS`, "-fps_mode", "passthrough", // …ON THE SOURCE'S OWN TIME BASE (review H1): the default, 1 / the // frame rate, rounded a millisecond-stamped recording's times onto a // 1/60 s grid (up to 0.67 ms off); the 90 kHz copy holds them exactly. "-enc_time_base:v", "demux", ]), "-c:v", "libsvtav1", "-preset", String(s.preset), "-crf", String(s.crf), "-svtav1-params", `fps-num=${Math.round(outRate(s) * 1000)}:fps-denom=1000`, "-force_key_frames", `expr:gte(t,n_forced*${s.gopSeconds})`, "-g", String(gop), "-pix_fmt", s.pixFmt, "-video_track_timescale", "90000", "-f", "mp4", out, ]; } // The chunks joined (concat demuxer, `-c copy`), the source's video start kept, // and EVERY OTHER STREAM OF THE SOURCE COPIED bit for bit — every audio track // (a later transcription hears the same samples, at the same seconds), // subtitles, data, attachments — and its chapters and metadata. An mp4 when // the source's other streams fit one, else Matroska (SourceProbe.container). export function muxArgs( listFile: string, src: string, videoStart: number, out: string, opts: { mainVideoIndex?: number; container?: "mp4" | "matroska" } = {}, ): string[] { const container = opts.container ?? "mp4"; return [ "-nostdin", "-hide_banner", "-loglevel", "error", "-y", ...(videoStart > 0 ? ["-itsoffset", videoStart.toFixed(6)] : []), "-f", "concat", "-safe", "0", "-i", listFile, "-i", src, "-map", "0:v:0", "-map", "1", "-map", `-1:${opts.mainVideoIndex ?? 0}`, "-c", "copy", "-map_metadata", "1", "-map_chapters", "1", ...(container === "mp4" ? ["-movflags", "+faststart", "-f", "mp4"] : ["-f", "matroska"]), out, ]; } // EVERY STREAM BUT ONE VIDEO, AND THE CHAPTERS, as words to compare: what a // copy must hold of its source besides the picture it replaces. export async function streamInventory(ffprobeBin: string, file: string, skipIndex: number): Promise { const r = await execa(ffprobeBin, ["-v", "error", "-show_streams", "-show_chapters", "-of", "json", file], { reject: false }); if (r.exitCode !== 0) throw new Error(`ffprobe could not read the streams of ${path.basename(file)}`); const doc = JSON.parse(String(r.stdout)) as { streams?: { index?: number; codec_type?: string; codec_name?: string; channels?: number; disposition?: { attached_pic?: number } }[]; chapters?: unknown[]; }; const out = (doc.streams ?? []) .filter((x) => x.index !== skipIndex) .map((x) => [x.codec_type ?? "?", x.codec_name ?? "?", ...(x.channels ? [`${x.channels}ch`] : []), ...(x.disposition?.attached_pic ? ["attached"] : [])].join(":"), ); if (doc.chapters?.length) out.push(`chapters:${doc.chapters.length}`); return out.sort(); } // The concat list. With `durations` (every chunk's but the last: the next // chunk's first source pts less its own), each chunk starts at its SOURCE time, // not where the one before happened to end. export function concatList(files: string[], durations?: number[]): string { return ( files .map((f, i) => `file '${f.replace(/'/g, "'\\''")}'` + (durations && i < durations.length ? `\nduration ${durations[i].toFixed(6)}` : "")) .join("\n") + "\n" ); } // --- timestamps ------------------------------------------------------------- // THE KEPT FRAMES (reviews G4, H1). A source capped by a whole ratio keeps a // frame when at least `keepMinStep` has passed since the last kept frame's // pts — by TIME, from the source's own timestamps: a 60 fps stretch keeps // every other frame, a stretch where the recording ran at 30 keeps every // frame, after a gap the next frame; each kept frame keeps its own pts. // // ONE CONSTANT RULE, the same in ffmpeg and in the code: the encoder's select // is `keepSelect` (a few dozen characters, whatever the file — a set of runs // fragmented into hundreds of thousands on a recording with millisecond // timestamps, and broke ffmpeg's parser and argv), and every check that pairs // source and copy frames derives the kept set from the same rule // (`keptSourceFrames`). The step is one copy frame less HALF A SOURCE FRAME // (less 0.25 ms more): between one source step and two, so a 60 fps source // whose timestamps are rounded to the millisecond (16, 17, 17 ms) keeps // exactly every other frame, and off every millisecond and 90 kHz tick, so a // rounding can never put a step exactly on it. export type KeepRule = { minStep: number }; export function keepMinStep(outFps: number, sourceFps: number): number { return Number((1 / outFps - 0.5 / sourceFps - 0.00025).toFixed(6)); } export function keptSourceFrames(pts: Float64Array, minStep: number): Uint8Array { const m = new Uint8Array(pts.length); let last = -Infinity; for (let i = 0; i < pts.length; i += 1) { if (i > 0 && pts[i] - last < minStep) continue; m[i] = 1; last = pts[i]; } return m; } // The rule as ffmpeg's select: the first frame, then each one at least // `minStep` after the last selected. export function keepSelect(minStep: number): string { return `isnan(prev_selected_t)+gte(t-prev_selected_t,${minStep.toFixed(6)})`; } // The nominal frame rate of a scan: 1 / its typical frame step — the mean of // the steps within half of the median, so a live recording's dropped frames // (long steps) do not move it, and a container's ticks (a 30 fps mkv's 33 and // 34 ms) average out. Within 0.05 % of a whole or an NTSC (×1000/1001) rate, // that rate (1/60 s in 1/15360 s ticks reads 59.998). export function nominalFps(pts: Float64Array): number | null { if (pts.length < 2) return null; const d = new Float64Array(pts.length - 1); for (let i = 1; i < pts.length; i += 1) d[i - 1] = pts[i] - pts[i - 1]; const sorted = Float64Array.from(d).sort(); const median = sorted[sorted.length >> 1]; if (!(median > 0)) return null; let sum = 0; let n = 0; for (const x of d) { if (Math.abs(x - median) > median / 2) continue; sum += x; n += 1; } const r = n / sum; let best: number | null = null; for (const c of [Math.round(r), Math.round(r * 1.001) / 1.001]) { if (c > 0 && Math.abs(r - c) / c < 0.0005 && (best === null || Math.abs(r - c) < Math.abs(r - best))) best = c; } return best ?? r; } export type SourceGaps = { count: number; totalSeconds: number; largest: number; largestAt: number; at: number[] }; // The recording's DROPPED FRAMES: every step longer than 1.5 nominal frames, // how many, how much time they hold beyond one frame each, the largest and // where (the first 20 places). export function sourceGaps(pts: Float64Array): SourceGaps { const fps = nominalFps(pts); const out: SourceGaps = { count: 0, totalSeconds: 0, largest: 0, largestAt: 0, at: [] }; if (!fps) return out; const step = 1 / fps; for (let i = 1; i < pts.length; i += 1) { const d = pts[i] - pts[i - 1]; if (d <= 1.5 * step) continue; out.count += 1; out.totalSeconds += d - step; if (out.at.length < 20) out.at.push(pts[i - 1]); if (d > out.largest) { out.largest = d; out.largestAt = pts[i - 1]; } } return out; } // THE COPY'S TIMESTAMPS, as the encode must have written them: for each // chunk, its source frames' pts — every m-th from its first under a whole // ratio m — or, through the fps filter, the constant grid from its first frame. export function expectedCopyPts( pts: Float64Array, chunks: Pick[], ratio: number | null, fps: number | null, keep?: KeepRule, ): Float64Array { const out: number[] = []; if (keep) { // The file's kept frames, by the rule the encode's `select` applied. const mask = keptSourceFrames(pts, keep.minStep); for (let i = 0; i < pts.length; i += 1) if (mask[i]) out.push(pts[i]); return Float64Array.from(out); } for (const c of chunks) { const a = countIn(pts, -Infinity, c.from - EDGE); const b = countIn(pts, -Infinity, c.to - EDGE); if (fps && !ratio) { for (let k = 0; k < c.expectedFrames; k += 1) out.push(pts[a] + k / fps); } else { const m = ratio ?? 1; for (let i = a; i < b; i += m) out.push(pts[i]); } } return Float64Array.from(out); } export type TimestampCheck = { frames: number; expected: number; maxDeviation: number; at: number; over: number; perChunk: number[] }; // Every frame of the copy against the timestamp it must have (both sorted, // each relative to its own file's start), within `tolerance` (a container's // rounding: Matroska keeps milliseconds). The worst deviation per chunk is // the picture against the sound at that point of the file: the audio is the // source's, packet for packet, at the source's times. export function compareCopyPts(expected: Float64Array, actual: Float64Array, tolerance: number, chunkStarts: number[] = [0]): TimestampCheck { const n = Math.min(expected.length, actual.length); const out: TimestampCheck = { frames: actual.length, expected: expected.length, maxDeviation: 0, at: 0, over: 0, perChunk: chunkStarts.map(() => 0) }; let c = 0; for (let i = 0; i < n; i += 1) { while (c + 1 < chunkStarts.length && i >= chunkStarts[c + 1]) c += 1; const d = Math.abs(actual[i] - expected[i]); if (d > out.perChunk[c]) out.perChunk[c] = d; if (d > tolerance) out.over += 1; if (d > out.maxDeviation) { out.maxDeviation = d; out.at = expected[i]; } } return out; } // --- verification ----------------------------------------------------------- // Every frame of the video decoded, with ffmpeg told to stop at the first // error (`-xerror`) and to print any. An empty stderr and a zero exit is a // clean decode. // WHAT A FULL DECODE'S STDERR MEANS (review, before the second real run: a // correct copy of a source with a dropped frame failed on a NULL MUXER line). // FATAL — the decoder or demuxer reporting damage to the picture or sound: // any line matching DECODE_FATAL. BENIGN — the null muxer's own timestamp // bookkeeping, not the picture: DECODE_BENIGN (with `-enc_time_base demux` it // does not happen; if it does, it is not a decode error). Anything else is a // note, recorded and not fatal. A non-zero exit is always fatal (-xerror stops // at the decoder's first error). export const DECODE_FATAL: RegExp[] = [ /error/i, /invalid/i, /corrupt/i, /conceal/i, /missing/i, /non-existing/i, /overread/i, /out of range/i, /illegal/i, /damaged/i, /truncat/i, /unavailable/i, /failed/i, /mmco/i, /desync/i, /no frame/i, /broken/i, // Review H4: references and bitstreams, the container, AAC. /frame num gap/i, /could not find ref/i, /unknown obu/i, /partial file/i, /reserved bit set/i, /prediction is not allowed/i, /is not allocated/i, /input buffer exhausted/i, /exceeds limit/i, /inconsistent channel configuration/i, ]; export const DECODE_BENIGN: RegExp[] = [/non[- ]monotonic(ally increasing)? dts/i, /^last message repeated/i]; export function classifyDecodeStderr(text: string): { fatal: string[]; benign: string[]; notes: string[] } { const out = { fatal: [] as string[], benign: [] as string[], notes: [] as string[] }; for (const raw of text.split("\n")) { const l = raw.trim(); if (!l) continue; // Strip "[h264 @ 0x55…] " so a pattern judges the message. const msg = l.replace(/^\[[^\]]*\]\s*/, ""); if (DECODE_BENIGN.some((r) => r.test(msg))) out.benign.push(l); else if (DECODE_FATAL.some((r) => r.test(msg))) out.fatal.push(l); else out.notes.push(l); } return out; } // Every frame decoded into the null muxer, KEEPING EACH STREAM'S OWN TIME // BASE (`-enc_time_base demux`): re-quantised to the copy's nominal 1001/30000, // two kept frames around a dropped one rounded to the same tick and the muxer // complained, about nothing in the picture. // // TWO PASSES (review H4). The VIDEO, 0:v:0 alone, stopping at its first // error: any fatal line fails the copy. Then the AUDIO, every track: it is the // source's, packet for packet (checked apart), so damage in it is the // source's — with `reference` (the source) given, fatal audio lines the // source's own audio decode shows as many of are a note; more than the // source's fail. async function decodePass(paths: GatedPaths, file: string, map: string[], xerror: boolean, signal?: AbortSignal) { try { const err = await runHeavyFfmpeg( paths, ["-nostdin", "-hide_banner", "-v", "error", ...(xerror ? ["-xerror"] : []), "-i", file, ...map, "-enc_time_base", "demux", "-f", "null", "-"], { estimateMB: DECODE_ESTIMATE_MB, ...(signal ? { signal } : {}) }, ); return { exited: true, ...classifyDecodeStderr(err) }; } catch (e) { if (signal?.aborted) throw e; return { exited: false, fatal: [(e as Error).message], benign: [] as string[], notes: [] as string[] }; } } export async function fullDecode( paths: GatedPaths, file: string, signal?: AbortSignal, reference?: string, ): Promise<{ ok: boolean; why?: string; notes?: string[] }> { const v = await decodePass(paths, file, ["-map", "0:v:0"], true, signal); if (v.fatal.length) return { ok: false, why: `video: ${v.fatal.slice(-2).join(" | ")}` }; const notes = [...v.benign, ...v.notes]; const a = await decodePass(paths, file, ["-map", "0:a?", "-vn"], false, signal); // No audio at all: ffmpeg has nothing to write and says so. if (!a.exited && /does not contain any stream/i.test(a.fatal[0] ?? "")) return notes.length ? { ok: true, notes: notes.slice(0, 5) } : { ok: true }; if (a.fatal.length) { const ref = reference ? await decodePass(paths, reference, ["-map", "0:a?", "-vn"], false, signal) : null; if (!ref || !a.exited || ref.fatal.length < a.fatal.length) { return { ok: false, why: `audio: ${a.fatal.slice(-2).join(" | ")}${ref ? ` (the source's own audio: ${ref.fatal.length} such line(s))` : ""}` }; } notes.push(`audio: ${a.fatal.length} decode error line(s), as many as the source's own audio shows (copied packet for packet): ${a.fatal[0]}`); } notes.push(...a.benign, ...a.notes); return notes.length ? { ok: true, notes: notes.slice(0, 5) } : { ok: true }; } export type AudioHash = { // sha256 over every audio packet's (stream, size, md5) in order. data: string; // sha256 over every audio packet's (stream, pts, duration) relative to the // first packet's pts, and that first pts. timing: string; firstPts: number | null; packets: number; // Every packet's time from the first, in seconds — compared with a tolerance // of a container's rounding (Matroska keeps milliseconds). times?: Float64Array; }; export const AUDIO_TIMING_TOLERANCE_S = 0.002; // Same audio timing: the per-packet times within the tolerance (or, without // them, the timing hashes equal). export function sameAudioTiming(a: AudioHash, b: AudioHash): boolean { if (!a.times || !b.times) return a.timing === b.timing; if (a.times.length !== b.times.length) return false; for (let i = 0; i < a.times.length; i += 1) if (Math.abs(a.times[i] - b.times[i]) > AUDIO_TIMING_TOLERANCE_S) return false; return true; } // The audio packets of every audio stream, demuxed and copied (`-c copy`) into // framemd5: what a copied track must reproduce exactly. // AAC carried in ADTS (an mpegts, a raw .aac) loses its ADTS headers when // copied into an mp4 (aac_adtstoasc, which ffmpeg inserts): the same samples // in other packet bytes. Both sides are hashed through that filter, which // passes a packet with no ADTS header through as it is. async function aacAudioIndexes(ffprobeBin: string, file: string): Promise { const r = await execa(ffprobeBin, ["-v", "error", "-select_streams", "a", "-show_entries", "stream=codec_name", "-of", "csv=p=0", file], { reject: false, }); return String(r.stdout ?? "") .split("\n") .map((l, i) => (l.trim() === "aac" ? i : -1)) .filter((i) => i >= 0); } export async function audioPacketsHash(ffmpegBin: string, file: string, signal?: AbortSignal, ffprobeBin = "ffprobe"): Promise { const bsf = (await aacAudioIndexes(ffprobeBin, file)).flatMap((i) => [`-bsf:a:${i}`, "aac_adtstoasc"]); const data = createHash("sha256"); const timing = createHash("sha256"); let first: number | null = null; let packets = 0; const times: number[] = []; await new Promise((resolve, reject) => { const child = spawn( ffmpegBin, ["-nostdin", "-hide_banner", "-v", "error", "-i", file, "-map", "0:a?", "-c", "copy", ...bsf, "-f", "framemd5", "-"], { stdio: ["ignore", "pipe", "pipe"] }, ); let carry = ""; let err = ""; const onAbort = () => child.kill("SIGKILL"); signal?.addEventListener("abort", onAbort, { once: true }); // Each stream's timebase, from framemd5's header ("#tb 0: 1/44100"): the // timing is compared in SECONDS, to the millisecond — the same packets // carried by a Matroska source (1 ms ticks) and an mp4 copy (1/44100 s) // are the same times in other numbers. const tbs = new Map(); const take = (line: string) => { if (!line) return; if (line.startsWith("#")) { const m = /^#tb (\d+): (\d+)\/(\d+)/.exec(line); if (m) tbs.set(m[1], Number(m[2]) / Number(m[3])); return; } const f = line.split(",").map((x) => x.trim()); if (f.length < 6) return; const [streamIdx, , pts, , size, md5] = f; const p = Number(pts) * (tbs.get(streamIdx) ?? 1); if (first === null) first = p; packets += 1; data.update(`${streamIdx},${size},${md5}\n`); timing.update(`${streamIdx},${Math.round((p - (first ?? 0)) * 100)}\n`); times.push(p - (first ?? 0)); }; child.stdout.setEncoding("utf8"); child.stdout.on("data", (d: string) => { const lines = (carry + d).split("\n"); carry = lines.pop() ?? ""; for (const l of lines) take(l.trim()); }); child.stderr.on("data", (d: Buffer) => (err = (err + d.toString()).slice(-2000))); child.on("error", reject); child.on("close", (code) => { signal?.removeEventListener("abort", onAbort); if (carry.trim()) take(carry.trim()); if (signal?.aborted) reject(new Error("cancelled")); else if (code !== 0) reject(new Error(`ffmpeg could not read the audio of ${path.basename(file)}: ${err.trim()}`)); else resolve(); }); }); return { data: data.digest("hex"), timing: timing.digest("hex"), firstPts: first, packets, times: Float64Array.from(times) }; } export type QualitySample = { at: number; score: number }; // THE SOURCE TAKEN TO THE COPY'S RATE, the same way in the encode and in every // check: for a whole ratio (60 -> 30) every m-th frame from the first — the // copy's frame k IS the source's frame m·k, chunks starting on the copy's grid // — else the fps filter. (The fps filter's rounding took the ODD frames of a // 60 fps chunk seeked a millisecond early: a copy one source frame late.) export function wholeRatio(sourceFps: number | null | undefined, fps: number | null): number | null { if (!fps || !sourceFps) return null; const m = sourceFps / fps; return m > 1 && Math.abs(m - Math.round(m)) < 0.01 ? Math.round(m) : null; } export function decimateTo(sourceFps: number | null | undefined, fps: number | null): string { if (!fps) return ""; const m = wholeRatio(sourceFps, fps); return m ? `select='not(mod(n,${m}))',` : `fps=${fps},`; } // One quality score of a 2-second excerpt of the re-encode against the same // seconds of the source (both input-seeked to `at`; the source taken to the // re-encode's frame rate first). VMAF where this ffmpeg has libvmaf, else SSIM. export async function scoreExcerpt( paths: GatedPaths, opts: { compacted: string; source: string; at: number; // The SAME FRAME's seek time in the source, when its command-line // timeline starts elsewhere than the copy's (cliTimelineStart); else `at`. sourceAt?: number; // The kept frames' `select` (keepSelect), in place of the ratio's // decimation; the excerpt starts on a kept frame. sourceSelect?: string; seconds: number; fps: number | null; sourceFps?: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal; }, ): Promise { // FRAMES PAIRED BY THEIR NUMBER, not their timestamps: both inputs start on // the same picture (sampleTimes puts `at` on the copy's frame grid), and the // source is taken to the copy's rate first, so frame n of one is frame n of // the other. A timestamp pairing paired neighbours wherever a container // rounded a frame's time. const n = renumber(opts.fps ?? opts.sourceFps ?? null); const srcAt = opts.sourceAt ?? opts.at; const pre = Math.max(0, srcAt - 10); const dec = opts.sourceSelect ? `select='${opts.sourceSelect}',` : decimateTo(opts.sourceFps, opts.fps); const ref = `[1:v]trim=start=${(srcAt - pre).toFixed(4)},${dec}${n}[r]`; const dist = `[0:v]${n}[d]`; const log = path.join(opts.scratchDir, `vmaf-${Math.round(opts.at * 1000)}.json`); const metric = opts.metric === "vmaf" ? `[d][r]libvmaf=log_fmt=json:log_path=${log.replace(/[:\\']/g, "\\$&")}:n_threads=4` : "[d][r]ssim"; const args = [ "-nostdin", "-hide_banner", "-loglevel", "info", "-ss", opts.at.toFixed(4), "-t", opts.seconds.toFixed(3), "-i", opts.compacted, // The source decoded from up to 10 s earlier and trimmed to the second: // exact in any container (see referenceCutArgs). "-ss", pre.toFixed(4), "-t", (srcAt - pre + opts.seconds).toFixed(3), "-i", opts.source, "-lavfi", `${dist};${ref};${metric}`, "-f", "null", "-", ]; const err = await runHeavyFfmpeg(paths, args, { estimateMB: SCORE_ESTIMATE_MB, ...(opts.signal ? { signal: opts.signal } : {}), }); if (opts.metric === "ssim") { const m = /SSIM .*All:(-?[0-9.]+)/.exec(err); if (!m) throw new Error(`no SSIM in ffmpeg's output at ${opts.at.toFixed(1)} s`); return Number(m[1]); } try { const doc = JSON.parse(await readFile(log, "utf8")) as { pooled_metrics?: { vmaf?: { mean?: number } } }; const mean = doc.pooled_metrics?.vmaf?.mean; if (typeof mean !== "number") throw new Error("no pooled VMAF"); return mean; } catch (e) { const m = /VMAF score: ([0-9.]+)/.exec(err); if (m) return Number(m[1]); throw new Error(`no VMAF for the excerpt at ${opts.at.toFixed(1)} s: ${(e as Error).message}`); } finally { await rm(log, { force: true }).catch(() => {}); } } // The excerpts' seconds: `n` spread through the file, away from its ends, each // ON THE RE-ENCODE'S FRAME GRID less a quarter frame. A seek lands on the // first frame at or after it, so both files start on the same picture; off the // grid, a 30 fps copy's first frame is a 60 fps source's NEXT one, and a // one-frame offset on moving content scores as a bad encode. export function sampleTimes(seconds: number, n: number, excerpt: number, fps: number): number[] { const usable = Math.max(0, seconds - excerpt - 0.5); if (usable <= 0) return [0]; const out: number[] = []; for (let i = 0; i < n; i += 1) { const t = Math.round((((i + 0.5) / n) * usable) * fps) / fps; out.push(Number(Math.max(0, t - 0.25 / fps).toFixed(4))); } return [...new Set(out)]; } // A REAL WINDOW CUT FROM EACH COPY through the evidence cutter // (evidenceCutArgs: the input seek and the x264 re-encode every saved-video // window goes through), and the two cuts compared FRAME BY FRAME at the cut's // own size (at most 1280×720), the original's cut taken to the copy's rate: // frames paired by number, SSIM at the pairing as cut and at one frame either // way. The copy's cut must score best as cut: one that scores better a frame // off lands on other frames than the original's (on moving picture; on a // still one all three tie, and a tie passes — an offset there shows nothing). export type CutComparison = { ssim: number; earlier: number; later: number }; // Frame n's time is n / rate on both sides — the rate written out, because a // `select` keeps its input's FRAME_RATE, and a pairing by time then pairs the // copy's frame n with the original's n / 2. // // // The SAME timebase and integer timestamps on both sides (`settb=1/rate`, // then `setpts=N`): the filters pair frames by time, and n / 30 s carried in a // 90 kHz copy and a 15360 Hz source rounds to different numbers — measured: a // lossless copy, frame for frame identical by framemd5, paired every fifth // frame with its neighbour. function renumber(rate: number | null): string { return rate ? `settb=1/${rate},setpts=N` : "setpts=N/FRAME_RATE/TB,settb=AVTB"; } async function ssimOf(paths: GatedPaths, b: string, a: string, rate: string, outRate: number | null, shift: number, signal?: AbortSignal): Promise { const n = renumber(outRate); // shift > 0: the copy's frame n against the original's n + shift. const trimA = shift > 0 ? `trim=start_frame=${shift},` : ""; const trimB = shift < 0 ? `trim=start_frame=${-shift},` : ""; const r = await execa( paths.ffmpegBin, [ "-nostdin", "-hide_banner", "-loglevel", "info", "-i", b, "-i", a, "-lavfi", `[0:v]${trimB}${n}[d];[1:v]${rate}${trimA}${n}[r];[d][r]ssim=eof_action=endall`, "-f", "null", "-", ], { reject: false, ...(signal ? { cancelSignal: signal } : {}) }, ); const m = /SSIM .*All:(-?[0-9.]+)/.exec(String(r.stderr ?? "")); if (r.exitCode !== 0 || !m) throw new Error("could not compare the two cuts"); return Number(m[1]); } // THE ORIGINAL'S CUT, as the reference: the evidence cutter's own encode, but // decoded from up to 10 s earlier and seeked on the output — exact whatever // the container (an input seek into an mpegts lands mid-GOP, and its first // pictures are the decoder's guesses). The COPY is cut by the cutter itself, // input seek and all: that is what is being proved. export function referenceCutArgs(file: string, a: number, b: number, out: string): string[] { const args = evidenceCutArgs(file, a, b, "video", out); const i = args.indexOf("-ss"); const pre = Math.max(0, a - 10); args.splice(i, 6, "-ss", pre.toFixed(3), "-i", file, "-ss", (a - pre).toFixed(3), "-t", (b - a).toFixed(3)); return args; } export async function compareCuts( paths: GatedPaths, opts: { compacted: string; source: string; at: number; // The same frame's time in the source's command-line timeline (see // scoreExcerpt); else `at`. sourceAt?: number; // The kept frames' `select` (keepSelect); the cut starts on a kept frame. sourceSelect?: string; seconds: number; fps: number | null; sourceFps?: number | null; scratchDir: string; signal?: AbortSignal; }, ): Promise { const srcAt = opts.sourceAt ?? opts.at; const a = path.join(opts.scratchDir, `cut-src-${Math.round(opts.at * 1000)}.mp4`); const b = path.join(opts.scratchDir, `cut-out-${Math.round(opts.at * 1000)}.mp4`); try { for (const [file, out, args] of [ [opts.source, a, referenceCutArgs(opts.source, srcAt, srcAt + opts.seconds, a)], [opts.compacted, b, evidenceCutArgs(opts.compacted, opts.at, opts.at + opts.seconds, "video", b)], ] as const) { const r = await execa(paths.ffmpegBin, args, { reject: false, ...(opts.signal ? { cancelSignal: opts.signal } : {}), }); if (r.exitCode !== 0) { throw new Error( `the evidence cutter failed on ${path.basename(file)} at ${opts.at.toFixed(1)} s: ` + String(r.stderr ?? "").trim().split("\n").slice(-2).join(" | "), ); } } const rate = opts.sourceSelect ? `select='${opts.sourceSelect}',` : decimateTo(opts.sourceFps, opts.fps); const outRate = opts.fps ?? opts.sourceFps ?? null; const ssim = await ssimOf(paths, b, a, rate, outRate, 0, opts.signal); const later = await ssimOf(paths, b, a, rate, outRate, 1, opts.signal); const earlier = await ssimOf(paths, b, a, rate, outRate, -1, opts.signal); return { ssim, earlier, later }; } finally { await rm(a, { force: true }).catch(() => {}); await rm(b, { force: true }).catch(() => {}); } } // WHERE A FILE'S COMMAND-LINE TIMELINE STARTS (absolute seconds): an `-ss t` // on it lands on the first frame at or after this + t. Not always the // container's start ffprobe reports — measured: an mpegts whose audio starts at // 2.877 s and video at 2.900 s is placed by ffmpeg from 2.900 s, our mp4 copy // of it from its container start — so the copy and its source each get their // own seek time for the same frame. The first video frame's time without a // seek, against its pts. export async function cliTimelineStart(ffmpegBin: string, file: string, firstVideoPts: number): Promise { const r = await execa(ffmpegBin, ["-nostdin", "-hide_banner", "-i", file, "-map", "0:v:0", "-an", "-sn", "-vf", "showinfo", "-frames:v", "1", "-f", "null", "-"], { reject: false, }); const m = /pts_time:(-?[0-9.]+)/.exec(String(r.stderr ?? "")); if (!m) throw new Error(`could not read where ffmpeg starts ${path.basename(file)}'s timeline`); return firstVideoPts - Number(m[1]); } // A cut a frame off scores better shifted than as cut (beyond noise). export const CUT_OFFSET_MARGIN = 0.001; export function cutIsOffset(c: CutComparison): boolean { return Math.max(c.earlier, c.later) > c.ssim + CUT_OFFSET_MARGIN; } // THE WHOLE FILE, COMPARED, EVERY FRAME (reviews H1 and F2). Both copies // decoded end to end; the source taken to the copy's rate exactly as the // encode took it (decimateTo), both on one clock and paired frame for frame // (renumber); scaled to WHOLE_FILE_WIDTH px wide, its aspect kept, grey. Each // frame scored by SSIM whole, AND split into a WHOLE_FILE_GRID × WHOLE_FILE_GRID // grid of tiles, each tile scored on its own — so a change to a small region // is not averaged away by the rest of the picture. One ffmpeg run (the tiles // are crops of the same decoded frames: one decode, 1 + grid² SSIM filters). // // Answers every frame's whole score, and per tile its lowest score (and // frame) and its longest run of frames below `tileFloor` (and where it // starts). The caller judges the floors. export const WHOLE_FILE_WIDTH = 256; export const WHOLE_FILE_GRID = 8; export const WHOLE_FILE_ESTIMATE_MB = 1500; export type TileSummary = { index: number; col: number; row: number; min: number; minAt: number; // frame index longestBelow: number; // frames longestBelowAt: number; // frame index of the run's start }; export type WholeFileComparison = { frames: Float32Array; // THE COLOUR (review D1): every frame's SSIM on the U and the V plane — the // luma comparison and VMAF are blind to a hue shift or chroma-only noise. chromaU: Float32Array; chromaV: Float32Array; tiles: TileSummary[]; width: number; height: number; grid: number; // The source's picture detail per paired frame (review G2): the mean of a // Sobel edge map of the source frame, grey, at the comparison's size. sourceDetail?: Float32Array; }; function ssimScores(text: string, plane = "All"): number[] { const out: number[] = []; // An SSIM may be NEGATIVE (an inverted plane): a pattern without the sign // drops that frame's line, and the planes' counts then disagree. const re = new RegExp(`\\b${plane}:(-?[0-9.]+|inf)`); for (const l of text.split("\n")) { const m = re.exec(l); if (m) out.push(m[1] === "inf" ? 1 : Number(m[1])); } return out; } export async function compareWholeFile( paths: GatedPaths, opts: { compacted: string; source: string; scratchDir: string; // The copy's frame rate when it was capped, the source's rate, its size. fps: number | null; sourceFps: number | null; // The file's kept frames' `select` (keepSelect), in place of the // ratio's decimation. sourceSelect?: string; sourceWidth: number | null; sourceHeight: number | null; tileFloor: number; signal?: AbortSignal; }, ): Promise { const W = WHOLE_FILE_WIDTH; const aspect = opts.sourceWidth && opts.sourceHeight ? opts.sourceHeight / opts.sourceWidth : 9 / 16; const H = Math.max(2 * WHOLE_FILE_GRID, 2 * Math.round((W * aspect) / 2)); const G = WHOLE_FILE_GRID; const tw = Math.floor(W / G); const th = Math.floor(H / G); const T = G * G; const rate = opts.fps ?? opts.sourceFps ?? null; const n = renumber(rate); const esc = (f: string) => f.replace(/[:\\']/g, "\\$&"); const whole = path.join(opts.scratchDir, "wf-whole.log"); const detailLog = path.join(opts.scratchDir, "wf-detail.log"); const tileLog = (k: number) => path.join(opts.scratchDir, `wf-tile-${k}.log`); const labels = (p: string) => Array.from({ length: T + 1 }, (_, k) => `[${p}${k}]`).join(""); // The whole frame keeps its colour (yuv420p: the ssim filter's stats give // Y, U and V apart); the tiles are grey. const chains = [ `[0:v]${n},scale=${W}:${H}:flags=area,format=yuv420p,split=2[d0][dg]`, `[dg]format=gray,split=${T}${labels("d").replace("[d0]", "")}`, `[1:v]${opts.sourceSelect ? `select='${opts.sourceSelect}',` : decimateTo(opts.sourceFps, opts.fps)}${n},scale=${W}:${H}:flags=area,format=yuv420p,split=2[r0][rg]`, // …and one more: the SOURCE's own picture detail per frame (the mean of a // Sobel edge map, review G2), so a chunk drop at a join can be told from // a segment of harder picture starting there. `[rg]format=gray,split=${T + 1}${labels("r").replace("[r0]", "")}[rdet]`, `[rdet]sobel,signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=${esc(detailLog)},nullsink`, `[d0][r0]ssim=stats_file=${esc(whole)}:eof_action=endall[out]`, ]; for (let k = 0; k < T; k += 1) { const x = (k % G) * tw; const y = Math.floor(k / G) * th; const crop = `crop=${tw}:${th}:${x}:${y}`; chains.push(`[d${k + 1}]${crop}[dc${k}]`, `[r${k + 1}]${crop}[rc${k}]`, `[dc${k}][rc${k}]ssim=stats_file=${esc(tileLog(k))}:eof_action=endall,nullsink`); } const graphFile = path.join(opts.scratchDir, "wf-graph.txt"); await writeFile(graphFile, chains.join(";\n")); try { await runHeavyFfmpeg( paths, [ "-nostdin", "-hide_banner", "-loglevel", "error", "-i", opts.compacted, "-i", opts.source, // ffmpeg 7+: a "-/" option reads its value from the file. "-/filter_complex", graphFile, "-map", "[out]", "-f", "null", "-", ], { estimateMB: WHOLE_FILE_ESTIMATE_MB, ...(opts.signal ? { signal: opts.signal } : {}) }, ); const wholeText = await readFile(whole, "utf8"); const frames = Float32Array.from(ssimScores(wholeText, "Y")); const chromaU = Float32Array.from(ssimScores(wholeText, "U")); const chromaV = Float32Array.from(ssimScores(wholeText, "V")); const tiles: TileSummary[] = []; for (let k = 0; k < T; k += 1) { const sc = ssimScores(await readFile(tileLog(k), "utf8")); let min = 1; let minAt = 0; let run = 0; let runAt = 0; let longest = 0; let longestAt = 0; for (let i = 0; i < sc.length; i += 1) { if (sc[i] < min) { min = sc[i]; minAt = i; } if (sc[i] < opts.tileFloor) { if (run === 0) runAt = i; run += 1; if (run > longest) { longest = run; longestAt = runAt; } } else run = 0; } tiles.push({ index: k, col: k % G, row: Math.floor(k / G), min, minAt, longestBelow: longest, longestBelowAt: longestAt }); } const sourceDetail = Float32Array.from( [...(await readFile(detailLog, "utf8").catch(() => "")).matchAll(/lavfi\.signalstats\.YAVG=(-?[0-9.]+)/g)].map((m) => Number(m[1])), ); return { frames, chromaU, chromaV, tiles, width: W, height: H, grid: G, ...(sourceDetail.length === frames.length ? { sourceDetail } : {}) }; } finally { await rm(whole, { force: true }).catch(() => {}); await rm(detailLog, { force: true }).catch(() => {}); await rm(graphFile, { force: true }).catch(() => {}); for (let k = 0; k < T; k += 1) await rm(tileLog(k), { force: true }).catch(() => {}); } } // The whole-file verdict (pure, so the thresholds are tested on their own). export type WholeFileVerdict = { ok: boolean; why?: string; mean: number; // The ROBUST centre and spread (review D2): the median and 1.4826 × the // median absolute deviation — a few bad frames cannot widen their own floor. median: number; sd: number; min: number; minAt: number; // frame index relativeFloor: number; // THE LOCAL FLOOR (review E1): each frame against its own neighbourhood. // The worst margin (frame − its floor) and where; the window in frames. worstLocalMargin: number; worstLocalAt: number; windowFrames: number; // The file's recurring lower kind of picture, when it has one (review F-a), // and why a candidate was refused (review G1). lowerState: LowerState | null; lowerStateRefused?: string; // Every chunk against the others (review G2); null without chunk starts. chunks: ChunkVerdict | null; worstTile: TileSummary | null; chroma: { mean: number; min: number; minAt: number; plane: "U" | "V" }; }; function medianOf(a: Float32Array | number[]): number { const s = Float64Array.from(a).sort(); if (!s.length) return 0; const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; } // The floor of one stretch of frames: its median − max(k · robust spread, margin). function floorOf(f: Float32Array, k: number, margin: number): { median: number; sd: number; floor: number } { const r = robustSpread(f); return { ...r, floor: r.median - Math.max(k * r.sd, margin) }; } // EACH FRAME AGAINST ITS OWN NEIGHBOURHOOD: the half-window of frames just // before it and the half-window just after it (blocks of windowFrames / 2, // laid every windowFrames / 8), each with its own floor; a frame is judged // against the LOWER of the two. So a scene change into another kind of // picture (a webcam after a screen share) moves the floor with it — the frames // after the change fit their right-hand side — while a short defect inside a // steady stretch has the steady stretch on both sides and falls below. A file // shorter than the window is one neighbourhood: the whole file. // // FAST SWITCHING (review F-a): a half-window that is half screen share and half // webcam has a floor that flips with whichever is the majority (and, split // evenly, a median between the two and a floor far too low). So when the file // has a RECURRING LOWER KIND of picture (`lowerState`), a neighbourhood holding // at least LOWER_STATE_BLOCK_SHARE of its frames in that kind's runs takes its // floor from THOSE frames alone: the frames in the same state. A second's dip // inside a steady stretch is in no run and keeps the stretch's floor. export function localFloors(f: Float32Array, windowFrames: number, k: number, margin: number, lower?: LowerState | null): Float32Array { const out = new Float32Array(f.length); const half = Math.max(8, Math.floor(windowFrames / 2)); const lowCount = new Uint32Array(f.length + 1); for (let i = 0; i < f.length; i += 1) lowCount[i + 1] = lowCount[i] + (lower?.mask[i] ? 1 : 0); const blockFloor = (s: number, e: number) => { const block = f.subarray(s, e); if (!lower || lowCount[e] - lowCount[s] < LOWER_STATE_BLOCK_SHARE * (e - s)) return floorOf(block, k, margin).floor; return floorOf(block.filter((_, j) => lower.mask[s + j] === 1), k, margin).floor; }; if (f.length <= windowFrames) { out.fill(blockFloor(0, f.length)); return out; } const stride = Math.max(1, Math.floor(windowFrames / 8)); const starts: number[] = []; for (let s = 0; s + half <= f.length; s += stride) starts.push(s); if (starts[starts.length - 1] !== f.length - half) starts.push(f.length - half); const floors = starts.map((s) => blockFloor(s, s + half)); for (let i = 0; i < f.length; i += 1) { // Left: the last block ending at or before i; right: the first starting after i. let lo = 0; let hi = starts.length - 1; let left = -1; while (lo <= hi) { const mid = (lo + hi) >> 1; if (starts[mid] + half <= i) { left = mid; lo = mid + 1; } else hi = mid - 1; } lo = 0; hi = starts.length - 1; let right = -1; while (lo <= hi) { const mid = (lo + hi) >> 1; if (starts[mid] > i) { right = mid; hi = mid - 1; } else lo = mid + 1; } // At the file's ends one side is missing: the first frames have no block // ending before them, the last none starting after them. That side is then // the first (or last) block, which holds the frame — not nothing, or a // webcam closing the file's last minute is judged by the share before it. const a = floors[left >= 0 ? left : 0]; const b = floors[right >= 0 ? right : starts.length - 1]; out[i] = Math.min(a, b); } return out; } // A RECURRING LOWER KIND OF PICTURE (review F-a, bounded by review G1). Only // SCENE STRUCTURE qualifies: frames count only in RUNS of at least // `minRunFrames` below the split (longer than one 5 s GOP, with margin, so a // per-GOP or periodic fault of a few seconds never forms a state). The split is // Otsu's on the scores, taken twice: the second time without the frames of the // first split's short runs. The state then needs // - its runs' frames at least LOWER_STATE_FILE_SHARE of the file, and the // frames above the split at least as many; // - at least LOWER_STATE_MIN_RUNS separate runs; // - its frames' median below the upper frames' own floor (else the upper // floor already admits them); // - a run with an edge on a CHUNK JOIN (within CHUNK_EDGE_FRAMES of an // interior join) is a bad chunk's signature, not a scene's — a scene // change lands within two frames of a 10-minute join about 0.03% of the // time, and a bad chunk next to a real lower stretch merges with it at one // end only: such a run never counts, and when most runs are such, the // state is refused. // Its floor is its frames' median − max(k · their robust spread, margin). export type LowerState = { threshold: number; floor: number; share: number; runs: number; mask: Uint8Array }; export const LOWER_STATE_FILE_SHARE = 0.1; export const LOWER_STATE_BLOCK_SHARE = 0.2; export const LOWER_STATE_MIN_RUNS = 3; export const CHUNK_EDGE_FRAMES = 2; function otsuThreshold(values: Float32Array, minSide: number): number | null { const n = values.length; if (n < 2 * minSide || minSide < 1) return null; const s = Float64Array.from(values).sort(); const sum = new Float64Array(n + 1); for (let i = 0; i < n; i += 1) sum[i + 1] = sum[i] + s[i]; let best = -1; let at = minSide; for (let j = minSide; j <= n - minSide; j += 1) { const d = sum[j] / j - (sum[n] - sum[j]) / (n - j); const between = j * (n - j) * d * d; if (between > best) { best = between; at = j; } } return (s[at - 1] + s[at]) / 2; } // The runs of frames below `threshold`, [from, to). function runsBelow(f: Float32Array, threshold: number): [number, number][] { const out: [number, number][] = []; let start = -1; for (let i = 0; i <= f.length; i += 1) { const low = i < f.length && f[i] < threshold; if (low && start < 0) start = i; else if (!low && start >= 0) { out.push([start, i]); start = -1; } } return out; } export function lowerState( f: Float32Array, k: number, margin: number, o: { minRunFrames: number; chunkStarts?: number[] } = { minRunFrames: 1 }, ): { state: LowerState | null; refused?: string } { const n = f.length; const minSide = Math.ceil(LOWER_STATE_FILE_SHARE * n); if (n < 32) return { state: null }; const minRun = Math.max(1, Math.round(o.minRunFrames)); const long = (t: number) => runsBelow(f, t).filter(([a, b]) => b - a >= minRun); const t1 = otsuThreshold(f, minSide); if (t1 === null) return { state: null }; const keep1 = new Uint8Array(n).fill(1); for (const [a, b] of runsBelow(f, t1)) if (b - a < minRun) keep1.fill(0, a, b); const t = otsuThreshold(f.filter((_, i) => keep1[i] === 1), Math.min(minSide, Math.floor(n / 4))) ?? t1; const joins = new Set((o.chunkStarts ?? []).filter((x) => x > 0 && x < n)); const onJoin = (x: number) => { for (let d = -CHUNK_EDGE_FRAMES; d <= CHUNK_EDGE_FRAMES; d += 1) if (joins.has(x + d)) return true; return false; }; const all = long(t); const aligned = joins.size ? all.filter(([a, b]) => onJoin(a) || onJoin(b)) : []; const runs = all.filter((r) => !aligned.includes(r)); if (all.length && aligned.length * 2 > all.length) { return { state: null, refused: `${aligned.length} of its ${all.length} runs begin or end on a chunk join (a bad chunk's signature)` }; } const mask = new Uint8Array(n); let count = 0; for (const [a, b] of runs) { mask.fill(1, a, b); count += b - a; } const upper = f.filter((x) => x >= t); if (count < minSide || upper.length < minSide || runs.length < LOWER_STATE_MIN_RUNS) return { state: null }; const low = f.filter((_, i) => mask[i] === 1); if (medianOf(low) >= floorOf(upper, k, margin).floor) return { state: null }; return { state: { threshold: t, floor: floorOf(low, k, margin).floor, share: count / n, runs: runs.length, mask } }; } export function robustSpread(f: Float32Array): { median: number; sd: number } { const median = medianOf(f); const dev = new Float64Array(f.length); for (let i = 0; i < f.length; i += 1) dev[i] = Math.abs(f[i] - median); return { median, sd: 1.4826 * medianOf(Array.from(dev)) }; } export function judgeWholeFile( c: Pick & Partial>, t: { minFrame: number; meanFloor: number; sigmaK: number; sigmaMinMargin: number; tileRunFrames: number; expectedFrames: number; fps: number; chromaMinFrame: number; chromaMeanFloor: number; // The neighbourhood's length in frames (settings wholeFileWindowSeconds × fps). windowFrames?: number; // The shortest run below the split that counts toward a lower state, in // frames (wholeFileLowerRunSeconds × fps). Default: 8 s. lowerRunFrames?: number; // Each chunk's first frame in the copy (the first is 0). With them, the // lower state refuses runs on chunk joins and every chunk is compared with // the others (`chunks`). chunkStarts?: number[]; chunkSigmaK?: number; chunkMargin?: number; }, ): WholeFileVerdict { const f = c.frames; let sum = 0; let min = 1; let minAt = 0; for (let i = 0; i < f.length; i += 1) { sum += f[i]; if (f[i] < min) { min = f[i]; minAt = i; } } const mean = f.length ? sum / f.length : 0; const { median, sd } = robustSpread(f); const relativeFloor = median - Math.max(t.sigmaK * sd, t.sigmaMinMargin); const windowFrames = Math.max(16, Math.round(t.windowFrames ?? f.length)); const lowerResult = lowerState(f, t.sigmaK, t.sigmaMinMargin, { minRunFrames: t.lowerRunFrames ?? 8 * t.fps, chunkStarts: t.chunkStarts }); const lower = lowerResult.state; const local = localFloors(f, windowFrames, t.sigmaK, t.sigmaMinMargin, lower); let worstLocalMargin = Infinity; let worstLocalAt = 0; for (let i = 0; i < f.length; i += 1) { const m = f[i] - local[i]; if (m < worstLocalMargin) { worstLocalMargin = m; worstLocalAt = i; } } if (!f.length) worstLocalMargin = 0; let worstTile: TileSummary | null = null; for (const tile of c.tiles) { if (!worstTile || tile.longestBelow > worstTile.longestBelow || (tile.longestBelow === worstTile.longestBelow && tile.min < worstTile.min)) worstTile = tile; } // The colour planes: the lower of U and V, frame by frame. const u = c.chromaU ?? new Float32Array(); const v = c.chromaV ?? new Float32Array(); let cSum = 0; let cMin = 1; let cMinAt = 0; let cPlane: "U" | "V" = "U"; for (let i = 0; i < u.length; i += 1) { const x = Math.min(u[i], v[i] ?? 1); cSum += (u[i] + (v[i] ?? u[i])) / 2; if (x < cMin) { cMin = x; cMinAt = i; cPlane = u[i] <= (v[i] ?? 1) ? "U" : "V"; } } const chroma = { mean: u.length ? cSum / u.length : 0, min: cMin, minAt: cMinAt, plane: cPlane }; const at = (i: number) => `${(i / t.fps).toFixed(2)} s`; const chunks = t.chunkStarts && f.length === t.expectedFrames && u.length === f.length && v.length === f.length ? judgeChunks({ Y: f, U: u, V: v }, t.chunkStarts, lower, { sigmaK: t.chunkSigmaK ?? 4, margin: t.chunkMargin ?? 0.02, fps: t.fps }, c.sourceDetail) : null; const base = { mean, median, sd, min, minAt, relativeFloor, worstLocalMargin, worstLocalAt, windowFrames, lowerState: lower, ...(lowerResult.refused ? { lowerStateRefused: lowerResult.refused } : {}), worstTile, chroma, chunks, }; if (f.length !== t.expectedFrames || u.length !== t.expectedFrames || v.length !== t.expectedFrames) { return { ...base, ok: false, why: `the comparison saw ${f.length} of the copy's ${t.expectedFrames} frames (colour: ${u.length}): it ends early or skips` }; } if (min < t.minFrame) return { ...base, ok: false, why: `a frame at ${at(minAt)} scores ${min.toFixed(3)} (no frame may fall below ${t.minFrame})` }; if (mean < t.meanFloor) return { ...base, ok: false, why: `the mean is ${mean.toFixed(3)} (needs ${t.meanFloor})` }; if (worstLocalMargin < 0) { const i = worstLocalAt; return { ...base, ok: false, why: `a frame at ${at(i)} scores ${f[i].toFixed(4)}, below its neighbourhood's floor ${local[i].toFixed(4)} ` + `(the median − max(${t.sigmaK}·robust spread, ${t.sigmaMinMargin}) of the ${(windowFrames / 2 / t.fps).toFixed(0)} s on either side)`, }; } if (worstTile && worstTile.longestBelow > t.tileRunFrames) { return { ...base, ok: false, why: `tile ${worstTile.col},${worstTile.row} of the ${Math.sqrt(c.tiles.length)}×${Math.sqrt(c.tiles.length)} grid is below its floor for ` + `${worstTile.longestBelow} frames from ${at(worstTile.longestBelowAt)} (lowest ${worstTile.min.toFixed(3)}; more than ${t.tileRunFrames} fails)`, }; } if (cMin < t.chromaMinFrame) { return { ...base, ok: false, why: `the colour (${cPlane} plane) of a frame at ${at(cMinAt)} scores ${cMin.toFixed(3)} (no frame may fall below ${t.chromaMinFrame})` }; } if (chroma.mean < t.chromaMeanFloor) return { ...base, ok: false, why: `the colour's mean is ${chroma.mean.toFixed(3)} (needs ${t.chromaMeanFloor})` }; if (chunks && !chunks.ok) return { ...base, ok: false, why: chunks.why }; return { ...base, ok: true }; } // EVERY CHUNK AGAINST THE OTHERS (review G2). A stretch longer than the local // window is its own neighbourhood, so a whole chunk evenly worse (a bad encode // of one chunk) passed the frame floors. Each chunk's mean, on Y, U and V, is // held to the other chunks' median − max(sigmaK × their robust spread, margin). // A chunk below it fails UNLESS the source explains the drop: // - most of its frames are in the file's recurring lower kind of picture // (`lowerState`, whose runs on chunk joins never count) AND its mean // reaches what that mix predicts — its share of each kind times that // kind's median, less the margin — so a bad chunk flanked by the lower // kind on both sides is not explained by it; or // - neither of its joins shows the drop: the frames just inside the chunk // score within half the drop of the frames just outside. A bad chunk // changes level AT its joins; a harder scene that runs across chunks // (a game segment in a talk stream) changes level where the scene changes; // - or THE SOURCE ITSELF STEPS TO HARDER PICTURE at every join where the // copy drops (reviews G2, H2: a scheduled segment that starts right at a // join): its picture detail (`sourceDetail`) is SOURCE_CHANGE_SHARE or // more higher inside than outside, over the 5 s either side AND over the // whole chunk against the neighbouring one. A bad chunk of unchanged, // drifting or easier picture still fails. // One chunk: nothing to compare. Two: each against the other. export type ChunkVerdict = { ok: boolean; why?: string; count: number; sigmaK: number; margin: number; // The lowest chunk mean relative to its floor (not exempt), on any plane. worst: { index: number; plane: "Y" | "U" | "V"; mean: number; centre: number; floor: number; joinAt?: number } | null; exempt: { index: number; plane: "Y" | "U" | "V"; why: "lower state" | "no step at its joins" | "the source changes at its join" }[]; }; export const CHUNK_JOIN_SECONDS = 5; export const SOURCE_CHANGE_SHARE = 0.1; export function judgeChunks( planes: { Y: Float32Array; U: Float32Array; V: Float32Array }, chunkStarts: number[], lower: LowerState | null, o: { sigmaK: number; margin: number; fps: number }, sourceDetail?: Float32Array, ): ChunkVerdict { const n = planes.Y.length; const starts = [...new Set(chunkStarts.filter((x) => x >= 0 && x < n))].sort((a, b) => a - b); if (starts[0] !== 0) starts.unshift(0); const spans = starts.map((a, i) => [a, i + 1 < starts.length ? starts[i + 1] : n] as const); const out: ChunkVerdict = { ok: true, count: spans.length, sigmaK: o.sigmaK, margin: o.margin, worst: null, exempt: [] }; if (spans.length < 2) return out; const meanOf = (p: Float32Array, a: number, b: number) => { let x = 0; for (let i = a; i < b; i += 1) x += p[i]; return b > a ? x / (b - a) : 0; }; for (const plane of ["Y", "U", "V"] as const) { const p = planes[plane]; const means = spans.map(([a, b]) => meanOf(p, a, b)); // The two kinds' typical scores on this plane, when the file has a lower state. const lowMedian = lower ? medianOf(p.filter((_, i) => lower.mask[i] === 1)) : 0; const upMedian = lower ? medianOf(p.filter((_, i) => lower.mask[i] === 0)) : 0; spans.forEach(([a, b], ci) => { const others = Float32Array.from(means.filter((_, j) => j !== ci)); const r = robustSpread(others); const floor = r.median - Math.max(o.sigmaK * r.sd, o.margin); const gap = means[ci] - floor; if (gap >= 0) return; let lowFrames = 0; if (lower) for (let i = a; i < b; i += 1) lowFrames += lower.mask[i]; const m = lowFrames / (b - a); if (lower && m >= 0.5 && means[ci] >= m * lowMedian + (1 - m) * upMedian - o.margin) { out.exempt.push({ index: ci, plane, why: "lower state" }); return; } const drop = r.median - means[ci]; const w = Math.max(1, Math.min(Math.round(CHUNK_JOIN_SECONDS * o.fps), Math.floor((b - a) / 4))); const windows = (join: number): [[number, number], [number, number]] => join === a ? [[a, Math.min(b, a + w)], [Math.max(0, a - w), a]] : [[Math.max(a, b - w), b], [b, Math.min(n, b + w)]]; const stepAt = (join: number) => { const [inside, outside] = windows(join); return meanOf(p, outside[0], outside[1]) - meanOf(p, inside[0], inside[1]) >= drop / 2; }; // The source EXPLAINS the drop at a join (review H2) only by a step to // HARDER picture (more detail inside the chunk), both sharp at the join // (the 5 s either side) and SUSTAINED (the chunk's mean detail against // the neighbouring chunk's, across that join). A drift, a step the other // way, or noise over a flat picture explains nothing. const sourceChangesAt = (join: number) => { if (!sourceDetail || sourceDetail.length !== n) return false; const [inside, outside] = windows(join); const harder = (x: number, y: number) => x - y >= SOURCE_CHANGE_SHARE * Math.max(1e-6, y) && x > 1e-6; if (!harder(meanOf(sourceDetail, inside[0], inside[1]), meanOf(sourceDetail, outside[0], outside[1]))) return false; const nb = join === a ? spans[ci - 1] : spans[ci + 1]; return !!nb && harder(meanOf(sourceDetail, a, b), meanOf(sourceDetail, nb[0], nb[1])); }; const stepping = [...(ci > 0 && stepAt(a) ? [a] : []), ...(ci < spans.length - 1 && stepAt(b) ? [b] : [])]; if (!stepping.length) { out.exempt.push({ index: ci, plane, why: "no step at its joins" }); return; } if (stepping.every(sourceChangesAt)) { out.exempt.push({ index: ci, plane, why: "the source changes at its join" }); return; } if (!out.worst || gap < out.worst.mean - out.worst.floor) { out.worst = { index: ci, plane, mean: means[ci], centre: r.median, floor, joinAt: stepping[0] }; } }); } if (out.worst) { const wst = out.worst; const [a, b] = spans[wst.index]; out.ok = false; out.why = `chunk ${wst.index + 1} of ${spans.length} (${(a / o.fps).toFixed(1)}–${(b / o.fps).toFixed(1)} s) scores ${wst.mean.toFixed(4)} on ${wst.plane}, ` + `below the other chunks' floor ${wst.floor.toFixed(4)} (their median ${wst.centre.toFixed(4)} − max(${o.sigmaK}·robust spread, ${o.margin})), ` + `and the drop begins or ends at its chunk join at ${((wst.joinAt ?? a) / o.fps).toFixed(1)} s${sourceDetail ? ", where the source's own picture does not change" : ""}. ` + "It may still be a segment of harder picture starting exactly at that join: look at the source there; a run with another " + "chunkMinutes puts the joins elsewhere (it encodes again)"; } return out; }