commit 8444241f623c13102563a499e2c0a59fef7ce76c
parent f290379c4c34c9f241c19b34defd73147c9562f7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 14 Nov 2026 11:48:22 -0500
compact-saved-videos: one constant keep rule, a sustained source step, skipped cuts named, more decode damage fatal
Review of f290379c4, before the second real run.
H1. The kept frames were a set of runs turned into a select expression; on
a recording with millisecond timestamps (steps of 16 and 17 ms) it
fragments into hundreds of thousands of runs, past ffmpeg's expression
parser and the argv limit. Now ONE constant rule: keep a frame when at least
keepMinStep has passed since the last kept frame - one copy frame less half
a source frame less 0.25 ms (24.75 ms at 60 -> 30), between one source step
and two and off every millisecond and 90 kHz tick, so ms rounding can never
tie with it. ffmpeg applies it as select='isnan(prev_selected_t)+gte(t-
prev_selected_t,<step>)' (constant size); every check that pairs source and
copy frames applies the same rule in code; the scratch state saves only the
step. A 60 fps source rounded to the millisecond keeps exactly every other
frame, with a 67 ms gap and with a choppy pattern too, and ffmpeg's select
and the code agree frame for frame on such files. The chunk encode now
keeps the source's own time base (-enc_time_base:v demux): the default
rounded millisecond times onto a 1/60 s grid, up to 0.67 ms off.
H2. The source-detail exemption excused a bad chunk when detail merely
drifted. It now needs a step to HARDER picture inside the chunk, both sharp
at the join (5 s either side) and sustained (the chunk's mean detail against
the neighbouring chunk's), each by 10 % or more. A drift, a step to easier
picture, a static or near-flat noisy source excuse nothing.
H3. On a very choppy source no window was regular enough for the evidence
cutter and the cuts could not run. A cut needs 3 s of evenly spaced copy
frames; where there is none it is SKIPPED and named (checks.skipped), never
counted as passed, and "after-verify" never drops an original after a
skipped check.
H4. Fatal decode lines now include frame num gap, could not find ref,
unknown OBU, partial file and the AAC decoder's damage lines. The video pass
decodes 0:v:0 alone; the audio pass then decodes every track, and audio
damage the source's own audio shows as much of (it is copied packet for
packet) is a note, more than that is fatal.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
7 files changed, 407 insertions(+), 184 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 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
+ - 60 → 30 keeps a source frame when at least `keepMinStep` has passed since the last kept frame: one copy frame
+ less half a source frame, less 0.25 ms (24.75 ms at 60 → 30). That is a frame by TIME, each at its source
+ time. A 60 fps stretch keeps every other frame, even with timestamps rounded to the millisecond (16, 17,
+ 17 ms). A stretch where the recording ran at 30 keeps every frame, and after a gap the next frame. It is ONE
+ CONSTANT RULE: the encoder's `select` is `isnan(prev_selected_t)+gte(t-prev_selected_t,<step>)`, a few
+ dozen characters whatever the file. A set of runs fragmented into hundreds of thousands on a recording with
+ millisecond timestamps and broke ffmpeg's parser and argv. Every check that pairs source and copy frames
+ applies the same rule in code. The scratch state saves the step. 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 kept keyframe, so each chunk's own selection is the file's.
@@ -1215,12 +1218,19 @@ 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. 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`);
+ - a full decode without an error, in two passes. 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.
+ - The video pass decodes 0:v:0 alone.
+ - The audio pass then decodes every track. The audio is the source's packet for packet, so audio damage the
+ source's own audio shows as much of is a note; more than that fails.
+
+ Fatal: a non-zero exit of the video pass, or a line naming damage. The patterns are error, invalid, corrupt,
+ conceal, missing, non-existing, overread, out of range, illegal, damaged, truncated, unavailable, failed,
+ mmco, desync, no frame, broken, frame num gap, could not find ref, unknown OBU, partial file, and the AAC
+ decoder's reserved bit, prediction, not allocated, input buffer exhausted, exceeds limit and inconsistent
+ channel configuration. 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
@@ -1269,9 +1279,12 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"}
- 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;
- - 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
+ - or the SOURCE itself steps to HARDER picture 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) must be 10 % or more higher
+ inside than outside, both over the 5 s either side and over the whole chunk against the neighbouring one.
+ That is a scheduled segment starting right at a join. A drift, a step to easier picture, or noise over a flat
+ picture explains nothing. A bad chunk that coincides exactly with a harder scene of its own length looks the
+ same as a good one and passes. 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).
@@ -1280,7 +1293,10 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"}
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;
- three windows cut through the evidence cutter from both copies, compared frame by frame: a cut that matches the
- original's better a frame off fails;
+ original's better a frame off fails. A window needs 3 s whose copy frames are evenly spaced (each step within
+ a tenth of a copy frame), because the cutter re-encodes on its own time base. On a recording too choppy for
+ one, that cut is SKIPPED and named in `checks.skipped`, never counted as passed. "after-verify" never drops an
+ original after a skipped check;
- the recording clock (`clock.json`) re-measured against the re-encode and within its tolerance of the old map.
The map is then retargeted (its id kept, so windows cut through it stay current) in the swap's own lock.
- **A failed check keeps the encode.** The chunks, the state and the joined copy stay in `.compact-scratch/`, the
diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts
@@ -24,6 +24,7 @@ import {
encodeChunkArgs,
ffmpegHas,
fullDecode,
+ keepMinStep,
keptSourceFrames,
planChunks,
scanVideoPackets,
@@ -1301,8 +1302,7 @@ test("G4: a constant 60 fps source decimates to the same frames and times as bef
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 chunk = planChunks(scan, 60, 30, 60, { minStep: keepMinStep(30, 60) })[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"]) {
@@ -1321,3 +1321,79 @@ test("G4: a constant 60 fps source decimates to the same frames and times as bef
await rm(d, { recursive: true, force: true });
}
});
+
+// Review H1: a source whose timestamps are rounded to the millisecond (a
+// Matroska recording: steps of 16 and 17 ms) keeps exactly every other frame,
+// with a 67 ms gap and with a choppy pattern too; every timing check passes.
+test("H1: ms-rounded 60 fps sources (plain, a 67 ms gap, choppy) compact with every frame the rule keeps", { skip: NO_TOOLS }, async () => {
+ for (const gen of [
+ { seconds: 8, fps: 60, ext: "mkv" },
+ { seconds: 8, fps: 60, ext: "mkv", drop: [[240, 242]] },
+ { seconds: 8, fps: 60, ext: "mkv", dropExpr: "eq(mod(n,7),3)*gte(n,150)+eq(mod(n,11),5)" },
+ ] as Gen[]) {
+ 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", `${JSON.stringify(gen)}: ${log.lines.join("\n")}`);
+ const p = (await loadSavedVideo(fx.videoDir))!;
+ const src = await ptsOf(fx.source);
+ const mask = keptSourceFrames(Float64Array.from(src), keepMinStep(30, 60));
+ const want = src.filter((_, i) => mask[i]);
+ const copy = await ptsOf(path.join(fx.storeDir, p.file));
+ assert.equal(copy.length, want.length, JSON.stringify(gen));
+ assert.ok(copy.every((t, i) => Math.abs(t - want[i]) < 0.0005), `${JSON.stringify(gen)}: the copy holds the frames the rule keeps`);
+ if (!gen.drop && !gen.dropExpr) assert.deepEqual(want, src.filter((_, i) => i % 2 === 0), "plain: exactly every other frame");
+ assert.equal(p.compacted!.checks.timestamps?.over, 0);
+ });
+ }
+});
+
+// Review H3: a very choppy source (a frame dropped every 17) has no window
+// without a gap: the cuts are SKIPPED and say so; a skipped check is never
+// counted as passed, so the original is not dropped after it.
+test("H3: on a very choppy source the window cuts are skipped and named, and after-verify does not drop", { skip: NO_TOOLS }, async () => {
+ await withVideo({ gen: { seconds: 10, fps: 60, dropExpr: "eq(mod(n,17),0)*gt(n,0)" } }, async (fx) => {
+ const log = logger();
+ const r = await run(fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), SETTINGS, log.onLog);
+ assert.equal(r.status, "compacted", log.lines.join("\n"));
+ const p = (await loadSavedVideo(fx.videoDir))!;
+ const c = p.compacted!.checks;
+ assert.ok(c.skipped && c.skipped.some((x) => /window cut/.test(x)), JSON.stringify(c.skipped));
+ assert.ok(log.lines.some((l) => /SKIPPED/.test(l)), log.lines.join("\n"));
+ assert.equal((r as { dropped: boolean }).dropped, false);
+ assert.ok(log.lines.some((l) => /skipped .* does not drop/.test(l)), log.lines.join("\n"));
+ });
+});
+
+// Review H4: the video pass decodes 0:v:0 alone; audio damage the copy does
+// not share with its source is fatal, damage it carries over from it is not.
+test("H4: the full decode — video alone, then the audio against the source's own", { skip: NO_TOOLS }, async () => {
+ const d = await mkdtemp(path.join(tmpdir(), "compact-aac-"));
+ try {
+ const v = path.join(d, "v.mp4");
+ const a = path.join(d, "a.aac");
+ await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=30:d=4", "-c:v", "libx264", "-preset", "ultrafast", v]);
+ await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=4", "-c:a", "aac", "-b:a", "64k", a]);
+ const bytes = await readFile(a);
+ for (let i = Math.floor(bytes.length / 2); i < Math.floor(bytes.length / 2) + 600; i += 1) bytes[i] ^= 0x5a;
+ const aBad = path.join(d, "abad.aac");
+ await writeFile(aBad, bytes);
+ const mux = async (out: string, audio: string) => execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-i", v, "-i", audio, "-map", "0:v", "-map", "1:a", "-c", "copy", out]);
+ const clean = path.join(d, "clean.mp4");
+ const damaged = path.join(d, "damaged.mp4");
+ await mux(clean, a);
+ await mux(damaged, aBad);
+ const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "" };
+ // The copy's audio is damaged and its source's is not: fatal.
+ const r1 = await fullDecode(paths, damaged, undefined, clean);
+ assert.equal(r1.ok, false, JSON.stringify(r1));
+ assert.match(r1.why!, /audio/);
+ // The same damage in the source (the audio is copied packet for packet): a note.
+ const r2 = await fullDecode(paths, damaged, undefined, damaged);
+ assert.equal(r2.ok, true, JSON.stringify(r2));
+ assert.ok(r2.notes?.some((x) => /the source's own audio/.test(x)), JSON.stringify(r2.notes));
+ assert.deepEqual(await fullDecode(paths, clean, undefined, clean), { ok: true });
+ } finally {
+ await rm(d, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts
@@ -105,12 +105,11 @@ import {
concatList,
countVideoFrames,
expectedCopyPts,
- keptSourceFrames,
+ keepMinStep,
+ keepSelect,
nominalFps,
- selectExpr,
sourceGaps,
wholeRatio,
- type KeptRuns,
type SourceGaps,
cutIsOffset,
encodeChunkArgs,
@@ -157,8 +156,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).
-// 4: the kept frames decided by time (review G4) and saved.
-const STATE_VERSION = 4;
+// 5: the kept frames by ONE constant rule (review H1); its step saved.
+const STATE_VERSION = 5;
export type Presence = { onPlatform: boolean; availability: Availability | null; why: string };
@@ -177,7 +176,9 @@ 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; notes?: string[] }>;
+ // `reference`: the source, whose own audio decode excuses audio damage the
+ // copy carries over packet for packet.
+ fullDecode?: (file: string, signal?: AbortSignal, reference?: string) => 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>;
@@ -238,7 +239,7 @@ function resolveDeps(paths: Paths, settings: SavedVideoCompactionSettings, deps:
{ estimateMB: 300, nice: true, ...(o.signal ? { signal: o.signal } : {}) },
);
}),
- fullDecode: deps.fullDecode ?? ((f, s) => fullDecode(paths, f, s)),
+ fullDecode: deps.fullDecode ?? ((f, s, ref) => fullDecode(paths, f, s, ref)),
audioHash: deps.audioHash ?? ((f, s) => audioPacketsHash(paths.ffmpegBin, f, s, paths.ffprobeBin)),
inventory: deps.inventory ?? ((f, skip) => streamInventory(paths.ffprobeBin, f, skip)),
wholeFile: deps.wholeFile ?? ((o) => compareWholeFile(paths, o)),
@@ -554,9 +555,10 @@ 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;
+ // Under a whole ratio: the step of the rule that decides which source
+ // frames the copy keeps (keepMinStep); the encoder's select and every check
+ // apply this one rule.
+ keepMinStep?: number;
chunks: ChunkState[];
};
@@ -767,8 +769,8 @@ async function compactPlanned(
const scan = await deps.scan(src, signal);
const nominal = nominalFps(scan.pts) ?? probe.fps;
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);
+ const keep = m && nominal ? { minStep: keepMinStep(nominal / m, nominal) } : undefined;
+ const plan = planChunks(scan, s.chunkMinutes * 60, fps, nominal, keep);
if (!plan.length) return { status: "failed", reason: "the source has no video packets" };
const n = scan.pts.length;
state = {
@@ -785,7 +787,7 @@ async function compactPlanned(
sourceMaxGap: maxGap(scan.pts),
sourceFps: nominal,
sourceGaps: sourceGaps(scan.pts),
- ...(kept ? { kept } : {}),
+ ...(keep ? { keepMinStep: keep.minStep } : {}),
chunks: plan.map((c) => ({ ...c, file: `chunk-${String(c.index).padStart(4, "0")}${CHUNK_EXT}`, done: false })),
};
await writeState();
@@ -1131,6 +1133,11 @@ async function verify(o: {
const fail = (why: string): void => {
problems.push(why);
};
+ // A check that could not be made on this source: named on the record,
+ // never counted as passed.
+ const skip = (what: string): void => {
+ checks.skipped = [...(checks.skipped ?? []), what];
+ };
const fatal = (why: string): never => {
problems.push(why);
throw new VerifyFailure(problems.join("; "), { ...checks, failures: [...problems] }, failedChunks);
@@ -1148,7 +1155,7 @@ async function verify(o: {
// The source's NOMINAL rate (its median frame step), as the encode took it.
const srcFps = state.sourceFps ?? o.probe.fps;
log(`${tag}: verifying — a full decode first…`);
- const dec = await deps.fullDecode(o.muxed, signal);
+ const dec = await deps.fullDecode(o.muxed, signal, o.src);
checks.decoded = dec.ok;
// Lines the decode printed that are not damage (a null-muxer timestamp
// line, anything unrecognised): kept, never fatal.
@@ -1165,25 +1172,11 @@ 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, 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 keepRule = state.keepMinStep ? { minStep: state.keepMinStep } : undefined;
+ const expectedPts = expectedCopyPts(srcScan.pts, state.chunks, ratio, o.fps && !ratio ? o.fps : null, keepRule);
+ // The kept frames' select for the source side of every comparison: the
+ // encoder's one constant rule (each comparison starts on a kept frame).
+ const keptSelect = (): string | undefined => (keepRule ? keepSelect(keepRule.minStep) : undefined);
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` : ""}`);
@@ -1257,9 +1250,16 @@ async function verify(o: {
at: Number(Math.max(0, rel + op.formatStart - copyT0 - quarter).toFixed(4)),
sourceAt: Number(Math.max(0, rel + o.probe.formatStart - srcT0 - quarter).toFixed(4)),
});
- const snap = (t: number, seconds: number): number => {
+ // `regular`: no step in [start, start + seconds] off one copy frame by
+ // more than a tenth — a window the evidence cutter (an x264 re-encode on its
+ // own time base) carries frame for frame. A cut needs one (review H3); an
+ // excerpt does not (it is no re-encode, and both sides keep frames by the
+ // same rule across any gap).
+ const copyStep = 1 / (state.keepMinStep && srcFps ? srcFps / (ratio ?? 1) : outFps);
+ const irregularAt = (j: number) => Math.abs(expRel[j] - expRel[j - 1] - copyStep) > copyStep / 10;
+ const snap = (t: number, seconds: number, regular = false): { rel: number; regular: boolean } => {
const rel = expRel;
- if (!rel.length) return t;
+ if (!rel.length) return { rel: t, regular: true };
let lo = 0;
let hi = rel.length - 1;
while (lo < hi) {
@@ -1268,11 +1268,12 @@ async function verify(o: {
else hi = mid;
}
let i = lo;
- const step = 1.5 / outFps;
- for (let j = i + 1; j < rel.length && rel[j] <= rel[i] + seconds + 1 / outFps; j += 1) {
- if (rel[j] - rel[j - 1] > step) i = j;
+ if (!regular) return { rel: rel[i], regular: true };
+ for (let j = i + 1; j < rel.length && rel[j] <= rel[i] + seconds + copyStep; j += 1) {
+ if (irregularAt(j)) i = j;
}
- return rel[i];
+ const ok = rel[i] + seconds <= rel[rel.length - 1];
+ return { rel: rel[i], regular: ok };
};
// The audio, copied: identical packets AT IDENTICAL TIMES — with the
@@ -1312,7 +1313,7 @@ async function verify(o: {
scratchDir: o.scratch,
fps: o.fps,
sourceFps: srcFps,
- ...(state.kept ? { sourceSelect: keptSelect() } : {}),
+ ...(keepRule ? { sourceSelect: keptSelect() } : {}),
sourceWidth: o.probe.width,
sourceHeight: o.probe.height,
tileFloor: s.wholeFileTileMin,
@@ -1409,21 +1410,21 @@ async function verify(o: {
await step("the excerpt scores", async () => {
const metric: "vmaf" | "ssim" = (await deps.hasVmaf().catch(() => false)) ? "vmaf" : "ssim";
const lastAt = Math.max(0, srcSeconds - EXCERPT_SECONDS - 0.25);
- const times = new Set<number>(sampleTimes(srcSeconds, s.qualitySamples, EXCERPT_SECONDS, outFps).map((t) => snap(t + relStart, EXCERPT_SECONDS)));
+ const times = new Set<number>(sampleTimes(srcSeconds, s.qualitySamples, EXCERPT_SECONDS, outFps).map((t) => snap(t + relStart, EXCERPT_SECONDS).rel));
// …and at least one every wholeFileWindowSeconds across the whole file: a
// degraded stretch longer than the local floor's window looks steady to
// that floor, and always holds one of these.
- for (let t = s.wholeFileWindowSeconds / 2; t < lastAt; t += s.wholeFileWindowSeconds) times.add(snap(t + relStart, EXCERPT_SECONDS));
+ for (let t = s.wholeFileWindowSeconds / 2; t < lastAt; t += s.wholeFileWindowSeconds) times.add(snap(t + relStart, EXCERPT_SECONDS).rel);
for (const c of state.chunks) {
const from = c.from - state.sourceFirstPts;
const to = c.last ? srcSeconds : c.to - state.sourceFirstPts;
- if (c.index > 0) times.add(snap(Math.min(lastAt, Math.max(0, from - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS));
- times.add(snap(Math.min(lastAt, Math.max(0, (from + to) / 2 - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS));
+ if (c.index > 0) times.add(snap(Math.min(lastAt, Math.max(0, from - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS).rel);
+ times.add(snap(Math.min(lastAt, Math.max(0, (from + to) / 2 - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS).rel);
}
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);
+ const sourceSelect = keptSelect();
if (signal?.aborted) throw new Error("cancelled");
scores.push(
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 }),
@@ -1441,12 +1442,18 @@ async function verify(o: {
// Real windows cut from each, compared frame by frame.
await step("the window cuts", async () => {
- const cutTimes = sampleTimes(srcSeconds, CUT_SAMPLES, CUT_SECONDS, outFps).map((t) => snap(t + relStart, CUT_SECONDS));
+ const cutTimes = sampleTimes(srcSeconds, CUT_SAMPLES, CUT_SECONDS, outFps).map((t) => ({ t, ...snap(t + relStart, CUT_SECONDS, true) }));
checks.cuts = [];
checks.cutSsimMin = CUT_SSIM_MIN;
- for (const rel of cutTimes) {
+ for (const { t, rel, regular } of cutTimes) {
+ // SKIPPED, AND SAID (review H3): a recording too choppy for a window the
+ // cutter carries frame for frame. A skipped check is named, never passed.
+ if (!regular) {
+ skip(`the window cut near ${t.toFixed(1)} s: no ${CUT_SECONDS} s from there on without a dropped or uneven frame`);
+ continue;
+ }
const { at, sourceAt } = seekPair(rel);
- const sourceSelect = keptSelect(rel + o.probe.formatStart, CUT_SECONDS);
+ const sourceSelect = keptSelect();
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})`);
@@ -1457,7 +1464,7 @@ async function verify(o: {
);
}
}
- log(`${tag}: ${checks.cuts.length} window cut(s) through the evidence cutter compared with the original's.`);
+ log(`${tag}: ${checks.cuts.length} window cut(s) through the evidence cutter compared with the original's${checks.skipped?.length ? `; SKIPPED: ${checks.skipped.join("; ")}` : ""}.`);
});
// The recording clock.
@@ -1577,6 +1584,13 @@ 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.skipped?.length) {
+ log(
+ `${tag}: the verification skipped ${pointer.compacted.checks.skipped.length} check(s) (${pointer.compacted.checks.skipped.join("; ")}): ` +
+ `"after-verify" does not drop the original ${original.file}.`,
+ );
+ return { dropped: false, review: state() };
+ }
if (!pointer.compacted?.checks.wholeFile || !pointer.compacted.checks.wholeFile.chroma || !pointer.compacted.checks.chunkMeans) {
log(
`${tag}: the verification has no whole-file luma, colour AND per-chunk comparison: "after-verify" does not drop the original ${original.file}.`,
diff --git a/common/lib/compactMedia-server.ts b/common/lib/compactMedia-server.ts
@@ -236,8 +236,8 @@ export type ChunkPlan = {
// 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).
+ // the rate is reduced by a whole ratio — the constant `select` (keepSelect)
+ // that keeps the file's KEPT FRAMES among them.
fromIndex?: number;
toIndex?: number;
select?: string;
@@ -264,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, kept?: KeptRuns): ChunkPlan[] {
+export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: number | null, sourceFps?: number | null, keep?: KeepRule): ChunkPlan[] {
const { pts, keyframes } = scan;
if (!pts.length) return [];
const first = pts[0];
@@ -284,7 +284,7 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe
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 mask = keep && m ? keptSourceFrames(pts, keep.minStep) : null;
const onGrid = (k: number) => {
if (!outFps) return true;
if (mask) return mask[indexOf(k)] === 1;
@@ -318,7 +318,7 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe
: framesAtFps(pts, from, to, outFps, i + 1 === starts.length),
fromIndex: a,
toIndex: b,
- ...(mask ? { select: selectExpr(kept!, a, b) } : {}),
+ ...(mask ? { select: keepSelect(keep!.minStep) } : {}),
...(i + 1 === starts.length ? { last: true } : {}),
});
}
@@ -394,7 +394,13 @@ 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", `${chunk.select ? `select='${chunk.select}',` : 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",
+ // …ON THE SOURCE'S OWN TIME BASE (review H1): the default, 1 / the
+ // frame rate, rounded a millisecond-stamped recording's times onto a
+ // 1/60 s grid (up to 0.67 ms off); the 90 kHz copy holds them exactly.
+ "-enc_time_base:v", "demux",
+ ]),
"-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})`,
@@ -463,52 +469,43 @@ 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;
+// THE KEPT FRAMES (reviews G4, H1). A source capped by a whole ratio keeps a
+// frame when at least `keepMinStep` 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, after a gap the next frame; each kept frame keeps its own pts.
+//
+// ONE CONSTANT RULE, the same in ffmpeg and in the code: the encoder's select
+// is `keepSelect` (a few dozen characters, whatever the file — a set of runs
+// fragmented into hundreds of thousands on a recording with millisecond
+// timestamps, and broke ffmpeg's parser and argv), and every check that pairs
+// source and copy frames derives the kept set from the same rule
+// (`keptSourceFrames`). The step is one copy frame less HALF A SOURCE FRAME
+// (less 0.25 ms more): between one source step and two, so a 60 fps source
+// whose timestamps are rounded to the millisecond (16, 17, 17 ms) keeps
+// exactly every other frame, and off every millisecond and 90 kHz tick, so a
+// rounding can never put a step exactly on it.
+export type KeepRule = { minStep: number };
+
+export function keepMinStep(outFps: number, sourceFps: number): number {
+ return Number((1 / outFps - 0.5 / sourceFps - 0.00025).toFixed(6));
+}
+
+export function keptSourceFrames(pts: Float64Array, minStep: number): Uint8Array {
+ const m = new Uint8Array(pts.length);
let last = -Infinity;
for (let i = 0; i < pts.length; i += 1) {
- if (i > 0 && pts[i] - last < min) continue;
+ if (i > 0 && pts[i] - last < minStep) continue;
+ m[i] = 1;
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 rule as ffmpeg's select: the first frame, then each one at least
+// `minStep` after the last selected.
+export function keepSelect(minStep: number): string {
+ return `isnan(prev_selected_t)+gte(t-prev_selected_t,${minStep.toFixed(6)})`;
}
// The nominal frame rate of a scan: 1 / its typical frame step — the mean of
@@ -570,12 +567,12 @@ export function expectedCopyPts(
chunks: Pick<ChunkPlan, "from" | "to" | "expectedFrames">[],
ratio: number | null,
fps: number | null,
- kept?: KeptRuns,
+ keep?: KeepRule,
): Float64Array {
const out: number[] = [];
- if (kept) {
- // The file's kept frames, as the encode's `select` kept them.
- const mask = keptMask(kept, pts.length);
+ if (keep) {
+ // The file's kept frames, by the rule the encode's `select` applied.
+ const mask = keptSourceFrames(pts, keep.minStep);
for (let i = 0; i < pts.length; i += 1) if (mask[i]) out.push(pts[i]);
return Float64Array.from(out);
}
@@ -632,6 +629,10 @@ export function compareCopyPts(expected: Float64Array, actual: Float64Array, tol
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,
+ // Review H4: references and bitstreams, the container, AAC.
+ /frame num gap/i, /could not find ref/i, /unknown obu/i, /partial file/i,
+ /reserved bit set/i, /prediction is not allowed/i, /is not allocated/i, /input buffer exhausted/i,
+ /exceeds limit/i, /inconsistent channel configuration/i,
];
export const DECODE_BENIGN: RegExp[] = [/non[- ]monotonic(ally increasing)? dts/i, /^last message repeated/i];
@@ -653,20 +654,48 @@ export function classifyDecodeStderr(text: string): { fatal: string[]; benign: s
// 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[] }> {
+//
+// TWO PASSES (review H4). The VIDEO, 0:v:0 alone, stopping at its first
+// error: any fatal line fails the copy. Then the AUDIO, every track: it is the
+// source's, packet for packet (checked apart), so damage in it is the
+// source's — with `reference` (the source) given, fatal audio lines the
+// source's own audio decode shows as many of are a note; more than the
+// source's fail.
+async function decodePass(paths: GatedPaths, file: string, map: string[], xerror: boolean, signal?: AbortSignal) {
try {
const err = await runHeavyFfmpeg(
paths,
- ["-nostdin", "-hide_banner", "-v", "error", "-xerror", "-i", file, "-map", "0:v:0", "-map", "0:a?", "-enc_time_base", "demux", "-f", "null", "-"],
+ ["-nostdin", "-hide_banner", "-v", "error", ...(xerror ? ["-xerror"] : []), "-i", file, ...map, "-enc_time_base", "demux", "-f", "null", "-"],
{ estimateMB: DECODE_ESTIMATE_MB, ...(signal ? { signal } : {}) },
);
- 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 } : {}) };
+ return { exited: true, ...classifyDecodeStderr(err) };
} catch (e) {
if (signal?.aborted) throw e;
- return { ok: false, why: (e as Error).message };
+ return { exited: false, fatal: [(e as Error).message], benign: [] as string[], notes: [] as string[] };
+ }
+}
+
+export async function fullDecode(
+ paths: GatedPaths,
+ file: string,
+ signal?: AbortSignal,
+ reference?: string,
+): Promise<{ ok: boolean; why?: string; notes?: string[] }> {
+ const v = await decodePass(paths, file, ["-map", "0:v:0"], true, signal);
+ if (v.fatal.length) return { ok: false, why: `video: ${v.fatal.slice(-2).join(" | ")}` };
+ const notes = [...v.benign, ...v.notes];
+ const a = await decodePass(paths, file, ["-map", "0:a?", "-vn"], false, signal);
+ // No audio at all: ffmpeg has nothing to write and says so.
+ if (!a.exited && /does not contain any stream/i.test(a.fatal[0] ?? "")) return notes.length ? { ok: true, notes: notes.slice(0, 5) } : { ok: true };
+ if (a.fatal.length) {
+ const ref = reference ? await decodePass(paths, reference, ["-map", "0:a?", "-vn"], false, signal) : null;
+ if (!ref || !a.exited || ref.fatal.length < a.fatal.length) {
+ return { ok: false, why: `audio: ${a.fatal.slice(-2).join(" | ")}${ref ? ` (the source's own audio: ${ref.fatal.length} such line(s))` : ""}` };
+ }
+ notes.push(`audio: ${a.fatal.length} decode error line(s), as many as the source's own audio shows (copied packet for packet): ${a.fatal[0]}`);
}
+ notes.push(...a.benign, ...a.notes);
+ return notes.length ? { ok: true, notes: notes.slice(0, 5) } : { ok: true };
}
export type AudioHash = {
@@ -798,8 +827,8 @@ 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.
+ // The kept frames' `select` (keepSelect), in place of the ratio's
+ // decimation; the excerpt starts on a kept frame.
sourceSelect?: string;
seconds: number;
fps: number | null;
@@ -940,7 +969,7 @@ 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.
+ // The kept frames' `select` (keepSelect); the cut starts on a kept frame.
sourceSelect?: string;
seconds: number;
fps: number | null;
@@ -1064,8 +1093,8 @@ 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.
+ // The file's kept frames' `select` (keepSelect), in place of the
+ // ratio's decimation.
sourceSelect?: string;
sourceWidth: number | null;
sourceHeight: number | null;
@@ -1503,10 +1532,12 @@ export function judgeWholeFile(
// 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;
-// - 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.
+// - or THE SOURCE ITSELF STEPS TO HARDER PICTURE at every join where the
+// copy drops (reviews G2, H2: a scheduled segment that starts right at a
+// join): its picture detail (`sourceDetail`) is SOURCE_CHANGE_SHARE or
+// more higher inside than outside, over the 5 s either side AND over the
+// whole chunk against the neighbouring one. A bad chunk of unchanged,
+// drifting or easier picture still fails.
// One chunk: nothing to compare. Two: each against the other.
export type ChunkVerdict = {
ok: boolean;
@@ -1566,12 +1597,18 @@ export function judgeChunks(
const [inside, outside] = windows(join);
return meanOf(p, outside[0], outside[1]) - meanOf(p, inside[0], inside[1]) >= drop / 2;
};
+ // The source EXPLAINS the drop at a join (review H2) only by a step to
+ // HARDER picture (more detail inside the chunk), both sharp at the join
+ // (the 5 s either side) and SUSTAINED (the chunk's mean detail against
+ // the neighbouring chunk's, across that join). A drift, a step the other
+ // way, or noise over a flat picture explains nothing.
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 harder = (x: number, y: number) => x - y >= SOURCE_CHANGE_SHARE * Math.max(1e-6, y) && x > 1e-6;
+ if (!harder(meanOf(sourceDetail, inside[0], inside[1]), meanOf(sourceDetail, outside[0], outside[1]))) return false;
+ const nb = join === a ? spans[ci - 1] : spans[ci + 1];
+ return !!nb && harder(meanOf(sourceDetail, a, b), meanOf(sourceDetail, nb[0], nb[1]));
};
const stepping = [...(ci > 0 && stepAt(a) ? [a] : []), ...(ci < spans.length - 1 && stepAt(b) ? [b] : [])];
if (!stepping.length) {
diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts
@@ -137,6 +137,10 @@ export type SavedVideoCompactedChecks = {
// What the decode printed that is not damage (classifyDecodeStderr): a
// null-muxer timestamp line, an unrecognised one. Never fatal.
decodeNotes?: string[];
+ // Checks this source could not have (review H3: no window regular enough
+ // for the evidence cutter on a very choppy recording): named, never passed.
+ // "after-verify" never drops an original after one.
+ skipped?: string[];
// [source, re-encode] video lengths in seconds, and the allowed difference.
seconds: [number, number];
secondsTolerance: number;
@@ -573,6 +577,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) } : {}),
+ ...(Array.isArray(c.skipped) ? { skipped: c.skipped.map(String) } : {}),
...(c.timestamps && typeof c.timestamps === "object"
? (() => {
const t = obj(c.timestamps);
diff --git a/common/lib/savedVideoCompaction.test.ts b/common/lib/savedVideoCompaction.test.ts
@@ -410,56 +410,67 @@ test("G2: a segment starting at a join is exempt when the source changes there;
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})`);
+// Review G4, then H1: the kept frames by TIME, by ONE constant rule — a frame
+// when at least keepMinStep has passed since the last kept one. The rule is
+// the same in ffmpeg's select (constant size, whatever the file) and in the
+// code that pairs frames, and holds on millisecond-rounded timestamps.
+test("H1: kept frames by a constant rule, exact on ms-rounded 60 fps, a gap, a choppy pattern and a 30 fps stretch", async () => {
+ const { keepMinStep, keptSourceFrames, keepSelect, planChunks, expectedCopyPts } = await import("./compactMedia-server");
+ const min = keepMinStep(30, 60);
+ // Off any millisecond and any 90 kHz tick, between one 60 fps step and two.
+ assert.ok(min > 0.017 && min < 0.0333 && Math.abs(min * 1000 - Math.round(min * 1000)) > 0.1, String(min));
+ const ms = (x: number) => Math.round(x * 1000) / 1000;
+ const keptOf = (t: number[]) => {
+ const mask = keptSourceFrames(Float64Array.from(t), min);
+ return t.filter((_, i) => mask[i]);
+ };
+ // 60 fps rounded to the millisecond: steps 16, 17, 17 — exactly every other frame.
+ const t60 = Array.from({ length: 1200 }, (_, i) => ms(i / 60));
+ assert.deepEqual(keptOf(t60), t60.filter((_, i) => i % 2 === 0));
+ // One 67 ms gap (frames 600–602 missing): every other before, the next frame after, every other from there.
+ const gap = t60.filter((_, i) => i < 600 || i > 602);
+ const kg = keptOf(gap);
+ assert.ok(kg.includes(ms(603 / 60)), "the first frame after the gap");
+ assert.deepEqual(kg.filter((x) => x > 10.04), gap.filter((x) => x >= ms(603 / 60)).filter((_, k) => k % 2 === 0));
+ // A truly choppy pattern: no two kept closer than the rule, none skipped that it allows.
+ let seed = 7;
+ const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
+ const choppy: number[] = [];
+ for (let x = 0; x < 60; x += 0.006 + rnd() * 0.045) choppy.push(ms(x));
+ const unique = [...new Set(choppy)];
+ const kc = new Set(keptOf(unique));
+ let last = -Infinity;
+ for (const x of unique) {
+ if (kc.has(x)) {
+ assert.ok(x - last >= min - 1e-9, `${last} -> ${x}`);
+ last = x;
+ } else assert.ok(x - last < min, `${x} could be kept`);
}
- // 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);
+ // A 30 fps stretch in a 60 fps file keeps every frame of it.
+ const mixed = t60.filter((_, i) => !(i >= 300 && i < 600 && i % 2 === 1));
+ const km = keptOf(mixed);
+ assert.deepEqual(km.filter((x) => x >= 5 && x < 10), mixed.filter((x) => x >= 5 && x < 10));
+ // ffmpeg's select is one constant expression, the same for every chunk and every file.
+ const sel = keepSelect(min);
+ assert.match(sel, /^isnan\(prev_selected_t\)\+gte\(t-prev_selected_t,0\.0\d+\)$/);
+ // A 5.8-hour ms-rounded 60 fps scan with one gap: the plan is cheap and every select is that expression.
+ const n = 1_254_927;
+ const big = new Float64Array(n);
+ for (let i = 0; i < n; i += 1) big[i] = ms(0.016 + (i < n - 2 ? i : i + 3) / 60);
+ const keyframes: number[] = [];
+ for (let i = 0; i < n; i += 120) keyframes.push(big[i]);
+ const plan = planChunks({ pts: big, keyframes }, 600, 30, 60, { minStep: min });
+ const mask = keptSourceFrames(big, min);
+ let total = 0;
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.equal(c.select, sel);
+ assert.equal(mask[c.fromIndex!], 1, `chunk ${c.index} starts on a kept frame`);
+ total += c.expectedFrames;
}
- assert.deepEqual(Array.from(expectedCopyPts(pts, plan, 2, null, runs)), kept);
+ assert.equal(total, mask.reduce((x, y) => x + y, 0));
+ assert.ok(Math.abs(total - Math.ceil(n / 2)) <= 1, String(total));
+ const exp = expectedCopyPts(big, plan, 2, null, { minStep: min });
+ assert.equal(exp.length, total);
});
test("G1: what a decode's stderr means", async () => {
@@ -477,3 +488,64 @@ test("G1: what a decode's stderr means", async () => {
assert.equal(c.fatal.length, 3);
assert.deepEqual(c.notes, ["Something ffmpeg says that is neither"]);
});
+
+// Review H2: the source excuses a chunk's drop only with a SUSTAINED step
+// against its neighbour, toward harder picture; a drift excuses nothing.
+test("H2: only a sustained step to harder source picture at the join excuses a chunk", async () => {
+ const { judgeChunks } = await import("./compactMedia-server");
+ const FPS = 30;
+ const CH = 600 * FPS;
+ const N = 35;
+ const starts = Array.from({ length: N }, (_, i) => i * CH);
+ let seed = 9;
+ const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
+ const mk = (fn: (i: number) => number, noise: number) => Float32Array.from({ length: N * CH }, (_, i) => fn(i) + (rnd() - 0.5) * noise);
+ const chunkOf = (i: number) => Math.floor(i / CH);
+ const g = new Float32Array(N * CH).fill(0.99);
+ const judge = (y: Float32Array, det: Float32Array) => judgeChunks({ Y: y, U: g, V: g }, starts, null, { sigmaK: 4, margin: 0.02, fps: FPS }, det);
+ const bad = mk((i) => (chunkOf(i) === 17 ? 0.95 : 0.995), 0.004);
+ // Fails: constant detail; a change at only one of its two joins; a static
+ // source; a near-flat noisy one; a dark one drifting 15 % every 10 s; one
+ // that gets EASIER (less detail) in the chunk.
+ for (const [label, det] of [
+ ["constant", mk(() => 20, 0.4)],
+ ["one join", mk((i) => (i >= 17 * CH ? 26 : 20), 0.4)],
+ ["static", new Float32Array(N * CH)],
+ ["near-flat noisy", mk(() => 0.3, 0.3)],
+ ["drifting", mk((i) => 2 * (1 + 0.15 * Math.sin(((i / FPS) * 2 * Math.PI) / 20)), 0.6)],
+ ["easier", mk((i) => (chunkOf(i) === 17 ? 14 : 20), 0.4)],
+ ] as const) {
+ const v = judge(bad, det);
+ assert.equal(v.ok, false, label);
+ assert.ok(!v.exempt.some((e) => e.why === "the source changes at its join"), `${label}: ${JSON.stringify(v.exempt)}`);
+ }
+ // Passes: a harder segment from a join where the source's picture steps up and stays up.
+ const good = judge(mk((i) => (i >= 17 * CH && i < 20 * CH ? 0.965 : 0.995), 0.004), mk((i) => (i >= 17 * CH && i < 20 * CH ? 30 : 20), 0.4));
+ assert.equal(good.ok, true, good.why);
+ assert.ok(good.exempt.some((e) => e.why === "the source changes at its join"));
+});
+
+// Review H4: more decoder damage is fatal.
+test("H4: frame-num gaps, missing refs, unknown OBUs, partial files and AAC damage are fatal", async () => {
+ const { classifyDecodeStderr } = await import("./compactMedia-server");
+ const fatal = [
+ "[h264 @ 0x55] Frame num gap 3 1",
+ "[hevc @ 0x55] Could not find ref with POC 12",
+ "[av1 @ 0x55] Unknown OBU type 9",
+ "[mov,mp4,m4a,3gp,3g2,mj2 @ 0x55] stream 0, offset 0x1234: partial file",
+ "[aac @ 0x55] Reserved bit set.",
+ "[aac @ 0x55] Prediction is not allowed in AAC-LC.",
+ "[aac @ 0x55] channel element 1.0 is not allocated",
+ "[aac @ 0x55] Input buffer exhausted before END element found",
+ "[aac @ 0x55] Number of bands (20) exceeds limit (14).",
+ "[aac @ 0x55] Inconsistent channel configuration",
+ "[h264 @ 0x55] co located POCs unavailable",
+ "[h264 @ 0x55] reference picture missing during reorder",
+ ];
+ const notes = ["[av1 @ 0x55] Your platform doesn't support hardware accelerated AV1 decoding.", "[h264 @ 0x55] Increasing reorder buffer to 1"];
+ const benign = ["[av1 @ 0x55] Non-monotonic DTS in output stream; previous: 5, current: 5"];
+ const c = classifyDecodeStderr([...fatal, ...notes, ...benign].join("\n"));
+ assert.deepEqual(c.fatal, fatal);
+ assert.deepEqual(c.notes, notes);
+ assert.deepEqual(c.benign, benign);
+});
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -48,10 +48,13 @@
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. 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.
+ decided by TIME, by one constant rule (`select` of a few dozen characters; the same rule in the checks), so a
+ stretch where the recording ran at 30 fps keeps 30 fps and millisecond-rounded 60 fps keeps exactly every
+ other frame. The full decode keeps each stream's time base, decodes the video alone and then the audio
+ against the source's own, and fails only on damage. A chunk that drops at a join where the source's own
+ picture steps to harder and stays harder (a segment starting there) is exempt, and the failure message names
+ the join and what to do. On a recording too choppy for an even window, the window cuts are skipped and named
+ (`checks.skipped`); "after-verify" never drops after a skipped check.
- 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, 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