import { test } from "node:test"; import assert from "node:assert/strict"; import { DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS as D, compactedFileName, compactionFreeNeeded, COMPACTION_DISK_MARGIN_BYTES, decideCompaction, estimateCompaction, isDeliberatelyStored, availabilitySaysPresent, sanitizeSavedVideoCompaction, targetFps, type CompactionProbe, } from "./savedVideoCompaction"; import type { SavedVideoPointer } from "./savedVideo"; const pointer = (extra: Partial = {}): SavedVideoPointer => ({ storedAt: "2026-11-01T00:00:00Z", dir: "/store/kick/v1", file: "source-media.mp4", bytes: 12_000_000_000, keepReason: "pin", ...extra, }); const probe = (extra: Partial = {}): CompactionProbe => ({ hasVideo: true, vcodec: "h264", width: 1920, height: 1080, fps: 60, seconds: 19_000, videoKbps: 5000, audioKbps: 155, ...extra, }); const decide = (o: Partial[0]> = {}) => decideCompaction({ pointer: pointer(), platform: "kick", channelExcluded: false, mode: "select", containerPresent: true, probe: probe(), settings: D, ...o, }); test("the operator's rulings are the defaults", () => { assert.equal(D.crf, 36); assert.equal(D.preset, 8); assert.equal(D.maxFps, 30); assert.deepEqual(D.maxFpsPlatforms, ["kick", "twitch"]); assert.deepEqual(D.platforms, ["kick", "twitch", "rumble"]); // In this slice the original is kept by default (orchestrator, after review). assert.equal(D.dropOriginal, "keep"); assert.equal(D.availabilityMaxAgeDays, 7); assert.deepEqual(sanitizeSavedVideoCompaction(undefined), D); }); test("sanitize clamps, lowercases platforms and refuses unknown values", () => { const s = sanitizeSavedVideoCompaction({ platforms: [" Kick ", "kick", "YouTube", 3], crf: 99, preset: 2, chunkMinutes: 0, dropOriginal: "always", maxFps: 0, }); assert.deepEqual(s.platforms, ["kick", "youtube"]); assert.equal(s.crf, D.crf); assert.equal(s.preset, D.preset); assert.equal(s.chunkMinutes, D.chunkMinutes); assert.equal(s.dropOriginal, "keep"); assert.equal(s.maxFps, 0); assert.equal(sanitizeSavedVideoCompaction({ dropOriginal: "after-verify" }).dropOriginal, "after-verify"); }); test("deliberately stored: a pin, an explicit persist, a requested container — never keep-latest, persist-kept or a legacy pointer", () => { assert.equal(isDeliberatelyStored({ keepReason: "pin" }), true); assert.equal(isDeliberatelyStored({ keepReason: "override", explicit: true }), true); // persist-kept (the keep-latest catch-up) writes "override" with no explicit // mark; a pointer from before the mark cannot say which it was. assert.equal(isDeliberatelyStored({ keepReason: "override" }), false); assert.equal(isDeliberatelyStored({ keepReason: "keep-latest", origin: { requestedBy: "umtool" } }), true); assert.equal(isDeliberatelyStored({ keepReason: "keep-latest" }), false); assert.equal(isDeliberatelyStored({}), false); }); test("a record's word: public or unlisted only (the gone rule itself is platformPresence)", () => { assert.equal(availabilitySaysPresent("public"), true); assert.equal(availabilitySaysPresent("unlisted"), true); for (const a of ["deleted", "private", "members_only", "needs_auth", "error", null, undefined] as const) { assert.equal(availabilitySaysPresent(a), false, String(a)); } }); test("the selector picks only deliberately stored AND platform AND bitrate AND height", () => { assert.deepEqual(decide(), { ok: true }); assert.match((decide({ pointer: pointer({ keepReason: "keep-latest" }) }) as { reason: string }).reason, /keep-latest/); assert.match((decide({ pointer: pointer({ keepReason: undefined }) }) as { reason: string }).reason, /legacy pointer/); assert.match((decide({ platform: "youtube" }) as { reason: string }).reason, /platform youtube is not selected/); assert.match((decide({ probe: probe({ videoKbps: 2500 }) }) as { reason: string }).reason, /below minVideoMbps 3/); assert.match((decide({ probe: probe({ height: 480 }) }) as { reason: string }).reason, /below minHeight/); assert.deepEqual(decide({ platform: "rumble", probe: probe({ fps: 30, videoKbps: 3200, height: 720 }) }), { ok: true }); }); test("an explicit item the selector would not pick needs belowThreshold; the deliberate rule has no override", () => { const below = decide({ mode: "explicit", platform: "youtube", probe: probe({ videoKbps: 400, height: 360 }) }); assert.equal(below.ok, false); assert.match((below as { reason: string }).reason, /platform youtube is not selected; named explicitly, it is compacted only with "belowThreshold": true/); assert.deepEqual(decide({ mode: "explicit", platform: "youtube", probe: probe({ videoKbps: 400 }), belowThreshold: true }), { ok: true, belowThreshold: "platform youtube is not selected", }); assert.deepEqual(decide({ mode: "explicit" }), { ok: true }); assert.equal(decide({ mode: "explicit", belowThreshold: true, pointer: pointer({ keepReason: "keep-latest" }) }).ok, false); }); test("a pointer that already keeps an original (of this or an earlier copy) is never compacted again", () => { for (const keptAs of ["original", "former-original"] as const) { const d = decide({ pointer: pointer({ alternates: [{ file: "a.mp4", bytes: 1, storedAt: "", setAsideAt: "", keptAs }] }) }); assert.match((d as { reason: string }).reason, /already keeps an original/); } }); test("already compacted, opted out, audio-only, already AV1 and a missing container are skipped", () => { const compacted = pointer({ compacted: { at: "x" } as SavedVideoPointer["compacted"] }); assert.deepEqual(decide({ pointer: compacted }), { ok: false, reason: "already compacted" }); assert.match((decide({ channelExcluded: true }) as { reason: string }).reason, /opts out/); assert.match((decide({ probe: probe({ hasVideo: false }) }) as { reason: string }).reason, /audio-only/); assert.match((decide({ probe: probe({ vcodec: "av1" }) }) as { reason: string }).reason, /already AV1/); assert.match((decide({ containerPresent: false }) as { reason: string }).reason, /not in the store/); }); test("60 -> 30 fps on Kick and Twitch only, and only above the cap", () => { assert.equal(targetFps(60, "kick", D), 30); assert.equal(targetFps(59.94, "twitch", D), 30); assert.equal(targetFps(30, "kick", D), null); assert.equal(targetFps(60, "rumble", D), null); assert.equal(targetFps(60, "kick", { ...D, maxFps: 0 }), null); }); test("the estimate follows the design's measured shares", () => { const p = probe({ seconds: 20_940, videoKbps: 5000, audioKbps: 155 }); const at60 = estimateCompaction({ probe: p, crf: 36, fps: null }); assert.ok(Math.abs(at60.share - 0.64) < 1e-9); const at30 = estimateCompaction({ probe: p, crf: 36, fps: 30 }); assert.ok(Math.abs(at30.share - 0.44) < 1e-6, String(at30.share)); assert.ok(at30.bytes[1] < at60.bytes[1]); assert.ok(at60.bytes[0] < at60.bytes[1]); assert.ok(at60.hours[0] < at60.hours[1]); // crf 40 interpolates to its row. assert.ok(Math.abs(estimateCompaction({ probe: p, crf: 40, fps: null }).share - 0.47) < 1e-9); }); test("the disk floor is two outputs less what the chunks hold, plus the margin", () => { assert.equal(compactionFreeNeeded(1000, 0), 2000 + COMPACTION_DISK_MARGIN_BYTES); assert.equal(compactionFreeNeeded(1000, 600), 1400 + COMPACTION_DISK_MARGIN_BYTES); }); test("the compacted copy has its own name, never the original's", () => { const at = new Date("2026-11-14T03:12:09Z"); assert.equal(compactedFileName(at), "source-media.compact-av1-20261114031209.mp4"); assert.equal( compactedFileName(at, ["source-media.compact-av1-20261114031209.mp4"]), "source-media.compact-av1-20261114031209-2.mp4", ); }); test("D2: the relative floor uses a robust spread, so a few bad frames cannot widen their own floor", async () => { const { judgeWholeFile } = await import("./compactMedia-server"); const frames = new Float32Array(600).map((_, i) => 0.998 + ((i % 7) - 3) * 0.0002); for (let i = 300; i < 320; i += 1) frames[i] = 0.93; // above the hard floor of 0.9 const t = { minFrame: 0.9, meanFloor: 0.97, sigmaK: 8, sigmaMinMargin: 0.03, tileRunFrames: 2, expectedFrames: 600, fps: 30, chromaMinFrame: 0.9, chromaMeanFloor: 0.97 }; const ones = new Float32Array(600).fill(1); const v = judgeWholeFile({ frames, tiles: [], chromaU: ones, chromaV: ones }, t); // mean − 8·sd would sit near 0.90 here; the median and MAD keep it near 0.968. assert.ok(v.relativeFloor > 0.96, String(v.relativeFloor)); assert.equal(v.ok, false); assert.match(v.why!, /below its neighbourhood's floor/); frames.fill(0.998, 300, 320); assert.equal(judgeWholeFile({ frames, tiles: [], chromaU: ones, chromaV: ones }, t).ok, true); // The colour planes are judged on their own floors. const u = new Float32Array(600).fill(0.999); u[100] = 0.6; const c = judgeWholeFile({ frames, tiles: [], chromaU: u, chromaV: ones }, t); assert.equal(c.ok, false); assert.match(c.why!, /the colour \(U plane\) of a frame at 3\.33 s scores 0\.600/); }); // E1: the relative floor is local. The reviewer's synthetic hour: a good copy // whose picture has two modes (a webcam stretch at 0.965 inside a screen share // at 0.995) — 20%, 30% and 45% of it — PASSES on the defaults; a short defect // inside either mode still FAILS. test("E1: a good copy with two kinds of picture passes; a short defect in either still fails", async () => { const { judgeWholeFile } = await import("./compactMedia-server"); const fps = 30; const n = 3600 * fps; const jitter = (i: number) => (((i * 7919) % 11) - 5) * 0.00012; const t = { minFrame: 0.9, meanFloor: 0.97, sigmaK: 8, sigmaMinMargin: 0.03, tileRunFrames: 2, expectedFrames: n, fps, chromaMinFrame: 0.9, chromaMeanFloor: 0.97, windowFrames: 120 * fps }; const ones = new Float32Array(n).fill(1); const make = (share: number, alternate = false) => { const f = new Float32Array(n); for (let i = 0; i < n; i += 1) { const lower = alternate ? Math.floor(i / (300 * fps)) % 2 === 1 : i >= n * 0.3 && i < n * (0.3 + share); f[i] = (lower ? 0.965 : 0.995) + jitter(i); } return f; }; for (const share of [0.2, 0.3, 0.45]) { const f = make(share); const v = judgeWholeFile({ frames: f, tiles: [], chromaU: ones, chromaV: ones }, t); assert.equal(v.ok, true, `${share}: ${v.why}`); assert.ok(v.worstLocalMargin >= 0 && v.windowFrames === 3600, String(v.worstLocalMargin)); // A second of bad frames in the screen-share mode, and in the webcam mode. for (const [at, score] of [[n * 0.1, 0.955], [n * (0.3 + share / 2), 0.92]] as const) { const g = Float32Array.from(f); g.fill(score, Math.floor(at), Math.floor(at) + fps); const w = judgeWholeFile({ frames: g, tiles: [], chromaU: ones, chromaV: ones }, t); assert.equal(w.ok, false, `${share} defect at ${at}`); assert.match(w.why!, /below its neighbourhood's floor/); } } // Five-minute stretches alternating all hour long. assert.equal(judgeWholeFile({ frames: make(0, true), tiles: [], chromaU: ones, chromaV: ones }, t).ok, true); // Judged as one neighbourhood (the whole-file floor of the round before), // the 20% case fails: one stretch is one run, not a recurring kind (G1). const whole = judgeWholeFile({ frames: make(0.2), tiles: [], chromaU: ones, chromaV: ones }, { ...t, windowFrames: n }); assert.equal(whole.ok, false); assert.equal(whole.lowerState, null); }); // F-a: fast switching. A share (0.995) and a webcam (0.96) every 20 s fill each // half-window half and half, and its floor flipped with the majority. The file's // recurring lower kind of picture lends its floor to a neighbourhood holding a // fifth of its frames at that level; a second's dip in a steady stretch does not. test("F-a: a good copy switching every 20, 60 or 90 s passes; a short dip still fails", async () => { const { judgeWholeFile } = await import("./compactMedia-server"); const fps = 30; const n = 3600 * fps; const jitter = (i: number) => (((i * 7919) % 11) - 5) * 0.0004; const t = { minFrame: 0.9, meanFloor: 0.97, sigmaK: 8, sigmaMinMargin: 0.03, tileRunFrames: 2, expectedFrames: n, fps, chromaMinFrame: 0.9, chromaMeanFloor: 0.97, windowFrames: 120 * fps }; const ones = new Float32Array(n).fill(1); const judge = (f: Float32Array) => judgeWholeFile({ frames: f, tiles: [], chromaU: ones, chromaV: ones }, t); const alternate = (period: number) => Float32Array.from({ length: n }, (_, i) => (Math.floor(i / fps / period) % 2 ? 0.96 : 0.995) + jitter(i)); const dip = (f: Float32Array, at: number, score: number) => (f.fill(score, at * fps, (at + 1) * fps), f); // 60 s: a webcam closing the file's last minute (it has no block after it). for (const period of [20, 60, 90]) { const v = judge(alternate(period)); assert.equal(v.ok, true, `${period} s: ${v.why}`); assert.ok(v.lowerState && Math.abs(v.lowerState.share - 0.5) < 0.02, JSON.stringify(v.lowerState)); // A second at 0.92 inside a webcam stretch is below the webcam's own floor. const w = judge(dip(alternate(period), period + 2, 0.92)); assert.equal(w.ok, false, `${period} s dip`); assert.match(w.why!, /below its neighbourhood's floor/); } // A screen share with one 12-minute webcam stretch: a second at 0.95 inside the // share keeps the share's floor (the neighbourhood is not a fifth webcam). const once = Float32Array.from({ length: n }, (_, i) => (i >= 1000 * fps && i < 1720 * fps ? 0.96 : 0.995) + jitter(i)); assert.equal(judge(once).ok, true); const d = judge(dip(once, 300, 0.95)); assert.equal(d.ok, false); assert.match(d.why!, /below its neighbourhood's floor 0\.96/); // A file of one kind of picture has no lower state: a 20 s stretch at 0.95 fails. const plain = Float32Array.from({ length: n }, (_, i) => 0.995 + jitter(i)); assert.equal(judge(plain).lowerState, null); plain.fill(0.95, 1000 * fps, 1020 * fps); assert.equal(judge(plain).ok, false); }); // G1: only SCENE STRUCTURE makes a lower kind of picture. A periodic fault of a // few seconds (a broken setting, a per-GOP fault) used to manufacture its own // lower state and pass; runs under 8 s never count, and a run on a chunk join // never counts. G2: every chunk against the others. test("G: a periodic short fault fails, a bad chunk fails, real scene structure passes", async () => { const { judgeWholeFile } = await import("./compactMedia-server"); const fps = 30; const jitter = (i: number) => (((i * 7919) % 11) - 5) * 0.0004; const base = { minFrame: 0.9, meanFloor: 0.97, sigmaK: 8, sigmaMinMargin: 0.03, tileRunFrames: 2, fps, chromaMinFrame: 0.9, chromaMeanFloor: 0.97, windowFrames: 120 * fps }; const CH = 300 * fps; // 5-minute chunks const make = (seconds: number, at: (t: number) => number) => Float32Array.from({ length: seconds * fps }, (_, i) => at(i / fps) + jitter(i)); const judge = (f: Float32Array, o: { u?: Float32Array; chunks?: boolean } = {}) => { const ones = new Float32Array(f.length).fill(0.99); const chunkStarts = Array.from({ length: Math.ceil(f.length / CH) }, (_, k) => k * CH); return judgeWholeFile({ frames: f, tiles: [], chromaU: o.u ?? ones, chromaV: ones }, { ...base, expectedFrames: f.length, ...(o.chunks === false ? {} : { chunkStarts }) }); }; const H = 3600; // The reviewer's periodic faults (one kind of picture): every one fails again. for (const [on, period, lvl] of [[2, 8, 0.95], [2, 8, 0.93], [3, 10, 0.93], [2, 8, 0.91], [1, 4, 0.94]] as const) { const v = judge(make(H, (t) => (t % period < on ? lvl : 0.995))); assert.equal(v.ok, false, `${on}/${period} at ${lvl}`); assert.equal(v.lowerState, null); } // Good copies: alternation every 10/20/60/90 s, a webcam opening or closing // the file, a 20/30/45% webcam stretch, a game hour across several chunks. for (const p of [10, 20, 60, 90]) { const v = judge(make(H, (t) => (Math.floor(t / p) % 2 ? 0.96 : 0.995))); assert.equal(v.ok, true, `alternating ${p} s: ${v.why}`); assert.ok(v.chunks && v.chunks.worst === null); } assert.equal(judge(make(H, (t) => (t >= H - 50 ? 0.96 : 0.995))).ok, true); assert.equal(judge(make(H, (t) => (t < 50 ? 0.96 : 0.995))).ok, true); for (const share of [0.2, 0.3, 0.45]) assert.equal(judge(make(H, (t) => (t >= 1000 && t < 1000 + share * H ? 0.96 : 0.995))).ok, true, `${share}`); const game = judge(make(4 * H, (t) => (t >= 4410 && t < 8010 ? 0.975 : 0.995))); assert.equal(game.ok, true, game.why); assert.ok(game.chunks!.exempt.some((x) => x.why === "no step at its joins")); // 1 s dips still fail. assert.equal(judge(make(H, (t) => (t >= 300 && t < 301 ? 0.95 : 0.995))).ok, false); assert.equal(judge(make(H, (t) => (t >= 1022 && t < 1023 ? 0.92 : Math.floor(t / 20) % 2 ? 0.96 : 0.995))).ok, false); // Bad chunks (20 chunks, one kind of picture): 1, 2, 4, 6 at 0.96/0.94/0.92 fail on the chunk check. for (const lvl of [0.96, 0.94, 0.92]) { for (const bad of [1, 2, 4, 6]) { const at = new Set(Array.from({ length: bad }, (_, k) => 2 + k * 3)); const v = judge(make(20 * 300, (t) => (at.has(Math.floor(t / 300)) ? lvl : 0.995))); assert.equal(v.ok, false, `${bad} at ${lvl}`); assert.match(v.why!, /^chunk (3|6|9|12|15|18) of 20 .* on Y, below the other chunks' floor/); // Without the chunk joins (the round before): a stretch longer than the window passed. if (lvl !== 0.92) assert.equal(judge(make(20 * 300, (t) => (at.has(Math.floor(t / 300)) ? lvl : 0.995)), { chunks: false }).ok, true); } } // Six bad chunks would be a tenth of the file in 3+ runs — a lower state of // their own — but their runs sit on chunk joins: refused. const six = judge(make(20 * 300, (t) => ([2, 5, 8, 11, 14, 17].includes(Math.floor(t / 300)) ? 0.96 : 0.995))); assert.match(six.lowerStateRefused ?? "", /chunk join/); // A chunk worse only in colour fails on that plane. const f = make(20 * 300, () => 0.995); const u = Float32Array.from({ length: f.length }, (_, i) => (Math.floor(i / CH) === 7 ? 0.965 : 0.99)); const c = judge(f, { u }); assert.equal(c.ok, false); assert.match(c.why!, /^chunk 8 of 20 .* on U/); // Bad chunks inside fast switching: the bad run merges with a webcam run at // one end and sits on the join at the other — not a scene; it fails. const alt = judge(make(20 * 300, (t) => (Math.floor(t / 300) === 6 ? 0.93 : Math.floor(t / 20) % 2 ? 0.96 : 0.995))); assert.equal(alt.ok, false); assert.match(alt.why!, /^chunk 7 of 20/); }); // THE SOURCE'S TIMESTAMPS (review, the first real run): the helpers. test("timestamps: dropped frames found, chunk starts on even indexes, the copy's times derived and compared", async () => { const { planChunks, expectedCopyPts, compareCopyPts, sourceGaps, nominalFps, concatList } = await import("./compactMedia-server"); // 60 fps, 20 s; 31 frames dropped at 5 s (odd) and 5 at the very end. const all: number[] = []; for (let i = 0; i < 1200; i += 1) if (!(i >= 300 && i <= 330) && !(i >= 1190 && i <= 1194)) all.push(i / 60); const pts = Float64Array.from(all); assert.ok(Math.abs(nominalFps(pts)! - 60) < 1e-9); // A container's ticks: a 30 fps mkv (ms), 60 fps in 1/15360 s, and a true 59.94. const ticks = (rate: number, tick: number) => Float64Array.from({ length: 600 }, (_, i) => Math.round(i / rate / tick) * tick); assert.equal(nominalFps(ticks(30, 0.001)), 30); assert.equal(nominalFps(ticks(60, 1 / 15360)), 60); assert.ok(Math.abs(nominalFps(ticks(60000 / 1001, 1 / 90000))! - 60000 / 1001) < 1e-9); const g = sourceGaps(pts); assert.equal(g.count, 2); assert.ok(Math.abs(g.largest - 32 / 60) < 1e-9 && Math.abs(g.largestAt - 299 / 60) < 1e-9, JSON.stringify(g)); assert.ok(Math.abs(g.totalSeconds - (31 + 5) / 60) < 1e-9); // Keyframes every 45 FRAMES of the file (so some fall on odd indexes). const keyframes = all.filter((_, i) => i % 45 === 0); const plan = planChunks({ pts, keyframes }, 4, 30, 60); const indexOf = (t: number) => all.findIndex((x) => Math.abs(x - t) < 1e-9); assert.ok(plan.length >= 3); for (const c of plan) assert.equal(indexOf(c.from) % 2, 0, `chunk at ${c.from}`); // The time grid would have taken a keyframe at an ODD index after the gap. const oddOnTimeGrid = keyframes.find((k) => k > 6 && Math.abs(k * 30 - Math.round(k * 30)) < 0.02 && indexOf(k) % 2 === 1); assert.ok(oddOnTimeGrid !== undefined, "the case the index rule exists for"); // The copy's expected times: every other source frame, chunk by chunk. const exp = expectedCopyPts(pts, plan, 2, null); assert.equal(exp.length, plan.reduce((n, c) => n + c.expectedFrames, 0)); assert.ok(exp.every((t, i) => t === pts[2 * i])); // A copy at those times passes; one re-timed to 30 fps fails from the gap on. assert.equal(compareCopyPts(exp, Float64Array.from(exp), 0.001).over, 0); const cfr = exp.map((_, i) => i / 30); const bad = compareCopyPts(exp, cfr, 0.001, [0, 100]); // Off by both gaps at the end (the error only grows). assert.ok(bad.over > 0 && Math.abs(bad.maxDeviation - 36 / 60) < 1 / 30, JSON.stringify({ ...bad, perChunk: undefined })); assert.ok(bad.perChunk[0] < 0.001 && bad.perChunk[1] > 0.5); // 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, 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`); } // 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(c.select, sel); assert.equal(mask[c.fromIndex!], 1, `chunk ${c.index} starts on a kept frame`); total += c.expectedFrames; } 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 () => { 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"]); }); // 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); });