Archilyzer · Source

archilyzer

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

commit a6c5d7ffbd78e5eed5825310f894d0da1eda7581
parent db66f1196dbb1398d7d6b8e6c71ae8bd794b1e67
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 16:33:53 -0500

liveJoin: the proof checks the picture, a late cut is a hole, and scratch goes however it ends

REVIEW-1 of live-guard-2, 1.5 and 1.6:

- Beside the sound, the joined file's PICTURE is compared with its
  segments' (a 32x18 grey frame, mean difference at most 12 of 255: a
  re-mux or a frame off matches, another moment does not) 10 s either
  side of every join, at the head and at the tail; no picture decoded is
  a failure. The sound is now checked at the tail too.
- A cut whose stream copy starts more than 0.25 s after the point asked
  leaves seconds in neither part and refuses the join; one that starts
  more than 30 s before it is no keyframe snap and refuses it too. Each
  overlap records where the cut was asked (cutAt) and where the copy
  really starts (cutFrom); duplicatedSeconds is their difference.
- Every scratch file is removed in a finally, also when ffmpeg, the
  decode or the probe throws; why a join stopped is carried to the log.

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

Diffstat:
Mcommon/controller/liveJoin.ts | 103++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/controller/recordLive.test.ts | 66+++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/liveCapture.ts | 5+++++
3 files changed, 157 insertions(+), 17 deletions(-)

diff --git a/common/controller/liveJoin.ts b/common/controller/liveJoin.ts @@ -55,6 +55,15 @@ export const JOIN_MIN_GAIN_S = 30; export const JOIN_MAX_PARTS = 4; // A part shorter than this is never joined (the checks need its sound). export const JOIN_MIN_PART_S = 60; +// A cut whose stream copy starts this much after the point asked leaves a hole; +// one that starts more than JOIN_MAX_EARLY_CUT_S before it is not a keyframe +// snap (REVIEW-1 1.5 of live-guard-2). +export const JOIN_CUT_LATE_TOLERANCE_S = 0.25; +export const JOIN_MAX_EARLY_CUT_S = 30; +// Two frames (32x18 grey) are the same picture when they differ by at most +// this on average (0-255): a re-mux decodes the same frame, a frame or two off +// still matches, another moment does not. +export const JOIN_FRAME_MAX_DIFF = 12; export type JoinStreams = { seconds: number | null; @@ -75,8 +84,18 @@ export type JoinDeps = { // The files one after the other, stream-copied into `out`. concat: (files: string[], out: string) => Promise<void>; probe: (file: string) => Promise<JoinStreams | null>; + // A small grey frame of the picture at `at` seconds (null: no picture + // decoded there). + frame: (file: string, at: number) => Promise<Uint8Array | null>; }; +export function frameDiff(a: Uint8Array, b: Uint8Array): number { + if (a.length !== b.length || a.length === 0) return Infinity; + let d = 0; + for (let i = 0; i < a.length; i++) d += Math.abs(a[i]! - b[i]!); + return d / a.length; +} + export type JoinPart = { stem: string; file: string; @@ -112,14 +131,28 @@ function matchAt( const r3 = (x: number) => Math.round(x * 1000) / 1000; -export async function joinLiveParts(o: { +export type JoinOpts = { parts: JoinPart[]; streamStartedAt: string | null; // `<stem>` for the joined file (its scratch name is `<stem>.temp.<ext>`). outStem: string; deps: JoinDeps; say: (s: string) => void; -}): Promise<JoinResult> { +}; + +// Every scratch file the join writes is removed however it ends — a refusal, +// a proof that fails, or a tool that throws (REVIEW-1 1.6 of live-guard-2). +// Only the proven joined file, renamed out of its scratch name, stays. +export async function joinLiveParts(o: JoinOpts): Promise<JoinResult> { + const scratch: string[] = []; + try { + return await joinInner(o, scratch); + } finally { + for (const f of scratch) await rm(f, { force: true }).catch(() => {}); + } +} + +async function joinInner(o: JoinOpts, scratch: string[]): Promise<JoinResult> { const { deps, say } = o; const startMs = o.streamStartedAt ? Date.parse(o.streamStartedAt) : NaN; const usable = o.parts.filter((p) => p.seconds >= JOIN_MIN_PART_S); @@ -158,12 +191,12 @@ export async function joinLiveParts(o: { const segs: Seg[] = [{ part: base, file: base.file, fileFrom: 0, streamFrom: 0, streamFromBasis: base.fromStart ? "start" : "clock" }]; const joins: LiveJoin[] = []; - const scratch: string[] = []; const cleanup = async () => { for (const f of scratch) await rm(f, { force: true }); }; let unionEnd = base.seconds; const rate = JOIN_SAMPLE_RATE; + let stopWhy: string | null = null; for (const { p, place } of others) { if (segs.length >= JOIN_MAX_PARTS) break; if (place + p.seconds < unionEnd + JOIN_MIN_GAIN_S) continue; @@ -180,14 +213,16 @@ export async function joinLiveParts(o: { const from = Math.max(last.fileFrom, inLast(place) - JOIN_SEARCH_BEFORE_S); const to = Math.min(lastFileEnd, inLast(place) + JOIN_SEARCH_AFTER_S + JOIN_PROBE_SECONDS); if (to - from < JOIN_PROBE_SECONDS * 1.5) { - say(`${path.basename(p.file)}: too little of the part before it to search; not joined.`); + stopWhy = `${path.basename(p.file)}: too little of the part before it to search; not joined.`; + say(stopWhy); break; } const probeA = await deps.decode(p.file, 0, JOIN_PROBE_SECONDS, rate); const search = await deps.decode(last.file, from, to - from, rate); const m1 = matchAt(probeA, search, from, null); if (!m1.ok) { - say(`${path.basename(p.file)}: its start is not found in ${path.basename(last.file)} (${m1.why}); not joined — the longest lands, the rest are kept.`); + stopWhy = `${path.basename(p.file)}: its start is not found in ${path.basename(last.file)} (${m1.why}); not joined — the longest lands, the rest are kept.`; + say(stopWhy); break; } // m1.at: seconds into the last file where this part's second 0 is. @@ -201,18 +236,33 @@ export async function joinLiveParts(o: { const search2 = await deps.decode(last.file, from2, Math.min(lastFileEnd, expect2 + JOIN_PROBE_SECONDS + 3) - from2, rate); const m2 = matchAt(probeB, search2, from2, expect2); if (!m2.ok) { - say(`${path.basename(p.file)}: the second check near the join does not agree (${m2.why}); not joined — the longest lands, the rest are kept.`); + stopWhy = `${path.basename(p.file)}: the second check near the join does not agree (${m2.why}); not joined — the longest lands, the rest are kept.`; + say(stopWhy); break; } const segFile = `${o.outStem}.seg${segs.length}.temp${path.extname(p.file) || ".mkv"}`; scratch.push(segFile); const realFrom = await deps.cut(p.file, cutAt, segFile); - const dup = Math.max(0, cutAt - realFrom); + if (realFrom > cutAt + JOIN_CUT_LATE_TOLERANCE_S) { + stopWhy = `${path.basename(p.file)}: its stream copy starts ${(realFrom - cutAt).toFixed(2)} s after the cut point — a hole of seconds in neither part; not joined.`; + say(stopWhy); + break; + } + if (cutAt - realFrom > JOIN_MAX_EARLY_CUT_S) { + stopWhy = `${path.basename(p.file)}: its stream copy starts ${(cutAt - realFrom).toFixed(2)} s before the cut point (not a keyframe's snap); not joined.`; + say(stopWhy); + break; + } + // The seconds heard twice: where the copy really starts, against where + // it was asked to (both recorded). + const dup = cutAt - realFrom; joins.push({ at: 0, // set below, once the segments' lengths are known kind: "overlap", seconds: r3(unionEnd - streamAt), duplicatedSeconds: r3(dup), + cutAt: r3(cutAt), + cutFrom: r3(realFrom), basis: "content", score: r3(Math.min(m1.score, m2.score)), parts: [last.part.stem, p.stem], @@ -229,7 +279,7 @@ export async function joinLiveParts(o: { } if (segs.length < 2) { await cleanup(); - return { ok: false, why: "nothing could be joined" }; + return { ok: false, why: stopWhy ?? "nothing could be joined" }; } // Each segment's length in the joined file, and where each join falls. @@ -291,6 +341,34 @@ export async function joinLiveParts(o: { } at += len; } + // The tail: the joined file ends with its last segment. + { + const lastSeg = segs[segs.length - 1]!; + const lastLen = lengths[lengths.length - 1]!; + const tail = await check(lastSeg.file, lastLen - 25, sum - 25, "the tail"); + if (tail) fails.push(tail); + } + // THE PICTURE (REVIEW-1 1.5): on both sides of every join, at the head and + // at the tail, the joined file's frame is the segment's. + if (b0.videoCodec) { + const pic = async (segFile: string, segAt: number, joinedAt: number, what: string) => { + const [x, y] = await Promise.all([deps.frame(segFile, segAt), deps.frame(temp, joinedAt)]); + if (!x || !y) return `${what}: no picture decoded`; + const d = frameDiff(x, y); + return d <= JOIN_FRAME_MAX_DIFF ? null : `${what}: the picture differs (${d.toFixed(1)})`; + }; + const checks: Promise<string | null>[] = [pic(segs[0]!.file, 5, 5, "the head's picture")]; + let pAt = 0; + for (let i = 0; i < segs.length; i++) { + if (i > 0) { + checks.push(pic(segs[i - 1]!.file, lengths[i - 1]! - 10, pAt - 10, `the picture before join ${i}`)); + checks.push(pic(segs[i]!.file, 10, pAt + 10, `the picture after join ${i}`)); + } + pAt += lengths[i]!; + } + checks.push(pic(segs[segs.length - 1]!.file, lengths[lengths.length - 1]! - 10, sum - 10, "the tail's picture")); + for (const r of await Promise.all(checks)) if (r) fails.push(r); + } if (fails.length) { await cleanup(); return { ok: false, why: `the joined file does not hold its parts where it should (${fails.join("; ")}): not proven` }; @@ -347,6 +425,15 @@ export function ffmpegJoinDeps( } }, probe: (file) => probeJoinStreams(bins.ffprobeBin, file), + frame: async (file, at) => { + const r = await execa( + bins.ffmpegBin, + ["-v", "error", "-nostdin", "-ss", Math.max(0, at).toFixed(3), "-i", file, "-frames:v", "1", "-vf", "scale=32:18,format=gray", "-f", "rawvideo", "pipe:1"], + { encoding: "buffer", reject: false, timeout: 60_000, ...opt }, + ); + const buf = Buffer.from((r.stdout ?? new Uint8Array()) as Uint8Array); + return r.exitCode === 0 && buf.length === 32 * 18 ? new Uint8Array(buf) : null; + }, }; } diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -1730,16 +1730,31 @@ const noiseAt = (seed: number, n: number) => { x ^= x >>> 15; return x / 4294967296 - 0.5; }; -type FakeSeg = { stream: number; seconds: number; seed: number }; +// `vseed`: what its picture shows (default: the same as its sound). +type FakeSeg = { stream: number; seconds: number; seed: number; vseed: number }; const readFake = async (file: string): Promise<FakeSeg[]> => { const t = await readFile(file, "utf8").catch(() => ""); const segs = /segs=([^;]+)/.exec(t); - if (segs) return segs[1]!.split(",").map((x) => { const [s, l, k] = x.split(":").map(Number); return { stream: s!, seconds: l!, seed: k! }; }); - const num = (k: string, d: number) => Number(new RegExp(`${k}=([\\d.]+)`).exec(t)?.[1] ?? d); - return [{ stream: num("stream", 0), seconds: num("seconds", 0), seed: num("seed", 0) }]; + if (segs) return segs[1]!.split(",").map((x) => { const [s, l, k, v] = x.split(":").map(Number); return { stream: s!, seconds: l!, seed: k!, vseed: v ?? k! }; }); + const num = (k: string, d: number) => Number(new RegExp(`(?:^|;)${k}=([\\d.]+)`).exec(t)?.[1] ?? d); + const seed = num("seed", 0); + return [{ stream: num("stream", 0), seconds: num("seconds", 0), seed, vseed: num("vseed", seed) }]; }; -function fakeJoinDeps(o: { drop?: boolean } = {}) { +function fakeJoinDeps(o: { drop?: boolean; cutLate?: boolean; cutThrows?: boolean; garblePicture?: boolean } = {}) { return { + // A 32-byte "frame" of the picture at that second (5 frames a second). + frame: async (file: string, at: number) => { + const segs = await readFake(file); + let t = at; + for (const g of segs) { + if (t < g.seconds) { + const f = Math.floor((g.stream + t) * 5); + return Uint8Array.from({ length: 32 }, (_, i) => Math.floor((noiseAt(g.vseed + 1000, f * 32 + i) + 0.5) * 255)); + } + t -= g.seconds; + } + return null; + }, decode: async (file: string, from: number, seconds: number, rate: number) => { const segs = await readFake(file); const out = new Float32Array(Math.round(seconds * rate)); @@ -1757,15 +1772,22 @@ function fakeJoinDeps(o: { drop?: boolean } = {}) { }, cut: async (file: string, from: number, out: string) => { const [g] = await readFake(file); - const real = Math.floor(from / 2) * 2; - await writeFile(out, `format=mov,mp4;seconds=${g!.seconds - real};stream=${g!.stream + real};seed=${g!.seed};`); + // A late cut: the stream copy starts after the point asked (a hole). + const real = o.cutLate ? Math.ceil(from) + 2 : Math.floor(from / 2) * 2; + await writeFile(out, `format=mov,mp4;seconds=${g!.seconds - real};stream=${g!.stream + real};seed=${g!.seed};vseed=${g!.vseed};`); + if (o.cutThrows) throw new Error("No space left on device"); return real; }, concat: async (files: string[], out: string) => { const all = (await Promise.all(files.map(readFake))).flat(); const kept = o.drop ? all.slice(0, -1) : all; const total = kept.reduce((n, g) => n + g.seconds, 0); - await writeFile(out, `format=matroska;seconds=${total};segs=${kept.map((g) => `${g.stream}:${g.seconds}:${g.seed}`).join(",")};`); + // garblePicture: the joined file's picture after the first segment is + // not the segment's (its sound is). + await writeFile( + out, + `format=matroska;seconds=${total};segs=${kept.map((g, i) => `${g.stream}:${g.seconds}:${g.seed}:${o.garblePicture && i > 0 ? g.vseed + 1 : g.vseed}`).join(",")};`, + ); }, probe: async (file: string) => { const t = await readFile(file, "utf8").catch(() => ""); @@ -1787,6 +1809,7 @@ async function joinCase( edgeStream: number; edgeSeconds: number; edgeSeed?: number; + edgeVseed?: number; duration?: number; deps?: ReturnType<typeof fakeJoinDeps>; signal?: AbortSignal; @@ -1804,7 +1827,10 @@ async function joinCase( const b = `.${id}.live-${stamp}.ytdlp-edge-a4`; await mkdir(store(), { recursive: true }); await writeFile(path.join(store(), `${a}.mp4`), "format=mov,mp4;seconds=3000;stream=0;seed=7;"); - await writeFile(path.join(store(), `${b}.mp4`), `format=mov,mp4;seconds=${o.edgeSeconds};stream=${o.edgeStream};seed=${o.edgeSeed ?? 7};`); + await writeFile( + path.join(store(), `${b}.mp4`), + `format=mov,mp4;seconds=${o.edgeSeconds};stream=${o.edgeStream};seed=${o.edgeSeed ?? 7};${o.edgeVseed !== undefined ? `vseed=${o.edgeVseed};` : ""}`, + ); const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await ytChannel(); await upsertLiveRecordingRow(paths, YT_SLUG, { @@ -1854,6 +1880,8 @@ test("slice 5: an overlap found by its sound — the two parts joined at it, pro assert.equal(j.at, 3000); assert.equal(j.seconds, 599, "the overlap, found by sound (the clock said 579)"); assert.equal(j.duplicatedSeconds, 1, "the cut starts a keyframe early"); + assert.equal(j.cutAt, 599, "where the second part was asked to start"); + assert.equal(j.cutFrom, 598, "where its copy really starts"); assert.equal(row.coverage?.covers, true); assert.equal(row.removedParts?.length, 2); assert.ok(row.removedParts!.every((r) => /inside the joined file/.test(r.why))); @@ -2069,3 +2097,23 @@ test("REVIEW 1.7: no join during a shutdown's landing — the longest lands, the assert.equal(s.landed?.seconds, 3000); assert.ok((await left(id)).some((n) => /ytdlp-edge-a4\.mp4$/.test(n)), "the other part is kept"); }); + +test("REVIEW 1.5/1.6: the join's proof checks the PICTURE, refuses a cut that starts late (a hole), and leaves no scratch when a tool throws", { timeout: 120_000 }, async () => { + // (a) The sound is right but the joined file's picture after the join is + // not the second part's. + const a = await joinCase("exmpljoin07", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ garblePicture: true }) }); + await a.run; + assert.ok(a.log.some((l) => /Not joined/.test(l) && /picture/.test(l)), a.log.filter((l) => /join/i.test(l)).join("")); + assert.equal((await rowOf("exmpljoin07")).find((r) => r.resumeOf)!.keptParts?.length, 1); + // (b) The stream copy starts after the cut point: seconds in neither part. + const b = await joinCase("exmpljoin08", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ cutLate: true }) }); + await b.run; + assert.ok(b.log.some((l) => /Not joined/.test(l) && /hole/.test(l))); + // (c) The cut throws (a full disk): the scratch it wrote is gone, the longest lands, the rest kept. + const c = await joinCase("exmpljoin09", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ cutThrows: true }) }); + const sc = await c.run; + assert.equal(sc.landed?.seconds, 3000); + const files = await left("exmpljoin09"); + assert.deepEqual(files.filter((n) => /\.temp\./.test(n)), [], `no scratch left: ${files.join(", ")}`); + assert.equal(files.length, 1); +}); diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -581,6 +581,11 @@ export type LiveJoin = { kind: "overlap" | "gap"; seconds: number; duplicatedSeconds?: number; + // An overlap: where the next part was asked to start, and where its stream + // copy really starts (seconds into that part); duplicatedSeconds is the + // difference. + cutAt?: number; + cutFrom?: number; basis: "content" | "clock"; score?: number; parts: string[];