commit 2b89a004c7a17a17144765400839dd84e0f5cda9
parent a0c8587a5b9b9f88551c8a085645cc2d9062a86f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 18:02:13 -0500
liveJoin: the two parts' pictures are compared across the overlap, and the joined file's timestamps must run on at every join
REVIEW-2 2.1 of live-guard-2: the picture proof compared each segment with
the joined file, which proves only that the concat copied its segments.
Now, for an overlap, the two SOURCE parts are compared with each other at
matching stream times at four points spread over the overlap (a mean
difference of at most 12 of 255), and against the same frames one second
apart, which must differ clearly for the picture to prove the alignment.
At every join of the joined file the video and audio packets 5 s either
side must run on with no jump over 1.5 times their interval (ffprobe's
packet timestamps). A static scene is proven by the timestamps alone; when
neither the picture nor the timestamps can be established, no join: the
longest lands and the rest are kept.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
2 files changed, 119 insertions(+), 1 deletion(-)
diff --git a/common/controller/liveJoin.ts b/common/controller/liveJoin.ts
@@ -64,6 +64,10 @@ export const JOIN_MAX_EARLY_CUT_S = 30;
// 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;
+// Frames compared across an overlap, and how much more the same frames one
+// second apart must differ for the picture to prove the alignment.
+export const JOIN_PICTURE_SAMPLES = 4;
+export const JOIN_PICTURE_MARGIN = 4;
export type JoinStreams = {
seconds: number | null;
@@ -87,6 +91,9 @@ export type JoinDeps = {
// A small grey frame of the picture at `at` seconds (null: no picture
// decoded there).
frame: (file: string, at: number) => Promise<Uint8Array | null>;
+ // The packets' timestamps (seconds) of [from, from + seconds) of `file`,
+ // video and audio (null: cannot be read).
+ timestamps: (file: string, from: number, seconds: number) => Promise<{ video: number[]; audio: number[] } | null>;
};
export function frameDiff(a: Uint8Array, b: Uint8Array): number {
@@ -197,6 +204,8 @@ async function joinInner(o: JoinOpts, scratch: string[]): Promise<JoinResult> {
let unionEnd = base.seconds;
const rate = JOIN_SAMPLE_RATE;
let stopWhy: string | null = null;
+ // Per join: did the two parts' pictures prove it (REVIEW-2 2.1)?
+ const provenByPicture: boolean[] = [];
for (const { p, place } of others) {
if (segs.length >= JOIN_MAX_PARTS) break;
if (place + p.seconds < unionEnd + JOIN_MIN_GAIN_S) continue;
@@ -240,6 +249,32 @@ async function joinInner(o: JoinOpts, scratch: string[]): Promise<JoinResult> {
say(stopWhy);
break;
}
+ // THE PICTURE ACROSS THE OVERLAP (REVIEW-2 2.1): the two SOURCE parts
+ // compared with each other at matching stream times, spread over the
+ // overlap; and the same frames one second apart, which must differ
+ // for the picture to prove anything (a static scene cannot).
+ let pictureProves = false;
+ if (b0.videoCodec) {
+ const lo = streamAt + 2;
+ const hi = unionEnd - 2;
+ const match: number[] = [];
+ const off: number[] = [];
+ for (let k = 0; k < JOIN_PICTURE_SAMPLES && hi > lo; k++) {
+ const t = lo + ((hi - lo) * (k + 0.5)) / JOIN_PICTURE_SAMPLES;
+ const [x, y, z] = await Promise.all([deps.frame(last.file, inLast(t)), deps.frame(p.file, t - streamAt), deps.frame(p.file, t - streamAt + 1)]);
+ if (!x || !y || !z) continue;
+ match.push(frameDiff(x, y));
+ off.push(frameDiff(x, z));
+ }
+ if (match.some((d) => d > JOIN_FRAME_MAX_DIFF)) {
+ stopWhy = `${path.basename(p.file)}: its picture is not ${path.basename(last.file)}'s at the same stream times across the overlap (difference up to ${Math.max(...match).toFixed(1)}); not joined.`;
+ say(stopWhy);
+ break;
+ }
+ const mean = (v: number[]) => v.reduce((n, x) => n + x, 0) / (v.length || 1);
+ pictureProves = match.length >= 2 && mean(off) > 2 * mean(match) + JOIN_PICTURE_MARGIN;
+ }
+ provenByPicture.push(pictureProves);
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);
@@ -273,6 +308,7 @@ async function joinInner(o: JoinOpts, scratch: string[]): Promise<JoinResult> {
// GAP (or too little overlap to align): joined as it is, stated.
const gap = Math.max(0, place - unionEnd);
joins.push({ at: 0, kind: "gap", seconds: r3(gap), basis: "clock", parts: [last.part.stem, p.stem] });
+ provenByPicture.push(false);
segs.push({ part: p, file: p.file, fileFrom: 0, streamFrom: Math.max(place, unionEnd), streamFromBasis: "clock" });
unionEnd = Math.max(place, unionEnd) + p.seconds;
}
@@ -369,6 +405,31 @@ async function joinInner(o: JoinOpts, scratch: string[]): Promise<JoinResult> {
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);
}
+ // THE TIMESTAMPS ACROSS EACH JOIN (REVIEW-2 2.1): in the joined file,
+ // video (and audio) packets 5 s either side of every join go on with no
+ // jump larger than a frame (a packet) interval. A join the pictures did
+ // not prove needs this; when it cannot be read either, no join.
+ {
+ let jAt = 0;
+ for (let i = 1; i < segs.length; i++) {
+ jAt += lengths[i - 1]!;
+ const ts = await deps.timestamps(temp, Math.max(0, jAt - 5), 10).catch(() => null);
+ const jumps = (v: number[]) => {
+ const d = [...v].sort((a, b) => a - b).slice(1).map((x, k) => x - [...v].sort((a, b) => a - b)[k]!);
+ if (d.length < 3) return null;
+ const med = [...d].sort((a, b) => a - b)[Math.floor(d.length / 2)]!;
+ return Math.max(...d) > med * 1.5 + 0.001 ? Math.max(...d) : 0;
+ };
+ const v = ts && (b0.videoCodec ? jumps(ts.video) : 0);
+ const a = ts && jumps(ts.audio);
+ const established = ts !== null && v !== null && a !== null;
+ if (established && ((v ?? 0) > 0 || (a ?? 0) > 0)) {
+ fails.push(`join ${i}: the timestamps jump by ${Math.max(v ?? 0, a ?? 0).toFixed(3)} s`);
+ } else if (!established && !provenByPicture[i - 1]) {
+ fails.push(`join ${i}: neither the picture (a static scene, or none) nor the timestamps can prove it`);
+ }
+ }
+ }
if (fails.length) {
await cleanup();
return { ok: false, why: `the joined file does not hold its parts where it should (${fails.join("; ")}): not proven` };
@@ -425,6 +486,22 @@ export function ffmpegJoinDeps(
}
},
probe: (file) => probeJoinStreams(bins.ffprobeBin, file),
+ timestamps: async (file, from, seconds) => {
+ const read = async (sel: string) => {
+ const r = await execa(
+ bins.ffprobeBin,
+ ["-v", "error", "-select_streams", sel, "-read_intervals", `${Math.max(0, from).toFixed(3)}%+${seconds.toFixed(3)}`, "-show_entries", "packet=pts_time", "-of", "csv=p=0", file],
+ { reject: false, timeout: 60_000, ...opt },
+ );
+ if (r.exitCode !== 0) return null;
+ return String(r.stdout)
+ .split("\n")
+ .map((l) => Number(l.trim().replace(/,$/, "")))
+ .filter((x) => Number.isFinite(x) && x >= from && x < from + seconds);
+ };
+ const [video, audio] = await Promise.all([read("v:0"), read("a:0")]);
+ return video && audio ? { video, audio } : null;
+ },
frame: async (file, at) => {
const r = await execa(
bins.ffmpegBin,
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -1766,10 +1766,30 @@ const readFake = async (file: string): Promise<FakeSeg[]> => {
const seed = num("seed", 0);
return [{ stream: num("stream", 0), seconds: num("seconds", 0), seed, vseed: num("vseed", seed) }];
};
-function fakeJoinDeps(o: { drop?: boolean; cutLate?: boolean; cutThrows?: boolean; garblePicture?: boolean } = {}) {
+function fakeJoinDeps(
+ o: { drop?: boolean; cutLate?: boolean; cutThrows?: boolean; garblePicture?: boolean; staticPicture?: boolean; ptsJump?: boolean; noTimestamps?: boolean } = {},
+) {
return {
+ // The packets' timestamps of [from, from + seconds) of the file: video at
+ // 5 frames a second, audio every 0.02 s, continuous across segments
+ // (`ptsJump`: a 2 s jump at each segment boundary).
+ timestamps: async (file: string, from: number, seconds: number) => {
+ if (o.noTimestamps) return null;
+ const segs = await readFake(file);
+ const bounds: number[] = [];
+ let acc = 0;
+ for (const g of segs) bounds.push((acc += g.seconds));
+ const shift = (t: number) => (o.ptsJump ? bounds.slice(0, -1).filter((b) => t >= b).length * 2 : 0);
+ const at = (step: number) => {
+ const out: number[] = [];
+ for (let t = Math.ceil(from / step) * step; t < from + seconds; t += step) out.push(Math.round((t + shift(t)) * 1000) / 1000);
+ return out;
+ };
+ return { video: at(0.2), audio: at(0.02) };
+ },
// A 32-byte "frame" of the picture at that second (5 frames a second).
frame: async (file: string, at: number) => {
+ if (o.staticPicture) return new Uint8Array(32).fill(16);
const segs = await readFake(file);
let t = at;
for (const g of segs) {
@@ -2493,3 +2513,24 @@ test("REVIEW2 1.1: a part holding the stream's end is kept by its place on the s
assert.ok(ins, "the insurance ran");
assert.ok(row.keptParts?.some((k) => /ytdlp-insure$/.test(k.stem)), "kept: it may hold the end");
});
+
+test("REVIEW2 2.1: the join's picture proof compares the two SOURCE parts across the overlap; on a static scene the timestamps' continuity decides; neither, no join", { timeout: 120_000 }, async () => {
+ const base = { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301 };
+ // (a) The second part's picture is another moment than the first's at the same stream time.
+ const a = await joinCase("exmplr2j101", { ...base, edgeVseed: 55 });
+ 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(""));
+ // (b) A static scene, the timestamps continuous: joined.
+ const b = await joinCase("exmplr2j102", { ...base, deps: fakeJoinDeps({ staticPicture: true }) });
+ await b.run;
+ assert.ok(b.log.some((l) => /Joined 2 parts/.test(l)), b.log.filter((l) => /join/i.test(l)).join(""));
+ // (c) A static scene and a jump in the timestamps at the join: no join.
+ const c = await joinCase("exmplr2j103", { ...base, deps: fakeJoinDeps({ staticPicture: true, ptsJump: true }) });
+ await c.run;
+ assert.ok(c.log.some((l) => /Not joined/.test(l) && /timestamps/.test(l)));
+ // (d) A static scene and no timestamps to read: neither proof, no join.
+ const d = await joinCase("exmplr2j104", { ...base, deps: fakeJoinDeps({ staticPicture: true, noTimestamps: true }) });
+ await d.run;
+ assert.ok(d.log.some((l) => /Not joined/.test(l)));
+ assert.equal((await rowOf("exmplr2j104")).find((r) => r.resumeOf)!.keptParts?.length, 1);
+});