commit e881894248863350d9703e9fb40dd889062fdcc3
parent 98419195c833422a3aebffa8807b4941ea2ad604
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 13 Nov 2026 15:27:33 -0500
persist-videos: replace "below-height" upgrades a lower saved copy and keeps it as the proxy
A saved copy whose height (recorded, else probed with ffprobe) is below what
the requested quality gives -- the lower of its ceiling and the tallest video
format metadata.info.json lists -- is sorted into a new `lowerHeight` bucket
and re-fetched under `replace: "below-height"`. The download becomes the
active copy as above-height's replace does; the old one stays beside it and,
once the new copy is measured taller, its alternate entry is marked
`keptAs: "proxy"` (a new, optional pointer key). A copy that cannot be
compared (no readable height, or "original" with no format heights) is
`heightUnknown` and left alone; a copy downloaded at the requested preset is
what it gives and is left alone. "never" and "above-height" sort exactly as
before and probe nothing.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
6 files changed, 626 insertions(+), 23 deletions(-)
diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts
@@ -9,9 +9,11 @@ import type { SiteSettings } from "../lib/settings";
import type { DiskGateStatus } from "../lib/diskSpace";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server";
+import { savedAlternatesLine } from "../lib/savedVideo";
import {
PERSIST_VIDEOS_DOWNLOAD,
persistVideos,
+ tallestFormatHeight,
type PersistVideoDownload,
type PersistVideosDeps,
} from "./persistVideos";
@@ -82,12 +84,30 @@ function videoDir(paths: Paths, slug: string, id: string): string {
}
// A downloaded video: its dir and the metadata that names its source URL.
-async function seedVideo(paths: Paths, slug: string, id: string): Promise<void> {
+async function seedVideo(
+ paths: Paths,
+ slug: string,
+ id: string,
+ formatHeights?: number[],
+): Promise<void> {
const dir = videoDir(paths, slug, id);
await mkdir(dir, { recursive: true });
await writeFile(
path.join(dir, "metadata.info.json"),
- JSON.stringify({ id, webpage_url: `https://www.youtube.com/watch?v=${id}` }),
+ JSON.stringify({
+ id,
+ webpage_url: `https://www.youtube.com/watch?v=${id}`,
+ ...(formatHeights
+ ? {
+ formats: [
+ // A storyboard and an audio-only format are not video.
+ { format_id: "sb0", ext: "mhtml", vcodec: "none", height: 4320 },
+ { format_id: "ba", vcodec: "none", acodec: "opus" },
+ ...formatHeights.map((height) => ({ format_id: `v${height}`, height, vcodec: "avc1" })),
+ ],
+ }
+ : {}),
+ }),
);
}
@@ -100,22 +120,32 @@ async function seedSaved(
file?: string;
keepReason?: "keep-latest" | "pin";
requestedBy?: string;
+ // The preset the copy was downloaded at; null = a landed copy (an import
+ // or an attach), which records no format at all.
+ preset?: "original" | "video_720" | null;
+ // The video formats its metadata.info.json lists (absent: no `formats`).
+ formatHeights?: number[];
} = {},
): Promise<void> {
- await seedVideo(paths, slug, id);
+ await seedVideo(paths, slug, id, opts.formatHeights);
const dir = videoDir(paths, slug, id);
const file = opts.file ?? "source-media.mp4";
await writeFile(path.join(dir, file), `old ${id}`);
+ const preset = opts.preset === undefined ? "original" : opts.preset;
await persistSourceVideo({
videoDir: dir,
sourceFilename: file,
storeDir: path.join(paths.savedVideosDir, slug, id),
keepReason: opts.keepReason ?? "keep-latest",
...(opts.requestedBy ? { origin: { requestedBy: opts.requestedBy } } : {}),
- format: {
- preset: "original",
- ...(opts.height ? { height: opts.height } : {}),
- },
+ ...(preset
+ ? {
+ format: {
+ preset,
+ ...(opts.height ? { height: opts.height } : {}),
+ },
+ }
+ : {}),
});
}
@@ -182,6 +212,8 @@ function harness(
getSettings: () => SETTINGS,
readChannelConfig: async (_p, slug) => (slug === "nope" ? null : CONFIG),
onPlatformBackoff: async () => {},
+ // No ffprobe in a test: a stored file's height is scripted per test.
+ probeHeight: async () => null,
...over,
},
};
@@ -565,3 +597,285 @@ test("a saved-video store whose drive is not answering stops the run before any
}
});
});
+
+// UPGRADE: "below-height" (a saved copy lower than the quality gives). The
+// probe is scripted by the stored file's content ("old <id>"), so a test says
+// which copies answer ffprobe and at what height.
+function probeBy(heights: Record<string, number>, calls: string[] = []) {
+ return async (_paths: Paths, file: string): Promise<number | null> => {
+ const id = path.basename(path.dirname(file));
+ calls.push(id);
+ return heights[id] ?? null;
+ };
+}
+
+test("tallestFormatHeight: the tallest video format; storyboards, audio and no formats are not one", () => {
+ assert.equal(
+ tallestFormatHeight({
+ formats: [
+ { ext: "mhtml", vcodec: "none", height: 4320 },
+ { vcodec: "none", acodec: "opus" },
+ { height: 360, vcodec: "avc1" },
+ { height: 1080 },
+ { height: 720.5 },
+ ],
+ }),
+ 1080,
+ );
+ assert.equal(tallestFormatHeight({ formats: [{ vcodec: "none" }] }), null);
+ assert.equal(tallestFormatHeight({ id: "x" }), null);
+ assert.equal(tallestFormatHeight(null), null);
+});
+
+test("below-height sorts saved copies: lower, equal, taller, probed, not compared — and fetches nothing on a dry run", async () => {
+ await withPaths(async (paths) => {
+ const S = "demo-channel";
+ const tall = [360, 720, 1080];
+ // A landed 360p import: no format on the pointer, so its height is probed.
+ await seedSaved(paths, S, "lower11", { preset: null, requestedBy: "import-media", keepReason: "pin", formatHeights: tall });
+ // A 720p download at the other preset: its recorded height is used.
+ await seedSaved(paths, S, "rec7201", { preset: "video_720", height: 720, formatHeights: tall });
+ // Equal: probed at the tallest the source offers.
+ await seedSaved(paths, S, "equal11", { preset: null, requestedBy: "import-media", formatHeights: tall });
+ // Downloaded at this very preset: what "original" gives, even though lower.
+ await seedSaved(paths, S, "same111", { preset: "original", height: 480, formatHeights: tall });
+ // No formats in its metadata: what "original" gives is not known.
+ await seedSaved(paths, S, "nofmt11", { preset: null, requestedBy: "import-media" });
+ // ffprobe cannot read it: not compared.
+ await seedSaved(paths, S, "noprob1", { preset: null, requestedBy: "import-media", formatHeights: tall });
+ const items = ["lower11", "rec7201", "equal11", "same111", "nofmt11", "noprob1"].map((id) => ({ slug: S, id }));
+ const calls: string[] = [];
+ const h = harness(paths, {
+ probeHeight: probeBy({ lower11: 360, equal11: 1080, nofmt11: 360 }, calls),
+ });
+ const lines: string[] = [];
+ const res = await persistVideos({
+ paths,
+ items,
+ format: "original",
+ replace: "below-height",
+ dryRun: true,
+ onLog: (l) => lines.push(l),
+ deps: h.deps,
+ });
+ assert.equal(h.downloads.length, 0);
+ const ids = (b: { items: { id: string }[] }) => b.items.map((i) => i.id);
+ assert.deepEqual(ids(res.plan.lowerHeight), ["lower11", "rec7201"]);
+ assert.deepEqual(ids(res.plan.saved), ["equal11", "same111"]);
+ assert.deepEqual(ids(res.plan.heightUnknown), ["nofmt11", "noprob1"]);
+ assert.equal(res.plan.wrongHeight.count, 0);
+ assert.equal(res.plan.willFetch, 2);
+ // Only a pointer with no recorded height is probed.
+ assert.deepEqual(calls.sort(), ["equal11", "lower11", "nofmt11", "noprob1"]);
+ const text = lines.join("");
+ assert.match(text, /2 saved below it \(to replace, the saved copy kept as a proxy\), 2 saved and not compared/);
+ assert.match(text, /demo-channel\/lower11: saved at 360p \(probed\), below the 1080p original gives\./);
+ assert.match(text, /demo-channel\/rec7201: saved at 720p \(recorded\), below the 1080p original gives\./);
+ assert.match(text, /nofmt11: saved, not compared — its metadata\.info\.json lists no format heights/);
+ assert.match(text, /noprob1: saved, not compared — its height is not recorded and ffprobe could not read one/);
+
+ // The other policies sort exactly as before: nothing probed, no lower bucket.
+ for (const replace of ["never", "above-height"] as const) {
+ const before: string[] = [];
+ const other = await persistVideos({
+ paths,
+ items,
+ format: "original",
+ replace,
+ dryRun: true,
+ deps: { ...h.deps, probeHeight: probeBy({}, before) },
+ });
+ assert.equal(other.plan.saved.count, 6, replace);
+ assert.equal(other.plan.lowerHeight.count, 0, replace);
+ assert.equal(other.plan.heightUnknown.count, 0, replace);
+ assert.equal(other.plan.willFetch, 0, replace);
+ assert.deepEqual(before, [], replace);
+ }
+ });
+});
+
+test("below-height at video_720: the ceiling caps what it gives; taller or unmeasured stays wrongHeight", async () => {
+ await withPaths(async (paths) => {
+ const S = "demo-channel";
+ // 360p, the source offers 1080: below the 720 the quality gives.
+ await seedSaved(paths, S, "low3601", { preset: null, requestedBy: "import-media", formatHeights: [360, 1080] });
+ // 360p with no formats in its metadata: the ceiling is still known.
+ await seedSaved(paths, S, "low3602", { preset: null, requestedBy: "import-media" });
+ // 480p, and the source tops out at 480: that is all video_720 gives.
+ await seedSaved(paths, S, "top4801", { preset: "original", height: 480, formatHeights: [240, 480] });
+ // Taller than the ceiling, and one ffprobe cannot read: wrongHeight, left alone.
+ await seedSaved(paths, S, "tall108", { preset: null, requestedBy: "import-media", formatHeights: [1080] });
+ await seedSaved(paths, S, "nohgt11", { preset: null, requestedBy: "import-media", formatHeights: [1080] });
+ const items = ["low3601", "low3602", "top4801", "tall108", "nohgt11"].map((id) => ({ slug: S, id }));
+ const h = harness(paths, {
+ probeHeight: probeBy({ low3601: 360, low3602: 360, tall108: 1080 }),
+ });
+ const res = await persistVideos({
+ paths,
+ items,
+ format: "video_720",
+ replace: "below-height",
+ dryRun: true,
+ deps: h.deps,
+ });
+ const ids = (b: { items: { id: string }[] }) => b.items.map((i) => i.id);
+ assert.deepEqual(ids(res.plan.lowerHeight), ["low3601", "low3602"]);
+ assert.deepEqual(ids(res.plan.saved), ["top4801"]);
+ assert.deepEqual(ids(res.plan.wrongHeight), ["tall108", "nohgt11"]);
+ assert.equal(res.plan.willFetch, 2);
+ });
+});
+
+test("below-height does not probe a store that is not answering; the copy is not compared", async () => {
+ const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth");
+ await withPaths(async (paths) => {
+ await seedSaved(paths, "demo-channel", "lower11", { preset: null, requestedBy: "import-media", formatHeights: [1080] });
+ recordLocationHealth(
+ { id: "store", label: "Store drive", root: path.dirname(paths.savedVideosDir) },
+ "stalled",
+ );
+ try {
+ const calls: string[] = [];
+ const lines: string[] = [];
+ const res = await persistVideos({
+ paths,
+ items: [{ slug: "demo-channel", id: "lower11" }],
+ format: "original",
+ replace: "below-height",
+ dryRun: true,
+ onLog: (l) => lines.push(l),
+ deps: harness(paths, { probeHeight: probeBy({ lower11: 360 }, calls) }).deps,
+ });
+ assert.deepEqual(calls, []);
+ assert.equal(res.plan.heightUnknown.count, 1);
+ assert.match(lines.join(""), /its height is not recorded and the store cannot be read/);
+ } finally {
+ resetStorageHealth();
+ }
+ });
+});
+
+test("below-height makes the taller download active and keeps the lower copy beside it as the proxy", async () => {
+ await withPaths(async (paths) => {
+ const S = "demo-channel";
+ // The real case: a landed 360p import of a VOD the source offers at 1080p.
+ await seedSaved(paths, S, "kickvod", {
+ preset: null,
+ requestedBy: "import-media",
+ keepReason: "pin",
+ formatHeights: [160, 360, 720, 1080],
+ });
+ // A requested 720p download, keep-latest: its provenance carries over.
+ await seedSaved(paths, S, "dl72011", {
+ preset: "video_720",
+ height: 720,
+ requestedBy: "umtool",
+ formatHeights: [720, 1080],
+ });
+ const items = ["kickvod", "dl72011"].map((id) => ({ slug: S, id }));
+ const oldKick = await loadSavedVideo(videoDir(paths, S, "kickvod"));
+ const h = harness(paths, { height: 1080, probeHeight: probeBy({ kickvod: 360 }) });
+ const lines: string[] = [];
+ const res = await persistVideos({
+ paths,
+ items,
+ format: "original",
+ replace: "below-height",
+ onLog: (l) => lines.push(l),
+ deps: h.deps,
+ });
+ assert.deepEqual(h.downloads, [
+ { slug: S, id: "kickvod", quality: "original" },
+ { slug: S, id: "dl72011", quality: "original" },
+ ]);
+ assert.deepEqual(res.replaced.map((i) => i.id), ["kickvod", "dl72011"]);
+ assert.equal(res.proxies.length, 2);
+ assert.equal(res.failed.length, 0);
+
+ const kick = await loadSavedVideo(videoDir(paths, S, "kickvod"));
+ // The download is the active copy, at the height it was taken.
+ assert.equal(await readFile(path.join(kick!.dir, kick!.file), "utf8"), "new kickvod");
+ assert.equal(kick?.format?.height, 1080);
+ // A pin stays a pin; a landed copy's origin stays with that copy.
+ assert.equal(kick?.keepReason, "pin");
+ assert.equal(kick?.origin, undefined);
+ const proxy = kick?.alternates?.[0];
+ assert.equal(kick?.alternates?.length, 1);
+ assert.equal(proxy?.keptAs, "proxy");
+ assert.equal(proxy?.storedAt, oldKick?.storedAt);
+ assert.equal(proxy?.origin?.requestedBy, "import-media");
+ assert.equal(await readFile(path.join(kick!.dir, proxy!.file), "utf8"), "old kickvod");
+ assert.deepEqual(res.proxies[0], { slug: S, id: "kickvod", file: proxy!.file });
+ assert.match(savedAlternatesLine(kick!), /kept on purpose as the lower-quality proxy/);
+
+ const dl = await loadSavedVideo(videoDir(paths, S, "dl72011"));
+ assert.equal(dl?.keepReason, "keep-latest");
+ assert.deepEqual(dl?.origin, { requestedBy: "umtool" });
+ assert.equal(dl?.alternates?.[0]?.height, 720);
+ assert.equal(dl?.alternates?.[0]?.keptAs, "proxy");
+ assert.equal(dl?.alternates?.[0]?.preset, "video_720");
+
+ const text = lines.join("");
+ assert.match(text, /kickvod: upgrading the saved 360p container \(original\)/);
+ // (The harness's ffprobe reads no height, so the alternate's name has none;
+ // in a real run finalizeAppExtraction probes the old copy and names it 360p.)
+ assert.match(text, /kickvod: now 1080p; the 360p copy stays beside it as source-media\.alt-\d{14}\.mp4, kept as its proxy\./);
+ assert.match(text, /2 persisted \(2 replaced, 2 old copies kept as proxies\)/);
+
+ // RE-RUNNING IS THE RESUME: both are now what "original" gives.
+ const again = harness(paths, { height: 1080, probeHeight: probeBy({}) });
+ const rerun = await persistVideos({
+ paths,
+ items,
+ format: "original",
+ replace: "below-height",
+ deps: again.deps,
+ });
+ assert.equal(again.downloads.length, 0);
+ assert.equal(rerun.plan.saved.count, 2);
+ });
+});
+
+test("below-height: a download that is not taller leaves both copies flagged for a check, no proxy", async () => {
+ await withPaths(async (paths) => {
+ await seedSaved(paths, "demo-channel", "lower11", {
+ preset: null,
+ requestedBy: "import-media",
+ formatHeights: [360, 1080],
+ });
+ // The source no longer gives more than 360p.
+ const h = harness(paths, { height: 360, probeHeight: probeBy({ lower11: 360 }) });
+ const lines: string[] = [];
+ const res = await persistVideos({
+ paths,
+ items: [{ slug: "demo-channel", id: "lower11" }],
+ format: "original",
+ replace: "below-height",
+ onLog: (l) => lines.push(l),
+ deps: h.deps,
+ });
+ assert.equal(res.replaced.length, 1);
+ assert.deepEqual(res.proxies, []);
+ const ptr = await loadSavedVideo(videoDir(paths, "demo-channel", "lower11"));
+ assert.equal(ptr?.alternates?.length, 1);
+ assert.equal(ptr?.alternates?.[0]?.keptAs, undefined);
+ assert.match(lines.join(""), /the download is 360p, not taller than 360p; .*flagged for a check \(not marked as a proxy\)/);
+ });
+});
+
+test("below-height leaves a saved copy above the ceiling alone (that is above-height's)", async () => {
+ await withPaths(async (paths) => {
+ await seedSaved(paths, "demo-channel", "tall111", { height: 1080, preset: "original", formatHeights: [1080] });
+ const h = harness(paths);
+ const res = await persistVideos({
+ paths,
+ items: [{ slug: "demo-channel", id: "tall111" }],
+ format: "video_720",
+ replace: "below-height",
+ deps: h.deps,
+ });
+ assert.equal(h.downloads.length, 0);
+ assert.equal(res.plan.wrongHeight.count, 1);
+ assert.equal(res.plan.willFetch, 0);
+ });
+});
diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts
@@ -8,11 +8,13 @@ import { diskGate, type DiskGateStatus } from "../lib/diskSpace";
import { savedVideosStoreRefusal } from "../lib/savedVideoStore";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
-import { savedVideoDir, type SavedVideoPointer } from "../lib/savedVideo";
+import { savedVideoDir, savedVideoPath, type SavedVideoPointer } from "../lib/savedVideo";
import {
loadSavedVideo,
+ markSavedAlternate,
restoreSavedVideoProvenance,
} from "../lib/savedVideo-server";
+import { probeVideoHeight } from "../ytdlp/ffprobeDuration";
import { readChannelConfig } from "./channels";
import { findVideoSourceUrl } from "./undownloadedVideos";
import {
@@ -62,10 +64,24 @@ import { recordDownloadBackoff } from "../jobs/downloadBackoff";
// The replacement keeps the old pointer's `keepReason` and `origin` (a landed
// copy's origin stays with that copy), so a keep-latest container stays
// evictable and a requested one keeps its requester.
+//
+// UPGRADING KEEPS THE OLD COPY AS A PROXY. `replace: "below-height"` re-fetches
+// a saved video whose height is below what the requested quality gives: the
+// lower of its ceiling (720 for "video_720", none for "original") and the
+// tallest video format its metadata.info.json lists. The saved copy's height is
+// the pointer's (`format`, else `probed`), else an ffprobe of the stored file —
+// a landed import or attach records none. Not compared, and so not fetched
+// (`heightUnknown`): a height the probe could not read, or an "original" ask of
+// a record whose metadata lists no format heights. A copy a download already
+// made at the requested quality is what that quality gives, and is left alone
+// (a re-fetch would bring the same file back on every re-run). The replace is
+// the same as above-height's, and the old copy's alternate entry is then
+// marked `keptAs: "proxy"` — kept on purpose, not for a check — once the new
+// active copy is measured taller. Each policy re-fetches only its own bucket.
export type PersistVideoItem = { slug: string; id: string };
-export const PERSIST_REPLACE_POLICIES = ["never", "above-height"] as const;
+export const PERSIST_REPLACE_POLICIES = ["never", "above-height", "below-height"] as const;
export type PersistReplacePolicy = (typeof PERSIST_REPLACE_POLICIES)[number];
export function isPersistReplacePolicy(v: unknown): v is PersistReplacePolicy {
@@ -81,17 +97,24 @@ export type PersistVideosBucket = { count: number; items: PersistVideoItem[] };
// saved already in the store at an acceptable height — left alone
// wrongHeight in the store, but its height is unknown or above the ceiling
// of the requested quality; re-fetched only under "above-height"
+// lowerHeight in the store, below what the requested quality gives;
+// re-fetched only under "below-height" (sorted only then)
+// heightUnknown in the store, but whether it is below what the quality gives
+// could not be told (sorted only under "below-height"); never
+// fetched
// toFetch not saved, with a resolvable source URL
// noUrl not saved, and no source URL can be resolved
// unknown no such channel, or no data/<id>/ for that video
export type PersistVideosPlan = {
saved: PersistVideosBucket;
wrongHeight: PersistVideosBucket;
+ lowerHeight: PersistVideosBucket;
+ heightUnknown: PersistVideosBucket;
toFetch: PersistVideosBucket;
noUrl: PersistVideosBucket;
unknown: PersistVideosBucket;
- // How many downloads a run would attempt: toFetch, plus wrongHeight when
- // the replace policy re-fetches it.
+ // How many downloads a run would attempt: toFetch, plus wrongHeight or
+ // lowerHeight when the replace policy re-fetches it.
willFetch: number;
};
@@ -112,6 +135,9 @@ export type PersistVideosResult = {
persisted: PersistVideoItem[];
// Of `persisted`, the ones that replaced an existing container.
replaced: PersistVideoItem[];
+ // Of `replaced` ("below-height"), the ones whose old copy is now kept as
+ // the proxy (`keptAs: "proxy"`), with that copy's file name.
+ proxies: (PersistVideoItem & { file: string })[];
failed: (PersistVideoItem & { error: string })[];
// Due a download but not attempted because the run stopped first.
notAttempted: PersistVideoItem[];
@@ -145,6 +171,9 @@ export type PersistVideosDeps = {
paths: Paths,
failureClass: "rate_limit" | "network",
) => Promise<void>;
+ // Pixel height of a stored container's first video stream, or null.
+ // "below-height" asks it of a saved copy whose pointer records none.
+ probeHeight: (paths: Paths, file: string) => Promise<number | null>;
};
// How often the memory wait re-reads /proc/meminfo.
@@ -210,6 +239,7 @@ const DEFAULT_DEPS: PersistVideosDeps = {
readChannelConfig,
onPlatformBackoff: (platform, paths, failureClass) =>
recordDownloadBackoff(platform, paths, failureClass),
+ probeHeight: (paths, file) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file }),
};
// The tallest height a quality accepts, or null for "original" (no ceiling).
@@ -239,14 +269,97 @@ async function isDirectory(p: string): Promise<boolean> {
}
}
+// The tallest video format a record's metadata.info.json lists, or null when
+// it lists none with a height (no file, no `formats`, audio only). Storyboards
+// (vcodec "none", mhtml) are not video.
+export function tallestFormatHeight(meta: unknown): number | null {
+ const formats = (meta as { formats?: unknown } | null)?.formats;
+ if (!Array.isArray(formats)) return null;
+ let tallest: number | null = null;
+ for (const f of formats) {
+ if (!f || typeof f !== "object") continue;
+ const r = f as Record<string, unknown>;
+ if (r.vcodec === "none" || r.ext === "mhtml") continue;
+ const h = r.height;
+ if (typeof h !== "number" || !Number.isInteger(h) || h <= 0) continue;
+ if (tallest === null || h > tallest) tallest = h;
+ }
+ return tallest;
+}
+
+async function readTallestFormatHeight(videoDir: string): Promise<number | null> {
+ try {
+ return tallestFormatHeight(
+ JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")),
+ );
+ } catch {
+ return null;
+ }
+}
+
type PlannedItem = PersistVideoItem & {
bucket: Exclude<keyof PersistVideosPlan, "willFetch">;
config?: ChannelConfig;
quality?: SourceVideoQuality;
url?: string;
pointer?: SavedVideoPointer;
+ // "below-height": the saved copy's height and where it came from, what the
+ // quality would give, and — for heightUnknown — why it was not compared.
+ height?: number;
+ heightFrom?: "recorded" | "probed";
+ target?: number;
+ why?: string;
};
+// "below-height" sorting of one saved copy. The saved copy's height is the
+// pointer's, else the stored file's (probed, unless the store cannot answer).
+async function classifyForUpgrade(
+ paths: Paths,
+ videoDir: string,
+ pointer: SavedVideoPointer,
+ quality: SourceVideoQuality,
+ deps: PersistVideosDeps,
+): Promise<Pick<PlannedItem, "bucket" | "height" | "heightFrom" | "target" | "why">> {
+ const ceiling = sourceVideoQualityMaxHeight(quality);
+ let height = pointer.format?.height ?? pointer.probed?.height;
+ let heightFrom: PlannedItem["heightFrom"] = height !== undefined ? "recorded" : undefined;
+ let noHeight = "its height is not recorded";
+ if (height === undefined) {
+ // A stalled or moving store is not probed: ffprobe on a drive that is not
+ // answering would hold the plan.
+ const refusal = await savedVideosStoreRefusal(paths, pointer.dir);
+ if (refusal) {
+ noHeight = `its height is not recorded and the store cannot be read (${refusal.message})`;
+ } else {
+ const probed = await deps.probeHeight(paths, savedVideoPath(pointer));
+ if (probed !== null) {
+ height = probed;
+ heightFrom = "probed";
+ } else {
+ noHeight = "its height is not recorded and ffprobe could not read one";
+ }
+ }
+ }
+ const at = { ...(height !== undefined ? { height, heightFrom } : {}) };
+ // Too tall, or (with a ceiling) of unknown height: wrongHeight, as ever.
+ if (ceiling !== null && (height === undefined || height > ceiling)) {
+ return { bucket: "wrongHeight", ...at };
+ }
+ if (height === undefined) return { bucket: "heightUnknown", why: noHeight };
+ // Already what this quality gives: a re-fetch would bring the same back.
+ if (pointer.format?.preset === quality) return { bucket: "saved", ...at };
+ const tallest = await readTallestFormatHeight(videoDir);
+ const target = ceiling === null ? tallest : tallest === null ? ceiling : Math.min(ceiling, tallest);
+ if (target === null) {
+ return {
+ bucket: "heightUnknown",
+ ...at,
+ why: "its metadata.info.json lists no format heights, so what the original would give is not known",
+ };
+ }
+ return { bucket: height < target ? "lowerHeight" : "saved", ...at, target };
+}
+
function emptyBucket(): PersistVideosBucket {
return { count: 0, items: [] };
}
@@ -256,6 +369,7 @@ async function classify(
paths: Paths,
items: PersistVideoItem[],
format: SourceVideoQuality | undefined,
+ replace: PersistReplacePolicy,
settings: SiteSettings,
deps: PersistVideosDeps,
): Promise<PlannedItem[]> {
@@ -288,6 +402,17 @@ async function classify(
const pointer = await loadSavedVideo(videoDir);
const url =
(await findVideoSourceUrl(paths, item.slug, item.id, config)) ?? undefined;
+ if (pointer && replace === "below-height") {
+ out.push({
+ ...item,
+ ...(await classifyForUpgrade(paths, videoDir, pointer, quality, deps)),
+ config,
+ quality,
+ url,
+ pointer,
+ });
+ continue;
+ }
if (pointer) {
const ceiling = sourceVideoQualityMaxHeight(quality);
const height = pointer.format?.height;
@@ -314,6 +439,8 @@ function planOf(
const plan: PersistVideosPlan = {
saved: emptyBucket(),
wrongHeight: emptyBucket(),
+ lowerHeight: emptyBucket(),
+ heightUnknown: emptyBucket(),
toFetch: emptyBucket(),
noUrl: emptyBucket(),
unknown: emptyBucket(),
@@ -323,11 +450,26 @@ function planOf(
plan[p.bucket].items.push({ slug: p.slug, id: p.id });
plan[p.bucket].count += 1;
}
- plan.willFetch =
- plan.toFetch.count + (replace === "above-height" ? plan.wrongHeight.count : 0);
+ plan.willFetch = plan.toFetch.count + replacedBucket(plan, replace);
return plan;
}
+// The saved items a policy re-fetches.
+function replaces(bucket: PlannedItem["bucket"], replace: PersistReplacePolicy): boolean {
+ return (
+ (bucket === "wrongHeight" && replace === "above-height") ||
+ (bucket === "lowerHeight" && replace === "below-height")
+ );
+}
+
+function replacedBucket(plan: PersistVideosPlan, replace: PersistReplacePolicy): number {
+ return replace === "above-height"
+ ? plan.wrongHeight.count
+ : replace === "below-height"
+ ? plan.lowerHeight.count
+ : 0;
+}
+
function label(item: PersistVideoItem): string {
return `${item.slug}/${item.id}`;
}
@@ -371,13 +513,14 @@ export async function persistVideos({
const downloadSignal = signal ?? new AbortController().signal;
const settings = deps.getSettings();
- const planned = await classify(paths, items, format, settings, deps);
+ const planned = await classify(paths, items, format, replace, settings, deps);
const plan = planOf(planned, replace);
const result: PersistVideosResult = {
plan,
dryRun,
persisted: [],
replaced: [],
+ proxies: [],
failed: [],
notAttempted: [],
stopped: null,
@@ -386,21 +529,30 @@ export async function persistVideos({
`Persist videos: ${planned.length} item(s) — ${plan.toFetch.count} to fetch, ` +
`${plan.saved.count} already saved, ${plan.wrongHeight.count} saved above the ` +
`requested height${replace === "above-height" ? " (to replace)" : " (left alone)"}, ` +
+ (replace === "below-height"
+ ? `${plan.lowerHeight.count} saved below it (to replace, the saved copy kept as a proxy), ` +
+ `${plan.heightUnknown.count} saved and not compared (left alone), `
+ : "") +
`${plan.noUrl.count} with no source URL, ${plan.unknown.count} unknown.`,
);
for (const p of planned) {
if (p.bucket === "unknown") log(` ${label(p)}: unknown channel or video, skipping.`);
else if (p.bucket === "noUrl") log(` ${label(p)}: no resolvable source URL, skipping.`);
- else if (p.bucket === "wrongHeight" && replace === "above-height" && !p.url) {
+ else if (p.bucket === "lowerHeight") {
+ log(
+ ` ${label(p)}: saved at ${p.height}p (${p.heightFrom}), below the ${p.target}p ` +
+ `${p.quality} gives${p.url ? "" : " — no resolvable source URL to replace it from, skipping"}.`,
+ );
+ } else if (p.bucket === "heightUnknown") {
+ log(` ${label(p)}: saved, not compared — ${p.why}; left alone.`);
+ } else if (replaces(p.bucket, replace) && !p.url) {
log(` ${label(p)}: no resolvable source URL to replace it from, skipping.`);
}
}
if (dryRun) return result;
const work = planned.filter(
- (p) =>
- p.bucket === "toFetch" ||
- (p.bucket === "wrongHeight" && replace === "above-height" && p.url),
+ (p) => p.bucket === "toFetch" || (replaces(p.bucket, replace) && p.url),
);
let attempted = 0;
const stop = (why: PersistVideosStop, from: number) => {
@@ -480,9 +632,15 @@ export async function persistVideos({
stop("store-unavailable", i);
break;
}
- const replacing = p.bucket === "wrongHeight";
+ const upgrading = p.bucket === "lowerHeight";
log(
- ` ${label(p)}: ${replacing ? "replacing the saved container" : "fetching the source container"} (${quality})…`,
+ ` ${label(p)}: ${
+ upgrading
+ ? `upgrading the saved ${p.height}p container`
+ : p.bucket === "wrongHeight"
+ ? "replacing the saved container"
+ : "fetching the source container"
+ } (${quality})…`,
);
attempted += 1;
const videoDir = path.join(paths.channelsDir, p.slug, "data", p.id);
@@ -530,7 +688,25 @@ export async function persistVideos({
}
if (p.pointer) {
const kept = pointer.alternates?.find((a) => a.storedAt === p.pointer!.storedAt);
- if (kept) {
+ if (kept && upgrading) {
+ // THE PROXY: the lower copy is kept on purpose — but only when the
+ // download really is taller. One that is not (the source no longer
+ // offers more) leaves both flagged for a check, as any replace does.
+ const newHeight = pointer.format?.height ?? pointer.probed?.height;
+ if (newHeight !== undefined && newHeight > p.height!) {
+ await markSavedAlternate(videoDir, kept.file, "proxy");
+ result.proxies.push({ slug: p.slug, id: p.id, file: kept.file });
+ log(
+ ` ${label(p)}: now ${newHeight}p; the ${p.height}p copy stays beside it as ${kept.file}, ` +
+ `kept as its proxy.`,
+ );
+ } else {
+ log(
+ ` ${label(p)}: the download is ${newHeight !== undefined ? `${newHeight}p, not taller than ${p.height}p` : "of unknown height"}; ` +
+ `the old copy stays beside it as ${kept.file}, flagged for a check (not marked as a proxy).`,
+ );
+ }
+ } else if (kept) {
// The persist kept the old copy beside the new one and carried its
// provenance over itself (ytdlp/savedAlternates.ts).
log(` ${label(p)}: the replaced container stays beside it as ${kept.file}, flagged for a check.`);
@@ -549,7 +725,11 @@ export async function persistVideos({
log(
`Persist videos: ${result.persisted.length} persisted` +
- (result.replaced.length ? ` (${result.replaced.length} replaced)` : "") +
+ (result.replaced.length
+ ? ` (${result.replaced.length} replaced` +
+ (result.proxies.length ? `, ${result.proxies.length} old cop${result.proxies.length === 1 ? "y" : "ies"} kept as proxies` : "") +
+ ")"
+ : "") +
`, ${result.failed.length} failed, ${plan.saved.count} already saved` +
(result.notAttempted.length
? `, ${result.notAttempted.length} not attempted (stopped: ${result.stopped})`
diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts
@@ -20,6 +20,7 @@ import {
type SavedVideoFormat,
type SavedVideoKeepReason,
type SavedVideoAlternate,
+ type SavedAlternateKeptAs,
type SavedVideoOrigin,
type SavedVideoPointer,
} from "./savedVideo";
@@ -194,6 +195,35 @@ export async function restoreSavedVideoProvenance(
});
}
+// SAY WHY ONE ALTERNATE IS KEPT (`keptAs`, savedVideo.ts): persist-videos'
+// "below-height" marks the lower-quality copy a taller download replaced as
+// its proxy. Rewritten from the pointer's RAW JSON under its file lock, as
+// dropSavedAlternate does — every other key and entry stays as it was. Only the
+// pointer in the data dir is written; the store is not touched. False (nothing
+// written) when there is no pointer or it does not list `file`.
+export async function markSavedAlternate(
+ videoDir: string,
+ file: string,
+ keptAs: SavedAlternateKeptAs,
+): Promise<boolean> {
+ const pointerFile = savedVideoPointerPath(videoDir);
+ return withJsonFileLock(pointerFile, async () => {
+ const read = await readJsonFile(pointerFile);
+ if (!read.ok || !read.value || typeof read.value !== "object") return false;
+ const raw = { ...(read.value as Record<string, unknown>) };
+ if (!Array.isArray(raw.alternates)) return false;
+ let found = false;
+ raw.alternates = raw.alternates.map((a: unknown) => {
+ if (!a || typeof a !== "object" || (a as { file?: unknown }).file !== file) return a;
+ found = true;
+ return { ...(a as Record<string, unknown>), keptAs };
+ });
+ if (!found) return false;
+ await writeJsonAtomic(pointerFile, raw);
+ return true;
+ });
+}
+
// Best-effort removal of a now-empty store dir (and its empty <slug> parent).
async function pruneEmptyStoreDirs(storeDir: string): Promise<void> {
await rm(storeDir, { recursive: false, force: true }).catch(() => {});
diff --git a/common/lib/savedVideo.test.ts b/common/lib/savedVideo.test.ts
@@ -6,6 +6,7 @@ import path from "node:path";
import type { Paths } from "./paths";
import {
parseSavedVideoPointer,
+ savedAlternatesLine,
savedVideoDir,
savedVideoFormatFromLine,
savedVideoRoot,
@@ -109,6 +110,29 @@ test("format: an old pointer parses as before, a new one carries its format", ()
assert.equal(bad && "format" in bad, false);
});
+test("an alternate's keptAs: \"proxy\" parses and is said; an unknown one, or none, reads as before", () => {
+ const p = parseSavedVideoPointer({
+ storedAt: "2026-11-13T00:00:00.000Z",
+ dir: "/store/demo/v1",
+ file: "source-media.mp4",
+ bytes: 1,
+ format: { preset: "original", height: 1080 },
+ alternates: [
+ { file: "source-media.alt-360p-1.mp4", bytes: 1, storedAt: "", setAsideAt: "", height: 360, keptAs: "proxy" },
+ { file: "source-media.alt-720p-2.mp4", bytes: 1, storedAt: "", setAsideAt: "", height: 720, keptAs: "spare" },
+ { file: "source-media.alt-480p-3.mp4", bytes: 1, storedAt: "", setAsideAt: "", height: 480 },
+ ],
+ });
+ assert.deepEqual(p?.alternates?.map((a) => a.keptAs), ["proxy", undefined, undefined]);
+ assert.equal(
+ savedAlternatesLine(p!),
+ "4 saved copies: active 1080p, length unknown (download); " +
+ "alternate 360p, length unknown (download, source-media.alt-360p-1.mp4, kept on purpose as the lower-quality proxy); " +
+ "alternate 720p, length unknown (download, source-media.alt-720p-2.mp4); " +
+ "alternate 480p, length unknown (download, source-media.alt-480p-3.mp4)",
+ );
+});
+
test("savedVideoFormatFromLine reads the printed format line", () => {
assert.deepEqual(savedVideoFormatFromLine("720 avc1.4d401f 136+140", "video_720"), {
preset: "video_720",
diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts
@@ -90,6 +90,19 @@ export type SavedVideoAlternate = {
origin?: SavedVideoOrigin;
// A download's copy: the quality it asked for.
preset?: SourceVideoQuality;
+ // 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.
+ keptAs?: SavedAlternateKeptAs;
+};
+
+export const SAVED_ALTERNATE_KEPT_AS = ["proxy"] 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",
};
export type SavedVideoFormat = {
@@ -214,6 +227,10 @@ function parseAlternate(raw: unknown): SavedVideoAlternate | null {
const origin = parseOrigin(r.origin);
if (origin) out.origin = origin;
if (isSourceVideoQuality(r.preset)) out.preset = r.preset;
+ // An unknown value is dropped: the copy reads as one kept for a check.
+ if ((SAVED_ALTERNATE_KEPT_AS as readonly unknown[]).includes(r.keptAs)) {
+ out.keptAs = r.keptAs as SavedAlternateKeptAs;
+ }
return out;
}
@@ -232,7 +249,11 @@ export function savedAlternatesLine(pointer: SavedVideoPointer): string {
return (
`${alts.length + 1} saved copies: active ${active}); ` +
alts
- .map((a) => `alternate ${facts(a.height, a.seconds, a.origin?.requestedBy ?? "download")}, ${a.file})`)
+ .map(
+ (a) =>
+ `alternate ${facts(a.height, a.seconds, a.origin?.requestedBy ?? "download")}, ${a.file}` +
+ `${a.keptAs ? `, ${SAVED_ALTERNATE_KEPT_AS_LABELS[a.keptAs]}` : ""})`,
+ )
.join("; ")
);
}
diff --git a/common/lib/savedVideoDropAlternate.test.ts b/common/lib/savedVideoDropAlternate.test.ts
@@ -7,6 +7,7 @@ import type { Paths } from "./paths";
import {
dropSavedAlternate,
loadSavedVideo,
+ markSavedAlternate,
SavedAlternateRefusal,
savedVideoPointerPath,
} from "./savedVideo-server";
@@ -165,3 +166,36 @@ test("the store's relocation marker holds a drop; a dry run is held too", async
assert.deepEqual((await readdir(storeDir)).sort(), [ALT, ACTIVE].sort());
});
});
+
+// markSavedAlternate (persist-videos "below-height"): the replaced lower copy
+// is said to be kept on purpose as the proxy. One key on one entry; every
+// other byte of the pointer stays; the store is not touched.
+test("markSavedAlternate sets keptAs on the one listed entry and changes nothing else", async () => {
+ await withVideo([ALT, ALT2], async ({ videoDir, storeDir, pointer }) => {
+ assert.equal(await markSavedAlternate(videoDir, ALT2, "proxy"), true);
+ const expected = {
+ ...pointer,
+ alternates: (pointer.alternates as { file: string }[]).map((a) =>
+ a.file === ALT2 ? { ...a, keptAs: "proxy" } : a,
+ ),
+ };
+ assert.equal(await pointerText(videoDir), JSON.stringify(expected, null, 2) + "\n");
+ const loaded = await loadSavedVideo(videoDir);
+ assert.equal(loaded?.alternates?.find((a) => a.file === ALT2)?.keptAs, "proxy");
+ assert.equal(loaded?.alternates?.find((a) => a.file === ALT)?.keptAs, undefined);
+ assert.deepEqual((await readdir(storeDir)).sort(), [ALT, ALT2, ACTIVE].sort());
+ // A name the pointer does not list, or the active copy, writes nothing.
+ const before = await pointerText(videoDir);
+ assert.equal(await markSavedAlternate(videoDir, "source-media.alt-9p-1.mp4", "proxy"), false);
+ assert.equal(await markSavedAlternate(videoDir, ACTIVE, "proxy"), false);
+ assert.equal(await pointerText(videoDir), before);
+ });
+});
+
+test("markSavedAlternate with no pointer, or none listed, is false", async () => {
+ await withVideo([], async ({ videoDir }) => {
+ assert.equal(await markSavedAlternate(videoDir, ALT, "proxy"), false);
+ await rm(savedVideoPointerPath(videoDir));
+ assert.equal(await markSavedAlternate(videoDir, ALT, "proxy"), false);
+ });
+});