Archilyzer · Source

archilyzer

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

commit 1cb48dcb8eaccd6c83ef6cfae9449dbaeb5ab401
parent c064a3daeb5b3fc0daefaee993bb425b23d60fce
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 01:27:17 -0500

compaction follow-ups: the colour compared, a robust relative floor, a race-free marker clear

- D1. The whole-file comparison also scores the U and V planes, every frame
  (the same run: the whole-frame SSIM now reads yuv420p, its stats give Y, U
  and V apart; the tiles stay grey), against wholeFileChromaMin (0.9) and
  wholeFileChromaMean (0.97), recorded on the pointer. A good SVT-AV1 crf-36
  copy of a 640x360 test pattern: lowest 0.991, mean 0.9986. A 3 s hue shift
  (0.04) and 3 s of chroma-only noise (0.47) fail. "after-verify" drops only
  when the pointer records both the luma and the colour comparison.
- D2. The relative floor is the median minus max(8 x 1.4826 x MAD, 0.03): a
  few bad frames can no longer widen their own floor.
- D3. A clear renames the marker aside, reads it there, and removes it only if
  it is still the one judged stale; a marker written meanwhile goes back.

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

Diffstat:
MOPERATING.md | 11+++++++++--
MSETTINGS.md | 6+++++-
Mcommon/controller/compactSavedVideos.test.ts | 5+++++
Mcommon/controller/compactSavedVideos.ts | 16++++++++++++++--
Mcommon/lib/compactMedia-server.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mcommon/lib/compactingMarker-server.ts | 45++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/compactingMarker.test.ts | 16++++++++++++++++
Mcommon/lib/savedVideo.ts | 13+++++++++++++
Mcommon/lib/savedVideoCompaction.test.ts | 21+++++++++++++++++++++
Mcommon/lib/savedVideoCompaction.ts | 11++++++++++-
Meditor/CHANGELOG.md | 3+++
Msettings.json.example | 2++
12 files changed, 209 insertions(+), 31 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1206,7 +1206,13 @@ 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 taken from the median and a robust spread + (1.4826 × the median absolute deviation), so a few bad frames cannot widen their own floor. 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 +1244,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,12 @@ 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 itself: no frame below its 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). | | `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 +688,8 @@ Default: "wholeFileSigmaMargin": 0.03, "wholeFileTileMin": 0.7, "wholeFileTileRunFrames": 2, + "wholeFileChromaMin": 0.9, + "wholeFileChromaMean": 0.97, "availabilityMaxAgeDays": 7, "dropOriginal": "keep" } diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts @@ -838,6 +838,9 @@ 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)], ]; for (const [label, defect] of defects) { await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 12, fps: 30, gop: 30 } }, async (fx) => { @@ -864,6 +867,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)); }); }); diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts @@ -1069,6 +1069,8 @@ async function verify(o: { tileRunFrames: s.wholeFileTileRunFrames, expectedFrames: n, fps: outFps, + chromaMinFrame: s.wholeFileChromaMin, + chromaMeanFloor: s.wholeFileChromaMean, }); checks.wholeFile = { fps: outFps, @@ -1081,7 +1083,16 @@ async function verify(o: { meanFloor: s.wholeFileSsimMean, maxGapSeconds: round(gap, 4), sd: round(v.sd, 5), + median: round(v.median, 4), 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 +1111,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"}.`, ); @@ -1261,8 +1273,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 @@ -756,16 +756,21 @@ 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[] = []; + const re = new RegExp(`${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 +804,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 +833,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 +862,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 +875,44 @@ 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; 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; +} + +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; + }, ): WholeFileVerdict { const f = c.frames; let sum = 0; @@ -886,18 +926,33 @@ 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); 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, 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})` }; @@ -905,7 +960,7 @@ export function judgeWholeFile( 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(minAt)} scores ${min.toFixed(4)}, below the file's own median ${median.toFixed(4)} − max(${t.sigmaK}·${sd.toFixed(4)}, ${t.sigmaMinMargin}) = ${relativeFloor.toFixed(4)}`, }; } if (worstTile && worstTile.longestBelow > t.tileRunFrames) { @@ -917,5 +972,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,10 @@ 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 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 +493,15 @@ 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 } : {}), + ...(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,24 @@ 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 the file's own median/); + 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/); +}); diff --git a/common/lib/savedVideoCompaction.ts b/common/lib/savedVideoCompaction.ts @@ -53,6 +53,8 @@ export type SavedVideoCompactionSettings = { wholeFileSigmaMargin: number; wholeFileTileMin: number; wholeFileTileRunFrames: number; + wholeFileChromaMin: number; + wholeFileChromaMean: number; availabilityMaxAgeDays: number; dropOriginal: CompactionDropOriginal; }; @@ -82,6 +84,8 @@ export const DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS: SavedVideoCompactionSettin wholeFileSigmaMargin: 0.03, wholeFileTileMin: 0.7, wholeFileTileRunFrames: 2, + wholeFileChromaMin: 0.9, + wholeFileChromaMean: 0.97, availabilityMaxAgeDays: 7, dropOriginal: "keep", }; @@ -109,11 +113,14 @@ 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 itself: no frame below its 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).", 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 +165,8 @@ 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), 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 @@ -32,6 +32,9 @@ 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. 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,8 @@ "wholeFileSigmaMargin": 0.03, "wholeFileTileMin": 0.7, "wholeFileTileRunFrames": 2, + "wholeFileChromaMin": 0.9, + "wholeFileChromaMean": 0.97, "availabilityMaxAgeDays": 7, "dropOriginal": "keep" },