commit 8ad0b83cc8f5743921cca63ea76cf26119face5b parent b6b4be3e00b4ff773a3f88c872c990e0c408ea0c Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Fri, 13 Nov 2026 18:15:52 -0500 Taller clip windows, review fixes: opt-in per project, one cap for every lookup, refetch by tier - render.tallWindows (a look key: umtool look <p> tallWindows=true) is the only switch. Without it a project fetches and resolves exactly as on main: no maxHeight sent, no height probe, no clips-raw.heights.json, no tiered window read. maxHeightSource alone switches nothing. - The cap is read in ONE place (sources.mjs tallWindowCap) from the render block every lookup now states: the build, quote-check, --align, scenes, cut points, the availability check, quick clip, the chain, the bench and fetch-via-editor resolve the same file. A sweep test fails any call site that does not state its render. - evict-clips takes "tiers": "plain" | "tiered" (default both, so the age-out and the clock retirement still remove every tier); a named `<from>-<to>.h<tier>` is that window alone. umtool fetch --refetch evicts the taller windows on a tall project and the plain ones on any other. - A plain ask that misses, over a span a tiered window holds, is cut from that window locally (the 1280x720 box; source "clip-window", derivedFrom), never fetched. - The plain path is main's again: no post-fetch probe, no height written; the single route's plain hit probes without writing. - fittedHeight follows ffmpeg's scale arithmetic (1366x768 in the 720 box is 720), checked against real ffmpeg cuts. - Tiers snap to 1080/1440/2160, held to clips.windowMaxHeight; a job's spec carries its tier and a Retry uses it. - A tall cut from a saved copy waits while render mode holds the machine (said in the log); the single route answers with what there is and why. - check-windows sweeps the tiered windows; fetch_clip says belowAsked; a saved copy with no height gets the probed one on probed.height. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
52 files changed, 994 insertions(+), 181 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md @@ -173,7 +173,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `build-homepage` | build-homepage builds the homepage package into homepage/out; {"deploy": true} deploys it after (only if the build succeeded), and deploy-homepage ships the one already built. Both deploy to the Pages project archilyzer (https://archilyzer.pages.dev), production unless "preview" is given. | | | `relocate` | relocate moves channels' media to a location: {"slugs", "locationId" \| "root"}. "dryRun": true answers each channel's preview (bytes to copy, free space both sides) and moves nothing — though, as on the Storage panel, a channel never tiered is first tiered in place on the corpus disk. | `pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter"}'`<br>`pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter","dryRun":true}'` | | `relocate-back` | relocate-back moves channels' media back onto the corpus disk, one job per channel on the relocation queue: {"slugs"}. A busy channel is answered in "skipped"; --wait follows the jobs started. | | -| `evict-clips` | evict-clips deletes cached clip windows (data/<id>/clips/) older than a number of days, as /storage's button does: {"olderThanDays", "slug"?, "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a window; an evicted window is fetched again when asked for. TARGETED, for windows known bad: {"slug", "id"} evicts every window of that video; "windows": \["<from>-<to>", ...\] only those named, "covering": \[{"from", "to"}, ...\] any window overlapping a span (umtool fetch --refetch asks this way); "olderThanDays" is then optional, "dryRun" only lists. | `pnpm ops evict-clips --json '{"slug":"x","id":"abc123","covering":[{"from":10,"to":40}],"dryRun":true}' --wait` | +| `evict-clips` | evict-clips deletes cached clip windows (data/<id>/clips/) older than a number of days, as /storage's button does: {"olderThanDays", "slug"?, "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a window; an evicted window is fetched again when asked for. TARGETED, for windows known bad: {"slug", "id"} evicts every window of that video; "windows": \["<from>-<to>", ...\] only those named, "covering": \[{"from", "to"}, ...\] any window overlapping a span (umtool fetch --refetch asks this way); "olderThanDays" is then optional, "dryRun" only lists. "tiers": "plain" \| "tiered" narrows to the <from>-<to> windows or the taller <from>-<to>.h<height> ones (default "all": both). | `pnpm ops evict-clips --json '{"slug":"x","id":"abc123","covering":[{"from":10,"to":40}],"dryRun":true}' --wait` | | `check-windows` | check-windows probes cached clip windows (data/<id>/clips/) for a picture that runs off the sound (a Rumble HLS seek) and sets each desynced one aside as <from>-<to>.desynced.<ext> (never deleted; no reader sees it, and evict-clips ages it out): {"slug"?, "video"?, "dryRun"?}. "video" needs "slug"; "dryRun" only lists. A fetch then fills the span again, from the saved video first. | | | `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "<id>"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` | | `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` | diff --git a/OPERATING.md b/OPERATING.md @@ -798,16 +798,26 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md" - `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. 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 window asked taller than 720 (`"maxHeight"` on `fetch-windows`, fetch-window, `fetch_clip`; umtool sends it only + for a project with `render.tallWindows` on) is its own file beside the 720 one: `clips/<from>-<to>.h<tier>.mp4`, + with its own sidecar. The 720 window is never replaced, retired or re-fetched for this. An ask with no `maxHeight` + is 720, as before. + - The tier is the smallest of 1080, 1440 and 2160 at or above the ask, held to `settings.clips.windowMaxHeight` + (default 1080), so asks of 900 and 1080 share one file. A Retry keeps the tier its job was queued at. + - A held window lower than asked is cut taller from the video's saved copy when that copy is taller. That cut waits + while render mode holds the machine, and says so in the job log. A single fetch-window answers with what there is + now instead, and says why. + - With no taller saved copy, the lower window is used as it is. The answer lists it under `"lower"` (fetch-window + and `fetch_clip`: `belowAsked`) with its height and why. Nothing fetches a taller one from the network over it; + persist the video (`persist-videos`) to give it a copy to cut from. + - `umtool fetch --refetch` on a tall project evicts only the taller windows of the span, then cuts them again; the + 720 window stays. Without `render.tallWindows` a refetch evicts the 720 windows only, as before. + - Heights are recorded only for taller windows, and for a 720 window the first time a tall ask needs it (one probe, + written to its sidecar). A saved copy with no recorded height gets the height that probe found (`probed.height`). + - A 720 ask that misses, over a span a taller window holds, is cut from that window (the 1280×720 box; its sidecar + says `source: "clip-window"`, `derivedFrom`), never fetched. + - `evict-clips` takes `"tiers": "plain" | "tiered"` (default both). The age-out, named and covering evictions and the + clock retirement treat a taller window as a window of its span. `check-windows` checks the taller windows too. - A cited recording deleted or made private on its platform cannot be fetched from its page. `find-copy` (a site's `siteId`, an `article`, or `"articles": true`) looks for a copy of each — a Wayback Machine capture of its page, then an archive.org mirror naming its YouTube id — and fetches the cited windows from it as one fetch-windows job; diff --git a/SETTINGS.md b/SETTINGS.md @@ -1365,7 +1365,7 @@ How clip windows are fetched (controller/fetchWindows.ts): the platforms whose w | 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. | +| `windowMaxHeight` | `1080` | The tallest source height, in pixels, a clip-window request may ask for (`maxHeight` on fetch-window, fetch-windows, fetch_clip; umtool sends its project's `render.maxHeightSource` only when the project has `render.tallWindows` on). A CEILING, not a default: a request with no `maxHeight` is fetched and cut at 720 as before, and one asking more is clamped to this. A window asked above 720 is a separate cache entry beside the 720 one (`<from>-<to>.h<tier>.mp4`, the tier the smallest of 1080, 1440, 2160 at or above the ask, held to this), cut from the saved copy when there is a taller one; the 720 window and every published site's evidence media are never touched. Site-driven fetches (`fetch-windows {"siteId"}`, Fetch missing evidence) stay at 720. Default 1080; 144–2160. | Default: diff --git a/common/controller/checkClipWindows.ts b/common/controller/checkClipWindows.ts @@ -81,7 +81,8 @@ async function checkVideo( out: CheckClipWindowsResult, ): Promise<void> { const videoDir = path.join(opts.paths.channelsDir, slug, "data", id); - const windows = await listClipWindows(videoDir); + // The taller (tiered) windows too: a remote seek at any height can run off its sound. + const windows = await listClipWindows(videoDir, { tiers: true }); if (windows.length === 0) return; out.videos += 1; for (const w of windows) { diff --git a/common/controller/evictClipWindows.ts b/common/controller/evictClipWindows.ts @@ -4,9 +4,10 @@ import type { Paths } from "../lib/paths"; import { CLIPS_DIR_NAME, clipWindowDesyncedSidecar, - clipWindowName, clipWindowSidecar, + clipWindowStem, parseAnyClipWindowName, + parseTieredClipWindowName, parseClipWindowName, parseDesyncedClipWindowName, } from "../lib/clipWindow"; @@ -58,6 +59,15 @@ import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; // `<from>-<to>.desynced.<ext>` of a targeted span goes with it. export type ClipWindowSpan = { from: number; to: number }; +// A named window: its span, and — named `<from>-<to>.h<tier>` — that tier only. +export type NamedClipWindow = ClipWindowSpan & { tier?: number }; + +export const EVICT_TIERS = ["all", "plain", "tiered"] as const; +export type EvictTiers = (typeof EVICT_TIERS)[number]; + +export function isEvictTiers(v: unknown): v is EvictTiers { + return typeof v === "string" && (EVICT_TIERS as readonly string[]).includes(v); +} export type EvictClipWindowsOptions = { paths: Paths; @@ -66,10 +76,18 @@ export type EvictClipWindowsOptions = { // One video of `slug` (a record id; a Twitch v<n> resolves to its dir, as // check-windows does). Every window of it, unless `windows`/`covering` narrow. id?: string; - // Windows named exactly (`<from>-<to>`, parsed): needs `id`. - windows?: ClipWindowSpan[]; + // Windows named exactly (`<from>-<to>`, parsed): needs `id`. A plain name + // names its span (every tier `tiers` allows); `<from>-<to>.h<tier>` names + // that tiered window alone. + windows?: NamedClipWindow[]; // Any window overlapping one of these spans: needs `id`. covering?: ClipWindowSpan[]; + // WHICH WINDOWS OF A SPAN (the height tier, lib/clipWindow.ts): "all" (the + // default — the age-out, a named or covering eviction, the clock + // retirement), "plain" (`<from>-<to>.<ext>` only) or "tiered" (the taller + // `<from>-<to>.h<tier>.<ext>` cuts only — what umtool's refetch of a tall + // project asks, so the 720 window a site's evidence reads stays). + tiers?: EvictTiers; // A window is evicted when it has not been touched for this many days. // 0 means "everything", which is a legitimate ask (the operator is emptying // a drive) and is why this is not clamped to a minimum. Required unless @@ -199,6 +217,9 @@ async function evictChannel( const aside = live ? null : parseDesyncedClipWindowName(name); const span = live ?? aside; if (!span) continue; + // The tier filter: a window of the other kind is not this run's. + const tiers = opts.tiers ?? "all"; + if ((tiers === "plain" && span.tier !== undefined) || (tiers === "tiered" && span.tier === undefined)) continue; const file = path.join(clipsDir, name); let st; try { @@ -209,7 +230,7 @@ async function evictChannel( if (!st.isFile()) continue; sawWindow = true; if (opts.windows || opts.covering) { - const hits = named.flatMap((w, i) => (sameSpan(w, span) ? [i] : [])); + const hits = named.flatMap((w, i) => (sameSpan(w, span) && (w.tier === undefined || w.tier === span.tier) ? [i] : [])); for (const i of hits) matchedNames.add(i); const covered = (opts.covering ?? []).some((c) => overlaps(c, span)); if (!hits.length && !covered) { @@ -264,7 +285,7 @@ const sameSpan = (a: ClipWindowSpan, b: ClipWindowSpan) => // Strictly: a window that only touches a span's edge holds none of its seconds. const overlaps = (a: ClipWindowSpan, b: ClipWindowSpan) => a.from < b.to && b.from < a.to; -const spanName = (w: ClipWindowSpan) => clipWindowName(w.from, w.to); +const spanName = (w: NamedClipWindow) => clipWindowStem(w.from, w.to, w.tier); const isSpanObj = (v: unknown): v is ClipWindowSpan => { if (!v || typeof v !== "object" || Array.isArray(v)) return false; @@ -289,17 +310,20 @@ export function parseEvictTargets(raw: { windows?: unknown; covering?: unknown; }): - | { ok: true; windows?: ClipWindowSpan[]; covering?: ClipWindowSpan[] } + | { ok: true; windows?: NamedClipWindow[]; covering?: ClipWindowSpan[] } | { ok: false; error: string } { - const out: { windows?: ClipWindowSpan[]; covering?: ClipWindowSpan[] } = {}; + const out: { windows?: NamedClipWindow[]; covering?: ClipWindowSpan[] } = {}; if (raw.windows !== undefined) { const v = raw.windows; if (!Array.isArray(v) || v.length === 0) { return { ok: false, error: '"windows" must be a non-empty array of "<from>-<to>" names (e.g. "1992.68-2013.56")' }; } - const spans: ClipWindowSpan[] = []; + const spans: NamedClipWindow[] = []; for (const name of v) { - const span = typeof name === "string" ? parseClipWindowName(name.trim()) : null; + const span = + typeof name === "string" + ? (parseClipWindowName(name.trim()) ?? parseTieredClipWindowName(`${name.trim()}.mp4`)) + : null; if (!span) { return { ok: false, error: `"windows" holds ${JSON.stringify(name)}, which is not a window name "<from>-<to>" (seconds, from < to)` }; } diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -13,8 +13,9 @@ import type { SavedVideoOrigin } from "../lib/savedVideo"; import { DEFAULT_CLIPS_SETTINGS, windowMaxHeightOf } from "../lib/clipSettings"; import { downloadOneManaged, sourceFetchFailure } from "../ytdlp/downloadOneManaged"; import { resolveSourceVideoQuality } from "../ytdlp/downloadFormat"; -import { clampWindowCap, windowTierOf, type ClipCopy } from "../lib/clipWindow"; +import { clampWindowCap, isWindowTier, windowTierOf, type ClipCopy } from "../lib/clipWindow"; import { tallerFromSaved } from "../lib/clipWindowTier-server"; +import { renderModeHeldNow, waitWhileRenderHeld } from "../lib/renderHold"; import { probeVideoHeight } from "../ytdlp/ffprobeDuration"; import { isSourceSideCopyFailure, recordFailedCopy, type FailedCopy } from "../lib/copyAttempts-server"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; @@ -35,9 +36,10 @@ import { channelConfigPlatform } from "../lib/videoId"; import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; import { ensureRecordingClock } from "../lib/recordingClock-server"; import type { RecordingClock } from "../lib/recordingClock.mjs"; -import { listClipWindows } from "../lib/clipWindow-server"; +import { listClipWindows, tieredWindowHolding } from "../lib/clipWindow-server"; import { evictClipWindows } from "./evictClipWindows"; import { + cutPlainFromTieredWindow, cutSavedVideoWindow, savedWindowSource, } from "../lib/savedVideoWindow-server"; @@ -370,6 +372,11 @@ export type FetchWindowsDeps = { // A window's picture height, for a tall ask over a window with none // recorded (probed once; the answer is written to its sidecar). probeHeight: (file: string, paths: Paths) => Promise<number | null>; + // Render mode's holder, or null (lib/renderHold.ts): a TALL cut from a saved + // copy waits while it holds the machine. + renderHeld: () => string | null; + // A plain window cut from a tiered one (a plain miss, the height tier). + cutPlainFromTiered: typeof cutPlainFromTieredWindow; }; // The windows of a video cut on another clock than `clockId`, evicted through @@ -516,6 +523,8 @@ const DEFAULT_DEPS: FetchWindowsDeps = { }), retireOffClock: retireOffClockWindows, probeHeight: (file, paths) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file }), + renderHeld: renderModeHeldNow, + cutPlainFromTiered: cutPlainFromTieredWindow, assertMediaReachable: (paths, slug) => assertChannelMediaReachable(paths, slug), saveWholeRecording: saveWholeRecordingManaged, }; @@ -565,6 +574,7 @@ export async function fetchWindows({ items, provenance, maxHeight, + tier: givenTier, gapMs, minGapSeconds, storedUrl: storedMode = "never", @@ -579,6 +589,10 @@ export async function fetchWindows({ items: FetchWindowsItem[]; provenance: FetchWindowsProvenance; maxHeight?: number; + // THE TIER THE RUN WAS QUEUED AT (lib/clipWindow.ts windowTierOf), carried + // in its job spec so a Retry cuts the same file whatever the settings say + // now. Absent: decided here from `maxHeight` and clips.windowMaxHeight. + tier?: number; // The pause between two network fetches. Absent = the platform's batch gap, // floored at CLIP_WINDOW_MIN_GAP_SECONDS. gapMs?: number; @@ -607,8 +621,14 @@ export async function fetchWindows({ // 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); + // A tier a Retry carries in its spec wins over today's settings (`tier`). + const ceiling = windowMaxHeightOf(settings.clips); + const fixed = isWindowTier(givenTier) ? givenTier : undefined; + const { cap: asked, clampedFrom } = + fixed !== undefined ? { cap: fixed as number | undefined, clampedFrom: undefined as number | undefined } : clampWindowCap(maxHeight, ceiling); + const tier = fixed ?? windowTierOf(asked, ceiling); + // The network's cap: the tier when tall (so 900 and 1080 fetch one file), else the ask as given. + const cap = tier ?? asked; const work = dedupeFetchWindowsItems(items); const result: FetchWindowsResult = { fetched: [], @@ -751,6 +771,22 @@ export async function fetchWindows({ source: Extract<Awaited<ReturnType<typeof savedWindowSource>>, { kind: "covers" }>, beside?: string, ): Promise<void> => { + // A TALL cut waits while render mode holds the machine (H, 13 Nov): not + // heavy enough for the slot, but cores a render wants. Said in the log. + if (tier !== undefined) { + const waited = await waitWhileRenderHeld({ + held: deps.renderHeld, + sleep: deps.sleep, + onLog: log, + what: `${label} (the ${tier}p cut)`, + signal: fetchSignal, + }); + if (waited === null) { + result.notAttempted.push(item); + result.stopped ??= "cancel"; + return; + } + } try { const cut = await deps.cutSavedWindow({ paths, @@ -759,7 +795,7 @@ export async function fetchWindows({ from: item.from, to: item.to, // A tall ask's cut is its own tier, beside any plain window. - ...(tier !== undefined ? { maxHeight: tier } : {}), + ...(tier !== undefined ? { tier } : {}), provenance: { requestedBy: provenance.requestedBy, manifest: provenance.manifest, @@ -928,6 +964,41 @@ export async function fetchWindows({ continue; } + // A PLAIN MISS A TALLER WINDOW HOLDS (D, 13 Nov): the plain 720 window is + // cut here from the tiered file — the evidence filter, nothing fetched, + // nothing on disk changed but the new window. A cut that fails goes on to + // the network as before. + if (tier === undefined) { + const tiered = await tieredWindowHolding(videoDir, item.from, item.to); + if (tiered) { + try { + const cut = await deps.cutPlainFromTiered({ + paths, + videoDir, + tiered, + from: item.from, + to: item.to, + provenance: { + requestedBy: provenance.requestedBy, + manifest: provenance.manifest, + clipId: item.clipId, + reason: item.reason, + pad: item.pad, + requestedAt, + }, + signal: fetchSignal, + }); + result.cut.push(item); + log(` ✂ ${label}: cut from clips/${tiered.file} into clips/${cut.file} (the 720 window; nothing fetched)`); + done += 1; + progress(); + continue; + } catch (e) { + log(` ${label}: cutting it from clips/${tiered.file} failed (${(e as Error).message}) — fetching it instead.`); + } + } + } + const url = item.webpageUrl?.trim() || (await deps.findVideoSourceUrl(paths, item.slug, dirId, config)); diff --git a/common/controller/fetchWindowsTier.test.ts b/common/controller/fetchWindowsTier.test.ts @@ -44,11 +44,21 @@ const covers = (height: number): SavedWindowSource => probe: { durationSec: 100, width: Math.round((height * 16) / 9), height, hasVideo: true, hasAudio: true }, }) as SavedWindowSource; -function harness(o: { saved?: SavedWindowSource; windowMaxHeight?: number } = {}) { +function harness(o: { saved?: SavedWindowSource; windowMaxHeight?: number; renderHeld?: () => string | null } = {}) { const fetches: FetchWindowOpts[] = []; const cuts: { maxHeight?: number; from: number; to: number }[] = []; + const derived: { from: string; to: number }[] = []; + const sleeps: number[] = []; const deps: Partial<FetchWindowsDeps> = { - sleep: async () => {}, + sleep: async (ms) => { + sleeps.push(ms); + }, + renderHeld: o.renderHeld ?? (() => null), + cutPlainFromTiered: async (c) => { + derived.push({ from: c.tiered.file, to: c.to }); + const file = `${c.from.toFixed(2)}-${c.to.toFixed(2)}.mp4`; + return { file, path: path.join(c.videoDir, "clips", file), from: c.from, to: c.to, bytes: 1, provenance: null }; + }, getSettings: () => ({ sleepBetweenDownloadsSeconds: 0, @@ -67,8 +77,8 @@ function harness(o: { saved?: SavedWindowSource; windowMaxHeight?: number } = {} 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; + cuts.push({ maxHeight: c.tier, from: c.from, to: c.to }); + const tier = c.tier; const file = `${c.from.toFixed(2)}-${c.to.toFixed(2)}${tier ? `.h${tier}` : ""}.mp4`; return { file, path: path.join(c.videoDir, "clips", file), from: c.from, to: c.to, bytes: 1, provenance: null, ...(tier ? { tier, height: tier } : {}) }; }, @@ -77,7 +87,7 @@ function harness(o: { saved?: SavedWindowSource; windowMaxHeight?: number } = {} return { file: "/x", from: f.from, to: f.to, bytes: 1, cached: false, provenance: null } as never; }, }; - return { deps, fetches, cuts }; + return { deps, fetches, cuts, derived, sleeps }; } const item: FetchWindowsItem = { slug: "c", id: "v1", from: 10, to: 20 }; @@ -217,3 +227,96 @@ test("eviction sees a tiered window as a window of its span: named, covered and assert.deepEqual(await readdir(clips), ["50.00-60.00.mp4"]); }); }); + +// C: the tier filter — what a refetch asks. "tiered" leaves the 720 window a +// site reads; "plain" leaves the taller cuts; a named tiered window is that one. +test("eviction's tier filter: covering with tiers tiered or plain removes only that kind", async () => { + await withCorpus(async ({ paths, clips }) => { + await writeFile(path.join(paths.channelsDir, "c", "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube" })); + const seed = async () => { + for (const n of ["10.00-20.00.mp4", "10.00-20.00.json", "10.00-20.00.h1080.mp4", "10.00-20.00.h1080.json", "10.00-20.00.h1440.mp4"]) { + await writeFile(path.join(clips, n), "media"); + } + }; + await seed(); + const tall = await evictClipWindows({ paths, slug: "c", id: "v1", covering: [{ from: 12, to: 18 }], tiers: "tiered" }); + assert.equal(tall.windows, 2); + assert.deepEqual((await readdir(clips)).sort(), ["10.00-20.00.json", "10.00-20.00.mp4"]); + await seed(); + const plain = await evictClipWindows({ paths, slug: "c", id: "v1", covering: [{ from: 12, to: 18 }], tiers: "plain" }); + assert.equal(plain.windows, 1); + assert.deepEqual((await readdir(clips)).sort(), ["10.00-20.00.h1080.json", "10.00-20.00.h1080.mp4", "10.00-20.00.h1440.mp4"]); + await seed(); + const one = await evictClipWindows({ paths, slug: "c", id: "v1", windows: [{ from: 10, to: 20, tier: 1080 }] }); + assert.equal(one.windows, 1); + assert.ok(!(await readdir(clips)).includes("10.00-20.00.h1080.mp4")); + assert.ok((await readdir(clips)).includes("10.00-20.00.mp4")); + }); +}); + +// G: THE LADDER. Asks of 900, 1000 and 1080 share the 1080 file; a Retry's +// tier (its spec) wins over today's settings. +test("tiers snap to the ladder, held to the ceiling; a given tier wins over the settings", async () => { + await withCorpus(async ({ paths }) => { + for (const ask of [900, 1000, 1080]) { + const h = harness(); + await run(paths, h.deps, ask); + assert.equal(h.fetches[0].tier, 1080, String(ask)); + assert.equal(h.fetches[0].maxHeight, 1080, String(ask)); + } + const over = harness({ windowMaxHeight: 2160 }); + await run(paths, over.deps, 1200); + assert.equal(over.fetches[0].tier, 1440); + const held = harness({ windowMaxHeight: 1200 }); + await run(paths, held.deps, 1200); + assert.equal(held.fetches[0].tier, 1200, "a rung above the ceiling is held to it"); + // A Retry: the spec's 1440, though today's ceiling is 1080. + const retry = harness({ windowMaxHeight: 1080 }); + await fetchWindows({ paths, items: [item], provenance: { requestedBy: "umtool" }, maxHeight: 1440, tier: 1440, gapMs: 0, deps: retry.deps }); + assert.equal(retry.fetches[0].tier, 1440); + }); +}); + +// D: a PLAIN miss a tiered window holds is cut locally from it, never fetched. +test("a plain ask that misses, over a span a tiered window holds, is cut from that window; nothing is fetched", async () => { + await withCorpus(async ({ paths, clips }) => { + await writeFile(path.join(clips, "0.00-30.00.h1080.mp4"), "taller"); + await writeFile(path.join(clips, "0.00-30.00.h1080.json"), JSON.stringify({ requestedBy: "umtool", height: 1080 })); + const h = harness(); + const lines: string[] = []; + const r = await run(paths, h.deps, undefined, lines); + assert.deepEqual(h.derived, [{ from: "0.00-30.00.h1080.mp4", to: 20 }]); + assert.equal(h.fetches.length, 0); + assert.equal(r.cut.length, 1); + assert.match(lines.join(""), /cut from clips\/0\.00-30\.00\.h1080\.mp4 into clips\/10\.00-20\.00\.mp4/); + // A cut that fails goes to the network, as before. + const bad = harness(); + bad.deps.cutPlainFromTiered = async () => { + throw new Error("ffmpeg refused"); + }; + await run(paths, bad.deps); + assert.equal(bad.fetches.length, 1); + }); +}); + +// H: a tall cut from the saved copy waits while render mode holds the machine. +test("a tall cut from the saved copy waits out render mode, and says so", async () => { + await withCorpus(async ({ paths }) => { + let polls = 0; + const h = harness({ saved: covers(1080), renderHeld: () => (polls++ < 2 ? "umtool take p --id t, since 13:31" : null) }); + const lines: string[] = []; + const r = await run(paths, h.deps, 1080, lines); + assert.equal(h.cuts.length, 1); + assert.equal(r.cut.length, 1); + assert.equal(h.sleeps.length, 2); + const text = lines.join(""); + assert.match(text, /the 1080p cut\): render mode holds the machine \(umtool take p --id t, since 13:31\) — waiting/); + assert.match(text, /render mode ended — waited \d+s/); + // A plain cut does not wait. + let asked = 0; + const plain = harness({ saved: covers(1080), renderHeld: () => (asked++, "held") }); + await run(paths, plain.deps); + assert.equal(asked, 0); + assert.equal(plain.cuts.length, 1); + }); +}); diff --git a/common/lib/clipSettings.ts b/common/lib/clipSettings.ts @@ -37,11 +37,12 @@ export const CLIPS_SETTINGS_FIELD_DOCS: FieldDocs<ClipsSettings> = { "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. " + + "fetch-windows, fetch_clip; umtool sends its project's `render.maxHeightSource` only when the project has " + + "`render.tallWindows` on). A CEILING, not a default: a request with no `maxHeight` is fetched and cut at 720 as " + + "before, and one asking more is clamped to this. A window asked above 720 is a separate cache entry beside the " + + "720 one (`<from>-<to>.h<tier>.mp4`, the tier the smallest of 1080, 1440, 2160 at or above the ask, held to this), " + + "cut from the saved copy when there is a taller one; the 720 window and every published site's evidence media " + + "are never touched. Site-driven fetches (`fetch-windows {\"siteId\"}`, Fetch missing evidence) stay at 720. " + "Default 1080; 144–2160.", }; diff --git a/common/lib/clipWindow-server.ts b/common/lib/clipWindow-server.ts @@ -129,6 +129,22 @@ export async function windowHeightOf( return h; } +// A PLAIN MISS'S LOCAL SOURCE: the tightest TIERED window holding [from, to] +// (lowest tier of equals — the least to decode), or null. A plain window can +// be cut from it (savedVideoWindow-server cutPlainFromTieredWindow) instead +// of a fetch. +export async function tieredWindowHolding( + videoDir: string, + from: number, + to: number, +): Promise<ClipWindow | null> { + const held = (await listClipWindows(videoDir, { tiers: true })).filter( + (w) => w.tier !== undefined && clipWindowContains(w, from, to), + ); + held.sort((a, b) => a.to - a.from - (b.to - b.from) || (a.tier ?? 0) - (b.tier ?? 0)); + return held[0] ?? null; +} + // THE TALL LOOKUP: of the windows (plain and tiered) holding [from, to], the // order a request for `cap` pixels takes them in — the tallest at or under the // cap first (the tightest of equals), then those taller than the cap, lowest diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts @@ -95,9 +95,21 @@ export function clipWindowName(from: number, to: number): string { // 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; +// THE LADDER a tier snaps to, so asks of 900, 1000 and 1080 share one file. +export const WINDOW_TIER_RUNGS = [1080, 1440, 2160] as const; + +// The tier a (clamped) cap asks for: none at or under the plain height; else +// the smallest rung at or above it, held to the ceiling (clips.windowMaxHeight). +export function windowTierOf(cap: number | undefined, ceiling: number = MAX_FETCH_MAX_HEIGHT): number | undefined { + if (cap === undefined || cap <= PLAIN_WINDOW_MAX_HEIGHT) return undefined; + const rung = WINDOW_TIER_RUNGS.find((r) => r >= cap) ?? MAX_FETCH_MAX_HEIGHT; + return Math.min(rung, ceiling); +} + +// A tier a job spec carries (a Retry runs on the tier it was asked with, not +// on today's settings): a whole number above the plain height, at most 4K. +export function isWindowTier(v: unknown): v is number { + return typeof v === "number" && Number.isInteger(v) && v > PLAIN_WINDOW_MAX_HEIGHT && v <= MAX_FETCH_MAX_HEIGHT; } // A request's height against the setting's ceiling: absent stays absent (the @@ -266,10 +278,14 @@ export type ClipProvenance = { // the media URL its metadata.info.json stores (release 32 R5, // lib/storedMediaUrl.ts), with that URL's host in `sourceHost`; // "live-recording" for one cut from a live recording still in progress (live - // pre-clip's share, lib/livePreclip-server.ts cutLiveWindow). Absent on a - // window fetched through the page. + // pre-clip's share, lib/livePreclip-server.ts cutLiveWindow); "clip-window" + // for a plain 720 window cut locally from a taller tiered window of the same + // video (`derivedFrom` names it; lib/savedVideoWindow-server.ts + // cutPlainFromTieredWindow). Absent on a window fetched through the page. source?: ClipWindowSource; sourceHost?: string; + // "clip-window": the tiered window's file name this one was cut from. + derivedFrom?: string; // How many times the player's page was opened for this window's cut (release // 32 R9, ytdlp/storedUrlPageOpen.ts): a stored-URL cut opens it before the // first cut of each video in a run. Absent when none was. @@ -329,7 +345,7 @@ export function coerceClipCopy(v: unknown): ClipCopy | undefined { return { from: r.from as ClipCopy["from"], url: r.url }; } -export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url", "live-recording"] as const; +export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url", "live-recording", "clip-window"] as const; export type ClipWindowSource = (typeof CLIP_WINDOW_SOURCES)[number]; const str = (v: unknown): string | undefined => @@ -371,6 +387,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null { } const sourceHost = str(r.sourceHost); if (sourceHost) out.sourceHost = sourceHost; + const derivedFrom = str(r.derivedFrom); + if (derivedFrom) out.derivedFrom = derivedFrom; const pageOpens = num(r.pageOpens); if (pageOpens !== undefined && pageOpens > 0) out.pageOpens = pageOpens; const copy = coerceClipCopy(r.copy); diff --git a/common/lib/clipWindowTier-server.ts b/common/lib/clipWindowTier-server.ts @@ -6,7 +6,8 @@ // 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. +// reason. Nothing fetches a taller window from the network over a lower one: +// persisting the video gives it a copy to cut from. // // Cheap first: the pointer's recorded height (`format`, else `probed`) settles // most asks with no probe; the saved container is probed (savedWindowSource) @@ -15,7 +16,7 @@ // SERVER-ONLY. import type { Paths } from "./paths"; -import { loadSavedVideo } from "./savedVideo-server"; +import { loadSavedVideo, recordSavedVideoProbedHeight } from "./savedVideo-server"; import { savedWindowSource, type SavedWindowSource } from "./savedVideoWindow-server"; export type TallerFromSaved = @@ -24,7 +25,7 @@ export type TallerFromSaved = 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"; + "persist the video (persist-videos) to give it one"; export async function tallerFromSaved(opts: { paths: Pick<Paths, "transcriptsDir" | "savedVideosDir" | "ffprobeBin">; @@ -62,6 +63,11 @@ export async function tallerFromSaved(opts: { if (!source.probe.hasVideo || savedHeight === null) { return { kind: "lower", why: "the saved copy's picture height cannot be read" }; } + // A pointer with no height gets the probe's, so the next ask is answered + // from the pointer (a failed write costs that ask a probe, nothing else). + if (recorded === undefined && source.probe.height) { + await recordSavedVideoProbedHeight(opts.videoDir, pointer.file, source.probe.height).catch(() => false); + } 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` }; diff --git a/common/lib/clipWindowTier.test.ts b/common/lib/clipWindowTier.test.ts @@ -79,6 +79,13 @@ test("the tier and the ceiling: no ask is the plain path; above the ceiling is c assert.equal(windowTierOf(720), undefined); assert.equal(windowTierOf(480), undefined); assert.equal(windowTierOf(1080), 1080); + // THE LADDER: 900, 1000, 1080 share one file; held to the ceiling. + assert.equal(windowTierOf(900, 1080), 1080); + assert.equal(windowTierOf(1000, 1080), 1080); + assert.equal(windowTierOf(1200, 2160), 1440); + assert.equal(windowTierOf(1600, 2160), 2160); + assert.equal(windowTierOf(1200, 1200), 1200); + assert.equal(windowTierOf(721, 900), 900); assert.deepEqual(clampWindowCap(undefined, 1080), { cap: undefined }); assert.deepEqual(clampWindowCap(1080, 1080), { cap: 1080 }); assert.deepEqual(clampWindowCap(2160, 1080), { cap: 1080, clampedFrom: 2160 }); @@ -227,10 +234,12 @@ test("taller from the saved copy: only when the copy is taller than the window; 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. + // A 1440 copy with no recorded height, asked 1080: cut at the ask, and the + // probed height kept on the pointer so the next ask needs no probe (I). await pointer(videoDir); const r3 = await tallerFromSaved({ ...base, hitHeight: null, source: src(covers(1440)) }); assert.equal((r3 as { height: number }).height, 1080); + assert.equal(JSON.parse(await readFile(path.join(videoDir, "saved-video.json"), "utf8")).probed.height, 1440); // A copy that does not hold the span, or has no picture: lower, with why. const r4 = await tallerFromSaved({ ...base, hitHeight: 720, source: async () => ({ kind: "not-covering", container: "/s", durationSec: 5 }) }); assert.match((r4 as { why: string }).why, /does not hold this span/); diff --git a/common/lib/evidenceClip-server.ts b/common/lib/evidenceClip-server.ts @@ -222,9 +222,14 @@ export function fitBoxWidth(maxHeight: number): number { } // 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. +// `maxHeight` — the filter above, computed THE WAY FFMPEG DOES +// (libavfilter scale_eval.c, ff_scale_adjust_dimensions): the expressions give +// w = min(boxW, iw), h = min(boxH, ih); `force_original_aspect_ratio=decrease` +// then takes w = min(w, round(h·iw/ih)) and h = min(h, round(w·ih/iw)) from +// those (av_rescale rounds to nearest), and `force_divisible_by=2` rounds each +// DOWN to even. So 1366×768 in the 720 box is 1280×720, as ffmpeg writes it. +// A tiered cut records this instead of probing what it wrote. Null for a size +// it was not told. export function fittedHeight( width: number | null, height: number | null, @@ -232,9 +237,11 @@ export function fittedHeight( ): 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; + const w0 = Math.min(boxW, width); + const h0 = Math.min(maxHeight, height); + const h = Math.min(h0, Math.round((w0 * height) / width)); + const even = h - (h % 2); + return even > 0 ? even : null; } // The ffmpeg arguments that cut [a, b] seconds INTO `file` as `kind`, writing diff --git a/common/lib/renderHold.ts b/common/lib/renderHold.ts @@ -0,0 +1,50 @@ +// RENDER MODE, AS A WAIT (common/lib/renderPriority.mjs; AGENTS.md "Render +// mode"): work that is not heavy enough for the heavy slot but still takes +// cores a render the operator is waiting for wants — a taller clip window cut +// from a saved copy (the height tier) — waits while the hold is on, the way +// the lanes are held. Read as the heavy slot's gate reads it. +// +// SERVER-ONLY. + +import { describeRenderPriority, readRenderPriority, renderPriorityFile } from "./renderPriority.mjs"; + +/** Render mode, as the heavy slot's gate reads it: who holds it, or null. */ +export function renderModeHeldNow(): string | null { + try { + const s = readRenderPriority(renderPriorityFile(process.env, { root: process.cwd() })); + return s.held && s.state ? describeRenderPriority(s.state) : null; + } catch { + return null; // an unreadable state file holds nothing (queue-lock's rule) + } +} + +export const RENDER_HOLD_POLL_MS = 30_000; + +// Wait while `held()` names a holder: one line when the wait starts, one when +// it ends. Returns how long it waited (0: not held), or null when `signal` +// ended the wait first. +export async function waitWhileRenderHeld(opts: { + held?: () => string | null; + sleep: (ms: number, signal?: AbortSignal) => Promise<void>; + onLog: (line: string) => void; + what: string; + signal?: AbortSignal; + pollMs?: number; + now?: () => number; +}): Promise<number | null> { + const held = opts.held ?? renderModeHeldNow; + const now = opts.now ?? Date.now; + let by = held(); + if (!by) return 0; + const start = now(); + opts.onLog(` ⏸ ${opts.what}: render mode holds the machine (${by}) — waiting.`); + while (by) { + if (opts.signal?.aborted) return null; + await opts.sleep(opts.pollMs ?? RENDER_HOLD_POLL_MS, opts.signal); + if (opts.signal?.aborted) return null; + by = held(); + } + const waited = now() - start; + opts.onLog(` ▶ ${opts.what}: render mode ended — waited ${Math.round(waited / 1000)}s.`); + return waited; +} diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts @@ -4,7 +4,7 @@ type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>; type Render = Record<string, unknown> | null | undefined; -export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic"; +export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic" | "tallWindows"; export const LOOK_KEYS: readonly LookKey[]; export const BAND_MAX: number; export const TRANSITION_MAX: number; diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs @@ -26,7 +26,7 @@ const q = (v) => JSON.stringify(v); const round2 = (n) => Number(Number(n).toFixed(2)); /** The render keys the Look panel writes, in its order. */ -export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic"]); +export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows"]); /** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */ export const BAND_MAX = 240; @@ -461,6 +461,13 @@ export function applyLookPatch(manifest, patch) { } else if (v === "basic") render.mode = "basic"; else errors.push(`render.mode must be "deck" (the default) or "basic" (the footage alone, no chrome)`); break; + case "tallWindows": + // OFF is the default, written as no key: the project's opt-in to clip + // windows above 720 (umtool report-to-video/sources.mjs tallWindowCap). + if (v === true) render.tallWindows = true; + else if (v === false) delete render.tallWindows; + else errors.push("render.tallWindows must be true (windows up to render.maxHeightSource) or false (720, the default)"); + break; case "format": // "landscape" is the default: written as no key at all. if (v === "landscape") delete render.format; diff --git a/common/lib/report/videoAssistOps.test.ts b/common/lib/report/videoAssistOps.test.ts @@ -26,7 +26,7 @@ test("the look's rules: one patch function — keys refused, null removes, qr on assert.deepEqual(bad.errors, validateTransitionStyle({ render: { slide: { blur: 9 } } })); assert.deepEqual(applyLookPatch(m, { loudness: { target: -40 } }).errors, validateLook({ render: { loudness: { target: -40 } } })); assert.deepEqual(lookErrors(m), []); - assert.equal(LOOK_KEYS.length, 15); + assert.equal(LOOK_KEYS.length, 16); }); test("render.mode and render.basic: deck is the default (no key), basic the footage alone; the fades checked", () => { diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts @@ -194,6 +194,33 @@ export async function restoreSavedVideoProvenance( }); } +// RECORD THE ACTIVE COPY'S PROBED HEIGHT (`probed.height`), when the pointer +// records none (no `format.height`, no `probed.height`): a pointer is then +// probed once, not on every tall clip ask (lib/clipWindowTier-server.ts). +// Rewritten from the RAW JSON under its file lock, every other key kept; +// nothing is written when a height is already there or the pointer names +// another file than the one probed. False when nothing was written. +export async function recordSavedVideoProbedHeight( + videoDir: string, + file: string, + height: number, +): Promise<boolean> { + if (!Number.isInteger(height) || height <= 0) return false; + const pointerFile = savedVideoPointerPath(videoDir); + return withJsonFileLock(pointerFile, async () => { + const read = await readJsonFile(pointerFile); + if (!read.ok || !read.value || typeof read.value !== "object") return false; + const raw = { ...(read.value as Record<string, unknown>) }; + if (raw.file !== file) return false; + const fmt = raw.format as { height?: unknown } | undefined; + const probed = (raw.probed && typeof raw.probed === "object" ? raw.probed : {}) as Record<string, unknown>; + if (typeof fmt?.height === "number" || typeof probed.height === "number") return false; + raw.probed = { ...probed, height }; + await writeJsonAtomic(pointerFile, raw); + return true; + }); +} + // Best-effort removal of a now-empty store dir (and its empty <slug> parent). async function pruneEmptyStoreDirs(storeDir: string): Promise<void> { await rm(storeDir, { recursive: false, force: true }).catch(() => {}); diff --git a/common/lib/savedVideoWindow-server.test.ts b/common/lib/savedVideoWindow-server.test.ts @@ -12,10 +12,12 @@ import { execFileSync } from "node:child_process"; import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { cutSavedVideoWindow, savedWindowSource } from "./savedVideoWindow-server"; +import { cutPlainFromTieredWindow, cutSavedVideoWindow, savedWindowSource } from "./savedVideoWindow-server"; +import { evidenceCutArgs, fittedHeight } from "./evidenceClip-server"; import { findContainingClipWindow, listClipWindows } from "./clipWindow-server"; import { stat } from "node:fs/promises"; import { probeMedia } from "./evidenceClip-server"; +import { recordSavedVideoProbedHeight, loadSavedVideo } from "./savedVideo-server"; import { SAVED_VIDEOS_MARKER_FILENAME } from "./savedVideoStore"; const SLUG = "demo-channel"; @@ -279,15 +281,15 @@ test("a tall cut lands beside the plain window as <from>-<to>.h1080.mp4, its hei 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); + // A plain cut records no height, as before the tier (E). + assert.equal(plain.height, undefined); + assert.equal(plain.provenance?.height, undefined); const before = await stat(plain.path); const bytesBefore = await readFile(plain.path); const logs: string[] = []; const tall = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 2, to: 5, - provenance: { requestedBy: "umtool" }, maxHeight: 1080, onLog: (l) => logs.push(l), + provenance: { requestedBy: "umtool" }, tier: 1080, onLog: (l) => logs.push(l), }); assert.equal(tall.file, "2.00-5.00.h1080.mp4"); assert.equal(tall.tier, 1080); @@ -304,6 +306,60 @@ test("a tall cut lands beside the plain window as <from>-<to>.h1080.mp4, its hei 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]], + [["2.00-5.00.mp4", null, null], ["2.00-5.00.h1080.mp4", 1080, 90]], ); }); + +// D: a plain window cut LOCALLY from a tiered one — the evidence box, its +// provenance naming the file it came from; the tiered file untouched. +test("a plain window is cut from a tiered one: 1280x720 box, derivedFrom named, the tiered file untouched", async () => { + const c = await corpus(PICTURE); + const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 7 }); + if (src.kind !== "covers") return assert.fail(src.kind); + const tiered = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 1, to: 7, provenance: { requestedBy: "umtool" }, tier: 1080 }); + const before = await stat(tiered.path); + const logs: string[] = []; + const plain = await cutPlainFromTieredWindow({ + paths: c.paths, videoDir: c.videoDir, tiered, from: 2, to: 5, provenance: { requestedBy: "reports", clipId: "r#1" }, onLog: (l) => logs.push(l), + }); + assert.equal(plain.file, "2.00-5.00.mp4"); + assert.equal(plain.provenance?.source, "clip-window"); + assert.equal(plain.provenance?.derivedFrom, "1.00-7.00.h1080.mp4"); + assert.equal(plain.provenance?.height, undefined); + assert.match(logs.join(""), /from clips\/1\.00-7\.00\.h1080\.mp4 into clips\/2\.00-5\.00\.mp4/); + const p = await probeMedia(plain.path, "ffprobe"); + assert.ok(p && p.durationSec !== null && Math.abs(p.durationSec - 3) < 0.25, String(p?.durationSec)); + assert.equal((await stat(tiered.path)).mtimeMs, before.mtimeMs); + assert.equal((await findContainingClipWindow(c.videoDir, 2, 5))?.file, "2.00-5.00.mp4"); +}); + +// F: the recorded height is ffmpeg's, not an approximation — every size here +// is cut by ffmpeg through the very filter and probed. +test("fittedHeight is what ffmpeg's scale filter writes (1366x768 in the 720 box is 720)", async () => { + const dir = path.join(ROOT, "fit"); + await mkdir(dir, { recursive: true }); + const sizes: [number, number][] = [[1366, 768], [1440, 1080], [1080, 1920], [640, 360], [1920, 1080], [1280, 1024], [854, 480]]; + assert.equal(fittedHeight(1366, 768), 720); + for (const [w, h] of sizes) { + const src = path.join(dir, `${w}x${h}.mp4`); + ff(["-f", "lavfi", "-i", `testsrc=size=${w}x${h}:rate=5:duration=0.4`, "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", src]); + for (const box of [720, 1080]) { + const out = path.join(dir, `${w}x${h}-${box}.mp4`); + execFileSync("ffmpeg", evidenceCutArgs(src, 0, 0.3, "video", out, box).map(String)); + const probed = await probeMedia(out, "ffprobe"); + assert.equal(fittedHeight(w, h, box), probed?.height, `${w}x${h} in the ${box} box`); + } + } +}); + +// I: a pointer with no height takes the one a tall ask probed — once. +test("recordSavedVideoProbedHeight writes probed.height once, only for the file it probed, never over a recorded one", async () => { + const c = await corpus(PICTURE); + assert.equal(await recordSavedVideoProbedHeight(c.videoDir, "other.mp4", 90), false); + assert.equal(await recordSavedVideoProbedHeight(c.videoDir, "source-media.mp4", 90), true); + assert.equal((await loadSavedVideo(c.videoDir))?.probed?.height, 90); + assert.equal(await recordSavedVideoProbedHeight(c.videoDir, "source-media.mp4", 1080), false); + assert.equal((await loadSavedVideo(c.videoDir))?.probed?.height, 90); + const raw = JSON.parse(await readFile(path.join(c.videoDir, "saved-video.json"), "utf8")); + assert.equal(raw.origin.kind, "local-archive", "every other key kept"); +}); diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts @@ -38,7 +38,7 @@ import { execa } from "execa"; import { WIN_EPS, clipWindowFile, - windowTierOf, + isWindowTier, type ClipProvenance, } from "./clipWindow"; import { @@ -172,16 +172,16 @@ 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; + // THE HEIGHT TIER (lib/clipWindow.ts windowTierOf, already snapped and held + // to the ceiling by the caller): the cut is fitted inside that height's 16:9 + // box and written beside the plain window as `<from>-<to>.h<tier>.mp4`. + // Absent: the plain window in the 1280×720 box, as always. + tier?: number; onLog?: (line: string) => void; signal?: AbortSignal; }): Promise<ClipWindow> { const { from, to, source } = opts; - const tier = windowTierOf(opts.maxHeight); + const tier = isWindowTier(opts.tier) ? opts.tier : undefined; const box = tier ?? EVIDENCE_MAX_HEIGHT; const dest = clipWindowPath(opts.videoDir, from, to, tier); await mkdir(path.dirname(dest), { recursive: true }); @@ -208,9 +208,10 @@ 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; + // A TIERED cut records the height the box makes of the container's + // picture (the filter's own arithmetic, evidenceClip-server fittedHeight); + // a plain cut records none, as before the tier. + const height = tier !== undefined && kind === "video" ? fittedHeight(source.probe.width, source.probe.height, box) : null; const provenance: ClipProvenance = { requestedBy: opts.provenance.requestedBy, ...(opts.provenance.manifest ? { manifest: opts.provenance.manifest } : {}), @@ -260,3 +261,70 @@ export async function cutSavedVideoWindow(opts: { await rm(tmp, { force: true }).catch(() => {}); } } + +// A PLAIN WINDOW CUT FROM A TALLER ONE (operator ruling, 13 Nov): a plain ask +// (no height, or 720 and under) that misses, for a span a tiered window of the +// same video holds (`<from>-<to>.h<tier>.mp4`, the height tier), is cut here +// from that file into the plain `<from>-<to>.mp4` — the evidence filter, the +// 1280×720 box — instead of a fetch. Nothing on disk changes but the new +// window: the tiered file is read, never touched. Its provenance names the +// file it came from (`source: "clip-window"`, `derivedFrom`) and carries the +// tiered window's clock, shifted to this span, so the clock retirement treats +// it as the window it was cut from. A failed cut throws; the caller goes on to +// the network as before. +export async function cutPlainFromTieredWindow(opts: { + paths: Pick<Paths, "ffmpegBin">; + videoDir: string; + tiered: ClipWindow; + from: number; + to: number; + provenance: SavedWindowProvenance; + onLog?: (line: string) => void; + signal?: AbortSignal; +}): Promise<ClipWindow> { + const { from, to, tiered } = opts; + const dest = clipWindowPath(opts.videoDir, from, to); + await mkdir(path.dirname(dest), { recursive: true }); + const tmp = tmpPathFor(dest); + const a = Math.max(0, from - tiered.from); + const b = Math.max(a, to - tiered.from); + try { + const r = await execa(opts.paths.ffmpegBin, evidenceCutArgs(tiered.path, a, b, "video", tmp), { + reject: false, + timeout: CUT_TIMEOUT_MS, + ...(opts.signal ? { cancelSignal: opts.signal } : {}), + }); + if (r.exitCode !== 0) { + const err = String(r.stderr ?? "").trim().split("\n").slice(-3).join(" | "); + throw new SavedWindowCutError( + `ffmpeg failed cutting ${from.toFixed(2)}–${to.toFixed(2)} from clips/${tiered.file}` + + `${err ? `: ${err}` : ` (exit ${r.exitCode ?? "?"})`}`, + ); + } + const bytes = (await stat(tmp)).size; + await rename(tmp, dest); + const now = new Date().toISOString(); + const c = tiered.provenance?.clock; + const provenance: ClipProvenance = { + requestedBy: opts.provenance.requestedBy, + ...(opts.provenance.manifest ? { manifest: opts.provenance.manifest } : {}), + ...(opts.provenance.clipId ? { clipId: opts.provenance.clipId } : {}), + ...(opts.provenance.reason ? { reason: opts.provenance.reason } : {}), + requestedAt: opts.provenance.requestedAt ?? now, + ...(typeof opts.provenance.pad === "number" ? { pad: opts.provenance.pad } : {}), + bytes, + fetchedAt: now, + source: "clip-window", + derivedFrom: tiered.file, + ...(c ? { clock: { ...c, from: c.from + (from - tiered.from), to: c.from + (to - tiered.from) } } : {}), + }; + await writeClipProvenance(opts.videoDir, from, to, provenance); + opts.onLog?.( + `Cut ${from.toFixed(2)}–${to.toFixed(2)} from clips/${tiered.file} into clips/${clipWindowFile(from, to)} ` + + `(${bytes} bytes, the 1280×720 box); nothing fetched.\n`, + ); + return { file: clipWindowFile(from, to), path: dest, from, to, bytes, provenance }; + } finally { + await rm(tmp, { force: true }).catch(() => {}); + } +} diff --git a/common/ytdlp/fetchWindowManaged.test.ts b/common/ytdlp/fetchWindowManaged.test.ts @@ -202,3 +202,13 @@ test("a window fetched with a tier lands as <from>-<to>.h<tier>.mp4 with its sid assert.equal(again.cached, true); assert.equal(path.basename(again.file), "10.00-20.00.h1080.mp4"); }); + +// E: the plain path is as before the tier — no probe after the fetch, no height written. +test("a plain window's sidecar records no height (no probe after a plain fetch)", async () => { + process.env.FAKE_MODE = "progressive"; + const videoDir = await setup("plain-no-height"); + const res = await fetchWindowManaged({ ...opts(videoDir), videoUrl: "https://www.youtube.com/watch?v=v1", paths: { ytdlpBin: BIN, ffprobeBin: "/nonexistent/would-be-probed" } as unknown as Paths }); + assert.equal(path.basename(res.file), "10.00-20.00.mp4"); + const sidecar = JSON.parse(await readFile(path.join(videoDir, "clips", "10.00-20.00.json"), "utf8")); + assert.equal("height" in sidecar, false); +}); diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts @@ -634,9 +634,12 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< opts.onLog(`Audio check: ${probe.verdict}${attempt > 1 ? ` (attempt ${attempt})` : ""}.\n`); } await rename(produced, dest); - // 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); + // A TIERED window's picture height, read once now so no later ask has to + // (the height tier's record). A plain window is not probed, as before. + const height = + tier !== undefined + ? await probeVideoHeight({ ffprobeBin: opts.paths.ffprobeBin, file: dest }).catch(() => null) + : null; const provenance: ClipProvenance = { requestedBy: opts.provenance.requestedBy, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -7,17 +7,21 @@ 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. + - The tier snaps to 1080, 1440 or 2160 (held to the setting), so asks of 900 and 1080 share one file. A Retry + keeps its tier. + - A held window lower than asked, with no taller saved copy, is used as it is and listed under `lower` (fetch-window + and `fetch_clip`: `belowAsked`) with why. It is never fetched again for its height. + - A taller cut from a saved copy waits while render mode holds the machine. + - Heights are recorded for taller windows, and for a 720 window only when a tall ask first needs it. A 720 ask with + no window is cut from a taller one when it exists, never fetched. + - The video page lists the taller windows; `check-windows` checks them. `evict-clips` takes `"tiers": "plain" | + "tiered"`; the age-out and the clock retirement remove both. - Site-driven fetches (`fetch-windows {"siteId"}`, Fetch missing evidence) stay at 720, and a site's evidence clips are cut from the 720 window exactly as before. -- **umtool: 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. +- **umtool: taller clips are opt-in per project: `umtool look <p> tallWindows=true`.** With it on, `umtool fetch` asks + for the project's `render.maxHeightSource` and prints each clip that stays lower, with why; the build and every + tool that checks its sources take the tallest local source up to that height, the same file; `--refetch` re-cuts + only the taller windows. Without it a project fetches and renders exactly as before. - **`persist-videos` can upgrade a saved copy that is lower than asked, and keeps the old one as its proxy.** `"replace": "below-height"` re-fetches a saved video whose height is below what the quality gives: the tallest format its metadata lists for `original`; for `video_720`, 720 or that tallest format, whichever is lower. A copy with no recorded height (an import or an attach) is measured with ffprobe first. The download becomes the active copy; the old one stays beside it, marked `"keptAs": "proxy"` once the new one is taller, and the video page, /saved-videos and `get saved-alternates` say it is the lower-quality copy kept on purpose. The dry run's new buckets are `lowerHeight`, `heightUnknown` (not compared: the height could not be read, or `original` with no format heights in the metadata) and `tallerAlternate` (a copy at that height is already kept beside it; it is named, not fetched and not made active). A copy already downloaded at that quality is left alone, and the plan says so, unless its metadata is newer than the copy. "Save these videos" has a select for it in place of the checkbox. `"never"` stays the default, and `"above-height"` works as before. - **umtool: a picture-only post's read can become its screen, and a screen line can be read in your own voice.** `umtool posts screen <p> <item> add --from-read` (the post bench's "From its read") turns the script of a picture-only post into a screen: one line per line of the script, not checked, and with no speaker split out of a line. That screen *is* the post's read, so the thread read no longer reads the same words twice. `posts screen … record <id> <n> --recording <file>` (the bench's per-line Record / Stop / Keep) records one line as the read says it, with masked numbers and redacted words left out of what you read. It is kept as new takes: recorded, cleaned, and converted to the line's speaker's character's stock voice. None of them is picked. A line take is read only when you choose it, with the bench's per-line select or `set <id> take.<n>=<take>`. A choice follows its line when lines move, and is refused when the line's words or speaker changed. `--check-words` (CLI only) transcribes the recording first and refuses it if it says a number, a handle, an anonymous author's name or a redacted term. The lint flags every chosen take that was not heard this way. - **umtool: no preview plays a read the build refuses.** After a screen line is edited, removed, redacted or no longer read, the build refuses the old read. Play, Present (including the public payload), the card page and the post bench's player now refuse it too: they play the item silent and say why, until the read is made again. Present's public payload carries a post's screens the way the card draws them (masked, blurred speakers nameless), never the raw lines. diff --git a/editor/app/api/ops/evict-clips/route.ts b/editor/app/api/ops/evict-clips/route.ts @@ -5,7 +5,8 @@ export const dynamic = "force-dynamic"; // POST { olderThanDays: number, slug?: string, dryRun?: boolean } // | { slug: string, id: string, windows?: ["<from>-<to>", …], -// covering?: [{from, to}, …], olderThanDays?: number, dryRun?: boolean } +// covering?: [{from, to}, …], olderThanDays?: number, +// tiers?: "all" | "plain" | "tiered", dryRun?: boolean } // -> { ok: true, jobId } // // AN ADAPTER, like every route here: one call to the action the /storage button @@ -18,11 +19,13 @@ export const dynamic = "force-dynamic"; // result — see controller/evictClipWindows.ts. TARGETED (`slug` + `id`), the // caller knows which windows are bad: every window of that video, or those // named in `windows` (the cache's `<from>-<to>` stems), or any overlapping a -// `covering` span — the form `umtool fetch --refetch` asks with. +// `covering` span — the form `umtool fetch --refetch` asks with. `tiers` +// narrows to the plain `<from>-<to>` windows or the taller tiered ones (the +// height tier); default "all", both. export async function POST(request: Request) { return ops( request, - ["olderThanDays", "slug", "id", "windows", "covering", "dryRun"], + ["olderThanDays", "slug", "id", "windows", "covering", "tiers", "dryRun"], async (body) => { const raw = body.olderThanDays; const olderThanDays = @@ -37,6 +40,7 @@ export async function POST(request: Request) { ...(body.windows !== undefined ? { windows: body.windows } : {}), ...(body.covering !== undefined ? { covering: body.covering } : {}), ...(olderThanDays !== undefined ? { olderThanDays } : {}), + ...(body.tiers !== undefined ? { tiers: body.tiers } : {}), ...(dryRun ? { dryRun: true } : {}), }), ); diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -95,12 +95,14 @@ import { MAX_CLIP_WINDOW_SECONDS, clampWindowCap, isFetchMaxHeight, + isWindowTier, windowTierOf, type ClipProvenance, } from "yt-dlp-transcript-common/lib/clipWindow"; -import { clipWindowPath, windowHeightOf } from "yt-dlp-transcript-common/lib/clipWindow-server"; +import { clipWindowPath, tieredWindowHolding, windowHeightOf } from "yt-dlp-transcript-common/lib/clipWindow-server"; import { windowMaxHeightOf } from "yt-dlp-transcript-common/lib/clipSettings"; import { tallerFromSaved } from "yt-dlp-transcript-common/lib/clipWindowTier-server"; +import { renderModeHeldNow } from "yt-dlp-transcript-common/lib/renderHold"; import { ffprobeWindowProbe, findInSyncContainingClipWindow, @@ -109,6 +111,7 @@ import { } from "yt-dlp-transcript-common/lib/clipWindowSync-server"; import { desyncedWindowMessage } from "yt-dlp-transcript-common/lib/clipWindowSync"; import { + cutPlainFromTieredWindow, cutSavedVideoWindow, savedWindowSource, } from "yt-dlp-transcript-common/lib/savedVideoWindow-server"; @@ -1589,6 +1592,9 @@ export async function fetchWindowAction(req: { // the default (DEFAULT_CLIP_MAX_HEIGHT). Checked again here for the same // reason the window is: a replayed spec is a file on disk. maxHeight?: number; + // THE TIER a Retry carries in its spec (lib/clipWindow.ts windowTierOf): it + // wins over `maxHeight` and today's clips.windowMaxHeight. + tier?: number; // Hand back the StreamActionResult instead of detaching it. Set by Retry, // which renders the log; the HTTP route leaves it off and polls. stream?: boolean; @@ -1628,8 +1634,13 @@ export async function fetchWindowAction(req: { // 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 ceiling = windowMaxHeightOf(getSettings().clips); + const fixedTier = isWindowTier(req.tier) ? req.tier : undefined; + const { cap: asked, clampedFrom } = + fixedTier !== undefined ? { cap: fixedTier as number | undefined, clampedFrom: undefined as number | undefined } : clampWindowCap(req.maxHeight, ceiling); + const tier = fixedTier ?? windowTierOf(asked, ceiling); + // The network's cap: the tier when tall (asks of 900 and 1080 share a file). + const cap = tier ?? asked; const clamped = clampedFrom !== undefined ? { clampedFrom } : {}; // Before the cache: a local library's recording has no window to hold. const localRefusal = localMediaFetchRefusal(slug, r.config, req.videoId); @@ -1664,16 +1675,23 @@ export async function fetchWindowAction(req: { // copy when that is taller (below); else the window as it is, and why. let taller: Extract<Awaited<ReturnType<typeof tallerFromSaved>>, { kind: "cut" }> | null = null; let belowAsked: { asked: number; why: string } | undefined; + // RENDER MODE (H): a tall cut waits while a render holds the machine. A + // request cannot wait that long, so it is answered with what there is now — + // the lower window, or (with none) the plain cut — and says why. + const renderBy = tier !== undefined ? renderModeHeldNow() : null; + const renderWhy = renderBy + ? `render mode holds the machine (${renderBy}): the ${tier}p cut waits — ask again when it ends` + : null; if (hit && !clocked && tier !== undefined && (hit.height ?? 0) < tier) { const t = await tallerFromSaved({ paths, slug, videoDir, from, to, hitHeight: hit.height ?? null, cap: tier }); - if (t.kind === "cut") taller = t; - else belowAsked = { asked: tier, why: t.why }; + if (t.kind === "cut" && !renderWhy) taller = t; + else belowAsked = { asked: tier, why: t.kind === "cut" ? renderWhy! : 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); + // The window's own height. A tall ask reads its sidecar's record, else + // probes once and records it there (windowHeightOf); any other ask probes + // it and writes nothing, as before the tier. + const height = tier !== undefined ? await windowHeightOf(hit, heightProbe) : await heightProbe(hit.path); return { ok: true, cached: true, @@ -1734,6 +1752,8 @@ export async function fetchWindowAction(req: { return { ok: false, status: 503, error: (e as Error).message }; } let cut; + // Held by render mode, a tall ask with nothing on disk gets the plain cut now. + const cutTier = renderWhy ? undefined : tier; try { cut = await cutSavedVideoWindow({ paths, @@ -1743,7 +1763,7 @@ export async function fetchWindowAction(req: { to, provenance: req.provenance, // A tall ask's cut is its own tier, beside any plain window. - ...(tier !== undefined ? { maxHeight: tier } : {}), + ...(cutTier !== undefined ? { tier: cutTier } : {}), }); } catch (e) { return { ok: false, status: 500, error: (e as Error).message }; @@ -1760,10 +1780,37 @@ export async function fetchWindowAction(req: { bytes: cut.bytes, provenance: cut.provenance, ...(height !== null ? { height } : {}), + ...(renderWhy && tier !== undefined ? { belowAsked: { asked: tier, why: renderWhy } } : {}), ...clamped, }; } + // A PLAIN MISS A TALLER WINDOW HOLDS (D): the 720 window is cut here from + // the tiered file — nothing fetched, nothing on disk changed but the new + // window. A cut that fails goes on to the network as before. + if (tier === undefined) { + const tiered = await tieredWindowHolding(videoDir, from, to); + if (tiered) { + try { + await assertChannelTextReadable(paths, slug); + const cut = await cutPlainFromTieredWindow({ paths, videoDir, tiered, from, to, provenance: req.provenance }); + safeRevalidate([`/channels/${slug}/videos/${videoId}`]); + return { + ok: true, + cached: true, + file: cut.path, + from: cut.from, + to: cut.to, + bytes: cut.bytes, + provenance: cut.provenance, + ...clamped, + }; + } catch { + // The network, as before the tier. + } + } + } + const url = req.webpageUrl?.trim() || (await findVideoSourceUrl(paths, slug, videoId, r.config)); @@ -1974,6 +2021,8 @@ export async function replayFetchWindowAction(req: { provenance: FetchWindowProvenance; queueKey?: string; maxHeight?: number; + // The tier the job was queued at (its spec), not today's settings'. + tier?: number; storedUrl?: StoredUrlMode; }): Promise<StreamActionResult> { const r = await fetchWindowAction({ ...req, stream: true }); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -20,10 +20,12 @@ import { PLAIN_WINDOW_MAX_HEIGHT, clampWindowCap, isFetchMaxHeight, + isWindowTier, windowTierOf, } from "yt-dlp-transcript-common/lib/clipWindow"; import { windowMaxHeightOf } from "yt-dlp-transcript-common/lib/clipSettings"; import { tallerFromSaved } from "yt-dlp-transcript-common/lib/clipWindowTier-server"; +import { tieredWindowHolding } from "yt-dlp-transcript-common/lib/clipWindow-server"; import { probeVideoHeight } from "yt-dlp-transcript-common/ytdlp/ffprobeDuration"; import { ffprobeWindowProbe, @@ -236,8 +238,9 @@ async function planFetchWindows( // 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 ceiling = windowMaxHeightOf(settings.clips); + const { cap, clampedFrom } = clampWindowCap(maxHeight, ceiling); + const tier = windowTierOf(cap, ceiling); const lower: FetchWindowsLower[] = []; const heightProbe = (file: string) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file }); const configs = new Map<string, ChannelConfig | null>(); @@ -359,7 +362,10 @@ async function planFetchWindows( unresolved.push({ item, error: saved.error }); continue; } - if (saved.kind === "covers") { + // ...or, on a plain ask, a taller (tiered) window of the span: the job + // cuts the 720 window from it locally (the height tier, D), on the same + // queue no platform shares. + if (saved.kind === "covers" || (tier === undefined && (await tieredWindowHolding(videoDir, item.from, item.to)))) { const queueKey = resolveQueueKey(SAVED_VIDEO_CLIP_QUEUE, queueOverride); const group = groups.get(queueKey) ?? { platform: SAVED_VIDEO_CLIP_PLATFORM, @@ -503,6 +509,9 @@ export async function fetchWindowsJobAction(req: { manifest?: string; siteId?: string; maxHeight?: number; + // The tier a Retry carries in its spec (lib/clipWindow.ts windowTierOf); + // absent, decided now from maxHeight and clips.windowMaxHeight, and stored. + tier?: number; queueKey: string; storedUrl?: StoredUrlMode; minGapSeconds?: number; @@ -522,6 +531,10 @@ export async function fetchWindowsJobAction(req: { const paths = getPaths(); const requestedAt = new Date().toISOString(); const slugs = [...new Set(req.items.map((i) => i.slug))]; + // THE TIER, fixed at queue time and kept in the spec: a Retry cuts the same + // file whatever the settings say by then. + const ceiling = windowMaxHeightOf(getSettings().clips); + const tier = isWindowTier(req.tier) ? req.tier : windowTierOf(clampWindowCap(req.maxHeight, ceiling).cap, ceiling); return runManagedFunction({ kind: "fetch-windows", queueKey: req.queueKey, @@ -541,6 +554,7 @@ export async function fetchWindowsJobAction(req: { ...(req.manifest ? { manifest: req.manifest } : {}), ...(req.siteId ? { siteId: req.siteId } : {}), ...(req.maxHeight !== undefined ? { maxHeight: req.maxHeight } : {}), + ...(tier !== undefined ? { tier } : {}), // A Retry keeps the mode it was asked with. ...(req.storedUrl && req.storedUrl !== "never" ? { storedUrl: req.storedUrl } : {}), ...(req.minGapSeconds !== undefined ? { minGapSeconds: req.minGapSeconds } : {}), @@ -558,6 +572,7 @@ export async function fetchWindowsJobAction(req: { requestedAt, }, maxHeight: req.maxHeight, + ...(tier !== undefined ? { tier } : {}), storedUrl: req.storedUrl, minGapSeconds: req.minGapSeconds, ...(req.wholeRecording === false ? { wholeRecording: false } : {}), diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -219,6 +219,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { }, queueKey, maxHeight: num(p.maxHeight), + // The tier it was queued at (the height tier), not today's settings'. + ...(num(p.tier) !== undefined ? { tier: num(p.tier) } : {}), ...(isStoredUrlMode(p.storedUrl) ? { storedUrl: p.storedUrl } : {}), ...(num(p.minGapSeconds) !== undefined ? { minGapSeconds: num(p.minGapSeconds) } : {}), }); @@ -240,6 +242,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { manifest: str(p.manifest), siteId: str(p.siteId), maxHeight: num(p.maxHeight), + // The tier it was queued at (the height tier), not today's settings'. + ...(num(p.tier) !== undefined ? { tier: num(p.tier) } : {}), queueKey, // Release 32 R5: a replay keeps the stored-URL mode it was asked with. ...(isStoredUrlMode(p.storedUrl) ? { storedUrl: p.storedUrl } : {}), diff --git a/editor/app/storage/actions.ts b/editor/app/storage/actions.ts @@ -32,7 +32,7 @@ import { channelMediaBusyReason } from "../channels/lib/mediaBusy"; import { enqueueRepointJob } from "./lib/repointJob"; import { enqueueSavedVideosRelocation } from "./lib/savedVideosJob"; import { enqueueEvictClipWindows } from "./lib/evictClipsJob"; -import { parseEvictTargets } from "yt-dlp-transcript-common/controller/evictClipWindows"; +import { EVICT_TIERS, isEvictTiers, parseEvictTargets } from "yt-dlp-transcript-common/controller/evictClipWindows"; import { enqueueCheckClipWindows } from "./lib/checkWindowsJob"; import { savedVideosStoreBusyReason } from "./lib/storeBusy"; import { refreshLocationHealth } from "yt-dlp-transcript-common/controller/storageWatch"; @@ -465,11 +465,16 @@ export async function evictClipWindowsAction(opts: { windows?: unknown; covering?: unknown; olderThanDays?: number; + // "all" (default) | "plain" | "tiered": which windows of a span (the height tier). + tiers?: unknown; dryRun?: boolean; }): Promise<StreamActionResult> { if (opts.id !== undefined && opts.slug === undefined) { return { ok: false, error: "A video is named within a channel: give its slug too." }; } + if (opts.tiers !== undefined && !isEvictTiers(opts.tiers)) { + return { ok: false, error: `"tiers" must be one of ${EVICT_TIERS.join(", ")}` }; + } if ((opts.windows !== undefined || opts.covering !== undefined) && opts.id === undefined) { return { ok: false, @@ -524,6 +529,7 @@ export async function evictClipWindowsAction(opts: { ...(opts.olderThanDays !== undefined ? { olderThanDays: Math.floor(opts.olderThanDays) } : {}), + ...(isEvictTiers(opts.tiers) && opts.tiers !== "all" ? { tiers: opts.tiers } : {}), ...(opts.dryRun ? { dryRun: true } : {}), }); } diff --git a/editor/app/storage/lib/evictClipsJob.ts b/editor/app/storage/lib/evictClipsJob.ts @@ -8,6 +8,7 @@ import { evictClipWindows, evictClipWindowsSummary, type ClipWindowSpan, + type EvictTiers, } from "yt-dlp-transcript-common/controller/evictClipWindows"; import { clipWindowName } from "yt-dlp-transcript-common/lib/clipWindow"; @@ -35,6 +36,8 @@ export async function enqueueEvictClipWindows(opts: { windows?: ClipWindowSpan[]; covering?: ClipWindowSpan[]; olderThanDays?: number; + // "all" (default) | "plain" | "tiered" — controller/evictClipWindows.ts. + tiers?: EvictTiers; dryRun?: boolean; }): Promise<StreamActionResult> { const spans = (l: ClipWindowSpan[]) => l.map((w) => clipWindowName(w.from, w.to)).join(", "); @@ -58,6 +61,7 @@ export async function enqueueEvictClipWindows(opts: { (opts.windows && opts.covering ? " or" : "") + (opts.covering ? ` overlapping ${spans(opts.covering)}` : "") + (!opts.windows && !opts.covering ? " (every one)" : "") + + (opts.tiers === "plain" ? ", the plain windows only" : opts.tiers === "tiered" ? ", the taller (tiered) windows only" : "") + (opts.olderThanDays !== undefined ? `, not touched for ${opts.olderThanDays} day(s)` : "") + @@ -85,6 +89,7 @@ export async function enqueueEvictClipWindows(opts: { ...(opts.windows ? { windows: opts.windows } : {}), ...(opts.covering ? { covering: opts.covering } : {}), ...(opts.olderThanDays !== undefined ? { olderThanDays: opts.olderThanDays } : {}), + ...(opts.tiers && opts.tiers !== "all" ? { tiers: opts.tiers } : {}), ...(opts.dryRun ? { dryRun: true } : {}), onLog, signal, diff --git a/mcp/src/fetchClip.test.ts b/mcp/src/fetchClip.test.ts @@ -324,6 +324,23 @@ test("200 cached: the exact window (within 0.02 s) says so", async () => { assert.ok(!/requested by/.test(r.text)); }); +test("200 cached lower than asked: the editor's belowAsked is said, with its reason", async () => { + const { deps } = editor( + seq({ + status: 200, + body: { + cached: true, file: CLIP_FILE, from: 7, to: 23, bytes: 5, provenance: null, height: 720, + belowAsked: { asked: 1080, why: "no saved copy of the recording to cut a taller one from" }, + }, + }), + ); + const r = renderFetchClip(await fetchClip(windowRequest(), deps), CTX); + assert.match(r.text, /\nlower than asked: 720p for the 1080p asked — no saved copy of the recording to cut a taller one from$/); + // A malformed one is not said. + const { deps: d2 } = editor(seq({ status: 200, body: { cached: true, file: CLIP_FILE, from: 7, to: 23, bytes: 5, belowAsked: { asked: "x" } } })); + assert.ok(!/lower than asked/.test(renderFetchClip(await fetchClip(windowRequest(), d2), CTX).text)); +}); + test("202 → running → done: the poll's file, span and bytes", async () => { const { deps, calls, sleeps } = editor( seq( diff --git a/mcp/src/fetchClip.ts b/mcp/src/fetchClip.ts @@ -315,6 +315,9 @@ export type FetchClipOutcome = // call asked for, so the answer can say when a cached file is taller. height?: number; maxHeight?: number; + // A tall ask answered with a window LOWER than it asked (the editor's + // height tier): the height asked, and why no taller one was cut. + belowAsked?: { asked: number; why: string }; } | { kind: "fetched"; @@ -586,6 +589,7 @@ export async function fetchClip( bytes: num(answer.bytes) ?? 0, requestedBy: prov && typeof prov === "object" ? str(prov.requestedBy) : undefined, ...heightFields(num(answer.height), target.maxHeight), + ...belowAskedOf(answer.belowAsked), }; } if (res.status === 202 && str(answer.jobId)) { @@ -608,6 +612,14 @@ export async function fetchClip( }; } +// The editor's `belowAsked` ({asked, why}), only when it is well formed. +function belowAskedOf(v: unknown): { belowAsked?: { asked: number; why: string } } { + if (!v || typeof v !== "object") return {}; + const asked = num((v as Json).asked); + const why = str((v as Json).why); + return asked !== undefined && why ? { belowAsked: { asked, why } } : {}; +} + // ─── The answer an agent reads ─── const READ_ONLY_NOTE = @@ -699,7 +711,12 @@ export function renderFetchClip( `${fmtSeconds(outcome.reqFrom)}–${fmtSeconds(outcome.reqTo)}: ` + `${fmtSeconds(outcome.from)}–${fmtSeconds(outcome.to)}.`; } - return { text: `${head}\n\n${footer(outcome.mode, outcome, true)}`, isError: false }; + // LOWER THAN ASKED is said too, with the editor's reason. + const below = outcome.belowAsked + ? `\nlower than asked: ${outcome.height !== undefined ? `${outcome.height}p` : "this window"} for the ` + + `${outcome.belowAsked.asked}p asked — ${outcome.belowAsked.why}` + : ""; + return { text: `${head}\n\n${footer(outcome.mode, outcome, true)}${below}`, isError: false }; } case "fetched": { if (!outcome.file) { diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1525,6 +1525,8 @@ export function usage() { ' "windows": ["<from>-<to>", ...] only those named, "covering": [{"from",', ' "to"}, ...] any window overlapping a span (umtool fetch --refetch asks', ' this way); "olderThanDays" is then optional, "dryRun" only lists.', + ' "tiers": "plain" | "tiered" narrows to the <from>-<to> windows or the', + ' taller <from>-<to>.h<height> ones (default "all": both).', "", 'check-windows probes cached clip windows (data/<id>/clips/) for a picture', ' that runs off the sound (a Rumble HLS seek) and sets each desynced one', diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -359,6 +359,24 @@ the render unchanged. The two are not set together: on a migrated cut the series The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets the look's keys (`transition=0.3`, …: [report-video.md](report-video.md#the-look-captions-loudness-shorts-release-36)). +## Taller windows (`render.tallWindows`) + +`render.tallWindows: true` lets a project's clips be fetched and cut taller than 720, up to its +`render.maxHeightSource` (1080 when unset). It is OFF by default, and a project without it renders exactly as before: +no height probe, no `out/clips-raw.heights.json`, no taller window read, no `maxHeight` sent. `maxHeightSource` is +1080 in every scaffold and preset, so it is not the switch. + +With it on, `umtool fetch` asks the editor for that height. The editor keeps the taller window beside the 720 one +(`clips/<from>-<to>.h<tier>.mp4`), cut from the saved copy when that copy is taller, and prints each clip that stays +lower, with why. The build and every tool that checks its sources (quote-check, `--align`, scenes, cut points, the +availability check, quick clip, the chain) read the cap from the manifest, so they all resolve the same file. +`--refetch` evicts and re-cuts only the taller windows; the 720 window, which a site's evidence is cut from, stays. A +take records the knob with the rest of the look. + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| taller windows | — | `umtool look <p> tallWindows=true` (`false` turns it off) | `PUT /api/report/render {patch: {tallWindows}}` | + ## Basic output (the footage alone) `render.mode: "basic"` renders the cut as its footage and nothing else (`report-to-video/basic.mjs`): each clip's diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -3110,20 +3110,24 @@ 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`. +TALLER WINDOWS ARE OPT-IN per project: `umtool look <p> tallWindows=true` ([knobs.md](knobs.md#taller-windows-rendertallwindows)). +Without it nothing here changes: no `maxHeight` in the body, no height probe, no taller window read. With it the +body carries `maxHeight`, the manifest's `render.maxHeightSource`, and the editor keeps a taller window beside the 720 +one (`<from>-<to>.h<tier>.mp4`), cut from the saved copy when that copy is taller, and holds the ask to its +`clips.windowMaxHeight` (1080 by default). A clip that stays lower is printed as a `lower` line, with its height and +why — usually "no saved copy". The build, quote-check, `--align`, scenes, cut points, the availability check, quick +clip and the chain all take the cap from the manifest's render, so they resolve the same file: a raw `out/clips-raw` +file or a 720 corpus window gives way to a taller corpus window or to the saved copy. Neither is deleted. A raw +file's height is probed once and kept in `out/clips-raw.heights.json`. A window on disk that is BAD (cut from a saved video that turned out corrupt) is a cache hit all the same, so a plain fetch keeps it. `umtool fetch <project> --refetch z01,w01` (the clip bench's **Fetch this window again**, a queue step) evicts first: each named clip's fetch span — the very `from`–`to` the body asks for, pad included — goes to the editor's `evict-clips` -as `{slug, id, covering: [{from, to}]}`, which removes every cached window of -that video OVERLAPPING the span (a wider window the dedup would have served it +as `{slug, id, covering: [{from, to}], tiers}`, which removes every cached window of +that video OVERLAPPING the span — on a tall project only the taller (`.h<tier>`) +windows, which are then cut again from the saved copy, the 720 one left for the +sites; on any other only the 720 windows, as before (a wider window the dedup would have served it from included, and its `.desynced.*` twin), and only once that job has ended is the fetch asked. `--refetch-video <slug>/<id>` does the same for every window the project asks of one video. A window another project shares is evicted too: diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -573,8 +573,7 @@ export const clipWindowDirs = async ( }; // The corpus behind the project's channels tree, for a video its tree has no window of (channelsLayersFor). const behind = channelsDir && channelsFallbackOn(m) && path.resolve(GLOBAL_CHANNELS_DIR()) !== path.resolve(root) ? GLOBAL_CHANNELS_DIR() : null; - const 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) => + const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe, fallbackChannelsDir: behind, render: m?.render ?? null })).filter((w) => readable(w.path), ); if (windows.length) out.push({ video: e.video, windows }); diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -196,7 +196,7 @@ const STEPS = { const rawDir = path.join(ctx.project, "out", "clips-raw"); const missing = []; for (const item of body.items) { - const hit = await resolveLocalSource({ video: item.id, slug: item.slug, from: item.from, to: item.to }, { rawDir, channelsDir: ctx.paths.channelsDir }).catch(() => null); + const hit = await resolveLocalSource({ video: item.id, slug: item.slug, from: item.from, to: item.to }, { rawDir, channelsDir: ctx.paths.channelsDir, render: manifest.render ?? null }).catch(() => null); if (!hit) missing.push(item); } if (missing.length === 0) return `the cut's ${body.items.length} window(s) are on disk already`; diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -116,7 +116,7 @@ async function cutContext(project, take) { // sources are the corpus's windows or the project's cache); the project's // raw cache is looked in after it, as the bench does. const locals = [...new Set([outRoot, path.join(/* turbopackIgnore: true */ project.dir, "out")])].map((root) => - localSources({ rawDir: path.join(/* turbopackIgnore: true */ root, "clips-raw"), channelsDir, channelSlug: provenance.channelSlug ?? null }), + localSources({ rawDir: path.join(/* turbopackIgnore: true */ root, "clips-raw"), channelsDir, channelSlug: provenance.channelSlug ?? null, render }), ); const localMedia = createLocalMedia({ baseDir: project.dir, allowAbsolute: render.allowAbsoluteSrc === true }); // Where a gap-joined clip's pieces are joined for measuring (piecedClipSource): beside the other diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs @@ -29,6 +29,7 @@ import { readFetchRuns, recordFetchRun, refetchEvictions, + refetchTiers, summarizeAnswer, } from "./fetchWindows.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; @@ -179,7 +180,7 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con if (!plan.ok) throw new CliError(plan.error); refetch = []; for (const req of plan.requests) { - const { jobId } = await postEvictClips(cfg, req, { dryRun }); + const { jobId } = await postEvictClips(cfg, { ...req, tiers: refetchTiers(body) }, { dryRun }); let status = "unknown"; for (;;) { status = String((await jobStatus(cfg, jobId))?.job?.status ?? "unknown"); diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs @@ -39,6 +39,7 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { LEFT_OUT_VERDICTS, clipMomentKey, readMontageRulings } from "umtool-report-to-video/montage-rulings"; import { fetchPieces, renderGaps } from "umtool-report-to-video/gaps"; +import { tallWindowCap } from "umtool-report-to-video/sources"; import { agentToken } from "../annotations/agentAuth.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; @@ -110,10 +111,12 @@ 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); + // A TALL PROJECT (`render.tallWindows`, sources.mjs tallWindowCap) asks for + // its render.maxHeightSource: the editor holds it to its + // clips.windowMaxHeight, keeps a taller window beside a 720 one and says + // which clips stayed lower and why (`lower` in its answer). Any other + // project sends no height, as before. + const maxHeight = tallWindowCap(manifest?.render); return { body: { requestedBy: `umtool:${project}`, @@ -127,16 +130,7 @@ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = nu }; } -/** - * 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+$)/, ""); @@ -293,15 +287,27 @@ export function postFetchWindows(cfg, body, { dryRun = false } = {}) { } /** - * POST /api/ops/evict-clips, targeted: `{slug, id, covering}` -> `{jobId}`. + * POST /api/ops/evict-clips, targeted: `{slug, id, covering, tiers}` -> `{jobId}`. + * `tiers` is "plain" or "tiered" (refetchTiers): a refetch removes only the + * windows its project reads, never the other kind. * @param {{ url: string, token: string, fetch?: typeof fetch }} cfg - * @param {{ slug: string, id: string, covering: { from: number, to: number }[] }} req + * @param {{ slug: string, id: string, covering: { from: number, to: number }[], tiers?: "plain" | "tiered" }} req * @param {{ dryRun?: boolean }} [opts] */ -export function postEvictClips(cfg, { slug, id, covering }, { dryRun = false } = {}) { - return ask(cfg, "/api/ops/evict-clips", { method: "POST", body: { slug, id, covering, ...(dryRun ? { dryRun: true } : {}) } }); +export function postEvictClips(cfg, { slug, id, covering, tiers }, { dryRun = false } = {}) { + return ask(cfg, "/api/ops/evict-clips", { method: "POST", body: { slug, id, covering, ...(tiers ? { tiers } : {}), ...(dryRun ? { dryRun: true } : {}) } }); } +/** + * Which windows a refetch evicts (the height tier): a TALL project's body asks + * a height (`maxHeight`, tallWindowCap) and evicts only the taller tiered + * windows of its spans — the plain 720 window a site's evidence reads stays; + * any other project evicts the plain windows only, as before the tier. Pure. + * @param {{ maxHeight?: number }} body + * @returns {"plain" | "tiered"} + */ +export const refetchTiers = (body) => (body?.maxHeight !== undefined ? "tiered" : "plain"); + // `evicting <slug>/<id>/<name> (…)` / `would evict …` — the line // common/controller/evictClipWindows.ts logs for each window. const EVICT_LINE = /^\s*(?:would evict|evicting) [^/\s]+\/[^/\s]+\/(\S+) /; diff --git a/umtool/lib/report/fetchWindows.test.mjs b/umtool/lib/report/fetchWindows.test.mjs @@ -245,7 +245,7 @@ test("umtool fetch --refetch: evict-clips {slug, id, covering} first, waited for const run = (args) => fetchCommand(args, { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg, pollMs: 1 }); assert.equal(await run(["synth-oops", "--refetch", "s02", "--dry-run"]), 0); - assert.deepEqual(ed.seen[0], { key: "POST /api/ops/evict-clips", body: { slug: "synth-rumble", id: "v2abc", covering: [{ from: 0, to: 7.5 }], dryRun: true }, auth: "Bearer tok" }); + assert.deepEqual(ed.seen[0], { key: "POST /api/ops/evict-clips", body: { slug: "synth-rumble", id: "v2abc", covering: [{ from: 0, to: 7.5 }], tiers: "plain", dryRun: true }, auth: "Bearer tok" }); assert.equal(ed.seen.at(-1).key, "POST /api/ops/fetch-windows"); assert.equal(ed.seen.at(-1).body.dryRun, true); assert.match(lines.join("\n"), /would evict for s02 \(synth-rumble\/v2abc, job E0\): 0\.00-9\.00\.mp4/); @@ -302,13 +302,14 @@ test("a gap-joined clip is fetched per kept piece, each padded at its own edges // 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 () => { +test("a tall project's body carries its maxHeightSource as maxHeight; the answer's lower clips are summarized and printed", async () => { const { summaryLines } = await import("./fetchCli.mjs"); - const tall = { ...MANIFEST, render: { ...MANIFEST.render, maxHeightSource: 1080 } }; + const tall = { ...MANIFEST, render: { ...MANIFEST.render, tallWindows: true, maxHeightSource: 1080 } }; const { body } = fetchWindowsBody(tall, { manifestPath: "/x/m.json", project: "p" }); assert.equal(body.maxHeight, 1080); - 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); + // Without the knob, no height, whatever maxHeightSource says. + assert.equal(fetchWindowsBody({ ...MANIFEST, render: { maxHeightSource: 1080 } }, { manifestPath: "/x/m.json", project: "p" }).body.maxHeight, undefined); + assert.equal(fetchWindowsBody({ ...MANIFEST, render: { tallWindows: true, maxHeightSource: 99 } }, { manifestPath: "/x/m.json", project: "p" }).body.maxHeight, undefined); const s = summarizeAnswer({ cached: [{ slug: "synth-yt", id: "yt1", clipId: "s01" }], lower: [{ item: { slug: "synth-yt", id: "yt1", clipId: "s01" }, file: "55.81-63.87.mp4", height: 720, asked: 1080, why: "no saved copy of the recording to cut a taller one from" }], diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs @@ -46,7 +46,7 @@ const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NA test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => { const p = await project({ transition: 0.4, crf: 21 }); try { - assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic"]); + assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows"]); const token = await manifestToken(p.dir); const r = await updateRender(p.dir, { headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", diff --git a/umtool/lib/report/quickClip.mjs b/umtool/lib/report/quickClip.mjs @@ -234,7 +234,9 @@ export async function quickClip(ask, { root = REPORTS_ROOT, channelsDir = CHANNE // ONE CLOCK PER RECORDING: the build's lookup (resolveLocalSource) maps the span through a saved recording's // time map (clock.json, common recordingClock.mjs) -- its windowStart is the CUE second the file's 0 plays -- // so the span is asked on the file's clock and the words come back onto the cues', as quote-check does. - const src = await (deps.resolve ?? resolveLocalSource)({ video, slug: spec.channel, from, to }, { rawDir: path.join(project.dir, "out", "clips-raw"), channelsDir }); + // The project's render, as the take's build will read it (its tallWindowCap). + const render = await readFile(path.join(project.dir, "video.manifest.json"), "utf8").then((t) => JSON.parse(t)?.render ?? null, () => null); + const src = await (deps.resolve ?? resolveLocalSource)({ video, slug: spec.channel, from, to }, { rawDir: path.join(project.dir, "out", "clips-raw"), channelsDir, render }); if (!src) throw new Error(`--snap words: no window on disk holds ${from.toFixed(2)}–${to.toFixed(2)} (the fetch landed a narrower one?)`); if (src.clock && !src.clock.certain) say(`--snap words: ${path.basename(src.path)}'s clock is NOT certain over this span (a step in its time map) -- check the words land (umtool quote-check)`); const { mkdir } = await import("node:fs/promises"); diff --git a/umtool/lib/report/quoteCheck.mjs b/umtool/lib/report/quoteCheck.mjs @@ -191,7 +191,8 @@ export async function planQuoteCheck(dir, manifest, { channelsDirs, rawDir = pat } const src = await resolveLocalSource( { video: e.video, slug, from: cut.from, to: cut.to }, - { rawDir, channelsDir: channelsDirs[0], fallbackChannelsDir: channelsDirs[1] ?? null, ...(probe ? { probe } : {}) }, + // The manifest's render: the build's own cap (sources.mjs tallWindowCap), so this vouches for the file it cuts. + { rawDir, channelsDir: channelsDirs[0], fallbackChannelsDir: channelsDirs[1] ?? null, render: manifest?.render ?? null, ...(probe ? { probe } : {}) }, ); if (!src) { rows.push({ ...base, skip: "no-window" }); diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs @@ -139,7 +139,7 @@ export async function recordingAudio({ channelsDir, channel, video, videoDir, du const p = path.join(videoDir, name); if (await isFile(p)) return { path: p, kind: "audio", clock: 0 }; } - const hit = await resolveLocalSource({ video, slug: channel, from: 0, to: Math.max(1, duration - 1) }, { channelsDir, audio: true, probe: ffprobeSource }).catch(() => null); + const hit = await resolveLocalSource({ video, slug: channel, from: 0, to: Math.max(1, duration - 1) }, { channelsDir, audio: true, probe: ffprobeSource, render: null }).catch(() => null); if (!hit) return null; return { path: hit.path, kind: hit.kind, clock: (hit.windowStart ?? 0) + (await clockOffset(hit.path)) }; } diff --git a/umtool/lib/report/scenesCli.mjs b/umtool/lib/report/scenesCli.mjs @@ -139,12 +139,13 @@ export async function scanClip(project, clipId, opts = {}) { const slug = channelFor(manifest, entry); const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); const rawDir = path.join(project.dir, "out", "clips-raw"); - const config = { rawDir, channelsDir, probe: ffprobeSource }; + // The build's lookup, with the manifest's render (its tallWindowCap): one call site. + const lookup = (want) => resolveLocalSource(want, { rawDir, channelsDir, probe: ffprobeSource, render: manifest.render ?? null }); // What the build would fetch, then the extent alone (a window that holds the clip but not its pad). const span = fetchSpan(entry, manifest.render ?? {}); const hit = - (await resolveLocalSource({ video: entry.video, slug, from: span.from, to: span.to }, config)) ?? - (await resolveLocalSource({ video: entry.video, slug, from: entry.start, to: entry.end }, config)); + (await lookup({ video: entry.video, slug, from: span.from, to: span.to })) ?? + (await lookup({ video: entry.video, slug, from: entry.start, to: entry.end })); const clipRow = { id: clipId, channel: slug, @@ -169,7 +170,7 @@ export async function scanClip(project, clipId, opts = {}) { }; if (!hit) { // A clip with gaps is fetched per kept piece (fetchSpans): scan each piece on disk. - const local = { resolve: (e, sp) => resolveLocalSource({ video: e.video, slug, from: sp.from, to: sp.to }, config) }; + const local = { resolve: (e, sp) => lookup({ video: e.video, slug, from: sp.from, to: sp.to }) }; const had = await localPieces(entry, manifest.render ?? {}, local); if (had) { const wantFrom = opts.from ?? entry.start - pad; diff --git a/umtool/lib/report/tallWindows.test.mjs b/umtool/lib/report/tallWindows.test.mjs @@ -0,0 +1,143 @@ +// render.tallWindows (the height tier's opt-in, report-to-video/sources.mjs +// tallWindowCap): the build and every tool that vouches for its sources +// resolve ONE file; without the knob a project resolves exactly as before — +// no probe, no height index, no tiered window read — even beside a taller +// saved copy and a tiered window; and every call site states its render. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { planQuoteCheck } from "./quoteCheck.mjs"; +import { localSources } from "umtool-report-to-video/build-video"; +import { rawWindowName, resolveLocalSource, tallWindowCap } from "umtool-report-to-video/sources"; +import { fetchWindowsBody, refetchTiers } from "./fetchWindows.mjs"; + +const SLUG = "demo"; +const VIDEO = "vid1"; +const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); + +async function project() { + const dir = await mkdtemp(path.join(os.tmpdir(), "tall-windows-")); + const rawDir = path.join(dir, "out", "clips-raw"); + const channelsDir = path.join(dir, "channels"); + const videoDir = path.join(channelsDir, SLUG, "data", VIDEO); + const clips = path.join(videoDir, "clips"); + const store = path.join(dir, "store"); + for (const d of [rawDir, clips, store]) await mkdir(d, { recursive: true }); + // A 720 raw file, a 720 corpus window, a 1080 tiered window elsewhere, and a 1080 saved copy. + await writeFile(path.join(rawDir, rawWindowName(VIDEO, 0, 60)), "raw"); + await writeFile(path.join(clips, "0.00-60.00.mp4"), "plain"); + await writeFile(path.join(clips, "0.00-60.00.json"), JSON.stringify({ requestedBy: "reports", height: 720 })); + await writeFile(path.join(clips, "5.00-55.00.h1080.mp4"), "tiered"); + await writeFile(path.join(clips, "5.00-55.00.h1080.json"), JSON.stringify({ requestedBy: "umtool", height: 1080 })); + await writeFile(path.join(store, "source-media.mp4"), "whole"); + await writeFile( + path.join(videoDir, "saved-video.json"), + JSON.stringify({ storedAt: "", dir: store, file: "source-media.mp4", bytes: 5, format: { preset: "original", height: 1080 } }), + ); + return { dir, rawDir, channelsDir }; +} + +const manifestOf = (render) => ({ + render, + provenance: { channelSlug: SLUG }, + timeline: [{ type: "clip", id: "c1", video: VIDEO, start: 10, end: 20, quote: "hello there" }], +}); + +function counting() { + const calls = []; + return { calls, probe: async (f) => (calls.push(f), { duration: 600, height: 720 }) }; +} + +test("tallWindowCap: only render.tallWindows turns it on; maxHeightSource alone is no switch", () => { + assert.equal(tallWindowCap({ maxHeightSource: 1080 }), undefined); + assert.equal(tallWindowCap({ tallWindows: true, maxHeightSource: 1080 }), 1080); + assert.equal(tallWindowCap({ tallWindows: true }), 1080); + assert.equal(tallWindowCap({ tallWindows: true, maxHeightSource: 720 }), undefined); + assert.equal(tallWindowCap(null), undefined); +}); + +test("with the knob on, quote-check vouches for the very file the build cuts (the taller saved copy)", async () => { + const t = await project(); + try { + const manifest = manifestOf({ tallWindows: true, maxHeightSource: 1080 }); + const { probe } = counting(); + const [row] = await planQuoteCheck(t.dir, manifest, { channelsDirs: [t.channelsDir], rawDir: t.rawDir, probe, pad: 0 }); + const local = localSources({ rawDir: t.rawDir, channelsDir: t.channelsDir, channelSlug: SLUG, probe, render: manifest.render }); + const built = await local.resolve(manifest.timeline[0], row.cut); + assert.equal(row.source.path, built.path); + assert.notEqual(built.kind, "raw-cache", "the 720 raw file gave way"); + assert.equal(built.height, 1080); + } finally { + await rm(t.dir, { recursive: true, force: true }); + } +}); + +test("without the knob a project resolves as before: the raw file, no probe, no height index, no tier read", async () => { + const t = await project(); + try { + const manifest = manifestOf({ maxHeightSource: 1080 }); + const { calls, probe } = counting(); + const want = { video: VIDEO, slug: SLUG, from: 10, to: 20 }; + const plain = await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, render: manifest.render }); + // What main resolves: the raw file, exactly this shape, nothing else. + assert.deepEqual(plain, { + kind: "raw-cache", + path: path.join(t.rawDir, rawWindowName(VIDEO, 0, 60)), + name: rawWindowName(VIDEO, 0, 60), + windowStart: 0, + windowEnd: 60, + }); + const [row] = await planQuoteCheck(t.dir, manifest, { channelsDirs: [t.channelsDir], rawDir: t.rawDir, probe, pad: 0 }); + assert.equal(row.source.path, plain.path); + // The corpus alone: the plain window, never the tiered one. + const corpus = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe, render: manifest.render }); + assert.equal(corpus.name, "0.00-60.00.mp4"); + assert.equal(corpus.height, undefined); + assert.deepEqual(calls, [], "nothing probed"); + assert.ok(!(await readdir(path.join(t.dir, "out"))).includes("clips-raw.heights.json")); + } finally { + await rm(t.dir, { recursive: true, force: true }); + } +}); + +test("umtool fetch sends a window height only with the knob; a refetch evicts its own tier only", () => { + const off = fetchWindowsBody(manifestOf({ maxHeightSource: 1080 }), { manifestPath: "/x/m.json", project: "p" }).body; + assert.equal("maxHeight" in off, false); + assert.equal(refetchTiers(off), "plain"); + const on = fetchWindowsBody(manifestOf({ tallWindows: true, maxHeightSource: 1080 }), { manifestPath: "/x/m.json", project: "p" }).body; + assert.equal(on.maxHeight, 1080); + assert.equal(refetchTiers(on), "tiered"); +}); + +// SO CALLERS CANNOT DRIFT: every lookup outside the tests states the render it +// resolves for (sources.mjs tallWindowCap reads it) -- `render: null` for one +// that is not a cut's (a reference recording's sound). +test("every resolveLocalSource / localSources / corpusWindowsOf call site states a render", async () => { + const { execFileSync } = await import("node:child_process"); + const files = execFileSync("git", ["ls-files", "umtool/*.mjs", "umtool/*.ts", "umtool/**/*.mjs", "umtool/**/*.ts"], { cwd: REPO, encoding: "utf8" }) + .split("\n") + .filter((f) => f && !/\.test\.|\/e2e\/|\.d\.ts$/.test(f)); + const missing = []; + for (const f of files) { + const text = await readFile(path.join(REPO, f), "utf8"); + const re = /(?:resolveLocalSource|localSources|corpusWindowsOf)\s*\)?\s*\(/g; + for (let m = re.exec(text); m; m = re.exec(text)) { + const before = text.slice(Math.max(0, m.index - 30), m.index); + if (/function\s+$|export\s+$|\.\s*$/.test(before) || /import|typeof/.test(before)) continue; + // The call's text: to its closing parenthesis (depth-counted). + let depth = 0; + let i = m.index + m[0].length - 1; + for (; i < text.length; i++) { + if (text[i] === "(") depth++; + else if (text[i] === ")" && --depth === 0) break; + } + const call = text.slice(m.index, i + 1); + if (!/\brender\b/.test(call)) missing.push(`${f}:${text.slice(0, m.index).split("\n").length}`); + } + } + assert.deepEqual(missing, []); +}); diff --git a/umtool/lib/report/voiceMatch.mjs b/umtool/lib/report/voiceMatch.mjs @@ -164,12 +164,12 @@ export async function planClips(dir, manifest, { channelsDir, rawDir = path.join seen.add(key); const s = await clipSpan(entry, slug, transcripts, { span, pad }); const base = { key, ...(id ? { id } : {}), channel: slug, video: entry.video, from: s.from, to: s.to, via: s.via }; - let hit = await resolveLocalSource({ video: entry.video, slug, from: s.from, to: s.to }, { rawDir, channelsDir, audio: true, probe: ffprobeSource }); + let hit = await resolveLocalSource({ video: entry.video, slug, from: s.from, to: s.to }, { rawDir, channelsDir, audio: true, probe: ffprobeSource, render: manifest?.render ?? null }); let from = s.from; let to = s.to; if (!hit && num(entry.cutStart) && num(entry.cutEnd)) { // A window that holds the cut but not its pad: the cut alone. - hit = await resolveLocalSource({ video: entry.video, slug, from: entry.cutStart, to: entry.cutEnd }, { rawDir, channelsDir, audio: true, probe: ffprobeSource }); + hit = await resolveLocalSource({ video: entry.video, slug, from: entry.cutStart, to: entry.cutEnd }, { rawDir, channelsDir, audio: true, probe: ffprobeSource, render: manifest?.render ?? null }); if (hit) { from = Math.max(entry.cutStart, hit.windowStart); to = Math.min(entry.cutEnd, hit.windowEnd); @@ -241,7 +241,8 @@ export async function referenceRecordings({ channelsDir, channels, videos = [], const from = Math.max(0, r.first); const hit = await resolveLocalSource( { video: r.videoId, slug: r.slug, from, to: from + REFERENCE_SECONDS }, - { channelsDir, audio: true, probe: ffprobeSource }, + // A reference recording, not a cut's clip: no render. + { channelsDir, audio: true, probe: ffprobeSource, render: null }, ); if (!hit) { skipped.push({ channel: r.slug, video: r.videoId, why: "no local source covers it" }); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -1084,7 +1084,7 @@ export function virtualEntry(entry, clock) { * so `--no-network`'s up-front pass and the clip's own fetch probe a saved * container once between them. */ -export function localSources({ rawDir, channelsDir, channelSlug = null, probe, fallbackChannelsDir = null, log = undefined, maxHeight = undefined } = {}) { +export function localSources({ rawDir, channelsDir, channelSlug = null, probe, fallbackChannelsDir = null, log = undefined, render = null } = {}) { const memo = new Map(); const slugOf = (entry) => entry.channel ?? channelSlug ?? null; return { @@ -1096,12 +1096,11 @@ export function localSources({ rawDir, channelsDir, channelSlug = null, probe, f const slug = slugOf(entry); const key = `${slug}/${entry.video}/${span.from}/${span.to}/${exact}/${audio}`; if (memo.has(key)) return memo.get(key); - // `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). + // `render`: the manifest's, for its tallWindowCap (sources.mjs) -- the + // one place the cap is read, so every checker resolves what this does. const hit = await resolveLocalSource( { video: entry.video, slug, from: span.from, to: span.to }, - { rawDir, channelsDir, exact, probe, audio, fallbackChannelsDir, log, ...(maxHeight !== undefined ? { maxHeight } : {}) }, + { rawDir, channelsDir, exact, probe, audio, fallbackChannelsDir, log, render }, ); // Hits only: a miss is about to be fetched into the raw cache, and the // next clip asking for the same span must find that file. @@ -6963,7 +6962,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly dirs.local = localSources({ rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe, fallbackChannelsDir: layers[1] ?? null, log: (m) => EMIT("note", { message: m }), - ...(Number.isInteger(render?.maxHeightSource) ? { maxHeight: render.maxHeightSource } : {}), + render, }); FX_CHANNELS_DIR = channelsDir; // Read only for a cut that plays post items: a cut without them publishes nothing it could blank. diff --git a/umtool/report-to-video/check-availability.mjs b/umtool/report-to-video/check-availability.mjs @@ -177,6 +177,7 @@ export async function checkAvailability(manifestPath, { fallback: CHANNELS_DIR, }), channelSlug: manifest.provenance?.channelSlug ?? null, + render: manifest.render ?? null, }); const render = manifest.render ?? {}; diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs @@ -29,7 +29,7 @@ import path from "node:path"; import { readFile } from "node:fs/promises"; import { corpusChannelsDir, isWholeRecording, localVideoId, mappedLine, recordingPlatform, withLocalIds } from "./recording-ids.mjs"; -import { resolveLocalSource } from "./sources.mjs"; +import { resolveLocalSource, tallWindowCap } from "./sources.mjs"; const DEFAULT_EDITOR = "http://localhost:3001"; // One poll a second while a job runs, one every five while it waits its turn. @@ -134,16 +134,12 @@ 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); +// A WINDOW'S HEIGHT: --max-height, else the project's tall cap -- only with +// `render.tallWindows` on (sources.mjs tallWindowCap): its render.maxHeightSource. +// Above 720 the editor keeps the taller window beside the 720 one, held to its +// clips.windowMaxHeight, and says when a clip stays lower. Without the knob no +// height is sent, as before. A whole recording (--full) keeps --max-height alone. +const windowMaxHeight = maxHeight ?? tallWindowCap(whole?.render); const provenance = whole.provenance ?? {}; const pad = Number(flag("--pad") ?? 3); @@ -444,7 +440,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"], ...(windowMaxHeight !== undefined ? { maxHeight: windowMaxHeight } : {}) }, + { channelsDir: corpusChannelsDir(), kinds: ["corpus-window"], render: whole?.render ?? null }, ); if (!hit) { die( diff --git a/umtool/report-to-video/sources.mjs b/umtool/report-to-video/sources.mjs @@ -194,6 +194,29 @@ export async function rawHeightOf(rawDir, w, probe = ffprobeSource) { return h; } +// ---- the project's opt-in to taller sources -------------------------------------- +// `render.tallWindows: true` (a look key, `umtool look <p> tallWindows=true`) is +// the ONLY switch: `render.maxHeightSource` is 1080 in every scaffold and +// preset, so it cannot be one. Absent, everything is as it always was -- no +// height probe, no clips-raw.heights.json, no tiered window read, no saved +// container probed for its height, no `maxHeight` sent for a window. On, the +// cap is `render.maxHeightSource` (1080 when unset). EVERY lookup takes the cap +// from here, through the render block it is given, so the build and the tools +// that vouch for its sources (quote-check, --align, scenes, cut points, the +// availability check, quick clip, the chain) cannot resolve different files. + +/** + * The height a project's windows are asked and resolved at, or undefined for + * the plain 720 path. Pure. + * @param {Record<string, any> | null | undefined} render the manifest's render block + * @returns {number | undefined} + */ +export function tallWindowCap(render) { + if (render?.tallWindows !== true) return undefined; + const h = Number(render?.maxHeightSource ?? 1080); + return Number.isInteger(h) && h > 720 && h <= 2160 ? h : undefined; +} + export async function cachedWindowsFor(rawDir, video) { return windowsFromNames(await listRawNames(rawDir), rawDir, video); } @@ -224,13 +247,15 @@ export const TIERS = [{ kind: "raw-cache", windows: rawCacheWindows }, ...CORPUS * `from`/`to` are the PADDED span -- what the build would otherwise fetch. * @param {{ rawDir?: string|null, channelsDir?: string|null, exact?: boolean, * probe?: (file: string) => Promise<{duration: number, height?: number}|null>, - * kinds?: string[], maxHeight?: number }} [config] + * kinds?: string[], render?: Record<string, any> | null }} [config] * `exact` (`--no-reuse`) accepts only the raw-cache file named for exactly * this span. `kinds` narrows the tiers consulted (default: all, in order). * `audio` admits the audio tier (default false; see `audioUse`). - * `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. + * `render`: the manifest's render block, read for its tallWindowCap. With + * `tallWindows` on, the tallest the disk holds up to the cap wins -- a raw + * file lower than what the corpus can give without a fetch (a taller window, + * the saved copy) gives way to it. Every caller states it (null for a + * lookup that is not a cut's: a reference recording's sound). * @returns {Promise<null | { kind: string, path: string, name: string, * windowStart: number, windowEnd: number, height?: number }>} */ @@ -245,7 +270,8 @@ export async function resolveLocalSource(want, config = {}) { async function resolveLocalSourceIn(want, config = {}) { const { video, slug = null, from, to } = want; - const { rawDir = null, channelsDir = null, exact = false, probe, kinds = null, audio = false, maxHeight } = config; + const { rawDir = null, channelsDir = null, exact = false, probe, kinds = null, audio = false, render = null } = config; + const maxHeight = tallWindowCap(render); if (!video || !Number.isFinite(from) || !Number.isFinite(to)) return null; if (exact) { @@ -285,14 +311,15 @@ 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, maxHeight = undefined }) { +export async function corpusWindowsOf({ video, slug, channelsDir, probe = ffprobeSource, fallbackChannelsDir = null, render = null }) { + const maxHeight = tallWindowCap(render); const own = await corpusWindowsIn({ video, slug, channelsDir, probe, maxHeight }); if (own.length || !fallbackChannelsDir) return own; return corpusWindowsIn({ video, slug, channelsDir: fallbackChannelsDir, probe, maxHeight }); } -// `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. +// A tall project (tallWindowCap) lists the taller windows too, so the bench's +// "fetched" and a tall render's "local" are the same set. async function corpusWindowsIn({ video, slug, channelsDir, probe, maxHeight }) { const ctx = { video, slug, channelsDir, probe, ...(maxHeight !== undefined ? { maxHeight } : {}) }; const out = []; diff --git a/umtool/report-to-video/sources.test.mjs b/umtool/report-to-video/sources.test.mjs @@ -605,6 +605,9 @@ test("buildVideo --no-network: a video clip with only its sound is refused, unle } }); +// The knob: `render.tallWindows` with the height it reaches for (sources.mjs tallWindowCap). +const TALL = { tallWindows: true, maxHeightSource: 1080 }; + // THE HEIGHT TIER (common/lib/clipWindow.ts): with render.maxHeightSource // above 720, the tallest the disk holds up to it wins -- a raw file or a 720 // corpus window gives way to a taller window or the saved copy, and is never @@ -623,7 +626,7 @@ test("a tall ask: a 720 raw file gives way to a 1080 corpus window beside the 72 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 }); + const tall = await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, render: TALL }); assert.equal(tall.kind, "corpus-window"); assert.equal(tall.name, "0.00-60.00.h1080.mp4"); assert.equal(tall.height, 1080); @@ -631,12 +634,12 @@ test("a tall ask: a 720 raw file gives way to a 1080 corpus window beside the 72 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 }); + await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, render: TALL }); assert.equal(calls.length, 1); // A raw file as tall as the ask is kept: the earliest tier that reaches it. idx[rawWindowName(VIDEO, 0, 60)].height = 1080; await writeFile(rawHeightsPath(t.rawDir), JSON.stringify(idx)); - const raw1080 = await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, maxHeight: 1080 }); + const raw1080 = await resolveLocalSource(want, { rawDir: t.rawDir, channelsDir: t.channelsDir, probe, render: TALL }); assert.equal(raw1080.kind, "raw-cache"); } finally { await rm(t.root, { recursive: true, force: true }); @@ -651,10 +654,10 @@ test("a tall ask with only lower windows reaches for the saved copy when it is t 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 }); + const hit = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe: fakeProbe(600).probe, render: TALL }); assert.equal(hit.kind, "saved-video"); await pointTo(t.videoDir, t.storeDir, "source-media.mp4", { format: { preset: "original", height: 480 } }); - const lower = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe: fakeProbe(600).probe, maxHeight: 1080 }); + const lower = await resolveLocalSource(want, { channelsDir: t.channelsDir, probe: fakeProbe(600).probe, render: TALL }); assert.equal(lower.kind, "corpus-window"); assert.equal(lower.name, "0.00-60.00.mp4"); } finally {