commit 59a17713f344255baad3b1a188d3789bdc00364a
parent e010ef684b79d9aa001a179685379527afea6087
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 13 Nov 2026 20:54:29 -0500
saved videos: a compacted pointer and its original, guarded
A pointer may carry `compacted` (the active copy is a re-encode: its source's
sha256/bytes/height/fps/codec, the encoder and settings, every verification
number, the re-check, the original's drop) and keep its original as the
alternate `keptAs: "original"` (with its sha256 and, when a person gave one, a
review). Parsed tolerantly: a pointer without them parses as before, and a
damaged block still reads as a re-encode whose checks did not pass.
compactedLine is the one sentence every surface says about such a copy;
savedAlternatesLine names a re-encode and the original.
Nothing deletes an original but a confirmed dropSavedAlternate: it needs
confirmOriginal, the compacted copy re-checked against its recorded sha256
just before, passed checks, and for a video not known to be on its platform a
recorded review. dropSavedVideo refuses a video that keeps one; unpersist
brings the original back as the source and refuses a re-encode whose original
was dropped; a persist landing under the original's name moves it aside first;
a checksum is written only while the pointer names the file that was hashed.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
12 files changed, 1243 insertions(+), 28 deletions(-)
diff --git a/common/controller/backupSavedVideos.ts b/common/controller/backupSavedVideos.ts
@@ -95,7 +95,7 @@ export async function backupSavedVideos({
}
const sha256 = await sha256File(entry.storedPath);
// Cache the checksum back onto the pointer for the store/UI.
- await updateSavedVideoChecksum(entry.videoDir, sha256).catch(() => {});
+ await updateSavedVideoChecksum(entry.videoDir, sha256, entry.pointer.file).catch(() => {});
manifestEntries.push({
slug: entry.slug,
videoId: entry.videoId,
diff --git a/common/controller/preparePlayable.ts b/common/controller/preparePlayable.ts
@@ -264,7 +264,7 @@ export async function preparePlayable(opts: PreparePlayableOptions): Promise<Pre
if (!sourceSha256) {
onLog(`${id}: hashing ${pointer.file} (${formatBytes(srcBytes)})`);
sourceSha256 = await sha256File(src, opts.signal);
- if (!opts.dryRun) await updateSavedVideoChecksum(videoDir, sourceSha256);
+ if (!opts.dryRun) await updateSavedVideoChecksum(videoDir, sourceSha256, pointer.file);
}
const prior = manifest.entries[id];
if (prior && prior.sourceSha256 === sourceSha256) {
@@ -335,11 +335,18 @@ export async function preparePlayable(opts: PreparePlayableOptions): Promise<Pre
vcodec: probed?.vcodec ?? "",
acodec: probed?.acodec ?? null,
preparedAt: now().toISOString(),
+ // A copy of a re-encode says so, and of which original.
+ ...(pointer.compacted?.source.sha256
+ ? { compactedFrom: pointer.compacted.source.sha256, note: "re-encoded copy" as const }
+ : {}),
};
manifest.entries[id] = entry;
await writeJsonAtomic(playableManifestPath(root, opts.slug), manifest);
result.prepared.push(id);
- onLog(`${id}: ${name} ${formatBytes(bytes)}, infohash ${made.infoHash}, ${made.pieceLength / 1024} KiB pieces`);
+ onLog(
+ `${id}: ${name} ${formatBytes(bytes)}, infohash ${made.infoHash}, ${made.pieceLength / 1024} KiB pieces` +
+ (entry.compactedFrom ? `; a re-encoded copy (of the original sha256 ${entry.compactedFrom.slice(0, 12)}…)` : ""),
+ );
} catch (err) {
if (opts.signal?.aborted) {
result.stopped = "cancelled";
diff --git a/common/controller/pruneSavedVideos.ts b/common/controller/pruneSavedVideos.ts
@@ -69,10 +69,12 @@ export async function pruneSavedVideos({
if (pointer.alternates?.length) {
const n = pointer.alternates.length;
const proxies = pointer.alternates.filter((a) => a.keptAs === "proxy").length;
- const flagged = n - proxies;
- const what = proxies
+ const originals = pointer.alternates.filter((a) => a.keptAs === "original").length;
+ const flagged = n - proxies - originals;
+ const what = proxies || originals
? ` (${[
- `${proxies} kept on purpose as the lower-quality proxy`,
+ ...(originals ? ["the original a compacted copy was re-encoded from"] : []),
+ ...(proxies ? [`${proxies} kept on purpose as the lower-quality proxy`] : []),
...(flagged ? [`${flagged} flagged for a check`] : []),
].join(" and ")})`
: " flagged for a check";
diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts
@@ -286,6 +286,11 @@ export type ClipProvenance = {
sourceHost?: string;
// "clip-window": the tiered window's file name this one was cut from.
derivedFrom?: string;
+ // "saved-video": the saved copy it was cut from was a RE-ENCODE (a compacted
+ // copy, controller/compactSavedVideos.ts) — its file and the original's
+ // sha256 — so the window says it is a later generation. Absent on a cut from
+ // an original.
+ fromReencode?: { file: string; originalSha256: string };
// How many times the player's page was opened for this window's cut (release
// 32 R9, ytdlp/storedUrlPageOpen.ts): a stored-URL cut opens it before the
// first cut of each video in a run. Absent when none was.
@@ -389,6 +394,10 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
if (sourceHost) out.sourceHost = sourceHost;
const derivedFrom = str(r.derivedFrom);
if (derivedFrom) out.derivedFrom = derivedFrom;
+ const re = r.fromReencode as Record<string, unknown> | undefined;
+ if (re && typeof re === "object" && typeof re.file === "string" && typeof re.originalSha256 === "string") {
+ out.fromReencode = { file: re.file, originalSha256: re.originalSha256 };
+ }
const pageOpens = num(r.pageOpens);
if (pageOpens !== undefined && pageOpens > 0) out.pageOpens = pageOpens;
const copy = coerceClipCopy(r.copy);
diff --git a/common/lib/playableMedia.ts b/common/lib/playableMedia.ts
@@ -160,6 +160,11 @@ export type PlayableEntry = {
vcodec: string;
acodec: string | null;
preparedAt: string;
+ // MADE FROM A RE-ENCODE (the saved copy was compacted:
+ // controller/compactSavedVideos.ts): the ORIGINAL's sha256, and the words a
+ // reader shows. Absent on a copy of an original.
+ compactedFrom?: string;
+ note?: "re-encoded copy";
};
export type PlayableManifest = {
@@ -212,6 +217,9 @@ export function parsePlayableManifest(raw: unknown, slug: string): PlayableManif
vcodec: r.vcodec,
acodec: r.acodec as string | null,
preparedAt: r.preparedAt,
+ ...(typeof r.compactedFrom === "string" && HEX64.test(r.compactedFrom)
+ ? { compactedFrom: r.compactedFrom, note: "re-encoded copy" as const }
+ : {}),
};
}
return out;
diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts
@@ -7,6 +7,7 @@ import {
import path from "node:path";
import {
mkdir,
+ readdir,
readFile,
rename,
rm,
@@ -14,9 +15,11 @@ import {
} from "node:fs/promises";
import {
SAVED_VIDEO_POINTER_FILENAME,
+ compactedOriginalOf,
parseSavedVideoPointer,
savedVideoBytes,
savedVideoPath,
+ type SavedAlternateReview,
type SavedVideoFormat,
type SavedVideoKeepReason,
type SavedVideoAlternate,
@@ -24,10 +27,28 @@ import {
type SavedVideoPointer,
} from "./savedVideo";
import { assertSavedVideosStoreWritable } from "./savedVideoStore";
+import { resolveEffectiveAvailability } from "./availability-server";
+import type { Availability } from "./availability";
+import { isStillOnPlatform } from "./savedVideoCompaction";
import type { Paths } from "./paths";
// Filesystem side of the saved-video store. See savedVideo.ts for the layout.
+function stampOf(at: Date): string {
+ return at.toISOString().replace(/\D/g, "").slice(0, 14);
+}
+
+// An alternate's name, `source-media.alt-<h>p-<stamp>.<ext>`, unique in
+// `taken` (ytdlp/savedAlternates.ts re-exports it).
+export function alternateName(file: string, height: number | null, at: Date, taken: Iterable<string> = []): string {
+ const ext = path.extname(file);
+ const stem = `source-media.alt-${height ? `${height}p-` : ""}${stampOf(at)}`;
+ const names = new Set(taken);
+ let name = `${stem}${ext}`;
+ for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`;
+ return name;
+}
+
export function savedVideoPointerPath(videoDir: string): string {
return path.join(videoDir, SAVED_VIDEO_POINTER_FILENAME);
}
@@ -146,7 +167,29 @@ export async function persistSourceVideo(opts: {
// are still in that dir: the new pointer carries them, or they would be
// files no pointer names.
const before = await loadSavedVideo(opts.videoDir);
- const alternates = before?.dir === opts.storeDir ? before.alternates : undefined;
+ let alternates = before?.dir === opts.storeDir ? before.alternates : undefined;
+ // AN ALTERNATE UNDER THE NAME THIS PERSIST WRITES is moved aside first, never
+ // overwritten: a compacted video keeps its original as `source-media.<ext>`
+ // (the backup holds it under that name), and a download over it lands under
+ // the same name — the rename below would replace the original's bytes.
+ if (before && alternates?.some((a) => a.file === opts.sourceFilename)) {
+ const at = new Date();
+ const taken = new Set(await readdir(opts.storeDir).catch(() => [] as string[]));
+ const moved: SavedVideoAlternate[] = [];
+ for (const a of alternates) {
+ if (a.file !== opts.sourceFilename) {
+ moved.push(a);
+ continue;
+ }
+ const aside = alternateName(a.file, a.height ?? null, at, taken);
+ taken.add(aside);
+ await rename(path.join(opts.storeDir, a.file), path.join(opts.storeDir, aside));
+ moved.push({ ...a, file: aside });
+ }
+ alternates = moved;
+ // The pointer names the new name before the download takes the old one.
+ await writePointer(opts.videoDir, { ...before, alternates });
+ }
await moveFileCrossDevice(src, dest);
const pointer: SavedVideoPointer = {
storedAt: new Date().toISOString(),
@@ -166,13 +209,54 @@ export async function persistSourceVideo(opts: {
// Record a content hash on a video's pointer (populated by the backup step so
// the store + UI can show a verified checksum). Best-effort: a missing pointer
// is a no-op.
+//
+// `file`: the basename that was hashed. The hash is written only while the
+// pointer still names that file — a backup or a remux hashes for minutes, and
+// a compaction (or a re-download) that swapped the active copy meanwhile must
+// not get the old file's hash. Rewritten from the RAW JSON under its lock.
export async function updateSavedVideoChecksum(
videoDir: string,
sha256: string,
+ file?: string,
): Promise<void> {
- const pointer = await loadSavedVideo(videoDir);
- if (!pointer) return;
- await writePointer(videoDir, { ...pointer, sha256 });
+ const pointerFile = savedVideoPointerPath(videoDir);
+ await withJsonFileLock(pointerFile, async () => {
+ const read = await readJsonFile(pointerFile);
+ if (!read.ok || !parseSavedVideoPointer(read.value)) return;
+ const raw = { ...(read.value as Record<string, unknown>) };
+ if (file !== undefined && raw.file !== file) return;
+ raw.sha256 = sha256;
+ await writeJsonAtomic(pointerFile, raw);
+ });
+}
+
+// A PERSON'S REVIEW OF A COMPACTED COPY, recorded on its original's alternate
+// entry (`review`): what a video gone from its platform needs before its
+// original may be dropped (dropSavedAlternate). Refused when the pointer keeps
+// no `keptAs: "original"` alternate. Raw JSON, under the pointer's lock.
+export async function recordOriginalReview(
+ videoDir: string,
+ review: SavedAlternateReview,
+): Promise<SavedVideoAlternate> {
+ const pointerFile = savedVideoPointerPath(videoDir);
+ return withJsonFileLock(pointerFile, async () => {
+ const read = await readJsonFile(pointerFile);
+ const pointer = read.ok ? parseSavedVideoPointer(read.value) : null;
+ if (!read.ok || !pointer) throw new SavedAlternateRefusal("This video has no saved-video pointer.");
+ const original = compactedOriginalOf(pointer);
+ if (!original) {
+ throw new SavedAlternateRefusal("This video keeps no original beside a compacted copy: there is nothing to review.");
+ }
+ if (pointer.compacted && !pointer.compacted.checks.passed) {
+ throw new SavedAlternateRefusal("The compacted copy's checks did not pass: it cannot be reviewed as good.");
+ }
+ const raw = { ...(read.value as Record<string, unknown>) };
+ raw.alternates = (Array.isArray(raw.alternates) ? raw.alternates : []).map((a) =>
+ a && typeof a === "object" && (a as { file?: unknown }).file === original.file ? { ...(a as object), review } : a,
+ );
+ await writeJsonAtomic(pointerFile, raw);
+ return { ...original, review };
+ });
}
// Put a replaced pointer's provenance back on its replacement: the old
@@ -240,6 +324,18 @@ export async function unpersistSavedVideo(
): Promise<boolean> {
const pointer = await loadSavedVideo(videoDir);
if (!pointer) return false;
+ // A COMPACTED VIDEO (controller/compactSavedVideos.ts). With its original
+ // still kept, every copy comes back under its own name, as below: the
+ // original is `source-media.<ext>`, so it is the one the video dir takes for
+ // its source, and the re-encode is a file no reader takes for one. With the
+ // original dropped, the re-encode would be the only copy and the pointer —
+ // the one record that it is a re-encode — would go: refused.
+ if (pointer.compacted && !compactedOriginalOf(pointer)) {
+ throw new SavedAlternateRefusal(
+ `${pointer.file} is a re-encode (compacted ${pointer.compacted.at.slice(0, 10)}) and its original was dropped: ` +
+ "moving it back would leave a re-encode in the video dir with no record that it is one. Not unpersisted.",
+ );
+ }
if (paths) await assertSavedVideosStoreWritable(paths, pointer.dir);
const src = savedVideoPath(pointer);
const dest = path.join(videoDir, pointer.file);
@@ -262,9 +358,19 @@ export async function unpersistSavedVideo(
// a video that rolled out of the keep-latest window). Returns bytes freed. The
// whole video goes, its alternates with it — the prune itself never calls this
// for a video that holds any (pruneSavedVideos leaves those for the check).
+//
+// NEVER A VIDEO THAT KEEPS AN ORIGINAL (`keptAs: "original"`, the source of a
+// compacted copy): refused, nothing touched. Only a confirmed
+// dropSavedAlternate deletes an original.
export async function dropSavedVideo(videoDir: string): Promise<number> {
const pointer = await loadSavedVideo(videoDir);
if (!pointer) return 0;
+ const original = compactedOriginalOf(pointer);
+ if (original) {
+ throw new SavedAlternateRefusal(
+ `This video keeps its original ${original.file} beside a compacted copy: it is never dropped whole.`,
+ );
+ }
await rm(savedVideoPath(pointer), { force: true });
for (const alt of pointer.alternates ?? []) {
await rm(path.join(pointer.dir, alt.file), { force: true });
@@ -322,12 +428,31 @@ export function isBareStoreName(file: string): boolean {
);
}
+//
+// AN ORIGINAL (`keptAs: "original"`: the source bytes a compacted active copy
+// was re-encoded from — controller/compactSavedVideos.ts) is refused unless:
+// - `confirmOriginal: true` names the intent;
+// - when the active copy is still that re-encode: its checks passed, and the
+// caller read it back from disk just now — `verifiedActive.sha256` equal to
+// the pointer's (compactSavedVideos' recheckCompactedCopy); a dry run is
+// answered without it;
+// - the video is still on its platform (availability public or unlisted),
+// OR a person's review is recorded on the entry (recordOriginalReview). A
+// video whose availability is unknown counts as gone.
+// The drop then records `compacted.originalDropped` (when, by whom, the file,
+// its bytes and sha256) in the same pointer write.
export async function dropSavedAlternate(
videoDir: string,
file: string,
opts: {
dryRun?: boolean;
paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">;
+ confirmOriginal?: boolean;
+ verifiedActive?: { sha256: string };
+ // Who drops it, for `originalDropped.by` (default "drop-saved-alternate").
+ by?: string;
+ // The availability the gone-video rule reads (default: the video dir's).
+ availability?: Availability | null;
} = {},
): Promise<DropSavedAlternateResult> {
if (!isBareStoreName(file)) {
@@ -354,6 +479,34 @@ export async function dropSavedAlternate(
".",
);
}
+ if (alternate.keptAs === "original") {
+ if (opts.confirmOriginal !== true) {
+ throw new SavedAlternateRefusal(
+ `${file} is the ORIGINAL the active copy was re-encoded from (sha256 ${alternate.sha256?.slice(0, 12) ?? "unknown"}…): ` +
+ 'it is dropped only when the drop names it — pass "confirmOriginal": true.',
+ );
+ }
+ if (pointer.compacted) {
+ if (!pointer.compacted.checks.passed) {
+ throw new SavedAlternateRefusal(`The compacted copy's checks did not pass: ${file}, its original, is kept.`);
+ }
+ if (!opts.dryRun && (!opts.verifiedActive || !pointer.sha256 || opts.verifiedActive.sha256 !== pointer.sha256)) {
+ throw new SavedAlternateRefusal(
+ `The compacted copy ${pointer.file} was not read back from disk and matched against its recorded sha256 ` +
+ `just before this drop: ${file}, its original, is kept.`,
+ );
+ }
+ }
+ const availability =
+ opts.availability !== undefined ? opts.availability : await resolveEffectiveAvailability(videoDir).catch(() => null);
+ if (!isStillOnPlatform(availability) && !alternate.review) {
+ throw new SavedAlternateRefusal(
+ `This video is not known to be on its platform any more (availability: ${availability ?? "unknown"}): ` +
+ `the stored ${file} may be the only original there is. Review the compacted copy first ` +
+ "(review-compacted-original), then drop it.",
+ );
+ }
+ }
if (opts.paths) await assertSavedVideosStoreWritable(opts.paths, pointer.dir);
const target = path.join(pointer.dir, file);
const st = await stat(target).catch(() => null);
@@ -375,6 +528,18 @@ export async function dropSavedAlternate(
);
if (kept.length) raw.alternates = kept;
else delete raw.alternates;
+ if (alternate.keptAs === "original" && raw.compacted && typeof raw.compacted === "object") {
+ raw.compacted = {
+ ...(raw.compacted as Record<string, unknown>),
+ originalDropped: {
+ at: new Date().toISOString(),
+ by: opts.by ?? "drop-saved-alternate",
+ file,
+ bytes: st?.size ?? alternate.bytes,
+ sha256: alternate.sha256 ?? pointer.compacted?.source.sha256 ?? "",
+ },
+ };
+ }
await writeJsonAtomic(pointerFile, raw);
return result;
});
diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts
@@ -72,10 +72,102 @@ export type SavedVideoPointer = {
// The active copy's own measured length and height, written when an
// alternate was recorded beside it (a landed container has no `format`).
probed?: SavedVideoProbe;
+ // THE ACTIVE COPY IS A RE-ENCODE (compact-saved-videos,
+ // controller/compactSavedVideos.ts): what it was made from, how, and every
+ // number its verification measured. `sha256`, `bytes` and `file` above are
+ // the re-encode's own; the source's are in `compacted.source`, and the
+ // source itself stays in `alternates` with `keptAs: "original"` until it is
+ // dropped (then `compacted.originalDropped` says when, and its hash). Absent
+ // on every pointer that was never compacted, which parses as before.
+ compacted?: SavedVideoCompacted;
};
export type SavedVideoProbe = { seconds?: number; height?: number };
+// What compaction asked the encoder for. The result's own measurements are in
+// `result` and `checks`.
+export type SavedVideoCompactedSettings = {
+ codec: string; // "av1"
+ encoder: string; // "libsvtav1"
+ preset: number;
+ crf: number;
+ gopSeconds: number;
+ pixFmt: string;
+ // The output frame rate when the source's was capped (60 -> 30), else null:
+ // the source's own.
+ fps: number | null;
+ audio: "copy";
+ chunkSeconds: number;
+};
+
+export type SavedVideoCompactedStream = {
+ file: string;
+ bytes: number;
+ sha256: string;
+ vcodec?: string;
+ height?: number;
+ fps?: number;
+ seconds?: number;
+ frames?: number;
+ // The video stream's own bitrate in kbit/s (container bytes minus audio,
+ // over the length), as the selector measured it.
+ videoKbps?: number;
+};
+
+// Every check compaction ran before the re-encode became active. `passed` is
+// true only when every one of them did; a pointer is never swapped otherwise.
+export type SavedVideoCompactedChecks = {
+ passed: boolean;
+ // Full decode of the re-encode, every frame, without an error.
+ decoded: boolean;
+ // [source, re-encode] video lengths in seconds, and the allowed difference.
+ seconds: [number, number];
+ secondsTolerance: number;
+ // [source frames, re-encode frames, frames expected from the fps change].
+ frames: [number, number, number];
+ // The audio packets' framemd5 of both files, hashed: equal or the copy fails.
+ audio: "identical";
+ audioHash: string;
+ quality: {
+ metric: "vmaf" | "ssim";
+ mean: number;
+ min: number;
+ samples: number;
+ minMean: number;
+ minSample: number;
+ };
+ // A window cut from each copy through the evidence cutter at a few seconds,
+ // compared on a downscaled picture.
+ cuts: { at: number; ssim: number }[];
+ cutSsimMin: number;
+ // The recording clock (data/<id>/clock.json): "none" (no map), "kept" (the
+ // map re-measured against the re-encode and within tolerance of the old
+ // one, then written for it), "stale" (the map was already not current: it is
+ // measured again on the next fetch, as before).
+ clock: "none" | "kept" | "stale";
+};
+
+export type SavedVideoCompacted = {
+ at: string;
+ tool: string;
+ // `ffmpeg -version`'s first line and the encoder's banner, when it printed one.
+ encoder: string;
+ settings: SavedVideoCompactedSettings;
+ source: SavedVideoCompactedStream & { format?: SavedVideoFormat };
+ result: SavedVideoCompactedStream;
+ checks: SavedVideoCompactedChecks;
+ chunks: number;
+ // The second check, after the swap was written and before any drop: the
+ // re-encode read back from disk (size, sha256, container, length).
+ recheck?: { at: string; ok: boolean; why?: string };
+ // The original's drop, when it happened: by whom and the bytes that went.
+ originalDropped?: { at: string; by: string; file: string; bytes: number; sha256: string };
+};
+
+// A person's word that a compacted copy is good (the review a video gone from
+// its platform needs before its original may be dropped).
+export type SavedAlternateReview = { at: string; by: string; note?: string };
+
export type SavedVideoAlternate = {
// Basename in the pointer's `dir`.
file: string;
@@ -93,16 +185,26 @@ export type SavedVideoAlternate = {
// WHY IT IS KEPT, when on purpose rather than for a check. "proxy": the
// lower-quality copy a taller download replaced (persist-videos
// `replace: "below-height"`), kept as the light copy to work from — not a
- // suspected duplicate. Absent on every other alternate.
+ // suspected duplicate. "original": the source's own bytes a compacted
+ // active copy was re-encoded from (controller/compactSavedVideos.ts), kept
+ // until a confirmed drop. Absent on every other alternate.
keptAs?: SavedAlternateKeptAs;
+ // The copy's sha256, when it is known (an original: always).
+ sha256?: string;
+ // THIS COPY IS A RE-ENCODE of the bytes with this sha256: a compacted copy
+ // that a later download or attach replaced as the active one.
+ compactedFrom?: string;
+ // An original's review (see SavedAlternateReview).
+ review?: SavedAlternateReview;
};
-export const SAVED_ALTERNATE_KEPT_AS = ["proxy"] as const;
+export const SAVED_ALTERNATE_KEPT_AS = ["proxy", "original"] as const;
export type SavedAlternateKeptAs = (typeof SAVED_ALTERNATE_KEPT_AS)[number];
// The words for an alternate's `keptAs`, wherever one is listed.
export const SAVED_ALTERNATE_KEPT_AS_LABELS: Record<SavedAlternateKeptAs, string> = {
proxy: "kept on purpose as the lower-quality proxy",
+ original: "the original the active copy was re-encoded from, kept until it is dropped",
};
export type SavedVideoFormat = {
@@ -231,9 +333,158 @@ function parseAlternate(raw: unknown): SavedVideoAlternate | null {
if ((SAVED_ALTERNATE_KEPT_AS as readonly unknown[]).includes(r.keptAs)) {
out.keptAs = r.keptAs as SavedAlternateKeptAs;
}
+ if (typeof r.sha256 === "string" && r.sha256 !== "") out.sha256 = r.sha256;
+ if (typeof r.compactedFrom === "string" && r.compactedFrom !== "") out.compactedFrom = r.compactedFrom;
+ const review = parseReview(r.review);
+ if (review) out.review = review;
return out;
}
+function parseReview(raw: unknown): SavedAlternateReview | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ if (typeof r.at !== "string" || r.at === "" || typeof r.by !== "string" || r.by === "") return null;
+ return { at: r.at, by: r.by, ...(typeof r.note === "string" && r.note !== "" ? { note: r.note } : {}) };
+}
+
+function obj(v: unknown): Record<string, unknown> {
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
+}
+function num(v: unknown, d = 0): number {
+ return typeof v === "number" && Number.isFinite(v) ? v : d;
+}
+function strOr(v: unknown, d = ""): string {
+ return typeof v === "string" ? v : d;
+}
+
+function parseCompactedStream(raw: unknown): SavedVideoCompactedStream {
+ const r = obj(raw);
+ const out: SavedVideoCompactedStream = { file: strOr(r.file), bytes: num(r.bytes), sha256: strOr(r.sha256) };
+ if (typeof r.vcodec === "string" && r.vcodec !== "") out.vcodec = r.vcodec;
+ for (const k of ["height", "fps", "seconds", "frames", "videoKbps"] as const) {
+ const v = positive(r[k]);
+ if (v !== undefined) out[k] = v;
+ }
+ return out;
+}
+
+// LENIENT ON PURPOSE: a `compacted` block that is there but damaged still
+// says "this is a re-encode" (missing numbers read 0, `passed` reads false),
+// because dropping it would make a re-encode read as the original's bytes.
+function parseCompacted(raw: unknown): SavedVideoCompacted | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ const s = obj(r.settings);
+ const c = obj(r.checks);
+ const q = obj(c.quality);
+ const pair = (v: unknown): [number, number] =>
+ Array.isArray(v) ? [num(v[0]), num(v[1])] : [0, 0];
+ const source = parseCompactedStream(r.source);
+ const format = parseFormat(obj(r.source).format);
+ const out: SavedVideoCompacted = {
+ at: strOr(r.at),
+ tool: strOr(r.tool),
+ encoder: strOr(r.encoder),
+ settings: {
+ codec: strOr(s.codec, "av1"),
+ encoder: strOr(s.encoder, "libsvtav1"),
+ preset: num(s.preset),
+ crf: num(s.crf),
+ gopSeconds: num(s.gopSeconds),
+ pixFmt: strOr(s.pixFmt),
+ fps: typeof s.fps === "number" && s.fps > 0 ? s.fps : null,
+ audio: "copy",
+ chunkSeconds: num(s.chunkSeconds),
+ },
+ source: { ...source, ...(format ? { format } : {}) },
+ result: parseCompactedStream(r.result),
+ checks: {
+ passed: c.passed === true,
+ decoded: c.decoded === true,
+ seconds: pair(c.seconds),
+ secondsTolerance: num(c.secondsTolerance),
+ frames: Array.isArray(c.frames) ? [num(c.frames[0]), num(c.frames[1]), num(c.frames[2])] : [0, 0, 0],
+ audio: "identical",
+ audioHash: strOr(c.audioHash),
+ quality: {
+ metric: q.metric === "ssim" ? "ssim" : "vmaf",
+ mean: num(q.mean),
+ min: num(q.min),
+ samples: num(q.samples),
+ minMean: num(q.minMean),
+ minSample: num(q.minSample),
+ },
+ cuts: Array.isArray(c.cuts)
+ ? c.cuts.map((x) => ({ at: num(obj(x).at), ssim: num(obj(x).ssim) }))
+ : [],
+ cutSsimMin: num(c.cutSsimMin),
+ clock: c.clock === "kept" || c.clock === "stale" ? c.clock : "none",
+ },
+ chunks: num(r.chunks),
+ };
+ const re = obj(r.recheck);
+ if (typeof re.at === "string") {
+ out.recheck = { at: re.at, ok: re.ok === true, ...(typeof re.why === "string" ? { why: re.why } : {}) };
+ }
+ const d = obj(r.originalDropped);
+ if (typeof d.at === "string") {
+ out.originalDropped = { at: d.at, by: strOr(d.by), file: strOr(d.file), bytes: num(d.bytes), sha256: strOr(d.sha256) };
+ }
+ return out;
+}
+
+// The alternate a compacted pointer keeps its original as, when it still does.
+export function compactedOriginalOf(pointer: SavedVideoPointer): SavedVideoAlternate | null {
+ return pointer.alternates?.find((a) => a.keptAs === "original") ?? null;
+}
+
+function codecName(vcodec: string | undefined): string {
+ if (!vcodec) return "video";
+ const v = vcodec.toLowerCase();
+ if (v.startsWith("avc") || v === "h264") return "H.264";
+ if (v.startsWith("hev") || v.startsWith("hvc") || v === "hevc" || v === "h265") return "HEVC";
+ if (v.startsWith("av01") || v === "av1") return "AV1";
+ if (v.startsWith("vp09") || v === "vp9") return "VP9";
+ return vcodec;
+}
+
+function fmtBytes(n: number): string {
+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;
+ if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;
+ return `${n} B`;
+}
+
+function day(iso: string): string {
+ return /^\d{4}-\d{2}-\d{2}/.test(iso) ? iso.slice(0, 10) : iso || "an unknown day";
+}
+
+// THE ONE SENTENCE every surface says about a compacted copy (the video page,
+// /saved-videos, ops lines): it is a re-encode, of what, how, and where the
+// original is. Null for a pointer that was never compacted.
+// "Re-encoded copy (AV1 crf 36, 1080p30 from 60 fps, audio copied) of a
+// 12.30 GB H.264 original — 4.90 GB, 2026-11-13. The original is kept
+// beside it (source-media.mp4)."
+export function compactedLine(pointer: SavedVideoPointer): string | null {
+ const c = pointer.compacted;
+ if (!c) return null;
+ const h = c.result.height ?? c.source.height;
+ const fps = c.result.fps ?? c.settings.fps ?? c.source.fps;
+ const fromFps = c.settings.fps && c.source.fps && c.source.fps > c.settings.fps ? ` from ${Math.round(c.source.fps)} fps` : "";
+ const how =
+ `${codecName(c.settings.codec)} crf ${c.settings.crf}` +
+ `${h ? `, ${h}p${fps ? Math.round(fps) : ""}` : ""}${fromFps}, audio copied`;
+ const original = compactedOriginalOf(pointer);
+ const where = original
+ ? ` The original is kept beside it (${original.file}).`
+ : c.originalDropped
+ ? ` The original was dropped on ${day(c.originalDropped.at)} (sha256 ${c.originalDropped.sha256.slice(0, 12)}…, ${c.originalDropped.bytes} bytes).`
+ : " The original is not kept.";
+ return (
+ `Re-encoded copy (${how}) of a ${fmtBytes(c.source.bytes)} ${codecName(c.source.vcodec)} original — ` +
+ `${fmtBytes(pointer.bytes)}, ${day(c.at)}.${where}`
+ );
+}
+
// One line for a video holding alternates, for the review listing:
// "2 saved copies: active 720p, 4696.5 s (download); alternate 360p, 4696.6 s
// (attach-media, source-media.alt-360p-20261023172312.mp4)".
@@ -246,13 +497,19 @@ export function savedAlternatesLine(pointer: SavedVideoPointer): string {
pointer.probed?.seconds,
pointer.origin?.requestedBy ?? "download",
);
+ // A re-encode says so wherever a copy is listed.
+ const activeReencode = pointer.compacted
+ ? `, a re-encode (${codecName(pointer.compacted.settings.codec)} crf ${pointer.compacted.settings.crf})`
+ : "";
return (
- `${alts.length + 1} saved copies: active ${active}); ` +
+ `${alts.length + 1} saved copies: active ${active}${activeReencode}); ` +
alts
.map(
(a) =>
`alternate ${facts(a.height, a.seconds, a.origin?.requestedBy ?? "download")}, ${a.file}` +
- `${a.keptAs ? `, ${SAVED_ALTERNATE_KEPT_AS_LABELS[a.keptAs]}` : ""})`,
+ `${a.keptAs ? `, ${SAVED_ALTERNATE_KEPT_AS_LABELS[a.keptAs]}` : ""}` +
+ `${a.compactedFrom ? ", a re-encode" : ""}` +
+ `${a.keptAs === "original" && a.review ? `, reviewed ${day(a.review.at)} by ${a.review.by}` : ""})`,
)
.join("; ")
);
@@ -322,5 +579,8 @@ export function parseSavedVideoPointer(raw: unknown): SavedVideoPointer | null {
if (alternates.length) pointer.alternates = alternates;
const probed = parseProbe(r.probed);
if (probed) pointer.probed = probed;
+ // And again: no `compacted`, the pointer parses as before.
+ const compacted = parseCompacted(r.compacted);
+ if (compacted) pointer.compacted = compacted;
return pointer;
}
diff --git a/common/lib/savedVideoCompaction.test.ts b/common/lib/savedVideoCompaction.test.ts
@@ -0,0 +1,152 @@
+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,
+ isStillOnPlatform,
+ sanitizeSavedVideoCompaction,
+ targetFps,
+ type CompactionProbe,
+} from "./savedVideoCompaction";
+import type { SavedVideoPointer } from "./savedVideo";
+
+const pointer = (extra: Partial<SavedVideoPointer> = {}): 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> = {}): CompactionProbe => ({
+ hasVideo: true,
+ vcodec: "h264",
+ width: 1920,
+ height: 1080,
+ fps: 60,
+ seconds: 19_000,
+ videoKbps: 5000,
+ audioKbps: 155,
+ ...extra,
+});
+
+const decide = (o: Partial<Parameters<typeof decideCompaction>[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"]);
+ assert.equal(D.dropOriginal, "after-verify");
+ 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, "after-verify");
+ assert.equal(s.maxFps, 0);
+ assert.equal(sanitizeSavedVideoCompaction({ dropOriginal: "keep" }).dropOriginal, "keep");
+});
+
+test("deliberately stored: a pin, an explicit persist, a requested container — never keep-latest or a legacy pointer", () => {
+ assert.equal(isDeliberatelyStored({ keepReason: "pin" }), true);
+ assert.equal(isDeliberatelyStored({ keepReason: "override" }), true);
+ assert.equal(isDeliberatelyStored({ keepReason: "keep-latest", origin: { requestedBy: "umtool" } }), true);
+ assert.equal(isDeliberatelyStored({ keepReason: "keep-latest" }), false);
+ assert.equal(isDeliberatelyStored({}), false);
+});
+
+test("on its platform only when a record says public or unlisted; unknown counts as gone", () => {
+ assert.equal(isStillOnPlatform("public"), true);
+ assert.equal(isStillOnPlatform("unlisted"), true);
+ for (const a of ["deleted", "private", "members_only", "needs_auth", "error", null, undefined] as const) {
+ assert.equal(isStillOnPlatform(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 list skips the selector's thresholds but never the deliberate rule", () => {
+ assert.deepEqual(decide({ mode: "explicit", platform: "youtube", probe: probe({ videoKbps: 400, height: 360 }) }), { ok: true });
+ assert.equal(decide({ mode: "explicit", pointer: pointer({ keepReason: "keep-latest" }) }).ok, false);
+});
+
+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",
+ );
+});
diff --git a/common/lib/savedVideoCompaction.ts b/common/lib/savedVideoCompaction.ts
@@ -0,0 +1,335 @@
+// 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"`);
+// - 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 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;
+ 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,
+ dropOriginal: "after-verify",
+};
+
+export const SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS: FieldDocs<SavedVideoCompactionSettings> = {
+ 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.",
+ dropOriginal:
+ '"after-verify" (default, operator ruling): 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`). "keep": every original stays until a person drops it.',
+};
+
+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<string, unknown>;
+ 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),
+ dropOriginal: (COMPACTION_DROP_ORIGINAL as readonly unknown[]).includes(r.dropOriginal)
+ ? (r.dropOriginal as CompactionDropOriginal)
+ : d.dropOriginal,
+ };
+}
+
+// --- what counts --------------------------------------------------------------
+
+// DELIBERATELY STORED (ruling 4): a pointer whose keepReason 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;
+// keepReason "override" an explicit persist ("Persist source video",
+// persist-videos, the whole-recording fetch);
+// any `origin` a container somebody requested (umtool's
+// `full: true`, a landed or attached file), whatever
+// its keepReason.
+// NOT: keepReason "keep-latest" with no origin (the automatic window), and a
+// legacy pointer with neither (nobody recorded why it is kept).
+export function isDeliberatelyStored(pointer: Pick<SavedVideoPointer, "keepReason" | "origin">): boolean {
+ if (pointer.origin) return true;
+ return pointer.keepReason === "pin" || pointer.keepReason === "override";
+}
+
+// STILL ON ITS PLATFORM: only a record that says so. Anything else — deleted,
+// private, members-only, needs-auth, a probe that errored, or no record at
+// all — is treated as gone (ruling 6: the stored bytes may be the only
+// original that exists).
+export function isStillOnPlatform(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;
+};
+
+export type CompactionDecision = { ok: true } | { ok: false; reason: 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;
+}): CompactionDecision {
+ const { pointer, settings: s, probe } = opts;
+ if (pointer.compacted) return { ok: false, reason: "already compacted" };
+ 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)"
+ : "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" };
+ if (opts.mode === "select") {
+ if (!opts.platform || !s.platforms.includes(opts.platform)) {
+ return { ok: false, reason: `platform ${opts.platform ?? "unknown"} is not selected` };
+ }
+ if (probe.height === null || probe.height < s.minHeight) {
+ return { ok: false, reason: `${probe.height ?? "unknown "}p is below minHeight ${s.minHeight}` };
+ }
+ if (probe.videoKbps === null || probe.videoKbps < s.minVideoMbps * 1000) {
+ return {
+ ok: false,
+ reason: `${probe.videoKbps === null ? "unknown" : (probe.videoKbps / 1000).toFixed(2)} Mbit/s video is below minVideoMbps ${s.minVideoMbps}`,
+ };
+ }
+ }
+ return { ok: true };
+}
+
+// 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<SavedVideoCompactionSettings, "maxFps" | "maxFpsPlatforms">,
+): 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.<ext>`): the pointer is the
+// only thing that names it.
+export function compactedFileName(at: Date, taken: Iterable<string> = []): string {
+ const stem = `source-media.compact-av1-${at.toISOString().replace(/\D/g, "").slice(0, 14)}`;
+ const names = new Set(taken);
+ let name = `${stem}.mp4`;
+ for (let n = 2; names.has(name); n++) name = `${stem}-${n}.mp4`;
+ 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<CompactionReviewState, string> = {
+ "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",
+};
diff --git a/common/lib/savedVideoOriginal.test.ts b/common/lib/savedVideoOriginal.test.ts
@@ -0,0 +1,276 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "./paths";
+import {
+ compactedLine,
+ compactedOriginalOf,
+ parseSavedVideoPointer,
+ savedAlternatesLine,
+} from "./savedVideo";
+import {
+ SavedAlternateRefusal,
+ dropSavedAlternate,
+ dropSavedVideo,
+ loadSavedVideo,
+ persistSourceVideo,
+ recordOriginalReview,
+ savedVideoPointerPath,
+ unpersistSavedVideo,
+ updateSavedVideoChecksum,
+} from "./savedVideo-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/savedVideoOriginal.test.ts
+//
+// A COMPACTED VIDEO'S POINTER (controller/compactSavedVideos.ts): the
+// `compacted` block and the original kept as `keptAs: "original"` parse back,
+// say "re-encode" wherever they are listed, and the original is deleted by
+// nothing but a confirmed drop — with the re-check, and for a video not known
+// to be on its platform, a review.
+
+const ACTIVE = "source-media.compact-av1-20261114031209.mp4";
+const ORIGINAL = "source-media.mp4";
+const SHA_ACTIVE = "a".repeat(64);
+const SHA_ORIGINAL = "b".repeat(64);
+
+function compactedBlock(extra: Record<string, unknown> = {}) {
+ return {
+ at: "2026-11-14T03:12:09.000Z",
+ tool: "archilyzer compact-saved-videos 1",
+ encoder: "ffmpeg version n9.0.2",
+ settings: { codec: "av1", encoder: "libsvtav1", preset: 8, crf: 36, gopSeconds: 5, pixFmt: "yuv420p", fps: 30, audio: "copy", chunkSeconds: 600 },
+ source: { file: ORIGINAL, bytes: 1200, sha256: SHA_ORIGINAL, vcodec: "h264", height: 1080, fps: 60, seconds: 100 },
+ result: { file: ACTIVE, bytes: 5, sha256: SHA_ACTIVE, vcodec: "av1", height: 1080, fps: 30, seconds: 100 },
+ checks: {
+ passed: true,
+ decoded: true,
+ seconds: [100, 100],
+ secondsTolerance: 0.034,
+ frames: [6000, 3000, 3000],
+ audio: "identical",
+ audioHash: "c".repeat(64),
+ quality: { metric: "vmaf", mean: 94.2, min: 91.9, samples: 12, minMean: 90, minSample: 85 },
+ cuts: [{ at: 10, ssim: 0.97 }],
+ cutSsimMin: 0.9,
+ clock: "none",
+ },
+ chunks: 1,
+ ...extra,
+ };
+}
+
+type Fixture = { paths: Paths; videoDir: string; storeDir: string };
+
+async function withCompacted(
+ opts: { pointer?: Record<string, unknown>; originalOnDisk?: boolean } = {},
+ fn: (f: Fixture) => Promise<void>,
+): Promise<void> {
+ const root = await mkdtemp(path.join(tmpdir(), "compacted-original-"));
+ const paths = {
+ transcriptsDir: root,
+ channelsDir: path.join(root, "channels"),
+ savedVideosDir: path.join(root, "saved-videos"),
+ } as Paths;
+ const videoDir = path.join(paths.channelsDir, "kick", "data", "v1");
+ const storeDir = path.join(paths.savedVideosDir, "kick", "v1");
+ await mkdir(videoDir, { recursive: true });
+ await mkdir(storeDir, { recursive: true });
+ await writeFile(path.join(storeDir, ACTIVE), "av1!!");
+ if (opts.originalOnDisk !== false) await writeFile(path.join(storeDir, ORIGINAL), "o".repeat(1200));
+ const pointer = opts.pointer ?? {
+ storedAt: "2026-11-01T00:00:00.000Z",
+ dir: storeDir,
+ file: ACTIVE,
+ bytes: 5,
+ sha256: SHA_ACTIVE,
+ keepReason: "pin",
+ format: { preset: "original", height: 1080, vcodec: "av1" },
+ compacted: compactedBlock(),
+ alternates: [
+ {
+ file: ORIGINAL,
+ bytes: 1200,
+ storedAt: "2026-11-01T00:00:00.000Z",
+ setAsideAt: "2026-11-14T03:12:09.000Z",
+ height: 1080,
+ vcodec: "h264",
+ keptAs: "original",
+ sha256: SHA_ORIGINAL,
+ },
+ ],
+ };
+ await writeFile(savedVideoPointerPath(videoDir), JSON.stringify(pointer, null, 2) + "\n");
+ try {
+ await fn({ paths, videoDir, storeDir });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+const readRaw = async (videoDir: string) => JSON.parse(await readFile(savedVideoPointerPath(videoDir), "utf8"));
+
+test("a pointer without `compacted` parses exactly as before", () => {
+ const raw = { storedAt: "x", dir: "/s", file: "source-media.mp4", bytes: 3, keepReason: "pin" };
+ assert.deepEqual(parseSavedVideoPointer(raw), raw);
+ assert.equal(compactedLine(parseSavedVideoPointer(raw)!), null);
+});
+
+test("the compacted block and the original parse back, and every line says re-encode", () => {
+ const p = parseSavedVideoPointer({
+ storedAt: "x",
+ dir: "/s",
+ file: ACTIVE,
+ bytes: 4_900_000_000,
+ compacted: compactedBlock({ source: { file: ORIGINAL, bytes: 12_300_000_000, sha256: SHA_ORIGINAL, vcodec: "h264", height: 1080, fps: 60 } }),
+ alternates: [{ file: ORIGINAL, bytes: 12_300_000_000, storedAt: "", setAsideAt: "", keptAs: "original", sha256: SHA_ORIGINAL }],
+ })!;
+ assert.equal(p.compacted?.checks.passed, true);
+ assert.equal(p.compacted?.checks.quality.mean, 94.2);
+ assert.equal(compactedOriginalOf(p)?.file, ORIGINAL);
+ const line = compactedLine(p)!;
+ assert.match(line, /^Re-encoded copy \(AV1 crf 36, 1080p30 from 60 fps, audio copied\) of a 11\.46 GB H\.264 original — 4\.56 GB, 2026-11-14\./);
+ assert.match(line, /The original is kept beside it \(source-media\.mp4\)\./);
+ const alts = savedAlternatesLine(p);
+ assert.match(alts, /active .*a re-encode \(AV1 crf 36\)/);
+ assert.match(alts, /the original the active copy was re-encoded from, kept until it is dropped/);
+});
+
+test("a damaged compacted block still reads as a re-encode, its checks as not passed", () => {
+ const p = parseSavedVideoPointer({ storedAt: "x", dir: "/s", file: ACTIVE, bytes: 3, compacted: { at: 7, checks: "?" } })!;
+ assert.ok(p.compacted);
+ assert.equal(p.compacted.checks.passed, false);
+ assert.match(compactedLine(p)!, /^Re-encoded copy/);
+});
+
+test("an original is not dropped without confirmOriginal", async () => {
+ await withCompacted({}, async ({ videoDir, storeDir }) => {
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { availability: "public", verifiedActive: { sha256: SHA_ACTIVE } }),
+ (e: Error) => e instanceof SavedAlternateRefusal && /ORIGINAL .*confirmOriginal/.test(e.message),
+ );
+ await stat(path.join(storeDir, ORIGINAL));
+ });
+});
+
+test("an original is not dropped unless the compacted copy was just re-checked against its sha256", async () => {
+ await withCompacted({}, async ({ videoDir, storeDir }) => {
+ for (const verifiedActive of [undefined, { sha256: "f".repeat(64) }]) {
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, availability: "public", ...(verifiedActive ? { verifiedActive } : {}) }),
+ /was not read back from disk/,
+ );
+ }
+ await stat(path.join(storeDir, ORIGINAL));
+ // A dry run answers without the re-check.
+ const dry = await dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, availability: "public", dryRun: true });
+ assert.equal(dry.dryRun, true);
+ await stat(path.join(storeDir, ORIGINAL));
+ });
+});
+
+test("a video not known to be on its platform keeps its original until a review is recorded", async () => {
+ await withCompacted({}, async ({ videoDir, storeDir }) => {
+ for (const availability of [null, "deleted", "error", "private"] as const) {
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, verifiedActive: { sha256: SHA_ACTIVE }, availability }),
+ /not known to be on its platform any more.*Review the compacted copy first/,
+ );
+ }
+ // With no availability record on disk at all, the default reads it as gone.
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, verifiedActive: { sha256: SHA_ACTIVE } }),
+ /availability: unknown/,
+ );
+ await stat(path.join(storeDir, ORIGINAL));
+ const reviewed = await recordOriginalReview(videoDir, { at: "2026-11-20T10:00:00.000Z", by: "editor", note: "watched it" });
+ assert.equal(reviewed.review?.by, "editor");
+ const r = await dropSavedAlternate(videoDir, ORIGINAL, {
+ confirmOriginal: true,
+ verifiedActive: { sha256: SHA_ACTIVE },
+ availability: null,
+ by: "test",
+ });
+ assert.equal(r.existed, true);
+ await assert.rejects(stat(path.join(storeDir, ORIGINAL)));
+ const raw = await readRaw(videoDir);
+ assert.equal(raw.alternates, undefined);
+ assert.equal(raw.compacted.originalDropped.by, "test");
+ assert.equal(raw.compacted.originalDropped.sha256, SHA_ORIGINAL);
+ assert.equal(raw.compacted.originalDropped.bytes, 1200);
+ assert.match(compactedLine((await loadSavedVideo(videoDir))!)!, /The original was dropped on 20\d\d-\d\d-\d\d \(sha256 bbbbbbbbbbbb…, 1200 bytes\)/);
+ });
+});
+
+test("a video on its platform drops its original with confirm and the re-check, no review needed", async () => {
+ await withCompacted({}, async ({ videoDir, storeDir }) => {
+ await dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, verifiedActive: { sha256: SHA_ACTIVE }, availability: "public" });
+ await assert.rejects(stat(path.join(storeDir, ORIGINAL)));
+ await stat(path.join(storeDir, ACTIVE));
+ });
+});
+
+test("an original whose compacted copy's checks did not pass is never dropped, nor reviewed", async () => {
+ await withCompacted({}, async ({ videoDir }) => {
+ const raw = await readRaw(videoDir);
+ raw.compacted.checks.passed = false;
+ await writeFile(savedVideoPointerPath(videoDir), JSON.stringify(raw));
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, verifiedActive: { sha256: SHA_ACTIVE }, availability: "public" }),
+ /checks did not pass/,
+ );
+ await assert.rejects(recordOriginalReview(videoDir, { at: "x", by: "editor" }), /checks did not pass/);
+ });
+});
+
+test("dropSavedVideo (the prune's delete) refuses a video that keeps an original", async () => {
+ await withCompacted({}, async ({ videoDir, storeDir }) => {
+ await assert.rejects(dropSavedVideo(videoDir), (e: Error) => e instanceof SavedAlternateRefusal);
+ await stat(path.join(storeDir, ORIGINAL));
+ await stat(path.join(storeDir, ACTIVE));
+ assert.ok(await loadSavedVideo(videoDir));
+ });
+});
+
+test("unpersist brings every copy back with the original as the source; refused once the original is gone", async () => {
+ await withCompacted({}, async ({ videoDir }) => {
+ assert.equal(await unpersistSavedVideo(videoDir), true);
+ assert.equal(await readFile(path.join(videoDir, ORIGINAL), "utf8"), "o".repeat(1200));
+ await stat(path.join(videoDir, ACTIVE));
+ });
+ await withCompacted({}, async ({ videoDir, storeDir }) => {
+ const raw = await readRaw(videoDir);
+ delete raw.alternates;
+ await writeFile(savedVideoPointerPath(videoDir), JSON.stringify(raw));
+ await rm(path.join(storeDir, ORIGINAL));
+ await assert.rejects(unpersistSavedVideo(videoDir), /re-encode .*original was dropped/);
+ assert.ok(await loadSavedVideo(videoDir));
+ await stat(path.join(storeDir, ACTIVE));
+ });
+});
+
+test("a persist landing under the original's name moves the original aside, never over it", async () => {
+ await withCompacted({}, async ({ videoDir, storeDir }) => {
+ await writeFile(path.join(videoDir, ORIGINAL), "a new download");
+ const p = await persistSourceVideo({ videoDir, sourceFilename: ORIGINAL, storeDir, keepReason: "override" });
+ assert.equal(p.file, ORIGINAL);
+ assert.equal(await readFile(path.join(storeDir, ORIGINAL), "utf8"), "a new download");
+ const kept = p.alternates?.find((a) => a.keptAs === "original");
+ assert.ok(kept && kept.file !== ORIGINAL && /^source-media\.alt-1080p-\d{14}\.mp4$/.test(kept.file), kept?.file);
+ assert.equal(await readFile(path.join(storeDir, kept.file), "utf8"), "o".repeat(1200));
+ assert.ok((await readdir(storeDir)).includes(ACTIVE));
+ });
+});
+
+test("a checksum is written only while the pointer names the file that was hashed", async () => {
+ await withCompacted({}, async ({ videoDir }) => {
+ await updateSavedVideoChecksum(videoDir, "d".repeat(64), ORIGINAL);
+ assert.equal((await readRaw(videoDir)).sha256, SHA_ACTIVE);
+ await updateSavedVideoChecksum(videoDir, "e".repeat(64), ACTIVE);
+ const raw = await readRaw(videoDir);
+ assert.equal(raw.sha256, "e".repeat(64));
+ assert.ok(raw.compacted, "the rest of the pointer is kept");
+ });
+});
diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts
@@ -223,6 +223,10 @@ export async function cutSavedVideoWindow(opts: {
// When the window landed — for a cut, when it was cut.
fetchedAt: now,
source: "saved-video",
+ // A cut from a compacted copy says it is one generation further on.
+ ...(source.pointer.compacted
+ ? { fromReencode: { file: source.pointer.file, originalSha256: source.pointer.compacted.source.sha256 } }
+ : {}),
...(height !== null ? { height } : {}),
...(mapped && source.clock
? {
@@ -245,7 +249,7 @@ export async function cutSavedVideoWindow(opts: {
opts.onLog?.(
`Cut ${from.toFixed(2)}–${to.toFixed(2)}${onClock} from the saved video ${source.pointer.file} into ` +
`clips/${clipWindowFile(from, to, tier)} (${bytes} bytes` +
- `${height !== null ? `, ${height}p` : ""}); nothing fetched.\n`,
+ `${height !== null ? `, ${height}p` : ""}${source.pointer.compacted ? ", from the compacted re-encode" : ""}); nothing fetched.\n`,
);
return {
file: clipWindowFile(from, to, tier),
diff --git a/common/ytdlp/savedAlternates.ts b/common/ytdlp/savedAlternates.ts
@@ -38,6 +38,9 @@
// page's "Drop this alternate" — deletes one listed alternate and its pointer
// entry, never the active copy. Nothing else deletes one but `dropSavedVideo`
// (the whole video) and `unpersistSavedVideo` (which brings them back).
+// An ORIGINAL (`keptAs: "original"`, the source of a compacted copy —
+// controller/compactSavedVideos.ts) goes only by a confirmed
+// dropSavedAlternate: dropSavedVideo refuses a video that keeps one.
//
// Audio is not part of this: the landed guard's audio half still keeps the
// longer audio.<fmt> (a transcript was made from it), as before.
@@ -54,6 +57,7 @@ import {
type SavedVideoProbe,
} from "../lib/savedVideo";
import {
+ alternateName,
loadSavedVideo,
moveFileCrossDevice,
persistSourceVideo,
@@ -127,19 +131,9 @@ export async function planSavedContainer(opts: {
};
}
-function stampOf(at: Date): string {
- return at.toISOString().replace(/\D/g, "").slice(0, 14);
-}
-
-// `source-media.alt-<h>p-<stamp>.<ext>`, unique in `taken`.
-export function alternateName(file: string, height: number | null, at: Date, taken: Iterable<string> = []): string {
- const ext = path.extname(file);
- const stem = `source-media.alt-${height ? `${height}p-` : ""}${stampOf(at)}`;
- const names = new Set(taken);
- let name = `${stem}${ext}`;
- for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`;
- return name;
-}
+// `source-media.alt-<h>p-<stamp>.<ext>`, unique in `taken` (lib/savedVideo-server.ts:
+// persistSourceVideo moves an alternate aside under the same kind of name).
+export { alternateName };
function describe(height: number | null, seconds: number | null): string {
return `${height ? `${height}p` : "height unknown"}, ${seconds !== null ? `${seconds.toFixed(1)} s` : "length unknown"}`;
@@ -279,6 +273,9 @@ export async function persistOverExisting(
...(old.origin ? { origin: old.origin } : {}),
...(old.format?.preset ? { preset: old.format.preset } : {}),
...(proxy ? { keptAs: "proxy" as const } : {}),
+ // The copy set aside was itself a re-encode (a compacted active copy):
+ // it says so wherever it is listed.
+ ...(old.compacted ? { compactedFrom: old.compacted.source.sha256, ...(old.sha256 ? { sha256: old.sha256 } : {}) } : {}),
},
],
};