commit 6b49a2f625d1cd44b6a079f76ea3ffcbf5cdeca7
parent 26561ac7f623fbbb42e7580ceb47d846c70903ca
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 13 Nov 2026 17:03:35 -0500
Clip windows above 720: a taller window beside the 720 one, never in its place
A clip window asked for taller than 720 (maxHeight on fetch-windows,
fetch-window and fetch_clip; umtool now sends its project's
render.maxHeightSource) is its own cache entry beside the plain one,
clips/<from>-<to>.h<tier>.mp4 with its own sidecar. The plain window keeps
its bytes, name and mtime, so a published site's evidence cut (which reads
only plain names, in the 1280x720 box) never changes.
- The new setting clips.windowMaxHeight (default 1080) is a ceiling, not
a default: no maxHeight is the 720 path exactly as before; a larger ask
is clamped and the answer says so. Site-driven fetches stay at 720.
- A window's height is recorded in its sidecar at cut and fetch time; an
older window is probed once on its first tall ask and recorded there.
- A tall ask takes the tallest held window up to the cap. When that is
lower than min(cap, the saved copy's height), a taller cut is made from
the saved copy beside it; with no taller copy the lower window is used
as it is and listed in `lower` with why. Nothing is fetched again for
height; only an explicit refetch does that.
- Listing stays plain-only for every existing reader; the video page,
eviction (named, covering and by age) and the clock retirement see the
tiered windows as windows of their span.
- umtool: fetch sends render.maxHeightSource and prints the clips that
stay lower; the build's local resolve takes the tallest source up to it
(a raw file's height kept in out/clips-raw.heights.json), so a lower raw
file or 720 window gives way to a taller window or the saved copy.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
39 files changed, 1677 insertions(+), 118 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -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,18 @@ 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 its
+ project's `render.maxHeightSource`) is its own file beside the 720 one: `clips/<from>-<to>.h<height>.mp4`, with its
+ own sidecar. The 720 window is never replaced, retired or re-fetched for this. The ask is held to
+ `settings.clips.windowMaxHeight` (default 1080). An ask with no `maxHeight` is 720, as before.
+ - A held window lower than asked is cut taller from the video's saved copy when that copy is taller.
+ - With no taller saved copy, the lower window is used as it is. The answer lists it under `"lower"` with its height
+ and why. Only `umtool fetch <project> --refetch <clip>` fetches it again.
+ - A window's height is recorded in its sidecar when it is cut or fetched. An older window is probed once, on its
+ first tall ask, and its height written there.
+ - Eviction (`evict-clips`, the age-out, the clock retirement) treats a taller window as a window of its span.
- 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`). 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<height>.mp4`), 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/evictClipWindows.ts b/common/controller/evictClipWindows.ts
@@ -6,6 +6,7 @@ import {
clipWindowDesyncedSidecar,
clipWindowName,
clipWindowSidecar,
+ parseAnyClipWindowName,
parseClipWindowName,
parseDesyncedClipWindowName,
} from "../lib/clipWindow";
@@ -190,7 +191,11 @@ 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;
@@ -234,7 +239,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 },
);
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -10,10 +10,12 @@ 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, windowTierOf, type ClipCopy } from "../lib/clipWindow";
+import { tallerFromSaved } from "../lib/clipWindowTier-server";
+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";
@@ -294,6 +296,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 +367,9 @@ 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>;
};
// The windows of a video cut on another clock than `clockId`, evicted through
@@ -370,7 +381,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 +515,7 @@ const DEFAULT_DEPS: FetchWindowsDeps = {
signal: o.signal,
}),
retireOffClock: retireOffClockWindows,
+ probeHeight: (file, paths) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file }),
assertMediaReachable: (paths, slug) => assertChannelMediaReachable(paths, slug),
saveWholeRecording: saveWholeRecordingManaged,
};
@@ -592,6 +605,10 @@ 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).
+ const { cap, clampedFrom } = clampWindowCap(maxHeight, windowMaxHeightOf(settings.clips));
+ const tier = windowTierOf(cap);
const work = dedupeFetchWindowsItems(items);
const result: FetchWindowsResult = {
fetched: [],
@@ -605,8 +622,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,6 +749,7 @@ export async function fetchWindows({
label: string,
videoDir: string,
source: Extract<Awaited<ReturnType<typeof savedWindowSource>>, { kind: "covers" }>,
+ beside?: string,
): Promise<void> => {
try {
const cut = await deps.cutSavedWindow({
@@ -734,6 +758,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 ? { maxHeight: tier } : {}),
provenance: {
requestedBy: provenance.requestedBy,
manifest: provenance.manifest,
@@ -745,7 +771,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 +837,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 +868,36 @@ export async function fetchWindows({
`${d.setAsideAs}, and the span is fetched again.`,
);
}
+ 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;
+ }
+ (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}`);
@@ -1124,7 +1186,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,195 @@
+// 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, rm, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fetchWindows, type FetchWindowsDeps, type FetchWindowsItem } from "./fetchWindows";
+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 } = {}) {
+ const fetches: FetchWindowOpts[] = [];
+ const cuts: { maxHeight?: number; from: number; to: number }[] = [];
+ const deps: Partial<FetchWindowsDeps> = {
+ sleep: async () => {},
+ 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.maxHeight, from: c.from, to: c.to });
+ const tier = c.maxHeight && c.maxHeight > 720 ? c.maxHeight : undefined;
+ 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 };
+}
+
+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);
+ });
+});
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,39 @@ 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`). 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<height>.mp4`), 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,70 @@ 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;
+}
+
+// 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 +172,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 +187,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,43 @@ 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 tier a cap asks for: none at or under the plain height.
+export function windowTierOf(cap: number | undefined): number | undefined {
+ return cap !== undefined && cap > PLAIN_WINDOW_MAX_HEIGHT ? cap : undefined;
}
-export function clipWindowSidecar(from: number, to: number): string {
- return `${clipWindowName(from, to)}.json`;
+// 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 +167,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 +213,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 +230,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
@@ -228,6 +291,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
@@ -319,6 +386,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,29 @@ 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 },
+ opts: {
+ probe: WindowStreamProbe;
+ setAside?: boolean;
+ record?: boolean;
+ maxHeight?: number;
+ heightProbe?: (file: string) => Promise<number | null>;
+ },
): 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 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 });
diff --git a/common/lib/clipWindowTier-server.ts b/common/lib/clipWindowTier-server.ts
@@ -0,0 +1,70 @@
+// 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, and only an explicit refetch goes to the network again.
+//
+// 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 } from "./savedVideo-server";
+import { savedWindowSource, type SavedWindowSource } from "./savedVideoWindow-server";
+
+export type TallerFromSaved =
+ | { kind: "cut"; source: Extract<SavedWindowSource, { kind: "covers" }>; 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; " +
+ "an explicit refetch (umtool fetch --refetch) fetches it again";
+
+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" };
+ }
+ const best = Math.min(opts.cap, savedHeight);
+ if (best <= have) {
+ return { kind: "lower", why: `the saved copy is ${savedHeight}p, 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,280 @@
+// 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, the taller-from-saved decision and
+// the eviction — temp dirs, stubbed probes, no media.
+//
+// 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, utimes, 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 { evictClipWindows } from "../controller/evictClipWindows";
+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);
+ 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, asked 1080: cut at the ask.
+ await pointer(videoDir);
+ const r3 = await tallerFromSaved({ ...base, hitHeight: null, source: src(covers(1440)) });
+ assert.equal((r3 as { height: number }).height, 1080);
+ // 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("eviction sees a tiered window as a window of its span: named, covered and by age, with its sidecar", async () => {
+ await withVideo(async ({ clips, paths }) => {
+ 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 put(clips, n);
+ }
+ const old = new Date(Date.now() - 400 * 86_400_000);
+ for (const n of ["30.00-40.00.h1080.desynced.mp4"]) await utimes(path.join(clips, n), old, old);
+ const named = await evictClipWindows({ paths, slug: "demo", 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: "demo", id: "v1", olderThanDays: 30 });
+ assert.equal(aged.windows, 1);
+ assert.deepEqual(await readdir(clips), ["50.00-60.00.mp4"]);
+ });
+});
+
+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,50 @@ 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` (16:9, never upscaled, even) — what the filter above makes of
+// it, so a cut can record its height without 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 scale = Math.min(1, boxW / width, maxHeight / height);
+ const h = Math.floor(height * scale);
+ return h - (h % 2) || 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 +263,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,15 @@ 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;
+
/**
* A directory listing, or [] for a directory that is not there.
* @param {string} dir
@@ -80,9 +89,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 +193,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 +352,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 +467,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 +481,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 = 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/savedVideoWindow-server.test.ts b/common/lib/savedVideoWindow-server.test.ts
@@ -13,7 +13,8 @@ import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node
import { tmpdir } from "node:os";
import path from "node:path";
import { cutSavedVideoWindow, savedWindowSource } from "./savedVideoWindow-server";
-import { findContainingClipWindow } from "./clipWindow-server";
+import { findContainingClipWindow, listClipWindows } from "./clipWindow-server";
+import { stat } from "node:fs/promises";
import { probeMedia } from "./evidenceClip-server";
import { SAVED_VIDEOS_MARKER_FILENAME } from "./savedVideoStore";
@@ -266,3 +267,43 @@ 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" },
+ });
+ // The plain cut records its height too: the 160×90 picture, never upscaled.
+ assert.equal(plain.height, 90);
+ assert.equal(plain.provenance?.height, 90);
+ 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" }, maxHeight: 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, 90], ["2.00-5.00.h1080.mp4", 1080, 90]],
+ );
+});
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,
+ windowTierOf,
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): above 720, the cut is fitted inside
+ // that height's 16:9 box and written beside the plain window as
+ // `<from>-<to>.h<maxHeight>.mp4`. Absent or at most 720: the plain window in
+ // the 1280×720 box, as always.
+ maxHeight?: number;
onLog?: (line: string) => void;
signal?: AbortSignal;
}): Promise<ClipWindow> {
const { from, to, source } = opts;
- const dest = clipWindowPath(opts.videoDir, from, to);
+ const tier = windowTierOf(opts.maxHeight);
+ 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,9 @@ export async function cutSavedVideoWindow(opts: {
const bytes = (await stat(tmp)).size;
await rename(tmp, dest);
const now = new Date().toISOString();
+ // The height the box makes of the container's picture: recorded, not
+ // probed (the filter's arithmetic, evidenceClip-server fittedHeight).
+ const height = 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 +222,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 +235,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,15 +243,18 @@ 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(() => {});
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,25 @@ 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");
+});
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,9 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
opts.onLog(`Audio check: ${probe.verdict}${attempt > 1 ? ` (attempt ${attempt})` : ""}.\n`);
}
await rename(produced, dest);
+ // Its picture height, read once now so no later ask has to (the height
+ // tier's record). Unreadable: not recorded.
+ const height = await probeVideoHeight({ ffprobeBin: opts.paths.ffprobeBin, file: dest }).catch(() => null);
const provenance: ClipProvenance = {
requestedBy: opts.provenance.requestedBy,
@@ -636,11 +654,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,23 @@
# 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.
+ - A held window lower than asked, with no taller saved copy, is used as it is and listed under `lower` with why. It
+ is never fetched again for its height.
+ - Every new window records its height in its sidecar. An older one is probed once, the first time a taller window
+ is asked for.
+ - The video page lists the taller windows. Eviction and the clock retirement remove them with their span.
+ - 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: clips are fetched and rendered at the project's `render.maxHeightSource`.** `umtool fetch` and the
+ fetches a build asks the editor for send it. A clip that stays lower is printed with its height and why. The build
+ takes the tallest local source up to that height: a 720 window or raw file gives way to a taller window or the
+ saved copy, and is kept.
- **`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/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).
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,10 +93,14 @@ import {
} from "yt-dlp-transcript-common/lib/savedVideo";
import {
MAX_CLIP_WINDOW_SECONDS,
+ clampWindowCap,
isFetchMaxHeight,
+ 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 {
ffprobeWindowProbe,
findInSyncContainingClipWindow,
@@ -1515,6 +1519,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).
@@ -1615,6 +1625,12 @@ 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 { cap, clampedFrom } = clampWindowCap(req.maxHeight, windowMaxHeightOf(getSettings().clips));
+ const tier = windowTierOf(cap);
+ 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 +1647,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 +1660,20 @@ 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;
+ 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") taller = t;
+ else belowAsked = { asked: tier, why: t.why };
+ }
+ if (hit && !clocked && !taller) {
+ // The window's own height: its sidecar's record, else read once off its
+ // header and recorded there (windowHeightOf) — the only record of how tall
+ // a window fetched under an earlier cap is.
+ const height = await windowHeightOf(hit, heightProbe);
return {
ok: true,
cached: true,
@@ -1659,6 +1683,8 @@ export async function fetchWindowAction(req: {
bytes: hit.bytes,
provenance: hit.provenance,
...(height !== null ? { height } : {}),
+ ...(belowAsked ? { belowAsked } : {}),
+ ...clamped,
};
}
@@ -1666,7 +1692,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 +1704,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 +1720,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 };
}
@@ -1716,14 +1742,14 @@ export async function fetchWindowAction(req: {
from,
to,
provenance: req.provenance,
+ // A tall ask's cut is its own tier, beside any plain window.
+ ...(tier !== undefined ? { maxHeight: tier } : {}),
});
} 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,6 +1760,7 @@ export async function fetchWindowAction(req: {
bytes: cut.bytes,
provenance: cut.provenance,
...(height !== null ? { height } : {}),
+ ...clamped,
};
}
@@ -1814,6 +1841,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 +1864,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 +1905,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 +1931,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,
};
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -17,8 +17,14 @@ 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,
+ 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,
@@ -173,8 +179,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 +228,18 @@ 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 { cap, clampedFrom } = clampWindowCap(maxHeight, windowMaxHeightOf(settings.clips));
+ const tier = windowTierOf(cap);
+ 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,6 +310,7 @@ 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
@@ -295,6 +318,20 @@ async function planFetchWindows(
// 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)))) {
+ 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;
+ }
+ lower.push({ item, file: held.hit.file, height: hitHeight, asked: tier, why: t.why });
+ }
cached.push(item);
continue;
}
@@ -427,7 +464,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,
@@ -561,7 +607,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 +621,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 +705,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 +797,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,96 @@
+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, and lists the one that cannot be taller", 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"]]],
+ );
+ assert.deepEqual(r.cached.map((i) => i.clipId), ["c#2"]);
+ assert.equal(r.lower?.length, 1);
+ assert.equal(r.lower![0].item.clipId, "c#2");
+ assert.equal(r.lower![0].height, 90);
+ assert.equal(r.lower![0].asked, 1080);
+ assert.match(r.lower![0].why, /saved copy is 90p/);
+});
+
+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.equal(r.lower?.[0]?.asked, 1080);
+});
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1992,7 +1992,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/report-video.md b/umtool/docs/report-video.md
@@ -3110,6 +3110,14 @@ 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.
+The body also carries `maxHeight`, the manifest's `render.maxHeightSource`. Above 720 the editor keeps a taller
+window beside the 720 one (`<from>-<to>.h<height>.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". `--refetch <clip>` is the only thing that fetches it again. The build
+takes the tallest local source up to `render.maxHeightSource`: 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 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
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -573,7 +573,8 @@ 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 tall = Number(m?.render?.maxHeightSource);
+ const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe, fallbackChannelsDir: behind, ...(Number.isInteger(tall) ? { maxHeight: tall } : {}) })).filter((w) =>
readable(w.path),
);
if (windows.length) out.push({ video: e.video, windows });
diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs
@@ -63,6 +63,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;
}
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -110,18 +110,34 @@ 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(/\/+$/, "") : "";
+ // THE HEIGHT THE CUT RENDERS FROM (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).
+ const maxHeight = sourceMaxHeight(manifest);
return {
body: {
requestedBy: `umtool:${project}`,
manifest: path.resolve(manifestPath),
storedUrl: "fallback",
...(/^https?:\/\//.test(site) ? { archive: site } : {}),
+ ...(maxHeight !== undefined ? { maxHeight } : {}),
items,
},
skipped,
};
}
+/**
+ * The manifest's `render.maxHeightSource`, when it is a height the editor
+ * accepts as a fetch cap (a whole number from 144 to 2160). Pure.
+ * @param {Record<string, any>} manifest
+ * @returns {number | undefined}
+ */
+export function sourceMaxHeight(manifest) {
+ const v = Number(manifest?.render?.maxHeightSource);
+ return Number.isInteger(v) && v >= 144 && v <= 2160 ? v : undefined;
+}
+
// Twitch's record ids wear a `v` the directory does not: "v123" and "123" are one video.
const sameVideo = (a, b) => String(a).replace(/^v(?=\d+$)/, "") === String(b).replace(/^v(?=\d+$)/, "");
@@ -357,6 +373,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
@@ -299,3 +299,25 @@ 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("the body carries render.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, maxHeightSource: 1080 } };
+ const { body } = fetchWindowsBody(tall, { manifestPath: "/x/m.json", project: "p" });
+ assert.equal(body.maxHeight, 1080);
+ assert.equal(fetchWindowsBody(MANIFEST, { manifestPath: "/x/m.json", project: "p" }).body.maxHeight, undefined);
+ assert.equal(fetchWindowsBody({ ...MANIFEST, render: { 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/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, maxHeight = undefined } = {}) {
const memo = new Map();
const slugOf = (entry) => entry.channel ?? channelSlug ?? null;
return {
@@ -1096,9 +1096,12 @@ 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);
+ // `maxHeight` (render.maxHeightSource): above 720, the tallest the disk
+ // holds up to it -- a lower raw file gives way to a taller corpus window
+ // or the saved copy (sources.mjs, the height tier).
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, ...(maxHeight !== undefined ? { maxHeight } : {}) },
);
// 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 +6963,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 }),
+ ...(Number.isInteger(render?.maxHeightSource) ? { maxHeight: render.maxHeightSource } : {}),
});
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/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs
@@ -134,6 +134,16 @@ if (!token) {
}
const whole = JSON.parse(await readFile(manifestPath, "utf8"));
+// A WINDOW'S HEIGHT: --max-height, else the manifest's render.maxHeightSource
+// (the height the cut renders from). Above 720 the editor keeps the taller
+// window beside the 720 one, held to its clips.windowMaxHeight, and says when a
+// clip stays lower. A whole recording (--full) keeps --max-height alone.
+const manifestMaxHeight = Number(whole?.render?.maxHeightSource);
+const windowMaxHeight =
+ maxHeight ??
+ (Number.isInteger(manifestMaxHeight) && manifestMaxHeight >= MIN_MAX_HEIGHT && manifestMaxHeight <= MAX_MAX_HEIGHT
+ ? manifestMaxHeight
+ : undefined);
const provenance = whole.provenance ?? {};
const pad = Number(flag("--pad") ?? 3);
@@ -295,7 +305,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 +324,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 +425,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 +444,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"], ...(windowMaxHeight !== undefined ? { maxHeight: windowMaxHeight } : {}) },
);
if (!hit) {
die(
@@ -453,7 +468,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 +486,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/sources.mjs b/umtool/report-to-video/sources.mjs
@@ -60,13 +60,15 @@
// 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, rename, stat, writeFile } from "node:fs/promises";
import {
AUDIO_ONLY_PLATFORMS,
CORPUS_TIERS,
WINDOW_RE,
+ isTallAsk,
listNames,
present,
+ probeHeightOnce,
resolveFromTiers,
windowContains,
tightestContaining,
@@ -145,6 +147,54 @@ 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 };
+ const file = rawHeightsPath(rawDir);
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, JSON.stringify(now, null, 2) + "\n").then(() => rename(tmp, file)).catch(() => {});
+ return h;
+}
+
export async function cachedWindowsFor(rawDir, video) {
return windowsFromNames(await listRawNames(rawDir), rawDir, video);
}
@@ -175,10 +225,13 @@ 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[], maxHeight?: number }} [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`).
+ * `maxHeight` (render.maxHeightSource): above 720, the tallest the disk
+ * holds up to it wins -- a raw file lower than what the corpus can give
+ * without a fetch (a taller window, the saved copy) gives way to it.
* @returns {Promise<null | { kind: string, path: string, name: string,
* windowStart: number, windowEnd: number, height?: number }>}
*/
@@ -193,7 +246,7 @@ 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, maxHeight } = config;
if (!video || !Number.isFinite(from) || !Number.isFinite(to)) return null;
if (exact) {
@@ -208,7 +261,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 +286,16 @@ 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, maxHeight = undefined }) {
+ 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 };
+// `maxHeight` above 720 (render.maxHeightSource) 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,60 @@ test("buildVideo --no-network: a video clip with only its sound is refused, unle
await rm(t.root, { recursive: true, force: true });
}
});
+
+// 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, maxHeight: 1080 });
+ 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, maxHeight: 1080 });
+ 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, maxHeight: 1080 });
+ 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, maxHeight: 1080 });
+ 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, maxHeight: 1080 });
+ assert.equal(lower.kind, "corpus-window");
+ assert.equal(lower.name, "0.00-60.00.mp4");
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});