Archilyzer · Source

archilyzer

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

commit c0c08ee4aee3cd7d0546e621fecaa2bab0350af9
parent c2761b3b1d73fc55bbddab48bfdb46e54332a7e8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 22 Nov 2026 04:30:22 -0500

record-live: REVIEW-6 1-3: the real fatal line is read, no fragment past the state meets a resume, a short or torn track is never "verified"

- 1: the recorder's reader cuts lines on "\n" across chunks, then on "\r".
  A bare ERROR:/WARNING: segment is joined to the next, so yt-dlp's
  `ERROR: \r[download] Got error: … Giving up after N retries` is ONE line;
  a self-rewriting "\r" line is still read as it comes.
  isFragmentFatalLine matches it, "Giving up after N retries" and
  "fragment N not found, unable to continue", never a retry.
  Tests drive the real bytes, in two chunks, through spawnRecorder, and a
  whole run where only that line can stop the recorder.
- 2: before every resume, each stream's kept fragments past its state go.
  Measured against a local Range server: a complete one gives 416 and
  exit 3 under --abort-on-unavailable-fragments, and a silent skip under
  yt-dlp's default; without it the result is byte-identical to a straight
  download. The fake now refuses such a resume as measured.
- 3: the verifier fails when the two tracks' spans differ by more than
  max(2 s, 2 fragments). Before any fragment goes, each stream file must
  be byte for byte its kept fragments 1..N. The editor's own merge fails
  on any line ffmpeg writes at -loglevel error. Tests: a torn raw track
  and a track that stopped early, both on real ffmpeg files.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/recordLive.test.ts | 106++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/recordLive.ts | 105++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/liveFragments-server.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/liveVerify-server.test.ts | 28+++++++++++++++++++++++++++-
Mcommon/lib/liveVerify-server.ts | 21+++++++++++++++++++--
5 files changed, 288 insertions(+), 17 deletions(-)

diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -2843,6 +2843,16 @@ function resumableYtdlp( if (!st && ((await stat(files.video).catch(() => null))?.size ?? 0) > 0 && resumedFrom === null && count.video === 0 && (await stat(`${files.video}-Frag1`).catch(() => null))) { return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 416: Range Not Satisfiable. Giving up after 10 retries\n", signalled: false }; } + // REVIEW-6 2, measured against a Range server: a COMPLETE kept fragment + // just past the state is asked for by Range past its end — 416, exit 3, + // nothing recorded. (A partial one is resumed by Range.) + for (const kind of ["video", "audio"] as const) { + const next = `${files[kind]}-Frag${count[kind] + 1}`; + const have = await readFile(next, "utf8").catch(() => null); + if (st && have !== null && have === fragOf(kind, count[kind] + 1)) { + return { exitCode: 3, stderrTail: "ERROR: \r[download] Got error: HTTP Error 416: Range Not Satisfiable. Giving up after 10 retries\n", signalled: false }; + } + } } const what = await script({ n, resumedFrom, write, writeStream, tear, print: (l) => onLine?.(l), signal, args }); if (what === "die") return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; @@ -4110,7 +4120,8 @@ test("DESIGN-4 3: a fragment that cannot be fetched stops the recorder (SIGTERM) const id = "exmpld4abt1"; let live = true; const reasons: unknown[] = []; - const GOT = "1: ERROR: [download] Got error: HTTP Error 404: Not Found"; + // (As the recorder reads yt-dlp's `ERROR: \\r[download] …` line: REVIEW-6 1.) + const GOT = "ERROR: [download] Got error: HTTP Error 404: Not Found. Giving up after 10 retries"; const { run, calls, waits, log } = await incidentRun( id, resumableYtdlp(async ({ write, print, signal, args }) => { @@ -4432,8 +4443,8 @@ test("DESIGN-5 (c): fragments answered 403 while recording, then a read says pri id, resumableYtdlp(async ({ write, print, signal }) => { await write(3000); - for (let k = 1; k <= 3; k++) print(`1: [download] Got error: HTTP Error 403: Forbidden. Retrying fragment 52 (${k}/10)...`); - print("1: ERROR: [download] Got error: HTTP Error 403: Forbidden"); + for (let k = 1; k <= 3; k++) print(`[download] Got error: HTTP Error 403: Forbidden. Retrying fragment 52 (${k}/10)...`); + print("ERROR: [download] Got error: HTTP Error 403: Forbidden. Giving up after 10 retries"); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), @@ -4452,3 +4463,92 @@ test("DESIGN-5 (c): fragments answered 403 while recording, then a read says pri const files = await left(id); assert.ok(files.some((n) => n.endsWith(`.${FAKE_V}`)) && files.some((n) => n.endsWith(`.${FAKE_V}-Frag51`)), `nothing on disk removed: ${files.length} files`); }); + +// --- REVIEW-6: the real yt-dlp bytes, the repair's leftover fragment, the verifier's two holes --------- + +// yt-dlp's fatal fragment line, as its bytes are (measured in exp4/r5, r7b): +// `ERROR: ` then "\r", then the line — here split across two writes. +const FATAL_CHUNKS = ["[download] 12.0% of ~ 1.20GiB at 2.00MiB/s (frag 51/2000)\nERROR: \r[download] Got er", "ror: HTTP Error 404: Not Found. Giving up after 10 retries\n"]; +const fatalScript = `process.stderr.write(${JSON.stringify(FATAL_CHUNKS[0])}); setTimeout(() => process.stderr.write(${JSON.stringify(FATAL_CHUNKS[1])}), 150); setInterval(() => {}, 1000);`; + +test("REVIEW-6 1: through the real recorder reader, yt-dlp's `ERROR: \\r[download] Got error … Giving up` arriving in two chunks is ONE line, and it is a fragment's final failure", async () => { + const { isFragmentFatalLine } = await import("./recordLive"); + const ac = new AbortController(); + const lines: string[] = []; + const p = spawnRecorder({ bin: process.execPath, args: ["-e", fatalScript], cwd: ROOT, onLog: () => {}, signal: ac.signal, label: "t", onLine: (l) => void lines.push(l) }); + const by = Date.now() + 20_000; + while (!lines.some((l) => /Giving up/.test(l))) { + assert.ok(Date.now() < by, `no whole line: ${JSON.stringify(lines)}`); + await new Promise((r) => setTimeout(r, 20)); + } + ac.abort("SIGTERM"); + await p; + const fatal = lines.find((l) => /Giving up/.test(l))!; + assert.equal(fatal, "ERROR: [download] Got error: HTTP Error 404: Not Found. Giving up after 10 retries"); + assert.equal(isFragmentFatalLine(fatal), true); + assert.equal(isFragmentFatalLine("[download] Got error: HTTP Error 404: Not Found. Retrying fragment 52 (3/10)..."), false, "a retry is not the end"); + assert.ok(!lines.includes("ERROR:"), "no bare ERROR: line"); +}); + +test("REVIEW-6 1: a self-rewriting line (\\r, no \\n — ffmpeg's frame=) is read as it comes, not held until a newline", async () => { + const ac = new AbortController(); + const lines: string[] = []; + const script = `let i = 0; const t = setInterval(() => { process.stderr.write("frame=" + (++i) + "\\r"); }, 20);`; + const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: () => {}, signal: ac.signal, label: "t", onLine: (l) => void lines.push(l) }); + const by = Date.now() + 20_000; + while (lines.filter((l) => /^frame=/.test(l)).length < 3) { + assert.ok(Date.now() < by, "the \\r segments never came"); + await new Promise((r) => setTimeout(r, 20)); + } + ac.abort(); + await p; +}); + +test("REVIEW-6 1: the real fatal bytes through spawnRecorder STOP the recorder at once (SIGTERM, its state kept) and the resume waits 20 s — not the stall watchdog 10 minutes later", { timeout: 40_000 }, async () => { + const id = "exmplr6fat1"; + let live = true; + const { run, calls, waits, log } = await incidentRun( + id, + resumableYtdlp(async ({ n, write, print, signal }) => { + if (n === 1) { + await write(3000); + // The other stream's thread goes on: the process does not exit. + const o = await spawnRecorder({ bin: process.execPath, args: ["-e", fatalScript], cwd: ROOT, onLog: () => {}, signal, label: "real", onLine: print }); + return { exitCode: o.exitCode, stderrTail: o.stderrTail, signalled: o.signalled }; + } + await write(7200); + live = false; + return "end"; + }), + // (No stall watch in the way: only the line can stop it.) + { deps: { ...FAST_WATCH, stallMs: 600_000, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + assert.equal((await run).status, "landed"); + assert.ok(log.some((l) => /a fragment could not be fetched/.test(l)), "the stop is said"); + assert.ok(waits.includes(20_000), `the first wait before a resume: ${waits.join(", ")}`); + assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place"); +}); + +test("REVIEW-6 3: before any fragment goes, each stream file must be byte for byte its kept fragments — one that is not fails the check and NOTHING is removed", { timeout: 60_000 }, async () => { + const id = "exmplr6eq01"; + let live = true; + const { run } = await incidentRun( + id, + resumableYtdlp(async ({ write, args }) => { + await write(7200); + // A kept fragment that is not what the stream file holds there. + const f = `${outOf(args)}.${FAKE_V}-Frag10`; + const b = await readFile(f, "utf8"); + await writeFile(f, b.replace("#10;", "#99;")); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + assert.equal((await run).status, "landed"); + const row = (await rowOf(id))[0]!; + assert.equal(row.verification?.state, "failed"); + assert.match(row.verification?.why ?? "", /not fragment 10/); + assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files are kept"); + assert.equal(row.needsAttention, true); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -55,6 +55,7 @@ import { spawn } from "node:child_process"; import { createWriteStream } from "node:fs"; import { mkdir, open, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises"; import { uptime } from "node:os"; +import { StringDecoder } from "node:string_decoder"; import { execa } from "execa"; import type { ChannelConfig } from "../lib/channelConfig"; import { assertChannelTextReadable } from "../lib/channelMedia"; @@ -113,7 +114,7 @@ import { import { WHISPER_FILENAME } from "../lib/videoStatus"; import { parseTranscriptJson } from "../lib/whisper"; import { readStoredText } from "../lib/storedText-server"; -import { accountStream, dropFragments, fragmentGaps, fragNumbers, readYtdlIndex, reconcileStream } from "../lib/liveFragments-server"; +import { dropFragments, dropFragmentsAbove, fragmentGaps, fragNumbers, readYtdlIndex, reconcileStream, streamEqualsFragments } from "../lib/liveFragments-server"; import { verifyMerged, verifyScan } from "../lib/liveVerify-server"; import { liveJoinsSidecar, liveRecordingSidecar } from "../lib/mediaImport-server"; import { ffmpegJoinDeps, joinLiveParts, type JoinDeps } from "./liveJoin"; @@ -395,6 +396,15 @@ export type RecorderSpawn = (opts: { const PROGRESS_RE = /^(?:\d+:\s*)?(?:frame=|size=|\[download\]\s+(?:\d|Destination:)?)|time=\d\d:\d\d:\d\d/; const PROGRESS_EVERY_MS = 5 * 60_000; +// REVIEW-6 1: a fragment's FINAL failure as yt-dlp prints it — the error +// line (`ERROR: \r[download] Got error: …`, joined by the recorder's reader), +// a "Giving up after N retries" on a fragment, or "fragment N not found, +// unable to continue". Never a retry ("Retrying fragment N (k/10)"). +export function isFragmentFatalLine(l: string): boolean { + if (/Retrying fragment/i.test(l)) return false; + return /^(?:\d+:\s*)?ERROR: \[download\] Got error|Got error: .*Giving up after \d+ retries|fragment \d+ not found, unable to continue/i.test(l); +} + // Never thinned (DESIGN-4 3): what says a fragment is missing, failed, or the // state is not trusted — each such line is in the job's log. const NEVER_THINNED_RE = /Skipping fragment|Got error|fragment \d+ not found|\.ytdl file is corrupt|Inconsistent state|Unable to resume/i; @@ -475,18 +485,60 @@ export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, la let lastProgress = 0; let signalled = false; let killTimer: NodeJS.Timeout | null = null; + // REVIEW-6 1: lines are cut on "\n" ACROSS chunks (a line may arrive in + // two), then on "\r" (a progress line rewrites itself). yt-dlp prints an + // error as `ERROR: \r[download] Got error: …`: a bare `ERROR:` (or + // `WARNING:`) segment is joined to the segment after it, so the line read + // is the one yt-dlp meant. + const pend = { out: "", err: "" }; + const decoders = { out: new StringDecoder("utf8"), err: new StringDecoder("utf8") }; + const segmentsOf = (line: string): string[] => { + const segs = line.split("\r").map((x) => x.trim()).filter(Boolean); + const out: string[] = []; + for (let i = 0; i < segs.length; i++) { + if (/^(?:\d+:\s*)?(?:ERROR|WARNING):$/.test(segs[i]!) && i + 1 < segs.length) { + out.push(`${segs[i]} ${segs[i + 1]}`); + i++; + } else out.push(segs[i]!); + } + return out; + }; + const feedText = (text: string, isErr: boolean, flush = false) => { + const key = isErr ? "err" : "out"; + const all = pend[key] + text; + const lines = all.split("\n"); + let rest = flush ? "" : lines.pop()!; + for (const line of lines) for (const l of segmentsOf(line)) emit(l); + // A line that only ever rewrites itself (ffmpeg's `frame=` with "\r" + // and no "\n"): its finished segments are read now; the last one, and + // a bare `ERROR:` waiting for what follows it, stay pending. + const cut = rest.lastIndexOf("\r"); + if (cut >= 0) { + let done = rest.slice(0, cut); + let keep = rest.slice(cut + 1); + const lastSeg = done.slice(done.lastIndexOf("\r") + 1); + if (/^\s*(?:\d+:\s*)?(?:ERROR|WARNING):\s*$/.test(lastSeg)) { + done = done.slice(0, done.length - lastSeg.length); + keep = `${lastSeg}\r${keep}`; + } + for (const l of segmentsOf(done)) emit(l); + rest = keep; + } + pend[key] = rest.slice(-64 * 1024); + }; const feed = (chunk: Buffer, isErr: boolean) => { - const text = chunk.toString("utf8"); + const text = decoders[isErr ? "err" : "out"].write(chunk); if (isErr) tail = (tail + text).slice(-32 * 1024); - for (const line of text.split(/[\r\n]+/)) { - const l = line.trim(); - if (!l) continue; + feedText(text, isErr); + }; + const emit = (l: string) => { + { onLine?.(l); if (isProgressLine(l)) sinceProgress = ""; else sinceProgress = (sinceProgress + l + "\n").slice(-8 * 1024); if (isProgressLine(l)) { const now = Date.now(); - if (now - lastProgress < PROGRESS_EVERY_MS) continue; + if (now - lastProgress < PROGRESS_EVERY_MS) return; lastProgress = now; } onLog(`[${label}] ${l}\n`); @@ -517,7 +569,12 @@ export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, la signal.removeEventListener("abort", onAbort); resolve({ exitCode: code, stderrTail: tail, signalled, exitTail: sinceProgress }); }; - child.on("close", (code) => finish(code)); + child.on("close", (code) => { + // What is left without a final newline. + feedText(decoders.out.end(), false, true); + feedText(decoders.err.end(), true, true); + finish(code); + }); child.on("exit", (code) => { // Its output drains on `close`; a grandchild that keeps the pipes open // after yt-dlp is gone is killed with the group, and the recorder returns. @@ -845,12 +902,22 @@ async function defaultKickVod( // ffmpeg through the heavy slot when the checkout has the gate (a stream copy // of hours of video, as the landing's remux is). -export async function runFfmpegHeavy(paths: Paths, args: string[], signal?: AbortSignal): Promise<void> { +// `strict`: any line ffmpeg writes (it runs at -loglevel error) is a failure — +// the editor's own merge of a recording's streams (REVIEW-6 3); the heavy +// slot's own waiting lines are not ffmpeg's. +export async function runFfmpegHeavy(paths: Paths, args: string[], signal?: AbortSignal, o: { strict?: boolean } = {}): Promise<void> { const gate = paths.monorepoRoot ? path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs") : null; const gated = gate !== null && (await stat(gate).then((s) => s.isFile(), () => false)); - await execa(gated ? process.execPath : paths.ffmpegBin, gated ? [gate, "--heavy", "--", paths.ffmpegBin, ...args] : args, { + const r = await execa(gated ? process.execPath : paths.ffmpegBin, gated ? [gate, "--heavy", "--", paths.ffmpegBin, ...args] : args, { ...(signal ? { cancelSignal: signal } : {}), }); + if (o.strict) { + const said = String(r.stderr ?? "") + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => l && !/^(?:queue-lock|heavy)[:\s]/i.test(l)); + if (said.length) throw new Error(`ffmpeg's merge reported: ${said.slice(0, 3).join(" | ").slice(0, 400)}`); + } } export type ResolvedPart = { file: string; seconds: number | null; merged?: boolean } | { error: string }; @@ -1713,7 +1780,7 @@ async function recordLiveRunInner( } } if (/HTTP Error 403: Forbidden/i.test(l) && /fragment/i.test(l)) part.fragment403 = (part.fragment403 ?? 0) + 1; - if (/^(?:\d+:\s*)?ERROR: \[download\] Got error|fragment \d+ not found, unable to continue/i.test(l)) { + if (isFragmentFatalLine(l)) { part.fragmentErrors = (part.fragmentErrors ?? 0) + 1; if (!fragAbort && !own.signal.aborted) { const m = /fragment (\d+)/i.exec(l); @@ -1911,6 +1978,11 @@ async function recordLiveRunInner( for (const f of g?.streams ?? []) { const r = await reconcileStream(slugStore, f, true, say); if (!r.ok) return { ok: false, why: r.why }; + // REVIEW-6 2: no kept fragment past the index may meet the resume. + const idx = await readYtdlIndex(path.join(slugStore, f)); + if (typeof idx !== "number") return { ok: false, why: `${f}.ytdl does not read` }; + const gone = await dropFragmentsAbove(slugStore, f, idx); + if (gone.length) say(`${f}: fragment(s) ${gone.join(", ")} past its state (${idx}) removed before the resume (a complete one would be refused, 416, and the resume would record nothing).`); } return { ok: true }; }; @@ -2972,7 +3044,7 @@ async function recordLiveRunInner( // as private or removed confirmed by the second read. const lsEnd = typeof endMeta?.live_status === "string" ? endMeta.live_status : null; const stillLive = !endedByRefusal && !(lsEnd === "was_live" || lsEnd === "post_live" || lsEnd === "not_live"); - const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s)); + const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s, { strict: true })); const at = (n: string) => path.join(slugStore, n); // Every part on disk now — this run's and an earlier run's — by its stem. // WHAT THE STORE HOLDS for this id, failing CLOSED: a pointer that does not @@ -3613,6 +3685,17 @@ async function recordLiveRunInner( } catch (err) { verdict = { ok: false, why: (err as Error).message }; } + // REVIEW-6 3: before any fragment goes, each stream file is exactly its + // kept fragments 1..N, byte for byte (they may be the only whole copy). + if (verdict.ok) { + for (const f of mergedFrom) { + const eq = await streamEqualsFragments(slugStore, f).catch((e: Error) => ({ ok: false as const, why: e.message })); + if (eq && !eq.ok) { + verdict = { ok: false, why: eq.why }; + break; + } + } + } const keptBefore = kept.length; if (verdict.ok) { record.verification = { ...record.verification!, state: "verified", at: now().toISOString() }; diff --git a/common/lib/liveFragments-server.ts b/common/lib/liveFragments-server.ts @@ -184,6 +184,51 @@ export async function dropFragments(dir: string, name: string): Promise<number> return n; } +// REVIEW-6 2: BEFORE EVERY RESUME, every kept fragment past the state's +// index goes. Under --no-part a complete `-Frag<index+1>` gets a Range request +// past its end on the resume: 416, "Giving up", exit 3, nothing recorded +// (measured, LOG REVIEW-6). A partial one would be resumed by Range — it goes +// too; it costs a re-download, the whole one costs the resume. +export async function dropFragmentsAbove(dir: string, name: string, index: number): Promise<number[]> { + const names = await readdir(dir).catch(() => [] as string[]); + const gone: number[] = []; + for (const k of fragNumbers(name, names)) { + if (k <= index) continue; + await rm(path.join(dir, `${name}-Frag${k}`), { force: true }); + gone.push(k); + } + return gone; +} + +// REVIEW-6 3: does the stream file hold exactly its kept fragments 1..N, in +// order, every one non-empty? (Before the fragments are removed: they may be +// the only whole copy.) null: no fragments kept to compare with. +export async function streamEqualsFragments(dir: string, name: string): Promise<{ ok: true; fragments: number } | { ok: false; why: string } | null> { + const names = await readdir(dir).catch(() => [] as string[]); + const kept = fragNumbers(name, names); + if (!kept.length) return null; + if (kept[0] !== 1 || kept[kept.length - 1] !== kept.length) return { ok: false, why: `${name}: its kept fragments are not 1..${kept.length} without a gap` }; + const file = path.join(dir, name); + const size = (await stat(file).catch(() => null))?.size ?? 0; + let off = 0; + const fh = await open(file, "r").catch(() => null); + if (!fh) return { ok: false, why: `${name} does not open` }; + try { + for (const n of kept) { + const frag = await readFile(path.join(dir, `${name}-Frag${n}`)); + if (!frag.length) return { ok: false, why: `${name}: fragment ${n} is empty` }; + const here = Buffer.alloc(frag.length); + const { bytesRead } = await fh.read(here, 0, frag.length, off); + if (bytesRead !== frag.length || !here.equals(frag)) return { ok: false, why: `${name}: its bytes at ${off} are not fragment ${n}` }; + off += frag.length; + } + } finally { + await fh.close(); + } + if (off !== size) return { ok: false, why: `${name} is ${size} bytes, its ${kept.length} fragments ${off}` }; + return { ok: true, fragments: kept.length }; +} + // Fragment numbers missing between kept ones (a skip leaves no Frag file). export function fragmentGaps(kept: readonly number[], from: number): number[] { const out: number[] = []; diff --git a/common/lib/liveVerify-server.test.ts b/common/lib/liveVerify-server.test.ts @@ -65,7 +65,7 @@ test("a merged file that lost packets of a stream file (a merge cut short) is no const m = await merge(vShort, a, path.join(ROOT, "m2.mp4")); const r = await verifyMerged(FFPROBE, m, [v, a]); assert.equal(r.ok, false); - assert.match((r as { why: string }).why, /packets merged/); + assert.match((r as { why: string }).why, /packets merged|stopped short/); }); test("a file that does not read is not whole", async () => { @@ -99,3 +99,29 @@ test("WebM stream files as yt-dlp appends them (Matroska clusters of unknown len const r = await verifyMerged(FFPROBE, m, [v, a]); assert.equal(r.ok, true, JSON.stringify(r)); }); + +// REVIEW-6 3: the two cases the packet comparison alone passed. +test("a TORN raw video track (a fragment cut, later ones appended): raw and merged agree, but the picture stops where the tear is — not whole", async () => { + const parts = [await readFile(path.join(ROOT, "init-0.m4s"))]; + const names = await segs(0); + for (const [i, n] of names.entries()) { + const b = await readFile(path.join(ROOT, n)); + parts.push(i === 6 ? b.subarray(0, Math.floor(b.length * 0.6)) : b); + } + const v = path.join(ROOT, "vt.mp4"); + await writeFile(v, Buffer.concat(parts)); + const a = await streamFile(1, path.join(ROOT, "at.m4a")); + const m = await merge(v, a, path.join(ROOT, "mt.mp4")); + const r = await verifyMerged(FFPROBE, m, [v, a]); + assert.equal(r.ok, false, JSON.stringify(r)); + assert.match((r as { why: string }).why, /stopped short|hole/); +}); + +test("a video track that STOPPED EARLY (its thread ended, the sound went on): not whole", async () => { + const v = await streamFile(0, path.join(ROOT, "vs.mp4"), [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]); + const a = await streamFile(1, path.join(ROOT, "as.m4a")); + const m = await merge(v, a, path.join(ROOT, "ms.mp4")); + const r = await verifyMerged(FFPROBE, m, [v, a]); + assert.equal(r.ok, false, JSON.stringify(r)); + assert.match((r as { why: string }).why, /stopped short/); +}); diff --git a/common/lib/liveVerify-server.ts b/common/lib/liveVerify-server.ts @@ -104,25 +104,42 @@ const holeOf = (t: TrackScan): string | null => { return null; }; +// REVIEW-6 3: the picture and the sound of one recording end together. A +// track torn or stopped early reads, raw and merged alike, only up to where +// it stopped (ffprobe stops where the merge did), so the packets agree; the +// OTHER track does not. Apart by more than max(2 s, 2 fragments): not whole. +export const TRACK_SPAN_MIN_TOLERANCE_SECONDS = 2; +const tracksApart = (tracks: TrackScan[], fragmentSeconds: number): string | null => { + const v = tracks.find((t) => t.kind === "video"); + const a = tracks.find((t) => t.kind === "audio"); + if (!v || !a) return null; + const tol = Math.max(TRACK_SPAN_MIN_TOLERANCE_SECONDS, 2 * fragmentSeconds); + return Math.abs(v.span - a.span) > tol ? `its video holds ${v.span.toFixed(1)} s and its audio ${a.span.toFixed(1)} s (more than ${tol} s apart): one track stopped short` : null; +}; + // One file alone (a muxed recording): the scan. -export async function verifyScan(ffprobeBin: string, file: string, signal?: AbortSignal): Promise<Verdict> { +export async function verifyScan(ffprobeBin: string, file: string, signal?: AbortSignal, o: { fragmentSeconds?: number } = {}): Promise<Verdict> { const s = await scanMediaFile(ffprobeBin, file, signal); if ("error" in s) return { ok: false, why: `it does not read (${s.error})` }; for (const t of s.tracks) { const h = holeOf(t); if (h) return { ok: false, why: h }; } + const apart = tracksApart(s.tracks, o.fragmentSeconds ?? 0); + if (apart) return { ok: false, why: apart }; return { ok: true, tracks: s.tracks }; } // A merged file against the stream files it was made from. -export async function verifyMerged(ffprobeBin: string, merged: string, streams: readonly string[], signal?: AbortSignal): Promise<Verdict> { +export async function verifyMerged(ffprobeBin: string, merged: string, streams: readonly string[], signal?: AbortSignal, o: { fragmentSeconds?: number } = {}): Promise<Verdict> { const m = await scanMediaFile(ffprobeBin, merged, signal); if ("error" in m) return { ok: false, why: `the merged file does not read (${m.error})` }; for (const t of m.tracks) { const h = holeOf(t); if (h) return { ok: false, why: `the merged file has ${h}` }; } + const apart = tracksApart(m.tracks, o.fragmentSeconds ?? 0); + if (apart) return { ok: false, why: `the merged file: ${apart}` }; for (const f of streams) { const s = await scanMediaFile(ffprobeBin, f, signal); if ("error" in s) return { ok: false, why: `${f.split("/").pop()} does not read (${s.error})` };