commit e010ef684b79d9aa001a179685379527afea6087
parent 58fba9279c82bf3e6095f66759c637cd1433b3a9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 13 Nov 2026 19:36:12 -0500
Merge lane/persist-upgrade (second part): clip windows for a umtool project may be taller than 720 -- a project that sets render.tallWindows asks for its windows up to clips.windowMaxHeight (1080), and a taller cut is kept beside the plain 720 window, never in place of it; the build, quote-check, align and every other lookup resolve the same file; a project without the switch, every site's evidence cut and every plain ask behave as before, site-driven fetches stay at 720; nothing is fetched again for height unless a refetch asks, a refetch on a tall project leaves the 720 window alone, and a 720 window a site needs is cut from the taller one already here; heights are recorded, never upscaled, and tall cuts wait while a render holds the machine
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
64 files changed, 2826 insertions(+), 166 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -173,7 +173,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `build-homepage` | build-homepage builds the homepage package into homepage/out; {"deploy": true} deploys it after (only if the build succeeded), and deploy-homepage ships the one already built. Both deploy to the Pages project archilyzer (https://archilyzer.pages.dev), production unless "preview" is given. | |
| `relocate` | relocate moves channels' media to a location: {"slugs", "locationId" \| "root"}. "dryRun": true answers each channel's preview (bytes to copy, free space both sides) and moves nothing — though, as on the Storage panel, a channel never tiered is first tiered in place on the corpus disk. | `pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter"}'`<br>`pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter","dryRun":true}'` |
| `relocate-back` | relocate-back moves channels' media back onto the corpus disk, one job per channel on the relocation queue: {"slugs"}. A busy channel is answered in "skipped"; --wait follows the jobs started. | |
-| `evict-clips` | evict-clips deletes cached clip windows (data/<id>/clips/) older than a number of days, as /storage's button does: {"olderThanDays", "slug"?, "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a window; an evicted window is fetched again when asked for. TARGETED, for windows known bad: {"slug", "id"} evicts every window of that video; "windows": \["<from>-<to>", ...\] only those named, "covering": \[{"from", "to"}, ...\] any window overlapping a span (umtool fetch --refetch asks this way); "olderThanDays" is then optional, "dryRun" only lists. | `pnpm ops evict-clips --json '{"slug":"x","id":"abc123","covering":[{"from":10,"to":40}],"dryRun":true}' --wait` |
+| `evict-clips` | evict-clips deletes cached clip windows (data/<id>/clips/) older than a number of days, as /storage's button does: {"olderThanDays", "slug"?, "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a window; an evicted window is fetched again when asked for. TARGETED, for windows known bad: {"slug", "id"} evicts every window of that video; "windows": \["<from>-<to>", ...\] only those named, "covering": \[{"from", "to"}, ...\] any window overlapping a span (umtool fetch --refetch asks this way); "olderThanDays" is then optional, "dryRun" only lists. "tiers": "plain" \| "tiered" narrows to the <from>-<to> windows or the taller <from>-<to>.h<height> ones (default "all": both). | `pnpm ops evict-clips --json '{"slug":"x","id":"abc123","covering":[{"from":10,"to":40}],"dryRun":true}' --wait` |
| `check-windows` | check-windows probes cached clip windows (data/<id>/clips/) for a picture that runs off the sound (a Rumble HLS seek) and sets each desynced one aside as <from>-<to>.desynced.<ext> (never deleted; no reader sees it, and evict-clips ages it out): {"slug"?, "video"?, "dryRun"?}. "video" needs "slug"; "dryRun" only lists. A fetch then fills the span again, from the saved video first. | |
| `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "<id>"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` |
| `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` |
@@ -183,7 +183,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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; "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 (<from>-<to>.desynced.<ext>) 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` |
+| `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). Above 720 it is a tall ask, clamped to settings clips.windowMaxHeight (default 1080): its window is its own file beside the 720 one (<from>-<to>.h<height>.mp4), cut from the saved copy when that is taller; a cached window lower than asked with no taller saved copy is used as it is and listed in "lower" with why -- never fetched again for height. "siteId" stays at 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 (<from>-<to>.desynced.<ext>) 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 "## \[<version>\] - <date>": {"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 <workspace> <version>") — 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": "<its version, as you saw it>", "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}'` |
| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -796,7 +796,33 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md"
[CITATIONS.md](CITATIONS.md)); `reports convert` makes one from a `/sweep` report, an `/ask` answer or a
report-to-video manifest.
- `fetch-windows` with `siteId` fetches every clip window the site's published reports cite that the disk does not
- hold, one paced job per platform; a re-run resumes.
+ hold, one paced job per platform; a re-run resumes. It stays at 720: a site's evidence clip is cut inside
+ 1280×720 from the plain `<from>-<to>.mp4` window.
+- A window asked taller than 720 (`"maxHeight"` on `fetch-windows`, fetch-window, `fetch_clip`; umtool sends it only
+ for a project with `render.tallWindows` on) is its own file beside the 720 one: `clips/<from>-<to>.h<tier>.mp4`,
+ with its own sidecar. The 720 window is never replaced, retired or re-fetched for this. An ask with no `maxHeight`
+ is 720, as before.
+ - The tier is the smallest of 1080, 1440 and 2160 at or above the ask, held to `settings.clips.windowMaxHeight`
+ (default 1080), so asks of 900 and 1080 share one file. A Retry keeps the tier its job was queued at.
+ - A held window lower than asked is cut taller from the video's saved copy when that copy is taller. That cut waits
+ while render mode holds the machine, and says so in the job log. A single fetch-window answers with what there is
+ now instead, and says why.
+ - With no taller saved copy, the lower window is used as it is. The answer lists it under `"lower"` (fetch-window
+ and `fetch_clip`: `belowAsked`) with its height and why. Only a refetch fetches a taller one from the network over
+ it; persisting the video (`persist-videos`) gives it a copy to cut from.
+ - `umtool fetch --refetch` on a tall project evicts only the taller windows of the span, then cuts them again from
+ the saved copy, or fetches them at their tier; the 720 window stays. Without `render.tallWindows` a refetch evicts
+ the 720 windows only, as before.
+ - Heights are recorded only for taller windows, and for a 720 window the first time a tall ask needs it (one probe,
+ written to its sidecar). A saved copy with no recorded height gets the height that probe found (`probed.height`).
+ - A 720 ask that misses, over a span a taller window holds, is cut from that window (the 1280×720 box; its sidecar
+ says `source: "clip-window"`, `derivedFrom`), never fetched. Only a taller window that passes the sync check is
+ used; a failed cut fails the item. That 720 window may later serve as a site's evidence: a further encode of the
+ same seconds.
+ - A refetch marks its items (`"refetch": true`): a lower held window does not answer them. They are cut again at
+ their tier from the saved copy, or, with none, fetched at their tier on the platform's own queue.
+ - `evict-clips` takes `"tiers": "plain" | "tiered"` (default both). The age-out, named and covering evictions and the
+ clock retirement treat a taller window as a window of its span. `check-windows` checks the taller windows too.
- A cited recording deleted or made private on its platform cannot be fetched from its page. `find-copy` (a site's
`siteId`, an `article`, or `"articles": true`) looks for a copy of each — a Wayback Machine capture of its page,
then an archive.org mirror naming its YouTube id — and fetches the cited windows from it as one fetch-windows job;
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -1358,13 +1358,14 @@ Default:
## `clips`
-How clip windows are fetched (controller/fetchWindows.ts): the platforms whose windows are cut from the saved WHOLE recording rather than by a remote seek — Rumble by default, because its HLS seek put the picture 1–4 s off the sound (lib/clipWindowSync.ts). See ClipsSettings.
+How clip windows are fetched (controller/fetchWindows.ts): the platforms whose windows are cut from the saved WHOLE recording rather than by a remote seek — Rumble by default, because its HLS seek put the picture 1–4 s off the sound (lib/clipWindowSync.ts) — and the tallest height a window may be asked for (`windowMaxHeight`, a ceiling: an ask with no height is 720 as before). See ClipsSettings.
#### `clips`
| Key | Default | Description |
|---|---|---|
| `wholeRecordingPlatforms` | list — see below | Platforms (as the URL names them: "rumble", "youtube", …) whose clip windows are cut from the WHOLE recording instead of fetched by a remote seek: a fetch-windows run saves the video once to the saved-video store (as "Persist source video" does, on the platform's download queue) and cuts every window of it locally. A failed whole download fails its windows; it never falls back to a seek. A run's `"wholeRecording": false` restores the seek for that run. Default ["rumble"] (a Rumble seek put the picture 1–4 s off the sound in 26 of 205 windows); [] = every platform seeks. |
+| `windowMaxHeight` | `1080` | The tallest source height, in pixels, a clip-window request may ask for (`maxHeight` on fetch-window, fetch-windows, fetch_clip; umtool sends its project's `render.maxHeightSource` only when the project has `render.tallWindows` on). A CEILING, not a default: a request with no `maxHeight` is fetched and cut at 720 as before, and one asking more is clamped to this. A window asked above 720 is a separate cache entry beside the 720 one (`<from>-<to>.h<tier>.mp4`, the tier the smallest of 1080, 1440, 2160 at or above the ask, held to this), cut from the saved copy when there is a taller one; the 720 window and every published site's evidence media are never touched. Site-driven fetches (`fetch-windows {"siteId"}`, Fetch missing evidence) stay at 720. Default 1080; 144–2160. |
Default:
@@ -1372,7 +1373,8 @@ Default:
{
"wholeRecordingPlatforms": [
"rumble"
- ]
+ ],
+ "windowMaxHeight": 1080
}
```
diff --git a/common/controller/checkClipWindows.ts b/common/controller/checkClipWindows.ts
@@ -81,7 +81,8 @@ async function checkVideo(
out: CheckClipWindowsResult,
): Promise<void> {
const videoDir = path.join(opts.paths.channelsDir, slug, "data", id);
- const windows = await listClipWindows(videoDir);
+ // The taller (tiered) windows too: a remote seek at any height can run off its sound.
+ const windows = await listClipWindows(videoDir, { tiers: true });
if (windows.length === 0) return;
out.videos += 1;
for (const w of windows) {
diff --git a/common/controller/evictClipWindows.ts b/common/controller/evictClipWindows.ts
@@ -4,8 +4,10 @@ import type { Paths } from "../lib/paths";
import {
CLIPS_DIR_NAME,
clipWindowDesyncedSidecar,
- clipWindowName,
clipWindowSidecar,
+ clipWindowStem,
+ parseAnyClipWindowName,
+ parseTieredClipWindowName,
parseClipWindowName,
parseDesyncedClipWindowName,
} from "../lib/clipWindow";
@@ -57,6 +59,15 @@ import { resolveVideoDirId } from "../lib/videoDir-server.mjs";
// `<from>-<to>.desynced.<ext>` of a targeted span goes with it.
export type ClipWindowSpan = { from: number; to: number };
+// A named window: its span, and — named `<from>-<to>.h<tier>` — that tier only.
+export type NamedClipWindow = ClipWindowSpan & { tier?: number };
+
+export const EVICT_TIERS = ["all", "plain", "tiered"] as const;
+export type EvictTiers = (typeof EVICT_TIERS)[number];
+
+export function isEvictTiers(v: unknown): v is EvictTiers {
+ return typeof v === "string" && (EVICT_TIERS as readonly string[]).includes(v);
+}
export type EvictClipWindowsOptions = {
paths: Paths;
@@ -65,10 +76,18 @@ export type EvictClipWindowsOptions = {
// One video of `slug` (a record id; a Twitch v<n> resolves to its dir, as
// check-windows does). Every window of it, unless `windows`/`covering` narrow.
id?: string;
- // Windows named exactly (`<from>-<to>`, parsed): needs `id`.
- windows?: ClipWindowSpan[];
+ // Windows named exactly (`<from>-<to>`, parsed): needs `id`. A plain name
+ // names its span (every tier `tiers` allows); `<from>-<to>.h<tier>` names
+ // that tiered window alone.
+ windows?: NamedClipWindow[];
// Any window overlapping one of these spans: needs `id`.
covering?: ClipWindowSpan[];
+ // WHICH WINDOWS OF A SPAN (the height tier, lib/clipWindow.ts): "all" (the
+ // default — the age-out, a named or covering eviction, the clock
+ // retirement), "plain" (`<from>-<to>.<ext>` only) or "tiered" (the taller
+ // `<from>-<to>.h<tier>.<ext>` cuts only — what umtool's refetch of a tall
+ // project asks, so the 720 window a site's evidence reads stays).
+ tiers?: EvictTiers;
// A window is evicted when it has not been touched for this many days.
// 0 means "everything", which is a legitimate ask (the operator is emptying
// a drive) and is why this is not clamped to a minimum. Required unless
@@ -190,10 +209,17 @@ async function evictChannel(
// A SET-ASIDE WINDOW (`<from>-<to>.desynced.<ext>`, lib/clipWindowSync.ts)
// is cache like any other and ages out the same way, with its own
// `.desynced.json`: no reader sees it, so nothing else ever would.
- const live = parseClipWindowName(name);
+ //
+ // A TIERED window (`<from>-<to>.h<tier>.<ext>`, the height tier in
+ // lib/clipWindow.ts) is a window of its span: named, covered and aged
+ // out as the plain one, with its own `.h<tier>.json`.
+ const live = parseAnyClipWindowName(name);
const aside = live ? null : parseDesyncedClipWindowName(name);
const span = live ?? aside;
if (!span) continue;
+ // The tier filter: a window of the other kind is not this run's.
+ const tiers = opts.tiers ?? "all";
+ if ((tiers === "plain" && span.tier !== undefined) || (tiers === "tiered" && span.tier === undefined)) continue;
const file = path.join(clipsDir, name);
let st;
try {
@@ -204,7 +230,7 @@ async function evictChannel(
if (!st.isFile()) continue;
sawWindow = true;
if (opts.windows || opts.covering) {
- const hits = named.flatMap((w, i) => (sameSpan(w, span) ? [i] : []));
+ const hits = named.flatMap((w, i) => (sameSpan(w, span) && (w.tier === undefined || w.tier === span.tier) ? [i] : []));
for (const i of hits) matchedNames.add(i);
const covered = (opts.covering ?? []).some((c) => overlaps(c, span));
if (!hits.length && !covered) {
@@ -234,7 +260,9 @@ async function evictChannel(
await rm(
path.join(
clipsDir,
- aside ? clipWindowDesyncedSidecar(span.from, span.to) : clipWindowSidecar(span.from, span.to),
+ aside
+ ? clipWindowDesyncedSidecar(span.from, span.to, span.tier)
+ : clipWindowSidecar(span.from, span.to, span.tier),
),
{ force: true },
);
@@ -257,7 +285,7 @@ const sameSpan = (a: ClipWindowSpan, b: ClipWindowSpan) =>
// Strictly: a window that only touches a span's edge holds none of its seconds.
const overlaps = (a: ClipWindowSpan, b: ClipWindowSpan) =>
a.from < b.to && b.from < a.to;
-const spanName = (w: ClipWindowSpan) => clipWindowName(w.from, w.to);
+const spanName = (w: NamedClipWindow) => clipWindowStem(w.from, w.to, w.tier);
const isSpanObj = (v: unknown): v is ClipWindowSpan => {
if (!v || typeof v !== "object" || Array.isArray(v)) return false;
@@ -282,17 +310,20 @@ export function parseEvictTargets(raw: {
windows?: unknown;
covering?: unknown;
}):
- | { ok: true; windows?: ClipWindowSpan[]; covering?: ClipWindowSpan[] }
+ | { ok: true; windows?: NamedClipWindow[]; covering?: ClipWindowSpan[] }
| { ok: false; error: string } {
- const out: { windows?: ClipWindowSpan[]; covering?: ClipWindowSpan[] } = {};
+ const out: { windows?: NamedClipWindow[]; covering?: ClipWindowSpan[] } = {};
if (raw.windows !== undefined) {
const v = raw.windows;
if (!Array.isArray(v) || v.length === 0) {
return { ok: false, error: '"windows" must be a non-empty array of "<from>-<to>" names (e.g. "1992.68-2013.56")' };
}
- const spans: ClipWindowSpan[] = [];
+ const spans: NamedClipWindow[] = [];
for (const name of v) {
- const span = typeof name === "string" ? parseClipWindowName(name.trim()) : null;
+ const span =
+ typeof name === "string"
+ ? (parseClipWindowName(name.trim()) ?? parseTieredClipWindowName(`${name.trim()}.mp4`))
+ : null;
if (!span) {
return { ok: false, error: `"windows" holds ${JSON.stringify(name)}, which is not a window name "<from>-<to>" (seconds, from < to)` };
}
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -10,16 +10,20 @@ import {
type DownloadFailureClass,
} from "../lib/availability";
import type { SavedVideoOrigin } from "../lib/savedVideo";
-import { DEFAULT_CLIPS_SETTINGS } from "../lib/clipSettings";
+import { DEFAULT_CLIPS_SETTINGS, windowMaxHeightOf } from "../lib/clipSettings";
import { downloadOneManaged, sourceFetchFailure } from "../ytdlp/downloadOneManaged";
import { resolveSourceVideoQuality } from "../ytdlp/downloadFormat";
-import type { ClipCopy } from "../lib/clipWindow";
+import { clampWindowCap, isWindowTier, windowTierOf, type ClipCopy } from "../lib/clipWindow";
+import { tallerFromSaved } from "../lib/clipWindowTier-server";
+import { renderModeHeldNow, waitWhileRenderHeld } from "../lib/renderHold";
+import { probeVideoHeight } from "../ytdlp/ffprobeDuration";
import { isSourceSideCopyFailure, recordFailedCopy, type FailedCopy } from "../lib/copyAttempts-server";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import { assertChannelMediaReachable, assertChannelTextReadable } from "../lib/channelMedia";
import { detectPlatform } from "../lib/platform";
import {
findInSyncContainingClipWindow,
+ findInSyncTieredWindowHolding,
judgeClipWindow,
probeWindowStreams,
setAsideDesyncedWindow,
@@ -36,6 +40,7 @@ import type { RecordingClock } from "../lib/recordingClock.mjs";
import { listClipWindows } from "../lib/clipWindow-server";
import { evictClipWindows } from "./evictClipWindows";
import {
+ cutPlainFromTieredWindow,
cutSavedVideoWindow,
savedWindowSource,
} from "../lib/savedVideoWindow-server";
@@ -237,6 +242,11 @@ export type FetchWindowsItem = {
// is gone (a stale reading: made public again, a geo block read as removed).
// The editor's door refuses a gone recording's window without it.
force?: boolean;
+ // A REFETCH (umtool fetch --refetch, after it evicted the span's taller
+ // windows): on a tall ask a LOWER held window does not answer it — it is
+ // cut again at its tier from the saved copy, or, with none, fetched at its
+ // tier on the platform's own queue. No effect on a plain ask.
+ refetch?: boolean;
};
export type FetchWindowsFailureClass =
@@ -294,6 +304,12 @@ export type FetchWindowsResult = {
// clock (`<slug>/<dir id>/clips/<from>-<to>`).
clocked?: string[];
retired?: string[];
+ // THE HEIGHT TIER (lib/clipWindow.ts): held windows LOWER than a tall ask,
+ // used as they are — the window, its height (null: unknown) and why no
+ // taller one was cut. And the ask's own height when the setting's ceiling
+ // (clips.windowMaxHeight) clamped it.
+ lower?: { item: FetchWindowsItem; file: string; height: number | null; asked: number; why: string }[];
+ clampedFrom?: number;
stopped?: FetchWindowsStop;
};
@@ -359,6 +375,14 @@ export type FetchWindowsDeps = {
// cut made before the map): their seconds are another clock's. Returns the
// retired `<from>-<to>` names.
retireOffClock: (opts: { paths: Paths; slug: string; dirId: string; videoDir: string; clockId: string }) => Promise<string[]>;
+ // A window's picture height, for a tall ask over a window with none
+ // recorded (probed once; the answer is written to its sidecar).
+ probeHeight: (file: string, paths: Paths) => Promise<number | null>;
+ // Render mode's holder, or null (lib/renderHold.ts): a TALL cut from a saved
+ // copy waits while it holds the machine.
+ renderHeld: () => string | null;
+ // A plain window cut from a tiered one (a plain miss, the height tier).
+ cutPlainFromTiered: typeof cutPlainFromTieredWindow;
};
// The windows of a video cut on another clock than `clockId`, evicted through
@@ -370,7 +394,8 @@ async function retireOffClockWindows(o: {
videoDir: string;
clockId: string;
}): Promise<string[]> {
- const off = (await listClipWindows(o.videoDir)).filter((w) => w.provenance?.clock?.id !== o.clockId);
+ // Tiered windows too (the height tier): a window of the span, on any clock.
+ const off = (await listClipWindows(o.videoDir, { tiers: true })).filter((w) => w.provenance?.clock?.id !== o.clockId);
if (!off.length) return [];
await evictClipWindows({
paths: o.paths,
@@ -503,6 +528,9 @@ const DEFAULT_DEPS: FetchWindowsDeps = {
signal: o.signal,
}),
retireOffClock: retireOffClockWindows,
+ probeHeight: (file, paths) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file }),
+ renderHeld: renderModeHeldNow,
+ cutPlainFromTiered: cutPlainFromTieredWindow,
assertMediaReachable: (paths, slug) => assertChannelMediaReachable(paths, slug),
saveWholeRecording: saveWholeRecordingManaged,
};
@@ -552,6 +580,7 @@ export async function fetchWindows({
items,
provenance,
maxHeight,
+ tier: givenTier,
gapMs,
minGapSeconds,
storedUrl: storedMode = "never",
@@ -566,6 +595,10 @@ export async function fetchWindows({
items: FetchWindowsItem[];
provenance: FetchWindowsProvenance;
maxHeight?: number;
+ // THE TIER THE RUN WAS QUEUED AT (lib/clipWindow.ts windowTierOf), carried
+ // in its job spec so a Retry cuts the same file whatever the settings say
+ // now. Absent: decided here from `maxHeight` and clips.windowMaxHeight.
+ tier?: number;
// The pause between two network fetches. Absent = the platform's batch gap,
// floored at CLIP_WINDOW_MIN_GAP_SECONDS.
gapMs?: number;
@@ -592,6 +625,16 @@ export async function fetchWindows({
const settings = deps.getSettings();
const requestedAt = provenance.requestedAt ?? new Date().toISOString();
+ // THE HEIGHT ASKED, against the ceiling (clips.windowMaxHeight). No height
+ // is the plain 720 path, exactly as before; above 720 is a tall ask (tier).
+ // A tier a Retry carries in its spec wins over today's settings (`tier`).
+ const ceiling = windowMaxHeightOf(settings.clips);
+ const fixed = isWindowTier(givenTier) ? givenTier : undefined;
+ const { cap: asked, clampedFrom } =
+ fixed !== undefined ? { cap: fixed as number | undefined, clampedFrom: undefined as number | undefined } : clampWindowCap(maxHeight, ceiling);
+ const tier = fixed ?? windowTierOf(asked, ceiling);
+ // The network's cap: the tier when tall (so 900 and 1080 fetch one file), else the ask as given.
+ const cap = tier ?? asked;
const work = dedupeFetchWindowsItems(items);
const result: FetchWindowsResult = {
fetched: [],
@@ -605,8 +648,14 @@ export async function fetchWindows({
};
log(
`Fetch windows: ${work.length} window(s) for ${provenance.requestedBy}` +
- `${provenance.manifest ? ` · ${provenance.manifest}` : ""}.`,
+ `${provenance.manifest ? ` · ${provenance.manifest}` : ""}` +
+ `${tier !== undefined ? ` at up to ${tier}p` : ""}.`,
);
+ if (clampedFrom !== undefined) {
+ result.clampedFrom = clampedFrom;
+ log(` ${clampedFrom}p was asked; clips.windowMaxHeight caps a window at ${cap}p.`);
+ }
+ const heightProbe = (file: string) => deps.probeHeight(file, paths);
let done = 0;
const progress = () =>
@@ -726,7 +775,24 @@ export async function fetchWindows({
label: string,
videoDir: string,
source: Extract<Awaited<ReturnType<typeof savedWindowSource>>, { kind: "covers" }>,
+ beside?: string,
): Promise<void> => {
+ // A TALL cut waits while render mode holds the machine (H, 13 Nov): not
+ // heavy enough for the slot, but cores a render wants. Said in the log.
+ if (tier !== undefined) {
+ const waited = await waitWhileRenderHeld({
+ held: deps.renderHeld,
+ sleep: deps.sleep,
+ onLog: log,
+ what: `${label} (the ${tier}p cut)`,
+ signal: fetchSignal,
+ });
+ if (waited === null) {
+ result.notAttempted.push(item);
+ result.stopped ??= "cancel";
+ return;
+ }
+ }
try {
const cut = await deps.cutSavedWindow({
paths,
@@ -734,6 +800,8 @@ export async function fetchWindows({
source,
from: item.from,
to: item.to,
+ // A tall ask's cut is its own tier, beside any plain window.
+ ...(tier !== undefined ? { tier } : {}),
provenance: {
requestedBy: provenance.requestedBy,
manifest: provenance.manifest,
@@ -745,7 +813,10 @@ export async function fetchWindows({
signal: fetchSignal,
});
result.cut.push(item);
- log(` ✂ ${label}: cut from the saved video into clips/${cut.file}`);
+ log(
+ ` ✂ ${label}: cut from the saved video into clips/${cut.file}` +
+ (beside ? ` (${cut.height ?? "?"}p, beside clips/${beside}, which stays as it is)` : ""),
+ );
} catch (e) {
fail(item, "cut-failed", (e as Error).message);
}
@@ -808,7 +879,10 @@ export async function fetchWindows({
// the span goes on below as missing.
let held: Awaited<ReturnType<typeof findInSyncContainingClipWindow>>;
try {
- held = await findInSyncContainingClipWindow(videoDir, item.from, item.to, { probe });
+ held = await findInSyncContainingClipWindow(videoDir, item.from, item.to, {
+ probe,
+ ...(tier !== undefined ? { maxHeight: tier, heightProbe } : {}),
+ });
} catch (e) {
// A rename refused in clips/ (read-only, gone mid-run): the window is
// neither usable nor out of the way, so the item is not fetched over it.
@@ -836,6 +910,49 @@ export async function fetchWindows({
`${d.setAsideAs}, and the span is fetched again.`,
);
}
+ // A refetch is not answered by a lower window (the evicted tier is wanted).
+ if (hit && tier !== undefined && item.refetch && (hit.height ?? 0) < tier) {
+ log(` ${label}: a refetch — clips/${hit.file} (${hit.height ?? "?"}p) does not answer it; cut or fetched again at ${tier}p.`);
+ hit = null;
+ }
+ if (hit && tier !== undefined && (hit.height ?? 0) < tier) {
+ // A TALL ASK OVER A LOWER WINDOW: a taller cut beside it from the saved
+ // copy when that is taller; else the window as it is, and why. Never a
+ // network fetch for height (lib/clipWindowTier-server.ts).
+ const t = await tallerFromSaved({
+ paths,
+ slug: item.slug,
+ videoDir,
+ from: item.from,
+ to: item.to,
+ hitHeight: hit.height ?? null,
+ cap: tier,
+ source: deps.savedWindowSource,
+ });
+ if (t.kind === "cut") {
+ await cutFromSaved(item, label, videoDir, t.source, hit.file);
+ done += 1;
+ progress();
+ continue;
+ }
+ if (t.kind === "best") {
+ // As tall as the saved copy gives in the tier's box: an ordinary hit.
+ result.cached.push(item);
+ log(` = ${label}: cached in clips/${hit.file} (${t.height}p, all the saved copy gives at ${tier}p)`);
+ done += 1;
+ progress();
+ continue;
+ }
+ (result.lower ??= []).push({ item, file: hit.file, height: hit.height ?? null, asked: tier, why: t.why });
+ result.cached.push(item);
+ log(
+ ` = ${label}: cached in clips/${hit.file} at ${hit.height !== undefined ? `${hit.height}p` : "an unknown height"}, ` +
+ `below the ${tier}p asked — ${t.why}`,
+ );
+ done += 1;
+ progress();
+ continue;
+ }
if (hit) {
result.cached.push(item);
log(` = ${label}: cached in clips/${hit.file}`);
@@ -866,6 +983,52 @@ export async function fetchWindows({
continue;
}
+ // A PLAIN MISS A TALLER WINDOW HOLDS (D, 13 Nov): the plain 720 window is
+ // cut here from the tiered file — the evidence filter, nothing fetched,
+ // nothing on disk changed but the new window. A cut that fails goes on to
+ // the network as before.
+ if (tier === undefined) {
+ // Only a tiered window that is in sync (judged as any window in use; a
+ // desynced one is set aside and the plain ask goes on without it).
+ const t = await findInSyncTieredWindowHolding(videoDir, item.from, item.to, { probe }).catch(() => ({ hit: null, desynced: [] }));
+ for (const d of t.desynced) {
+ result.setAside.push(`${item.slug}/${dirId}/clips/${d.setAsideAs}`);
+ log(` ! ${label}: clips/${d.window.file} — ${windowSyncLagText(d.sync)}; set aside as ${d.setAsideAs}.`);
+ }
+ const tiered = t.hit;
+ if (tiered) {
+ try {
+ const cut = await deps.cutPlainFromTiered({
+ paths,
+ videoDir,
+ tiered,
+ from: item.from,
+ to: item.to,
+ provenance: {
+ requestedBy: provenance.requestedBy,
+ manifest: provenance.manifest,
+ clipId: item.clipId,
+ reason: item.reason,
+ pad: item.pad,
+ requestedAt,
+ },
+ signal: fetchSignal,
+ });
+ result.cut.push(item);
+ log(` ✂ ${label}: cut from clips/${tiered.file} into clips/${cut.file} (the 720 window; nothing fetched)`);
+ done += 1;
+ progress();
+ continue;
+ } catch (e) {
+ // As a failed cut from a saved copy: the item fails, nothing is fetched.
+ fail(item, "cut-failed", `cutting it from clips/${tiered.file} failed: ${(e as Error).message}`);
+ done += 1;
+ progress();
+ continue;
+ }
+ }
+ }
+
const url =
item.webpageUrl?.trim() ||
(await deps.findVideoSourceUrl(paths, item.slug, dirId, config));
@@ -1124,7 +1287,8 @@ export async function fetchWindows({
...(item.copy ? { copy: item.copy } : {}),
},
cookiePolicy: resolveCookiePolicy(settings, config),
- maxHeight,
+ maxHeight: cap,
+ ...(tier !== undefined ? { tier } : {}),
onLog: fetchLog,
signal: fetchSignal,
onPlatformBackoff: () => deps.recordBackoff(platform, paths, "rate_limit"),
diff --git a/common/controller/fetchWindowsTier.test.ts b/common/controller/fetchWindowsTier.test.ts
@@ -0,0 +1,376 @@
+// fetchWindows (the batch) and THE HEIGHT TIER (lib/clipWindow.ts): a tall ask
+// over a lower held window cuts a taller one beside it from the saved copy,
+// or uses the window as it is and says why — never a network fetch for height;
+// a tall ask with nothing held fetches into its own tier; no ask is exactly as
+// before; the ceiling clamps. Every network and media dependency is stubbed.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchWindowsTier.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, stat, utimes, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fetchWindows, type FetchWindowsDeps, type FetchWindowsItem } from "./fetchWindows";
+import { evictClipWindows } from "./evictClipWindows";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { SiteSettings } from "../lib/settings";
+import type { SavedWindowSource } from "../lib/savedVideoWindow-server";
+import type { FetchWindowOpts } from "../ytdlp/fetchWindowManaged";
+
+const CONFIG = { url: "https://www.youtube.com/@x", platform: "youtube" } as unknown as ChannelConfig;
+
+async function withCorpus(fn: (o: { paths: Paths; videoDir: string; clips: string }) => Promise<void>) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "fetchwindows-tier-"));
+ const channelsDir = path.join(root, "channels");
+ const videoDir = path.join(channelsDir, "c", "data", "v1");
+ const clips = path.join(videoDir, "clips");
+ await mkdir(clips, { recursive: true });
+ const paths = { transcriptsDir: root, channelsDir, savedVideosDir: path.join(root, "saved") } as unknown as Paths;
+ try {
+ await fn({ paths, videoDir, clips });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+const covers = (height: number): SavedWindowSource =>
+ ({
+ kind: "covers",
+ pointer: { storedAt: "", dir: "/s", file: "source-media.mp4", bytes: 1 },
+ container: "/s/source-media.mp4",
+ durationSec: 100,
+ probe: { durationSec: 100, width: Math.round((height * 16) / 9), height, hasVideo: true, hasAudio: true },
+ }) as SavedWindowSource;
+
+function harness(o: { saved?: SavedWindowSource; windowMaxHeight?: number; renderHeld?: () => string | null } = {}) {
+ const fetches: FetchWindowOpts[] = [];
+ const cuts: { maxHeight?: number; from: number; to: number }[] = [];
+ const derived: { from: string; to: number }[] = [];
+ const sleeps: number[] = [];
+ const deps: Partial<FetchWindowsDeps> = {
+ sleep: async (ms) => {
+ sleeps.push(ms);
+ },
+ renderHeld: o.renderHeld ?? (() => null),
+ cutPlainFromTiered: async (c) => {
+ derived.push({ from: c.tiered.file, to: c.to });
+ const file = `${c.from.toFixed(2)}-${c.to.toFixed(2)}.mp4`;
+ return { file, path: path.join(c.videoDir, "clips", file), from: c.from, to: c.to, bytes: 1, provenance: null };
+ },
+ getSettings: () =>
+ ({
+ sleepBetweenDownloadsSeconds: 0,
+ clips: { wholeRecordingPlatforms: [], ...(o.windowMaxHeight ? { windowMaxHeight: o.windowMaxHeight } : {}) },
+ }) as unknown as SiteSettings,
+ readChannelConfig: async () => CONFIG,
+ findVideoSourceUrl: async () => "https://www.youtube.com/watch?v=v1",
+ assertTextReadable: async () => undefined,
+ cooldownRemainingMs: async () => 0,
+ heldRefusal: async () => null,
+ recordBackoff: async () => {},
+ recordClean: async () => null,
+ gapRemainingMs: () => 0,
+ noteGap: () => {},
+ probeWindow: async () => null,
+ probeHeight: async () => null,
+ savedWindowSource: async () => o.saved ?? { kind: "none" },
+ cutSavedWindow: async (c) => {
+ cuts.push({ maxHeight: c.tier, from: c.from, to: c.to });
+ const tier = c.tier;
+ const file = `${c.from.toFixed(2)}-${c.to.toFixed(2)}${tier ? `.h${tier}` : ""}.mp4`;
+ return { file, path: path.join(c.videoDir, "clips", file), from: c.from, to: c.to, bytes: 1, provenance: null, ...(tier ? { tier, height: tier } : {}) };
+ },
+ fetchWindow: async (f) => {
+ fetches.push(f);
+ return { file: "/x", from: f.from, to: f.to, bytes: 1, cached: false, provenance: null } as never;
+ },
+ };
+ return { deps, fetches, cuts, derived, sleeps };
+}
+
+const item: FetchWindowsItem = { slug: "c", id: "v1", from: 10, to: 20 };
+const run = (paths: Paths, deps: Partial<FetchWindowsDeps>, maxHeight?: number, lines: string[] = []) =>
+ fetchWindows({ paths, items: [item], provenance: { requestedBy: "umtool" }, maxHeight, gapMs: 0, onLog: (l) => lines.push(l), deps });
+
+async function plainWindow(clips: string, height?: number) {
+ await writeFile(path.join(clips, "10.00-20.00.mp4"), "the 720 window");
+ await writeFile(path.join(clips, "10.00-20.00.json"), JSON.stringify({ requestedBy: "reports", ...(height ? { height } : {}) }));
+}
+
+test("a tall ask over a 720 window with a 1080 saved copy cuts the 1080 beside it; the 720 one is not touched", async () => {
+ await withCorpus(async ({ paths, videoDir, clips }) => {
+ await plainWindow(clips, 720);
+ await writeFile(
+ path.join(videoDir, "saved-video.json"),
+ JSON.stringify({ storedAt: "2026-11-13T00:00:00.000Z", dir: "/s", file: "source-media.mp4", bytes: 1, format: { preset: "original", height: 1080 } }),
+ );
+ const before = await stat(path.join(clips, "10.00-20.00.mp4"));
+ const h = harness({ saved: covers(1080) });
+ const lines: string[] = [];
+ const r = await run(paths, h.deps, 1080, lines);
+ assert.deepEqual(h.cuts, [{ maxHeight: 1080, from: 10, to: 20 }]);
+ assert.equal(h.fetches.length, 0);
+ assert.equal(r.cut.length, 1);
+ assert.equal(r.lower, undefined);
+ assert.match(lines.join(""), /cut from the saved video into clips\/10\.00-20\.00\.h1080\.mp4 \(1080p, beside clips\/10\.00-20\.00\.mp4, which stays as it is\)/);
+ const after = await stat(path.join(clips, "10.00-20.00.mp4"));
+ assert.equal(after.mtimeMs, before.mtimeMs);
+ assert.equal(await readFile(path.join(clips, "10.00-20.00.mp4"), "utf8"), "the 720 window");
+ });
+});
+
+test("a tall ask over a 720 window with no saved copy uses it as it is, says why, and fetches nothing", async () => {
+ await withCorpus(async ({ paths, clips }) => {
+ await plainWindow(clips, 720);
+ const h = harness();
+ const lines: string[] = [];
+ const r = await run(paths, h.deps, 1080, lines);
+ assert.equal(h.fetches.length, 0);
+ assert.equal(h.cuts.length, 0);
+ assert.equal(r.cached.length, 1);
+ assert.equal(r.lower?.length, 1);
+ assert.equal(r.lower![0].file, "10.00-20.00.mp4");
+ assert.equal(r.lower![0].height, 720);
+ assert.equal(r.lower![0].asked, 1080);
+ assert.match(r.lower![0].why, /no saved copy/);
+ assert.match(lines.join(""), /cached in clips\/10\.00-20\.00\.mp4 at 720p, below the 1080p asked — no saved copy/);
+ });
+});
+
+test("an old window with no recorded height is probed once on its first tall ask, and recorded", async () => {
+ await withCorpus(async ({ paths, clips }) => {
+ await plainWindow(clips);
+ const h = harness();
+ let probes = 0;
+ h.deps.probeHeight = async () => {
+ probes += 1;
+ return 1080;
+ };
+ const r = await run(paths, h.deps, 1080);
+ assert.equal(r.cached.length, 1);
+ assert.equal(r.lower, undefined, "a 1080 window is not lower than a 1080 ask");
+ assert.equal(probes, 1);
+ assert.equal(JSON.parse(await readFile(path.join(clips, "10.00-20.00.json"), "utf8")).height, 1080);
+ await run(paths, h.deps, 1080);
+ assert.equal(probes, 1, "the second ask reads the record");
+ });
+});
+
+test("a tall ask with nothing held fetches into its own tier at its height; no ask fetches as before", async () => {
+ await withCorpus(async ({ paths }) => {
+ const tall = harness();
+ await run(paths, tall.deps, 1080);
+ assert.equal(tall.fetches.length, 1);
+ assert.equal(tall.fetches[0].maxHeight, 1080);
+ assert.equal(tall.fetches[0].tier, 1080);
+ const plain = harness();
+ await run(paths, plain.deps);
+ assert.equal(plain.fetches[0].maxHeight, undefined);
+ assert.equal(plain.fetches[0].tier, undefined);
+ const at480 = harness();
+ await run(paths, at480.deps, 480);
+ assert.equal(at480.fetches[0].maxHeight, 480);
+ assert.equal(at480.fetches[0].tier, undefined);
+ });
+});
+
+test("an ask above clips.windowMaxHeight is clamped to it, and said", async () => {
+ await withCorpus(async ({ paths }) => {
+ const h = harness({ windowMaxHeight: 1080 });
+ const lines: string[] = [];
+ const r = await run(paths, h.deps, 2160, lines);
+ assert.equal(r.clampedFrom, 2160);
+ assert.equal(h.fetches[0].maxHeight, 1080);
+ assert.equal(h.fetches[0].tier, 1080);
+ assert.match(lines.join(""), /2160p was asked; clips\.windowMaxHeight caps a window at 1080p/);
+ });
+});
+
+test("with no ask, a held 720 window answers as always, unprobed, whatever the saved copy holds", async () => {
+ await withCorpus(async ({ paths, clips }) => {
+ await plainWindow(clips);
+ const h = harness({ saved: covers(1080) });
+ let probes = 0;
+ h.deps.probeHeight = async () => {
+ probes += 1;
+ return 720;
+ };
+ const r = await run(paths, h.deps);
+ assert.equal(r.cached.length, 1);
+ assert.equal(h.cuts.length, 0);
+ assert.equal(probes, 0);
+ assert.equal(r.lower, undefined);
+ });
+});
+
+// EVICTION sees a tiered window as a window of its span: named, covered and by
+// age, each with its own `.h<tier>.json` (and a set-aside tiered one too).
+test("eviction sees a tiered window as a window of its span: named, covered and by age, with its sidecar", async () => {
+ await withCorpus(async ({ paths, clips }) => {
+ await writeFile(path.join(paths.channelsDir, "c", "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube" }));
+ for (const n of ["10.00-20.00.mp4", "10.00-20.00.json", "10.00-20.00.h1080.mp4", "10.00-20.00.h1080.json", "30.00-40.00.h1080.desynced.mp4", "30.00-40.00.h1080.desynced.json", "50.00-60.00.mp4"]) {
+ await writeFile(path.join(clips, n), "media");
+ }
+ const old = new Date(Date.now() - 400 * 86_400_000);
+ await utimes(path.join(clips, "30.00-40.00.h1080.desynced.mp4"), old, old);
+ const named = await evictClipWindows({ paths, slug: "c", id: "v1", windows: [{ from: 10, to: 20 }], olderThanDays: 0 });
+ assert.equal(named.windows, 2);
+ assert.deepEqual((await readdir(clips)).sort(), [
+ "30.00-40.00.h1080.desynced.json",
+ "30.00-40.00.h1080.desynced.mp4",
+ "50.00-60.00.mp4",
+ ]);
+ const aged = await evictClipWindows({ paths, slug: "c", id: "v1", olderThanDays: 30 });
+ assert.equal(aged.windows, 1);
+ assert.deepEqual(await readdir(clips), ["50.00-60.00.mp4"]);
+ });
+});
+
+// C: the tier filter — what a refetch asks. "tiered" leaves the 720 window a
+// site reads; "plain" leaves the taller cuts; a named tiered window is that one.
+test("eviction's tier filter: covering with tiers tiered or plain removes only that kind", async () => {
+ await withCorpus(async ({ paths, clips }) => {
+ await writeFile(path.join(paths.channelsDir, "c", "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube" }));
+ const seed = async () => {
+ for (const n of ["10.00-20.00.mp4", "10.00-20.00.json", "10.00-20.00.h1080.mp4", "10.00-20.00.h1080.json", "10.00-20.00.h1440.mp4"]) {
+ await writeFile(path.join(clips, n), "media");
+ }
+ };
+ await seed();
+ const tall = await evictClipWindows({ paths, slug: "c", id: "v1", covering: [{ from: 12, to: 18 }], tiers: "tiered" });
+ assert.equal(tall.windows, 2);
+ assert.deepEqual((await readdir(clips)).sort(), ["10.00-20.00.json", "10.00-20.00.mp4"]);
+ await seed();
+ const plain = await evictClipWindows({ paths, slug: "c", id: "v1", covering: [{ from: 12, to: 18 }], tiers: "plain" });
+ assert.equal(plain.windows, 1);
+ assert.deepEqual((await readdir(clips)).sort(), ["10.00-20.00.h1080.json", "10.00-20.00.h1080.mp4", "10.00-20.00.h1440.mp4"]);
+ await seed();
+ const one = await evictClipWindows({ paths, slug: "c", id: "v1", windows: [{ from: 10, to: 20, tier: 1080 }] });
+ assert.equal(one.windows, 1);
+ assert.ok(!(await readdir(clips)).includes("10.00-20.00.h1080.mp4"));
+ assert.ok((await readdir(clips)).includes("10.00-20.00.mp4"));
+ });
+});
+
+// G: THE LADDER. Asks of 900, 1000 and 1080 share the 1080 file; a Retry's
+// tier (its spec) wins over today's settings.
+test("tiers snap to the ladder, held to the ceiling; a given tier wins over the settings", async () => {
+ await withCorpus(async ({ paths }) => {
+ for (const ask of [900, 1000, 1080]) {
+ const h = harness();
+ await run(paths, h.deps, ask);
+ assert.equal(h.fetches[0].tier, 1080, String(ask));
+ assert.equal(h.fetches[0].maxHeight, 1080, String(ask));
+ }
+ const over = harness({ windowMaxHeight: 2160 });
+ await run(paths, over.deps, 1200);
+ assert.equal(over.fetches[0].tier, 1440);
+ const held = harness({ windowMaxHeight: 1200 });
+ await run(paths, held.deps, 1200);
+ assert.equal(held.fetches[0].tier, 1200, "a rung above the ceiling is held to it");
+ // A Retry: the spec's 1440, though today's ceiling is 1080.
+ const retry = harness({ windowMaxHeight: 1080 });
+ await fetchWindows({ paths, items: [item], provenance: { requestedBy: "umtool" }, maxHeight: 1440, tier: 1440, gapMs: 0, deps: retry.deps });
+ assert.equal(retry.fetches[0].tier, 1440);
+ });
+});
+
+// D: a PLAIN miss a tiered window holds is cut locally from it, never fetched.
+test("a plain ask that misses, over a span a tiered window holds, is cut from that window; nothing is fetched", async () => {
+ await withCorpus(async ({ paths, clips }) => {
+ await writeFile(path.join(clips, "0.00-30.00.h1080.mp4"), "taller");
+ await writeFile(path.join(clips, "0.00-30.00.h1080.json"), JSON.stringify({ requestedBy: "umtool", height: 1080 }));
+ const h = harness();
+ const lines: string[] = [];
+ const r = await run(paths, h.deps, undefined, lines);
+ assert.deepEqual(h.derived, [{ from: "0.00-30.00.h1080.mp4", to: 20 }]);
+ assert.equal(h.fetches.length, 0);
+ assert.equal(r.cut.length, 1);
+ assert.match(lines.join(""), /cut from clips\/0\.00-30\.00\.h1080\.mp4 into clips\/10\.00-20\.00\.mp4/);
+ // A cut that fails fails the item, as a saved-copy cut does: nothing is fetched.
+ await rm(path.join(clips, "10.00-20.00.mp4"), { force: true });
+ const bad = harness();
+ bad.deps.cutPlainFromTiered = async () => {
+ throw new Error("ffmpeg refused");
+ };
+ const failed = await run(paths, bad.deps);
+ assert.equal(bad.fetches.length, 0);
+ assert.equal(failed.failed[0]?.class, "cut-failed");
+ assert.match(failed.failed[0]?.message ?? "", /cutting it from clips\/0\.00-30\.00\.h1080\.mp4 failed: ffmpeg refused/);
+ });
+});
+
+// H: a tall cut from the saved copy waits while render mode holds the machine.
+test("a tall cut from the saved copy waits out render mode, and says so", async () => {
+ await withCorpus(async ({ paths }) => {
+ let polls = 0;
+ const h = harness({ saved: covers(1080), renderHeld: () => (polls++ < 2 ? "umtool take p --id t, since 13:31" : null) });
+ const lines: string[] = [];
+ const r = await run(paths, h.deps, 1080, lines);
+ assert.equal(h.cuts.length, 1);
+ assert.equal(r.cut.length, 1);
+ assert.equal(h.sleeps.length, 2);
+ const text = lines.join("");
+ assert.match(text, /the 1080p cut\): render mode holds the machine \(umtool take p --id t, since 13:31\) — waiting/);
+ assert.match(text, /render mode ended — waited \d+s/);
+ // A plain cut does not wait.
+ let asked = 0;
+ const plain = harness({ saved: covers(1080), renderHeld: () => (asked++, "held") });
+ await run(paths, plain.deps);
+ assert.equal(asked, 0);
+ assert.equal(plain.cuts.length, 1);
+ });
+});
+
+// 4: a tiered window that is not in sync is no source: set aside, and the plain
+// ask goes on as if it were not there (here: the network).
+test("a desynced tiered window is set aside, not cut from; the plain ask is fetched", async () => {
+ await withCorpus(async ({ paths, clips }) => {
+ await writeFile(path.join(clips, "0.00-30.00.h1080.mp4"), "taller");
+ await writeFile(path.join(clips, "0.00-30.00.h1080.json"), JSON.stringify({ requestedBy: "umtool", height: 1080 }));
+ const h = harness();
+ h.deps.probeWindow = async () => [
+ { codec_type: "video", start_time: "3.200000", duration: "93.733000" },
+ { codec_type: "audio", start_time: "3.140000", duration: "90.580000" },
+ ];
+ const r = await run(paths, h.deps);
+ assert.deepEqual(h.derived, []);
+ assert.equal(h.fetches.length, 1);
+ assert.equal(h.fetches[0].tier, undefined);
+ assert.deepEqual(r.setAside, ["c/v1/clips/0.00-30.00.h1080.desynced.mp4"]);
+ assert.ok((await readdir(clips)).includes("0.00-30.00.h1080.desynced.mp4"));
+ });
+});
+
+// 1: a REFETCH on a tall ask is not answered by the lower 720 window.
+test("a tall refetch over a 720 window: cut at its tier from the saved copy; with none, fetched at its tier", async () => {
+ await withCorpus(async ({ paths, videoDir, clips }) => {
+ await plainWindow(clips, 720);
+ const refetch: FetchWindowsItem = { ...item, refetch: true };
+ // No saved copy: the network, at the tier.
+ const h = harness();
+ const lines: string[] = [];
+ const r = await fetchWindows({ paths, items: [refetch], provenance: { requestedBy: "umtool" }, maxHeight: 1080, gapMs: 0, onLog: (l) => lines.push(l), deps: h.deps });
+ assert.equal(r.cached.length, 0);
+ assert.equal(r.lower, undefined);
+ assert.equal(h.fetches.length, 1);
+ assert.equal(h.fetches[0].tier, 1080);
+ assert.match(lines.join(""), /a refetch — clips\/10\.00-20\.00\.mp4 \(720p\) does not answer it/);
+ // A saved copy (even one no taller): cut again at the tier from it.
+ await writeFile(
+ path.join(videoDir, "saved-video.json"),
+ JSON.stringify({ storedAt: "", dir: "/s", file: "source-media.mp4", bytes: 1, format: { preset: "original", height: 720 } }),
+ );
+ const s = harness({ saved: covers(720) });
+ await fetchWindows({ paths, items: [refetch], provenance: { requestedBy: "umtool" }, maxHeight: 1080, gapMs: 0, deps: s.deps });
+ assert.deepEqual(s.cuts, [{ maxHeight: 1080, from: 10, to: 20 }]);
+ assert.equal(s.fetches.length, 0);
+ // Without the flag the same ask is the 720 window, listed lower.
+ const plain = harness({ saved: covers(720) });
+ const p = await run(paths, plain.deps, 1080);
+ assert.equal(p.cached.length, 1);
+ assert.equal(plain.cuts.length, 0);
+ });
+});
diff --git a/common/lib/clipSettings.ts b/common/lib/clipSettings.ts
@@ -6,8 +6,17 @@ import type { FieldDocs } from "./fieldDocs";
export type ClipsSettings = {
wholeRecordingPlatforms: string[];
+ windowMaxHeight: number;
};
+// THE TALLEST A CLIP WINDOW MAY BE ASKED FOR (lib/clipWindow.ts, the height
+// tier). A CEILING, not a default: a request that names no `maxHeight` is cut
+// and fetched at 720 as it always was, and one that names more is clamped to
+// this. Bounds are the fetch cap's own (MIN/MAX_FETCH_MAX_HEIGHT).
+export const DEFAULT_WINDOW_MAX_HEIGHT = 1080;
+const WINDOW_MAX_HEIGHT_MIN = 144;
+const WINDOW_MAX_HEIGHT_MAX = 2160;
+
// RUMBLE BY DEFAULT, on the evidence (2026-10-23): a window cut by a remote
// seek into Rumble's HLS came out with its picture 1–4 s off its sound 26 times
// in 205; a cut from the saved whole recording measured exactly in sync. One
@@ -15,6 +24,7 @@ export type ClipsSettings = {
// fetch per clip.
export const DEFAULT_CLIPS_SETTINGS: ClipsSettings = {
wholeRecordingPlatforms: ["rumble"],
+ windowMaxHeight: DEFAULT_WINDOW_MAX_HEIGHT,
};
export const CLIPS_SETTINGS_FIELD_DOCS: FieldDocs<ClipsSettings> = {
@@ -25,17 +35,40 @@ export const CLIPS_SETTINGS_FIELD_DOCS: FieldDocs<ClipsSettings> = {
"locally. A failed whole download fails its windows; it never falls back to a seek. A run's " +
"`\"wholeRecording\": false` restores the seek for that run. Default [\"rumble\"] (a Rumble seek put the " +
"picture 1–4 s off the sound in 26 of 205 windows); [] = every platform seeks.",
+ windowMaxHeight:
+ "The tallest source height, in pixels, a clip-window request may ask for (`maxHeight` on fetch-window, " +
+ "fetch-windows, fetch_clip; umtool sends its project's `render.maxHeightSource` only when the project has " +
+ "`render.tallWindows` on). A CEILING, not a default: a request with no `maxHeight` is fetched and cut at 720 as " +
+ "before, and one asking more is clamped to this. A window asked above 720 is a separate cache entry beside the " +
+ "720 one (`<from>-<to>.h<tier>.mp4`, the tier the smallest of 1080, 1440, 2160 at or above the ask, held to this), " +
+ "cut from the saved copy when there is a taller one; the 720 window and every published site's evidence media " +
+ "are never touched. Site-driven fetches (`fetch-windows {\"siteId\"}`, Fetch missing evidence) stay at 720. " +
+ "Default 1080; 144–2160.",
};
+function sanitizeWindowMaxHeight(v: unknown): number {
+ return typeof v === "number" && Number.isInteger(v) && v >= WINDOW_MAX_HEIGHT_MIN && v <= WINDOW_MAX_HEIGHT_MAX
+ ? v
+ : DEFAULT_WINDOW_MAX_HEIGHT;
+}
+
export function sanitizeClips(value: unknown): ClipsSettings {
const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>;
+ const windowMaxHeight = sanitizeWindowMaxHeight(r.windowMaxHeight);
const raw = r.wholeRecordingPlatforms;
- if (!Array.isArray(raw)) return { wholeRecordingPlatforms: [...DEFAULT_CLIPS_SETTINGS.wholeRecordingPlatforms] };
+ if (!Array.isArray(raw)) {
+ return { wholeRecordingPlatforms: [...DEFAULT_CLIPS_SETTINGS.wholeRecordingPlatforms], windowMaxHeight };
+ }
const out: string[] = [];
for (const v of raw) {
if (typeof v !== "string") continue;
const p = v.trim().toLowerCase();
if (p && !out.includes(p)) out.push(p);
}
- return { wholeRecordingPlatforms: out };
+ return { wholeRecordingPlatforms: out, windowMaxHeight };
+}
+
+// The ceiling in force (settings may predate the field).
+export function windowMaxHeightOf(clips: Partial<ClipsSettings> | undefined): number {
+ return sanitizeWindowMaxHeight(clips?.windowMaxHeight);
}
diff --git a/common/lib/clipWindow-server.ts b/common/lib/clipWindow-server.ts
@@ -2,22 +2,24 @@
// layout and for why a `clips/` subdirectory is invisible to every video-dir
// enumerator in the repo.
-import { writeJsonAtomic } from "./jsonFile-server";
+import { readJsonFile, writeJsonAtomic } from "./jsonFile-server";
import path from "node:path";
import { mkdir, readFile, readdir, stat } from "node:fs/promises";
import {
clipsDirFor,
+ clipWindowContains,
clipWindowFile,
clipWindowSidecar,
parseClipProvenance,
hasClipWindowExt,
parseClipWindowName,
+ parseTieredClipWindowName,
tightestClipWindow,
type ClipProvenance,
} from "./clipWindow";
export type ClipWindow = {
- // `<from>-<to>.mp4`, the file's own name.
+ // `<from>-<to>.mp4` (or `<from>-<to>.h<tier>.mp4`), the file's own name.
file: string;
// Absolute path to it.
path: string;
@@ -27,13 +29,28 @@ export type ClipWindow = {
// The sidecar's contents, when there is one. A window fetched before the
// sidecar existed (or one whose sidecar was hand-removed) is still a window.
provenance: ClipProvenance | null;
+ // A TIERED window's tier (clipWindow.ts, the height tier); absent on a plain
+ // one. Listed only with `{tiers: true}`.
+ tier?: number;
+ // The picture height its sidecar records (`height`), read whether or not the
+ // sidecar has a provenance — a height-only sidecar is what a window older
+ // than the field gets after its one probe.
+ height?: number;
};
// Every fetched window in a video dir, oldest-window-first by start second.
//
// A missing `clips/` is an empty list, not an error: most video dirs have none,
// and the video page asks on every render.
-export async function listClipWindows(videoDir: string): Promise<ClipWindow[]> {
+//
+// PLAIN WINDOWS ONLY unless `tiers: true`: every reader that predates the
+// height tier — the fetch dedup, the sync check, live clips — keeps exactly the
+// set it always had. The tall lookups, the video page and the clock
+// retirement ask for the tiers too.
+export async function listClipWindows(
+ videoDir: string,
+ opts: { tiers?: boolean } = {},
+): Promise<ClipWindow[]> {
const dir = clipsDirFor(videoDir);
const entries = await readdir(dir).catch(() => [] as string[]);
const out: ClipWindow[] = [];
@@ -42,19 +59,25 @@ export async function listClipWindows(videoDir: string): Promise<ClipWindow[]> {
// `hasClipWindowExt`. A `.json` sidecar has none of these extensions, so it
// never lists as a window; it is read BY the window it describes.
if (!hasClipWindowExt(name)) continue;
- const span = parseClipWindowName(name);
+ const plain = parseClipWindowName(name);
+ const tiered = plain || !opts.tiers ? null : parseTieredClipWindowName(name);
+ const span = plain ?? tiered;
if (!span) continue;
+ const tier = tiered?.tier;
const abs = path.join(dir, name);
const st = await stat(abs).catch(() => null);
if (!st?.isFile()) continue;
const sidecar = await readFile(
- path.join(dir, clipWindowSidecar(span.from, span.to)),
+ path.join(dir, clipWindowSidecar(span.from, span.to, tier)),
"utf8",
).catch(() => null);
let provenance: ClipProvenance | null = null;
+ let height: number | undefined;
if (sidecar !== null) {
try {
- provenance = parseClipProvenance(JSON.parse(sidecar));
+ const raw = JSON.parse(sidecar) as unknown;
+ provenance = parseClipProvenance(raw);
+ height = heightOfRaw(raw);
} catch {
provenance = null;
}
@@ -66,12 +89,86 @@ export async function listClipWindows(videoDir: string): Promise<ClipWindow[]> {
to: span.to,
bytes: st.size,
provenance,
+ ...(tier !== undefined ? { tier } : {}),
+ ...(height !== undefined ? { height } : {}),
});
}
- out.sort((a, b) => a.from - b.from || a.to - b.to);
+ out.sort((a, b) => a.from - b.from || a.to - b.to || (a.tier ?? 0) - (b.tier ?? 0));
return out;
}
+function heightOfRaw(raw: unknown): number | undefined {
+ const h = (raw as { height?: unknown } | null)?.height;
+ return typeof h === "number" && Number.isInteger(h) && h > 0 ? h : undefined;
+}
+
+// The sidecar beside a window, plain or tiered.
+export function clipWindowSidecarPath(win: Pick<ClipWindow, "path" | "from" | "to" | "tier">): string {
+ return path.join(path.dirname(win.path), clipWindowSidecar(win.from, win.to, win.tier));
+}
+
+// A window's picture height: its sidecar's record, else ONE probe whose answer
+// is merged into the sidecar (created holding only `height` when there was
+// none — it parses as no provenance, exactly as the missing file did), so the
+// next ask reads it. Null when the probe cannot tell (no picture, unreadable);
+// nothing is recorded then. A failed write costs the next ask one probe.
+export async function windowHeightOf(
+ win: ClipWindow,
+ probe: (file: string) => Promise<number | null>,
+): Promise<number | null> {
+ if (win.height !== undefined) return win.height;
+ const h = await probe(win.path);
+ if (h === null) return null;
+ const sidecar = clipWindowSidecarPath(win);
+ const read = await readJsonFile(sidecar);
+ const raw = read.ok && read.value && typeof read.value === "object" && !Array.isArray(read.value)
+ ? (read.value as Record<string, unknown>)
+ : {};
+ await writeJsonAtomic(sidecar, { ...raw, height: h }).catch(() => {});
+ win.height = h;
+ return h;
+}
+
+// A PLAIN MISS'S LOCAL SOURCE: the tightest TIERED window holding [from, to]
+// (lowest tier of equals — the least to decode), or null. A plain window can
+// be cut from it (savedVideoWindow-server cutPlainFromTieredWindow) instead
+// of a fetch.
+export async function tieredWindowHolding(
+ videoDir: string,
+ from: number,
+ to: number,
+): Promise<ClipWindow | null> {
+ const held = (await listClipWindows(videoDir, { tiers: true })).filter(
+ (w) => w.tier !== undefined && clipWindowContains(w, from, to),
+ );
+ held.sort((a, b) => a.to - a.from - (b.to - b.from) || (a.tier ?? 0) - (b.tier ?? 0));
+ return held[0] ?? null;
+}
+
+// THE TALL LOOKUP: of the windows (plain and tiered) holding [from, to], the
+// order a request for `cap` pixels takes them in — the tallest at or under the
+// cap first (the tightest of equals), then those taller than the cap, lowest
+// first (a cached window that is too tall still beats a network fetch). A
+// window of unknown height counts as the lowest. Each window's height is its
+// record, else one probe (windowHeightOf).
+export async function tallClipWindowCandidates(
+ videoDir: string,
+ from: number,
+ to: number,
+ cap: number,
+ probe: (file: string) => Promise<number | null>,
+): Promise<ClipWindow[]> {
+ const holding = (await listClipWindows(videoDir, { tiers: true })).filter((w) =>
+ clipWindowContains(w, from, to),
+ );
+ for (const w of holding) await windowHeightOf(w, probe);
+ const h = (w: ClipWindow) => w.height ?? 0;
+ const span = (w: ClipWindow) => w.to - w.from;
+ const under = holding.filter((w) => h(w) <= cap).sort((a, b) => h(b) - h(a) || span(a) - span(b));
+ const over = holding.filter((w) => h(w) > cap).sort((a, b) => h(a) - h(b) || span(a) - span(b));
+ return [...under, ...over];
+}
+
// The tightest already-fetched window covering [from, to], or null. This is
// what makes a second request for the same seconds free — and what makes a
// deliberately generous fetch BE the next caller's cache rather than a second
@@ -91,10 +188,11 @@ export async function writeClipProvenance(
from: number,
to: number,
provenance: ClipProvenance,
+ tier?: number,
): Promise<string> {
const dir = clipsDirFor(videoDir);
await mkdir(dir, { recursive: true });
- const file = path.join(dir, clipWindowSidecar(from, to));
+ const file = path.join(dir, clipWindowSidecar(from, to, tier));
await writeJsonAtomic(file, provenance);
return file;
}
@@ -105,6 +203,7 @@ export function clipWindowPath(
videoDir: string,
from: number,
to: number,
+ tier?: number,
): string {
- return path.join(clipsDirFor(videoDir), clipWindowFile(from, to));
+ return path.join(clipsDirFor(videoDir), clipWindowFile(from, to, tier));
}
diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts
@@ -83,12 +83,55 @@ export function clipWindowName(from: number, to: number): string {
return `${from.toFixed(2)}-${to.toFixed(2)}`;
}
-export function clipWindowFile(from: number, to: number): string {
- return `${clipWindowName(from, to)}.mp4`;
+// THE HEIGHT TIER (clips.windowMaxHeight). A window asked for ABOVE
+// PLAIN_WINDOW_MAX_HEIGHT is its own cache entry beside the plain one:
+// `<from>-<to>.h<tier>.<ext>`, sidecar `<from>-<to>.h<tier>.json`, the tier
+// being the cap it was cut or fetched under. The plain `<from>-<to>.<ext>` is
+// what every request with no height (or one at or under 720) reads and
+// writes, exactly as before — and the only name a published site's evidence
+// cut (lib/evidenceClip.mjs `windowsFromBareNames`) and umtool's clips-raw
+// parser accept, so a taller cut never changes a byte a site build reads.
+// `listClipWindows({tiers: true})`, `evictClipWindows` and the clock
+// retirement see a tiered window as a window of its span.
+export const PLAIN_WINDOW_MAX_HEIGHT = 720;
+
+// THE LADDER a tier snaps to, so asks of 900, 1000 and 1080 share one file.
+export const WINDOW_TIER_RUNGS = [1080, 1440, 2160] as const;
+
+// The tier a (clamped) cap asks for: none at or under the plain height; else
+// the smallest rung at or above it, held to the ceiling (clips.windowMaxHeight).
+export function windowTierOf(cap: number | undefined, ceiling: number = MAX_FETCH_MAX_HEIGHT): number | undefined {
+ if (cap === undefined || cap <= PLAIN_WINDOW_MAX_HEIGHT) return undefined;
+ const rung = WINDOW_TIER_RUNGS.find((r) => r >= cap) ?? MAX_FETCH_MAX_HEIGHT;
+ return Math.min(rung, ceiling);
}
-export function clipWindowSidecar(from: number, to: number): string {
- return `${clipWindowName(from, to)}.json`;
+// A tier a job spec carries (a Retry runs on the tier it was asked with, not
+// on today's settings): a whole number above the plain height, at most 4K.
+export function isWindowTier(v: unknown): v is number {
+ return typeof v === "number" && Number.isInteger(v) && v > PLAIN_WINDOW_MAX_HEIGHT && v <= MAX_FETCH_MAX_HEIGHT;
+}
+
+// A request's height against the setting's ceiling: absent stays absent (the
+// plain 720 path), and more than the ceiling is the ceiling, said.
+export function clampWindowCap(
+ requested: number | undefined,
+ ceiling: number,
+): { cap: number | undefined; clampedFrom?: number } {
+ if (requested === undefined) return { cap: undefined };
+ return requested > ceiling ? { cap: ceiling, clampedFrom: requested } : { cap: requested };
+}
+
+export function clipWindowStem(from: number, to: number, tier?: number): string {
+ return tier === undefined ? clipWindowName(from, to) : `${clipWindowName(from, to)}.h${tier}`;
+}
+
+export function clipWindowFile(from: number, to: number, tier?: number): string {
+ return `${clipWindowStem(from, to, tier)}.mp4`;
+}
+
+export function clipWindowSidecar(from: number, to: number, tier?: number): string {
+ return `${clipWindowStem(from, to, tier)}.json`;
}
const WINDOW_RE = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/;
@@ -136,6 +179,37 @@ export function parseClipWindowName(
return { from, to };
}
+const TIER_RE = /^(.+)\.h(\d{3,4})$/;
+
+// A stem `<from>-<to>.h<tier>` into its span and tier, or null. The tier must
+// be a fetch cap above the plain height.
+function parseTieredStem(stem: string): { from: number; to: number; tier: number } | null {
+ const m = TIER_RE.exec(stem);
+ if (!m) return null;
+ const tier = Number(m[2]);
+ if (!(tier > PLAIN_WINDOW_MAX_HEIGHT && tier <= MAX_FETCH_MAX_HEIGHT)) return null;
+ const span = parseClipWindowName(m[1]);
+ return span ? { ...span, tier } : null;
+}
+
+// `<from>-<to>.h<tier>.<ext>` — a TIERED window — or null. Never a plain one,
+// a sidecar, a `.part` or a set-aside window.
+export function parseTieredClipWindowName(
+ name: string,
+): { from: number; to: number; tier: number } | null {
+ const ext = clipWindowExtOf(name);
+ if (!ext) return null;
+ return parseTieredStem(name.slice(0, -ext.length));
+}
+
+// A plain or a tiered window's name (`tier` absent on a plain one), or null.
+export function parseAnyClipWindowName(
+ name: string,
+): { from: number; to: number; tier?: number } | null {
+ if (!clipWindowExtOf(name)) return null;
+ return parseClipWindowName(name) ?? parseTieredClipWindowName(name);
+}
+
// A WINDOW SET ASIDE, never deleted: one whose picture runs off its sound
// (lib/clipWindowSync.ts) is renamed `<from>-<to>.desynced.<ext>`, its sidecar
// `<from>-<to>.desynced.json`. The extra segment is what takes it out of every
@@ -151,12 +225,12 @@ export function parseClipWindowName(
// keeps the fetch's mtime, so a set-aside window goes when its fetch would have.
export const DESYNCED_CLIP_WINDOW_TAG = "desynced";
-export function clipWindowDesyncedFile(from: number, to: number, ext = ".mp4"): string {
- return `${clipWindowName(from, to)}.${DESYNCED_CLIP_WINDOW_TAG}${ext}`;
+export function clipWindowDesyncedFile(from: number, to: number, ext = ".mp4", tier?: number): string {
+ return `${clipWindowStem(from, to, tier)}.${DESYNCED_CLIP_WINDOW_TAG}${ext}`;
}
-export function clipWindowDesyncedSidecar(from: number, to: number): string {
- return `${clipWindowName(from, to)}.${DESYNCED_CLIP_WINDOW_TAG}.json`;
+export function clipWindowDesyncedSidecar(from: number, to: number, tier?: number): string {
+ return `${clipWindowStem(from, to, tier)}.${DESYNCED_CLIP_WINDOW_TAG}.json`;
}
// The window extension a name wears (`.mp4`, `.mkv`, `.webm`), or null.
@@ -168,13 +242,14 @@ export function clipWindowExtOf(name: string): string | null {
// counterpart of `parseClipWindowName` for a set-aside window. Never a sidecar.
export function parseDesyncedClipWindowName(
name: string,
-): { from: number; to: number } | null {
+): { from: number; to: number; tier?: number } | null {
const ext = clipWindowExtOf(name);
if (!ext) return null;
const tag = `.${DESYNCED_CLIP_WINDOW_TAG}`;
const stem = name.slice(0, -ext.length);
if (!stem.endsWith(tag)) return null;
- return parseClipWindowName(stem.slice(0, -tag.length));
+ const bare = stem.slice(0, -tag.length);
+ return parseClipWindowName(bare) ?? parseTieredStem(bare);
}
// Who asked for this window, and why. Written beside the file so the video page
@@ -203,10 +278,14 @@ export type ClipProvenance = {
// the media URL its metadata.info.json stores (release 32 R5,
// lib/storedMediaUrl.ts), with that URL's host in `sourceHost`;
// "live-recording" for one cut from a live recording still in progress (live
- // pre-clip's share, lib/livePreclip-server.ts cutLiveWindow). Absent on a
- // window fetched through the page.
+ // pre-clip's share, lib/livePreclip-server.ts cutLiveWindow); "clip-window"
+ // for a plain 720 window cut locally from a taller tiered window of the same
+ // video (`derivedFrom` names it; lib/savedVideoWindow-server.ts
+ // cutPlainFromTieredWindow). Absent on a window fetched through the page.
source?: ClipWindowSource;
sourceHost?: string;
+ // "clip-window": the tiered window's file name this one was cut from.
+ derivedFrom?: string;
// How many times the player's page was opened for this window's cut (release
// 32 R9, ytdlp/storedUrlPageOpen.ts): a stored-URL cut opens it before the
// first cut of each video in a run. Absent when none was.
@@ -228,6 +307,10 @@ export type ClipProvenance = {
// set it aside, and when (`setAsideAt`).
sync?: RecordedClipWindowSync;
setAsideAt?: string;
+ // THE WINDOW'S PICTURE HEIGHT, in pixels, recorded when it was cut or
+ // fetched (or probed once, on its first tall ask, for a window older than
+ // the field). Absent: not known yet, or no picture.
+ height?: number;
// ONE CLOCK PER RECORDING (lane one-clock, lib/recordingClock.mjs): a window
// cut from a saved container through the recording's time map. Its NAME is
// on the cue clock; the container seconds cut were `from`/`to` here, the
@@ -262,7 +345,7 @@ export function coerceClipCopy(v: unknown): ClipCopy | undefined {
return { from: r.from as ClipCopy["from"], url: r.url };
}
-export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url", "live-recording"] as const;
+export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url", "live-recording", "clip-window"] as const;
export type ClipWindowSource = (typeof CLIP_WINDOW_SOURCES)[number];
const str = (v: unknown): string | undefined =>
@@ -304,6 +387,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
}
const sourceHost = str(r.sourceHost);
if (sourceHost) out.sourceHost = sourceHost;
+ const derivedFrom = str(r.derivedFrom);
+ if (derivedFrom) out.derivedFrom = derivedFrom;
const pageOpens = num(r.pageOpens);
if (pageOpens !== undefined && pageOpens > 0) out.pageOpens = pageOpens;
const copy = coerceClipCopy(r.copy);
@@ -319,6 +404,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
if (setAsideAt) out.setAsideAt = setAsideAt;
const clock = coerceClipWindowClock(r.clock);
if (clock) out.clock = clock;
+ const height = num(r.height);
+ if (height !== undefined && Number.isInteger(height) && height > 0) out.height = height;
return out;
}
diff --git a/common/lib/clipWindowSync-server.ts b/common/lib/clipWindowSync-server.ts
@@ -12,9 +12,14 @@ import {
clipWindowDesyncedFile,
clipWindowDesyncedSidecar,
clipWindowExtOf,
- clipWindowSidecar,
+ windowTierOf,
} from "./clipWindow";
-import { listClipWindows, type ClipWindow } from "./clipWindow-server";
+import {
+ clipWindowSidecarPath,
+ listClipWindows,
+ tallClipWindowCandidates,
+ type ClipWindow,
+} from "./clipWindow-server";
import {
parseRecordedClipWindowSync,
windowSyncOf,
@@ -72,8 +77,7 @@ async function readRawSidecar(file: string): Promise<Record<string, unknown> | n
}
}
-const sidecarOf = (win: Pick<ClipWindow, "path" | "from" | "to">) =>
- path.join(path.dirname(win.path), clipWindowSidecar(win.from, win.to));
+const sidecarOf = (win: Pick<ClipWindow, "path" | "from" | "to" | "tier">) => clipWindowSidecarPath(win);
export type ClipWindowJudgement = {
// Null: the window could not be probed, and is kept as it is.
@@ -124,22 +128,23 @@ export async function judgeClipWindow(
// step; a crash before the sidecar moves leaves a sidecar with no window, which
// nothing reads and the next fetch of the span overwrites.
export async function setAsideDesyncedWindow(
- win: Pick<ClipWindow, "path" | "file" | "from" | "to" | "bytes">,
+ win: Pick<ClipWindow, "path" | "file" | "from" | "to" | "bytes" | "tier">,
sync: ClipWindowSync,
now: Date = new Date(),
): Promise<{ file: string; path: string }> {
const dir = path.dirname(win.path);
const ext = clipWindowExtOf(win.file) ?? ".mp4";
- const file = clipWindowDesyncedFile(win.from, win.to, ext);
+ // A tiered window is set aside under its tier: `<from>-<to>.h<tier>.desynced.<ext>`.
+ const file = clipWindowDesyncedFile(win.from, win.to, ext, win.tier);
const dest = path.join(dir, file);
for (const other of CLIP_WINDOW_EXTS) {
- if (other !== ext) await rm(path.join(dir, clipWindowDesyncedFile(win.from, win.to, other)), { force: true });
+ if (other !== ext) await rm(path.join(dir, clipWindowDesyncedFile(win.from, win.to, other, win.tier)), { force: true });
}
await rename(win.path, dest);
const sidecar = sidecarOf(win);
const raw = await readRawSidecar(sidecar);
const at = now.toISOString();
- await writeJsonAtomic(path.join(dir, clipWindowDesyncedSidecar(win.from, win.to)), {
+ await writeJsonAtomic(path.join(dir, clipWindowDesyncedSidecar(win.from, win.to, win.tier)), {
...(raw ?? {}),
sync: { ...sync, bytes: win.bytes, checkedAt: at },
setAsideAt: at,
@@ -162,15 +167,54 @@ export type DesyncedClipWindow = {
// a planner that only needs to know whether the span is held) and the next
// candidate is asked; none left is null — the span is missing, and the caller
// goes to the saved-video tier, then the network, as for any missing span.
+//
+// A TALL ASK (`maxHeight` above the plain 720, with `heightProbe`) takes the
+// plain and the tiered windows in tallClipWindowCandidates' order — the
+// tallest at or under the cap first — and the hit carries its `height`. Any
+// other ask is exactly as before: plain windows, tightest first, no height.
export async function findInSyncContainingClipWindow(
videoDir: string,
from: number,
to: number,
+ opts: {
+ probe: WindowStreamProbe;
+ setAside?: boolean;
+ record?: boolean;
+ maxHeight?: number;
+ heightProbe?: (file: string) => Promise<number | null>;
+ },
+): Promise<{ hit: ClipWindow | null; desynced: DesyncedClipWindow[] }> {
+ const tall = windowTierOf(opts.maxHeight) !== undefined && opts.heightProbe;
+ const candidates = tall
+ ? await tallClipWindowCandidates(videoDir, from, to, opts.maxHeight!, opts.heightProbe!)
+ : (await listClipWindows(videoDir))
+ .filter((w) => clipWindowContains(w, from, to))
+ .sort((a, b) => a.to - a.from - (b.to - b.from));
+ const desynced: DesyncedClipWindow[] = [];
+ for (const w of candidates) {
+ const { sync } = await judgeClipWindow(w, { probe: opts.probe, record: opts.record });
+ if (!sync || sync.ok) return { hit: w, desynced };
+ const aside = opts.setAside === false ? null : await setAsideDesyncedWindow(w, sync);
+ desynced.push({ window: w, sync, setAsideAs: aside?.file ?? null });
+ }
+ return { hit: null, desynced };
+}
+
+// THE TIERED WINDOW A PLAIN MISS MAY BE CUT FROM (the height tier, D) — only
+// one that is in sync, judged exactly as a window is when it is used: the
+// tiered windows holding [from, to], tightest first (lowest tier of equals);
+// a desynced one is set aside as usual (unless `setAside: false`, a planner)
+// and the next asked; none left is null — the plain ask goes on as if there
+// were no tiered window at all.
+export async function findInSyncTieredWindowHolding(
+ videoDir: string,
+ from: number,
+ to: number,
opts: { probe: WindowStreamProbe; setAside?: boolean; record?: boolean },
): Promise<{ hit: ClipWindow | null; desynced: DesyncedClipWindow[] }> {
- const candidates = (await listClipWindows(videoDir))
- .filter((w) => clipWindowContains(w, from, to))
- .sort((a, b) => a.to - a.from - (b.to - b.from));
+ const candidates = (await listClipWindows(videoDir, { tiers: true }))
+ .filter((w) => w.tier !== undefined && clipWindowContains(w, from, to))
+ .sort((a, b) => a.to - a.from - (b.to - b.from) || (a.tier ?? 0) - (b.tier ?? 0));
const desynced: DesyncedClipWindow[] = [];
for (const w of candidates) {
const { sync } = await judgeClipWindow(w, { probe: opts.probe, record: opts.record });
diff --git a/common/lib/clipWindowTier-server.ts b/common/lib/clipWindowTier-server.ts
@@ -0,0 +1,86 @@
+// A TALL ASK OVER A LOWER CACHED WINDOW (the height tier, lib/clipWindow.ts).
+//
+// A request for more than 720 pixels finds, at best, a window lower than it
+// asked (the plain 720 one, say). That window is never replaced, retired or
+// re-fetched for its height (operator rulings, 13 Nov): a TALLER cut is made
+// beside it only from the video's saved copy, and only when that copy is
+// taller than the window — `min(cap, the saved copy's height)` is the most the
+// disk can give. Otherwise the lower window is what the ask gets, with the
+// reason. Nothing fetches a taller window from the network over a lower one:
+// persisting the video gives it a copy to cut from.
+//
+// Cheap first: the pointer's recorded height (`format`, else `probed`) settles
+// most asks with no probe; the saved container is probed (savedWindowSource)
+// only when the pointer cannot rule the cut out.
+//
+// SERVER-ONLY.
+
+import type { Paths } from "./paths";
+import { loadSavedVideo, recordSavedVideoProbedHeight } from "./savedVideo-server";
+import { savedWindowSource, type SavedWindowSource } from "./savedVideoWindow-server";
+import { fittedHeight } from "./evidenceClip-server";
+
+export type TallerFromSaved =
+ | { kind: "cut"; source: Extract<SavedWindowSource, { kind: "covers" }>; height: number }
+ // The window is already as tall as the saved copy gives inside the cap's
+ // box (an ultrawide source fits a 1080 box at 810): nothing to cut, and not
+ // "lower" in any way a cut could fix.
+ | { kind: "best"; height: number }
+ | { kind: "lower"; why: string };
+
+export const NO_SAVED_COPY_WHY =
+ "no saved copy of the recording to cut a taller one from — the lower window is used as it is; " +
+ "persist the video (persist-videos) to give it one, or refetch it (umtool fetch --refetch) to fetch it taller";
+
+export async function tallerFromSaved(opts: {
+ paths: Pick<Paths, "transcriptsDir" | "savedVideosDir" | "ffprobeBin">;
+ slug: string;
+ videoDir: string;
+ from: number;
+ to: number;
+ // The best cached window's height (null: unknown, counted as lowest).
+ hitHeight: number | null;
+ cap: number;
+ // Injectable for the tests.
+ source?: typeof savedWindowSource;
+}): Promise<TallerFromSaved> {
+ const pointer = await loadSavedVideo(opts.videoDir);
+ if (!pointer) return { kind: "lower", why: NO_SAVED_COPY_WHY };
+ const have = opts.hitHeight ?? 0;
+ const recorded = pointer.format?.height ?? pointer.probed?.height;
+ if (recorded !== undefined && Math.min(opts.cap, recorded) <= have) {
+ return { kind: "lower", why: `the saved copy is ${recorded}p, no taller than the window` };
+ }
+ const source = await (opts.source ?? savedWindowSource)({
+ paths: opts.paths,
+ slug: opts.slug,
+ videoDir: opts.videoDir,
+ from: opts.from,
+ to: opts.to,
+ });
+ if (source.kind === "unreadable") {
+ return { kind: "lower", why: `the saved copy cannot be read now (${source.error})` };
+ }
+ if (source.kind !== "covers") {
+ return { kind: "lower", why: "the saved copy does not hold this span" };
+ }
+ const savedHeight = source.probe.height ?? recorded ?? null;
+ if (!source.probe.hasVideo || savedHeight === null) {
+ return { kind: "lower", why: "the saved copy's picture height cannot be read" };
+ }
+ // A pointer with no height gets the probe's, so the next ask is answered
+ // from the pointer (a failed write costs that ask a probe, nothing else).
+ if (recorded === undefined && source.probe.height) {
+ await recordSavedVideoProbedHeight(opts.videoDir, pointer.file, source.probe.height).catch(() => false);
+ }
+ // WHAT A CUT WOULD BE: the copy's picture fitted inside the cap's 16:9 box
+ // (the cut's own arithmetic) — not min(cap, height), which an ultrawide copy
+ // never reaches, so it would be cut again on every ask.
+ const best = fittedHeight(source.probe.width, source.probe.height, opts.cap) ?? Math.min(opts.cap, savedHeight);
+ if (best <= have) {
+ return have >= best && opts.hitHeight !== null
+ ? { kind: "best", height: best }
+ : { kind: "lower", why: `the saved copy gives ${best}p in the ${opts.cap}p box, no taller than the window` };
+ }
+ return { kind: "cut", source, height: best };
+}
diff --git a/common/lib/clipWindowTier.test.ts b/common/lib/clipWindowTier.test.ts
@@ -0,0 +1,268 @@
+// THE HEIGHT TIER (lib/clipWindow.ts): a window asked above 720 is its own
+// cache entry beside the plain one. The names, the listing, the one-probe
+// height record, the tall lookup's order and the taller-from-saved decision —
+// temp dirs, stubbed probes, no media. (Eviction: controller/fetchWindowsTier.test.ts.)
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/clipWindowTier.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import {
+ clampWindowCap,
+ clipWindowDesyncedFile,
+ clipWindowFile,
+ clipWindowSidecar,
+ parseAnyClipWindowName,
+ parseClipWindowName,
+ parseDesyncedClipWindowName,
+ parseTieredClipWindowName,
+ windowTierOf,
+} from "./clipWindow";
+import {
+ listClipWindows,
+ tallClipWindowCandidates,
+ windowHeightOf,
+} from "./clipWindow-server";
+import { findInSyncContainingClipWindow } from "./clipWindowSync-server";
+import { tallerFromSaved, NO_SAVED_COPY_WHY } from "./clipWindowTier-server";
+import { evidenceCutArgs, fittedHeight } from "./evidenceClip-server";
+import { resolveCorpusSource, windowsFromBareNames } from "./evidenceClip.mjs";
+import { DEFAULT_CLIPS_SETTINGS, sanitizeClips, windowMaxHeightOf } from "./clipSettings";
+import type { Paths } from "./paths";
+import type { SavedWindowSource } from "./savedVideoWindow-server";
+
+async function withVideo(fn: (o: { root: string; videoDir: string; clips: string; paths: Paths }) => Promise<void>) {
+ const root = await mkdtemp(path.join(tmpdir(), "clip-tier-"));
+ const channelsDir = path.join(root, "channels");
+ const videoDir = path.join(channelsDir, "demo", "data", "v1");
+ const clips = path.join(videoDir, "clips");
+ await mkdir(clips, { recursive: true });
+ await writeFile(path.join(channelsDir, "demo", "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube" }));
+ const paths = {
+ transcriptsDir: root,
+ channelsDir,
+ savedVideosDir: path.join(root, "saved"),
+ ffprobeBin: "/nonexistent/ffprobe",
+ } as Paths;
+ try {
+ await fn({ root, videoDir, clips, paths });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+const put = (dir: string, name: string, body = "media") => writeFile(path.join(dir, name), body);
+
+test("names: a tiered window is <from>-<to>.h<tier>.<ext>; the plain parser never takes one", () => {
+ assert.equal(clipWindowFile(10, 20), "10.00-20.00.mp4");
+ assert.equal(clipWindowFile(10, 20, 1080), "10.00-20.00.h1080.mp4");
+ assert.equal(clipWindowSidecar(10, 20, 1080), "10.00-20.00.h1080.json");
+ assert.equal(clipWindowDesyncedFile(10, 20, ".mp4", 1080), "10.00-20.00.h1080.desynced.mp4");
+ assert.equal(parseClipWindowName("10.00-20.00.h1080.mp4"), null);
+ assert.deepEqual(parseTieredClipWindowName("10.00-20.00.h1080.mp4"), { from: 10, to: 20, tier: 1080 });
+ assert.deepEqual(parseAnyClipWindowName("10.00-20.00.mp4"), { from: 10, to: 20 });
+ assert.deepEqual(parseAnyClipWindowName("10.00-20.00.h1440.webm"), { from: 10, to: 20, tier: 1440 });
+ assert.deepEqual(parseDesyncedClipWindowName("10.00-20.00.h1080.desynced.mp4"), { from: 10, to: 20, tier: 1080 });
+ // Not windows: a part, a sidecar, a tier at or under 720, a tier above 4K.
+ for (const n of ["10.00-20.00.h1080.part.mp4", "10.00-20.00.h1080.json", "10.00-20.00.h720.mp4", "10.00-20.00.h4320.mp4"]) {
+ assert.equal(parseAnyClipWindowName(n), null, n);
+ }
+ // A site's evidence cut and umtool's raw parser read bare names only.
+ assert.deepEqual(windowsFromBareNames(["10.00-20.00.mp4", "10.00-20.00.h1080.mp4"], "/c").map((w) => w.name), ["10.00-20.00.mp4"]);
+});
+
+test("the tier and the ceiling: no ask is the plain path; above the ceiling is clamped and said", () => {
+ assert.equal(windowTierOf(undefined), undefined);
+ assert.equal(windowTierOf(720), undefined);
+ assert.equal(windowTierOf(480), undefined);
+ assert.equal(windowTierOf(1080), 1080);
+ // THE LADDER: 900, 1000, 1080 share one file; held to the ceiling.
+ assert.equal(windowTierOf(900, 1080), 1080);
+ assert.equal(windowTierOf(1000, 1080), 1080);
+ assert.equal(windowTierOf(1200, 2160), 1440);
+ assert.equal(windowTierOf(1600, 2160), 2160);
+ assert.equal(windowTierOf(1200, 1200), 1200);
+ assert.equal(windowTierOf(721, 900), 900);
+ assert.deepEqual(clampWindowCap(undefined, 1080), { cap: undefined });
+ assert.deepEqual(clampWindowCap(1080, 1080), { cap: 1080 });
+ assert.deepEqual(clampWindowCap(2160, 1080), { cap: 1080, clampedFrom: 2160 });
+ assert.equal(DEFAULT_CLIPS_SETTINGS.windowMaxHeight, 1080);
+ assert.equal(sanitizeClips({}).windowMaxHeight, 1080);
+ assert.equal(sanitizeClips({ windowMaxHeight: 1440 }).windowMaxHeight, 1440);
+ assert.equal(sanitizeClips({ windowMaxHeight: 99 }).windowMaxHeight, 1080);
+ assert.equal(sanitizeClips({ windowMaxHeight: 1080.5 }).windowMaxHeight, 1080);
+ assert.equal(windowMaxHeightOf(undefined), 1080);
+ assert.deepEqual(sanitizeClips({ wholeRecordingPlatforms: ["Rumble"] }), { wholeRecordingPlatforms: ["rumble"], windowMaxHeight: 1080 });
+});
+
+test("the cut box: evidence stays 1280x720; a tier's box is its 16:9, never upscaled", () => {
+ const evidence = evidenceCutArgs("/in.mp4", 1, 2, "video", "/out");
+ assert.ok(evidence.includes("scale='min(1280,iw)':'min(720,ih)':force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p"));
+ const tall = evidenceCutArgs("/in.mp4", 1, 2, "video", "/out", 1080);
+ assert.ok(tall.includes("scale='min(1920,iw)':'min(1080,ih)':force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p"));
+ assert.equal(fittedHeight(1920, 1080), 720);
+ assert.equal(fittedHeight(1920, 1080, 1080), 1080);
+ assert.equal(fittedHeight(640, 360, 1080), 360);
+ assert.equal(fittedHeight(3840, 2160, 1080), 1080);
+ assert.equal(fittedHeight(1080, 1920, 1080), 1080);
+ assert.equal(fittedHeight(null, null, 1080), null);
+});
+
+test("listing: plain only by default; with tiers, each window with its tier and recorded height", async () => {
+ await withVideo(async ({ videoDir, clips }) => {
+ await put(clips, "10.00-20.00.mp4");
+ await put(clips, "10.00-20.00.json", JSON.stringify({ requestedBy: "umtool", height: 720 }));
+ await put(clips, "10.00-20.00.h1080.mp4", "taller");
+ await put(clips, "10.00-20.00.h1080.json", JSON.stringify({ requestedBy: "umtool", height: 1080 }));
+ await put(clips, "10.00-20.00.h1080.part.mp4", "in flight");
+ assert.deepEqual((await listClipWindows(videoDir)).map((w) => w.file), ["10.00-20.00.mp4"]);
+ const all = await listClipWindows(videoDir, { tiers: true });
+ assert.deepEqual(
+ all.map((w) => [w.file, w.tier ?? null, w.height ?? null, w.provenance?.height ?? null]),
+ [
+ ["10.00-20.00.mp4", null, 720, 720],
+ ["10.00-20.00.h1080.mp4", 1080, 1080, 1080],
+ ],
+ );
+ });
+});
+
+test("a window with no recorded height is probed ONCE; the answer goes into its sidecar (made when missing)", async () => {
+ await withVideo(async ({ videoDir, clips }) => {
+ await put(clips, "10.00-20.00.mp4");
+ await put(clips, "10.00-20.00.json", JSON.stringify({ requestedBy: "umtool", reason: "kept" }));
+ await put(clips, "30.00-40.00.mp4");
+ const before = await stat(path.join(clips, "10.00-20.00.mp4"));
+ const calls: string[] = [];
+ const probe = async (f: string) => {
+ calls.push(path.basename(f));
+ return 360;
+ };
+ for (const w of await listClipWindows(videoDir)) assert.equal(await windowHeightOf(w, probe), 360);
+ assert.deepEqual(calls.sort(), ["10.00-20.00.mp4", "30.00-40.00.mp4"]);
+ // Merged: the provenance is kept beside the height.
+ assert.deepEqual(JSON.parse(await readFile(path.join(clips, "10.00-20.00.json"), "utf8")), {
+ requestedBy: "umtool",
+ reason: "kept",
+ height: 360,
+ });
+ // Made: a height-only sidecar, which parses as no provenance.
+ assert.deepEqual(JSON.parse(await readFile(path.join(clips, "30.00-40.00.json"), "utf8")), { height: 360 });
+ // The next ask reads the record: no probe.
+ for (const w of await listClipWindows(videoDir)) await windowHeightOf(w, probe);
+ assert.equal(calls.length, 2);
+ // The window itself is not touched.
+ assert.equal((await stat(path.join(clips, "10.00-20.00.mp4"))).mtimeMs, before.mtimeMs);
+ // Unreadable: nothing recorded.
+ await put(clips, "50.00-60.00.mp4");
+ const w = (await listClipWindows(videoDir)).find((x) => x.from === 50)!;
+ assert.equal(await windowHeightOf(w, async () => null), null);
+ assert.ok(!(await readdir(clips)).includes("50.00-60.00.json"));
+ });
+});
+
+test("the tall lookup: the tallest at or under the ask first, then a taller one; unknown is lowest", async () => {
+ await withVideo(async ({ videoDir, clips }) => {
+ await put(clips, "0.00-60.00.mp4");
+ await put(clips, "0.00-60.00.json", JSON.stringify({ height: 720 }));
+ await put(clips, "5.00-25.00.mp4");
+ await put(clips, "5.00-25.00.json", JSON.stringify({ height: 720 }));
+ await put(clips, "0.00-60.00.h1080.mp4");
+ await put(clips, "0.00-60.00.h1080.json", JSON.stringify({ height: 1080 }));
+ await put(clips, "0.00-60.00.h1440.mp4");
+ await put(clips, "0.00-60.00.h1440.json", JSON.stringify({ height: 1440 }));
+ await put(clips, "8.00-22.00.mp4");
+ const order = await tallClipWindowCandidates(videoDir, 10, 20, 1080, async () => null);
+ assert.deepEqual(order.map((w) => w.file), [
+ "0.00-60.00.h1080.mp4",
+ // Two at 720: the tighter first.
+ "5.00-25.00.mp4",
+ "0.00-60.00.mp4",
+ // Unknown height counts as the lowest.
+ "8.00-22.00.mp4",
+ // Taller than asked: still a hit before any fetch.
+ "0.00-60.00.h1440.mp4",
+ ]);
+ // The sync-checked lookup: a tall ask gets the 1080; any other ask the plain tightest, as before.
+ const tall = await findInSyncContainingClipWindow(videoDir, 10, 20, { probe: async () => null, maxHeight: 1080, heightProbe: async () => null });
+ assert.equal(tall.hit?.file, "0.00-60.00.h1080.mp4");
+ assert.equal(tall.hit?.height, 1080);
+ const plain = await findInSyncContainingClipWindow(videoDir, 10, 20, { probe: async () => null });
+ assert.equal(plain.hit?.file, "8.00-22.00.mp4");
+ const at720 = await findInSyncContainingClipWindow(videoDir, 10, 20, { probe: async () => null, maxHeight: 720, heightProbe: async () => null });
+ assert.equal(at720.hit?.file, "8.00-22.00.mp4");
+ });
+});
+
+const covers = (height: number | null, hasVideo = true): SavedWindowSource =>
+ ({
+ kind: "covers",
+ pointer: { storedAt: "", dir: "/s", file: "source-media.mp4", bytes: 1 },
+ container: "/s/source-media.mp4",
+ durationSec: 100,
+ probe: { durationSec: 100, width: height ? Math.round((height * 16) / 9) : null, height, hasVideo, hasAudio: true },
+ }) as SavedWindowSource;
+
+async function pointer(videoDir: string, format?: { height: number }) {
+ await writeFile(
+ path.join(videoDir, "saved-video.json"),
+ JSON.stringify({ storedAt: "2026-11-13T00:00:00.000Z", dir: "/s", file: "source-media.mp4", bytes: 1, ...(format ? { format: { preset: "original", ...format } } : {}) }),
+ );
+}
+
+test("taller from the saved copy: only when the copy is taller than the window; no copy is the window as it is", async () => {
+ await withVideo(async ({ videoDir, paths }) => {
+ const base = { paths, slug: "demo", videoDir, from: 10, to: 20, cap: 1080 };
+ // No saved copy: lower, and never a fetch.
+ assert.deepEqual(await tallerFromSaved({ ...base, hitHeight: 720 }), { kind: "lower", why: NO_SAVED_COPY_WHY });
+ // A recorded 720 copy rules it out without a probe.
+ await pointer(videoDir, { height: 720 });
+ let asked = 0;
+ const src = (s: SavedWindowSource) => async () => {
+ asked += 1;
+ return s;
+ };
+ const r1 = await tallerFromSaved({ ...base, hitHeight: 720, source: src(covers(720)) });
+ assert.equal(r1.kind, "lower");
+ assert.match((r1 as { why: string }).why, /saved copy is 720p/);
+ assert.equal(asked, 0);
+ // A 1080 copy: cut at 1080.
+ await pointer(videoDir, { height: 1080 });
+ const r2 = await tallerFromSaved({ ...base, hitHeight: 720, source: src(covers(1080)) });
+ assert.equal(r2.kind, "cut");
+ assert.equal((r2 as { height: number }).height, 1080);
+ // A 1440 copy with no recorded height, asked 1080: cut at the ask, and the
+ // probed height kept on the pointer so the next ask needs no probe (I).
+ await pointer(videoDir);
+ const r3 = await tallerFromSaved({ ...base, hitHeight: null, source: src(covers(1440)) });
+ assert.equal((r3 as { height: number }).height, 1080);
+ assert.equal(JSON.parse(await readFile(path.join(videoDir, "saved-video.json"), "utf8")).probed.height, 1440);
+ // A copy that does not hold the span, or has no picture: lower, with why.
+ const r4 = await tallerFromSaved({ ...base, hitHeight: 720, source: async () => ({ kind: "not-covering", container: "/s", durationSec: 5 }) });
+ assert.match((r4 as { why: string }).why, /does not hold this span/);
+ const r5 = await tallerFromSaved({ ...base, hitHeight: 720, source: src(covers(null, false)) });
+ assert.match((r5 as { why: string }).why, /cannot be read/);
+ });
+});
+
+test("a site's evidence lookup reads the plain window even beside a taller one; a tall ask reads the taller", async () => {
+ await withVideo(async ({ clips, root }) => {
+ await put(clips, "10.00-20.00.mp4");
+ await put(clips, "10.00-20.00.json", JSON.stringify({ requestedBy: "reports", height: 720 }));
+ await put(clips, "0.00-30.00.h1080.mp4");
+ await put(clips, "0.00-30.00.h1080.json", JSON.stringify({ requestedBy: "umtool", height: 1080 }));
+ const channelsDir = path.join(root, "channels");
+ const want = { video: "v1", slug: "demo", from: 12, to: 18 };
+ const site = await resolveCorpusSource(want, { channelsDir, platform: "youtube" });
+ assert.equal(site?.name, "10.00-20.00.mp4");
+ const tall = await resolveCorpusSource(want, { channelsDir, platform: "youtube", maxHeight: 1080, probe: async () => null });
+ assert.equal(tall?.name, "0.00-30.00.h1080.mp4");
+ assert.equal(tall?.height, 1080);
+ // At or under 720 the ask is the plain path.
+ const at720 = await resolveCorpusSource(want, { channelsDir, platform: "youtube", maxHeight: 720 });
+ assert.equal(at720?.name, "10.00-20.00.mp4");
+ });
+});
diff --git a/common/lib/evidenceClip-server.ts b/common/lib/evidenceClip-server.ts
@@ -208,13 +208,57 @@ export function evidenceHash(source: SourceIdentity, span: EvidenceSpan, kind: E
}
// The video filter: fit inside the box, never upscale, even sides.
-const FIT_FILTER =
- `scale='min(${EVIDENCE_MAX_WIDTH},iw)':'min(${EVIDENCE_MAX_HEIGHT},ih)'` +
- ":force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p";
+function fitFilter(maxHeight: number): string {
+ const maxWidth = maxHeight === EVIDENCE_MAX_HEIGHT ? EVIDENCE_MAX_WIDTH : fitBoxWidth(maxHeight);
+ return (
+ `scale='min(${maxWidth},iw)':'min(${maxHeight},ih)'` +
+ ":force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p"
+ );
+}
+
+// A 16:9 box for a height, its width even (1080 → 1920).
+export function fitBoxWidth(maxHeight: number): number {
+ return Math.round((maxHeight * 16) / 9 / 2) * 2;
+}
+
+// The height a picture of `width`×`height` comes out at inside the box for
+// `maxHeight` — the filter above, computed THE WAY FFMPEG DOES
+// (libavfilter scale_eval.c, ff_scale_adjust_dimensions): the expressions give
+// w = min(boxW, iw), h = min(boxH, ih); `force_original_aspect_ratio=decrease`
+// then takes w = min(w, round(h·iw/ih)) and h = min(h, round(w·ih/iw)) from
+// those (av_rescale rounds to nearest), and `force_divisible_by=2` rounds each
+// DOWN to even. So 1366×768 in the 720 box is 1280×720, as ffmpeg writes it.
+// A tiered cut records this instead of probing what it wrote. Null for a size
+// it was not told.
+export function fittedHeight(
+ width: number | null,
+ height: number | null,
+ maxHeight: number = EVIDENCE_MAX_HEIGHT,
+): number | null {
+ if (!width || !height || width <= 0 || height <= 0) return null;
+ const boxW = maxHeight === EVIDENCE_MAX_HEIGHT ? EVIDENCE_MAX_WIDTH : fitBoxWidth(maxHeight);
+ const w0 = Math.min(boxW, width);
+ const h0 = Math.min(maxHeight, height);
+ const h = Math.min(h0, Math.round((w0 * height) / width));
+ const even = h - (h % 2);
+ return even > 0 ? even : null;
+}
// The ffmpeg arguments that cut [a, b] seconds INTO `file` as `kind`, writing
// `out` (whose name need not carry an extension: the muxer is named).
-export function evidenceCutArgs(file: string, a: number, b: number, kind: EvidenceKind, out: string): string[] {
+//
+// `maxHeight` is the box's height (16:9). Absent, the evidence box, 1280×720:
+// a report site's evidence clip is ALWAYS cut so (publish/reportMedia.ts and
+// composeReports pass none). A clip window asked for taller (the height tier,
+// lib/clipWindow.ts) passes its tier.
+export function evidenceCutArgs(
+ file: string,
+ a: number,
+ b: number,
+ kind: EvidenceKind,
+ out: string,
+ maxHeight: number = EVIDENCE_MAX_HEIGHT,
+): string[] {
const common = ["-map_metadata", "-1", "-sn", "-dn"];
const audio = ["-c:a", "aac", "-b:a", EVIDENCE_AUDIO_BITRATE, "-ac", "2"];
const tail = ["-movflags", "+faststart", "-f", "mp4", out];
@@ -226,7 +270,7 @@ export function evidenceCutArgs(file: string, a: number, b: number, kind: Eviden
...head,
"-map", "0:v:0",
"-map", "0:a:0?",
- "-vf", FIT_FILTER,
+ "-vf", fitFilter(maxHeight),
"-c:v", "libx264", "-preset", "medium", "-profile:v", "high", "-crf", String(EVIDENCE_CRF),
...audio,
...common,
diff --git a/common/lib/evidenceClip.mjs b/common/lib/evidenceClip.mjs
@@ -60,6 +60,24 @@ export const WIN_EPS = 0.02;
export const WINDOW_RE = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/;
+// THE HEIGHT TIER (lib/clipWindow.ts PLAIN_WINDOW_MAX_HEIGHT and its tiered
+// names): a window asked above 720 is `<from>-<to>.h<tier>.<ext>` beside the
+// plain one. Re-stated here: this file runs under bare node.
+export const PLAIN_WINDOW_MAX_HEIGHT = 720;
+const TIERED_RE = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)\.h(\d{3,4})$/;
+
+/** Is `maxHeight` a tall ask (above the plain 720)? */
+export const isTallAsk = (maxHeight) => Number.isFinite(maxHeight) && maxHeight > PLAIN_WINDOW_MAX_HEIGHT;
+
+// THE LADDER the editor snaps a tall ask to (lib/clipWindow.ts
+// WINDOW_TIER_RUNGS): an ask of 900 or 1000 is the 1080 file, 1200 the 1440.
+// A tall resolve takes the rung as its cap, so the editor's `.h1080` window is
+// what a project asking 900 gets, not "too tall".
+export const WINDOW_TIER_RUNGS = Object.freeze([1080, 1440, 2160]);
+
+/** The rung a tall ask snaps to (the editor's tier before its setting holds it). */
+export const tierRungOf = (maxHeight) => WINDOW_TIER_RUNGS.find((r) => r >= maxHeight) ?? 2160;
+
/**
* A directory listing, or [] for a directory that is not there.
* @param {string} dir
@@ -80,9 +98,16 @@ export async function listNames(dir) {
* @typedef {{ name: string, path: string, from: number, to: number, height?: number, clock?: SourceClock }} SourceWindow
* @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number, clock?: SourceClock }} LocalSource
* @typedef {(file: string) => Promise<{ duration: number, height?: number } | null>} SourceProbe
- * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe, platform?: string | null, want?: { from: number, to: number } }} TierContext
+ * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe, platform?: string | null, want?: { from: number, to: number }, maxHeight?: number, heightOf?: (kind: string, w: SourceWindow) => Promise<number | null> }} TierContext
* `want`: the span being resolved, when there is one (resolveFromTiers sets it) -- the
- * saved-video tier maps it through the recording's clock
+ * saved-video tier maps it through the recording's clock.
+ * `maxHeight`: THE HEIGHT ASKED (umtool's render.maxHeightSource). Above
+ * PLAIN_WINDOW_MAX_HEIGHT the corpus tier lists the TIERED windows too
+ * (`<from>-<to>.h<tier>.<ext>`, lib/clipWindow.ts) and resolveFromTiers
+ * takes the tallest the disk holds up to it (tallResolve). Absent -- every
+ * report site's evidence cut -- exactly the plain windows, as before.
+ * `heightOf`: a window's height when its tier did not say (default: one
+ * probe per file per process)
* @typedef {{ kind: string, windows: (ctx: TierContext) => Promise<SourceWindow[]>, audio?: boolean }} SourceTier
*/
@@ -177,6 +202,45 @@ export function windowsFromBareNames(names, dir) {
return out;
}
+/**
+ * The TIERED windows in a corpus clips dir, `<from>-<to>.h<tier>.<ext>`, each
+ * with its `tier`. Never a plain window, a sidecar, a `.part` or a set-aside
+ * one. Read only for a tall ask -- see corpusWindows.
+ * @param {string[]} names
+ * @param {string} dir
+ * @returns {(SourceWindow & { tier: number })[]}
+ */
+export function tieredWindowsFromNames(names, dir) {
+ const out = [];
+ for (const name of names) {
+ const ext = CORPUS_WINDOW_EXTS.find((x) => name.endsWith(x));
+ if (!ext) continue;
+ const m = TIERED_RE.exec(name.slice(0, -ext.length));
+ if (!m) continue;
+ const from = Number(m[1]);
+ const to = Number(m[2]);
+ const tier = Number(m[3]);
+ if (!(to > from) || !(tier > PLAIN_WINDOW_MAX_HEIGHT)) continue;
+ out.push({ name, path: path.join(/* turbopackIgnore: true */ dir, name), from, to, tier });
+ }
+ return out;
+}
+
+/**
+ * The `height` a corpus window's sidecar records (`<stem>.json`), or undefined.
+ * @param {string} windowPath
+ */
+async function sidecarHeight(windowPath) {
+ const ext = CORPUS_WINDOW_EXTS.find((x) => windowPath.endsWith(x));
+ if (!ext) return undefined;
+ try {
+ const h = Number(JSON.parse(await readFile(windowPath.slice(0, -ext.length) + ".json", "utf8"))?.height);
+ return Number.isInteger(h) && h > 0 ? h : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
export const SAVED_VIDEO_POINTER = "saved-video.json";
// lib/mediaFiles.ts's anchored `source-media.<ext>`, over its
@@ -297,10 +361,20 @@ export async function ffprobeSource(file, bin = process.env.FFPROBE_BIN ?? "ffpr
// channelsDir or slug) lists nothing.
/** @param {TierContext} ctx */
-async function corpusWindows({ video, slug, channelsDir, platform }) {
+async function corpusWindows({ video, slug, channelsDir, platform, maxHeight }) {
if (!channelsDir || !slug) return [];
const dir = corpusClipsDir(await recordDirOf(channelsDir, slug, video, platform));
- return windowsFromBareNames(await listNames(dir), dir);
+ const names = await listNames(dir);
+ const plain = windowsFromBareNames(names, dir);
+ if (!isTallAsk(maxHeight)) return plain;
+ // A TALL ASK: the tiered windows too, and every window's recorded height
+ // (the editor writes it in the sidecar; an old window has none until asked).
+ const all = [...plain, ...tieredWindowsFromNames(names, dir)];
+ for (const w of all) {
+ const h = await sidecarHeight(w.path);
+ if (h !== undefined) w.height = h;
+ }
+ return all;
}
// ONE CLOCK PER RECORDING (lane one-clock). A container whose video dir holds
@@ -402,6 +476,7 @@ export const asSource = (kind, w) => ({
*/
export async function resolveFromTiers(tiers, ctx, from, to, opts = {}) {
const { allow = (tier) => !tier.audio, preferName = () => null } = opts;
+ if (isTallAsk(ctx.maxHeight)) return tallResolve(tiers, ctx, from, to, { allow, preferName });
for (const tier of tiers) {
if (!allow(tier)) continue;
const windows = (await tier.windows({ ...ctx, want: { from, to } })).filter((w) => windowContains(w, from, to));
@@ -415,22 +490,95 @@ export async function resolveFromTiers(tiers, ctx, from, to, opts = {}) {
return null;
}
+// One probe per file per process, for a window whose height nothing recorded.
+const probedHeights = new Map();
+/**
+ * A file's picture height by one probe, remembered for the process.
+ * @param {string} file
+ * @param {SourceProbe} [probe]
+ * @returns {Promise<number | null>}
+ */
+export async function probeHeightOnce(file, probe = ffprobeSource) {
+ if (!probedHeights.has(file)) {
+ const info = await probe(file);
+ probedHeights.set(file, info?.height ?? null);
+ }
+ return probedHeights.get(file);
+}
+
+/** @param {TierContext} ctx @param {string} kind @param {SourceWindow} w */
+async function heightOfWindow(ctx, kind, w) {
+ if (w.height) return w.height;
+ if (ctx.heightOf) return ctx.heightOf(kind, w);
+ return probeHeightOnce(w.path, ctx.probe ?? ffprobeSource);
+}
+
+/**
+ * THE TALL RESOLVE (a `maxHeight` above 720): the tiers in their order, as
+ * ever, but the source is the EARLIEST one reaching the tallest picture the
+ * disk can give up to the ask -- a 720 window the build cut earlier gives way
+ * to a 1080 one beside it, or to the saved copy when that is taller, and is
+ * never thrown away. Within a tier, the tallest at or under the ask first
+ * (tightest of equals), then those taller, lowest first. Later tiers are
+ * looked at only when an earlier one's best is short of the ask, so a hit at
+ * full height costs what it always did. Unknown heights count as the lowest.
+ *
+ * @param {SourceTier[]} tiers
+ * @param {TierContext} ctx
+ * @param {number} from
+ * @param {number} to
+ * @param {{ allow: (tier: SourceTier) => boolean, preferName: (tier: SourceTier) => string | null }} opts
+ * @returns {Promise<LocalSource | null>}
+ */
+async function tallResolve(tiers, ctx, from, to, { allow, preferName }) {
+ const cap = tierRungOf(Number(ctx.maxHeight));
+ /** @type {{ tier: SourceTier, w: SourceWindow, h: number }[]} */
+ const best = [];
+ for (const tier of tiers) {
+ if (!allow(tier)) continue;
+ const windows = (await tier.windows({ ...ctx, want: { from, to } })).filter((w) => windowContains(w, from, to));
+ /** @type {{ w: SourceWindow, h: number }[]} */
+ const here = [];
+ for (const w of windows) {
+ if (!(await present(w.path))) continue;
+ here.push({ w, h: tier.audio ? 0 : (await heightOfWindow(ctx, tier.kind, w)) ?? 0 });
+ }
+ if (!here.length) continue;
+ const exactName = preferName(tier);
+ const span = (/** @type {SourceWindow} */ w) => w.to - w.from;
+ here.sort((a, b) => {
+ const ua = a.h <= cap;
+ const ub = b.h <= cap;
+ if (ua !== ub) return ua ? -1 : 1;
+ return (ua ? b.h - a.h : a.h - b.h) || Number(b.w.name === exactName) - Number(a.w.name === exactName) || span(a.w) - span(b.w);
+ });
+ best.push({ tier, w: here[0].w, h: here[0].h });
+ if (Math.min(here[0].h, cap) >= cap) break;
+ }
+ if (!best.length) return null;
+ const reach = Math.max(...best.map((b) => Math.min(b.h, cap)));
+ const pick = best.find((b) => Math.min(b.h, cap) === reach) ?? best[0];
+ return asSource(pick.tier.kind, pick.h ? { ...pick.w, height: pick.h } : pick.w);
+}
+
/**
* The corpus source for one span of one record, or null when nothing on disk
* holds it.
*
* @param {{ video: string, slug: string, from: number, to: number }} want
* `from`/`to` are the PADDED span.
- * @param {{ channelsDir: string, probe?: SourceProbe, audio?: boolean, platform?: string | null }} config
+ * @param {{ channelsDir: string, probe?: SourceProbe, audio?: boolean, platform?: string | null, maxHeight?: number }} config
* `audio` admits the audio tier (default false); `platform` is the record's,
* when known (else its channel's is read — recordDirOf).
* @returns {Promise<LocalSource | null>}
*/
export async function resolveCorpusSource(want, config) {
const { video, slug, from, to } = want;
- const { channelsDir, probe, audio = false, platform } = config;
+ const { channelsDir, probe, audio = false, platform, maxHeight } = config;
if (!video || !slug || !Number.isFinite(from) || !Number.isFinite(to)) return null;
- return resolveFromTiers(CORPUS_TIERS, { video, slug, channelsDir, probe, platform }, from, to, {
+ // `maxHeight` only when a caller states one (umtool); a site's evidence cut
+ // states none and reads the plain windows exactly as before.
+ return resolveFromTiers(CORPUS_TIERS, { video, slug, channelsDir, probe, platform, ...(maxHeight !== undefined ? { maxHeight } : {}) }, from, to, {
allow: (tier) => (tier.audio ? audio : true),
});
}
diff --git a/common/lib/renderHold.ts b/common/lib/renderHold.ts
@@ -0,0 +1,50 @@
+// RENDER MODE, AS A WAIT (common/lib/renderPriority.mjs; AGENTS.md "Render
+// mode"): work that is not heavy enough for the heavy slot but still takes
+// cores a render the operator is waiting for wants — a taller clip window cut
+// from a saved copy (the height tier) — waits while the hold is on, the way
+// the lanes are held. Read as the heavy slot's gate reads it.
+//
+// SERVER-ONLY.
+
+import { describeRenderPriority, readRenderPriority, renderPriorityFile } from "./renderPriority.mjs";
+
+/** Render mode, as the heavy slot's gate reads it: who holds it, or null. */
+export function renderModeHeldNow(): string | null {
+ try {
+ const s = readRenderPriority(renderPriorityFile(process.env, { root: process.cwd() }));
+ return s.held && s.state ? describeRenderPriority(s.state) : null;
+ } catch {
+ return null; // an unreadable state file holds nothing (queue-lock's rule)
+ }
+}
+
+export const RENDER_HOLD_POLL_MS = 30_000;
+
+// Wait while `held()` names a holder: one line when the wait starts, one when
+// it ends. Returns how long it waited (0: not held), or null when `signal`
+// ended the wait first.
+export async function waitWhileRenderHeld(opts: {
+ held?: () => string | null;
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
+ onLog: (line: string) => void;
+ what: string;
+ signal?: AbortSignal;
+ pollMs?: number;
+ now?: () => number;
+}): Promise<number | null> {
+ const held = opts.held ?? renderModeHeldNow;
+ const now = opts.now ?? Date.now;
+ let by = held();
+ if (!by) return 0;
+ const start = now();
+ opts.onLog(` ⏸ ${opts.what}: render mode holds the machine (${by}) — waiting.`);
+ while (by) {
+ if (opts.signal?.aborted) return null;
+ await opts.sleep(opts.pollMs ?? RENDER_HOLD_POLL_MS, opts.signal);
+ if (opts.signal?.aborted) return null;
+ by = held();
+ }
+ const waited = now() - start;
+ opts.onLog(` ▶ ${opts.what}: render mode ended — waited ${Math.round(waited / 1000)}s.`);
+ return waited;
+}
diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts
@@ -169,7 +169,7 @@ test("the look ops (release 38): look, slide and room through the look's own rul
assert.match(r.applied[1]!.warnings![0]!, /the slide's knobs show once the join style is blur slide/);
assert.deepEqual(
r.refused.map((x) => x.why),
- ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide, blur, intro, format, vertical, mode, basic)'],
+ ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide, blur, intro, format, vertical, mode, basic, tallWindows)'],
);
assert.equal((manifest.render as { transition: number }).transition, 0.4, "the input is not touched");
});
diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts
@@ -4,7 +4,7 @@
type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>;
type Render = Record<string, unknown> | null | undefined;
-export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic";
+export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic" | "tallWindows";
export const LOOK_KEYS: readonly LookKey[];
export const BAND_MAX: number;
export const TRANSITION_MAX: number;
diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs
@@ -26,7 +26,7 @@ const q = (v) => JSON.stringify(v);
const round2 = (n) => Number(Number(n).toFixed(2));
/** The render keys the Look panel writes, in its order. */
-export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic"]);
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows"]);
/** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */
export const BAND_MAX = 240;
@@ -461,6 +461,13 @@ export function applyLookPatch(manifest, patch) {
} else if (v === "basic") render.mode = "basic";
else errors.push(`render.mode must be "deck" (the default) or "basic" (the footage alone, no chrome)`);
break;
+ case "tallWindows":
+ // OFF is the default, written as no key: the project's opt-in to clip
+ // windows above 720 (umtool report-to-video/sources.mjs tallWindowCap).
+ if (v === true) render.tallWindows = true;
+ else if (v === false) delete render.tallWindows;
+ else errors.push("render.tallWindows must be true (windows up to render.maxHeightSource) or false (720, the default)");
+ break;
case "format":
// "landscape" is the default: written as no key at all.
if (v === "landscape") delete render.format;
diff --git a/common/lib/report/videoAssistOps.test.ts b/common/lib/report/videoAssistOps.test.ts
@@ -26,7 +26,7 @@ test("the look's rules: one patch function — keys refused, null removes, qr on
assert.deepEqual(bad.errors, validateTransitionStyle({ render: { slide: { blur: 9 } } }));
assert.deepEqual(applyLookPatch(m, { loudness: { target: -40 } }).errors, validateLook({ render: { loudness: { target: -40 } } }));
assert.deepEqual(lookErrors(m), []);
- assert.equal(LOOK_KEYS.length, 15);
+ assert.equal(LOOK_KEYS.length, 16);
});
test("render.mode and render.basic: deck is the default (no key), basic the footage alone; the fades checked", () => {
diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts
@@ -194,6 +194,33 @@ export async function restoreSavedVideoProvenance(
});
}
+// RECORD THE ACTIVE COPY'S PROBED HEIGHT (`probed.height`), when the pointer
+// records none (no `format.height`, no `probed.height`): a pointer is then
+// probed once, not on every tall clip ask (lib/clipWindowTier-server.ts).
+// Rewritten from the RAW JSON under its file lock, every other key kept;
+// nothing is written when a height is already there or the pointer names
+// another file than the one probed. False when nothing was written.
+export async function recordSavedVideoProbedHeight(
+ videoDir: string,
+ file: string,
+ height: number,
+): Promise<boolean> {
+ if (!Number.isInteger(height) || height <= 0) return false;
+ 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 (raw.file !== file) return false;
+ const fmt = raw.format as { height?: unknown } | undefined;
+ const probed = (raw.probed && typeof raw.probed === "object" ? raw.probed : {}) as Record<string, unknown>;
+ if (typeof fmt?.height === "number" || typeof probed.height === "number") return false;
+ raw.probed = { ...probed, height };
+ 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/savedVideoWindow-server.test.ts b/common/lib/savedVideoWindow-server.test.ts
@@ -12,9 +12,12 @@ import { execFileSync } from "node:child_process";
import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
-import { cutSavedVideoWindow, savedWindowSource } from "./savedVideoWindow-server";
-import { findContainingClipWindow } from "./clipWindow-server";
+import { cutPlainFromTieredWindow, cutSavedVideoWindow, savedWindowSource } from "./savedVideoWindow-server";
+import { evidenceCutArgs, fittedHeight } from "./evidenceClip-server";
+import { findContainingClipWindow, listClipWindows } from "./clipWindow-server";
+import { stat } from "node:fs/promises";
import { probeMedia } from "./evidenceClip-server";
+import { recordSavedVideoProbedHeight, loadSavedVideo } from "./savedVideo-server";
import { SAVED_VIDEOS_MARKER_FILENAME } from "./savedVideoStore";
const SLUG = "demo-channel";
@@ -266,3 +269,120 @@ test("a time map about another container (saved again) is not applied", async ()
assert.equal(src.kind, "covers");
if (src.kind === "covers") assert.equal(src.clock, undefined);
});
+
+// THE HEIGHT TIER (lib/clipWindow.ts): a cut asked above 720 is its own file
+// beside the plain window, which keeps every byte, its name and its mtime —
+// so a site's evidence cut, keyed by that file, never changes.
+test("a tall cut lands beside the plain window as <from>-<to>.h1080.mp4, its height recorded; the plain one is untouched", async () => {
+ const c = await corpus(PICTURE);
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 2, to: 5 });
+ assert.equal(src.kind, "covers");
+ if (src.kind !== "covers") return;
+ const plain = await cutSavedVideoWindow({
+ paths: c.paths, videoDir: c.videoDir, source: src, from: 2, to: 5, provenance: { requestedBy: "test" },
+ });
+ // A plain cut records no height, as before the tier (E).
+ assert.equal(plain.height, undefined);
+ assert.equal(plain.provenance?.height, undefined);
+ const before = await stat(plain.path);
+ const bytesBefore = await readFile(plain.path);
+ const logs: string[] = [];
+ const tall = await cutSavedVideoWindow({
+ paths: c.paths, videoDir: c.videoDir, source: src, from: 2, to: 5,
+ provenance: { requestedBy: "umtool" }, tier: 1080, onLog: (l) => logs.push(l),
+ });
+ assert.equal(tall.file, "2.00-5.00.h1080.mp4");
+ assert.equal(tall.tier, 1080);
+ assert.equal(tall.height, 90);
+ assert.match(logs.join(""), /clips\/2\.00-5\.00\.h1080\.mp4 \(\d+ bytes, 90p\)/);
+ const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", "2.00-5.00.h1080.json"), "utf8"));
+ assert.equal(sidecar.height, 90);
+ assert.equal(sidecar.source, "saved-video");
+ // The plain window: same bytes, same mtime; the plain lookups still see only it.
+ const after = await stat(plain.path);
+ assert.equal(after.mtimeMs, before.mtimeMs);
+ assert.deepEqual(await readFile(plain.path), bytesBefore);
+ assert.equal((await findContainingClipWindow(c.videoDir, 2, 5))?.file, "2.00-5.00.mp4");
+ assert.deepEqual((await listClipWindows(c.videoDir)).map((w) => w.file), ["2.00-5.00.mp4"]);
+ assert.deepEqual(
+ (await listClipWindows(c.videoDir, { tiers: true })).map((w) => [w.file, w.tier ?? null, w.height ?? null]),
+ [["2.00-5.00.mp4", null, null], ["2.00-5.00.h1080.mp4", 1080, 90]],
+ );
+});
+
+// D: a plain window cut LOCALLY from a tiered one — the evidence box, its
+// provenance naming the file it came from; the tiered file untouched.
+test("a plain window is cut from a tiered one: 1280x720 box, derivedFrom named, the tiered file untouched", async () => {
+ const c = await corpus(PICTURE);
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 7 });
+ if (src.kind !== "covers") return assert.fail(src.kind);
+ const tiered = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 1, to: 7, provenance: { requestedBy: "umtool" }, tier: 1080 });
+ const before = await stat(tiered.path);
+ const logs: string[] = [];
+ const plain = await cutPlainFromTieredWindow({
+ paths: c.paths, videoDir: c.videoDir, tiered, from: 2, to: 5, provenance: { requestedBy: "reports", clipId: "r#1" }, onLog: (l) => logs.push(l),
+ });
+ assert.equal(plain.file, "2.00-5.00.mp4");
+ assert.equal(plain.provenance?.source, "clip-window");
+ assert.equal(plain.provenance?.derivedFrom, "1.00-7.00.h1080.mp4");
+ assert.equal(plain.provenance?.height, undefined);
+ assert.match(logs.join(""), /from clips\/1\.00-7\.00\.h1080\.mp4 into clips\/2\.00-5\.00\.mp4/);
+ const p = await probeMedia(plain.path, "ffprobe");
+ assert.ok(p && p.durationSec !== null && Math.abs(p.durationSec - 3) < 0.25, String(p?.durationSec));
+ assert.equal((await stat(tiered.path)).mtimeMs, before.mtimeMs);
+ assert.equal((await findContainingClipWindow(c.videoDir, 2, 5))?.file, "2.00-5.00.mp4");
+});
+
+// F: the recorded height is ffmpeg's, not an approximation — every size here
+// is cut by ffmpeg through the very filter and probed.
+test("fittedHeight is what ffmpeg's scale filter writes (1366x768 in the 720 box is 720)", async () => {
+ const dir = path.join(ROOT, "fit");
+ await mkdir(dir, { recursive: true });
+ const sizes: [number, number][] = [[1366, 768], [1440, 1080], [1080, 1920], [640, 360], [1920, 1080], [1280, 1024], [854, 480]];
+ assert.equal(fittedHeight(1366, 768), 720);
+ for (const [w, h] of sizes) {
+ const src = path.join(dir, `${w}x${h}.mp4`);
+ ff(["-f", "lavfi", "-i", `testsrc=size=${w}x${h}:rate=5:duration=0.4`, "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", src]);
+ for (const box of [720, 1080]) {
+ const out = path.join(dir, `${w}x${h}-${box}.mp4`);
+ execFileSync("ffmpeg", evidenceCutArgs(src, 0, 0.3, "video", out, box).map(String));
+ const probed = await probeMedia(out, "ffprobe");
+ assert.equal(fittedHeight(w, h, box), probed?.height, `${w}x${h} in the ${box} box`);
+ }
+ }
+});
+
+// I: a pointer with no height takes the one a tall ask probed — once.
+test("recordSavedVideoProbedHeight writes probed.height once, only for the file it probed, never over a recorded one", async () => {
+ const c = await corpus(PICTURE);
+ assert.equal(await recordSavedVideoProbedHeight(c.videoDir, "other.mp4", 90), false);
+ assert.equal(await recordSavedVideoProbedHeight(c.videoDir, "source-media.mp4", 90), true);
+ assert.equal((await loadSavedVideo(c.videoDir))?.probed?.height, 90);
+ assert.equal(await recordSavedVideoProbedHeight(c.videoDir, "source-media.mp4", 1080), false);
+ assert.equal((await loadSavedVideo(c.videoDir))?.probed?.height, 90);
+ const raw = JSON.parse(await readFile(path.join(c.videoDir, "saved-video.json"), "utf8"));
+ assert.equal(raw.origin.kind, "local-archive", "every other key kept");
+});
+
+// 2: an ULTRAWIDE saved copy fits the 1080 box at 810 — the tall cut is made
+// once; the next ask finds it as tall as the copy gives and cuts nothing.
+test("an ultrawide saved copy is cut tall once; the second tall ask cuts nothing", async () => {
+ const { tallerFromSaved } = await import("./clipWindowTier-server");
+ const { listClipWindows } = await import("./clipWindow-server");
+ const uw = path.join(ROOT, "fixtures", "ultrawide.mp4");
+ ff(["-f", "lavfi", "-i", "testsrc=size=2560x1080:rate=5:duration=8", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", uw]);
+ const c = await corpus(uw);
+ const ask = (hitHeight: number | null) =>
+ tallerFromSaved({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 2, to: 5, hitHeight, cap: 1080 });
+ // The 720 window of it is 540 tall.
+ const first = await ask(540);
+ assert.equal(first.kind, "cut");
+ if (first.kind !== "cut") return;
+ assert.equal(first.height, 810);
+ const tall = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: first.source, from: 2, to: 5, provenance: { requestedBy: "umtool" }, tier: 1080 });
+ assert.equal(tall.height, 810);
+ assert.equal((await probeMedia(tall.path, "ffprobe"))?.height, 810);
+ const second = await ask(tall.height ?? null);
+ assert.deepEqual(second, { kind: "best", height: 810 });
+ assert.equal((await listClipWindows(c.videoDir, { tiers: true })).length, 1);
+});
diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts
@@ -38,6 +38,7 @@ import { execa } from "execa";
import {
WIN_EPS,
clipWindowFile,
+ isWindowTier,
type ClipProvenance,
} from "./clipWindow";
import {
@@ -45,7 +46,7 @@ import {
writeClipProvenance,
type ClipWindow,
} from "./clipWindow-server";
-import { evidenceCutArgs, probeMedia, type MediaProbe } from "./evidenceClip-server";
+import { EVIDENCE_MAX_HEIGHT, evidenceCutArgs, fittedHeight, probeMedia, type MediaProbe } from "./evidenceClip-server";
import { tmpPathFor } from "./jsonFile-server";
import { savedVideoPath, type SavedVideoPointer } from "./savedVideo";
import { loadSavedVideo } from "./savedVideo-server";
@@ -171,11 +172,18 @@ export async function cutSavedVideoWindow(opts: {
from: number;
to: number;
provenance: SavedWindowProvenance;
+ // THE HEIGHT TIER (lib/clipWindow.ts windowTierOf, already snapped and held
+ // to the ceiling by the caller): the cut is fitted inside that height's 16:9
+ // box and written beside the plain window as `<from>-<to>.h<tier>.mp4`.
+ // Absent: the plain window in the 1280×720 box, as always.
+ tier?: number;
onLog?: (line: string) => void;
signal?: AbortSignal;
}): Promise<ClipWindow> {
const { from, to, source } = opts;
- const dest = clipWindowPath(opts.videoDir, from, to);
+ const tier = isWindowTier(opts.tier) ? opts.tier : undefined;
+ const box = tier ?? EVIDENCE_MAX_HEIGHT;
+ const dest = clipWindowPath(opts.videoDir, from, to, tier);
await mkdir(path.dirname(dest), { recursive: true });
const tmp = tmpPathFor(dest);
const kind = source.probe.hasVideo ? "video" : "audio";
@@ -185,7 +193,7 @@ export async function cutSavedVideoWindow(opts: {
const cutFrom = mapped ? mapped.from : from;
const cutTo = mapped ? mapped.to : to;
try {
- const r = await execa(opts.paths.ffmpegBin, evidenceCutArgs(source.container, cutFrom, cutTo, kind, tmp), {
+ const r = await execa(opts.paths.ffmpegBin, evidenceCutArgs(source.container, cutFrom, cutTo, kind, tmp, box), {
reject: false,
timeout: CUT_TIMEOUT_MS,
...(opts.signal ? { cancelSignal: opts.signal } : {}),
@@ -200,6 +208,10 @@ export async function cutSavedVideoWindow(opts: {
const bytes = (await stat(tmp)).size;
await rename(tmp, dest);
const now = new Date().toISOString();
+ // A TIERED cut records the height the box makes of the container's
+ // picture (the filter's own arithmetic, evidenceClip-server fittedHeight);
+ // a plain cut records none, as before the tier.
+ const height = tier !== undefined && kind === "video" ? fittedHeight(source.probe.width, source.probe.height, box) : null;
const provenance: ClipProvenance = {
requestedBy: opts.provenance.requestedBy,
...(opts.provenance.manifest ? { manifest: opts.provenance.manifest } : {}),
@@ -211,6 +223,7 @@ export async function cutSavedVideoWindow(opts: {
// When the window landed — for a cut, when it was cut.
fetchedAt: now,
source: "saved-video",
+ ...(height !== null ? { height } : {}),
...(mapped && source.clock
? {
clock: {
@@ -223,7 +236,7 @@ export async function cutSavedVideoWindow(opts: {
}
: {}),
};
- await writeClipProvenance(opts.videoDir, from, to, provenance);
+ await writeClipProvenance(opts.videoDir, from, to, provenance, tier);
const onClock = mapped
? ` on the cue clock (the container's ${cutFrom.toFixed(2)}–${cutTo.toFixed(2)}, ` +
`${mapped.offsetFrom >= 0 ? "+" : ""}${mapped.offsetFrom.toFixed(2)} s` +
@@ -231,17 +244,87 @@ export async function cutSavedVideoWindow(opts: {
: "";
opts.onLog?.(
`Cut ${from.toFixed(2)}–${to.toFixed(2)}${onClock} from the saved video ${source.pointer.file} into ` +
- `clips/${clipWindowFile(from, to)} (${bytes} bytes); nothing fetched.\n`,
+ `clips/${clipWindowFile(from, to, tier)} (${bytes} bytes` +
+ `${height !== null ? `, ${height}p` : ""}); nothing fetched.\n`,
);
return {
- file: clipWindowFile(from, to),
+ file: clipWindowFile(from, to, tier),
path: dest,
from,
to,
bytes,
provenance,
+ ...(tier !== undefined ? { tier } : {}),
+ ...(height !== null ? { height } : {}),
};
} finally {
await rm(tmp, { force: true }).catch(() => {});
}
}
+
+// A PLAIN WINDOW CUT FROM A TALLER ONE (operator ruling, 13 Nov): a plain ask
+// (no height, or 720 and under) that misses, for a span a tiered window of the
+// same video holds (`<from>-<to>.h<tier>.mp4`, the height tier), is cut here
+// from that file into the plain `<from>-<to>.mp4` — the evidence filter, the
+// 1280×720 box — instead of a fetch. Nothing on disk changes but the new
+// window: the tiered file is read, never touched. Its provenance names the
+// file it came from (`source: "clip-window"`, `derivedFrom`) and carries the
+// tiered window's clock, shifted to this span, so the clock retirement treats
+// it as the window it was cut from. A failed cut throws; the caller goes on to
+// the network as before.
+export async function cutPlainFromTieredWindow(opts: {
+ paths: Pick<Paths, "ffmpegBin">;
+ videoDir: string;
+ tiered: ClipWindow;
+ from: number;
+ to: number;
+ provenance: SavedWindowProvenance;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+}): Promise<ClipWindow> {
+ const { from, to, tiered } = opts;
+ const dest = clipWindowPath(opts.videoDir, from, to);
+ await mkdir(path.dirname(dest), { recursive: true });
+ const tmp = tmpPathFor(dest);
+ const a = Math.max(0, from - tiered.from);
+ const b = Math.max(a, to - tiered.from);
+ try {
+ const r = await execa(opts.paths.ffmpegBin, evidenceCutArgs(tiered.path, a, b, "video", tmp), {
+ reject: false,
+ timeout: CUT_TIMEOUT_MS,
+ ...(opts.signal ? { cancelSignal: opts.signal } : {}),
+ });
+ if (r.exitCode !== 0) {
+ const err = String(r.stderr ?? "").trim().split("\n").slice(-3).join(" | ");
+ throw new SavedWindowCutError(
+ `ffmpeg failed cutting ${from.toFixed(2)}–${to.toFixed(2)} from clips/${tiered.file}` +
+ `${err ? `: ${err}` : ` (exit ${r.exitCode ?? "?"})`}`,
+ );
+ }
+ const bytes = (await stat(tmp)).size;
+ await rename(tmp, dest);
+ const now = new Date().toISOString();
+ const c = tiered.provenance?.clock;
+ const provenance: ClipProvenance = {
+ requestedBy: opts.provenance.requestedBy,
+ ...(opts.provenance.manifest ? { manifest: opts.provenance.manifest } : {}),
+ ...(opts.provenance.clipId ? { clipId: opts.provenance.clipId } : {}),
+ ...(opts.provenance.reason ? { reason: opts.provenance.reason } : {}),
+ requestedAt: opts.provenance.requestedAt ?? now,
+ ...(typeof opts.provenance.pad === "number" ? { pad: opts.provenance.pad } : {}),
+ bytes,
+ fetchedAt: now,
+ source: "clip-window",
+ derivedFrom: tiered.file,
+ ...(c ? { clock: { ...c, from: c.from + (from - tiered.from), to: c.from + (to - tiered.from) } } : {}),
+ };
+ await writeClipProvenance(opts.videoDir, from, to, provenance);
+ opts.onLog?.(
+ `Cut ${from.toFixed(2)}–${to.toFixed(2)} from clips/${tiered.file} into clips/${clipWindowFile(from, to)} ` +
+ `(${bytes} bytes, the 1280×720 box); nothing fetched.\n`,
+ );
+ return { file: clipWindowFile(from, to), path: dest, from, to, bytes, provenance };
+ } finally {
+ await rm(tmp, { force: true }).catch(() => {});
+ }
+}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -2073,7 +2073,7 @@ export const siteSettingsSchema = z.object({
"Report and video generation (release 27): where each task runs (`code` = Claude Code, `api` = the Claude API with a key, `local` = the local model), the models, the spend caps (a job's default, its max, the day's), the API key FILE (never the key), and where video projects live. A generation runs as a `report-draft` editor job (`pnpm ops report-draft`) on `draft:api` or `draft:local`. See GenerationSettings and common/lib/generationSettings.ts.",
),
clips: settingsField((v): ClipsSettings => sanitizeClips(v)).describe(
- "How clip windows are fetched (controller/fetchWindows.ts): the platforms whose windows are cut from the saved WHOLE recording rather than by a remote seek — Rumble by default, because its HLS seek put the picture 1–4 s off the sound (lib/clipWindowSync.ts). See ClipsSettings.",
+ "How clip windows are fetched (controller/fetchWindows.ts): the platforms whose windows are cut from the saved WHOLE recording rather than by a remote seek — Rumble by default, because its HLS seek put the picture 1–4 s off the sound (lib/clipWindowSync.ts) — and the tallest height a window may be asked for (`windowMaxHeight`, a ceiling: an ask with no height is 720 as before). See ClipsSettings.",
),
jobs: settingsField((v): JobsSettings => sanitizeJobs(v)).describe(
"What the job system does on its own across a restart: whether the jobs the previous process left interrupted are resumed at boot (common/jobs/resumeInterrupted.ts). See JobsSettings.",
diff --git a/common/ytdlp/fetchWindowManaged.test.ts b/common/ytdlp/fetchWindowManaged.test.ts
@@ -180,3 +180,35 @@ test("a window of a copy (one direct file of unknown height) is fetched with the
/Requested format is not available/,
);
});
+
+// THE HEIGHT TIER (lib/clipWindow.ts): a tall ask's window is its tier's file,
+// beside a plain one of the same span, which neither answers it nor is touched.
+test("a window fetched with a tier lands as <from>-<to>.h<tier>.mp4 with its sidecar; the plain window stays", async () => {
+ process.env.FAKE_MODE = "progressive";
+ const videoDir = await setup("tiered");
+ const clips = path.join(videoDir, "clips");
+ await mkdir(clips, { recursive: true });
+ await writeFile(path.join(clips, "10.00-20.00.mp4"), "the 720 window");
+ const before = (await runs()).length;
+ const res = await fetchWindowManaged({ ...opts(videoDir), videoUrl: "https://www.youtube.com/watch?v=v1", maxHeight: 1080, tier: 1080 });
+ assert.equal((await runs()).length - before, 1, "the plain window does not answer a tier's ask");
+ assert.equal(path.basename(res.file), "10.00-20.00.h1080.mp4");
+ assert.equal(await readFile(path.join(clips, "10.00-20.00.mp4"), "utf8"), "the 720 window");
+ const sidecar = JSON.parse(await readFile(path.join(clips, "10.00-20.00.h1080.json"), "utf8"));
+ assert.equal(sidecar.requestedBy, "test");
+ assert.ok(sidecar.ytdlp.args.join(" ").includes("height<=1080"));
+ // The second ask of the same tier is the cache.
+ const again = await fetchWindowManaged({ ...opts(videoDir), videoUrl: "https://www.youtube.com/watch?v=v1", maxHeight: 1080, tier: 1080 });
+ assert.equal(again.cached, true);
+ assert.equal(path.basename(again.file), "10.00-20.00.h1080.mp4");
+});
+
+// E: the plain path is as before the tier — no probe after the fetch, no height written.
+test("a plain window's sidecar records no height (no probe after a plain fetch)", async () => {
+ process.env.FAKE_MODE = "progressive";
+ const videoDir = await setup("plain-no-height");
+ const res = await fetchWindowManaged({ ...opts(videoDir), videoUrl: "https://www.youtube.com/watch?v=v1", paths: { ytdlpBin: BIN, ffprobeBin: "/nonexistent/would-be-probed" } as unknown as Paths });
+ assert.equal(path.basename(res.file), "10.00-20.00.mp4");
+ const sidecar = JSON.parse(await readFile(path.join(videoDir, "clips", "10.00-20.00.json"), "utf8"));
+ assert.equal("height" in sidecar, false);
+});
diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts
@@ -34,8 +34,10 @@ import { detectPlatform } from "../lib/platform";
import type { Paths } from "../lib/paths";
import {
clipsDirFor,
+ clipWindowContains,
clipWindowFile,
- clipWindowName,
+ clipWindowStem,
+ PLAIN_WINDOW_MAX_HEIGHT,
type ClipCopy,
type ClipAudioCheck,
type ClipProvenance,
@@ -43,9 +45,11 @@ import {
import {
clipWindowPath,
findContainingClipWindow,
+ listClipWindows,
writeClipProvenance,
type ClipWindow,
} from "../lib/clipWindow-server";
+import { probeVideoHeight } from "./ffprobeDuration";
import { channelExtraArgs, configForVideoUrl } from "./channelArgs";
import { runOneYtdlp } from "./runOneYtdlp";
import { FULL_LOG_PROGRESS_ARGS } from "./downloadOneManaged";
@@ -71,7 +75,7 @@ import { noteStoredUrlRead, storedUrlGapRemainingMs } from "../jobs/storedUrlPac
// The source height a clip is worth fetching at. 720 is umtool's number and the
// reason is the render: the deliverable is 1080p with a clip inset, so pixels
// above 720 are thrown away after paying for them.
-export const DEFAULT_CLIP_MAX_HEIGHT = 720;
+export const DEFAULT_CLIP_MAX_HEIGHT = PLAIN_WINDOW_MAX_HEIGHT;
// Rumble serves HLS whose segments are named `.tar`, and ffmpeg 8 refuses them
// ("URL … is not in allowed_segment_extensions", exit 183) — every Rumble window
@@ -160,6 +164,11 @@ export type FetchWindowOpts = {
provenance: FetchWindowProvenance;
cookiePolicy?: ResolvedCookiePolicy;
maxHeight?: number;
+ // THE HEIGHT TIER (lib/clipWindow.ts): the window is written as
+ // `<from>-<to>.h<tier>.mp4` beside any plain one, and only a window of the
+ // same tier answers the cache check below. Set by the callers when the cap
+ // asked for is above 720; absent, the plain window as always.
+ tier?: number;
onLog: (s: string) => void;
signal: AbortSignal;
// Called when the failure classifies as a platform-level signal (a 429 or a
@@ -314,7 +323,13 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
// one clip is worthless to the neighbour it already covers. `from`/`to` are
// the window WITH its padding (`provenance.pad` only records how much), so an
// unpadded window on disk never answers for a padded ask (release 27 S7).
- const hit = await findContainingClipWindow(videoDir, from, to);
+ const { tier } = opts;
+ const hit =
+ tier === undefined
+ ? await findContainingClipWindow(videoDir, from, to)
+ : ((await listClipWindows(videoDir, { tiers: true }))
+ .filter((w) => w.tier === tier && clipWindowContains(w, from, to))
+ .sort((a, b) => a.to - a.from - (b.to - b.from))[0] ?? null);
if (hit) {
opts.onLog(
`Window ${from.toFixed(2)}–${to.toFixed(2)} is already covered by ` +
@@ -325,7 +340,7 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
const clipsDir = clipsDirFor(videoDir);
await mkdir(clipsDir, { recursive: true });
- const dest = clipWindowPath(videoDir, from, to);
+ const dest = clipWindowPath(videoDir, from, to, tier);
// `<from>-<to>.part.mp4`, and BOTH halves of that name matter.
//
// `.part` in the middle is what stops a half-written window being read as a
@@ -336,7 +351,7 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
// extension. Given a name ending in `.part` it either refuses the merge or
// appends the real extension itself — the stray-file case below — and the
// whole point of --merge-output-format here is to avoid the VP9/webm trap.
- const part = path.join(clipsDir, `${clipWindowName(from, to)}.part.mp4`);
+ const part = path.join(clipsDir, `${clipWindowStem(from, to, tier)}.part.mp4`);
await rm(part, { force: true });
const maxHeight = opts.maxHeight ?? DEFAULT_CLIP_MAX_HEIGHT;
@@ -619,6 +634,12 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
opts.onLog(`Audio check: ${probe.verdict}${attempt > 1 ? ` (attempt ${attempt})` : ""}.\n`);
}
await rename(produced, dest);
+ // A TIERED window's picture height, read once now so no later ask has to
+ // (the height tier's record). A plain window is not probed, as before.
+ const height =
+ tier !== undefined
+ ? await probeVideoHeight({ ffprobeBin: opts.paths.ffprobeBin, file: dest }).catch(() => null)
+ : null;
const provenance: ClipProvenance = {
requestedBy: opts.provenance.requestedBy,
@@ -636,11 +657,12 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
bytes: st.size,
fetchedAt: new Date().toISOString(),
ytdlp: { args },
+ ...(height !== null ? { height } : {}),
};
- await writeClipProvenance(videoDir, from, to, provenance);
+ await writeClipProvenance(videoDir, from, to, provenance, tier);
opts.onLog(
`Fetched ${from.toFixed(2)}–${to.toFixed(2)} of ${opts.videoId} into ` +
- `clips/${clipWindowFile(from, to)} (${st.size} bytes)` +
+ `clips/${clipWindowFile(from, to, tier)} (${st.size} bytes${height !== null ? `, ${height}p` : ""})` +
(stored
? `: cut from the stored media URL (${stored.host}) ${storedUrlWhyText(stored.why, stored.platform)}`
: "") +
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,27 @@
# Changelog
## [Unreleased]
+- **Clip windows can be asked for taller than 720, and the 720 window stays.** A `maxHeight` above 720 on
+ fetch-windows, fetch-window or `fetch_clip` asks for a taller window, up to the new setting
+ `clips.windowMaxHeight` (default 1080; a taller ask is held to it and the answer says so). With no `maxHeight` a
+ window is 720, as before.
+ - The taller window is a separate file beside the 720 one, `clips/<from>-<to>.h1080.mp4`. It is cut from the
+ saved copy when that copy is taller, else fetched.
+ - The tier snaps to 1080, 1440 or 2160 (held to the setting), so asks of 900 and 1080 share one file. A Retry
+ keeps its tier.
+ - A held window lower than asked, with no taller saved copy, is used as it is and listed under `lower` (fetch-window
+ and `fetch_clip`: `belowAsked`) with why. It is never fetched again for its height.
+ - A taller cut from a saved copy waits while render mode holds the machine.
+ - Heights are recorded for taller windows, and for a 720 window only when a tall ask first needs it. A 720 ask with
+ no window is cut from a taller one when it exists, never fetched.
+ - The video page lists the taller windows; `check-windows` checks them. `evict-clips` takes `"tiers": "plain" |
+ "tiered"`; the age-out and the clock retirement remove both.
+ - Site-driven fetches (`fetch-windows {"siteId"}`, Fetch missing evidence) stay at 720, and a site's evidence clips
+ are cut from the 720 window exactly as before.
+- **umtool: taller clips are opt-in per project: `umtool look <p> tallWindows=true`.** With it on, `umtool fetch` asks
+ for the project's `render.maxHeightSource` and prints each clip that stays lower, with why; the build and every
+ tool that checks its sources take the tallest local source up to that height, the same file; `--refetch` re-cuts
+ only the taller windows. Without it a project fetches and renders exactly as before.
- **`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.
diff --git a/editor/app/api/media/fetch-window/[jobId]/route.ts b/editor/app/api/media/fetch-window/[jobId]/route.ts
@@ -1,5 +1,5 @@
import path from "node:path";
-import { stat } from "node:fs/promises";
+import { readFile, stat } from "node:fs/promises";
import { NextResponse } from "next/server";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { authorizeWorkerRequest } from "yt-dlp-transcript-common/lib/workerToken";
@@ -7,6 +7,7 @@ import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
import { readJobMeta } from "yt-dlp-transcript-common/jobs/jobMeta";
import { getJobEntry, readLogChunk } from "yt-dlp-transcript-common/jobs/listJobs";
import { clipWindowPath } from "yt-dlp-transcript-common/lib/clipWindow-server";
+import { clipWindowSidecar } from "yt-dlp-transcript-common/lib/clipWindow";
import { loadSavedVideo } from "yt-dlp-transcript-common/lib/savedVideo-server";
import { savedVideoPath } from "yt-dlp-transcript-common/lib/savedVideo";
@@ -72,9 +73,17 @@ export async function GET(
const from = Number(p.from);
const to = Number(p.to);
if (Number.isFinite(from) && Number.isFinite(to)) {
- file = clipWindowPath(videoDir, from, to);
+ // A tall ask's window is its tier's (`<from>-<to>.h<tier>.mp4`).
+ const tier = Number(p.tier);
+ const t = Number.isInteger(tier) && tier > 0 ? tier : undefined;
+ file = clipWindowPath(videoDir, from, to, t);
out.from = from;
out.to = to;
+ // The window's height as its fetch recorded it (the height tier).
+ const h = await readFile(path.join(videoDir, "clips", clipWindowSidecar(from, to, t)), "utf8")
+ .then((s) => Number((JSON.parse(s) as { height?: unknown }).height))
+ .catch(() => NaN);
+ if (Number.isInteger(h) && h > 0) out.height = h;
}
} else {
const pointer = await loadSavedVideo(videoDir);
diff --git a/editor/app/api/media/fetch-window/route.ts b/editor/app/api/media/fetch-window/route.ts
@@ -108,6 +108,9 @@ function answer(outcome: FetchMediaOutcome): NextResponse {
bytes: outcome.bytes,
provenance: outcome.provenance,
...(outcome.height !== undefined ? { height: outcome.height } : {}),
+ // A tall ask answered lower than it asked (the height tier), and why.
+ ...("belowAsked" in outcome && outcome.belowAsked ? { belowAsked: outcome.belowAsked } : {}),
+ ...("clampedFrom" in outcome && outcome.clampedFrom !== undefined ? { clampedFrom: outcome.clampedFrom } : {}),
},
{ status: 200 },
);
diff --git a/editor/app/api/ops/evict-clips/route.ts b/editor/app/api/ops/evict-clips/route.ts
@@ -5,7 +5,8 @@ export const dynamic = "force-dynamic";
// POST { olderThanDays: number, slug?: string, dryRun?: boolean }
// | { slug: string, id: string, windows?: ["<from>-<to>", …],
-// covering?: [{from, to}, …], olderThanDays?: number, dryRun?: boolean }
+// covering?: [{from, to}, …], olderThanDays?: number,
+// tiers?: "all" | "plain" | "tiered", dryRun?: boolean }
// -> { ok: true, jobId }
//
// AN ADAPTER, like every route here: one call to the action the /storage button
@@ -18,11 +19,13 @@ export const dynamic = "force-dynamic";
// result — see controller/evictClipWindows.ts. TARGETED (`slug` + `id`), the
// caller knows which windows are bad: every window of that video, or those
// named in `windows` (the cache's `<from>-<to>` stems), or any overlapping a
-// `covering` span — the form `umtool fetch --refetch` asks with.
+// `covering` span — the form `umtool fetch --refetch` asks with. `tiers`
+// narrows to the plain `<from>-<to>` windows or the taller tiered ones (the
+// height tier); default "all", both.
export async function POST(request: Request) {
return ops(
request,
- ["olderThanDays", "slug", "id", "windows", "covering", "dryRun"],
+ ["olderThanDays", "slug", "id", "windows", "covering", "tiers", "dryRun"],
async (body) => {
const raw = body.olderThanDays;
const olderThanDays =
@@ -37,6 +40,7 @@ export async function POST(request: Request) {
...(body.windows !== undefined ? { windows: body.windows } : {}),
...(body.covering !== undefined ? { covering: body.covering } : {}),
...(olderThanDays !== undefined ? { olderThanDays } : {}),
+ ...(body.tiers !== undefined ? { tiers: body.tiers } : {}),
...(dryRun ? { dryRun: true } : {}),
}),
);
diff --git a/editor/app/api/ops/fetch-windows/route.ts b/editor/app/api/ops/fetch-windows/route.ts
@@ -53,6 +53,13 @@ export const dynamic = "force-dynamic";
// down or held is `refused` for its group, and the other groups still start.
// Re-running the same body is the resume: fetched windows are cached.
//
+// `maxHeight` above 720 is a TALL ask (the height tier, lib/clipWindow.ts),
+// clamped to settings.clips.windowMaxHeight (`clampedFrom` says so): its
+// windows are their own cache entries beside the plain 720 ones, cut from the
+// saved copy when it is taller, else fetched; a held window lower than asked
+// with no taller saved copy is used as it is and listed in `lower` with its
+// height and why — never re-fetched for height. `siteId` stays at 720.
+//
// A window of a recording its availability says is deleted or private is
// refused (unresolved) unless the item names a `webpageUrl` (a copy: find-copy)
// or `"force": true` (the reading is stale — or check its availability again).
@@ -88,7 +95,7 @@ export const dynamic = "force-dynamic";
//
// A big list goes in a file: `pnpm ops fetch-windows --file list.json`.
-const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl", "force"];
+const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl", "force", "refetch"];
function optItemString(e: OpsBody, key: string, where: string): string | undefined {
const v = e[key];
@@ -97,6 +104,11 @@ function optItemString(e: OpsBody, key: string, where: string): string | undefin
return v.trim() || undefined;
}
+function reqItemBool(v: unknown, where: string, key: string): boolean {
+ if (typeof v !== "boolean") throw new OpsInputError(`"${where}.${key}" must be a boolean`);
+ return v;
+}
+
function reqItemForce(v: unknown, where: string): boolean {
if (typeof v !== "boolean") throw new OpsInputError(`"${where}.force" must be a boolean`);
return v;
@@ -154,6 +166,8 @@ function reqWindowItems(body: OpsBody): FetchWindowsItem[] {
...(typeof pad === "number" ? { pad } : {}),
webpageUrl: optItemString(e, "webpageUrl", where),
...(e.force !== undefined ? { force: reqItemForce(e.force, where) } : {}),
+ // A refetch (umtool fetch --refetch): a lower held window does not answer it.
+ ...(e.refetch !== undefined ? { refetch: reqItemBool(e.refetch, where, "refetch") } : {}),
};
});
}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/FetchedWindows.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/FetchedWindows.tsx
@@ -10,6 +10,10 @@ export type FetchedWindow = {
to: number;
bytes: number;
provenance: ClipProvenance | null;
+ // A taller cut kept beside the plain window (the height tier), and the
+ // picture height its sidecar records.
+ tier?: number;
+ height?: number;
};
// WHO ASKED, FOR WHAT, AND WHY — the three things a `clips/` directory has to
@@ -38,6 +42,8 @@ export function FetchedWindows({ windows }: { windows: FetchedWindow[] }) {
{w.from.toFixed(2)}–{w.to.toFixed(2)}{" "}
<span className="text-muted-foreground">
({formatDuration(w.to - w.from)}) · {formatBytes(w.bytes)}
+ {w.height ? ` · ${w.height}p` : ""}
+ {w.tier ? ` · the ${w.tier}p cut, beside the 720 one` : ""}
</span>
</span>
<span className="text-xs text-muted-foreground">
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -189,7 +189,8 @@ export default async function VideoDetailPage({
// The windows another tool asked this editor to fetch. One readdir of
// data/<id>/clips/ plus a stat per file — and no per-CHANNEL count anywhere,
// because that would be a walk of every video dir to draw one number.
- const clipWindows = await listClipWindows(videoDir);
+ // The taller cuts too (the height tier): each is bytes on this disk.
+ const clipWindows = await listClipWindows(videoDir, { tiers: true });
// Where each subtitle track came from, so the panel can say "YouTube
// auto-captions" vs "manual captions" — and offer to replace the former with a
// transcript of our own. One 4 KB head read per VTT (see subtitleProvenance).
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -93,18 +93,26 @@ import {
} from "yt-dlp-transcript-common/lib/savedVideo";
import {
MAX_CLIP_WINDOW_SECONDS,
+ clampWindowCap,
isFetchMaxHeight,
+ isWindowTier,
+ windowTierOf,
type ClipProvenance,
} from "yt-dlp-transcript-common/lib/clipWindow";
-import { clipWindowPath } from "yt-dlp-transcript-common/lib/clipWindow-server";
+import { clipWindowPath, windowHeightOf } from "yt-dlp-transcript-common/lib/clipWindow-server";
+import { windowMaxHeightOf } from "yt-dlp-transcript-common/lib/clipSettings";
+import { tallerFromSaved } from "yt-dlp-transcript-common/lib/clipWindowTier-server";
+import { renderModeHeldNow } from "yt-dlp-transcript-common/lib/renderHold";
import {
ffprobeWindowProbe,
findInSyncContainingClipWindow,
+ findInSyncTieredWindowHolding,
judgeClipWindow,
setAsideDesyncedWindow,
} from "yt-dlp-transcript-common/lib/clipWindowSync-server";
import { desyncedWindowMessage } from "yt-dlp-transcript-common/lib/clipWindowSync";
import {
+ cutPlainFromTieredWindow,
cutSavedVideoWindow,
savedWindowSource,
} from "yt-dlp-transcript-common/lib/savedVideoWindow-server";
@@ -1515,6 +1523,12 @@ export type FetchMediaOutcome =
bytes: number;
provenance: ClipProvenance | SavedVideoOrigin | null;
height?: number;
+ // THE HEIGHT TIER (lib/clipWindow.ts): a tall ask answered by a window
+ // LOWER than it asked, used as it is — the height asked, and why no
+ // taller one was cut (no saved copy, or one no taller). A clamped ask
+ // says the height it asked before clips.windowMaxHeight held it.
+ belowAsked?: { asked: number; why: string };
+ clampedFrom?: number;
}
// Queued. `file` is where the window WILL be; for a full source it is not
// knowable until the container's real extension is (null until then).
@@ -1579,6 +1593,9 @@ export async function fetchWindowAction(req: {
// the default (DEFAULT_CLIP_MAX_HEIGHT). Checked again here for the same
// reason the window is: a replayed spec is a file on disk.
maxHeight?: number;
+ // THE TIER a Retry carries in its spec (lib/clipWindow.ts windowTierOf): it
+ // wins over `maxHeight` and today's clips.windowMaxHeight.
+ tier?: number;
// Hand back the StreamActionResult instead of detaching it. Set by Retry,
// which renders the log; the HTTP route leaves it off and polls.
stream?: boolean;
@@ -1615,6 +1632,17 @@ export async function fetchWindowAction(req: {
}
const r = await loadConfigOrError(slug);
if (!r.ok) return { ok: false, status: 404, error: r.error };
+ // THE HEIGHT ASKED, against the ceiling (clips.windowMaxHeight): none is the
+ // plain 720 window as before; above 720 is a tall ask, its own tier beside
+ // the plain window (lib/clipWindow.ts).
+ const ceiling = windowMaxHeightOf(getSettings().clips);
+ const fixedTier = isWindowTier(req.tier) ? req.tier : undefined;
+ const { cap: asked, clampedFrom } =
+ fixedTier !== undefined ? { cap: fixedTier as number | undefined, clampedFrom: undefined as number | undefined } : clampWindowCap(req.maxHeight, ceiling);
+ const tier = fixedTier ?? windowTierOf(asked, ceiling);
+ // The network's cap: the tier when tall (asks of 900 and 1080 share a file).
+ const cap = tier ?? asked;
+ const clamped = clampedFrom !== undefined ? { clampedFrom } : {};
// Before the cache: a local library's recording has no window to hold.
const localRefusal = localMediaFetchRefusal(slug, r.config, req.videoId);
if (localRefusal) return { ok: false, status: 409, error: localRefusal };
@@ -1631,8 +1659,10 @@ export async function fetchWindowAction(req: {
// AND IN SYNC (lib/clipWindowSync.ts): a held window whose picture runs off
// its sound is set aside here (`<from>-<to>.desynced.<ext>`), and the span
// goes on as missing — to the saved container below, else the network.
+ const heightProbe = (file: string) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file });
const { hit } = await findInSyncContainingClipWindow(videoDir, from, to, {
probe: ffprobeWindowProbe(paths.ffprobeBin),
+ ...(tier !== undefined ? { maxHeight: tier, heightProbe } : {}),
});
// ONE CLOCK PER RECORDING (controller/fetchWindows.ts): a whole-recording
// channel's held window answers only when cut through the video's current
@@ -1642,14 +1672,28 @@ export async function fetchWindowAction(req: {
hit &&
wholeRecordingFor(getSettings(), channelConfigPlatform(r.config) ?? "", {}, undefined) &&
!(await heldWindowOnClock(videoDir, hit.provenance));
- if (hit && !clocked) {
- // The window's own height, read off its header: a window holds seconds,
- // so the probe is quick, and it is the only record of how tall a window
- // fetched under an earlier cap is.
- const height = await probeVideoHeight({
- ffprobeBin: paths.ffprobeBin,
- file: hit.path,
- });
+ // A TALL ASK OVER A LOWER WINDOW: cut a taller one beside it from the saved
+ // copy when that is taller (below); else the window as it is, and why.
+ let taller: Extract<Awaited<ReturnType<typeof tallerFromSaved>>, { kind: "cut" }> | null = null;
+ let belowAsked: { asked: number; why: string } | undefined;
+ // RENDER MODE (H): a tall cut waits while a render holds the machine. A
+ // request cannot wait that long, so it is answered with what there is now —
+ // the lower window, or (with none) the plain cut — and says why.
+ const renderBy = tier !== undefined ? renderModeHeldNow() : null;
+ const renderWhy = renderBy
+ ? `render mode holds the machine (${renderBy}): the ${tier}p cut waits — ask again when it ends`
+ : null;
+ if (hit && !clocked && tier !== undefined && (hit.height ?? 0) < tier) {
+ const t = await tallerFromSaved({ paths, slug, videoDir, from, to, hitHeight: hit.height ?? null, cap: tier });
+ if (t.kind === "cut" && !renderWhy) taller = t;
+ else if (t.kind === "cut") belowAsked = { asked: tier, why: renderWhy! };
+ else if (t.kind === "lower") belowAsked = { asked: tier, why: t.why };
+ }
+ if (hit && !clocked && !taller) {
+ // The window's own height. A tall ask reads its sidecar's record, else
+ // probes once and records it there (windowHeightOf); any other ask probes
+ // it and writes nothing, as before the tier.
+ const height = tier !== undefined ? await windowHeightOf(hit, heightProbe) : await heightProbe(hit.path);
return {
ok: true,
cached: true,
@@ -1659,6 +1703,8 @@ export async function fetchWindowAction(req: {
bytes: hit.bytes,
provenance: hit.provenance,
...(height !== null ? { height } : {}),
+ ...(belowAsked ? { belowAsked } : {}),
+ ...clamped,
};
}
@@ -1666,7 +1712,7 @@ export async function fetchWindowAction(req: {
// while its window is still queued or downloading is answered with that
// job, not a second one for the same seconds (jobs/windowJobs.ts). Retry
// (`stream: true`) is an explicit re-run and is not deduplicated.
- if (!req.stream) {
+ if (!req.stream && !taller) {
// A batch's item names the record, this job the directory: either may be
// the one already fetching this window (release 23 F1).
const live = getRegistry().list();
@@ -1678,7 +1724,7 @@ export async function fetchWindowAction(req: {
ok: true,
cached: false,
jobId: inFlight.jobId,
- file: clipWindowPath(videoDir, inFlight.from, inFlight.to),
+ file: clipWindowPath(videoDir, inFlight.from, inFlight.to, tier),
from: inFlight.from,
to: inFlight.to,
existing: true,
@@ -1694,7 +1740,7 @@ export async function fetchWindowAction(req: {
// network as before; a pointer whose container cannot be read is REFUSED —
// falling through would spend the source's patience (or, for a deleted
// channel, fail) on seconds that are on a drive somebody can plug in.
- const saved = await savedWindowSource({ paths, slug, videoDir, from, to });
+ const saved = taller ? taller.source : await savedWindowSource({ paths, slug, videoDir, from, to });
if (saved.kind === "unreadable") {
return { ok: false, status: 503, error: saved.error };
}
@@ -1708,6 +1754,8 @@ export async function fetchWindowAction(req: {
return { ok: false, status: 503, error: (e as Error).message };
}
let cut;
+ // Held by render mode, a tall ask with nothing on disk gets the plain cut now.
+ const cutTier = renderWhy ? undefined : tier;
try {
cut = await cutSavedVideoWindow({
paths,
@@ -1716,14 +1764,14 @@ export async function fetchWindowAction(req: {
from,
to,
provenance: req.provenance,
+ // A tall ask's cut is its own tier, beside any plain window.
+ ...(cutTier !== undefined ? { tier: cutTier } : {}),
});
} catch (e) {
return { ok: false, status: 500, error: (e as Error).message };
}
- const height = await probeVideoHeight({
- ffprobeBin: paths.ffprobeBin,
- file: cut.path,
- });
+ // Recorded by the cut (the box's arithmetic); probed only if it was not.
+ const height = cut.height ?? (await heightProbe(cut.path));
safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
return {
ok: true,
@@ -1734,9 +1782,45 @@ export async function fetchWindowAction(req: {
bytes: cut.bytes,
provenance: cut.provenance,
...(height !== null ? { height } : {}),
+ ...(renderWhy && tier !== undefined ? { belowAsked: { asked: tier, why: renderWhy } } : {}),
+ ...clamped,
};
}
+ // A PLAIN MISS A TALLER WINDOW HOLDS (D): the 720 window is cut here from
+ // the tiered file — nothing fetched, nothing on disk changed but the new
+ // window. A cut that fails goes on to the network as before.
+ if (tier === undefined) {
+ // Only an in-sync tiered window (a desynced one is set aside, as any).
+ const { hit: tiered } = await findInSyncTieredWindowHolding(videoDir, from, to, {
+ probe: ffprobeWindowProbe(paths.ffprobeBin),
+ });
+ if (tiered) {
+ try {
+ await assertChannelTextReadable(paths, slug);
+ } catch (e) {
+ return { ok: false, status: 503, error: (e as Error).message };
+ }
+ try {
+ const cut = await cutPlainFromTieredWindow({ paths, videoDir, tiered, from, to, provenance: req.provenance });
+ safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
+ return {
+ ok: true,
+ cached: true,
+ file: cut.path,
+ from: cut.from,
+ to: cut.to,
+ bytes: cut.bytes,
+ provenance: cut.provenance,
+ ...clamped,
+ };
+ } catch (e) {
+ // As a failed cut from a saved copy: refused, never a fetch instead.
+ return { ok: false, status: 500, error: (e as Error).message };
+ }
+ }
+ }
+
const url =
req.webpageUrl?.trim() ||
(await findVideoSourceUrl(paths, slug, videoId, r.config));
@@ -1814,6 +1898,8 @@ export async function fetchWindowAction(req: {
webpageUrl: url,
queueKey: req.queueKey,
...(req.maxHeight !== undefined ? { maxHeight: req.maxHeight } : {}),
+ // Where the window lands (the [jobId] route names the file from it).
+ ...(tier !== undefined ? { tier } : {}),
// A Retry keeps the mode it was asked with.
...(storedMode !== "never" ? { storedUrl: storedMode } : {}),
...req.provenance,
@@ -1835,7 +1921,8 @@ export async function fetchWindowAction(req: {
from,
to,
provenance: req.provenance,
- maxHeight: req.maxHeight,
+ maxHeight: cap,
+ ...(tier !== undefined ? { tier } : {}),
cookiePolicy: resolveCookiePolicy(settings, r.config),
onLog,
signal,
@@ -1875,6 +1962,7 @@ export async function fetchWindowAction(req: {
to: got.to,
bytes: got.bytes,
provenance: got.provenance,
+ ...(tier !== undefined ? { tier } : {}),
};
const { sync } = await judgeClipWindow(win, { probe: ffprobeWindowProbe(paths.ffprobeBin) });
if (sync && !sync.ok) {
@@ -1900,7 +1988,7 @@ export async function fetchWindowAction(req: {
ok: true,
cached: false,
jobId: res.jobId,
- file: clipWindowPath(videoDir, from, to),
+ file: clipWindowPath(videoDir, from, to, tier),
from,
to,
};
@@ -1943,6 +2031,8 @@ export async function replayFetchWindowAction(req: {
provenance: FetchWindowProvenance;
queueKey?: string;
maxHeight?: number;
+ // The tier the job was queued at (its spec), not today's settings'.
+ tier?: number;
storedUrl?: StoredUrlMode;
}): Promise<StreamActionResult> {
const r = await fetchWindowAction({ ...req, stream: true });
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -17,11 +17,19 @@ import { windowInFlight } from "yt-dlp-transcript-common/jobs/windowJobs";
import { detectPlatform, queueKeyForUrl } from "yt-dlp-transcript-common/lib/platform";
import {
MAX_CLIP_WINDOW_SECONDS,
+ PLAIN_WINDOW_MAX_HEIGHT,
+ clampWindowCap,
isFetchMaxHeight,
+ isWindowTier,
+ windowTierOf,
} from "yt-dlp-transcript-common/lib/clipWindow";
+import { windowMaxHeightOf } from "yt-dlp-transcript-common/lib/clipSettings";
+import { tallerFromSaved } from "yt-dlp-transcript-common/lib/clipWindowTier-server";
+import { probeVideoHeight } from "yt-dlp-transcript-common/ytdlp/ffprobeDuration";
import {
ffprobeWindowProbe,
findInSyncContainingClipWindow,
+ findInSyncTieredWindowHolding,
} from "yt-dlp-transcript-common/lib/clipWindowSync-server";
import { sourceGoneState } from "yt-dlp-transcript-common/lib/sourceGone-server";
import { savedWindowSource } from "yt-dlp-transcript-common/lib/savedVideoWindow-server";
@@ -173,8 +181,15 @@ export type FetchWindowsActionResult =
// Channels registered as remote-only for these windows (a dry run: the
// ones that would be), each once.
registered: string[];
+ // THE HEIGHT TIER (lib/clipWindow.ts): of `cached`, the windows LOWER
+ // than a tall ask that no taller cut can come from, with their height
+ // and why; and the asked height when clips.windowMaxHeight clamped it.
+ lower?: FetchWindowsLower[];
+ clampedFrom?: number;
};
+export type FetchWindowsLower = { item: FetchWindowsItem; file: string; height: number | null; asked: number; why: string };
+
export type FetchWindowsInFlight = { item: FetchWindowsItem; jobId: string };
// The window rules the HTTP door enforces, asked again here: a replayed spec is
@@ -215,9 +230,19 @@ async function planFetchWindows(
registered: string[];
// The planned items (as grouped) whose record stores a trusted media URL.
stored: Set<FetchWindowsItem>;
+ lower: FetchWindowsLower[];
+ clampedFrom?: number;
}> {
const paths = getPaths();
const settings = getSettings();
+ // A tall ask (above 720, clamped to clips.windowMaxHeight) reads the tiered
+ // windows too and may plan a taller cut beside a lower one; any other ask
+ // plans exactly as before (the controller decides the same at run time).
+ const ceiling = windowMaxHeightOf(settings.clips);
+ const { cap, clampedFrom } = clampWindowCap(maxHeight, ceiling);
+ const tier = windowTierOf(cap, ceiling);
+ const lower: FetchWindowsLower[] = [];
+ const heightProbe = (file: string) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file });
const configs = new Map<string, ChannelConfig | null>();
const groups = new Map<string, FetchWindowsGroup>();
const cached: FetchWindowsItem[] = [];
@@ -288,13 +313,31 @@ async function planFetchWindows(
const held = await findInSyncContainingClipWindow(videoDir, item.from, item.to, {
probe: ffprobeWindowProbe(paths.ffprobeBin),
setAside: false,
+ ...(tier !== undefined ? { maxHeight: tier, heightProbe } : {}),
});
// ONE CLOCK PER RECORDING (controller/fetchWindows.ts): a whole-recording
// channel's held window answers only when it was cut through the video's
// current time map; otherwise the span goes on (to the saved container,
// whose job measures the map and retires the off-clock window).
const clockedChannel = wholeRecordingFor(settings, channelConfigPlatform(config) ?? "", item, wholeRecording);
- if (held.hit && (!clockedChannel || (await heldWindowOnClock(videoDir, held.hit.provenance)))) {
+ // A REFETCH on a tall ask is not answered by a lower window: planned on to
+ // the saved copy (a cut at its tier) or, with none, its platform's queue.
+ const refetchPast = tier !== undefined && item.refetch === true && (held.hit?.height ?? 0) < tier;
+ if (held.hit && !refetchPast && (!clockedChannel || (await heldWindowOnClock(videoDir, held.hit.provenance)))) {
+ const hitHeight = held.hit.height ?? null;
+ if (tier !== undefined && (hitHeight ?? 0) < tier) {
+ // Lower than asked: a taller cut from the saved copy when it is
+ // taller (planned on the saved-video queue), else the window as it is.
+ const t = await tallerFromSaved({ paths, slug: item.slug, videoDir, from: item.from, to: item.to, hitHeight, cap: tier });
+ if (t.kind === "cut") {
+ const queueKey = resolveQueueKey(SAVED_VIDEO_CLIP_QUEUE, queueOverride);
+ const group = groups.get(queueKey) ?? { platform: SAVED_VIDEO_CLIP_PLATFORM, queueKey, items: [] };
+ group.items.push(item);
+ groups.set(queueKey, group);
+ continue;
+ }
+ if (t.kind === "lower") lower.push({ item, file: held.hit.file, height: hitHeight, asked: tier, why: t.why });
+ }
cached.push(item);
continue;
}
@@ -322,7 +365,20 @@ async function planFetchWindows(
unresolved.push({ item, error: saved.error });
continue;
}
- if (saved.kind === "covers") {
+ // ...or, on a plain ask, a taller (tiered) window of the span: the job
+ // cuts the 720 window from it locally (the height tier, D), on the same
+ // queue no platform shares.
+ if (
+ saved.kind === "covers" ||
+ (tier === undefined &&
+ (
+ await findInSyncTieredWindowHolding(videoDir, item.from, item.to, {
+ probe: ffprobeWindowProbe(paths.ffprobeBin),
+ setAside: false,
+ record: false,
+ })
+ ).hit)
+ ) {
const queueKey = resolveQueueKey(SAVED_VIDEO_CLIP_QUEUE, queueOverride);
const group = groups.get(queueKey) ?? {
platform: SAVED_VIDEO_CLIP_PLATFORM,
@@ -427,7 +483,16 @@ async function planFetchWindows(
}
groups.set(queueKey, group);
}
- return { groups: [...groups.values()], cached, inFlight, unresolved, stored, registered };
+ return {
+ groups: [...groups.values()],
+ cached,
+ inFlight,
+ unresolved,
+ stored,
+ registered,
+ lower,
+ ...(clampedFrom !== undefined ? { clampedFrom } : {}),
+ };
}
// The door each group passes before its job is queued: the platform's hold,
@@ -457,6 +522,9 @@ export async function fetchWindowsJobAction(req: {
manifest?: string;
siteId?: string;
maxHeight?: number;
+ // The tier a Retry carries in its spec (lib/clipWindow.ts windowTierOf);
+ // absent, decided now from maxHeight and clips.windowMaxHeight, and stored.
+ tier?: number;
queueKey: string;
storedUrl?: StoredUrlMode;
minGapSeconds?: number;
@@ -476,6 +544,10 @@ export async function fetchWindowsJobAction(req: {
const paths = getPaths();
const requestedAt = new Date().toISOString();
const slugs = [...new Set(req.items.map((i) => i.slug))];
+ // THE TIER, fixed at queue time and kept in the spec: a Retry cuts the same
+ // file whatever the settings say by then.
+ const ceiling = windowMaxHeightOf(getSettings().clips);
+ const tier = isWindowTier(req.tier) ? req.tier : windowTierOf(clampWindowCap(req.maxHeight, ceiling).cap, ceiling);
return runManagedFunction({
kind: "fetch-windows",
queueKey: req.queueKey,
@@ -495,6 +567,7 @@ export async function fetchWindowsJobAction(req: {
...(req.manifest ? { manifest: req.manifest } : {}),
...(req.siteId ? { siteId: req.siteId } : {}),
...(req.maxHeight !== undefined ? { maxHeight: req.maxHeight } : {}),
+ ...(tier !== undefined ? { tier } : {}),
// A Retry keeps the mode it was asked with.
...(req.storedUrl && req.storedUrl !== "never" ? { storedUrl: req.storedUrl } : {}),
...(req.minGapSeconds !== undefined ? { minGapSeconds: req.minGapSeconds } : {}),
@@ -512,6 +585,7 @@ export async function fetchWindowsJobAction(req: {
requestedAt,
},
maxHeight: req.maxHeight,
+ ...(tier !== undefined ? { tier } : {}),
storedUrl: req.storedUrl,
minGapSeconds: req.minGapSeconds,
...(req.wholeRecording === false ? { wholeRecording: false } : {}),
@@ -561,7 +635,7 @@ export async function fetchWindowsAction(
const archive: ConnectedArchive | null = req.archive?.trim()
? findConnectedArchive(connectedArchives(getSettings().remoteArchives), req.archive)
: null;
- const { groups, cached, inFlight, unresolved, stored, registered } = await planFetchWindows(
+ const { groups, cached, inFlight, unresolved, stored, registered, lower, clampedFrom } = await planFetchWindows(
req.items,
req.queueKey,
req.maxHeight,
@@ -575,7 +649,17 @@ export async function fetchWindowsAction(
},
);
if (registered.length && !req.dryRun) safeRevalidate(["/channels"]);
- const base = { groups, cached, inFlight, unresolved, registered, jobs: [], refused: [] };
+ const base = {
+ groups,
+ cached,
+ inFlight,
+ unresolved,
+ registered,
+ jobs: [],
+ refused: [],
+ ...(lower.length ? { lower } : {}),
+ ...(clampedFrom !== undefined ? { clampedFrom } : {}),
+ };
if (req.dryRun) return { ok: true, dryRun: true, ...base };
if (groups.length === 0) return { ok: true, dryRun: false, ...base };
@@ -649,7 +733,19 @@ export async function fetchWindowsAction(
error: refused.map((r) => `${r.platform}: ${r.error}`).join("; "),
};
}
- return { ok: true, dryRun: false, groups, cached, inFlight, unresolved, registered, jobs, refused };
+ return {
+ ok: true,
+ dryRun: false,
+ groups,
+ cached,
+ inFlight,
+ unresolved,
+ registered,
+ jobs,
+ refused,
+ ...(lower.length ? { lower } : {}),
+ ...(clampedFrom !== undefined ? { clampedFrom } : {}),
+ };
}
export type FetchMissingEvidenceResult =
@@ -729,7 +825,10 @@ async function fetchMissingFor(
requestedBy: "reports",
manifest: id,
...(opts.siteId ? { siteId: opts.siteId } : {}),
- maxHeight: opts.maxHeight,
+ // PINNED AT 720 (the height tier's ruling): a site's evidence is cut from
+ // the plain window in the 1280×720 box, so a site-driven fetch never asks
+ // more — a larger ask is held to 720, none stays the 720 default.
+ maxHeight: opts.maxHeight !== undefined ? Math.min(opts.maxHeight, PLAIN_WINDOW_MAX_HEIGHT) : undefined,
dryRun: opts.dryRun,
...(opts.storedUrl ? { storedUrl: opts.storedUrl } : {}),
...(opts.wholeRecording === false ? { wholeRecording: false } : {}),
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsTier.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsTier.test.ts
@@ -0,0 +1,103 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test 'app/channels/*/videos/fetchWindowsTier.test.ts'
+//
+// The fetch-windows PLAN and THE HEIGHT TIER (lib/clipWindow.ts): a tall ask
+// over a held window lower than the saved copy plans a cut beside it on the
+// saved-video queue; one over a window as tall as the saved copy answers it
+// as cached and lists it in `lower` with why; no ask plans as before. A temp
+// corpus with a real (tiny) saved container; nothing is started.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-windows-tier-"));
+const SLUG = "demo-channel";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+delete process.env.FFPROBE_BIN;
+delete process.env.FFMPEG_BIN;
+
+await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 }));
+await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true });
+await writeFile(
+ path.join(ROOT, "channels", SLUG, "config.json"),
+ JSON.stringify({ name: "Demo", handling: "youtube", url: "https://www.youtube.com/@demo" }),
+);
+
+// A video whose saved copy is a 160×90 picture, with a held window [0, 8]
+// whose sidecar records `height`.
+async function video(id: string, heldHeight: number): Promise<void> {
+ const videoDir = path.join(ROOT, "channels", SLUG, "data", id);
+ const store = path.join(ROOT, "saved-videos", SLUG, id);
+ const clips = path.join(videoDir, "clips");
+ await mkdir(clips, { recursive: true });
+ await mkdir(store, { recursive: true });
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id, webpage_url: `https://www.youtube.com/watch?v=${id}` }));
+ execFileSync("ffmpeg", [
+ "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=8",
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
+ path.join(store, "source-media.mp4"),
+ ]);
+ await writeFile(
+ path.join(videoDir, "saved-video.json"),
+ JSON.stringify({ storedAt: "", dir: store, file: "source-media.mp4", bytes: 1, keepReason: "pin" }),
+ );
+ await writeFile(path.join(clips, "0.00-8.00.mp4"), "held");
+ await writeFile(path.join(clips, "0.00-8.00.json"), JSON.stringify({ requestedBy: "reports", height: heldHeight }));
+}
+await video("short1", 72);
+await video("equal1", 90);
+
+const { fetchWindowsAction } = await import("./fetchWindowsAction");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const items = [
+ { slug: SLUG, id: "short1", from: 1, to: 3, clipId: "c#1" },
+ { slug: SLUG, id: "equal1", from: 1, to: 3, clipId: "c#2" },
+];
+
+test("a tall ask plans a taller cut beside a window lower than the saved copy; one as tall as the copy gives is a hit", async () => {
+ const r = await fetchWindowsAction({ items, requestedBy: "umtool", maxHeight: 1080, dryRun: true });
+ assert.ok(r.ok);
+ if (!r.ok) return;
+ assert.deepEqual(
+ r.groups.map((g) => [g.platform, g.items.map((i) => i.clipId)]),
+ [["saved-video", ["c#1"]]],
+ );
+ // 90p is all a 160×90 copy gives in the 1080 box: an ordinary hit, not "lower".
+ assert.deepEqual(r.cached.map((i) => i.clipId), ["c#2"]);
+ assert.equal(r.lower, undefined);
+});
+
+test("no ask plans as before: both held windows are cached, nothing listed lower", async () => {
+ const r = await fetchWindowsAction({ items, requestedBy: "umtool", dryRun: true });
+ assert.ok(r.ok);
+ if (!r.ok) return;
+ assert.deepEqual(r.cached.map((i) => i.clipId), ["c#1", "c#2"]);
+ assert.equal(r.groups.length, 0);
+ assert.equal(r.lower, undefined);
+});
+
+test("an ask above clips.windowMaxHeight is planned at the ceiling, and says so", async () => {
+ await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ minFreeDiskGB: 0, clips: { windowMaxHeight: 1080 } }));
+ const r = await fetchWindowsAction({ items: [items[1]], requestedBy: "umtool", maxHeight: 2160, dryRun: true });
+ assert.ok(r.ok);
+ if (!r.ok) return;
+ assert.equal(r.clampedFrom, 2160);
+ assert.deepEqual(r.cached.map((i) => i.clipId), ["c#2"]);
+});
+
+test("a tall refetch is not answered by a held window: planned onto the saved copy's cut", async () => {
+ await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ minFreeDiskGB: 0 }));
+ const r = await fetchWindowsAction({ items: [{ ...items[1], refetch: true }], requestedBy: "umtool", maxHeight: 1080, dryRun: true });
+ assert.ok(r.ok);
+ if (!r.ok) return;
+ assert.deepEqual(r.cached, []);
+ assert.deepEqual(r.groups.map((g) => [g.platform, g.items.map((i) => i.clipId)]), [["saved-video", ["c#2"]]]);
+ assert.equal(r.lower, undefined);
+});
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -126,6 +126,8 @@ function windowItems(v: unknown): FetchWindowsItem[] {
webpageUrl: str(r.webpageUrl),
// find-copy's copy (release 29 E2): a replay records it again.
copy: coerceClipCopy(r.copy),
+ // A refetch stays one (the height tier).
+ ...(r.refetch === true ? { refetch: true } : {}),
});
}
return out;
@@ -219,6 +221,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
},
queueKey,
maxHeight: num(p.maxHeight),
+ // The tier it was queued at (the height tier), not today's settings'.
+ ...(num(p.tier) !== undefined ? { tier: num(p.tier) } : {}),
...(isStoredUrlMode(p.storedUrl) ? { storedUrl: p.storedUrl } : {}),
...(num(p.minGapSeconds) !== undefined ? { minGapSeconds: num(p.minGapSeconds) } : {}),
});
@@ -240,6 +244,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
manifest: str(p.manifest),
siteId: str(p.siteId),
maxHeight: num(p.maxHeight),
+ // The tier it was queued at (the height tier), not today's settings'.
+ ...(num(p.tier) !== undefined ? { tier: num(p.tier) } : {}),
queueKey,
// Release 32 R5: a replay keeps the stored-URL mode it was asked with.
...(isStoredUrlMode(p.storedUrl) ? { storedUrl: p.storedUrl } : {}),
diff --git a/editor/app/storage/actions.ts b/editor/app/storage/actions.ts
@@ -32,7 +32,7 @@ import { channelMediaBusyReason } from "../channels/lib/mediaBusy";
import { enqueueRepointJob } from "./lib/repointJob";
import { enqueueSavedVideosRelocation } from "./lib/savedVideosJob";
import { enqueueEvictClipWindows } from "./lib/evictClipsJob";
-import { parseEvictTargets } from "yt-dlp-transcript-common/controller/evictClipWindows";
+import { EVICT_TIERS, isEvictTiers, parseEvictTargets } from "yt-dlp-transcript-common/controller/evictClipWindows";
import { enqueueCheckClipWindows } from "./lib/checkWindowsJob";
import { savedVideosStoreBusyReason } from "./lib/storeBusy";
import { refreshLocationHealth } from "yt-dlp-transcript-common/controller/storageWatch";
@@ -465,11 +465,16 @@ export async function evictClipWindowsAction(opts: {
windows?: unknown;
covering?: unknown;
olderThanDays?: number;
+ // "all" (default) | "plain" | "tiered": which windows of a span (the height tier).
+ tiers?: unknown;
dryRun?: boolean;
}): Promise<StreamActionResult> {
if (opts.id !== undefined && opts.slug === undefined) {
return { ok: false, error: "A video is named within a channel: give its slug too." };
}
+ if (opts.tiers !== undefined && !isEvictTiers(opts.tiers)) {
+ return { ok: false, error: `"tiers" must be one of ${EVICT_TIERS.join(", ")}` };
+ }
if ((opts.windows !== undefined || opts.covering !== undefined) && opts.id === undefined) {
return {
ok: false,
@@ -524,6 +529,7 @@ export async function evictClipWindowsAction(opts: {
...(opts.olderThanDays !== undefined
? { olderThanDays: Math.floor(opts.olderThanDays) }
: {}),
+ ...(isEvictTiers(opts.tiers) && opts.tiers !== "all" ? { tiers: opts.tiers } : {}),
...(opts.dryRun ? { dryRun: true } : {}),
});
}
diff --git a/editor/app/storage/lib/evictClipsJob.ts b/editor/app/storage/lib/evictClipsJob.ts
@@ -8,6 +8,7 @@ import {
evictClipWindows,
evictClipWindowsSummary,
type ClipWindowSpan,
+ type EvictTiers,
} from "yt-dlp-transcript-common/controller/evictClipWindows";
import { clipWindowName } from "yt-dlp-transcript-common/lib/clipWindow";
@@ -35,6 +36,8 @@ export async function enqueueEvictClipWindows(opts: {
windows?: ClipWindowSpan[];
covering?: ClipWindowSpan[];
olderThanDays?: number;
+ // "all" (default) | "plain" | "tiered" — controller/evictClipWindows.ts.
+ tiers?: EvictTiers;
dryRun?: boolean;
}): Promise<StreamActionResult> {
const spans = (l: ClipWindowSpan[]) => l.map((w) => clipWindowName(w.from, w.to)).join(", ");
@@ -58,6 +61,7 @@ export async function enqueueEvictClipWindows(opts: {
(opts.windows && opts.covering ? " or" : "") +
(opts.covering ? ` overlapping ${spans(opts.covering)}` : "") +
(!opts.windows && !opts.covering ? " (every one)" : "") +
+ (opts.tiers === "plain" ? ", the plain windows only" : opts.tiers === "tiered" ? ", the taller (tiered) windows only" : "") +
(opts.olderThanDays !== undefined
? `, not touched for ${opts.olderThanDays} day(s)`
: "") +
@@ -85,6 +89,7 @@ export async function enqueueEvictClipWindows(opts: {
...(opts.windows ? { windows: opts.windows } : {}),
...(opts.covering ? { covering: opts.covering } : {}),
...(opts.olderThanDays !== undefined ? { olderThanDays: opts.olderThanDays } : {}),
+ ...(opts.tiers && opts.tiers !== "all" ? { tiers: opts.tiers } : {}),
...(opts.dryRun ? { dryRun: true } : {}),
onLog,
signal,
diff --git a/mcp/src/fetchClip.test.ts b/mcp/src/fetchClip.test.ts
@@ -324,6 +324,23 @@ test("200 cached: the exact window (within 0.02 s) says so", async () => {
assert.ok(!/requested by/.test(r.text));
});
+test("200 cached lower than asked: the editor's belowAsked is said, with its reason", async () => {
+ const { deps } = editor(
+ seq({
+ status: 200,
+ body: {
+ cached: true, file: CLIP_FILE, from: 7, to: 23, bytes: 5, provenance: null, height: 720,
+ belowAsked: { asked: 1080, why: "no saved copy of the recording to cut a taller one from" },
+ },
+ }),
+ );
+ const r = renderFetchClip(await fetchClip(windowRequest(), deps), CTX);
+ assert.match(r.text, /\nlower than asked: 720p for the 1080p asked — no saved copy of the recording to cut a taller one from$/);
+ // A malformed one is not said.
+ const { deps: d2 } = editor(seq({ status: 200, body: { cached: true, file: CLIP_FILE, from: 7, to: 23, bytes: 5, belowAsked: { asked: "x" } } }));
+ assert.ok(!/lower than asked/.test(renderFetchClip(await fetchClip(windowRequest(), d2), CTX).text));
+});
+
test("202 → running → done: the poll's file, span and bytes", async () => {
const { deps, calls, sleeps } = editor(
seq(
diff --git a/mcp/src/fetchClip.ts b/mcp/src/fetchClip.ts
@@ -315,6 +315,9 @@ export type FetchClipOutcome =
// call asked for, so the answer can say when a cached file is taller.
height?: number;
maxHeight?: number;
+ // A tall ask answered with a window LOWER than it asked (the editor's
+ // height tier): the height asked, and why no taller one was cut.
+ belowAsked?: { asked: number; why: string };
}
| {
kind: "fetched";
@@ -586,6 +589,7 @@ export async function fetchClip(
bytes: num(answer.bytes) ?? 0,
requestedBy: prov && typeof prov === "object" ? str(prov.requestedBy) : undefined,
...heightFields(num(answer.height), target.maxHeight),
+ ...belowAskedOf(answer.belowAsked),
};
}
if (res.status === 202 && str(answer.jobId)) {
@@ -608,6 +612,14 @@ export async function fetchClip(
};
}
+// The editor's `belowAsked` ({asked, why}), only when it is well formed.
+function belowAskedOf(v: unknown): { belowAsked?: { asked: number; why: string } } {
+ if (!v || typeof v !== "object") return {};
+ const asked = num((v as Json).asked);
+ const why = str((v as Json).why);
+ return asked !== undefined && why ? { belowAsked: { asked, why } } : {};
+}
+
// ─── The answer an agent reads ───
const READ_ONLY_NOTE =
@@ -699,7 +711,12 @@ export function renderFetchClip(
`${fmtSeconds(outcome.reqFrom)}–${fmtSeconds(outcome.reqTo)}: ` +
`${fmtSeconds(outcome.from)}–${fmtSeconds(outcome.to)}.`;
}
- return { text: `${head}\n\n${footer(outcome.mode, outcome, true)}`, isError: false };
+ // LOWER THAN ASKED is said too, with the editor's reason.
+ const below = outcome.belowAsked
+ ? `\nlower than asked: ${outcome.height !== undefined ? `${outcome.height}p` : "this window"} for the ` +
+ `${outcome.belowAsked.asked}p asked — ${outcome.belowAsked.why}`
+ : "";
+ return { text: `${head}\n\n${footer(outcome.mode, outcome, true)}${below}`, isError: false };
}
case "fetched": {
if (!outcome.file) {
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1525,6 +1525,8 @@ export function usage() {
' "windows": ["<from>-<to>", ...] only those named, "covering": [{"from",',
' "to"}, ...] any window overlapping a span (umtool fetch --refetch asks',
' this way); "olderThanDays" is then optional, "dryRun" only lists.',
+ ' "tiers": "plain" | "tiered" narrows to the <from>-<to> windows or the',
+ ' taller <from>-<to>.h<height> ones (default "all": both).',
"",
'check-windows probes cached clip windows (data/<id>/clips/) for a picture',
' that runs off the sound (a Rumble HLS seek) and sets each desynced one',
@@ -1992,7 +1994,12 @@ export function usage() {
' 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',
+ ' "maxHeight" caps the source height (default 720). Above 720 it is a tall',
+ ' ask, clamped to settings clips.windowMaxHeight (default 1080): its window',
+ ' is its own file beside the 720 one (<from>-<to>.h<height>.mp4), cut from',
+ ' the saved copy when that is taller; a cached window lower than asked with',
+ ' no taller saved copy is used as it is and listed in "lower" with why --',
+ ' never fetched again for height. "siteId" stays at 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',
diff --git a/settings.json.example b/settings.json.example
@@ -370,7 +370,8 @@
"clips": {
"wholeRecordingPlatforms": [
"rumble"
- ]
+ ],
+ "windowMaxHeight": 1080
},
"jobs": {
"resumeInterruptedOnBoot": true
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -359,6 +359,26 @@ the render unchanged. The two are not set together: on a migrated cut the series
The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets
the look's keys (`transition=0.3`, …: [report-video.md](report-video.md#the-look-captions-loudness-shorts-release-36)).
+## Taller windows (`render.tallWindows`)
+
+`render.tallWindows: true` lets a project's clips be fetched and cut taller than 720, up to its
+`render.maxHeightSource` (1080 when unset). It is OFF by default, and a project without it renders exactly as before:
+no height probe, no `out/clips-raw.heights.json`, no taller window read, no `maxHeight` sent. `maxHeightSource` is
+1080 in every scaffold and preset, so it is not the switch.
+
+With it on, `umtool fetch` asks the editor for that height. The editor keeps the taller window beside the 720 one
+(`clips/<from>-<to>.h<tier>.mp4`), cut from the saved copy when that copy is taller, and prints each clip that stays
+lower, with why. The build and every tool that checks its sources (quote-check, `--align`, scenes, cut points, the
+availability check, quick clip, the chain) read the cap from the manifest, so they all resolve the same file.
+`--refetch` evicts and re-cuts only the taller windows; the 720 window, which a site's evidence is cut from, stays. A
+take records the knob with the rest of the look. A take with no saved base follows the project's current manifest, so
+like any look key it renders tall once the knob is turned on. `fetch-via-editor --max-height` above 720 is refused on a
+project without the knob.
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| taller windows | — | `umtool look <p> tallWindows=true` (`false` turns it off) | `PUT /api/report/render {patch: {tallWindows}}` |
+
## Basic output (the footage alone)
`render.mode: "basic"` renders the cut as its footage and nothing else (`report-to-video/basic.mjs`): each clip's
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -3110,12 +3110,29 @@ cannot resolve); **Start** queues one paced job per platform and the panel
follows them to their end, naming each window a job failed. Every run is
recorded in `fetch-runs.json` beside the manifest.
+TALLER WINDOWS ARE OPT-IN per project: `umtool look <p> tallWindows=true` ([knobs.md](knobs.md#taller-windows-rendertallwindows)).
+Without it nothing here changes: no `maxHeight` in the body, no height probe, no taller window read. With it the
+body carries `maxHeight`, the manifest's `render.maxHeightSource`, and the editor keeps a taller window beside the 720
+one (`<from>-<to>.h<tier>.mp4`), cut from the saved copy when that copy is taller, and holds the ask to its
+`clips.windowMaxHeight` (1080 by default). A clip that stays lower is printed as a `lower` line, with its height and
+why — usually "no saved copy". The build, quote-check, `--align`, scenes, cut points, the availability check, quick
+clip and the chain all take the cap from the manifest's render, so they resolve the same file: a raw `out/clips-raw`
+file or a 720 corpus window gives way to a taller corpus window or to the saved copy. Neither is deleted. A raw
+file's height is probed once and kept in `out/clips-raw.heights.json`. A height between the editor's rungs
+(1080, 1440, 2160) resolves as its rung, as the editor fetches it: a 900 project reads the `.h1080` window. A 720
+window the editor later cuts from a taller one (a site's plain ask) may serve as that site's evidence: a further
+encode of the same seconds.
+
A window on disk that is BAD (cut from a saved video that turned out corrupt)
is a cache hit all the same, so a plain fetch keeps it. `umtool fetch <project>
--refetch z01,w01` (the clip bench's **Fetch this window again**, a queue step) evicts first: each named clip's fetch span — the very
`from`–`to` the body asks for, pad included — goes to the editor's `evict-clips`
-as `{slug, id, covering: [{from, to}]}`, which removes every cached window of
-that video OVERLAPPING the span (a wider window the dedup would have served it
+as `{slug, id, covering: [{from, to}], tiers}`, which removes every cached window of
+that video OVERLAPPING the span — on a tall project only the taller (`.h<tier>`)
+windows, which are then cut again from the saved copy (or, with none, fetched
+again at their height: the items carry `refetch: true`, so the 720 window does
+not answer them), the 720 one left for the sites; on any other only the 720
+windows, as before (a wider window the dedup would have served it
from included, and its `.desynced.*` twin), and only once that job has ended is
the fetch asked. `--refetch-video <slug>/<id>` does the same for every window
the project asks of one video. A window another project shares is evicted too:
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -573,7 +573,7 @@ export const clipWindowDirs = async (
};
// The corpus behind the project's channels tree, for a video its tree has no window of (channelsLayersFor).
const behind = channelsDir && channelsFallbackOn(m) && path.resolve(GLOBAL_CHANNELS_DIR()) !== path.resolve(root) ? GLOBAL_CHANNELS_DIR() : null;
- const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe, fallbackChannelsDir: behind })).filter((w) =>
+ const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe, fallbackChannelsDir: behind, render: m?.render ?? null })).filter((w) =>
readable(w.path),
);
if (windows.length) out.push({ video: e.video, windows });
diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs
@@ -196,7 +196,7 @@ const STEPS = {
const rawDir = path.join(ctx.project, "out", "clips-raw");
const missing = [];
for (const item of body.items) {
- const hit = await resolveLocalSource({ video: item.id, slug: item.slug, from: item.from, to: item.to }, { rawDir, channelsDir: ctx.paths.channelsDir }).catch(() => null);
+ const hit = await resolveLocalSource({ video: item.id, slug: item.slug, from: item.from, to: item.to }, { rawDir, channelsDir: ctx.paths.channelsDir, render: manifest.render ?? null }).catch(() => null);
if (!hit) missing.push(item);
}
if (missing.length === 0) return `the cut's ${body.items.length} window(s) are on disk already`;
diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs
@@ -116,7 +116,7 @@ async function cutContext(project, take) {
// sources are the corpus's windows or the project's cache); the project's
// raw cache is looked in after it, as the bench does.
const locals = [...new Set([outRoot, path.join(/* turbopackIgnore: true */ project.dir, "out")])].map((root) =>
- localSources({ rawDir: path.join(/* turbopackIgnore: true */ root, "clips-raw"), channelsDir, channelSlug: provenance.channelSlug ?? null }),
+ localSources({ rawDir: path.join(/* turbopackIgnore: true */ root, "clips-raw"), channelsDir, channelSlug: provenance.channelSlug ?? null, render }),
);
const localMedia = createLocalMedia({ baseDir: project.dir, allowAbsolute: render.allowAbsoluteSrc === true });
// Where a gap-joined clip's pieces are joined for measuring (piecedClipSource): beside the other
diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs
@@ -28,7 +28,9 @@ import {
projectFetchBody,
readFetchRuns,
recordFetchRun,
+ markRefetched,
refetchEvictions,
+ refetchTiers,
summarizeAnswer,
} from "./fetchWindows.mjs";
import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs";
@@ -63,6 +65,11 @@ export function summaryLines(s) {
for (const u of s.unresolved) lines.push(` unresolved ${u.clipId}: ${u.error}`);
for (const r of s.refused) lines.push(` refused ${r.platform}: ${r.items} window(s) — ${r.error}`);
for (const j of s.jobs) lines.push(` job ${j.jobId} ${j.platform}, ${j.items} window(s)`);
+ // THE HEIGHT TIER: a clip that stays lower than the project renders from, and why.
+ if (s.clampedFrom !== undefined) lines.push(` height ${s.clampedFrom}p asked; the editor's clips.windowMaxHeight holds windows lower`);
+ for (const l of s.lower ?? []) {
+ lines.push(` lower ${l.clipId}: ${l.height !== null ? `${l.height}p` : "height unknown"} (asked ${l.asked}p) in ${l.file} — ${l.why}`);
+ }
return lines;
}
@@ -172,9 +179,12 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
}
const plan = refetchEvictions(body, skipped, { clipIds: refetchClips, videos });
if (!plan.ok) throw new CliError(plan.error);
+ // The refetched items say so (`refetch: true`): on a tall project a lower
+ // held window then does not answer them — cut again at their tier, or fetched.
+ markRefetched(body, plan.requests);
refetch = [];
for (const req of plan.requests) {
- const { jobId } = await postEvictClips(cfg, req, { dryRun });
+ const { jobId } = await postEvictClips(cfg, { ...req, tiers: refetchTiers(body) }, { dryRun });
let status = "unknown";
for (;;) {
status = String((await jobStatus(cfg, jobId))?.job?.status ?? "unknown");
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -39,6 +39,7 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { LEFT_OUT_VERDICTS, clipMomentKey, readMontageRulings } from "umtool-report-to-video/montage-rulings";
import { fetchPieces, renderGaps } from "umtool-report-to-video/gaps";
+import { tallWindowCap } from "umtool-report-to-video/sources";
import { agentToken } from "../annotations/agentAuth.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
@@ -110,12 +111,19 @@ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = nu
// editor registers a channel it does not hold as remote-only only when that
// origin is a CONNECTED archive; any other origin changes nothing.
const site = typeof manifest?.provenance?.siteOrigin === "string" ? manifest.provenance.siteOrigin.trim().replace(/\/+$/, "") : "";
+ // A TALL PROJECT (`render.tallWindows`, sources.mjs tallWindowCap) asks for
+ // its render.maxHeightSource: the editor holds it to its
+ // clips.windowMaxHeight, keeps a taller window beside a 720 one and says
+ // which clips stayed lower and why (`lower` in its answer). Any other
+ // project sends no height, as before.
+ const maxHeight = tallWindowCap(manifest?.render);
return {
body: {
requestedBy: `umtool:${project}`,
manifest: path.resolve(manifestPath),
storedUrl: "fallback",
...(/^https?:\/\//.test(site) ? { archive: site } : {}),
+ ...(maxHeight !== undefined ? { maxHeight } : {}),
items,
},
skipped,
@@ -277,13 +285,42 @@ export function postFetchWindows(cfg, body, { dryRun = false } = {}) {
}
/**
- * POST /api/ops/evict-clips, targeted: `{slug, id, covering}` -> `{jobId}`.
+ * POST /api/ops/evict-clips, targeted: `{slug, id, covering, tiers}` -> `{jobId}`.
+ * `tiers` is "plain" or "tiered" (refetchTiers): a refetch removes only the
+ * windows its project reads, never the other kind.
* @param {{ url: string, token: string, fetch?: typeof fetch }} cfg
- * @param {{ slug: string, id: string, covering: { from: number, to: number }[] }} req
+ * @param {{ slug: string, id: string, covering: { from: number, to: number }[], tiers?: "plain" | "tiered" }} req
* @param {{ dryRun?: boolean }} [opts]
*/
-export function postEvictClips(cfg, { slug, id, covering }, { dryRun = false } = {}) {
- return ask(cfg, "/api/ops/evict-clips", { method: "POST", body: { slug, id, covering, ...(dryRun ? { dryRun: true } : {}) } });
+export function postEvictClips(cfg, { slug, id, covering, tiers }, { dryRun = false } = {}) {
+ return ask(cfg, "/api/ops/evict-clips", { method: "POST", body: { slug, id, covering, ...(tiers ? { tiers } : {}), ...(dryRun ? { dryRun: true } : {}) } });
+}
+
+/**
+ * Which windows a refetch evicts (the height tier): a TALL project's body asks
+ * a height (`maxHeight`, tallWindowCap) and evicts only the taller tiered
+ * windows of its spans — the plain 720 window a site's evidence reads stays;
+ * any other project evicts the plain windows only, as before the tier. Pure.
+ * @param {{ maxHeight?: number }} body
+ * @returns {"plain" | "tiered"}
+ */
+export const refetchTiers = (body) => (body?.maxHeight !== undefined ? "tiered" : "plain");
+
+/**
+ * Mark the body's items a refetch evicts for (`refetch: true`, in place): the
+ * items of each request's video whose span overlaps one it evicts. The editor
+ * then does not answer them with a lower held window on a tall project.
+ * @param {{ items: Record<string, any>[] }} body
+ * @param {{ slug: string, id: string, covering: { from: number, to: number }[] }[]} requests
+ */
+export function markRefetched(body, requests) {
+ for (const it of body.items) {
+ const hit = requests.some(
+ (r) => r.slug === it.slug && sameVideo(r.id, it.id) && r.covering.some((c) => c.from < it.to && it.from < c.to),
+ );
+ if (hit) it.refetch = true;
+ }
+ return body;
}
// `evicting <slug>/<id>/<name> (…)` / `would evict …` — the line
@@ -357,6 +394,15 @@ export function summarizeAnswer(a) {
inFlight: (a?.inFlight ?? []).map((f) => ({ clipId: label(f.item), jobId: f.jobId })),
unresolved: (a?.unresolved ?? []).map((u) => ({ clipId: label(u.item), slug: u.item?.slug, id: u.item?.id, error: String(u.error ?? "") })),
refused: (a?.refused ?? []).map((r) => ({ platform: r.platform, items: Number(r.items ?? 0), error: String(r.error ?? "") })),
+ // Cached windows LOWER than the height asked, used as they are, and why.
+ lower: (a?.lower ?? []).map((l) => ({
+ clipId: label(l.item),
+ file: String(l.file ?? ""),
+ height: Number.isFinite(Number(l.height)) && l.height !== null ? Number(l.height) : null,
+ asked: Number(l.asked),
+ why: String(l.why ?? ""),
+ })),
+ ...(Number.isFinite(Number(a?.clampedFrom)) ? { clampedFrom: Number(a.clampedFrom) } : {}),
jobs: (a?.jobs ?? []).map((j) => ({ platform: j.platform, queueKey: j.queueKey ?? null, jobId: j.jobId, items: Number(j.items ?? 0) })),
};
}
diff --git a/umtool/lib/report/fetchWindows.test.mjs b/umtool/lib/report/fetchWindows.test.mjs
@@ -245,7 +245,7 @@ test("umtool fetch --refetch: evict-clips {slug, id, covering} first, waited for
const run = (args) => fetchCommand(args, { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg, pollMs: 1 });
assert.equal(await run(["synth-oops", "--refetch", "s02", "--dry-run"]), 0);
- assert.deepEqual(ed.seen[0], { key: "POST /api/ops/evict-clips", body: { slug: "synth-rumble", id: "v2abc", covering: [{ from: 0, to: 7.5 }], dryRun: true }, auth: "Bearer tok" });
+ assert.deepEqual(ed.seen[0], { key: "POST /api/ops/evict-clips", body: { slug: "synth-rumble", id: "v2abc", covering: [{ from: 0, to: 7.5 }], tiers: "plain", dryRun: true }, auth: "Bearer tok" });
assert.equal(ed.seen.at(-1).key, "POST /api/ops/fetch-windows");
assert.equal(ed.seen.at(-1).body.dryRun, true);
assert.match(lines.join("\n"), /would evict for s02 \(synth-rumble\/v2abc, job E0\): 0\.00-9\.00\.mp4/);
@@ -299,3 +299,26 @@ test("a gap-joined clip is fetched per kept piece, each padded at its own edges
const montage = fetchWindowsBody({ ...m, render: { ...m.render, montage: {} }, timeline: [joined] }, { manifestPath: "/r/p/video.manifest.json", project: "p" });
assert.deepEqual(montage.body.items.map((i) => [i.from, i.to]), [[5382, 21815]]);
});
+
+// THE HEIGHT TIER: the body asks for the height the cut renders from, and the
+// editor's answer says which clips stayed lower and why -- printed by `umtool fetch`.
+test("a tall project's body carries its maxHeightSource as maxHeight; the answer's lower clips are summarized and printed", async () => {
+ const { summaryLines } = await import("./fetchCli.mjs");
+ const tall = { ...MANIFEST, render: { ...MANIFEST.render, tallWindows: true, maxHeightSource: 1080 } };
+ const { body } = fetchWindowsBody(tall, { manifestPath: "/x/m.json", project: "p" });
+ assert.equal(body.maxHeight, 1080);
+ // Without the knob, no height, whatever maxHeightSource says.
+ assert.equal(fetchWindowsBody({ ...MANIFEST, render: { maxHeightSource: 1080 } }, { manifestPath: "/x/m.json", project: "p" }).body.maxHeight, undefined);
+ assert.equal(fetchWindowsBody({ ...MANIFEST, render: { tallWindows: true, maxHeightSource: 99 } }, { manifestPath: "/x/m.json", project: "p" }).body.maxHeight, undefined);
+ const s = summarizeAnswer({
+ cached: [{ slug: "synth-yt", id: "yt1", clipId: "s01" }],
+ lower: [{ item: { slug: "synth-yt", id: "yt1", clipId: "s01" }, file: "55.81-63.87.mp4", height: 720, asked: 1080, why: "no saved copy of the recording to cut a taller one from" }],
+ clampedFrom: 2160,
+ });
+ assert.deepEqual(s.lower, [{ clipId: "s01", file: "55.81-63.87.mp4", height: 720, asked: 1080, why: "no saved copy of the recording to cut a taller one from" }]);
+ assert.equal(s.clampedFrom, 2160);
+ const lines = summaryLines(s);
+ assert.ok(lines.includes(" lower s01: 720p (asked 1080p) in 55.81-63.87.mp4 — no saved copy of the recording to cut a taller one from"));
+ assert.ok(lines.some((l) => /2160p asked; the editor's clips\.windowMaxHeight/.test(l)));
+ assert.deepEqual(summarizeAnswer({}).lower, []);
+});
diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs
@@ -46,7 +46,7 @@ const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NA
test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => {
const p = await project({ transition: 0.4, crf: 21 });
try {
- assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic"]);
+ assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows"]);
const token = await manifestToken(p.dir);
const r = await updateRender(p.dir, {
headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack",
diff --git a/umtool/lib/report/quickClip.mjs b/umtool/lib/report/quickClip.mjs
@@ -234,7 +234,9 @@ export async function quickClip(ask, { root = REPORTS_ROOT, channelsDir = CHANNE
// ONE CLOCK PER RECORDING: the build's lookup (resolveLocalSource) maps the span through a saved recording's
// time map (clock.json, common recordingClock.mjs) -- its windowStart is the CUE second the file's 0 plays --
// so the span is asked on the file's clock and the words come back onto the cues', as quote-check does.
- const src = await (deps.resolve ?? resolveLocalSource)({ video, slug: spec.channel, from, to }, { rawDir: path.join(project.dir, "out", "clips-raw"), channelsDir });
+ // The project's render, as the take's build will read it (its tallWindowCap).
+ const render = await readFile(path.join(project.dir, "video.manifest.json"), "utf8").then((t) => JSON.parse(t)?.render ?? null, () => null);
+ const src = await (deps.resolve ?? resolveLocalSource)({ video, slug: spec.channel, from, to }, { rawDir: path.join(project.dir, "out", "clips-raw"), channelsDir, render });
if (!src) throw new Error(`--snap words: no window on disk holds ${from.toFixed(2)}–${to.toFixed(2)} (the fetch landed a narrower one?)`);
if (src.clock && !src.clock.certain) say(`--snap words: ${path.basename(src.path)}'s clock is NOT certain over this span (a step in its time map) -- check the words land (umtool quote-check)`);
const { mkdir } = await import("node:fs/promises");
diff --git a/umtool/lib/report/quoteCheck.mjs b/umtool/lib/report/quoteCheck.mjs
@@ -191,7 +191,8 @@ export async function planQuoteCheck(dir, manifest, { channelsDirs, rawDir = pat
}
const src = await resolveLocalSource(
{ video: e.video, slug, from: cut.from, to: cut.to },
- { rawDir, channelsDir: channelsDirs[0], fallbackChannelsDir: channelsDirs[1] ?? null, ...(probe ? { probe } : {}) },
+ // The manifest's render: the build's own cap (sources.mjs tallWindowCap), so this vouches for the file it cuts.
+ { rawDir, channelsDir: channelsDirs[0], fallbackChannelsDir: channelsDirs[1] ?? null, render: manifest?.render ?? null, ...(probe ? { probe } : {}) },
);
if (!src) {
rows.push({ ...base, skip: "no-window" });
diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs
@@ -139,7 +139,7 @@ export async function recordingAudio({ channelsDir, channel, video, videoDir, du
const p = path.join(videoDir, name);
if (await isFile(p)) return { path: p, kind: "audio", clock: 0 };
}
- const hit = await resolveLocalSource({ video, slug: channel, from: 0, to: Math.max(1, duration - 1) }, { channelsDir, audio: true, probe: ffprobeSource }).catch(() => null);
+ const hit = await resolveLocalSource({ video, slug: channel, from: 0, to: Math.max(1, duration - 1) }, { channelsDir, audio: true, probe: ffprobeSource, render: null }).catch(() => null);
if (!hit) return null;
return { path: hit.path, kind: hit.kind, clock: (hit.windowStart ?? 0) + (await clockOffset(hit.path)) };
}
diff --git a/umtool/lib/report/scenesCli.mjs b/umtool/lib/report/scenesCli.mjs
@@ -139,12 +139,13 @@ export async function scanClip(project, clipId, opts = {}) {
const slug = channelFor(manifest, entry);
const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
const rawDir = path.join(project.dir, "out", "clips-raw");
- const config = { rawDir, channelsDir, probe: ffprobeSource };
+ // The build's lookup, with the manifest's render (its tallWindowCap): one call site.
+ const lookup = (want) => resolveLocalSource(want, { rawDir, channelsDir, probe: ffprobeSource, render: manifest.render ?? null });
// What the build would fetch, then the extent alone (a window that holds the clip but not its pad).
const span = fetchSpan(entry, manifest.render ?? {});
const hit =
- (await resolveLocalSource({ video: entry.video, slug, from: span.from, to: span.to }, config)) ??
- (await resolveLocalSource({ video: entry.video, slug, from: entry.start, to: entry.end }, config));
+ (await lookup({ video: entry.video, slug, from: span.from, to: span.to })) ??
+ (await lookup({ video: entry.video, slug, from: entry.start, to: entry.end }));
const clipRow = {
id: clipId,
channel: slug,
@@ -169,7 +170,7 @@ export async function scanClip(project, clipId, opts = {}) {
};
if (!hit) {
// A clip with gaps is fetched per kept piece (fetchSpans): scan each piece on disk.
- const local = { resolve: (e, sp) => resolveLocalSource({ video: e.video, slug, from: sp.from, to: sp.to }, config) };
+ const local = { resolve: (e, sp) => lookup({ video: e.video, slug, from: sp.from, to: sp.to }) };
const had = await localPieces(entry, manifest.render ?? {}, local);
if (had) {
const wantFrom = opts.from ?? entry.start - pad;
diff --git a/umtool/lib/report/tallWindows.test.mjs b/umtool/lib/report/tallWindows.test.mjs
@@ -0,0 +1,158 @@
+// render.tallWindows (the height tier's opt-in, report-to-video/sources.mjs
+// tallWindowCap): the build and every tool that vouches for its sources
+// resolve ONE file; without the knob a project resolves exactly as before —
+// no probe, no height index, no tiered window read — even beside a taller
+// saved copy and a tiered window; and every call site states its render.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { planQuoteCheck } from "./quoteCheck.mjs";
+import { localSources } from "umtool-report-to-video/build-video";
+import { rawWindowName, resolveLocalSource, tallWindowCap } from "umtool-report-to-video/sources";
+import { fetchWindowsBody, markRefetched, refetchEvictions, refetchTiers } from "./fetchWindows.mjs";
+
+const SLUG = "demo";
+const VIDEO = "vid1";
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
+
+async function project() {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "tall-windows-"));
+ const rawDir = path.join(dir, "out", "clips-raw");
+ const channelsDir = path.join(dir, "channels");
+ const videoDir = path.join(channelsDir, SLUG, "data", VIDEO);
+ const clips = path.join(videoDir, "clips");
+ const store = path.join(dir, "store");
+ for (const d of [rawDir, clips, store]) await mkdir(d, { recursive: true });
+ // A 720 raw file, a 720 corpus window, a 1080 tiered window elsewhere, and a 1080 saved copy.
+ await writeFile(path.join(rawDir, rawWindowName(VIDEO, 0, 60)), "raw");
+ await writeFile(path.join(clips, "0.00-60.00.mp4"), "plain");
+ await writeFile(path.join(clips, "0.00-60.00.json"), JSON.stringify({ requestedBy: "reports", height: 720 }));
+ await writeFile(path.join(clips, "5.00-55.00.h1080.mp4"), "tiered");
+ await writeFile(path.join(clips, "5.00-55.00.h1080.json"), JSON.stringify({ requestedBy: "umtool", height: 1080 }));
+ await writeFile(path.join(store, "source-media.mp4"), "whole");
+ await writeFile(
+ path.join(videoDir, "saved-video.json"),
+ JSON.stringify({ storedAt: "", dir: store, file: "source-media.mp4", bytes: 5, format: { preset: "original", height: 1080 } }),
+ );
+ return { dir, rawDir, channelsDir };
+}
+
+const manifestOf = (render) => ({
+ render,
+ provenance: { channelSlug: SLUG },
+ timeline: [{ type: "clip", id: "c1", video: VIDEO, start: 10, end: 20, quote: "hello there" }],
+});
+
+function counting() {
+ const calls = [];
+ return { calls, probe: async (f) => (calls.push(f), { duration: 600, height: 720 }) };
+}
+
+test("tallWindowCap: only render.tallWindows turns it on; maxHeightSource alone is no switch", () => {
+ assert.equal(tallWindowCap({ maxHeightSource: 1080 }), undefined);
+ assert.equal(tallWindowCap({ tallWindows: true, maxHeightSource: 1080 }), 1080);
+ assert.equal(tallWindowCap({ tallWindows: true }), 1080);
+ assert.equal(tallWindowCap({ tallWindows: true, maxHeightSource: 720 }), undefined);
+ assert.equal(tallWindowCap(null), undefined);
+});
+
+test("with the knob on, quote-check vouches for the very file the build cuts (the taller saved copy)", async () => {
+ const t = await project();
+ try {
+ const manifest = manifestOf({ tallWindows: true, maxHeightSource: 1080 });
+ const { probe } = counting();
+ const [row] = await planQuoteCheck(t.dir, manifest, { channelsDirs: [t.channelsDir], rawDir: t.rawDir, probe, pad: 0 });
+ const local = localSources({ rawDir: t.rawDir, channelsDir: t.channelsDir, channelSlug: SLUG, probe, render: manifest.render });
+ const built = await local.resolve(manifest.timeline[0], row.cut);
+ assert.equal(row.source.path, built.path);
+ assert.notEqual(built.kind, "raw-cache", "the 720 raw file gave way");
+ assert.equal(built.height, 1080);
+ } finally {
+ await rm(t.dir, { recursive: true, force: true });
+ }
+});
+
+test("without the knob a project resolves as before: the raw file, no probe, no height index, no tier read", async () => {
+ const t = await project();
+ try {
+ const manifest = manifestOf({ maxHeightSource: 1080 });
+ const { calls, probe } = counting();
+ const want = { video: VIDEO, slug: SLUG, from: 10, to: 20 };
+ const plain = await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, render: manifest.render });
+ // What main resolves: the raw file, exactly this shape, nothing else.
+ assert.deepEqual(plain, {
+ kind: "raw-cache",
+ path: path.join(t.rawDir, rawWindowName(VIDEO, 0, 60)),
+ name: rawWindowName(VIDEO, 0, 60),
+ windowStart: 0,
+ windowEnd: 60,
+ });
+ const [row] = await planQuoteCheck(t.dir, manifest, { channelsDirs: [t.channelsDir], rawDir: t.rawDir, probe, pad: 0 });
+ assert.equal(row.source.path, plain.path);
+ // The corpus alone: the plain window, never the tiered one.
+ const corpus = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe, render: manifest.render });
+ assert.equal(corpus.name, "0.00-60.00.mp4");
+ assert.equal(corpus.height, undefined);
+ assert.deepEqual(calls, [], "nothing probed");
+ assert.ok(!(await readdir(path.join(t.dir, "out"))).includes("clips-raw.heights.json"));
+ } finally {
+ await rm(t.dir, { recursive: true, force: true });
+ }
+});
+
+test("umtool fetch sends a window height only with the knob; a refetch evicts its own tier only", () => {
+ const off = fetchWindowsBody(manifestOf({ maxHeightSource: 1080 }), { manifestPath: "/x/m.json", project: "p" }).body;
+ assert.equal("maxHeight" in off, false);
+ assert.equal(refetchTiers(off), "plain");
+ const on = fetchWindowsBody(manifestOf({ tallWindows: true, maxHeightSource: 1080 }), { manifestPath: "/x/m.json", project: "p" }).body;
+ assert.equal(on.maxHeight, 1080);
+ assert.equal(refetchTiers(on), "tiered");
+});
+
+// SO CALLERS CANNOT DRIFT: every lookup outside the tests states the render it
+// resolves for (sources.mjs tallWindowCap reads it) -- `render: null` for one
+// that is not a cut's (a reference recording's sound).
+test("every resolveLocalSource / localSources / corpusWindowsOf call site states a render", async () => {
+ const { execFileSync } = await import("node:child_process");
+ const files = execFileSync("git", ["ls-files", "umtool/*.mjs", "umtool/*.ts", "umtool/**/*.mjs", "umtool/**/*.ts"], { cwd: REPO, encoding: "utf8" })
+ .split("\n")
+ .filter((f) => f && !/\.test\.|\/e2e\/|\.d\.ts$/.test(f));
+ const missing = [];
+ for (const f of files) {
+ const text = await readFile(path.join(REPO, f), "utf8");
+ const re = /(?:resolveLocalSource|localSources|corpusWindowsOf)\s*\)?\s*\(/g;
+ for (let m = re.exec(text); m; m = re.exec(text)) {
+ const before = text.slice(Math.max(0, m.index - 30), m.index);
+ if (/function\s+$|export\s+$|\.\s*$/.test(before) || /import|typeof/.test(before)) continue;
+ // The call's text: to its closing parenthesis (depth-counted).
+ let depth = 0;
+ let i = m.index + m[0].length - 1;
+ for (; i < text.length; i++) {
+ if (text[i] === "(") depth++;
+ else if (text[i] === ")" && --depth === 0) break;
+ }
+ const call = text.slice(m.index, i + 1);
+ if (!/\brender\b/.test(call)) missing.push(`${f}:${text.slice(0, m.index).split("\n").length}`);
+ }
+ }
+ assert.deepEqual(missing, []);
+});
+
+test("a refetch marks the items it evicts for (refetch: true), and only those", () => {
+ const manifest = {
+ ...manifestOf({ tallWindows: true, maxHeightSource: 1080 }),
+ timeline: [
+ { type: "clip", id: "c1", video: VIDEO, start: 10, end: 20 },
+ { type: "clip", id: "c2", video: VIDEO, start: 300, end: 310 },
+ ],
+ };
+ const { body, skipped } = fetchWindowsBody(manifest, { manifestPath: "/x/m.json", project: "p" });
+ const plan = refetchEvictions(body, skipped, { clipIds: ["c1"] });
+ assert.ok(plan.ok);
+ markRefetched(body, plan.requests);
+ assert.deepEqual(body.items.map((i) => [i.clipId, i.refetch === true]), [["c1", true], ["c2", false]]);
+});
diff --git a/umtool/lib/report/voiceMatch.mjs b/umtool/lib/report/voiceMatch.mjs
@@ -164,12 +164,12 @@ export async function planClips(dir, manifest, { channelsDir, rawDir = path.join
seen.add(key);
const s = await clipSpan(entry, slug, transcripts, { span, pad });
const base = { key, ...(id ? { id } : {}), channel: slug, video: entry.video, from: s.from, to: s.to, via: s.via };
- let hit = await resolveLocalSource({ video: entry.video, slug, from: s.from, to: s.to }, { rawDir, channelsDir, audio: true, probe: ffprobeSource });
+ let hit = await resolveLocalSource({ video: entry.video, slug, from: s.from, to: s.to }, { rawDir, channelsDir, audio: true, probe: ffprobeSource, render: manifest?.render ?? null });
let from = s.from;
let to = s.to;
if (!hit && num(entry.cutStart) && num(entry.cutEnd)) {
// A window that holds the cut but not its pad: the cut alone.
- hit = await resolveLocalSource({ video: entry.video, slug, from: entry.cutStart, to: entry.cutEnd }, { rawDir, channelsDir, audio: true, probe: ffprobeSource });
+ hit = await resolveLocalSource({ video: entry.video, slug, from: entry.cutStart, to: entry.cutEnd }, { rawDir, channelsDir, audio: true, probe: ffprobeSource, render: manifest?.render ?? null });
if (hit) {
from = Math.max(entry.cutStart, hit.windowStart);
to = Math.min(entry.cutEnd, hit.windowEnd);
@@ -241,7 +241,8 @@ export async function referenceRecordings({ channelsDir, channels, videos = [],
const from = Math.max(0, r.first);
const hit = await resolveLocalSource(
{ video: r.videoId, slug: r.slug, from, to: from + REFERENCE_SECONDS },
- { channelsDir, audio: true, probe: ffprobeSource },
+ // A reference recording, not a cut's clip: no render.
+ { channelsDir, audio: true, probe: ffprobeSource, render: null },
);
if (!hit) {
skipped.push({ channel: r.slug, video: r.videoId, why: "no local source covers it" });
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -1084,7 +1084,7 @@ export function virtualEntry(entry, clock) {
* so `--no-network`'s up-front pass and the clip's own fetch probe a saved
* container once between them.
*/
-export function localSources({ rawDir, channelsDir, channelSlug = null, probe, fallbackChannelsDir = null, log = undefined } = {}) {
+export function localSources({ rawDir, channelsDir, channelSlug = null, probe, fallbackChannelsDir = null, log = undefined, render = null } = {}) {
const memo = new Map();
const slugOf = (entry) => entry.channel ?? channelSlug ?? null;
return {
@@ -1096,9 +1096,11 @@ export function localSources({ rawDir, channelsDir, channelSlug = null, probe, f
const slug = slugOf(entry);
const key = `${slug}/${entry.video}/${span.from}/${span.to}/${exact}/${audio}`;
if (memo.has(key)) return memo.get(key);
+ // `render`: the manifest's, for its tallWindowCap (sources.mjs) -- the
+ // one place the cap is read, so every checker resolves what this does.
const hit = await resolveLocalSource(
{ video: entry.video, slug, from: span.from, to: span.to },
- { rawDir, channelsDir, exact, probe, audio, fallbackChannelsDir, log },
+ { rawDir, channelsDir, exact, probe, audio, fallbackChannelsDir, log, render },
);
// Hits only: a miss is about to be fetched into the raw cache, and the
// next clip asking for the same span must find that file.
@@ -6960,6 +6962,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
dirs.local = localSources({
rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe,
fallbackChannelsDir: layers[1] ?? null, log: (m) => EMIT("note", { message: m }),
+ render,
});
FX_CHANNELS_DIR = channelsDir;
// Read only for a cut that plays post items: a cut without them publishes nothing it could blank.
diff --git a/umtool/report-to-video/check-availability.mjs b/umtool/report-to-video/check-availability.mjs
@@ -177,6 +177,7 @@ export async function checkAvailability(manifestPath, {
fallback: CHANNELS_DIR,
}),
channelSlug: manifest.provenance?.channelSlug ?? null,
+ render: manifest.render ?? null,
});
const render = manifest.render ?? {};
diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs
@@ -29,7 +29,7 @@
import path from "node:path";
import { readFile } from "node:fs/promises";
import { corpusChannelsDir, isWholeRecording, localVideoId, mappedLine, recordingPlatform, withLocalIds } from "./recording-ids.mjs";
-import { resolveLocalSource } from "./sources.mjs";
+import { resolveLocalSource, tallWindowCap } from "./sources.mjs";
const DEFAULT_EDITOR = "http://localhost:3001";
// One poll a second while a job runs, one every five while it waits its turn.
@@ -134,6 +134,21 @@ if (!token) {
}
const whole = JSON.parse(await readFile(manifestPath, "utf8"));
+// A WINDOW'S HEIGHT: --max-height, else the project's tall cap -- only with
+// `render.tallWindows` on (sources.mjs tallWindowCap): its render.maxHeightSource.
+// Above 720 the editor keeps the taller window beside the 720 one, held to its
+// clips.windowMaxHeight, and says when a clip stays lower. Without the knob no
+// height is sent, as before. A whole recording (--full) keeps --max-height alone.
+const windowMaxHeight = maxHeight ?? tallWindowCap(whole?.render);
+// A window asked taller than 720 by hand, on a project that does not read
+// taller windows: refused, rather than cut into a file its own build and checks
+// would never resolve.
+if (!wantFull && maxHeight !== undefined && maxHeight > 720 && tallWindowCap(whole?.render) === undefined) {
+ die(
+ `--max-height ${maxHeight} asks for a window taller than 720, but this project does not read taller windows: ` +
+ `turn them on with \`umtool look <p> tallWindows=true\` (render.tallWindows), or ask 720 or less`,
+ );
+}
const provenance = whole.provenance ?? {};
const pad = Number(flag("--pad") ?? 3);
@@ -295,7 +310,7 @@ if (wantAll) {
// The archive the cut cites (demo epic D1): a CONNECTED one registers a
// channel the editor does not hold as remote-only; any other is ignored.
...(/^https?:\/\//.test(String(provenance.siteOrigin ?? "")) ? { archive: String(provenance.siteOrigin).trim().replace(/\/+$/, "") } : {}),
- ...(maxHeight !== undefined ? { maxHeight } : {}),
+ ...(windowMaxHeight !== undefined ? { maxHeight: windowMaxHeight } : {}),
...storedUrl,
}),
});
@@ -314,6 +329,11 @@ if (wantAll) {
for (const r of body.refused ?? []) {
EMIT("note", { message: ` ${r.platform}: ${r.items} window(s) not started — ${r.error}` });
}
+ for (const l of body.lower ?? []) {
+ EMIT("note", {
+ message: ` ${l.item?.clipId ?? l.item?.id}: stays ${l.height ? `${l.height}p` : "at an unknown height"} (asked ${l.asked}p) — ${l.why}`,
+ });
+ }
const failed = await waitForJobs(body.jobs);
const unfinished = failed.length + (body.refused?.length ?? 0) + (body.unresolved?.length ?? 0);
if (unfinished > 0) {
@@ -410,7 +430,7 @@ if (!wantFull && (await isWholeRecording({ slug: channelSlug, webpageUrl: entry.
],
requestedBy: "umtool",
manifest: manifestId,
- ...(maxHeight !== undefined ? { maxHeight } : {}),
+ ...(windowMaxHeight !== undefined ? { maxHeight: windowMaxHeight } : {}),
}),
});
const body = await res.json().catch(() => ({}));
@@ -429,7 +449,7 @@ if (!wantFull && (await isWholeRecording({ slug: channelSlug, webpageUrl: entry.
if (failed.length) die(`the whole-recording fetch failed (no seek was tried):\n ${failed.join("\n ")}`);
const hit = await resolveLocalSource(
{ video: videoId, slug: channelSlug, from, to },
- { channelsDir: corpusChannelsDir(), kinds: ["corpus-window"] },
+ { channelsDir: corpusChannelsDir(), kinds: ["corpus-window"], render: whole?.render ?? null },
);
if (!hit) {
die(
@@ -453,7 +473,9 @@ const res = await ask(`${editorUrl}/api/media/fetch-window`, {
videoId,
webpageUrl: entry.webpageUrl ?? undefined,
...(wantFull ? { full: true } : { from, to, pad: Math.max(padBefore, padAfter) }),
- ...(maxHeight !== undefined ? { maxHeight } : {}),
+ ...(wantFull
+ ? maxHeight !== undefined ? { maxHeight } : {}
+ : windowMaxHeight !== undefined ? { maxHeight: windowMaxHeight } : {}),
...storedUrl,
requestedBy: "umtool",
manifest: manifestId,
@@ -469,6 +491,12 @@ const body = await res.json().catch(() => ({}));
// served as it is, never re-fetched for a different cap).
function heightOf(answer) {
const h = Number(answer.height);
+ // A tall ask answered lower (the height tier): said, with why.
+ if (answer.belowAsked) {
+ EMIT("note", {
+ message: ` ${path.basename(String(answer.file ?? ""))} stays ${Number.isInteger(h) && h > 0 ? `${h}p` : "at an unknown height"} (asked ${answer.belowAsked.asked}p) — ${answer.belowAsked.why}`,
+ });
+ }
if (!Number.isInteger(h) || h <= 0) return {};
if (maxHeight !== undefined && h > maxHeight) {
EMIT("note", {
diff --git a/umtool/report-to-video/fetch-via-editor.test.mjs b/umtool/report-to-video/fetch-via-editor.test.mjs
@@ -408,3 +408,19 @@ test("a Rumble clip whose whole-recording fetch fails: exit 1, and still no seek
await rm(c.root, { recursive: true, force: true });
}
});
+
+// A window asked above 720 on a project that does not read taller windows is
+// refused, naming the knob, before any request.
+test("--max-height above 720 without render.tallWindows is refused, naming the knob", async () => {
+ const ed = await stubEditor(CACHED(720));
+ try {
+ const { code, events } = await run(ed.url, ["--max-height", "1080"]);
+ assert.notEqual(code, 0);
+ assert.equal(ed.posts.length, 0);
+ assert.ok(events.some((e) => e.ev === "note" && /umtool look <p> tallWindows=true/.test(e.message)), JSON.stringify(events));
+ // 720 and under, and --full, are as before.
+ assert.equal((await run(ed.url, ["--max-height", "720"])).code, 0);
+ } finally {
+ await ed.close();
+ }
+});
diff --git a/umtool/report-to-video/sources.mjs b/umtool/report-to-video/sources.mjs
@@ -60,13 +60,16 @@
// root arrives as an argument (see umtool/lib/paths.mjs on why that matters to
// the Next build).
import path from "node:path";
-import { stat } from "node:fs/promises";
+import { readFile, stat } from "node:fs/promises";
+import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
import {
AUDIO_ONLY_PLATFORMS,
CORPUS_TIERS,
WINDOW_RE,
+ isTallAsk,
listNames,
present,
+ probeHeightOnce,
resolveFromTiers,
windowContains,
tightestContaining,
@@ -145,6 +148,75 @@ export function windowsFromNames(names, rawDir, video) {
return out;
}
+// ---- the raw cache's heights (the height tier) --------------------------------
+// A raw file carries no sidecar (nothing may be added to clips-raw/ that its
+// readers would have to learn to skip), so its picture height is kept in ONE
+// index beside the directory, `out/clips-raw.heights.json`: name → {bytes,
+// mtimeMs, height}, an entry good while the file is the same size and age.
+// Written only on a TALL ask (render.maxHeightSource above 720), the first
+// time a file's height is needed: one probe per file, ever. A lost or pruned
+// index costs a probe, nothing else.
+
+export const RAW_HEIGHTS_FILE = "clips-raw.heights.json";
+
+/** Where a raw cache's height index lives: beside `out/clips-raw`. */
+export const rawHeightsPath = (rawDir) => path.join(/* turbopackIgnore: true */ path.dirname(rawDir), RAW_HEIGHTS_FILE);
+
+async function readRawHeights(rawDir) {
+ try {
+ const v = JSON.parse(await readFile(rawHeightsPath(rawDir), "utf8"));
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * A raw-cache file's picture height: the index's record for it as it is now,
+ * else one probe, recorded. Null when the probe cannot tell.
+ * @param {string} rawDir
+ * @param {{ name: string, path: string }} w
+ * @param {(file: string) => Promise<{duration: number, height?: number}|null>} [probe]
+ * @returns {Promise<number | null>}
+ */
+export async function rawHeightOf(rawDir, w, probe = ffprobeSource) {
+ const st = await stat(w.path).catch(() => null);
+ if (!st) return null;
+ const idx = await readRawHeights(rawDir);
+ const e = idx[w.name];
+ if (e && e.bytes === st.size && e.mtimeMs === st.mtimeMs && Number.isInteger(e.height)) return e.height;
+ const h = (await probe(w.path))?.height ?? null;
+ if (!Number.isInteger(h)) return null;
+ // Re-read just before the write: another build may have recorded others.
+ const now = await readRawHeights(rawDir);
+ now[w.name] = { bytes: st.size, mtimeMs: st.mtimeMs, height: h };
+ await writeFileAtomic(rawHeightsPath(rawDir), JSON.stringify(now, null, 2) + "\n").catch(() => {});
+ return h;
+}
+
+// ---- the project's opt-in to taller sources --------------------------------------
+// `render.tallWindows: true` (a look key, `umtool look <p> tallWindows=true`) is
+// the ONLY switch: `render.maxHeightSource` is 1080 in every scaffold and
+// preset, so it cannot be one. Absent, everything is as it always was -- no
+// height probe, no clips-raw.heights.json, no tiered window read, no saved
+// container probed for its height, no `maxHeight` sent for a window. On, the
+// cap is `render.maxHeightSource` (1080 when unset). EVERY lookup takes the cap
+// from here, through the render block it is given, so the build and the tools
+// that vouch for its sources (quote-check, --align, scenes, cut points, the
+// availability check, quick clip, the chain) cannot resolve different files.
+
+/**
+ * The height a project's windows are asked and resolved at, or undefined for
+ * the plain 720 path. Pure.
+ * @param {Record<string, any> | null | undefined} render the manifest's render block
+ * @returns {number | undefined}
+ */
+export function tallWindowCap(render) {
+ if (render?.tallWindows !== true) return undefined;
+ const h = Number(render?.maxHeightSource ?? 1080);
+ return Number.isInteger(h) && h > 720 && h <= 2160 ? h : undefined;
+}
+
export async function cachedWindowsFor(rawDir, video) {
return windowsFromNames(await listRawNames(rawDir), rawDir, video);
}
@@ -175,10 +247,15 @@ export const TIERS = [{ kind: "raw-cache", windows: rawCacheWindows }, ...CORPUS
* `from`/`to` are the PADDED span -- what the build would otherwise fetch.
* @param {{ rawDir?: string|null, channelsDir?: string|null, exact?: boolean,
* probe?: (file: string) => Promise<{duration: number, height?: number}|null>,
- * kinds?: string[] }} [config]
+ * kinds?: string[], render?: Record<string, any> | null }} [config]
* `exact` (`--no-reuse`) accepts only the raw-cache file named for exactly
* this span. `kinds` narrows the tiers consulted (default: all, in order).
* `audio` admits the audio tier (default false; see `audioUse`).
+ * `render`: the manifest's render block, read for its tallWindowCap. With
+ * `tallWindows` on, the tallest the disk holds up to the cap wins -- a raw
+ * file lower than what the corpus can give without a fetch (a taller window,
+ * the saved copy) gives way to it. Every caller states it (null for a
+ * lookup that is not a cut's: a reference recording's sound).
* @returns {Promise<null | { kind: string, path: string, name: string,
* windowStart: number, windowEnd: number, height?: number }>}
*/
@@ -193,7 +270,8 @@ export async function resolveLocalSource(want, config = {}) {
async function resolveLocalSourceIn(want, config = {}) {
const { video, slug = null, from, to } = want;
- const { rawDir = null, channelsDir = null, exact = false, probe, kinds = null, audio = false } = config;
+ const { rawDir = null, channelsDir = null, exact = false, probe, kinds = null, audio = false, render = null } = config;
+ const maxHeight = tallWindowCap(render);
if (!video || !Number.isFinite(from) || !Number.isFinite(to)) return null;
if (exact) {
@@ -208,7 +286,14 @@ async function resolveLocalSourceIn(want, config = {}) {
// The raw cache's EXACT name first, as it always was; then tightest.
const exactName = rawWindowName(video, from, to);
- return resolveFromTiers(TIERS, { video, slug, rawDir, channelsDir, probe }, from, to, {
+ const tall = isTallAsk(maxHeight)
+ ? {
+ maxHeight,
+ // A raw file's height from the index beside clips-raw; any other, one probe.
+ heightOf: (kind, w) => (kind === "raw-cache" && rawDir ? rawHeightOf(rawDir, w, probe) : probeHeightOnce(w.path, probe)),
+ }
+ : {};
+ return resolveFromTiers(TIERS, { video, slug, rawDir, channelsDir, probe, ...tall }, from, to, {
allow: (tier) => (!kinds || kinds.includes(tier.kind)) && (tier.audio ? audio : !exact),
preferName: (tier) => (tier.kind === "raw-cache" ? exactName : null),
});
@@ -226,14 +311,17 @@ async function resolveLocalSourceIn(want, config = {}) {
* Not the audio tier: many transcribed videos keep their sound, and a
* bench that called each of those "fetched" would never offer a fetch.
*/
-export async function corpusWindowsOf({ video, slug, channelsDir, probe = ffprobeSource, fallbackChannelsDir = null }) {
- const own = await corpusWindowsIn({ video, slug, channelsDir, probe });
+export async function corpusWindowsOf({ video, slug, channelsDir, probe = ffprobeSource, fallbackChannelsDir = null, render = null }) {
+ const maxHeight = tallWindowCap(render);
+ const own = await corpusWindowsIn({ video, slug, channelsDir, probe, maxHeight });
if (own.length || !fallbackChannelsDir) return own;
- return corpusWindowsIn({ video, slug, channelsDir: fallbackChannelsDir, probe });
+ return corpusWindowsIn({ video, slug, channelsDir: fallbackChannelsDir, probe, maxHeight });
}
-async function corpusWindowsIn({ video, slug, channelsDir, probe }) {
- const ctx = { video, slug, channelsDir, probe };
+// A tall project (tallWindowCap) lists the taller windows too, so the bench's
+// "fetched" and a tall render's "local" are the same set.
+async function corpusWindowsIn({ video, slug, channelsDir, probe, maxHeight }) {
+ const ctx = { video, slug, channelsDir, probe, ...(maxHeight !== undefined ? { maxHeight } : {}) };
const out = [];
for (const tier of CORPUS_TIERS) {
if (tier.audio) continue;
diff --git a/umtool/report-to-video/sources.test.mjs b/umtool/report-to-video/sources.test.mjs
@@ -6,7 +6,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import path from "node:path";
import os from "node:os";
-import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import {
SOURCE_KINDS,
@@ -15,6 +15,7 @@ import {
audioUse,
channelsDirFor,
corpusWindowsOf,
+ rawHeightsPath,
rawWindowName,
readSavedVideoPointer,
resolveLocalSource,
@@ -603,3 +604,88 @@ test("buildVideo --no-network: a video clip with only its sound is refused, unle
await rm(t.root, { recursive: true, force: true });
}
});
+
+// The knob: `render.tallWindows` with the height it reaches for (sources.mjs tallWindowCap).
+const TALL = { tallWindows: true, maxHeightSource: 1080 };
+
+// THE HEIGHT TIER (common/lib/clipWindow.ts): with render.maxHeightSource
+// above 720, the tallest the disk holds up to it wins -- a raw file or a 720
+// corpus window gives way to a taller window or the saved copy, and is never
+// removed. Without it, exactly the order above.
+test("a tall ask: a 720 raw file gives way to a 1080 corpus window beside the 720 one; without the ask the raw file wins", async () => {
+ const t = await tree();
+ try {
+ await touch(path.join(t.rawDir, rawWindowName(VIDEO, 0, 60)));
+ await touch(path.join(t.clipsDir, "0.00-60.00.mp4"));
+ await writeFile(path.join(t.clipsDir, "0.00-60.00.json"), JSON.stringify({ requestedBy: "reports", height: 720 }));
+ await touch(path.join(t.clipsDir, "0.00-60.00.h1080.mp4"));
+ await writeFile(path.join(t.clipsDir, "0.00-60.00.h1080.json"), JSON.stringify({ requestedBy: "umtool", height: 1080 }));
+ // The raw file's height: one probe, then the index beside clips-raw.
+ const { probe, calls } = fakeProbe(600, { height: 720 });
+ const want = { video: VIDEO, slug: SLUG, from: 10, to: 20 };
+ const plain = await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe });
+ assert.equal(plain.kind, "raw-cache");
+ assert.equal(calls.length, 0, "no ask, no probe");
+ const tall = await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, render: TALL });
+ assert.equal(tall.kind, "corpus-window");
+ assert.equal(tall.name, "0.00-60.00.h1080.mp4");
+ assert.equal(tall.height, 1080);
+ assert.deepEqual(calls.map((c) => path.basename(c)), [rawWindowName(VIDEO, 0, 60)]);
+ const idx = JSON.parse(await readFile(rawHeightsPath(t.rawDir), "utf8"));
+ assert.equal(idx[rawWindowName(VIDEO, 0, 60)].height, 720);
+ // The next resolve reads the index: no second probe of the raw file.
+ await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, render: TALL });
+ assert.equal(calls.length, 1);
+ // A raw file as tall as the ask is kept: the earliest tier that reaches it.
+ idx[rawWindowName(VIDEO, 0, 60)].height = 1080;
+ await writeFile(rawHeightsPath(t.rawDir), JSON.stringify(idx));
+ const raw1080 = await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, render: TALL });
+ assert.equal(raw1080.kind, "raw-cache");
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});
+
+test("a tall ask with only lower windows reaches for the saved copy when it is taller; a lower one keeps the window", async () => {
+ const t = await tree();
+ try {
+ await touch(path.join(t.clipsDir, "0.00-60.00.mp4"));
+ await writeFile(path.join(t.clipsDir, "0.00-60.00.json"), JSON.stringify({ height: 720 }));
+ await touch(path.join(t.storeDir, "source-media.mp4"));
+ await pointTo(t.videoDir, t.storeDir, "source-media.mp4", { format: { preset: "original", height: 1080 } });
+ const want = { video: VIDEO, slug: SLUG, from: 10, to: 20 };
+ const hit = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe: fakeProbe(600).probe, render: TALL });
+ assert.equal(hit.kind, "saved-video");
+ await pointTo(t.videoDir, t.storeDir, "source-media.mp4", { format: { preset: "original", height: 480 } });
+ const lower = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe: fakeProbe(600).probe, render: TALL });
+ assert.equal(lower.kind, "corpus-window");
+ assert.equal(lower.name, "0.00-60.00.mp4");
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});
+
+// The editor's LADDER (1080, 1440, 2160): a project asking 900 or 1200 reads
+// the editor's `.h1080` / `.h1440` window as its rung, not as too tall.
+test("a tall ask between rungs resolves the rung's window: 900 and 1000 read .h1080, 1200 reads .h1440", async () => {
+ const t = await tree();
+ try {
+ await touch(path.join(t.clipsDir, "0.00-60.00.mp4"));
+ await writeFile(path.join(t.clipsDir, "0.00-60.00.json"), JSON.stringify({ height: 720 }));
+ await touch(path.join(t.clipsDir, "0.00-60.00.h1080.mp4"));
+ await writeFile(path.join(t.clipsDir, "0.00-60.00.h1080.json"), JSON.stringify({ height: 1080 }));
+ const want = { video: VIDEO, slug: SLUG, from: 10, to: 20 };
+ for (const h of [900, 1000]) {
+ const hit = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe: fakeProbe(600).probe, render: { tallWindows: true, maxHeightSource: h } });
+ assert.equal(hit.name, "0.00-60.00.h1080.mp4", String(h));
+ }
+ await touch(path.join(t.clipsDir, "0.00-60.00.h1440.mp4"));
+ await writeFile(path.join(t.clipsDir, "0.00-60.00.h1440.json"), JSON.stringify({ height: 1440 }));
+ const at1200 = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe: fakeProbe(600).probe, render: { tallWindows: true, maxHeightSource: 1200 } });
+ assert.equal(at1200.name, "0.00-60.00.h1440.mp4");
+ const at1080 = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe: fakeProbe(600).probe, render: TALL });
+ assert.equal(at1080.name, "0.00-60.00.h1080.mp4");
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});