Archilyzer · Source

archilyzer

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

commit f290379c4c34c9f241c19b34defd73147c9562f7
parent e9a0665a1b06a34e0414cfbdeae0e0f7eb7f9cc0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 11:04:57 -0500

compact-saved-videos: frames kept by time, a decode judged by its errors, a join's segment change told from a bad chunk, scratch removed with its video

Review of 9e69d6247 + e9a0665a1, before the second real run.

G1. The full decode failed a CORRECT copy of a 59.94 source with one dropped
frame: decoded into the null muxer at the copy's nominal 1001/30000 time
base, two kept frames rounded to one tick and the muxer printed "non
monotonically increasing dts ... 600 >= 600", and any stderr counted as
failure. The decode now keeps each stream's time base (-enc_time_base
demux), and its stderr is classified: fatal is a non-zero exit or a line
naming damage (error, invalid, corrupt, conceal, missing, non-existing,
overread, out of range, illegal, damaged, truncated, unavailable, failed,
mmco, desync, no frame, broken); benign is the muxer's dts line; anything
else is a note (checks.decodeNotes). The other decodes of the verification
were audited: the whole-file comparison, the excerpts and the cut pairing
renumber frames to integer pts in a 1/rate time base before anything
muxes them; the audio hash is a stream copy; the window cuts go through the
evidence cutter as in production, from a kept frame, across no gap.

G2. A good copy failed when a harder segment started at a chunk join. The
comparison's decode of the source now also measures each frame's picture
detail (the mean of a Sobel edge map); a chunk that drops at a join where
the SOURCE's detail changes by 10 % or more over the same 5 s is exempt
("the source changes at its join"). A bad chunk of unchanged picture still
fails, and its message names the join and its time, says it may still be a
segment there, and gives the way forward (look at the source there; a run
with another chunkMinutes puts the joins elsewhere).

G3. The kept scratch was orphaned when a video's pointer went: unpersist and
the prune's drop now remove .compact-scratch after the same guards, and
kept-failed-encodes also lists any scratch in the store with no pointer as
orphaned and clears it. pruneEmptyStoreDirs called rm without recursive,
which refuses every directory (EISDIR), so it never removed an empty store
dir; it uses rmdir now.

G4. "Every other frame by index" gave 15 fps where a recording ran at 30 for
a stretch. Frames are kept by TIME: a frame when at least one copy frame
less half a source tick has passed since the last kept one, each at its own
pts. The kept set is decided once from the packet scan and saved in the
scratch state as runs; each chunk's select (built from it), the chunk-start
rule (a kept keyframe), the expected timestamps and the source side of the
whole-file comparison, excerpts and cuts all read it. A constant 60 fps
source keeps the same frames at the same times as before.

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

Diffstat:
MOPERATING.md | 27+++++++++++++++++++++------
Mcommon/controller/compactSavedVideos.test.ts | 136++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/compactSavedVideos.ts | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcommon/lib/compactMedia-server.ts | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/lib/savedVideo-server.ts | 20++++++++++++++++----
Mcommon/lib/savedVideo.ts | 14++++++++++++--
Mcommon/lib/savedVideoCompaction.test.ts | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 8++++++--
8 files changed, 568 insertions(+), 57 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1164,11 +1164,14 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} `fetch_clip` answer all say it is a re-encode. - **The source's timestamps are kept.** A live Kick or Twitch recording drops frames, mid-stream as well as at the end, so its frames are not evenly spaced. The copy keeps every frame's own presentation time: - - 60 → 30 keeps every other source frame by index (`select`), each at its source time. Not `framestep`: it + - 60 → 30 keeps a source frame when at least one copy frame (less half a source tick) has passed since the last + kept frame: a frame by TIME, each at its source time. A 60 fps stretch keeps every other frame, a stretch where + the recording ran at 30 keeps every frame (by index it kept 15 fps there), and after a gap the next frame. The + kept frames are decided once from the packet scan and saved in the scratch state. Each chunk's `select` and + every check (the timestamps, the whole-file comparison, the excerpts, the cuts) read them. Not `framestep`: it re-times what it keeps, and after an odd gap it wrote a frame the source does not have. Any other ratio goes through the fps filter's constant grid, which repeats a frame across a gap, so the sync is still kept. - - A chunk starts on a keyframe whose index in the file is a multiple of that ratio. After an odd gap the time grid - and the index grid part. + - A chunk starts on a kept keyframe, so each chunk's own selection is the file's. - The join puts each chunk at its source time (the concat list's `duration`, the span to the next chunk's first frame), not where the chunk before it happened to end. @@ -1212,7 +1215,12 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} - **The checks.** Every one must pass, or the original stays active and untouched. EVERY CHECK RUNS and records its own result, so one failed run lists every failure (`failed.json` `failures`); only a copy that cannot be opened stops the list. The reasons are in the log, the result and `.compact-scratch/failed.json`. The checks: - - a full decode without an error; + - a full decode without an error. Each stream keeps its own time base (`-enc_time_base demux`): re-quantised + to the copy's nominal 1001/30000, two frames around a dropped one landed on one tick and the null muxer + complained about nothing in the picture. Fatal: a non-zero exit, or a line naming damage (error, invalid, + corrupt, conceal, missing, non-existing, overread, out of range, illegal, damaged, truncated, unavailable, + failed, mmco, desync, no frame, broken). Benign: the muxer's "non monotonically increasing dts". Any other line + is a note (`checks.decodeNotes`); - THE TIMESTAMPS, every frame (`checks.timestamps`): each copy frame at the time its source frame had, relative to each file's start, within `PTS_TOLERANCE_SECONDS` (1 ms: Matroska keeps milliseconds, mp4 at 90 kHz is exact). The pointer records the worst deviation, where, and the worst in each chunk: the picture against the sound @@ -1260,7 +1268,12 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} margin; or - neither of its joins shows the drop: the 5 s just inside the chunk score within half the drop of the 5 s just outside. A bad encode of a chunk changes level at its joins; a harder scene that runs across chunks (a game hour - in a talk stream) changes level where the scene changes. + in a talk stream) changes level where the scene changes; + - or the SOURCE itself changes at every join where the copy drops: its picture detail (the mean of a Sobel edge + map, per frame, from the decode the comparison already makes) differs by 10 % or more over the same 5 s. That + is a scheduled segment starting right at a join. A bad chunk of unchanged picture still fails, and its message + names the join and its time, says it may still be a segment change there, and gives the way forward: look at the + source there, or run with another `chunkMinutes`, which puts the joins elsewhere (it encodes again). `"after-verify"` drops only when the pointer records the luma, the colour and the per-chunk comparison; - VMAF on 2-second excerpts across every chunk join, inside every chunk, and at `qualitySamples` (12) more spread @@ -1277,7 +1290,9 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} A chunk whose own content failed (a frame count, the per-chunk comparison) is encoded again. - `"retryFailed": true`, or changed encode settings, encodes it all again. - `pnpm ops kept-failed-encodes` lists them with their size, and `{"clear": {"slug", "id"}}` removes one. A - compaction that is running is refused. + compaction that is running is refused. It also lists, as `orphaned`, any scratch in the store whose video has + no pointer any more, and clears those the same way. + - When the pointer goes (unpersist, the prune's drop), its scratch goes with it, after the same guards. The disk they hold is the store's: the floor of every later run sees less free space, and a re-verify needs room only for what it encodes again. diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts @@ -23,11 +23,23 @@ import { cutIsOffset, encodeChunkArgs, ffmpegHas, + fullDecode, + keptSourceFrames, + planChunks, + scanVideoPackets, type ChunkPlan, type EncodeSettings, } from "../lib/compactMedia-server"; import { DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, type SavedVideoCompactionSettings } from "../lib/savedVideoCompaction"; -import { SavedPointerChangedError, loadSavedVideo, persistSourceVideo, restoreSavedVideoProvenance, savedVideoPointerPath } from "../lib/savedVideo-server"; +import { + SavedPointerChangedError, + dropSavedVideo, + loadSavedVideo, + persistSourceVideo, + restoreSavedVideoProvenance, + savedVideoPointerPath, + unpersistSavedVideo, +} from "../lib/savedVideo-server"; import { compactedOriginalOf, savedVideoPath } from "../lib/savedVideo"; import { keepDownloadAsAlternate, planSavedContainer } from "../ytdlp/savedAlternates"; import { CLOCK_FILE, CLOCK_VERSION } from "../lib/recordingClock.mjs"; @@ -71,6 +83,8 @@ type Gen = { // A LIVE RECORDING'S DROPPED FRAMES: source frames [from, to] removed, every // other frame keeping its own timestamp (a gap, as a Kick stream has). drop?: [number, number][]; + // …or the same as one select expression of n (dropped where true). + dropExpr?: string; // A white frame pair at this second, and a click in the sound at the same // second: whether picture and sound still meet after a gap. flash?: number; @@ -82,6 +96,7 @@ async function makeSource(file: string, g: Gen = {}): Promise<void> { const vf = [ ...(g.flash !== undefined ? [`drawbox=c=white:t=fill:enable='between(t,${g.flash - 0.001},${g.flash + 0.03})'`] : []), ...(g.drop?.length ? [`select='not(${g.drop.map(([a, b]) => `between(n,${a},${b})`).join("+")})'`] : []), + ...(g.dropExpr ? [`select='not(${g.dropExpr})'`] : []), ]; const sound = g.flash !== undefined @@ -1187,3 +1202,122 @@ test("a tail gap (the first real run's source) and a 59.94 fps source pass", { s }); } }); + +// Review G1: a correct copy of a source with a dropped frame was failed by a +// null-muxer line. On the DEFAULT checks, with the real encoder. +test("G1: a 59.94 fps source with one dropped frame ends compacted on the default checks", { skip: NO_SVT }, async () => { + await withVideo({ gen: { seconds: 8, fps: "60000/1001", drop: [[301, 301]] } }, async (fx) => { + const log = logger(); + const settings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3, dropOriginal: "keep" as const }; + const r = await run(fx, { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15 }, settings, log.onLog); + assert.equal(r.status, "compacted", log.lines.join("\n")); + const c = (await loadSavedVideo(fx.videoDir))!.compacted!.checks; + assert.equal(c.decoded, true); + assert.equal(c.sourceGaps?.count, 1); + assert.equal(c.timestamps?.over, 0); + }); +}); + +test("G1: the full decode keeps each stream's time base; only damage is fatal", { skip: NO_TOOLS }, async () => { + const d = await mkdtemp(path.join(tmpdir(), "compact-dec-")); + try { + // Frames half a tick off the nominal 1001/30000 grid: re-quantised to it, + // two land on one tick and the null muxer complains. + const f = path.join(d, "ticks.mp4"); + await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=30000/1001:d=3", + "-vf", "setpts='(N+if(eq(N\\,10)\\,0.5\\,0))*1001/30000/TB'", "-fps_mode", "passthrough", "-c:v", "libx264", "-video_track_timescale", "90000", f]); + const old = await execa("ffmpeg", ["-nostdin", "-hide_banner", "-v", "error", "-xerror", "-i", f, "-map", "0:v:0", "-f", "null", "-"], { reject: false }); + assert.match(String(old.stderr), /non monotonically increasing dts/, "the old invocation's complaint"); + const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "" }; + assert.deepEqual(await fullDecode(paths, f), { ok: true }); + // A damaged file still fails. + const bad = path.join(d, "bad.mp4"); + const bytes = await readFile(f); + for (let i = Math.floor(bytes.length / 3); i < Math.floor(bytes.length / 3) + 4000; i += 1) bytes[i] = 0; + await writeFile(bad, bytes); + assert.equal((await fullDecode(paths, bad)).ok, false); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); + +// Review G3: a kept failed encode goes with its video's pointer; one left +// behind before this is listed as orphaned and can be cleared. +test("G3: unpersist and drop remove a kept failed encode; an orphaned one is listed and cleared", { skip: NO_TOOLS }, async () => { + for (const how of ["unpersist", "drop"] as const) { + await withVideo({}, async (fx) => { + await run(fx, flowDeps({ score: async () => 42 })); + const scratch = path.join(fx.storeDir, ".compact-scratch"); + await stat(scratch); + if (how === "unpersist") assert.equal(await unpersistSavedVideo(fx.videoDir), true); + else await dropSavedVideo(fx.videoDir); + await assert.rejects(stat(scratch), how); + const left = (await readdir(fx.storeDir).catch(() => [] as string[])).join(", "); + await assert.rejects(stat(fx.storeDir), `${how}: the store dir goes when empty (left: ${left})`); + }); + } + await withVideo({}, async (fx) => { + await run(fx, flowDeps({ score: async () => 42 })); + // A pointer removed by hand (as a release before this one left it). + await rm(savedVideoPointerPath(fx.videoDir)); + const rows = await listKeptFailedEncodes(fx.paths); + assert.equal(rows.length, 1); + assert.equal(rows[0].orphaned, true); + assert.ok((rows[0].bytes ?? 0) > 0); + const c = await clearKeptFailedEncode(fx.paths, { slug: "kick", id: "v1" }); + assert.equal(c.cleared, true, c.why); + assert.match(c.why, /orphaned/); + await assert.rejects(stat(path.join(fx.storeDir, ".compact-scratch"))); + assert.deepEqual(await listKeptFailedEncodes(fx.paths), []); + }); +}); + +// Review G4: a recording that ran at 30 fps for a stretch keeps 30 fps there. +test("G4: a 60 fps source with a 30 fps stretch keeps 30 fps throughout, each frame at its source time", { skip: NO_TOOLS }, async () => { + // Frames 120–359 at 30 fps (every odd one missing), and an odd gap later. + const gen: Gen = { seconds: 10, fps: 60, gop: 45, dropExpr: "between(n,121,359)*mod(n,2)+between(n,450,452)" }; + await withVideo({ gen }, async (fx) => { + const log = logger(); + const r = await run(fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), { ...SETTINGS, dropOriginal: "keep" }, log.onLog); + assert.equal(r.status, "compacted", log.lines.join("\n")); + const p = (await loadSavedVideo(fx.videoDir))!; + const copy = await ptsOf(path.join(fx.storeDir, p.file)); + const src = await ptsOf(fx.source); + assert.ok(copy.every((x) => src.some((y) => Math.abs(x - y) < 0.0005)), "every copy frame is a source frame at its time"); + for (let i = 1; i < copy.length; i += 1) { + const d = copy[i] - copy[i - 1]; + const acrossGap = copy[i - 1] <= 449 / 60 + 1e-6 && copy[i] >= 453 / 60 - 1e-6; + assert.ok(d > 1 / 30 - 0.001 && (acrossGap || d < 1 / 30 + 0.001), `${copy[i - 1]} -> ${copy[i]}`); + } + const stretch = src.filter((x) => x >= 2 && x < 6); + assert.equal(copy.filter((x) => x >= 2 && x < 6).length, stretch.length, "the 30 fps stretch keeps every frame"); + assert.equal(p.compacted!.checks.timestamps?.over, 0); + }); +}); + +test("G4: a constant 60 fps source decimates to the same frames and times as before", { skip: NO_TOOLS }, async () => { + const d = await mkdtemp(path.join(tmpdir(), "compact-cfr-")); + try { + const src = path.join(d, "src.mp4"); + await makeSource(src, { seconds: 4, fps: 60 }); + const scan = await scanVideoPackets("ffprobe", src); + const kept = keptSourceFrames(scan.pts, 30, 1 / 15360); + const chunk = planChunks(scan, 60, 30, 60, kept)[0]; + const s = { preset: 8, crf: 36, gopSeconds: 5, pixFmt: "yuv420p", fps: 30, sourceFps: 60, formatStart: 0 }; + const hashes: string[] = []; + for (const label of ["previous", "now"]) { + const out = path.join(d, `${label}.mp4`); + const args = encodeChunkArgs(src, label === "now" ? chunk : { ...chunk, select: undefined }, s, out); + const i = args.indexOf("libsvtav1"); + args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", "18"); + stripSvt(args); + if (label === "previous") assert.ok(args.includes("select='not(mod(n,2))',setpts=PTS-STARTPTS"), args.join(" ")); + await execa("ffmpeg", args); + const md = await execa("ffmpeg", ["-v", "error", "-i", out, "-map", "0:v", "-f", "framemd5", "-"]); + hashes.push(String(md.stdout).split("\n").filter((l) => l && !l.startsWith("#")).join("\n")); + } + assert.equal(hashes[1], hashes[0], "the same frames at the same times (framemd5 carries both)"); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts @@ -105,9 +105,12 @@ import { concatList, countVideoFrames, expectedCopyPts, + keptSourceFrames, nominalFps, + selectExpr, sourceGaps, wholeRatio, + type KeptRuns, type SourceGaps, cutIsOffset, encodeChunkArgs, @@ -154,7 +157,8 @@ export const FAILED_COPY_BASENAME = "failed-copy"; // millisecond (half of one at most), an mp4 at 90 kHz keeps them exactly. export const PTS_TOLERANCE_SECONDS = 0.001; // 3: the source's timestamps kept (a chunk encoded before is not reused). -const STATE_VERSION = 3; +// 4: the kept frames decided by time (review G4) and saved. +const STATE_VERSION = 4; export type Presence = { onPlatform: boolean; availability: Availability | null; why: string }; @@ -173,14 +177,14 @@ export type CompactDeps = { encodeChunk?: (o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string; signal?: AbortSignal }) => Promise<void>; countFrames?: (file: string) => Promise<number>; mux?: (o: { list: string; src: string; probe: SourceProbe; out: string; signal?: AbortSignal }) => Promise<void>; - fullDecode?: (file: string, signal?: AbortSignal) => Promise<{ ok: boolean; why?: string }>; + fullDecode?: (file: string, signal?: AbortSignal) => Promise<{ ok: boolean; why?: string; notes?: string[] }>; audioHash?: (file: string, signal?: AbortSignal) => Promise<AudioHash>; inventory?: (file: string, skipIndex: number) => Promise<string[]>; wholeFile?: (o: Parameters<typeof compareWholeFile>[1]) => Promise<WholeFileComparison>; hasVmaf?: () => Promise<boolean>; // `at` the copy's seek time, `sourceAt` the same frame's in the source. - score?: (o: { compacted: string; source: string; at: number; sourceAt?: number; seconds: number; fps: number | null; sourceFps: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal }) => Promise<number>; - cutCompare?: (o: { compacted: string; source: string; at: number; sourceAt?: number; seconds: number; fps: number | null; sourceFps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise<CutComparison>; + score?: (o: { compacted: string; source: string; at: number; sourceAt?: number; sourceSelect?: string; seconds: number; fps: number | null; sourceFps: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal }) => Promise<number>; + cutCompare?: (o: { compacted: string; source: string; at: number; sourceAt?: number; sourceSelect?: string; seconds: number; fps: number | null; sourceFps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise<CutComparison>; // Where ffmpeg's command line starts a file's timeline (cliTimelineStart). timelineStart?: (file: string, firstVideoPts: number) => Promise<number>; measureClock?: (o: { videoDir: string; source: string; container: string; sourceBytes: number; targetBytes: number; transcribedAt: string | null; extra: number[]; signal?: AbortSignal }) => Promise<RecordingClock>; @@ -550,6 +554,9 @@ type CompactState = { sourceFps?: number | null; // The recording's dropped frames (kept as gaps in the copy). sourceGaps?: SourceGaps; + // Under a whole ratio: the source frames the copy keeps (keptSourceFrames), + // decided once here; every chunk's `select` and every check read it. + kept?: KeptRuns; chunks: ChunkState[]; }; @@ -759,7 +766,9 @@ async function compactPlanned( log(`${tag}: scanning ${pointer.file}'s packets (frame count, keyframes)…`); const scan = await deps.scan(src, signal); const nominal = nominalFps(scan.pts) ?? probe.fps; - const plan = planChunks(scan, s.chunkMinutes * 60, fps, nominal); + const m = wholeRatio(nominal, fps); + const kept = m && nominal ? keptSourceFrames(scan.pts, nominal / m, probe.timeBase ?? 1e-6) : undefined; + const plan = planChunks(scan, s.chunkMinutes * 60, fps, nominal, kept); if (!plan.length) return { status: "failed", reason: "the source has no video packets" }; const n = scan.pts.length; state = { @@ -776,6 +785,7 @@ async function compactPlanned( sourceMaxGap: maxGap(scan.pts), sourceFps: nominal, sourceGaps: sourceGaps(scan.pts), + ...(kept ? { kept } : {}), chunks: plan.map((c) => ({ ...c, file: `chunk-${String(c.index).padStart(4, "0")}${CHUNK_EXT}`, done: false })), }; await writeState(); @@ -1140,6 +1150,9 @@ async function verify(o: { log(`${tag}: verifying — a full decode first…`); const dec = await deps.fullDecode(o.muxed, signal); checks.decoded = dec.ok; + // Lines the decode printed that are not damage (a null-muxer timestamp + // line, anything unrecognised): kept, never fatal. + if (dec.notes?.length) checks.decodeNotes = dec.notes; if (!dec.ok) fail(`the re-encode does not decode cleanly: ${dec.why ?? "errors"}`); // THE TIMESTAMPS, every frame (review, the first real run): the copy keeps @@ -1152,7 +1165,25 @@ async function verify(o: { const [outScan, srcScan] = await Promise.all([deps.scan(o.muxed, signal), deps.scan(o.src, signal)]); const n = outScan.pts.length; const ratio = wholeRatio(srcFps, o.fps); - const expectedPts = expectedCopyPts(srcScan.pts, state.chunks, ratio, o.fps && !ratio ? o.fps : null); + const expectedPts = expectedCopyPts(srcScan.pts, state.chunks, ratio, o.fps && !ratio ? o.fps : null, state.kept); + // The kept frames' `select` for a decode of the source starting at the + // frame at `absPts` and running `seconds` (+1 s), or from its first frame. + const findIndex = (t: number) => { + let lo = 0; + let hi = srcScan.pts.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (srcScan.pts[mid] < t - 1e-6) lo = mid + 1; + else hi = mid; + } + return lo; + }; + const keptSelect = (absPts?: number, seconds = 0): string | undefined => { + if (!state.kept) return undefined; + if (absPts === undefined) return selectExpr(state.kept, 0, srcScan.pts.length); + const g0 = findIndex(absPts); + return selectExpr(state.kept, g0, Math.max(g0 + 1, findIndex(absPts + seconds + 1))); + }; const expected = state.chunks.reduce((x, c) => x + c.expectedFrames, 0); checks.frames = [state.sourceFrames, n, expected]; if (n !== expected) fail(`the re-encode holds ${n} frames, not the ${expected} the source's ${state.sourceFrames} give${o.fps ? ` at ${o.fps} fps` : ""}`); @@ -1281,6 +1312,7 @@ async function verify(o: { scratchDir: o.scratch, fps: o.fps, sourceFps: srcFps, + ...(state.kept ? { sourceSelect: keptSelect() } : {}), sourceWidth: o.probe.width, sourceHeight: o.probe.height, tileFloor: s.wholeFileTileMin, @@ -1350,7 +1382,14 @@ async function verify(o: { sigmaK: v.chunks.sigmaK, margin: v.chunks.margin, worst: v.chunks.worst - ? { chunk: v.chunks.worst.index, plane: v.chunks.worst.plane, mean: round(v.chunks.worst.mean, 4), centre: round(v.chunks.worst.centre, 4), floor: round(v.chunks.worst.floor, 4) } + ? { + chunk: v.chunks.worst.index, + plane: v.chunks.worst.plane, + mean: round(v.chunks.worst.mean, 4), + centre: round(v.chunks.worst.centre, 4), + floor: round(v.chunks.worst.floor, 4), + ...(v.chunks.worst.joinAt !== undefined ? { joinAt: round(v.chunks.worst.joinAt / outFps, 3) } : {}), + } : null, exempt: v.chunks.exempt.map((x) => ({ chunk: x.index, plane: x.plane, why: x.why })), }; @@ -1384,9 +1423,10 @@ async function verify(o: { const scores: number[] = []; for (const rel of [...times].sort((x, y) => x - y)) { const { at, sourceAt } = seekPair(rel); + const sourceSelect = keptSelect(rel + o.probe.formatStart, EXCERPT_SECONDS); if (signal?.aborted) throw new Error("cancelled"); scores.push( - await deps.score({ compacted: o.muxed, source: o.src, at, sourceAt, seconds: EXCERPT_SECONDS, fps: o.fps, sourceFps: srcFps, metric, scratchDir: o.scratch, signal }), + await deps.score({ compacted: o.muxed, source: o.src, at, sourceAt, ...(sourceSelect ? { sourceSelect } : {}), seconds: EXCERPT_SECONDS, fps: o.fps, sourceFps: srcFps, metric, scratchDir: o.scratch, signal }), ); } const mean = scores.reduce((x, y) => x + y, 0) / Math.max(1, scores.length); @@ -1406,7 +1446,8 @@ async function verify(o: { checks.cutSsimMin = CUT_SSIM_MIN; for (const rel of cutTimes) { const { at, sourceAt } = seekPair(rel); - const c = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, sourceAt, seconds: CUT_SECONDS, fps: o.fps, sourceFps: srcFps, scratchDir: o.scratch, signal }); + const sourceSelect = keptSelect(rel + o.probe.formatStart, CUT_SECONDS); + const c = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, sourceAt, ...(sourceSelect ? { sourceSelect } : {}), seconds: CUT_SECONDS, fps: o.fps, sourceFps: srcFps, scratchDir: o.scratch, signal }); checks.cuts.push({ at, ssim: round(c.ssim, 4) }); if (c.ssim < CUT_SSIM_MIN) fail(`a window cut at ${at.toFixed(1)} s from the re-encode differs from the same cut of the original (SSIM ${c.ssim.toFixed(3)} < ${CUT_SSIM_MIN})`); if (cutIsOffset(c)) { @@ -1766,32 +1807,73 @@ export type KeptFailedEncodeRow = { reason: string; failedChunks: number[]; kept: KeptFailedEncode | null; + // A scratch in the store with NO POINTER naming its dir (review G3: left + // by a removal before this release, or an interrupted one): nothing will + // ever re-verify it; clear it. + orphaned?: boolean; + bytes?: number; }; +async function dirBytes(dir: string): Promise<number> { + let n = 0; + for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + const p = path.join(dir, e.name); + if (e.isDirectory()) n += await dirBytes(p); + else n += await stat(p).then((st) => st.size, () => 0); + } + return n; +} + // Every failed encode kept in the store (`<store dir>/.compact-scratch` with a -// failed.json): what failed, what is kept and its size. +// failed.json): what failed, what is kept and its size — and every scratch in +// the store whose video has no pointer any more, as ORPHANED. export async function listKeptFailedEncodes(paths: Paths): Promise<KeptFailedEncodeRow[]> { const rows: KeptFailedEncodeRow[] = []; + const owned = new Set<string>(); for (const e of await listSavedVideos({ paths })) { + owned.add(path.resolve(e.pointer.dir)); const f = await lastFailure(e.pointer.dir).catch(() => null); if (!f) continue; rows.push({ slug: e.slug, id: e.videoId, dir: path.join(e.pointer.dir, COMPACTION_SCRATCH_DIRNAME), at: f.at, reason: f.reason, failedChunks: f.failedChunks, kept: f.kept }); } + for (const slug of await readdir(paths.savedVideosDir).catch(() => [] as string[])) { + for (const id of await readdir(path.join(paths.savedVideosDir, slug)).catch(() => [] as string[])) { + const storeDir = path.resolve(paths.savedVideosDir, slug, id); + const scratch = path.join(storeDir, COMPACTION_SCRATCH_DIRNAME); + if (owned.has(storeDir) || !(await stat(scratch).then((st) => st.isDirectory(), () => false))) continue; + const f = await lastFailure(storeDir).catch(() => null); + rows.push({ + slug, + id, + dir: scratch, + at: f?.at ?? "", + reason: f?.reason ?? "no failed.json (a run that never finished)", + failedChunks: f?.failedChunks ?? [], + kept: f?.kept ?? null, + orphaned: true, + bytes: await dirBytes(scratch), + }); + } + } return rows; } // One video's kept failed encode removed (its whole scratch) — refused while -// a compaction of it runs (its marker is live). +// a compaction of it runs (its marker is live). A video with no pointer: its +// ORPHANED scratch in the store, under the same refusal. export async function clearKeptFailedEncode(paths: Paths, item: CompactItem): Promise<{ cleared: boolean; why: string; bytes?: number }> { const { markerLiveness } = await import("../lib/compactingMarker-server"); const p = await loadSavedVideo(path.join(paths.channelsDir, item.slug, "data", item.id)); - if (!p) return { cleared: false, why: "no saved video" }; - const f = await lastFailure(p.dir); - if (!f) return { cleared: false, why: "no failed encode is kept for it" }; - const m = await readCompactingMarker(p.dir).catch(() => null); + const storeDir = p ? p.dir : path.join(paths.savedVideosDir, item.slug, item.id); + const scratch = path.join(storeDir, COMPACTION_SCRATCH_DIRNAME); + const f = await lastFailure(storeDir).catch(() => null); + const present = await stat(scratch).then((st) => st.isDirectory(), () => false); + if (p ? !f : !present) return { cleared: false, why: p ? "no failed encode is kept for it" : "no saved video and no scratch in the store" }; + const m = await readCompactingMarker(storeDir).catch(() => null); if (m && (await markerLiveness(m)).live) return { cleared: false, why: "a compaction of it is running" }; - await rm(path.join(p.dir, COMPACTION_SCRATCH_DIRNAME), { recursive: true, force: true }); - return { cleared: true, why: `removed (${f.kept ? formatBytes(f.kept.bytes) : "no chunks"})`, ...(f.kept ? { bytes: f.kept.bytes } : {}) }; + const bytes = f?.kept?.bytes ?? (await dirBytes(scratch)); + await rm(scratch, { recursive: true, force: true }); + return { cleared: true, why: `removed${p ? "" : " (orphaned)"} (${formatBytes(bytes)})`, bytes }; } // Clear one video's marker — refused while it is live (cancel the job instead). diff --git a/common/lib/compactMedia-server.ts b/common/lib/compactMedia-server.ts @@ -92,6 +92,8 @@ export type SourceProbe = CompactionProbe & { bytes: number; // The stream index of the video stream compaction replaces. mainVideoIndex: number; + // That stream's time base (seconds per tick), when ffprobe says. + timeBase?: number | null; // What the container must keep besides that stream: "mp4" when every other // stream is one an mp4 holds when copied (audio, mov_text, an attached // picture), else "matroska". @@ -138,6 +140,10 @@ export async function probeCompactionSource(ffprobeBin: string, file: string): P const firstAudio = audios[0]; return { mainVideoIndex: typeof v?.index === "number" ? v.index : 0, + timeBase: (() => { + const [a, b] = String(v?.time_base ?? "").split("/").map(Number); + return a > 0 && b > 0 ? a / b : null; + })(), container: mp4Ok ? "mp4" : "matroska", audioStart: firstAudio ? (numOr(firstAudio.start_time) ?? 0) : null, formatStart: numOr(doc.format?.start_time) ?? 0, @@ -229,6 +235,12 @@ export type ChunkPlan = { sourceFrames: number; // Frames the chunk must hold: the source's, or the fps filter's count. expectedFrames: number; + // Its source frames by index in the file, [fromIndex, toIndex), and — when + // the rate is reduced by a whole ratio — the `select` expression over them + // that keeps exactly the file's KEPT FRAMES (keptSourceFrames). + fromIndex?: number; + toIndex?: number; + select?: string; // The last chunk runs to the end of the source. last?: boolean; }; @@ -252,7 +264,7 @@ const EDGE = 1e-4; // Chunks of about `chunkSeconds`, each starting on a source keyframe. A chunk // is never shorter than half the asked length unless it is the only one. -export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: number | null, sourceFps?: number | null): ChunkPlan[] { +export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: number | null, sourceFps?: number | null, kept?: KeptRuns): ChunkPlan[] { const { pts, keyframes } = scan; if (!pts.length) return []; const first = pts[0]; @@ -270,8 +282,12 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe // chunk's rounded count would move the picture by part of a frame. const m = wholeRatio(sourceFps, outFps); const indexOf = (k: number) => countIn(pts, -Infinity, k - EDGE); + // With the file's kept frames (keptSourceFrames), a chunk starts only on a + // KEPT keyframe: then each chunk's own selection is the file's. + const mask = kept && m ? keptMask(kept, pts.length) : null; const onGrid = (k: number) => { if (!outFps) return true; + if (mask) return mask[indexOf(k)] === 1; if (m) return indexOf(k) % m === 0; const x = (k - starts[0]) * outFps; return Math.abs(x - Math.round(x)) < 0.02; @@ -284,6 +300,10 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe const from = starts[i]; const to = i + 1 < starts.length ? starts[i + 1] : end; const sourceFrames = countIn(pts, from - EDGE, to - EDGE); + const a = indexOf(from); + const b = a + sourceFrames; + let keptHere = 0; + if (mask) for (let j = a; j < b; j += 1) keptHere += mask[j]; plans.push({ index: i, from, @@ -291,9 +311,14 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe sourceFrames, expectedFrames: !outFps ? sourceFrames - : wholeRatio(sourceFps, outFps) - ? Math.ceil(sourceFrames / wholeRatio(sourceFps, outFps)!) - : framesAtFps(pts, from, to, outFps, i + 1 === starts.length), + : mask + ? keptHere + : wholeRatio(sourceFps, outFps) + ? Math.ceil(sourceFrames / wholeRatio(sourceFps, outFps)!) + : framesAtFps(pts, from, to, outFps, i + 1 === starts.length), + fromIndex: a, + toIndex: b, + ...(mask ? { select: selectExpr(kept!, a, b) } : {}), ...(i + 1 === starts.length ? { last: true } : {}), }); } @@ -369,7 +394,7 @@ export function encodeChunkArgs(src: string, chunk: ChunkPlan, s: EncodeSettings // (`select` leaves the source's on the link). ...(s.fps && !wholeRatio(s.sourceFps, s.fps) ? ["-vf", `${decimateTo(s.sourceFps, s.fps)}setpts=PTS-STARTPTS`] - : ["-vf", `${decimateTo(s.sourceFps, s.fps)}setpts=PTS-STARTPTS`, "-fps_mode", "passthrough"]), + : ["-vf", `${chunk.select ? `select='${chunk.select}',` : decimateTo(s.sourceFps, s.fps)}setpts=PTS-STARTPTS`, "-fps_mode", "passthrough"]), "-c:v", "libsvtav1", "-preset", String(s.preset), "-crf", String(s.crf), "-svtav1-params", `fps-num=${Math.round(outRate(s) * 1000)}:fps-denom=1000`, "-force_key_frames", `expr:gte(t,n_forced*${s.gopSeconds})`, @@ -438,6 +463,54 @@ export function concatList(files: string[], durations?: number[]): string { // --- timestamps ------------------------------------------------------------- +// THE KEPT FRAMES (review G4). A source capped by a whole ratio keeps a frame +// when at least one copy frame (1 / `fps`) less half a source tick has passed +// since the last kept frame's pts — by TIME, from the source's own timestamps: +// a 60 fps stretch keeps every other frame, a stretch where the recording ran +// at 30 keeps every frame (by index it kept every other: 15 fps there), and +// after a gap the next frame. Each kept frame keeps its own pts. Decided ONCE +// from the source's packet scan and saved in the scratch state as runs +// [first index, stride, count]; the encoder's `select` and every check read it. +export type KeptRuns = [number, number, number][]; + +export function keptSourceFrames(pts: Float64Array, fps: number, tick: number): KeptRuns { + const runs: KeptRuns = []; + const min = 1 / fps - tick / 2 - 1e-9; + let last = -Infinity; + for (let i = 0; i < pts.length; i += 1) { + if (i > 0 && pts[i] - last < min) continue; + last = pts[i]; + const r = runs[runs.length - 1]; + if (r && r[2] === 1) { + r[1] = i - r[0]; + r[2] = 2; + } else if (r && i - (r[0] + r[1] * (r[2] - 1)) === r[1]) r[2] += 1; + else runs.push([i, 1, 1]); + } + return runs; +} + +export function keptMask(runs: KeptRuns, n: number): Uint8Array { + const m = new Uint8Array(n); + for (const [f, st, c] of runs) for (let k = 0; k < c; k += 1) if (f + k * st < n) m[f + k * st] = 1; + return m; +} + +// The `select` expression keeping the kept frames among source frames +// [from, to), over the frame number n counted from `from`. +export function selectExpr(runs: KeptRuns, from: number, to: number): string { + const terms: string[] = []; + for (const [f, st, c] of runs) { + const kmin = Math.max(0, Math.ceil((from - f) / st)); + const kmax = Math.min(c - 1, Math.floor((to - 1 - f) / st)); + if (kmin > kmax) continue; + const a = f + kmin * st - from; + const b = f + kmax * st - from; + terms.push(a === b ? `eq(n,${a})` : st === 1 ? `between(n,${a},${b})` : `between(n,${a},${b})*not(mod(n-${a},${st}))`); + } + return terms.length ? terms.join("+") : "0"; +} + // The nominal frame rate of a scan: 1 / its typical frame step — the mean of // the steps within half of the median, so a live recording's dropped frames // (long steps) do not move it, and a container's ticks (a 30 fps mkv's 33 and @@ -497,8 +570,15 @@ export function expectedCopyPts( chunks: Pick<ChunkPlan, "from" | "to" | "expectedFrames">[], ratio: number | null, fps: number | null, + kept?: KeptRuns, ): Float64Array { const out: number[] = []; + if (kept) { + // The file's kept frames, as the encode's `select` kept them. + const mask = keptMask(kept, pts.length); + for (let i = 0; i < pts.length; i += 1) if (mask[i]) out.push(pts[i]); + return Float64Array.from(out); + } for (const c of chunks) { const a = countIn(pts, -Infinity, c.from - EDGE); const b = countIn(pts, -Infinity, c.to - EDGE); @@ -541,15 +621,48 @@ export function compareCopyPts(expected: Float64Array, actual: Float64Array, tol // Every frame of the video decoded, with ffmpeg told to stop at the first // error (`-xerror`) and to print any. An empty stderr and a zero exit is a // clean decode. -export async function fullDecode(paths: GatedPaths, file: string, signal?: AbortSignal): Promise<{ ok: boolean; why?: string }> { +// WHAT A FULL DECODE'S STDERR MEANS (review, before the second real run: a +// correct copy of a source with a dropped frame failed on a NULL MUXER line). +// FATAL — the decoder or demuxer reporting damage to the picture or sound: +// any line matching DECODE_FATAL. BENIGN — the null muxer's own timestamp +// bookkeeping, not the picture: DECODE_BENIGN (with `-enc_time_base demux` it +// does not happen; if it does, it is not a decode error). Anything else is a +// note, recorded and not fatal. A non-zero exit is always fatal (-xerror stops +// at the decoder's first error). +export const DECODE_FATAL: RegExp[] = [ + /error/i, /invalid/i, /corrupt/i, /conceal/i, /missing/i, /non-existing/i, /overread/i, /out of range/i, + /illegal/i, /damaged/i, /truncat/i, /unavailable/i, /failed/i, /mmco/i, /desync/i, /no frame/i, /broken/i, +]; +export const DECODE_BENIGN: RegExp[] = [/non[- ]monotonic(ally increasing)? dts/i, /^last message repeated/i]; + +export function classifyDecodeStderr(text: string): { fatal: string[]; benign: string[]; notes: string[] } { + const out = { fatal: [] as string[], benign: [] as string[], notes: [] as string[] }; + for (const raw of text.split("\n")) { + const l = raw.trim(); + if (!l) continue; + // Strip "[h264 @ 0x55…] " so a pattern judges the message. + const msg = l.replace(/^\[[^\]]*\]\s*/, ""); + if (DECODE_BENIGN.some((r) => r.test(msg))) out.benign.push(l); + else if (DECODE_FATAL.some((r) => r.test(msg))) out.fatal.push(l); + else out.notes.push(l); + } + return out; +} + +// Every frame decoded into the null muxer, KEEPING EACH STREAM'S OWN TIME +// BASE (`-enc_time_base demux`): re-quantised to the copy's nominal 1001/30000, +// two kept frames around a dropped one rounded to the same tick and the muxer +// complained, about nothing in the picture. +export async function fullDecode(paths: GatedPaths, file: string, signal?: AbortSignal): Promise<{ ok: boolean; why?: string; notes?: string[] }> { try { const err = await runHeavyFfmpeg( paths, - ["-nostdin", "-hide_banner", "-v", "error", "-xerror", "-i", file, "-map", "0:v:0", "-map", "0:a?", "-f", "null", "-"], + ["-nostdin", "-hide_banner", "-v", "error", "-xerror", "-i", file, "-map", "0:v:0", "-map", "0:a?", "-enc_time_base", "demux", "-f", "null", "-"], { estimateMB: DECODE_ESTIMATE_MB, ...(signal ? { signal } : {}) }, ); - const lines = err.split("\n").map((l) => l.trim()).filter(Boolean); - return lines.length ? { ok: false, why: lines.slice(-2).join(" | ") } : { ok: true }; + const c = classifyDecodeStderr(err); + const notes = [...c.benign, ...c.notes].slice(0, 5); + return c.fatal.length ? { ok: false, why: c.fatal.slice(-2).join(" | ") } : { ok: true, ...(notes.length ? { notes } : {}) }; } catch (e) { if (signal?.aborted) throw e; return { ok: false, why: (e as Error).message }; @@ -685,6 +798,9 @@ export async function scoreExcerpt( // The SAME FRAME's seek time in the source, when its command-line // timeline starts elsewhere than the copy's (cliTimelineStart); else `at`. sourceAt?: number; + // The kept frames' `select` from the excerpt's first source frame + // (selectExpr), in place of the ratio's decimation. + sourceSelect?: string; seconds: number; fps: number | null; sourceFps?: number | null; @@ -701,7 +817,8 @@ export async function scoreExcerpt( const n = renumber(opts.fps ?? opts.sourceFps ?? null); const srcAt = opts.sourceAt ?? opts.at; const pre = Math.max(0, srcAt - 10); - const ref = `[1:v]trim=start=${(srcAt - pre).toFixed(4)},${decimateTo(opts.sourceFps, opts.fps)}${n}[r]`; + const dec = opts.sourceSelect ? `select='${opts.sourceSelect}',` : decimateTo(opts.sourceFps, opts.fps); + const ref = `[1:v]trim=start=${(srcAt - pre).toFixed(4)},${dec}${n}[r]`; const dist = `[0:v]${n}[d]`; const log = path.join(opts.scratchDir, `vmaf-${Math.round(opts.at * 1000)}.json`); const metric = @@ -823,6 +940,8 @@ export async function compareCuts( // The same frame's time in the source's command-line timeline (see // scoreExcerpt); else `at`. sourceAt?: number; + // The kept frames' `select` from the cut's first source frame. + sourceSelect?: string; seconds: number; fps: number | null; sourceFps?: number | null; @@ -849,7 +968,7 @@ export async function compareCuts( ); } } - const rate = decimateTo(opts.sourceFps, opts.fps); + const rate = opts.sourceSelect ? `select='${opts.sourceSelect}',` : decimateTo(opts.sourceFps, opts.fps); const outRate = opts.fps ?? opts.sourceFps ?? null; const ssim = await ssimOf(paths, b, a, rate, outRate, 0, opts.signal); const later = await ssimOf(paths, b, a, rate, outRate, 1, opts.signal); @@ -919,6 +1038,9 @@ export type WholeFileComparison = { width: number; height: number; grid: number; + // The source's picture detail per paired frame (review G2): the mean of a + // Sobel edge map of the source frame, grey, at the comparison's size. + sourceDetail?: Float32Array; }; function ssimScores(text: string, plane = "All"): number[] { @@ -942,6 +1064,9 @@ export async function compareWholeFile( // The copy's frame rate when it was capped, the source's rate, its size. fps: number | null; sourceFps: number | null; + // The file's kept frames' `select` from its first frame (selectExpr), in + // place of the ratio's decimation; it goes in the graph FILE, never argv. + sourceSelect?: string; sourceWidth: number | null; sourceHeight: number | null; tileFloor: number; @@ -959,6 +1084,7 @@ export async function compareWholeFile( const n = renumber(rate); const esc = (f: string) => f.replace(/[:\\']/g, "\\$&"); const whole = path.join(opts.scratchDir, "wf-whole.log"); + const detailLog = path.join(opts.scratchDir, "wf-detail.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 @@ -966,8 +1092,12 @@ export async function compareWholeFile( const chains = [ `[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]", "")}`, + `[1:v]${opts.sourceSelect ? `select='${opts.sourceSelect}',` : decimateTo(opts.sourceFps, opts.fps)}${n},scale=${W}:${H}:flags=area,format=yuv420p,split=2[r0][rg]`, + // …and one more: the SOURCE's own picture detail per frame (the mean of a + // Sobel edge map, review G2), so a chunk drop at a join can be told from + // a segment of harder picture starting there. + `[rg]format=gray,split=${T + 1}${labels("r").replace("[r0]", "")}[rdet]`, + `[rdet]sobel,signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=${esc(detailLog)},nullsink`, `[d0][r0]ssim=stats_file=${esc(whole)}:eof_action=endall[out]`, ]; for (let k = 0; k < T; k += 1) { @@ -1019,9 +1149,13 @@ export async function compareWholeFile( } tiles.push({ index: k, col: k % G, row: Math.floor(k / G), min, minAt, longestBelow: longest, longestBelowAt: longestAt }); } - return { frames, chromaU, chromaV, tiles, width: W, height: H, grid: G }; + const sourceDetail = Float32Array.from( + [...(await readFile(detailLog, "utf8").catch(() => "")).matchAll(/lavfi\.signalstats\.YAVG=(-?[0-9.]+)/g)].map((m) => Number(m[1])), + ); + return { frames, chromaU, chromaV, tiles, width: W, height: H, grid: G, ...(sourceDetail.length === frames.length ? { sourceDetail } : {}) }; } finally { await rm(whole, { force: true }).catch(() => {}); + await rm(detailLog, { force: true }).catch(() => {}); await rm(graphFile, { force: true }).catch(() => {}); for (let k = 0; k < T; k += 1) await rm(tileLog(k), { force: true }).catch(() => {}); } @@ -1241,7 +1375,7 @@ export function robustSpread(f: Float32Array): { median: number; sd: number } { } export function judgeWholeFile( - c: Pick<WholeFileComparison, "frames" | "tiles"> & Partial<Pick<WholeFileComparison, "chromaU" | "chromaV">>, + c: Pick<WholeFileComparison, "frames" | "tiles"> & Partial<Pick<WholeFileComparison, "chromaU" | "chromaV" | "sourceDetail">>, t: { minFrame: number; meanFloor: number; @@ -1317,7 +1451,7 @@ export function judgeWholeFile( const at = (i: number) => `${(i / t.fps).toFixed(2)} s`; const chunks = t.chunkStarts && f.length === t.expectedFrames && u.length === f.length && v.length === f.length - ? judgeChunks({ Y: f, U: u, V: v }, t.chunkStarts, lower, { sigmaK: t.chunkSigmaK ?? 4, margin: t.chunkMargin ?? 0.02, fps: t.fps }) + ? judgeChunks({ Y: f, U: u, V: v }, t.chunkStarts, lower, { sigmaK: t.chunkSigmaK ?? 4, margin: t.chunkMargin ?? 0.02, fps: t.fps }, c.sourceDetail) : null; const base = { mean, median, sd, min, minAt, relativeFloor, worstLocalMargin, worstLocalAt, windowFrames, @@ -1368,7 +1502,11 @@ export function judgeWholeFile( // - neither of its joins shows the drop: the frames just inside the chunk // score within half the drop of the frames just outside. A bad chunk // changes level AT its joins; a harder scene that runs across chunks -// (a game segment in a talk stream) changes level where the scene changes. +// (a game segment in a talk stream) changes level where the scene changes; +// - or THE SOURCE ITSELF CHANGES at every join where the copy drops (review +// G2: a scheduled segment that starts right at a join): its picture +// detail (`sourceDetail`) over the same 5 s inside and outside differs by +// SOURCE_CHANGE_SHARE or more. A bad chunk of unchanged picture still fails. // One chunk: nothing to compare. Two: each against the other. export type ChunkVerdict = { ok: boolean; @@ -1377,16 +1515,18 @@ export type ChunkVerdict = { sigmaK: number; margin: number; // The lowest chunk mean relative to its floor (not exempt), on any plane. - worst: { index: number; plane: "Y" | "U" | "V"; mean: number; centre: number; floor: number } | null; - exempt: { index: number; plane: "Y" | "U" | "V"; why: "lower state" | "no step at its joins" }[]; + worst: { index: number; plane: "Y" | "U" | "V"; mean: number; centre: number; floor: number; joinAt?: number } | null; + exempt: { index: number; plane: "Y" | "U" | "V"; why: "lower state" | "no step at its joins" | "the source changes at its join" }[]; }; export const CHUNK_JOIN_SECONDS = 5; +export const SOURCE_CHANGE_SHARE = 0.1; export function judgeChunks( planes: { Y: Float32Array; U: Float32Array; V: Float32Array }, chunkStarts: number[], lower: LowerState | null, o: { sigmaK: number; margin: number; fps: number }, + sourceDetail?: Float32Array, ): ChunkVerdict { const n = planes.Y.length; const starts = [...new Set(chunkStarts.filter((x) => x >= 0 && x < n))].sort((a, b) => a - b); @@ -1420,17 +1560,30 @@ export function judgeChunks( } const drop = r.median - means[ci]; const w = Math.max(1, Math.min(Math.round(CHUNK_JOIN_SECONDS * o.fps), Math.floor((b - a) / 4))); - const stepAt = (join: number, inside: [number, number]) => { - const outside: [number, number] = join === a ? [Math.max(0, a - w), a] : [b, Math.min(n, b + w)]; + const windows = (join: number): [[number, number], [number, number]] => + join === a ? [[a, Math.min(b, a + w)], [Math.max(0, a - w), a]] : [[Math.max(a, b - w), b], [b, Math.min(n, b + w)]]; + const stepAt = (join: number) => { + const [inside, outside] = windows(join); return meanOf(p, outside[0], outside[1]) - meanOf(p, inside[0], inside[1]) >= drop / 2; }; - const step = (ci > 0 && stepAt(a, [a, Math.min(b, a + w)])) || (ci < spans.length - 1 && stepAt(b, [Math.max(a, b - w), b])); - if (!step) { + const sourceChangesAt = (join: number) => { + if (!sourceDetail || sourceDetail.length !== n) return false; + const [inside, outside] = windows(join); + const x = meanOf(sourceDetail, inside[0], inside[1]); + const y = meanOf(sourceDetail, outside[0], outside[1]); + return Math.abs(x - y) >= SOURCE_CHANGE_SHARE * Math.max(1e-6, (x + y) / 2); + }; + const stepping = [...(ci > 0 && stepAt(a) ? [a] : []), ...(ci < spans.length - 1 && stepAt(b) ? [b] : [])]; + if (!stepping.length) { out.exempt.push({ index: ci, plane, why: "no step at its joins" }); return; } + if (stepping.every(sourceChangesAt)) { + out.exempt.push({ index: ci, plane, why: "the source changes at its join" }); + return; + } if (!out.worst || gap < out.worst.mean - out.worst.floor) { - out.worst = { index: ci, plane, mean: means[ci], centre: r.median, floor }; + out.worst = { index: ci, plane, mean: means[ci], centre: r.median, floor, joinAt: stepping[0] }; } }); } @@ -1441,7 +1594,9 @@ export function judgeChunks( out.why = `chunk ${wst.index + 1} of ${spans.length} (${(a / o.fps).toFixed(1)}–${(b / o.fps).toFixed(1)} s) scores ${wst.mean.toFixed(4)} on ${wst.plane}, ` + `below the other chunks' floor ${wst.floor.toFixed(4)} (their median ${wst.centre.toFixed(4)} − max(${o.sigmaK}·robust spread, ${o.margin})), ` + - "and the drop begins or ends at its chunk join"; + `and the drop begins or ends at its chunk join at ${((wst.joinAt ?? a) / o.fps).toFixed(1)} s${sourceDetail ? ", where the source's own picture does not change" : ""}. ` + + "It may still be a segment of harder picture starting exactly at that join: look at the source there; a run with another " + + "chunkMinutes puts the joins elsewhere (it encodes again)"; } return out; } diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts @@ -15,6 +15,7 @@ import { readFile, rename, rm, + rmdir, stat, } from "node:fs/promises"; import { @@ -35,6 +36,7 @@ import { import { assertSavedVideosStoreWritable } from "./savedVideoStore"; import { platformPresence } from "./availability-server"; import { assertNotCompacting } from "./compactingMarker-server"; +import { COMPACTION_SCRATCH_DIRNAME } from "./savedVideoCompaction"; import { probeMedia } from "./evidenceClip-server"; import type { Paths } from "./paths"; @@ -392,12 +394,20 @@ export async function recordSavedVideoProbedHeight( }); } +// A KEPT FAILED ENCODE goes with its video (review G3): when the pointer +// goes — unpersist, the prune's drop — its `.compact-scratch` (chunks and a +// failed copy, gigabytes, named by nothing else) is removed too, after the +// same guards (no compaction of the video is running). +async function removeCompactionScratch(storeDir: string): Promise<void> { + await rm(path.join(storeDir, COMPACTION_SCRATCH_DIRNAME), { recursive: true, force: true }).catch(() => {}); +} + // Best-effort removal of a now-empty store dir (and its empty <slug> parent). +// `rmdir`, which removes an EMPTY directory only: `rm` without `recursive` +// refuses every directory (EISDIR), so this never removed one before. async function pruneEmptyStoreDirs(storeDir: string): Promise<void> { - await rm(storeDir, { recursive: false, force: true }).catch(() => {}); - await rm(path.dirname(storeDir), { recursive: false, force: true }).catch( - () => {}, - ); + await rmdir(storeDir).catch(() => {}); + await rmdir(path.dirname(storeDir)).catch(() => {}); } // Reverse persistSourceVideo: move the stored container back into the data dir @@ -445,6 +455,7 @@ async function unpersistUnlocked( await moveFileCrossDevice(path.join(pointer.dir, alt.file), path.join(videoDir, alt.file)).catch(() => {}); } await rm(savedVideoPointerPath(videoDir), { force: true }); + await removeCompactionScratch(pointer.dir); await pruneEmptyStoreDirs(pointer.dir); return true; } @@ -473,6 +484,7 @@ export async function dropSavedVideo(videoDir: string): Promise<number> { await rm(path.join(pointer.dir, alt.file), { force: true }); } await rm(savedVideoPointerPath(videoDir), { force: true }); + await removeCompactionScratch(pointer.dir); await pruneEmptyStoreDirs(pointer.dir); return savedVideoBytes(pointer); }); diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts @@ -134,6 +134,9 @@ export type SavedVideoCompactedChecks = { passed: boolean; // Full decode of the re-encode, every frame, without an error. decoded: boolean; + // What the decode printed that is not damage (classifyDecodeStderr): a + // null-muxer timestamp line, an unrecognised one. Never fatal. + decodeNotes?: string[]; // [source, re-encode] video lengths in seconds, and the allowed difference. seconds: [number, number]; secondsTolerance: number; @@ -200,7 +203,8 @@ export type SavedVideoCompactedChecks = { count: number; sigmaK: number; margin: number; - worst: { chunk: number; plane: string; mean: number; centre: number; floor: number } | null; + // joinAt: the join (seconds) where the drop begins or ends. + worst: { chunk: number; plane: string; mean: number; centre: number; floor: number; joinAt?: number } | null; exempt: { chunk: number; plane: string; why: string }[]; }; // Every stream but the video, and the chapters: what the source holds and @@ -568,6 +572,7 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null { } : {}), ...(Array.isArray(c.avOffset) ? { avOffset: pair(c.avOffset) } : {}), + ...(Array.isArray(c.decodeNotes) ? { decodeNotes: c.decodeNotes.map(String).slice(0, 5) } : {}), ...(c.timestamps && typeof c.timestamps === "object" ? (() => { const t = obj(c.timestamps); @@ -594,7 +599,12 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null { count: num(m.count), sigmaK: num(m.sigmaK), margin: num(m.margin), - worst: w ? { chunk: num(w.chunk), plane: strOr(w.plane), mean: num(w.mean), centre: num(w.centre), floor: num(w.floor) } : null, + worst: w + ? { + chunk: num(w.chunk), plane: strOr(w.plane), mean: num(w.mean), centre: num(w.centre), floor: num(w.floor), + ...(typeof w.joinAt === "number" ? { joinAt: w.joinAt } : {}), + } + : null, exempt: Array.isArray(m.exempt) ? m.exempt.map((x) => ({ chunk: num(obj(x).chunk), plane: strOr(obj(x).plane), why: strOr(obj(x).why) })) : [], }, }; diff --git a/common/lib/savedVideoCompaction.test.ts b/common/lib/savedVideoCompaction.test.ts @@ -378,3 +378,102 @@ test("timestamps: dropped frames found, chunk starts on even indexes, the copy's // The concat list: each chunk's span to the next, so each starts at its time. assert.equal(concatList(["/a/x.mp4", "/a/y.mp4"], [4.25]), "file '/a/x.mp4'\nduration 4.250000\nfile '/a/y.mp4'\n"); }); + +// Review G2: a harder segment starting AT a chunk join is the source's doing +// when the source's own picture changes there; a bad chunk's source does not. +test("G2: a segment starting at a join is exempt when the source changes there; a bad chunk is not", async () => { + const { judgeChunks } = await import("./compactMedia-server"); + const fps = 30; + const CH = 300 * fps; + const N = 20; + const starts = Array.from({ length: N }, (_, i) => i * CH); + const jitter = (i: number) => (((i * 7919) % 11) - 5) * 0.0002; + const at = (seg: (i: number) => boolean, hard: number, easy = 0.995) => Float32Array.from({ length: N * CH }, (_, i) => (seg(i) ? hard : easy) + jitter(i)); + const ones = new Float32Array(N * CH).fill(0.99); + const o = { sigmaK: 4, margin: 0.02, fps }; + for (const offset of [0, 1, 2]) { + // A 25-minute game segment from chunk 7's join (+offset s): its picture detail is twice the talk's. + const seg = (i: number) => i >= 7 * CH + offset * fps && i < 7 * CH + offset * fps + 1500 * fps; + const y = at(seg, 0.965); + const detail = at(seg, 20, 10); + const without = judgeChunks({ Y: y, U: ones, V: ones }, starts, null, o); + assert.equal(without.ok, false, `offset ${offset}: without the source's detail it fails as before`); + const v = judgeChunks({ Y: y, U: ones, V: ones }, starts, null, o, detail); + assert.equal(v.ok, true, `offset ${offset}: ${v.why}`); + assert.ok(v.exempt.some((e) => e.why === "the source changes at its join"), JSON.stringify(v.exempt)); + } + // A bad chunk: the copy drops at its joins, the source's picture does not change. + const bad = (i: number) => i >= 7 * CH && i < 8 * CH; + const v = judgeChunks({ Y: at(bad, 0.96), U: ones, V: ones }, starts, null, o, Float32Array.from({ length: N * CH }, () => 10)); + assert.equal(v.ok, false); + assert.match(v.why!, /^chunk 8 of 20 \(2100\.0–2400\.0 s\).*join at 2100\.0 s, where the source's own picture does not change\. It may still be a segment .* another chunkMinutes puts the joins elsewhere/); + assert.equal(v.worst?.joinAt, 7 * CH); +}); + +// Review G4: the kept frames by TIME. +test("G4: kept frames by time — a 30 fps stretch keeps every frame, 60 fps every other, a gap the next; selects and plans read it", async () => { + const { keptSourceFrames, keptMask, selectExpr, planChunks, expectedCopyPts } = await import("./compactMedia-server"); + // CFR 60: one run, every other frame. + const cfr = Float64Array.from({ length: 600 }, (_, i) => i / 60); + assert.deepEqual(keptSourceFrames(cfr, 30, 1 / 90000), [[0, 2, 300]]); + // In ms ticks (an mkv) the same. + const ms = Float64Array.from({ length: 600 }, (_, i) => Math.round((i / 60) * 1000) / 1000); + assert.deepEqual(keptSourceFrames(ms, 30, 0.001), [[0, 2, 300]]); + // 60 fps, a 4 s stretch at 30 fps (every odd frame of it missing), an odd gap. + const t: number[] = []; + for (let i = 0; i < 1200; i += 1) { + if (i >= 300 && i < 540 && i % 2 === 1) continue; + if (i >= 900 && i <= 902) continue; + t.push(i / 60); + } + const pts = Float64Array.from(t); + const runs = keptSourceFrames(pts, 30, 1 / 90000); + const mask = keptMask(runs, pts.length); + const kept = t.filter((_, i) => mask[i]); + // Never closer than a copy frame (less half a tick); never farther than one, but at the gap. + for (let k = 1; k < kept.length; k += 1) { + const d = kept[k] - kept[k - 1]; + assert.ok(d >= 1 / 30 - 1e-6, `${kept[k - 1]} -> ${kept[k]}`); + if (!(kept[k - 1] < 15.04 && kept[k] > 14.99)) assert.ok(d <= 1 / 30 + 1e-6, `${kept[k - 1]} -> ${kept[k]} (${d})`); + } + // The 30 fps stretch keeps EVERY frame there. + const stretch = t.filter((x) => x >= 300 / 60 && x < 540 / 60); + assert.equal(stretch.filter((x) => kept.includes(x)).length, stretch.length); + // The select over a window keeps exactly the mask's frames. + const expr = selectExpr(runs, 250, 700); + const evalExpr = (n: number) => + expr.split("+").some((term) => { + const m = /^(?:eq\(n,(\d+)\)|between\(n,(\d+),(\d+)\)(?:\*not\(mod\(n-(\d+),(\d+)\)\))?)$/.exec(term)!; + if (m[1] !== undefined) return n === Number(m[1]); + const ok = n >= Number(m[2]) && n <= Number(m[3]); + return m[4] === undefined ? ok : ok && (n - Number(m[4])) % Number(m[5]) === 0; + }); + for (let g = 250; g < 700; g += 1) assert.equal(evalExpr(g - 250), mask[g] === 1, `frame ${g}`); + // The plan: chunks start on kept keyframes, hold the kept count, carry their select. + const keyframes = t.filter((_, i) => i % 45 === 0); + const plan = planChunks({ pts, keyframes }, 4, 30, 60, runs); + for (const c of plan) { + assert.equal(mask[c.fromIndex!], 1, `chunk at ${c.from}`); + let k = 0; + for (let i = c.fromIndex!; i < c.toIndex!; i += 1) k += mask[i]; + assert.equal(c.expectedFrames, k); + assert.ok(c.select && c.select.length > 0); + } + assert.deepEqual(Array.from(expectedCopyPts(pts, plan, 2, null, runs)), kept); +}); + +test("G1: what a decode's stderr means", async () => { + const { classifyDecodeStderr } = await import("./compactMedia-server"); + const c = classifyDecodeStderr( + [ + "[null @ 0x55dabfdf1140] Application provided invalid, non monotonically increasing dts to muxer in stream 0: 600 >= 600", + "[h264 @ 0x5] error while decoding MB 12 7, bytestream -5", + "[h264 @ 0x5] concealing 120 DC, 120 AC, 120 MV errors in P frame", + "[dav1d @ 0x6] Error parsing OBU data", + "Something ffmpeg says that is neither", + ].join("\n"), + ); + assert.equal(c.benign.length, 1); + assert.equal(c.fatal.length, 3); + assert.deepEqual(c.notes, ["Something ffmpeg says that is neither"]); +}); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -47,10 +47,14 @@ frame at its own time, chunks start on even frame indexes and join at their source times, and keyframes fall every 5 s of time. The check is every frame's time against its source frame's (`checks.timestamps`, 1 ms), not frames ÷ rate, which failed the first real run's correct copy by a tail gap. The recording's dropped frames - are recorded (`checks.sourceGaps`). A source with none decodes frame for frame as before. + are recorded (`checks.sourceGaps`). A source with none decodes frame for frame as before. The frames kept are + decided by TIME (one copy frame since the last kept), so a stretch where the recording ran at 30 fps keeps 30 + fps; they are saved in the scratch state and read by every chunk and check. The full decode keeps each + stream's time base and fails only on damage. A chunk that drops at a join where the source's own picture + changes (a segment starting there) is exempt, and the failure message names the join and what to do. - A failed check KEEPS THE ENCODE (chunks and the joined copy, never active): `"reverify": true` checks it again without encoding (a chunk whose own content failed is encoded again), and `kept-failed-encodes` lists and - clears them. The dry run says when one exists and how big it is. Every check runs and is recorded even after + clears them, orphaned ones included. Unpersist and the prune remove a video's scratch with its pointer. The dry run says when one exists and how big it is. Every check runs and is recorded even after one fails (`failed.json` `failures`). - **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