Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 58fba9279c82bf3e6095f66759c637cd1433b3a9
parent 98419195c833422a3aebffa8807b4941ea2ad604
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 16:42:02 -0500

Merge lane/persist-upgrade (first part): a saved video can be upgraded to a better copy -- persist-videos replace "below-height" re-fetches a saved copy that is lower than the requested quality gives (720, or the tallest format its metadata lists), makes the download the active copy and keeps the old one beside it, marked on purpose as the lower-quality proxy in the same pointer write; nothing is deleted, a pin stays a pin, a taller copy already kept as an alternate is named and not fetched again, and a copy already downloaded at that quality is left alone until its metadata is newer; never and above-height behave as before

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 8+++++---
MOPERATING.md | 12++++++++++++
Mcommon/controller/persistVideos.test.ts | 424+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/controller/persistVideos.ts | 267++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/controller/pruneSavedVideos.ts | 12+++++++++++-
Mcommon/lib/savedVideo.test.ts | 24++++++++++++++++++++++++
Mcommon/lib/savedVideo.ts | 23++++++++++++++++++++++-
Mcommon/ytdlp/downloadOneManaged.ts | 7+++++++
Mcommon/ytdlp/finalizeAppExtraction.ts | 4++++
Mcommon/ytdlp/savedAlternates.test.ts | 47++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/ytdlp/savedAlternates.ts | 21++++++++++++++++++++-
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/persist-videos/route.test.ts | 17+++++++++++++++--
Meditor/app/api/ops/persist-videos/route.ts | 8++++++--
Meditor/app/api/ops/saved-alternates/route.ts | 4+++-
Meditor/app/channels/[slug]/persistActions.ts | 1+
Meditor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx | 19+++++++++++++------
Meditor/app/saved-videos/components/PersistVideoListControl.tsx | 30+++++++++++++++++++++++-------
Meditor/app/saved-videos/persistListAction.ts | 4++--
Mscripts/archilyzer-ops.mjs | 34++++++++++++++++++++++------------
20 files changed, 903 insertions(+), 64 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -182,7 +182,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "&lt;id&gt;"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` | | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | | `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` | -| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`); nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` | +| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality; "below-height" one whose height (recorded, else ffprobed) is below what that quality gives -- its ceiling, capped by the tallest format the record's metadata lists -- and keeps the old copy as its proxy ("keptAs": "proxy" on the alternate, once the new copy is taller); one that cannot be compared, with a taller alternate already beside it, or already downloaded at that quality (unless its metadata is newer than the copy) is left alone (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, lowerHeight, heightUnknown, tallerAlternate, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`) or kept as the proxy; nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` | | `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. "archive" (items only) names the CONNECTED archive the items cite (settings.remoteArchives): a channel this editor does not hold is registered as a remote-only channel of it (config only, no listing; answered in "registered"; a dry run registers nothing), and a remote-only channel's page URL comes from the archive's record. Its window on a whole-recording platform is refused with the recording's estimated size unless "allowWholeRecording": true. Another origin registers nothing. A media URL's transient 403 (googlevideo's) is asked once more after a pause before it counts toward the two-403 stop. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (&lt;from&gt;-&lt;to&gt;.desynced.&lt;ext&gt;) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[&lt;version&gt;\] - &lt;date&gt;": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release &lt;workspace&gt; &lt;version&gt;") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | | `amend-release` | amend-release rewrites the LATEST release of one changelog: {"workspace": "editor" \| "export", "release": "&lt;its version, as you saw it&gt;", "version": "patch" \| "minor" \| "major" (a bump of the release BEFORE it) \| "X.Y.Z", "date": "YYYY-MM-DD", "fold": true (the \[Unreleased\] bullets move into it), "commit": boolean (default false)} -- or {"uncut": true} to withdraw it, its bullets back under \[Unreleased\]. An older release is refused. A version change commits as that version's release ("Release editor 0.12.0") with the amend in the body; history is never rewritten. The same amend again changes nothing. With no editor running, `archilyzer release amend` does the same locally. | `pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}'` | @@ -304,8 +304,10 @@ get saved-alternates [<slug>] lists every saved video holding two copies: explicit persist (persist-videos, Persist source video, a whole-recording fetch) makes the download active, any other keeps the saved one unless the download is longer — and the other stays beside it as - source-media.alt-<h>p-<stamp>.<ext>, flagged for a check. Each video: - its line, the active copy, the alternates (height, seconds, origin). + source-media.alt-<h>p-<stamp>.<ext>, flagged for a check -- or kept on + purpose ("keptAs": "proxy": the lower copy a persist-videos "below-height" + replaced). Each video: its line, the active copy, the alternates + (height, seconds, origin, keptAs). Once one is checked, `drop-saved-alternate` deletes it. get sites lists every site: id, title, siteUrl, Pages project, audience, listed, search, publish policy, channels, citedChannels. (`get publish` diff --git a/OPERATING.md b/OPERATING.md @@ -132,6 +132,18 @@ pnpm ops persist-videos --json '{"items":[{"slug":"example","id":"<videoId>"}] (`"operation"` pins one operation's tier). - Bucket names and sizes: `pnpm ops get channel example`. - Keep videos out of cleanup by title or description: `pnpm ops keep-videos --json '{"slug":"example","match":"interview","dryRun":true}'`. +- A saved copy lower than you want (a 360p import of a VOD the source has at 1080p): + `pnpm ops persist-videos --json '{"items":[{"slug":"example","id":"<videoId>"}],"format":"original","replace":"below-height","dryRun":true}'`. + It is in `lowerHeight` when its height (recorded, else read with ffprobe) is below what the quality gives. For + `original` that is the tallest format in its `metadata.info.json`. For `video_720` it is 720, or that tallest format + when it is lower (720 when the metadata lists none). `heightUnknown` means it could not be compared. + `tallerAlternate` means a copy at that height is already kept beside it; the plan names the file, and nothing makes + it active for you. Neither is fetched. Run it without `dryRun`. The download becomes the active copy, and the old + one stays beside it as its proxy (`"keptAs": "proxy"` in `get saved-alternates`). Nothing is deleted. +- A lower copy already downloaded at the asked quality is left alone (the plan says so, with its heights): that is + what the quality gave. If its `metadata.info.json` is newer than the copy (`refresh-metadata` since), it is + compared again. +- `"above-height"` is the other way: it re-fetches a saved copy taller than `video_720`, or of unknown height. - A new caption download writes its `transcript.cues.json` as it lands (a umtool build reads it); `build-cues` mends an older one. diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; @@ -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,44 +120,60 @@ 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 } : {}), + }, + } + : {}), }); } type Harness = { deps: Partial<PersistVideosDeps>; downloads: { slug: string; id: string; quality: string }[]; + // The ids whose download asked for the old copy to be kept as the proxy. + proxyAsked: string[]; sleeps: number[]; events: string[]; }; // The default harness: every channel exists, the gate is open, memory is // plentiful, and a download persists a 720p container named `file`. +// `oldHeights` is what finalizeAppExtraction's ffprobe reads of the copy +// already in the store (a landed one records no height of its own). function harness( paths: Paths, - over: Partial<PersistVideosDeps> & { file?: string; height?: number } = {}, + over: Partial<PersistVideosDeps> & { file?: string; height?: number; oldHeights?: Record<string, number> } = {}, ): Harness { const downloads: Harness["downloads"] = []; + const proxyAsked: string[] = []; const sleeps: number[] = []; const events: string[] = []; const download: PersistVideoDownload = async (o) => { const id = o.videoUrl.split("v=")[1]; downloads.push({ slug: o.channelSlug, id, quality: o.quality }); + if (o.oldCopyAsProxy) proxyAsked.push(id); events.push(`download ${id}`); const dir = videoDir(paths, o.channelSlug, id); const file = over.file ?? "source-media.mp4"; @@ -155,7 +191,14 @@ function harness( format: { preset: o.quality, height: over.height ?? 720 }, sourceFilename: file, explicitPersist: PERSIST_VIDEOS_DOWNLOAD.explicitPersist, - alternatesDeps: { measure: async () => null, height: async () => null }, + oldCopyAsProxy: o.oldCopyAsProxy, + alternatesDeps: { + measure: async () => null, + height: async (f) => { + const m = /^old (.+)$/.exec(await readFile(f, "utf8").catch(() => "")); + return (m && over.oldHeights?.[m[1]]) ?? null; + }, + }, onLog: () => {}, signal: o.signal, }); @@ -169,6 +212,7 @@ function harness( }; return { downloads, + proxyAsked, sleeps, events, deps: { @@ -182,6 +226,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 +611,361 @@ 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, its metadata no newer than the copy: + // what "original" gave, even though lower (a re-run must converge). + await seedSaved(paths, S, "same111", { preset: "original", height: 480, formatHeights: tall }); + // The same, but its metadata was refreshed AFTER the copy was stored: the + // source may have more now, so it is compared by height as usual. + await seedSaved(paths, S, "fresh11", { preset: "original", height: 480, formatHeights: tall }); + const later = new Date(Date.now() + 60_000); + await utimes(path.join(videoDir(paths, S, "fresh11"), "metadata.info.json"), later, later); + // 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", "fresh11", "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", "fresh11"]); + 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.tallerAlternate.count, 0); + assert.equal(res.plan.willFetch, 3); + // Only a pointer with no recorded height is probed. + assert.deepEqual(calls.sort(), ["equal11", "lower11", "nofmt11", "noprob1"]); + const text = lines.join(""); + assert.match(text, /3 saved below it \(to replace, the saved copy kept as a proxy\), 2 saved and not compared/); + // The same-preset rule says every copy it leaves alone, with its heights. + assert.match( + text, + /demo-channel\/same111: saved at 480p \(recorded\), below the 1080p its metadata lists, but it was downloaded at original and the metadata is not newer than the copy — left alone/, + ); + assert.doesNotMatch(text, /fresh11: saved at 480p \(recorded\), below the 1080p its metadata lists/); + assert.match(text, /demo-channel\/fresh11: saved at 480p \(recorded\), below the 1080p original gives\./); + 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, 7, 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 }), + oldHeights: { kickvod: 360 }, + }); + const lines: string[] = []; + const res = await persistVideos({ + paths, + items, + format: "original", + replace: "below-height", + onLog: (l) => lines.push(l), + deps: h.deps, + }); + // Only an upgrade asks the persist to keep the old copy as the proxy. + assert.deepEqual(h.proxyAsked, ["kickvod", "dl72011"]); + 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\)/); + assert.match(text, /kickvod: now 1080p; the 360p copy stays beside it as source-media\.alt-360p-\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 }), oldHeights: { 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 measured 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); + }); +}); + +test("below-height does not fetch what is already here as a taller alternate, and does not make it active", async () => { + await withPaths(async (paths) => { + const S = "demo-channel"; + await seedSaved(paths, S, "hasalt1", { + preset: null, + requestedBy: "import-media", + formatHeights: [360, 1080], + }); + // A 1080p copy kept beside it earlier (an automatic download that was not + // longer), and a shorter 480p one. + const dir = videoDir(paths, S, "hasalt1"); + const pointerFile = path.join(dir, "saved-video.json"); + const raw = JSON.parse(await readFile(pointerFile, "utf8")); + raw.alternates = [ + { file: "source-media.alt-480p-20261101000000.mp4", bytes: 1, storedAt: "", setAsideAt: "", height: 480 }, + { file: "source-media.alt-1080p-20261102000000.mp4", bytes: 1, storedAt: "", setAsideAt: "", height: 1080 }, + ]; + await writeFile(pointerFile, JSON.stringify(raw)); + const before = await readFile(pointerFile, "utf8"); + const h = harness(paths, { probeHeight: probeBy({ hasalt1: 360 }) }); + const lines: string[] = []; + const res = await persistVideos({ + paths, + items: [{ slug: S, id: "hasalt1" }], + format: "original", + replace: "below-height", + onLog: (l) => lines.push(l), + deps: h.deps, + }); + assert.equal(h.downloads.length, 0); + assert.deepEqual(res.plan.tallerAlternate.items, [{ slug: S, id: "hasalt1" }]); + assert.equal(res.plan.lowerHeight.count, 0); + assert.equal(res.plan.willFetch, 0); + assert.deepEqual(res.replaced, []); + assert.match( + lines.join(""), + /demo-channel\/hasalt1: saved at 360p \(probed\), below the 1080p original gives, but a 1080p copy is already here as the alternate source-media\.alt-1080p-20261102000000\.mp4 \(not the active one\) — not fetched/, + ); + assert.match(lines.join(""), /1 with a taller alternate already here \(left alone\)/); + // Nothing is promoted: the pointer is byte for byte what it was. + assert.equal(await readFile(pointerFile, "utf8"), before); + + // An alternate below the target does not hold the upgrade back. + raw.alternates = raw.alternates.slice(0, 1); + await writeFile(pointerFile, JSON.stringify(raw)); + const dry = await persistVideos({ + paths, + items: [{ slug: S, id: "hasalt1" }], + format: "original", + replace: "below-height", + dryRun: true, + deps: h.deps, + }); + assert.equal(dry.plan.lowerHeight.count, 1); + assert.equal(dry.plan.willFetch, 1); + }); +}); diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts @@ -8,11 +8,12 @@ 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, restoreSavedVideoProvenance, } from "../lib/savedVideo-server"; +import { probeVideoHeight } from "../ytdlp/ffprobeDuration"; import { readChannelConfig } from "./channels"; import { findVideoSourceUrl } from "./undownloadedVideos"; import { @@ -62,10 +63,30 @@ 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. Not fetched either +// (`tallerAlternate`): an alternate at or above the target is already in the +// store — it is named in the plan and NOT made active (a person's call). A +// lower copy a download already made at the requested quality is what that +// quality gave, and is left alone (a re-fetch would bring the same file back +// on every re-run) — unless the record's metadata.info.json was written after +// the copy was stored: a refresh since may list formats the source did not +// have then. Each such skip is said in the plan, with its heights. The replace +// is above-height's, asked with `oldCopyAsProxy`: persistOverExisting marks the +// old copy's alternate entry `keptAs: "proxy"` — kept on purpose, not for a +// check — in the same pointer write, when the download 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 +102,28 @@ 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 +// tallerAlternate in the store below what the quality gives, but an +// alternate copy at or above it is already there (sorted only +// under "below-height"); never fetched, never made active // 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; + tallerAlternate: 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 +144,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[]; @@ -127,6 +162,9 @@ export type PersistVideoDownload = (opts: { settings: SiteSettings; videoUrl: string; quality: SourceVideoQuality; + // "below-height": over the saved copy, keep it as the proxy when the + // download is taller (ManagedDownloadOpts.oldCopyAsProxy). + oldCopyAsProxy: boolean; onLog: (line: string) => void; signal: AbortSignal; }) => Promise<DownloadOutcomeRecord>; @@ -145,6 +183,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. @@ -174,6 +215,7 @@ const defaultDownload: PersistVideoDownload = (o) => globalSkipLiveDownloads: o.settings.skipLiveDownloads, ...PERSIST_VIDEOS_DOWNLOAD, persistFormatPreset: o.quality, + ...(o.oldCopyAsProxy ? { oldCopyAsProxy: true } : {}), }); function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { @@ -210,6 +252,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 +282,127 @@ 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; +} + +// The record's metadata: the tallest video format it lists, and when the file +// was last written (null: no readable metadata.info.json). +async function readRecordFormats( + videoDir: string, +): Promise<{ tallest: number | null; mtimeMs: number | null }> { + const file = path.join(videoDir, "metadata.info.json"); + try { + const [raw, st] = await Promise.all([readFile(file, "utf8"), stat(file)]); + return { tallest: tallestFormatHeight(JSON.parse(raw)), mtimeMs: st.mtimeMs }; + } catch { + return { tallest: null, mtimeMs: 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; + // A lower copy left `saved` by the same-preset rule: the plan says so. + samePreset?: boolean; + // tallerAlternate: the alternate already here at or above the target. + alternate?: { file: string; height: number }; }; +// "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" | "samePreset" | "alternate"> +> { + 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 }; + const meta = await readRecordFormats(videoDir); + const target = + ceiling === null ? meta.tallest : meta.tallest === null ? ceiling : Math.min(ceiling, meta.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", + }; + } + if (height >= target) return { bucket: "saved", ...at, target }; + // A TALLER COPY IS ALREADY HERE, as an alternate: not fetched again, and not + // made active either — that is a person's call. + const taller = (pointer.alternates ?? []) + .filter((a) => a.height !== undefined && a.height >= target) + .sort((a, b) => b.height! - a.height!)[0]; + if (taller) { + return { bucket: "tallerAlternate", ...at, target, alternate: { file: taller.file, height: taller.height! } }; + } + // ALREADY WHAT THIS QUALITY GAVE: a download at the requested preset brought + // this height, so a re-fetch would bring it back on every re-run — unless + // the record's metadata was written after the copy was stored (a refresh + // since may list formats the source did not have then). + const storedAtMs = Date.parse(pointer.storedAt); + if ( + pointer.format?.preset === quality && + // storedAt is to the millisecond; an mtime in that same millisecond is not newer. + !(meta.mtimeMs !== null && Number.isFinite(storedAtMs) && Math.floor(meta.mtimeMs) > storedAtMs) + ) { + return { bucket: "saved", ...at, target, samePreset: true }; + } + return { bucket: "lowerHeight", ...at, target }; +} + function emptyBucket(): PersistVideosBucket { return { count: 0, items: [] }; } @@ -256,6 +412,7 @@ async function classify( paths: Paths, items: PersistVideoItem[], format: SourceVideoQuality | undefined, + replace: PersistReplacePolicy, settings: SiteSettings, deps: PersistVideosDeps, ): Promise<PlannedItem[]> { @@ -288,6 +445,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 +482,9 @@ function planOf( const plan: PersistVideosPlan = { saved: emptyBucket(), wrongHeight: emptyBucket(), + lowerHeight: emptyBucket(), + heightUnknown: emptyBucket(), + tallerAlternate: emptyBucket(), toFetch: emptyBucket(), noUrl: emptyBucket(), unknown: emptyBucket(), @@ -323,11 +494,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 +557,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 +573,43 @@ 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.tallerAlternate.count} with a taller alternate already here (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 (p.bucket === "tallerAlternate") { + log( + ` ${label(p)}: saved at ${p.height}p (${p.heightFrom}), below the ${p.target}p ${p.quality} gives, ` + + `but a ${p.alternate!.height}p copy is already here as the alternate ${p.alternate!.file} ` + + `(not the active one) — not fetched; making it active is a person's call.`, + ); + } else if (p.samePreset) { + log( + ` ${label(p)}: saved at ${p.height}p (${p.heightFrom}), below the ${p.target}p its metadata lists, ` + + `but it was downloaded at ${p.quality} and the metadata is not newer than the copy — left alone ` + + `(refresh its metadata to compare again).`, + ); + } 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 +689,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); @@ -495,6 +710,7 @@ export async function persistVideos({ settings, videoUrl: p.url!, quality, + oldCopyAsProxy: upgrading, onLog: downloadLog, signal: downloadSignal, }); @@ -530,7 +746,24 @@ 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: persistOverExisting marked the lower copy in the same + // pointer write, only when the download was measured taller. One that + // is not (the source no longer offers more) stays flagged for a check. + const newHeight = pointer.format?.height ?? pointer.probed?.height; + if (kept.keptAs === "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 measured 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 +782,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/controller/pruneSavedVideos.ts b/common/controller/pruneSavedVideos.ts @@ -65,10 +65,20 @@ export async function pruneSavedVideos({ if (await isDoNotClean(videoDir)) continue; // pinned -> keep forever // Two copies kept for a check (ytdlp/savedAlternates.ts): the prune never // removes a flagged alternate, so it leaves the whole video for the check. + // A proxy (`keptAs`) is held the same way; the line names it as one. 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 + ? ` (${[ + `${proxies} kept on purpose as the lower-quality proxy`, + ...(flagged ? [`${flagged} flagged for a check`] : []), + ].join(" and ")})` + : " flagged for a check"; log( `Kept saved video ${id} although it rolled out of the keep-latest window: ` + - `it holds ${pointer.alternates.length} alternate cop${pointer.alternates.length === 1 ? "y" : "ies"} flagged for a check.`, + `it holds ${n} alternate cop${n === 1 ? "y" : "ies"}${what}.`, ); continue; } 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/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -222,6 +222,10 @@ export type ManagedDownloadOpts = { // either way. Set by "Persist source video", persist-videos and the // whole-recording fetch; never by an automatic download. explicitPersist?: boolean; + // With explicitPersist, over a copy already in the store: mark the old copy + // `keptAs: "proxy"` when the download is taller (ytdlp/savedAlternates.ts). + // Set by persist-videos' "below-height" only. + oldCopyAsProxy?: boolean; // Per-run override of channelConfig.audioFormat for the extracted audio. audioFormatOverride?: AudioFormat; // Resolved yt-dlp `-f` download-format preset (override > channel > global), @@ -1666,6 +1670,7 @@ async function runManagedDownload( origin: opts.persistOrigin, format: persistedFormat(), explicitPersist: opts.explicitPersist, + oldCopyAsProxy: opts.oldCopyAsProxy, onLog: opts.onLog, signal: opts.signal, }); @@ -1805,6 +1810,7 @@ async function runManagedDownload( origin: opts.persistOrigin, format: persistedFormat(), explicitPersist: opts.explicitPersist, + oldCopyAsProxy: opts.oldCopyAsProxy, extractAudio: false, onLog: opts.onLog, signal: opts.signal, @@ -1827,6 +1833,7 @@ async function runManagedDownload( origin: opts.persistOrigin, format: persistedFormat(), explicitPersist: opts.explicitPersist, + oldCopyAsProxy: opts.oldCopyAsProxy, onLog: opts.onLog, signal: opts.signal, }); diff --git a/common/ytdlp/finalizeAppExtraction.ts b/common/ytdlp/finalizeAppExtraction.ts @@ -62,6 +62,9 @@ export async function finalizeAppExtraction(opts: { // A PERSON ASKED FOR THIS CONTAINER (ManagedDownloadOpts.explicitPersist): // over a copy already in the store, the download becomes the active one. explicitPersist?: boolean; + // Over a copy already in the store, keep the old one as the proxy when the + // download is taller (ManagedDownloadOpts.oldCopyAsProxy). + oldCopyAsProxy?: boolean; // Test seam: how the two copies are measured. Production passes none. alternatesDeps?: SavedAlternatesDeps; onLog: (s: string) => void; @@ -158,6 +161,7 @@ export async function finalizeAppExtraction(opts: { keepReason, origin: opts.origin, format: opts.format, + ...(opts.oldCopyAsProxy ? { oldCopyAsProxy: true } : {}), paths: opts.paths, deps: alternatesDeps, onLog: opts.onLog, diff --git a/common/ytdlp/savedAlternates.test.ts b/common/ytdlp/savedAlternates.test.ts @@ -116,7 +116,7 @@ async function seed( async function download( paths: Paths, dir: string, - opts: { explicit: boolean; seconds?: number; height?: number }, + opts: { explicit: boolean; seconds?: number; height?: number; oldCopyAsProxy?: boolean }, ): Promise<string> { await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("new", opts.seconds ?? 4696.479777, opts.height ?? 720)); const log: string[] = []; @@ -132,6 +132,7 @@ async function download( extractAudio: false, format: { preset: "video_720", height: opts.height ?? 720, vcodec: "avc1" }, explicitPersist: opts.explicit, + ...(opts.oldCopyAsProxy ? { oldCopyAsProxy: true } : {}), alternatesDeps: deps, onLog: (s) => void log.push(s), signal: new AbortController().signal, @@ -296,6 +297,22 @@ test("the inventory counts and lists alternates; the prune never removes one; dr }); }); +test("the prune keeps a video holding a proxy and names it as one (wording only)", async () => { + await withCorpus(async (paths) => { + const dir = await seed(paths, "vproxyp", { keepReason: "keep-latest" }); + await download(paths, dir, { explicit: true, height: 1080, oldCopyAsProxy: true }); + await writeFile(path.join(paths.channelsDir, SLUG, "config.json"), JSON.stringify(CONFIG)); + const lines: string[] = []; + const r = await pruneSavedVideos({ paths, channelSlug: SLUG, onLog: (l) => void lines.push(l) }); + assert.equal(r.pruned, 0); + assert.match( + lines.join("\n"), + /Kept saved video vproxyp .*: it holds 1 alternate copy \(1 kept on purpose as the lower-quality proxy\)\./, + ); + assert.doesNotMatch(lines.join("\n"), /flagged for a check/); + }); +}); + test("a persist that fails after the rename puts the old name back", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vfail", { landed: true }); @@ -311,6 +328,34 @@ test("a persist that fails after the rename puts the old name back", async () => }); }); +// persist-videos "below-height": the old copy is marked the proxy in the SAME +// pointer write that lists it — never by a second write that a crash or a +// throw could leave undone. +test("oldCopyAsProxy: a taller download marks the old copy keptAs proxy in the one pointer write; not taller, no mark", async () => { + await withCorpus(async (paths) => { + const dir = await seed(paths, "vprox01", { landed: true }); + const log = await download(paths, dir, { explicit: true, height: 1080, oldCopyAsProxy: true }); + assert.match(log, /stays as source-media\.alt-360p-20261023172312\.mp4\. Kept on purpose as the lower-quality proxy\.\n/); + const p = (await loadSavedVideo(dir))!; + assert.equal(p.alternates?.length, 1); + assert.equal(p.alternates![0]!.keptAs, "proxy"); + assert.equal(p.alternates![0]!.height, 360); + assert.equal(p.keepReason, "pin"); + + // The download is not taller: both kept, no mark, flagged for a check. + const dir2 = await seed(paths, "vprox02", { height: 720, requestedBy: "umtool" }); + const log2 = await download(paths, dir2, { explicit: true, height: 720, oldCopyAsProxy: true }); + assert.match(log2, /Not marked as a proxy \(the download is not measured taller\); flagged for a check\.\n/); + const p2 = (await loadSavedVideo(dir2))!; + assert.equal(p2.alternates?.[0]?.keptAs, undefined); + + // Without the option (any other explicit persist): never a proxy. + const dir3 = await seed(paths, "vprox03", { landed: true }); + await download(paths, dir3, { explicit: true, height: 1080 }); + assert.equal((await loadSavedVideo(dir3))!.alternates?.[0]?.keptAs, undefined); + }); +}); + test("alternate names: height when known, a numbered suffix on a clash", () => { assert.equal(alternateName("source-media.webm", null, NOW), "source-media.alt-20261023172312.webm"); assert.equal( diff --git a/common/ytdlp/savedAlternates.ts b/common/ytdlp/savedAlternates.ts @@ -26,6 +26,12 @@ // do-not-clean marker is not touched. Its `origin` is the // download's requester, else the old one's — never a // landed copy's, which now describes the alternate. +// a PROXY `oldCopyAsProxy` (persist-videos "below-height" only): +// when the download is measured TALLER than the copy it +// replaces, the old copy's entry carries `keptAs: "proxy"` +// — kept on purpose, not for a check — in the same pointer +// write as the rest. Not taller, or either height unknown: +// no mark, flagged for a check as any other. // // DROPPING ONE after the check (2026-10-29): `dropSavedAlternate` // (lib/savedVideo-server.ts) — `pnpm ops drop-saved-alternate`, or the video @@ -220,6 +226,8 @@ export async function persistOverExisting( keepReason?: SavedVideoKeepReason; origin?: SavedVideoOrigin; format?: SavedVideoFormat | null; + // Mark the old copy as the proxy when the download is taller (see top). + oldCopyAsProxy?: boolean; paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">; deps: SavedAlternatesDeps; onLog: (s: string) => void; @@ -250,6 +258,11 @@ export async function persistOverExisting( throw err; } const probed = probeOf(plan.newSeconds, plan.newHeight); + const proxy = + opts.oldCopyAsProxy === true && + plan.newHeight !== null && + plan.oldHeight !== null && + plan.newHeight > plan.oldHeight; pointer = { ...pointer, ...(probed ? { probed } : {}), @@ -265,6 +278,7 @@ export async function persistOverExisting( ...(old.format?.vcodec ? { vcodec: old.format.vcodec } : {}), ...(old.origin ? { origin: old.origin } : {}), ...(old.format?.preset ? { preset: old.format.preset } : {}), + ...(proxy ? { keptAs: "proxy" as const } : {}), }, ], }; @@ -273,7 +287,12 @@ export async function persistOverExisting( const why = plan.explicit ? "" : " (it is longer)"; opts.onLog( `Kept both copies: the download (${describe(plan.newHeight, plan.newSeconds)}) is now the active source${why}; ` + - `the ${which} one (${describe(plan.oldHeight, plan.oldSeconds)}) stays as ${alt}. Flagged for a check.\n`, + `the ${which} one (${describe(plan.oldHeight, plan.oldSeconds)}) stays as ${alt}. ` + + (proxy + ? "Kept on purpose as the lower-quality proxy.\n" + : opts.oldCopyAsProxy + ? "Not marked as a proxy (the download is not measured taller); flagged for a check.\n" + : "Flagged for a check.\n"), ); await flag(plan, alt, at); return pointer; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **`persist-videos` can upgrade a saved copy that is lower than asked, and keeps the old one as its proxy.** `"replace": "below-height"` re-fetches a saved video whose height is below what the quality gives: the tallest format its metadata lists for `original`; for `video_720`, 720 or that tallest format, whichever is lower. A copy with no recorded height (an import or an attach) is measured with ffprobe first. The download becomes the active copy; the old one stays beside it, marked `"keptAs": "proxy"` once the new one is taller, and the video page, /saved-videos and `get saved-alternates` say it is the lower-quality copy kept on purpose. The dry run's new buckets are `lowerHeight`, `heightUnknown` (not compared: the height could not be read, or `original` with no format heights in the metadata) and `tallerAlternate` (a copy at that height is already kept beside it; it is named, not fetched and not made active). A copy already downloaded at that quality is left alone, and the plan says so, unless its metadata is newer than the copy. "Save these videos" has a select for it in place of the checkbox. `"never"` stays the default, and `"above-height"` works as before. - **umtool: a picture-only post's read can become its screen, and a screen line can be read in your own voice.** `umtool posts screen <p> <item> add --from-read` (the post bench's "From its read") turns the script of a picture-only post into a screen: one line per line of the script, not checked, and with no speaker split out of a line. That screen *is* the post's read, so the thread read no longer reads the same words twice. `posts screen … record <id> <n> --recording <file>` (the bench's per-line Record / Stop / Keep) records one line as the read says it, with masked numbers and redacted words left out of what you read. It is kept as new takes: recorded, cleaned, and converted to the line's speaker's character's stock voice. None of them is picked. A line take is read only when you choose it, with the bench's per-line select or `set <id> take.<n>=<take>`. A choice follows its line when lines move, and is refused when the line's words or speaker changed. `--check-words` (CLI only) transcribes the recording first and refuses it if it says a number, a handle, an anonymous author's name or a redacted term. The lint flags every chosen take that was not heard this way. - **umtool: no preview plays a read the build refuses.** After a screen line is edited, removed, redacted or no longer read, the build refuses the old read. Play, Present (including the public payload), the card page and the post bench's player now refuse it too: they play the item silent and say why, until the read is made again. Present's public payload carries a post's screens the way the card draws them (masked, blurred speakers nameless), never the raw lines. - **umtool: no part of a read may say what the item's screens mask.** A build refuses a read in which any part says a number or e-mail one of the item's screens masks, or the words of a redacted line. That covers the post's own words, a context post and a screen line. Two recordings kept at the same moment never take the same file: a recorded take's name is now claimed with an exclusive create. diff --git a/editor/app/api/ops/persist-videos/route.test.ts b/editor/app/api/ops/persist-videos/route.test.ts @@ -21,7 +21,10 @@ const items = [ ]; type Bucket = { count: number; items: { slug: string; id: string }[] }; -type Plan = Record<"saved" | "wrongHeight" | "toFetch" | "noUrl" | "unknown", Bucket> & { +type Plan = Record< + "saved" | "wrongHeight" | "lowerHeight" | "heightUnknown" | "tallerAlternate" | "toFetch" | "noUrl" | "unknown", + Bucket +> & { willFetch: number; }; @@ -35,6 +38,16 @@ test("persist-videos buckets a list in a dry run, and refuses a bad body and a l assert.equal(plan.saved.count, 0); assert.equal(plan.willFetch, 1); + // "below-height" is accepted and answers its two buckets; nothing here is + // saved, so they are empty. + const upgrade = await callPost(POST, { items, format: "original", replace: "below-height", dryRun: true }); + assert.equal(upgrade.status, 200, JSON.stringify(upgrade.body)); + const upPlan = upgrade.body.plan as Plan; + assert.deepEqual(upPlan.lowerHeight, { count: 0, items: [] }); + assert.deepEqual(upPlan.heightUnknown, { count: 0, items: [] }); + assert.deepEqual(upPlan.tallerAlternate, { count: 0, items: [] }); + assert.equal(upPlan.willFetch, 1); + // Nothing to fetch is an answer, not a job. const none = await callPost(POST, { items: [{ slug: "no-such-channel", id: "abc123" }] }); assert.equal(none.status, 200, JSON.stringify(none.body)); @@ -47,7 +60,7 @@ test("persist-videos buckets a list in a dry run, and refuses a bad body and a l [{ items: [{ slug, id: video, height: 720 }] }, /unknown key\(s\): height/], [{ items: [{ slug, id: "../escape" }] }, /is not a video id/], [{ items, format: "1080p" }, /"format" must be one of original, video_720/], - [{ items, replace: "always" }, /"replace" must be one of never, above-height/], + [{ items, replace: "always" }, /"replace" must be one of never, above-height, below-height/], [{ items, gapMs: -1 }, /"gapMs" must be a whole number, zero or above/], [{ items, minFreeMemMb: "4096" }, /"minFreeMemMb" must be a whole number/], [{ items, dryRun: "yes" }, /"dryRun" must be a boolean/], diff --git a/editor/app/api/ops/persist-videos/route.ts b/editor/app/api/ops/persist-videos/route.ts @@ -22,13 +22,17 @@ export const dynamic = "force-dynamic"; // // Persist specific videos, across channels, to the saved-video store: the // video page's "Persist source video" over a list. `plan` buckets every item — -// saved, wrongHeight, toFetch, noUrl, unknown — with counts and ids, and +// saved, wrongHeight, lowerHeight, heightUnknown, tallerAlternate, toFetch, +// noUrl, unknown — +// with counts and ids, and // `willFetch` is how many downloads a run makes. A real run starts one job per // channel with something to fetch, on that channel's download queue. // // `format` ("original" | "video_720") defaults to each channel's own quality. // `replace: "above-height"` also re-fetches a saved container whose height is -// unknown or above that quality's ceiling (default "never"). `gapMs` is the +// unknown or above that quality's ceiling; `replace: "below-height"` one whose +// height (recorded, else probed) is below what that quality gives, keeping the +// old copy beside it as its proxy (default "never"). `gapMs` is the // pause between downloads (default the batch downloads' gap), `minFreeMemMb` // holds each download until that much memory is available (default 0, off). // Re-running the same body is the resume: saved videos are skipped. diff --git a/editor/app/api/ops/saved-alternates/route.ts b/editor/app/api/ops/saved-alternates/route.ts @@ -14,7 +14,9 @@ export const dynamic = "force-dynamic"; // // Every saved video that holds two copies (ytdlp/savedAlternates.ts): a // download over a container already in the store keeps both, one active and -// the other flagged here for a check. The /saved-videos page lists the same. +// the other flagged here for a check — or, with `keptAs: "proxy"`, kept on +// purpose: the lower-quality copy persist-videos' "below-height" replaced. +// The /saved-videos page lists the same. // Pointers only — no container is opened. Nothing is written. export async function GET(request: Request) { return readRoute(request, ["slug"], async (q) => { diff --git a/editor/app/channels/[slug]/persistActions.ts b/editor/app/channels/[slug]/persistActions.ts @@ -188,6 +188,7 @@ export async function persistVideosAction( [ ...plan.toFetch.items, ...(opts.replace === "above-height" ? plan.wrongHeight.items : []), + ...(opts.replace === "below-height" ? plan.lowerHeight.items : []), ].map((i) => i.slug), ); const bySlug = new Map<string, string[]>(); diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx @@ -3,9 +3,10 @@ import { useState, useTransition } from "react"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import type { ChannelHandling } from "yt-dlp-transcript-common/lib/channelConfig"; -import type { - SavedVideoAlternate, - SavedVideoPointer, +import { + SAVED_ALTERNATE_KEPT_AS_LABELS, + type SavedVideoAlternate, + type SavedVideoPointer, } from "yt-dlp-transcript-common/lib/savedVideo"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { @@ -221,8 +222,9 @@ function PersistedSourceVideo({ > <p className="text-muted-foreground"> Other copies kept beside the active one (a download over a copy - already in the store keeps both), flagged for a check. Drop one - once it has been checked; the active copy is not touched. + already in the store keeps both), flagged for a check unless kept + on purpose as a proxy. Drop one once it has been checked; the + active copy is not touched. </p> <ul className="flex flex-col gap-2"> {savedVideo.alternates!.map((a) => ( @@ -290,6 +292,7 @@ function SavedAlternateRow({ alternate.vcodec, formatBytes(alternate.bytes), alternate.origin?.requestedBy ?? "download", + alternate.keptAs ? SAVED_ALTERNATE_KEPT_AS_LABELS[alternate.keptAs] : undefined, ] .filter(Boolean) .join(", "); @@ -305,7 +308,11 @@ function SavedAlternateRow({ <span className="flex flex-wrap items-center gap-2"> {armed ? ( <> - <span>Delete this copy from the store? No undo.</span> + <span> + {alternate.keptAs === "proxy" + ? "This is the lower-quality copy kept on purpose as a proxy. Delete it from the store? No undo." + : "Delete this copy from the store? No undo."} + </span> <button type="button" disabled={pending} diff --git a/editor/app/saved-videos/components/PersistVideoListControl.tsx b/editor/app/saved-videos/components/PersistVideoListControl.tsx @@ -5,6 +5,7 @@ import { useState, useTransition } from "react"; import { Button } from "yt-dlp-transcript-common/components/ui/button"; import { SOURCE_VIDEO_QUALITY_LABELS } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import type { PersistVideosActionResult } from "../../channels/[slug]/persistActions"; +import type { PersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos"; import { persistVideoListAction } from "../persistListAction"; // "Save these videos" (release 32 R6): `pnpm ops persist-videos` from the UI — @@ -14,12 +15,12 @@ import { persistVideoListAction } from "../persistListAction"; type Format = "" | "original" | "video_720"; -const sameKey = (text: string, format: Format, replace: boolean) => JSON.stringify([text.trim(), format, replace]); +const sameKey = (text: string, format: Format, replace: PersistReplacePolicy) => JSON.stringify([text.trim(), format, replace]); export function PersistVideoListControl() { const [text, setText] = useState(""); const [format, setFormat] = useState<Format>(""); - const [replace, setReplace] = useState(false); + const [replace, setReplace] = useState<PersistReplacePolicy>("never"); const [previewed, setPreviewed] = useState<string | null>(null); const [result, setResult] = useState<PersistVideosActionResult | null>(null); const [pending, start] = useTransition(); @@ -29,7 +30,7 @@ export function PersistVideoListControl() { const r = await persistVideoListAction({ text, ...(format ? { format } : {}), - ...(replace ? { replace: "above-height" as const } : {}), + ...(replace !== "never" ? { replace } : {}), dryRun, }); setResult(r); @@ -65,8 +66,17 @@ export function PersistVideoListControl() { </select> </label> <label className="flex items-center gap-2"> - <input type="checkbox" checked={replace} onChange={(e) => setReplace(e.target.checked)} /> - Also replace a saved one taller than that quality, or of unknown height + <span className="text-muted-foreground">One already saved</span> + <select + value={replace} + onChange={(e) => setReplace(e.target.value as PersistReplacePolicy)} + aria-label="replace saved copies" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="never">leave it</option> + <option value="above-height">replace it if taller than that quality, or of unknown height</option> + <option value="below-height">upgrade it if lower than that quality gives; keep the old one as a proxy</option> + </select> </label> </div> <div className="flex flex-wrap items-center gap-2"> @@ -83,10 +93,16 @@ export function PersistVideoListControl() { ); } -const BUCKETS: { key: "saved" | "toFetch" | "wrongHeight" | "noUrl" | "unknown"; words: string }[] = [ +const BUCKETS: { + key: "saved" | "toFetch" | "wrongHeight" | "lowerHeight" | "heightUnknown" | "tallerAlternate" | "noUrl" | "unknown"; + words: string; +}[] = [ { key: "toFetch", words: "to download" }, { key: "saved", words: "already saved" }, { key: "wrongHeight", words: "saved, but taller than asked or of unknown height" }, + { key: "lowerHeight", words: "saved, but lower than that quality gives" }, + { key: "heightUnknown", words: "saved, not compared (height, or the source's best, not known)" }, + { key: "tallerAlternate", words: "saved lower, but a taller copy is already kept beside it (not active; not fetched)" }, { key: "noUrl", words: "with no source address to download from" }, { key: "unknown", words: "not found (no such channel or video)" }, ]; @@ -107,7 +123,7 @@ function PersistOutcome({ result }: { result: PersistVideosActionResult }) { {plan.willFetch} video{plan.willFetch === 1 ? "" : "s"}. </p> <ul className="list-disc pl-5 text-muted-foreground"> - {BUCKETS.filter((b) => plan[b.key].count > 0).map((b) => ( + {BUCKETS.filter((b) => (plan[b.key]?.count ?? 0) > 0).map((b) => ( <li key={b.key} data-bucket={b.key}> {plan[b.key].count} {b.words} {plan[b.key].count <= 8 && ( diff --git a/editor/app/saved-videos/persistListAction.ts b/editor/app/saved-videos/persistListAction.ts @@ -1,7 +1,7 @@ "use server"; import { persistVideosAction, type PersistVideosActionResult } from "../channels/[slug]/persistActions"; -import type { PersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos"; +import { isPersistReplacePolicy, type PersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos"; import { isSourceVideoQuality, type SourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { parseVideoList } from "./lib/videoList"; @@ -38,6 +38,6 @@ export async function persistVideoListAction(input: { items, dryRun: input.dryRun, ...(format ? { format } : {}), - ...(input.replace === "above-height" ? { replace: "above-height" as const } : {}), + ...(isPersistReplacePolicy(input.replace) && input.replace !== "never" ? { replace: input.replace } : {}), }); } diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1173,8 +1173,10 @@ export function usage() { " explicit persist (persist-videos, Persist source video, a whole-recording", " fetch) makes the download active, any other keeps the saved one unless", " the download is longer — and the other stays beside it as", - " source-media.alt-<h>p-<stamp>.<ext>, flagged for a check. Each video:", - " its line, the active copy, the alternates (height, seconds, origin).", + " source-media.alt-<h>p-<stamp>.<ext>, flagged for a check -- or kept on", + ' purpose ("keptAs": "proxy": the lower copy a persist-videos "below-height"', + " replaced). Each video: its line, the active copy, the alternates", + " (height, seconds, origin, keptAs).", " Once one is checked, `drop-saved-alternate` deletes it.", "get sites lists every site: id, title, siteUrl, Pages project, audience,", " listed, search, publish policy, channels, citedChannels. (`get publish`", @@ -1824,16 +1826,24 @@ export function usage() { 'persist-videos saves specific videos, across channels, to the saved-video', ' store: {"items": [{"slug", "id"}, ...]}. "format": "original" |', ' "video_720" (default: each channel\'s own). "replace": "above-height" also', - ' re-fetches a saved one whose height is unknown or above that quality', - ' (default "never"). "gapMs" pauses between downloads (default the batch', - ' gap), "minFreeMemMb" waits for that much free memory before each.', - ' "dryRun": true answers with the buckets (saved, wrongHeight, toFetch,', - ' noUrl, unknown) and starts nothing. One job per channel, on its download', - " queue; a low disk or a rate limit stops it, and running the same body", - " again resumes — saved videos are skipped. Over a copy already in the", - " store (an import, an attach, a live recording or an earlier download) the", - " download becomes the active one and the old copy is kept beside it,", - " flagged for a check (`get saved-alternates`); nothing is deleted.", + ' re-fetches a saved one whose height is unknown or above that quality;', + ' "below-height" one whose height (recorded, else ffprobed) is below what', + ' that quality gives -- its ceiling, capped by the tallest format the', + ' record\'s metadata lists -- and keeps the old copy as its proxy', + ' ("keptAs": "proxy" on the alternate, once the new copy is taller); one', + ' that cannot be compared, with a taller alternate already beside it, or', + ' already downloaded at that quality (unless its metadata is newer than', + ' the copy) is left alone (default "never"). "gapMs" pauses between', + ' downloads (default the batch gap), "minFreeMemMb" waits for that much', + ' free memory before each. "dryRun": true answers with the buckets (saved,', + ' wrongHeight, lowerHeight, heightUnknown, tallerAlternate, toFetch, noUrl,', + ' unknown) and starts nothing. One job per', + " channel, on its download queue; a low disk or a rate limit stops it, and", + " running the same body again resumes — saved videos are skipped. Over a", + " copy already in the store (an import, an attach, a live recording or an", + " earlier download) the download becomes the active one and the old copy", + " is kept beside it, flagged for a check (`get saved-alternates`) or kept", + " as the proxy; nothing is deleted.", "", 'import-archive-org imports archive.org media into a channel, as one job on', ' archive.org\'s queue: {"slug", "item", "files": [...] | "match": "<regex>"}',