// COMPACTING A SAVED VIDEO — the pure half: the settings block, the selector, // the estimate and the names (controller/compactSavedVideos.ts does the work). // // A large stored stream (Kick, Twitch, the high-bitrate half of Rumble) is // re-encoded to AV1 (SVT-AV1 preset 8, crf 36, a keyframe every 5 s, the // source's height, 60 -> 30 fps on Kick and Twitch, the audio copied // bit-for-bit), verified, and made the ACTIVE copy; the original stays beside // it as the alternate `keptAs: "original"` until a separate step drops it. // Operator rulings, 13 Nov 2026: // - crf 36, preset 8, keyint 5 s, audio copied; // - Kick and Twitch above 30 fps go to 30; // - the original may be dropped once every check passed, in a step of its // own that reads the finished file back (`dropOriginal: "after-verify"`); // in this slice the DEFAULT is "keep" (orchestrator, 13 Nov, after review), // and "after-verify" drops only when the verification included the // whole-file comparison; // - DELIBERATELY STORED videos only (isDeliberatelyStored, below), never the // keep-latest containers and never the audio beside the record; // - the selector is deliberately stored AND platform in the set AND the // stored video bitrate above a threshold (Rumble's high-bitrate half); // YouTube is left alone by default; // - a video gone from its platform is compacted too, but its original is // NEVER dropped automatically: a person reviews the compacted copy first. // // Pure: no node imports (the editor's client pages read the labels). import type { FieldDocs } from "./fieldDocs"; import { keepsAnyOriginal, type SavedVideoPointer } from "./savedVideo"; import type { Availability } from "./availability"; // --- settings ----------------------------------------------------------------- export const COMPACTION_DROP_ORIGINAL = ["after-verify", "keep"] as const; export type CompactionDropOriginal = (typeof COMPACTION_DROP_ORIGINAL)[number]; export type SavedVideoCompactionSettings = { platforms: string[]; minVideoMbps: number; minHeight: number; crf: number; preset: number; maxFps: number; maxFpsPlatforms: string[]; chunkMinutes: number; qualitySamples: number; vmafMinMean: number; vmafMinSample: number; ssimMinMean: number; ssimMinSample: number; wholeFileSsimMin: number; wholeFileSsimMean: number; wholeFileSigmaK: number; wholeFileSigmaMargin: number; wholeFileTileMin: number; wholeFileTileRunFrames: number; wholeFileChromaMin: number; wholeFileChromaMean: number; wholeFileWindowSeconds: number; wholeFileLowerRunSeconds: number; wholeFileChunkSigmaK: number; wholeFileChunkMargin: number; availabilityMaxAgeDays: number; dropOriginal: CompactionDropOriginal; }; export const DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS: SavedVideoCompactionSettings = { platforms: ["kick", "twitch", "rumble"], minVideoMbps: 3, minHeight: 720, crf: 36, preset: 8, maxFps: 30, maxFpsPlatforms: ["kick", "twitch"], chunkMinutes: 10, qualitySamples: 12, // The design's measurement on a Kick 1080p60 sample: crf 36 scored VMAF // 94.2 mean, 91.9 at its worst frame. The thresholds keep a margin under it. vmafMinMean: 90, vmafMinSample: 85, // Only where this ffmpeg has no libvmaf: SSIM on the same samples. ssimMinMean: 0.95, ssimMinSample: 0.9, // The whole-file comparison (64 px grey, 2 frames a second, every second of // the file): no frame below the floor, the mean at least the mean floor. wholeFileSsimMin: 0.9, wholeFileSsimMean: 0.97, wholeFileSigmaK: 8, wholeFileSigmaMargin: 0.03, wholeFileTileMin: 0.7, wholeFileTileRunFrames: 2, wholeFileChromaMin: 0.9, wholeFileChromaMean: 0.97, wholeFileWindowSeconds: 120, wholeFileLowerRunSeconds: 8, wholeFileChunkSigmaK: 4, wholeFileChunkMargin: 0.02, availabilityMaxAgeDays: 7, dropOriginal: "keep", }; export const SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS: FieldDocs = { platforms: 'The selector\'s platforms (as the URL names them): a deliberately stored container on one of these, above `minVideoMbps` and at least `minHeight` tall, is what `compact-saved-videos {"select": true}` picks. An explicit `items` list is not held to it. Default ["kick", "twitch", "rumble"]; YouTube is left alone.', minVideoMbps: "The selector's floor: the stored VIDEO stream's bitrate (Mbit/s, the container's bytes less its audio, over its length) at or above which a container is a candidate. Default 3 (Rumble's high-bitrate half; Kick and Twitch store 5–6).", minHeight: "The selector's other floor: a container shorter than this (pixels) is already light. Default 720.", crf: "SVT-AV1's crf. Default 36 (operator ruling: about 0.64 × the source's video bitrate at VMAF 94 on the measured sample). 20–55.", preset: "SVT-AV1's preset. Default 8. 4–12.", maxFps: "The frame rate a source above it is brought down to, on `maxFpsPlatforms` only (operator ruling: Kick and Twitch above 30 fps go to 30). 0 = never change the frame rate.", maxFpsPlatforms: 'The platforms `maxFps` applies to. Default ["kick", "twitch"]; a Rumble 60 fps stream keeps its 60.', chunkMinutes: "The encode's chunk, in minutes of the source: each chunk starts on a source keyframe, takes the heavy slot on its own, and is what a restart resumes from. Default 10; 1–60.", qualitySamples: "How many 2-second excerpts, spread through the file, the quality check scores (VMAF, or SSIM where this ffmpeg has no libvmaf). Default 12; 3–60.", vmafMinMean: "The VMAF the excerpts' mean must reach (against the stored source). Default 90.", vmafMinSample: "The VMAF no single excerpt may fall below. Default 85.", ssimMinMean: "Without libvmaf: the SSIM the excerpts' mean must reach. Default 0.95.", ssimMinSample: "Without libvmaf: the SSIM no excerpt may fall below. Default 0.9.", wholeFileSsimMin: "THE WHOLE-FILE COMPARISON scores EVERY frame of the copy against the source's (256 px wide, grey, the source taken to the copy's rate, paired frame for frame): no frame may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern scores at least 0.996; one black frame scores 0).", wholeFileSsimMean: "The whole-file comparison's mean must reach this. Default 0.97.", wholeFileSigmaK: "The floor relative to the file's own frames NEARBY (wholeFileWindowSeconds): no frame below its neighbourhood's MEDIAN − max(k × its robust spread, wholeFileSigmaMargin). The spread is 1.4826 × the median absolute deviation, so a few bad frames cannot widen their own floor. Default k = 8 (measured: a good crf-36 copy's spread is about 0.0006).", wholeFileSigmaMargin: "The least the relative floor sits under the mean, for a file whose frames barely differ. Default 0.03.", wholeFileTileMin: "Each frame is also split into an 8×8 grid of tiles, each scored on its own, so a change to a small region is not averaged away: a tile below this for more than wholeFileTileRunFrames frames in a row fails. Default 0.7 (a good crf-36 copy's lowest tile: 0.949; a red box over 1% of the picture: 0.46).", wholeFileTileRunFrames: "How many frames in a row a tile may sit below wholeFileTileMin. Default 2: a 3-frame defect at 30 fps fails.", wholeFileChromaMin: "THE COLOUR, every frame: the whole-file comparison also scores the U and V planes (SSIM), which the grey comparison and VMAF do not see — a hue shift, chroma-only noise. No frame's lower plane may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern: lowest 0.991).", wholeFileChromaMean: "The colour planes' mean must reach this. Default 0.97 (good copy: 0.9986).", wholeFileWindowSeconds: "The NEIGHBOURHOOD the relative floor is taken over: each frame is judged against the frames in the half-window just before it and just after it (the lower of their two floors), so a stream alternating two kinds of picture (a webcam, a screen share) is judged stretch by stretch, not by the file's dominant mode. A short defect inside a steady stretch has that stretch on both sides and falls below it. A degraded stretch longer than the window looks steady to it: such a stretch is caught by the absolute per-frame floor, the tile grid, the mean floor, and the VMAF excerpts, one at least every window across the whole file. Default 120 s; 5–3600.", wholeFileLowerRunSeconds: "A file that keeps coming back to a lower-scoring kind of picture (a webcam between screen shares) judges a neighbourhood that is a fifth or more that kind by those frames alone. Only SCENES count toward that kind: runs of at least this many seconds below the split, at least 3 of them, at least a tenth of the file, and none beginning or ending on a chunk join (a bad chunk's signature). Shorter runs are judged by the stretch around them, so a fault of a few seconds every GOP never passes as a kind of picture. Default 8 (longer than one 5 s GOP, with margin); 1–600.", wholeFileChunkSigmaK: "EVERY CHUNK AGAINST THE OTHERS: each chunk's mean (grey, U and V) must reach the other chunks' median − max(this × their robust spread, wholeFileChunkMargin). A chunk below it fails unless the source explains it: most of it is the file's recurring lower kind of picture, or its joins show no drop (a harder scene runs across chunks; a bad chunk changes level at its joins). Default 4.", wholeFileChunkMargin: "The least the per-chunk floor sits under the other chunks' median. Default 0.02.", availabilityMaxAgeDays: "How fresh the platform check must be for a video to count as still on its platform: an availability record written by a real check (not a backfill), public or unlisted, at most this many days old. Anything else counts as gone, and its original waits for a person's review. Default 7.", dropOriginal: '"keep" (the default in this slice): every original stays until a person drops it. "after-verify": once every check passed and the pointer names the compacted copy, a separate step reads that copy back from disk (size, sha256, container, length) and then drops the original — except for a video gone from its platform (availability not public or unlisted, or unknown), whose original waits for a person\'s review (`get compaction-review`, `review-compacted-original`, then `drop-saved-alternate` with `confirmOriginal`); only when the verification included the whole-file comparison. There is no backup of the store: after such a drop the compacted copy is the only copy.', }; function clampNum(v: unknown, d: number, lo: number, hi: number): number { return typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi ? v : d; } function platformList(v: unknown, d: string[]): string[] { if (!Array.isArray(v)) return [...d]; const out: string[] = []; for (const x of v) { if (typeof x !== "string") continue; const p = x.trim().toLowerCase(); if (p && !out.includes(p)) out.push(p); } return out; } export function sanitizeSavedVideoCompaction(value: unknown): SavedVideoCompactionSettings { const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record; const d = DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS; return { platforms: platformList(r.platforms, d.platforms), minVideoMbps: clampNum(r.minVideoMbps, d.minVideoMbps, 0, 1000), minHeight: Math.round(clampNum(r.minHeight, d.minHeight, 0, 4320)), crf: Math.round(clampNum(r.crf, d.crf, 20, 55)), preset: Math.round(clampNum(r.preset, d.preset, 4, 12)), maxFps: clampNum(r.maxFps, d.maxFps, 0, 240), maxFpsPlatforms: platformList(r.maxFpsPlatforms, d.maxFpsPlatforms), chunkMinutes: clampNum(r.chunkMinutes, d.chunkMinutes, 1, 60), qualitySamples: Math.round(clampNum(r.qualitySamples, d.qualitySamples, 3, 60)), vmafMinMean: clampNum(r.vmafMinMean, d.vmafMinMean, 0, 100), vmafMinSample: clampNum(r.vmafMinSample, d.vmafMinSample, 0, 100), ssimMinMean: clampNum(r.ssimMinMean, d.ssimMinMean, 0, 1), ssimMinSample: clampNum(r.ssimMinSample, d.ssimMinSample, 0, 1), wholeFileSsimMin: clampNum(r.wholeFileSsimMin, d.wholeFileSsimMin, 0, 1), wholeFileSsimMean: clampNum(r.wholeFileSsimMean, d.wholeFileSsimMean, 0, 1), wholeFileSigmaK: clampNum(r.wholeFileSigmaK, d.wholeFileSigmaK, 1, 100), wholeFileSigmaMargin: clampNum(r.wholeFileSigmaMargin, d.wholeFileSigmaMargin, 0, 1), wholeFileTileMin: clampNum(r.wholeFileTileMin, d.wholeFileTileMin, 0, 1), wholeFileTileRunFrames: Math.round(clampNum(r.wholeFileTileRunFrames, d.wholeFileTileRunFrames, 0, 300)), wholeFileChromaMin: clampNum(r.wholeFileChromaMin, d.wholeFileChromaMin, 0, 1), wholeFileChromaMean: clampNum(r.wholeFileChromaMean, d.wholeFileChromaMean, 0, 1), wholeFileWindowSeconds: clampNum(r.wholeFileWindowSeconds, d.wholeFileWindowSeconds, 1, 3600), wholeFileLowerRunSeconds: clampNum(r.wholeFileLowerRunSeconds, d.wholeFileLowerRunSeconds, 1, 600), wholeFileChunkSigmaK: clampNum(r.wholeFileChunkSigmaK, d.wholeFileChunkSigmaK, 1, 100), wholeFileChunkMargin: clampNum(r.wholeFileChunkMargin, d.wholeFileChunkMargin, 0, 1), availabilityMaxAgeDays: clampNum(r.availabilityMaxAgeDays, d.availabilityMaxAgeDays, 0, 365), dropOriginal: (COMPACTION_DROP_ORIGINAL as readonly unknown[]).includes(r.dropOriginal) ? (r.dropOriginal as CompactionDropOriginal) : d.dropOriginal, }; } // --- what counts -------------------------------------------------------------- // DELIBERATELY STORED (ruling 4): a pointer that says a person or an explicit // action kept it — // keepReason "pin" pinned / irreplaceable; every landed container (an // import, a live recording, attach-media) is a pin; // `explicit` an explicit persist: persist-videos, the video // page's Persist source video, the whole-recording // fetch (downloadOneManaged's `explicitPersist`); // any `origin` a container somebody requested (umtool's // `full: true`, a landed or attached file). // NOT: keepReason "override" alone — persist-kept, the keep-latest catch-up, // writes it too, and a pointer from before `explicit` cannot say which it was, // so it is not selected; keepReason "keep-latest" with no origin (the // automatic window); a legacy pointer with none of these. export function isDeliberatelyStored(pointer: Pick): boolean { if (pointer.origin) return true; if (pointer.explicit === true) return true; return pointer.keepReason === "pin"; } // The record's word alone: public or unlisted. The gone rule itself is // availability-server's platformPresence (a fresh, first-hand check). export function availabilitySaysPresent(a: Availability | null | undefined): boolean { return a === "public" || a === "unlisted"; } // What the selector reads of a stored container (one ffprobe). export type CompactionProbe = { hasVideo: boolean; vcodec: string | null; width: number | null; height: number | null; fps: number | null; seconds: number | null; videoKbps: number | null; audioKbps: number | null; }; // `belowThreshold`: an explicitly named video the selector would not pick // (ruling 9) — refused unless the run says `"belowThreshold": true`. export type CompactionDecision = | { ok: true; belowThreshold?: string } | { ok: false; reason: string; belowThreshold?: string }; export function decideCompaction(opts: { pointer: SavedVideoPointer; platform: string | null; channelExcluded: boolean; // "select": the settings' selector applies; "explicit": a person named it. mode: "explicit" | "select"; containerPresent: boolean; probe: CompactionProbe | null; settings: SavedVideoCompactionSettings; // The run allows an explicit item the selector would not pick. belowThreshold?: boolean; }): CompactionDecision { const { pointer, settings: s, probe } = opts; if (pointer.compacted) return { ok: false, reason: "already compacted" }; if (keepsAnyOriginal(pointer)) { return { ok: false, reason: "it already keeps an original of an earlier compacted copy beside it" }; } if (opts.channelExcluded) return { ok: false, reason: "the channel opts out (excludeFromCompaction)" }; if (!isDeliberatelyStored(pointer)) { return { ok: false, reason: pointer.keepReason === "keep-latest" ? "an automatic keep-latest container (compaction is for deliberately stored videos only)" : pointer.keepReason === "override" ? 'kept as "override" with no record that a person asked for it (persist-kept, the keep-latest catch-up, writes it too): not known to be kept on purpose' : "no keep reason recorded (a legacy pointer): not known to be kept on purpose", }; } if (!opts.containerPresent) return { ok: false, reason: `its container ${pointer.file} is not in the store` }; if (!probe) return { ok: false, reason: `ffprobe could not read ${pointer.file}` }; if (!probe.hasVideo) return { ok: false, reason: "no video stream (an audio-only container)" }; if (probe.vcodec && /^(av1|av01)/i.test(probe.vcodec)) return { ok: false, reason: "already AV1" }; if (!probe.seconds) return { ok: false, reason: "its length is unknown" }; const miss = selectorMiss(opts.platform, probe, s); if (!miss) return { ok: true }; if (opts.mode === "select") return { ok: false, reason: miss }; // EXPLICITLY NAMED, NOT WHAT THE SELECTOR PICKS (ruling 9): not by accident. return opts.belowThreshold ? { ok: true, belowThreshold: miss } : { ok: false, reason: `${miss}; named explicitly, it is compacted only with "belowThreshold": true`, belowThreshold: miss }; } // Why the selector would not pick it, or null. function selectorMiss(platform: string | null, probe: CompactionProbe, s: SavedVideoCompactionSettings): string | null { if (!platform || !s.platforms.includes(platform)) return `platform ${platform ?? "unknown"} is not selected`; if (probe.height === null || probe.height < s.minHeight) return `${probe.height ?? "unknown "}p is below minHeight ${s.minHeight}`; if (probe.videoKbps === null || probe.videoKbps < s.minVideoMbps * 1000) { return `${probe.videoKbps === null ? "unknown" : (probe.videoKbps / 1000).toFixed(2)} Mbit/s video is below minVideoMbps ${s.minVideoMbps}`; } return null; } // The output frame rate: the cap when the source is above it on a capped // platform, else null (the source's own). export function targetFps( sourceFps: number | null, platform: string | null, s: Pick, ): number | null { if (!s.maxFps || sourceFps === null || !platform || !s.maxFpsPlatforms.includes(platform)) return null; return sourceFps > s.maxFps + 0.5 ? s.maxFps : null; } // --- the estimate ------------------------------------------------------------- // MEASURED (design note §3, 13 Nov 2026, one Kick 1080p60 screen-share // sample, SVT-AV1 preset 8, against its H.264 source): the output video // bitrate as a share of the source's, by crf; 60 -> 30 fps at crf 36 was 0.44 // against 0.64 at 60. Between the rows the share is interpolated. CRF output // follows the content, so the range around it is wide on purpose. const CRF_SHARE: [number, number][] = [ [32, 0.89], [36, 0.64], [40, 0.47], [44, 0.36], ]; const HALF_FPS_FACTOR = 0.44 / 0.64; // Encode speed, × realtime, for 1080p60 at preset 8: 0.47 (a loaded machine, // crf 40) to 0.91 (crf 36) measured; 30 fps ran 1.17 / 0.91 = 1.29× faster. const SPEED_1080P60: [number, number] = [0.47, 0.91]; const PIXEL_RATE_1080P60 = 1920 * 1080 * 60; export const ESTIMATE_RANGE: [number, number] = [0.8, 1.25]; function crfShare(crf: number): number { if (crf <= CRF_SHARE[0][0]) return CRF_SHARE[0][1]; for (let i = 1; i < CRF_SHARE.length; i += 1) { const [c1, s1] = CRF_SHARE[i - 1]; const [c2, s2] = CRF_SHARE[i]; if (crf <= c2) return s1 + ((crf - c1) / (c2 - c1)) * (s2 - s1); } return CRF_SHARE[CRF_SHARE.length - 1][1]; } export type CompactionEstimate = { // Output bytes, [low, high]. bytes: [number, number]; // Encode hours, [fast, slow]. hours: [number, number]; share: number; }; export function estimateCompaction(opts: { probe: CompactionProbe; crf: number; fps: number | null; }): CompactionEstimate { const { probe } = opts; const seconds = probe.seconds ?? 0; const srcFps = probe.fps ?? 30; const outFps = opts.fps ?? srcFps; const fpsFactor = outFps < srcFps ? Math.pow(outFps / srcFps, Math.log(HALF_FPS_FACTOR) / Math.log(0.5)) : 1; const share = crfShare(opts.crf) * fpsFactor; const videoKbps = probe.videoKbps ?? 0; const point = ((videoKbps * share + (probe.audioKbps ?? 0)) * 1000 * seconds) / 8; const pixels = (probe.width ?? 1920) * (probe.height ?? 1080) * outFps; const scale = Math.min(4, PIXEL_RATE_1080P60 / Math.max(1, pixels)); const fast = SPEED_1080P60[1] * scale; const slow = SPEED_1080P60[0] * scale; return { bytes: [Math.round(point * ESTIMATE_RANGE[0]), Math.round(point * ESTIMATE_RANGE[1])], hours: [seconds / fast / 3600, seconds / slow / 3600], share, }; } // The headroom a compaction needs on the store's disk: its chunks and the // muxed result side by side at the concat (≈ 2 × the output), less what the // chunks already hold, plus the playable copies' margin. export const COMPACTION_DISK_MARGIN_BYTES = 2 * 1024 ** 3; export function compactionFreeNeeded(estimateHighBytes: number, writtenBytes: number): number { return Math.max(0, 2 * estimateHighBytes - writtenBytes) + COMPACTION_DISK_MARGIN_BYTES; } // --- names -------------------------------------------------------------------- // The compacted copy's OWN name, never the original's: the backup mirror is // additive (rsync, no deletes), so a re-encode under `source-media.mp4` would // overwrite the backed-up original. No reader takes it for a source in a video // dir (lib/mediaFiles.ts anchors on `source-media.`): the pointer is the // only thing that names it. export function compactedFileName(at: Date, taken: Iterable = [], ext = ".mp4"): string { const stem = `source-media.compact-av1-${at.toISOString().replace(/\D/g, "").slice(0, 14)}`; const names = new Set(taken); let name = `${stem}${ext}`; for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`; return name; } // The scratch dir a compaction works in: inside the video's own store dir, on // the store's drive (never /tmp, a RAM disk here, and never the corpus SSD). // Its state file is what a restart resumes from. export const COMPACTION_SCRATCH_DIRNAME = ".compact-scratch"; export const COMPACTION_STATE_FILENAME = "state.json"; export const COMPACTION_TOOL = "archilyzer compact-saved-videos 1"; // The review list's states for a compacted video (`get compaction-review`). export type CompactionReviewState = | "awaiting-review" // gone from its platform (or unknown), not reviewed: the original waits | "reviewed" // reviewed; drop it with drop-saved-alternate confirmOriginal | "kept" // dropOriginal "keep": the original stays until a person drops it | "drop-pending" // on its platform under "after-verify": the drop step has not run or failed | "dropped"; // the original is gone export const COMPACTION_REVIEW_STATE_LABELS: Record = { "awaiting-review": "compacted, original awaiting review", reviewed: "compacted, reviewed: the original may be dropped", kept: "compacted, original kept (dropOriginal: keep)", "drop-pending": "compacted, original not dropped yet", dropped: "compacted, original dropped", };