commit f857db5d1a659586f20e63c7571920fa2d07bf60
parent a517df7b8d2a97a1803b5d17df067c17df41d70d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 14 Nov 2026 04:29:52 -0500
Merge lane/compact-store (follow-up): a compacted copy is compared with its source in colour as well as brightness, and each frame against the minutes around it -- a hue shift or colour noise fails; a stream that alternates two kinds of picture is not rejected for it; a few bad frames cannot widen their own floor; clearing a stale marker cannot remove a fresh one; dropping after verification is refused unless both comparisons are on record
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
12 files changed, 388 insertions(+), 34 deletions(-)
diff --git a/OPERATING.md b/OPERATING.md
@@ -1206,7 +1206,17 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"}
Each frame is also split into an 8×8 grid of tiles, each scored alone: a tile below `wholeFileTileMin` (0.7)
for more than `wholeFileTileRunFrames` (2) frames in a row fails, so a small region changed for 3 frames at 30
fps does not average away. The pointer records the mean, the spread, the lowest frame and when, and the worst
- tile and when. It costs about 1.3–1.6× a plain decode of both files;
+ tile and when. The colour is scored too, every frame, on the U and V planes: no frame's lower plane below
+ `wholeFileChromaMin` (0.9) and a mean of at least `wholeFileChromaMean` (0.97). The grey comparison and VMAF
+ cannot see a hue shift or chroma-only noise. The relative floor is LOCAL: each frame is judged against the
+ `wholeFileWindowSeconds` (120) around it, the lower of the floors of the half-window before and the half-window
+ after (median − max(8 × 1.4826 × the median absolute deviation, 0.03)). So a stream that alternates a webcam
+ and a screen share is judged stretch by stretch, and a few bad frames cannot widen their own floor. A degraded
+ stretch longer than the window looks steady to that floor. It is caught instead by the absolute per-frame floor,
+ the tile grid, the mean floor, and the VMAF excerpts, laid at least one every window across the file. At 640×360 the
+ comparison costs about 5–6× a plain decode of both files; its per-frame cost is fixed (about 4 ms at 256 px), so
+ it adds roughly 35 minutes to a 5-hour 30 fps stream (an estimate). `"after-verify"` drops only when the pointer
+ records both the luma and the colour comparison;
- VMAF on 2-second excerpts across every chunk join, inside every chunk, and at `qualitySamples` (12) more spread
through the file: mean at least `vmafMinMean` (90), none below `vmafMinSample` (85). SSIM where this ffmpeg has
no libvmaf. Frames are paired by number on one clock;
@@ -1238,7 +1248,8 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"}
re-check and the drop. It is live only on this machine's current boot and host, with the same pid and pid start
time, its job still running, and under 72 h old. Anything else is stale and ignored. Stale markers are removed at
editor boot, at the start of every compaction run, when the video is skipped as already compacted, and by
- `compaction-markers {"clear": …}`. A refusal by one video never stops a batch: the prune logs it and goes on.
+ `compaction-markers {"clear": …}`. A clear renames the marker aside and removes it only if it is still the one judged stale, so a marker a
+ new compaction wrote meanwhile is kept. A refusal by one video never stops a batch: the prune logs it and goes on.
- **A review.** `get compaction-review` gives each video's two files and an `smplayer` command that plays both. The
editor has no player for the store. Watch them, then record the review (the video page's **Review the compacted
copy**, or `review-compacted-original`). A review names the copy it watched (`forSha256`) and counts for that copy
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -649,10 +649,13 @@ Compacting a saved video (`pnpm ops compact-saved-videos`, controller/compactSav
| `ssimMinSample` | `0.9` | Without libvmaf: the SSIM no excerpt may fall below. Default 0.9. |
| `wholeFileSsimMin` | `0.9` | THE WHOLE-FILE COMPARISON scores EVERY frame of the copy against the source's (256 px wide, grey, the source taken to the copy's rate, paired frame for frame): no frame may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern scores at least 0.996; one black frame scores 0). |
| `wholeFileSsimMean` | `0.97` | The whole-file comparison's mean must reach this. Default 0.97. |
-| `wholeFileSigmaK` | `8` | The floor relative to the file itself: no frame below its mean − max(k × the frames' standard deviation, wholeFileSigmaMargin). Default k = 8 (measured: a good crf-36 copy has a spread of 0.0006, its worst frame 3 spreads under its mean). |
+| `wholeFileSigmaK` | `8` | The floor relative to the file's own frames NEARBY (wholeFileWindowSeconds): no frame below its neighbourhood's MEDIAN − max(k × its robust spread, wholeFileSigmaMargin). The spread is 1.4826 × the median absolute deviation, so a few bad frames cannot widen their own floor. Default k = 8 (measured: a good crf-36 copy's spread is about 0.0006). |
| `wholeFileSigmaMargin` | `0.03` | The least the relative floor sits under the mean, for a file whose frames barely differ. Default 0.03. |
| `wholeFileTileMin` | `0.7` | Each frame is also split into an 8×8 grid of tiles, each scored on its own, so a change to a small region is not averaged away: a tile below this for more than wholeFileTileRunFrames frames in a row fails. Default 0.7 (a good crf-36 copy's lowest tile: 0.949; a red box over 1% of the picture: 0.46). |
| `wholeFileTileRunFrames` | `2` | How many frames in a row a tile may sit below wholeFileTileMin. Default 2: a 3-frame defect at 30 fps fails. |
+| `wholeFileChromaMin` | `0.9` | THE COLOUR, every frame: the whole-file comparison also scores the U and V planes (SSIM), which the grey comparison and VMAF do not see — a hue shift, chroma-only noise. No frame's lower plane may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern: lowest 0.991). |
+| `wholeFileChromaMean` | `0.97` | The colour planes' mean must reach this. Default 0.97 (good copy: 0.9986). |
+| `wholeFileWindowSeconds` | `120` | The NEIGHBOURHOOD the relative floor is taken over: each frame is judged against the frames in the half-window just before it and just after it (the lower of their two floors), so a stream alternating two kinds of picture (a webcam, a screen share) is judged stretch by stretch, not by the file's dominant mode. A short defect inside a steady stretch has that stretch on both sides and falls below it. A degraded stretch longer than the window looks steady to it: such a stretch is caught by the absolute per-frame floor, the tile grid, the mean floor, and the VMAF excerpts, one at least every window across the whole file. Default 120 s; 5–3600. |
| `availabilityMaxAgeDays` | `7` | How fresh the platform check must be for a video to count as still on its platform: an availability record written by a real check (not a backfill), public or unlisted, at most this many days old. Anything else counts as gone, and its original waits for a person's review. Default 7. |
| `dropOriginal` | `"keep"` | "keep" (the default in this slice): every original stays until a person drops it. "after-verify": once every check passed and the pointer names the compacted copy, a separate step reads that copy back from disk (size, sha256, container, length) and then drops the original — except for a video gone from its platform (availability not public or unlisted, or unknown), whose original waits for a person's review (`get compaction-review`, `review-compacted-original`, then `drop-saved-alternate` with `confirmOriginal`); only when the verification included the whole-file comparison. There is no backup of the store: after such a drop the compacted copy is the only copy. |
@@ -686,6 +689,9 @@ Default:
"wholeFileSigmaMargin": 0.03,
"wholeFileTileMin": 0.7,
"wholeFileTileRunFrames": 2,
+ "wholeFileChromaMin": 0.9,
+ "wholeFileChromaMean": 0.97,
+ "wholeFileWindowSeconds": 120,
"availabilityMaxAgeDays": 7,
"dropOriginal": "keep"
}
diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts
@@ -838,6 +838,11 @@ test("F2: every listed defect fails the whole-file comparison on the default thr
["a 3% region for 3 s", (c) => (c.index === 1 ? "drawbox=x=300:y=150:w=110:h=63:c=red:t=fill:enable='between(t,0.5,3.5)'" : undefined)],
["a 1% region for 3 frames", (c) => (c.index === 1 ? "drawbox=x=300:y=150:w=64:h=36:c=red:t=fill:enable='between(n,30,32)'" : undefined)],
["one black frame", (c) => (c.index === 1 ? "drawbox=c=black:t=fill:enable='eq(n,40)'" : undefined)],
+ // D1: colour only — the grey comparison and VMAF do not see these.
+ ["a 3 s hue shift", (c) => (c.index === 1 ? "hue=h=120:s=1:enable='between(t,0.5,3.5)'" : undefined)],
+ ["3 s of chroma-only noise", (c) => (c.index === 1 ? "noise=c1s=80:c1f=t:c2s=80:c2f=t:enable='between(t,0.5,3.5)'" : undefined)],
+ // E2: a plane whose SSIM goes NEGATIVE fails for the right reason.
+ ["1 s of the V plane inverted", (c) => (c.index === 1 ? "lutyuv=v=negval:enable='between(t,1,2)'" : undefined)],
];
for (const [label, defect] of defects) {
await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 12, fps: 30, gop: 30 } }, async (fx) => {
@@ -845,6 +850,7 @@ test("F2: every listed defect fails the whole-file comparison on the default thr
const r = await run(fx, flowDeps({ encodeChunk: (o) => x264Chunk(o, 18, defect(o.chunk)) }), { ...SETTINGS, chunkMinutes: 4 / 60 });
assert.equal(r.status, "failed", label);
assert.match((r as { reason: string }).reason, /verification failed: the whole-file comparison: /, label);
+ if (/V plane inverted/.test(label)) assert.match((r as { reason: string }).reason, /the colour \(V plane\) of a frame at .* scores -/, label);
assert.equal(await fx.pointerText(), before, label);
await stat(fx.source);
});
@@ -864,6 +870,8 @@ test("F2: a GOOD SVT-AV1 crf-36 encode of a detailed 640x360 fixture passes ever
assert.ok(w.min >= settings.wholeFileSsimMin + 0.05, JSON.stringify(w));
assert.ok(w.min >= w.relativeFloor! + 0.01, JSON.stringify(w));
assert.ok(w.worstTile && w.worstTile.min >= settings.wholeFileTileMin + 0.1 && w.worstTile.longestBelow === 0, JSON.stringify(w));
+ // The colour planes too (measured 0.991 at their lowest).
+ assert.ok(w.chroma && w.chroma.min >= settings.wholeFileChromaMin + 0.05 && w.chroma.mean >= settings.wholeFileChromaMean + 0.02, JSON.stringify(w.chroma));
});
});
@@ -940,3 +948,27 @@ test("kept-originals lists every pointer that keeps an original (what a rollback
assert.deepEqual(rows[0].kept.map((k) => [k.file, k.keptAs, k.sha256]), [[ORIGINAL, "original", fx.sourceSha]]);
});
});
+
+// E1: a degraded stretch LONGER than the local floor's window looks steady to
+// that floor; it is caught by the other checks. Scaled down: a 2 s window over
+// a 12 s file, a 4 s stretch (the same as 3 minutes against 120 s).
+test("E1: a degraded stretch longer than the window still fails (absolute floor, or the excerpts laid every window)", { skip: NO_TOOLS }, async () => {
+ const cases: [string, (c: ChunkPlan) => string | undefined, RegExp][] = [
+ ["4 s of heavy blocking", (c) => (c.index === 1 ? "scale=40:-2,scale=640:360:flags=neighbor" : undefined), /no frame may fall below 0\.9/],
+ // Measured: caught by the tile grid (a tile at 0.66 for 29 frames).
+ ["4 s of mild blur", (c) => (c.index === 1 ? "boxblur=3" : undefined), /tile .* is below its floor|VMAF .* at its worst excerpt/],
+ ];
+ for (const [label, defect, why] of cases) {
+ await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 12, fps: 30, gop: 30 } }, async (fx) => {
+ const log = logger();
+ const r = await run(
+ fx,
+ flowDeps({ score: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 18, defect(o.chunk)) }),
+ { ...SETTINGS, chunkMinutes: 4 / 60, wholeFileWindowSeconds: 2, qualitySamples: 3 },
+ log.onLog,
+ );
+ assert.equal(r.status, "failed", `${label}: ${log.lines.join("\n")}`);
+ assert.match((r as { reason: string }).reason, why, label);
+ });
+ }
+});
diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts
@@ -1069,6 +1069,9 @@ async function verify(o: {
tileRunFrames: s.wholeFileTileRunFrames,
expectedFrames: n,
fps: outFps,
+ chromaMinFrame: s.wholeFileChromaMin,
+ chromaMeanFloor: s.wholeFileChromaMean,
+ windowFrames: Math.round(s.wholeFileWindowSeconds * outFps),
});
checks.wholeFile = {
fps: outFps,
@@ -1081,7 +1084,19 @@ async function verify(o: {
meanFloor: s.wholeFileSsimMean,
maxGapSeconds: round(gap, 4),
sd: round(v.sd, 5),
+ median: round(v.median, 4),
+ windowSeconds: s.wholeFileWindowSeconds,
+ worstLocalMargin: round(v.worstLocalMargin, 4),
+ worstLocalAt: round(v.worstLocalAt / outFps, 3),
relativeFloor: round(v.relativeFloor, 4),
+ chroma: {
+ mean: round(v.chroma.mean, 4),
+ min: round(v.chroma.min, 4),
+ worstAt: round(v.chroma.minAt / outFps, 3),
+ plane: v.chroma.plane,
+ minFloor: s.wholeFileChromaMin,
+ meanFloor: s.wholeFileChromaMean,
+ },
grid: WHOLE_FILE_GRID,
tileFloor: s.wholeFileTileMin,
tileRunFrames: s.wholeFileTileRunFrames,
@@ -1100,6 +1115,7 @@ async function verify(o: {
if (!v.ok) fail(`the whole-file comparison: ${v.why}`);
log(
`${tag}: whole file SSIM ${v.mean.toFixed(4)} mean over ${cmp.frames.length} frames, lowest ${v.min.toFixed(4)} at ${(v.minAt / outFps).toFixed(2)} s; ` +
+ `colour ${v.chroma.mean.toFixed(4)} mean, lowest ${v.chroma.min.toFixed(4)} (${v.chroma.plane}); ` +
`worst tile ${v.worstTile ? `${v.worstTile.col},${v.worstTile.row} at ${v.worstTile.min.toFixed(3)} (${v.worstTile.longestBelow} frame(s) below ${s.wholeFileTileMin})` : "none"}.`,
);
@@ -1109,6 +1125,10 @@ async function verify(o: {
const relStart = state.sourceFirstPts - o.probe.formatStart;
const lastAt = Math.max(0, srcSeconds - EXCERPT_SECONDS - 0.25);
const times = new Set<number>(sampleTimes(srcSeconds, s.qualitySamples, EXCERPT_SECONDS, outFps).map((t) => onGrid(t + relStart, outFps)));
+ // …and at least one every wholeFileWindowSeconds across the whole file: a
+ // degraded stretch longer than the local floor's window looks steady to
+ // that floor, and always holds one of these.
+ for (let t = s.wholeFileWindowSeconds / 2; t < lastAt; t += s.wholeFileWindowSeconds) times.add(onGrid(t + relStart, outFps));
for (const c of state.chunks) {
const from = c.from - state.sourceFirstPts;
const to = c.last ? srcSeconds : c.to - state.sourceFirstPts;
@@ -1261,8 +1281,8 @@ async function afterSwap(o: {
log(`${tag}: dropOriginal is "keep": the original ${original.file} stays until a person drops it.`);
return { dropped: false, review: state() };
}
- if (!pointer.compacted?.checks.wholeFile) {
- log(`${tag}: the verification has no whole-file comparison: "after-verify" does not drop the original ${original.file}.`);
+ if (!pointer.compacted?.checks.wholeFile || !pointer.compacted.checks.wholeFile.chroma) {
+ log(`${tag}: the verification has no whole-file luma AND colour comparison: "after-verify" does not drop the original ${original.file}.`);
return { dropped: false, review: state() };
}
if (!presence.onPlatform) {
diff --git a/common/lib/compactMedia-server.ts b/common/lib/compactMedia-server.ts
@@ -587,7 +587,7 @@ export async function scoreExcerpt(
...(opts.signal ? { signal: opts.signal } : {}),
});
if (opts.metric === "ssim") {
- const m = /SSIM .*All:([0-9.]+)/.exec(err);
+ 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]);
}
@@ -661,7 +661,7 @@ async function ssimOf(paths: GatedPaths, b: string, a: string, rate: string, out
],
{ reject: false, ...(signal ? { cancelSignal: signal } : {}) },
);
- const m = /SSIM .*All:([0-9.]+)/.exec(String(r.stderr ?? ""));
+ 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]);
}
@@ -756,16 +756,23 @@ export type TileSummary = {
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;
};
-function ssimScores(text: string): number[] {
+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 = /All:([0-9.]+|inf)/.exec(l);
+ const m = re.exec(l);
if (m) out.push(m[1] === "inf" ? 1 : Number(m[1]));
}
return out;
@@ -799,9 +806,13 @@ export async function compareWholeFile(
const whole = path.join(opts.scratchDir, "wf-whole.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=gray,split=${T + 1}${labels("d")}`,
- `[1:v]${decimateTo(opts.sourceFps, opts.fps)}${n},scale=${W}:${H}:flags=area,format=gray,split=${T + 1}${labels("r")}`,
+ `[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]${decimateTo(opts.sourceFps, opts.fps)}${n},scale=${W}:${H}:flags=area,format=yuv420p,split=2[r0][rg]`,
+ `[rg]format=gray,split=${T}${labels("r").replace("[r0]", "")}`,
`[d0][r0]ssim=stats_file=${esc(whole)}:eof_action=endall[out]`,
];
for (let k = 0; k < T; k += 1) {
@@ -824,7 +835,10 @@ export async function compareWholeFile(
],
{ estimateMB: WHOLE_FILE_ESTIMATE_MB, ...(opts.signal ? { signal: opts.signal } : {}) },
);
- const frames = Float32Array.from(ssimScores(await readFile(whole, "utf8")));
+ 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"));
@@ -850,7 +864,7 @@ export async function compareWholeFile(
}
tiles.push({ index: k, col: k % G, row: Math.floor(k / G), min, minAt, longestBelow: longest, longestBelowAt: longestAt });
}
- return { frames, tiles, width: W, height: H, grid: G };
+ return { frames, chromaU, chromaV, tiles, width: W, height: H, grid: G };
} finally {
await rm(whole, { force: true }).catch(() => {});
await rm(graphFile, { force: true }).catch(() => {});
@@ -863,16 +877,106 @@ 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;
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.
+export function localFloors(f: Float32Array, windowFrames: number, k: number, margin: number): Float32Array {
+ const out = new Float32Array(f.length);
+ const half = Math.max(8, Math.floor(windowFrames / 2));
+ if (f.length <= windowFrames) {
+ out.fill(floorOf(f, k, margin).floor);
+ 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) => floorOf(f.subarray(s, s + half), k, margin).floor);
+ 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;
+ }
+ const a = left >= 0 ? floors[left] : Infinity;
+ const b = right >= 0 ? floors[right] : Infinity;
+ out[i] = Math.min(a, b) === Infinity ? floors[0] : Math.min(a, b);
+ }
+ return out;
+}
+
+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<WholeFileComparison, "frames" | "tiles">,
- t: { minFrame: number; meanFloor: number; sigmaK: number; sigmaMinMargin: number; tileRunFrames: number; expectedFrames: number; fps: number },
+ c: Pick<WholeFileComparison, "frames" | "tiles"> & Partial<Pick<WholeFileComparison, "chromaU" | "chromaV">>,
+ 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;
+ },
): WholeFileVerdict {
const f = c.frames;
let sum = 0;
@@ -886,26 +990,56 @@ export function judgeWholeFile(
}
}
const mean = f.length ? sum / f.length : 0;
- let v = 0;
- for (let i = 0; i < f.length; i += 1) v += (f[i] - mean) ** 2;
- const sd = f.length ? Math.sqrt(v / f.length) : 0;
- const relativeFloor = mean - Math.max(t.sigmaK * sd, t.sigmaMinMargin);
+ 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 local = localFloors(f, windowFrames, t.sigmaK, t.sigmaMinMargin);
+ 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 base = { mean, sd, min, minAt, relativeFloor, worstTile };
- if (f.length !== t.expectedFrames) {
- return { ...base, ok: false, why: `the comparison saw ${f.length} of the copy's ${t.expectedFrames} frames: it ends early or skips` };
+ const base = { mean, median, sd, min, minAt, relativeFloor, worstLocalMargin, worstLocalAt, windowFrames, worstTile, chroma };
+ 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 (min < relativeFloor) {
+ if (worstLocalMargin < 0) {
+ const i = worstLocalAt;
return {
...base,
ok: false,
- why: `a frame at ${at(minAt)} scores ${min.toFixed(4)}, below the file's own ${mean.toFixed(4)} − max(${t.sigmaK}·${sd.toFixed(4)}, ${t.sigmaMinMargin}) = ${relativeFloor.toFixed(4)}`,
+ 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) {
@@ -917,5 +1051,9 @@ export function judgeWholeFile(
`${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})` };
return { ...base, ok: true };
}
diff --git a/common/lib/compactingMarker-server.ts b/common/lib/compactingMarker-server.ts
@@ -20,7 +20,7 @@
// The compaction's own steps carry the marker's token, and pass where another
// writer is refused (the drop of the original under after-verify, F4).
-import { readFile, rm } from "node:fs/promises";
+import { link, readFile, rename, rm } from "node:fs/promises";
import { hostname } from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
@@ -151,15 +151,42 @@ export async function assertNotCompacting(storeDir: string, what: string, ownTok
}
// Remove a marker that is not live (or, with `token`, the caller's own).
-export async function clearCompactingMarker(storeDir: string, opts: { token?: string } = {}): Promise<{ cleared: boolean; why: string }> {
+//
+// NEVER A MARKER WRITTEN AFTER THE CHECK (review D3): a compaction may write a
+// fresh marker between this read and the removal. So the file is first
+// RENAMED aside (atomic), read again there, and removed only if it is still
+// the marker that was judged (same token); otherwise it is put back with a
+// link that refuses to overwrite (a newer marker at the path wins) and the
+// clear is refused.
+export async function clearCompactingMarker(
+ storeDir: string,
+ opts: { token?: string; beforeRemove?: () => Promise<void> } = {},
+): Promise<{ cleared: boolean; why: string }> {
const m = await readCompactingMarker(storeDir);
if (!m) return { cleared: false, why: "no marker" };
- if (opts.token && m.token === opts.token) {
- await rm(markerPath(storeDir), { force: true });
- return { cleared: true, why: "the compaction's own" };
+ let why: string;
+ if (opts.token && m.token === opts.token) why = "the compaction's own";
+ else {
+ const l = await markerLiveness(m);
+ if (l.live) return { cleared: false, why: `live: ${l.why} — cancel that job instead` };
+ why = `stale: ${l.why}`;
+ }
+ await opts.beforeRemove?.();
+ const p = markerPath(storeDir);
+ const aside = `${p}.clearing-${randomUUID()}`;
+ try {
+ await rename(p, aside);
+ } catch {
+ return { cleared: false, why: "the marker went meanwhile" };
+ }
+ const read = await readJsonFile(aside);
+ const token = read.ok && read.value && typeof read.value === "object" ? (read.value as { token?: unknown }).token : undefined;
+ if (token !== m.token) {
+ // A marker written after the check: it goes back where it was.
+ await link(aside, p).catch(() => {});
+ await rm(aside, { force: true });
+ return { cleared: false, why: "a new marker was written meanwhile: kept" };
}
- const l = await markerLiveness(m);
- if (l.live) return { cleared: false, why: `live: ${l.why} — cancel that job instead` };
- await rm(markerPath(storeDir), { force: true });
- return { cleared: true, why: `stale: ${l.why}` };
+ await rm(aside, { force: true });
+ return { cleared: true, why };
}
diff --git a/common/lib/compactingMarker.test.ts b/common/lib/compactingMarker.test.ts
@@ -94,3 +94,19 @@ test("this process's marker for a job the registry does not run is stale", async
await assert.rejects(assertNotCompacting(dir, "Persisting"), (e: Error) => e instanceof CompactionInProgressError);
});
});
+
+test("D3: a clear never deletes a marker written between its check and its removal", async () => {
+ await withDir(async (dir) => {
+ await write(dir, { pid: 2 ** 22 + 7, token: "stale" });
+ let fresh = "";
+ const r = await clearCompactingMarker(dir, {
+ beforeRemove: async () => {
+ // A compaction starts right here.
+ fresh = (await writeCompactingMarker(dir)).token;
+ },
+ });
+ assert.deepEqual(r, { cleared: false, why: "a new marker was written meanwhile: kept" });
+ assert.equal((await readCompactingMarker(dir))?.token, fresh);
+ assert.ok(await liveCompactingMarker(dir));
+ });
+});
diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts
@@ -165,6 +165,15 @@ export type SavedVideoCompactedChecks = {
tileFloor?: number;
tileRunFrames?: number;
worstTile?: { col: number; row: number; min: number; at: number; longestBelow: number };
+ // The median the relative floor is taken from (review D2).
+ median?: number;
+ // The local floor's window (seconds) and the worst frame's margin over
+ // its own neighbourhood's floor, and when (review E1).
+ windowSeconds?: number;
+ worstLocalMargin?: number;
+ worstLocalAt?: number;
+ // THE COLOUR (review D1): SSIM on the U and V planes, every frame.
+ chroma?: { mean: number; min: number; worstAt: number; plane: string; minFloor: number; meanFloor: number };
};
// Every stream but the video, and the chapters: what the source holds and
// the copy holds ("audio:aac", "subtitle:mov_text", "chapters:3", …).
@@ -489,6 +498,18 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null {
...(typeof w.grid === "number" ? { grid: w.grid } : {}),
...(typeof w.tileFloor === "number" ? { tileFloor: w.tileFloor } : {}),
...(typeof w.tileRunFrames === "number" ? { tileRunFrames: w.tileRunFrames } : {}),
+ ...(typeof w.median === "number" ? { median: w.median } : {}),
+ ...(typeof w.windowSeconds === "number" ? { windowSeconds: w.windowSeconds } : {}),
+ ...(typeof w.worstLocalMargin === "number" ? { worstLocalMargin: w.worstLocalMargin } : {}),
+ ...(typeof w.worstLocalAt === "number" ? { worstLocalAt: w.worstLocalAt } : {}),
+ ...(w.chroma && typeof w.chroma === "object"
+ ? (() => {
+ const c = obj(w.chroma);
+ return {
+ chroma: { mean: num(c.mean), min: num(c.min), worstAt: num(c.worstAt), plane: strOr(c.plane), minFloor: num(c.minFloor), meanFloor: num(c.meanFloor) },
+ };
+ })()
+ : {}),
...(w.worstTile && typeof w.worstTile === "object"
? (() => {
const t = obj(w.worstTile);
diff --git a/common/lib/savedVideoCompaction.test.ts b/common/lib/savedVideoCompaction.test.ts
@@ -169,3 +169,64 @@ test("the compacted copy has its own name, never the original's", () => {
"source-media.compact-av1-20261114031209-2.mp4",
);
});
+
+test("D2: the relative floor uses a robust spread, so a few bad frames cannot widen their own floor", async () => {
+ const { judgeWholeFile } = await import("./compactMedia-server");
+ const frames = new Float32Array(600).map((_, i) => 0.998 + ((i % 7) - 3) * 0.0002);
+ for (let i = 300; i < 320; i += 1) frames[i] = 0.93; // above the hard floor of 0.9
+ const t = { minFrame: 0.9, meanFloor: 0.97, sigmaK: 8, sigmaMinMargin: 0.03, tileRunFrames: 2, expectedFrames: 600, fps: 30, chromaMinFrame: 0.9, chromaMeanFloor: 0.97 };
+ const ones = new Float32Array(600).fill(1);
+ const v = judgeWholeFile({ frames, tiles: [], chromaU: ones, chromaV: ones }, t);
+ // mean − 8·sd would sit near 0.90 here; the median and MAD keep it near 0.968.
+ assert.ok(v.relativeFloor > 0.96, String(v.relativeFloor));
+ assert.equal(v.ok, false);
+ assert.match(v.why!, /below its neighbourhood's floor/);
+ frames.fill(0.998, 300, 320);
+ assert.equal(judgeWholeFile({ frames, tiles: [], chromaU: ones, chromaV: ones }, t).ok, true);
+ // The colour planes are judged on their own floors.
+ const u = new Float32Array(600).fill(0.999);
+ u[100] = 0.6;
+ const c = judgeWholeFile({ frames, tiles: [], chromaU: u, chromaV: ones }, t);
+ assert.equal(c.ok, false);
+ assert.match(c.why!, /the colour \(U plane\) of a frame at 3\.33 s scores 0\.600/);
+});
+
+// E1: the relative floor is local. The reviewer's synthetic hour: a good copy
+// whose picture has two modes (a webcam stretch at 0.965 inside a screen share
+// at 0.995) — 20%, 30% and 45% of it — PASSES on the defaults; a short defect
+// inside either mode still FAILS.
+test("E1: a good copy with two kinds of picture passes; a short defect in either still fails", async () => {
+ const { judgeWholeFile } = await import("./compactMedia-server");
+ const fps = 30;
+ const n = 3600 * fps;
+ const jitter = (i: number) => (((i * 7919) % 11) - 5) * 0.00012;
+ const t = { minFrame: 0.9, meanFloor: 0.97, sigmaK: 8, sigmaMinMargin: 0.03, tileRunFrames: 2, expectedFrames: n, fps, chromaMinFrame: 0.9, chromaMeanFloor: 0.97, windowFrames: 120 * fps };
+ const ones = new Float32Array(n).fill(1);
+ const make = (share: number, alternate = false) => {
+ const f = new Float32Array(n);
+ for (let i = 0; i < n; i += 1) {
+ const lower = alternate ? Math.floor(i / (300 * fps)) % 2 === 1 : i >= n * 0.3 && i < n * (0.3 + share);
+ f[i] = (lower ? 0.965 : 0.995) + jitter(i);
+ }
+ return f;
+ };
+ for (const share of [0.2, 0.3, 0.45]) {
+ const f = make(share);
+ const v = judgeWholeFile({ frames: f, tiles: [], chromaU: ones, chromaV: ones }, t);
+ assert.equal(v.ok, true, `${share}: ${v.why}`);
+ assert.ok(v.worstLocalMargin >= 0 && v.windowFrames === 3600, String(v.worstLocalMargin));
+ // A second of bad frames in the screen-share mode, and in the webcam mode.
+ for (const [at, score] of [[n * 0.1, 0.955], [n * (0.3 + share / 2), 0.92]] as const) {
+ const g = Float32Array.from(f);
+ g.fill(score, Math.floor(at), Math.floor(at) + fps);
+ const w = judgeWholeFile({ frames: g, tiles: [], chromaU: ones, chromaV: ones }, t);
+ assert.equal(w.ok, false, `${share} defect at ${at}`);
+ assert.match(w.why!, /below its neighbourhood's floor/);
+ }
+ }
+ // Five-minute stretches alternating all hour long.
+ assert.equal(judgeWholeFile({ frames: make(0, true), tiles: [], chromaU: ones, chromaV: ones }, t).ok, true);
+ // The whole-file floor of the round before rejected the 20% case.
+ const whole = judgeWholeFile({ frames: make(0.2), tiles: [], chromaU: ones, chromaV: ones }, { ...t, windowFrames: n });
+ assert.equal(whole.ok, false);
+});
diff --git a/common/lib/savedVideoCompaction.ts b/common/lib/savedVideoCompaction.ts
@@ -53,6 +53,9 @@ export type SavedVideoCompactionSettings = {
wholeFileSigmaMargin: number;
wholeFileTileMin: number;
wholeFileTileRunFrames: number;
+ wholeFileChromaMin: number;
+ wholeFileChromaMean: number;
+ wholeFileWindowSeconds: number;
availabilityMaxAgeDays: number;
dropOriginal: CompactionDropOriginal;
};
@@ -82,6 +85,9 @@ export const DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS: SavedVideoCompactionSettin
wholeFileSigmaMargin: 0.03,
wholeFileTileMin: 0.7,
wholeFileTileRunFrames: 2,
+ wholeFileChromaMin: 0.9,
+ wholeFileChromaMean: 0.97,
+ wholeFileWindowSeconds: 120,
availabilityMaxAgeDays: 7,
dropOriginal: "keep",
};
@@ -109,11 +115,16 @@ export const SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS: FieldDocs<SavedVideoCom
"THE WHOLE-FILE COMPARISON scores EVERY frame of the copy against the source's (256 px wide, grey, the source taken to the copy's rate, paired frame for frame): no frame may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern scores at least 0.996; one black frame scores 0).",
wholeFileSsimMean: "The whole-file comparison's mean must reach this. Default 0.97.",
wholeFileSigmaK:
- "The floor relative to the file itself: no frame below its mean − max(k × the frames' standard deviation, wholeFileSigmaMargin). Default k = 8 (measured: a good crf-36 copy has a spread of 0.0006, its worst frame 3 spreads under its mean).",
+ "The floor relative to the file's own frames NEARBY (wholeFileWindowSeconds): no frame below its neighbourhood's MEDIAN − max(k × its robust spread, wholeFileSigmaMargin). The spread is 1.4826 × the median absolute deviation, so a few bad frames cannot widen their own floor. Default k = 8 (measured: a good crf-36 copy's spread is about 0.0006).",
wholeFileSigmaMargin: "The least the relative floor sits under the mean, for a file whose frames barely differ. Default 0.03.",
wholeFileTileMin:
"Each frame is also split into an 8×8 grid of tiles, each scored on its own, so a change to a small region is not averaged away: a tile below this for more than wholeFileTileRunFrames frames in a row fails. Default 0.7 (a good crf-36 copy's lowest tile: 0.949; a red box over 1% of the picture: 0.46).",
wholeFileTileRunFrames: "How many frames in a row a tile may sit below wholeFileTileMin. Default 2: a 3-frame defect at 30 fps fails.",
+ wholeFileChromaMin:
+ "THE COLOUR, every frame: the whole-file comparison also scores the U and V planes (SSIM), which the grey comparison and VMAF do not see — a hue shift, chroma-only noise. No frame's lower plane may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern: lowest 0.991).",
+ wholeFileChromaMean: "The colour planes' mean must reach this. Default 0.97 (good copy: 0.9986).",
+ wholeFileWindowSeconds:
+ "The NEIGHBOURHOOD the relative floor is taken over: each frame is judged against the frames in the half-window just before it and just after it (the lower of their two floors), so a stream alternating two kinds of picture (a webcam, a screen share) is judged stretch by stretch, not by the file's dominant mode. A short defect inside a steady stretch has that stretch on both sides and falls below it. A degraded stretch longer than the window looks steady to it: such a stretch is caught by the absolute per-frame floor, the tile grid, the mean floor, and the VMAF excerpts, one at least every window across the whole file. Default 120 s; 5–3600.",
availabilityMaxAgeDays:
"How fresh the platform check must be for a video to count as still on its platform: an availability record written by a real check (not a backfill), public or unlisted, at most this many days old. Anything else counts as gone, and its original waits for a person's review. Default 7.",
dropOriginal:
@@ -158,6 +169,9 @@ export function sanitizeSavedVideoCompaction(value: unknown): SavedVideoCompacti
wholeFileSigmaMargin: clampNum(r.wholeFileSigmaMargin, d.wholeFileSigmaMargin, 0, 1),
wholeFileTileMin: clampNum(r.wholeFileTileMin, d.wholeFileTileMin, 0, 1),
wholeFileTileRunFrames: Math.round(clampNum(r.wholeFileTileRunFrames, d.wholeFileTileRunFrames, 0, 300)),
+ wholeFileChromaMin: clampNum(r.wholeFileChromaMin, d.wholeFileChromaMin, 0, 1),
+ wholeFileChromaMean: clampNum(r.wholeFileChromaMean, d.wholeFileChromaMean, 0, 1),
+ wholeFileWindowSeconds: clampNum(r.wholeFileWindowSeconds, d.wholeFileWindowSeconds, 1, 3600),
availabilityMaxAgeDays: clampNum(r.availabilityMaxAgeDays, d.availabilityMaxAgeDays, 0, 365),
dropOriginal: (COMPACTION_DROP_ORIGINAL as readonly unknown[]).includes(r.dropOriginal)
? (r.dropOriginal as CompactionDropOriginal)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -148,6 +148,11 @@
through the drop and checked against boot, host, pid start time and job. Stale ones are swept, and listed or
cleared with `compaction-markers`. The prune goes on past a video it may not drop. An interrupted drop of any
alternate is listed (`pendingDrops`) and finished by asking again.
+ - The whole-file comparison scores the colour (U and V planes) every frame too: a hue shift or chroma-only noise
+ fails it, and "after-verify" needs both the luma and the colour record. Its relative floor uses the median and a
+ robust spread over each frame's own two-minute neighbourhood (`wholeFileWindowSeconds`), so a stream alternating
+ two kinds of picture passes; a VMAF excerpt is laid at least every window. A negative plane score is read as
+ one. Clearing a marker never removes one written after the check.
- **ROLLBACK: do not roll the editor back past this release while `pnpm ops get kept-originals` lists anything.**
An older editor does not know `"keptAs": "original"` / `"former-original"`, would treat them as ordinary
alternates, and could prune or drop the only original.
diff --git a/settings.json.example b/settings.json.example
@@ -173,6 +173,9 @@
"wholeFileSigmaMargin": 0.03,
"wholeFileTileMin": 0.7,
"wholeFileTileRunFrames": 2,
+ "wholeFileChromaMin": 0.9,
+ "wholeFileChromaMean": 0.97,
+ "wholeFileWindowSeconds": 120,
"availabilityMaxAgeDays": 7,
"dropOriginal": "keep"
},