commit 820d1daddcb2ce822e7db67f4b187c9d158114fe
parent f16785c5a7cb73ba6109edaa4c10f5ec442f9d56
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 15:11:20 -0400
window sync: Rumble clip windows are cut from the saved whole recording; a window whose picture runs off its sound is set aside (<from>-<to>.desynced.<ext>), and check-windows sweeps the ones on disk
- lib/clipWindowSync.ts: windowSyncOf (a track starting > 0.25 s in, or video and audio durations > 0.25 s apart, is desynced; one-track windows are not judged), the measured numbers in the comment; clipWindowSync-server.ts: the ffprobe stream probe, the verdict recorded in the sidecar (no re-probe for the same size), the set-aside rename, the in-sync containing-window finder
- every reader ignores a .desynced name (parseClipWindowName, windowsFromBareNames); evictClipWindows ages them out with their own sidecar
- fetchWindows: a desynced held window is set aside and its span fetched again in the same run (saved video first); a seek that comes out desynced is set aside and fails `desynced`; the single fetch-window path and the batch planner judge held windows too
- settings.clips.wholeRecordingPlatforms (default ["rumble"]): such a window is cut from the whole recording, saved once per video through the persist download (downloadOneManaged, forceMedia, persistOrigin) on the platform's download queue; a failed download fails its windows, never a seek; "wholeRecording": false restores the seek for a run (route, replay, ops help)
- check-windows ops action + job (needsText, parallel), Check sync button on the Clip windows card
- SETTINGS.md, settings.json.example and COMMANDS.md regenerated
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
33 files changed, 2102 insertions(+), 57 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -138,6 +138,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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. | |
+| `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` |
| `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` |
@@ -145,7 +146,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` |
| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` |
| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. | `pnpm ops persist-videos --file list.json --wait` |
-| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
+| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
| `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[<version>\] - <date>": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release <workspace> <version>") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` |
| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` |
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -53,6 +53,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`seeder`](#seeder) | object — see below |
| [`tts`](#tts) | object — see below |
| [`generation`](#generation) | object — see below |
+| [`clips`](#clips) | object — see below |
## `adminTitle`
@@ -1217,3 +1218,23 @@ Default:
}
}
```
+
+## `clips`
+
+How clip windows are fetched (controller/fetchWindows.ts): the platforms whose windows are cut from the saved WHOLE recording rather than by a remote seek — Rumble by default, because its HLS seek put the picture 1–4 s off the sound (lib/clipWindowSync.ts). See ClipsSettings.
+
+#### `clips`
+
+| Key | Default | Description |
+|---|---|---|
+| `wholeRecordingPlatforms` | list — see below | Platforms (as the URL names them: "rumble", "youtube", …) whose clip windows are cut from the WHOLE recording instead of fetched by a remote seek: a fetch-windows run saves the video once to the saved-video store (as "Persist source video" does, on the platform's download queue) and cuts every window of it locally. A failed whole download fails its windows; it never falls back to a seek. A run's `"wholeRecording": false` restores the seek for that run. Default ["rumble"] (a Rumble seek put the picture 1–4 s off the sound in 26 of 205 windows); [] = every platform seeks. |
+
+Default:
+
+```json
+{
+ "wholeRecordingPlatforms": [
+ "rumble"
+ ]
+}
+```
diff --git a/common/controller/checkClipWindows.test.ts b/common/controller/checkClipWindows.test.ts
@@ -0,0 +1,115 @@
+// The check-windows sweep (lib/clipWindowSync.ts) over a temp corpus, with an
+// injected probe: a window is desynced when its name says "bad".
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/checkClipWindows.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { checkClipWindows, checkClipWindowsSummary } from "./checkClipWindows";
+import type { WindowStreamProbe } from "../lib/clipWindowSync-server";
+import type { Paths } from "../lib/paths";
+
+const DESYNCED = [
+ { codec_type: "video", start_time: "3.200000", duration: "93.733000" },
+ { codec_type: "audio", start_time: "3.140000", duration: "90.580000" },
+];
+const IN_SYNC = [
+ { codec_type: "video", start_time: "0.000000", duration: "30.000000" },
+ { codec_type: "audio", start_time: "0.000000", duration: "30.000000" },
+];
+
+async function withCorpus(fn: (paths: Paths, clipsOf: (slug: string, id: string) => string) => Promise<void>) {
+ const dir = await mkdtemp(path.join(tmpdir(), "check-windows-"));
+ const transcriptsDir = path.join(dir, "corpus");
+ const paths = { transcriptsDir, channelsDir: path.join(transcriptsDir, "channels") } as Paths;
+ const clipsOf = (slug: string, id: string) => path.join(paths.channelsDir, slug, "data", id, "clips");
+ const seed = async (slug: string, id: string, names: string[]) => {
+ await mkdir(clipsOf(slug, id), { recursive: true });
+ for (const n of names) await writeFile(path.join(clipsOf(slug, id), n), "mp4");
+ };
+ await seed("alpha", "v1", ["10.00-40.00.mp4", "bad-placeholder"]);
+ await seed("alpha", "v2", ["0.00-30.00.mp4"]);
+ await seed("beta", "v3", ["5.00-35.00.mp4"]);
+ try {
+ await fn(paths, clipsOf);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+// alpha/v1's 10-40 and beta/v3's window are the desynced ones.
+const BAD = new Set(["alpha/v1/10.00-40.00.mp4", "beta/v3/5.00-35.00.mp4"]);
+function probeOf(calls: string[]): WindowStreamProbe {
+ return async (file) => {
+ const parts = file.split(path.sep);
+ const key = `${parts.at(-5)}/${parts.at(-3)}/${parts.at(-1)}`;
+ calls.push(key);
+ return BAD.has(key) ? DESYNCED : IN_SYNC;
+ };
+}
+
+test("a dry run lists the desynced windows and touches nothing", async () => {
+ await withCorpus(async (paths, clipsOf) => {
+ const logs: string[] = [];
+ const calls: string[] = [];
+ const r = await checkClipWindows({ paths, dryRun: true, probe: probeOf(calls), onLog: (l) => logs.push(l) });
+ assert.equal(r.checked, 3);
+ assert.equal(r.videos, 3);
+ assert.equal(r.channels, 2);
+ assert.deepEqual(r.desynced.map((d) => [d.slug, d.id, d.file, d.lagS, d.setAsideAs]), [
+ ["alpha", "v1", "10.00-40.00.mp4", 3.2, null],
+ ["beta", "v3", "5.00-35.00.mp4", 3.2, null],
+ ]);
+ assert.equal(r.setAside, 0);
+ assert.deepEqual((await readdir(clipsOf("alpha", "v1"))).sort(), ["10.00-40.00.mp4", "bad-placeholder"]);
+ assert.deepEqual(await readdir(clipsOf("alpha", "v2")), ["0.00-30.00.mp4"], "a dry run records no verdict either");
+ assert.match(logs[0], /^desynced alpha\/v1\/clips\/10\.00-40\.00\.mp4: the picture runs 3\.2 s off the sound \(.*\) — would be set aside$/);
+ assert.equal(
+ checkClipWindowsSummary(r),
+ "Checked 3 window(s) in 3 video(s) across 2 channel(s): 2 desynced, 0 set aside (dry run: nothing renamed).",
+ );
+ });
+});
+
+test("a real run sets the desynced ones aside, records the good verdicts, and a second run probes nothing", async () => {
+ await withCorpus(async (paths, clipsOf) => {
+ const logs: string[] = [];
+ const calls: string[] = [];
+ const r = await checkClipWindows({ paths, probe: probeOf(calls), onLog: (l) => logs.push(l) });
+ assert.equal(r.setAside, 2);
+ assert.deepEqual(r.desynced.map((d) => d.setAsideAs), ["10.00-40.00.desynced.mp4", "5.00-35.00.desynced.mp4"]);
+ assert.deepEqual((await readdir(clipsOf("alpha", "v1"))).sort(), [
+ "10.00-40.00.desynced.json",
+ "10.00-40.00.desynced.mp4",
+ "bad-placeholder",
+ ]);
+ assert.deepEqual((await readdir(clipsOf("alpha", "v2"))).sort(), ["0.00-30.00.json", "0.00-30.00.mp4"]);
+ assert.ok(logs.some((l) => l.endsWith("— set aside as 5.00-35.00.desynced.mp4")), logs.join("\n"));
+ assert.equal(
+ checkClipWindowsSummary(r),
+ "Checked 3 window(s) in 3 video(s) across 2 channel(s): 2 desynced, 2 set aside.",
+ );
+ calls.length = 0;
+ const again = await checkClipWindows({ paths, probe: probeOf(calls) });
+ assert.equal(again.checked, 1);
+ assert.equal(again.fromRecord, 1);
+ assert.deepEqual(calls, []);
+ assert.equal(again.desynced.length, 0);
+ });
+});
+
+test("one channel, one video; a video without its channel is refused", async () => {
+ await withCorpus(async (paths) => {
+ const calls: string[] = [];
+ const one = await checkClipWindows({ paths, slug: "alpha", video: "v2", dryRun: true, probe: probeOf(calls) });
+ assert.equal(one.checked, 1);
+ assert.deepEqual(calls, ["alpha/v2/0.00-30.00.mp4"]);
+ const ch = await checkClipWindows({ paths, slug: "beta", dryRun: true, probe: probeOf([]) });
+ assert.equal(ch.checked, 1);
+ assert.equal(ch.desynced.length, 1);
+ await assert.rejects(() => checkClipWindows({ paths, video: "v2", probe: probeOf([]) }), /give its slug too/);
+ });
+});
diff --git a/common/controller/checkClipWindows.ts b/common/controller/checkClipWindows.ts
@@ -0,0 +1,203 @@
+import path from "node:path";
+import { readdir } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { CLIPS_DIR_NAME } from "../lib/clipWindow";
+import { listClipWindows } from "../lib/clipWindow-server";
+import { windowSyncLagText } from "../lib/clipWindowSync";
+import {
+ ffprobeWindowProbe,
+ judgeClipWindow,
+ setAsideDesyncedWindow,
+ type WindowStreamProbe,
+} from "../lib/clipWindowSync-server";
+import { inspectChannelMedia } from "../lib/channelMedia";
+import { channelConfigPlatform } from "../lib/videoId";
+import { resolveVideoDirId } from "../lib/videoDir-server.mjs";
+import { readChannelConfig } from "./channels";
+
+// CHECK THE WINDOWS ALREADY ON DISK (lib/clipWindowSync.ts).
+//
+// A fetch judges the windows IT considers (controller/fetchWindows.ts): the one
+// it just fetched, and the held ones it would have answered a span with. The
+// windows fetched before the check existed — 26 of the 318 Rumble windows on
+// the corpus on 2026-10-23 had their picture 1–4 s off their sound — are judged
+// only when something asks for their span again. This is the sweep that does
+// not wait: every window in one video, one channel or the corpus is probed,
+// and a desynced one is SET ASIDE (`<from>-<to>.desynced.<ext>`, never deleted)
+// so a report video stops cutting from it today, not on its next fetch.
+//
+// The walk is evictClipWindows' (the same text guard, the same skip of a
+// channel whose text cannot be read), and the probe is one ffprobe of the
+// stream headers per window. A window whose sidecar already records a good
+// verdict for its current size is not probed again — that verdict came from
+// this same probe of these same bytes — and a good verdict found here is
+// recorded the same way, so the second sweep of a corpus costs a readdir.
+
+export type CheckClipWindowsOptions = {
+ paths: Paths;
+ // One channel, or every channel when absent.
+ slug?: string;
+ // One video of `slug` (a record id; a Twitch v<n> resolves to its dir).
+ video?: string;
+ // List what is desynced; rename nothing, record nothing.
+ dryRun?: boolean;
+ onLog?: (message: string) => void;
+ signal?: AbortSignal;
+ // Tests inject one; absent = ffprobe at `paths.ffprobeBin`.
+ probe?: WindowStreamProbe;
+};
+
+export type CheckedDesyncedWindow = {
+ slug: string;
+ id: string;
+ file: string;
+ lagS: number;
+ reason?: string;
+ // The name it was set aside as; null on a dry run.
+ setAsideAs: string | null;
+};
+
+export type CheckClipWindowsResult = {
+ dryRun: boolean;
+ channels: number;
+ // Video dirs that held at least one window.
+ videos: number;
+ checked: number;
+ // Of `checked`: answered by a verdict the sidecar already recorded.
+ fromRecord: number;
+ // Of `checked`: ffprobe could not read them — kept, not judged.
+ unreadable: number;
+ desynced: CheckedDesyncedWindow[];
+ setAside: number;
+ // `<slug>: <reason>` for every channel the walk refused to touch.
+ skipped: string[];
+};
+
+async function checkVideo(
+ opts: CheckClipWindowsOptions,
+ probe: WindowStreamProbe,
+ slug: string,
+ id: string,
+ out: CheckClipWindowsResult,
+): Promise<void> {
+ const videoDir = path.join(opts.paths.channelsDir, slug, "data", id);
+ const windows = await listClipWindows(videoDir);
+ if (windows.length === 0) return;
+ out.videos += 1;
+ for (const w of windows) {
+ if (opts.signal?.aborted) return;
+ out.checked += 1;
+ const { sync, fromRecord } = await judgeClipWindow(w, { probe, record: !opts.dryRun });
+ if (fromRecord) out.fromRecord += 1;
+ if (!sync) {
+ out.unreadable += 1;
+ opts.onLog?.(`could not probe ${slug}/${id}/${CLIPS_DIR_NAME}/${w.file} — kept, not judged`);
+ continue;
+ }
+ if (sync.ok) continue;
+ let setAsideAs: string | null = null;
+ if (!opts.dryRun) {
+ try {
+ setAsideAs = (await setAsideDesyncedWindow(w, sync)).file;
+ out.setAside += 1;
+ } catch (e) {
+ // Counted desynced and not set aside; the summary's two numbers differ.
+ opts.onLog?.(`could not set ${slug}/${id}/${CLIPS_DIR_NAME}/${w.file} aside: ${(e as Error).message}`);
+ }
+ }
+ out.desynced.push({
+ slug,
+ id,
+ file: w.file,
+ lagS: sync.lagS,
+ ...(sync.reason ? { reason: sync.reason } : {}),
+ setAsideAs,
+ });
+ opts.onLog?.(
+ `desynced ${slug}/${id}/${CLIPS_DIR_NAME}/${w.file}: ${windowSyncLagText(sync)}` +
+ `${sync.reason ? ` (${sync.reason})` : ""} — ` +
+ (setAsideAs ? `set aside as ${setAsideAs}` : opts.dryRun ? "would be set aside" : "NOT set aside"),
+ );
+ }
+}
+
+async function checkChannel(
+ opts: CheckClipWindowsOptions,
+ probe: WindowStreamProbe,
+ slug: string,
+ out: CheckClipWindowsResult,
+): Promise<void> {
+ // THE TEXT GUARD, as evictClipWindows: `clips/` is on the corpus disk and
+ // never tiered, so a channel whose MEDIA is away is checked as usual; one
+ // whose text cannot be read (a `legacy` channel, a tier migration) would
+ // read as "no windows", and is skipped saying so instead.
+ const media = await inspectChannelMedia(opts.paths, slug, undefined, { fresh: true });
+ if (!media.text.readable) {
+ out.skipped.push(
+ `${slug}: media ${media.status}${media.detail ? ` (${media.detail})` : ""} — nothing was touched`,
+ );
+ return;
+ }
+ out.channels += 1;
+ if (opts.video) {
+ const config = await readChannelConfig(opts.paths, slug).catch(() => null);
+ const id = await resolveVideoDirId(opts.paths.channelsDir, slug, opts.video, {
+ ...(config ? { platform: channelConfigPlatform(config) } : {}),
+ });
+ await checkVideo(opts, probe, slug, id, out);
+ return;
+ }
+ const ids = await readdir(path.join(opts.paths.channelsDir, slug, "data")).catch(() => [] as string[]);
+ for (const id of ids.sort()) {
+ if (opts.signal?.aborted) return;
+ await checkVideo(opts, probe, slug, id, out);
+ }
+}
+
+export async function checkClipWindows(
+ opts: CheckClipWindowsOptions,
+): Promise<CheckClipWindowsResult> {
+ if (opts.video && !opts.slug) throw new Error("a video is named within a channel: give its slug too");
+ const out: CheckClipWindowsResult = {
+ dryRun: Boolean(opts.dryRun),
+ channels: 0,
+ videos: 0,
+ checked: 0,
+ fromRecord: 0,
+ unreadable: 0,
+ desynced: [],
+ setAside: 0,
+ skipped: [],
+ };
+ const probe = opts.probe ?? ffprobeWindowProbe(opts.paths.ffprobeBin);
+ let slugs: string[];
+ if (opts.slug) {
+ slugs = [opts.slug];
+ } else {
+ // `isDirectory()` for the reason channel listing does it: a symlinked
+ // `<slug>/` is not a channel (AGENTS.md).
+ const entries = await readdir(opts.paths.channelsDir, { withFileTypes: true }).catch(() => []);
+ slugs = entries
+ .filter((e) => e.isDirectory())
+ .map((e) => e.name)
+ .sort();
+ }
+ for (const slug of slugs) {
+ if (opts.signal?.aborted) break;
+ await checkChannel(opts, probe, slug, out);
+ }
+ return out;
+}
+
+// The one sentence every surface ends a run with.
+export function checkClipWindowsSummary(r: CheckClipWindowsResult): string {
+ return (
+ `Checked ${r.checked} window(s) in ${r.videos} video(s) across ${r.channels} channel(s)` +
+ (r.fromRecord ? ` (${r.fromRecord} by a recorded verdict)` : "") +
+ `: ${r.desynced.length} desynced, ${r.setAside} set aside` +
+ (r.dryRun && r.desynced.length ? " (dry run: nothing renamed)" : "") +
+ (r.unreadable ? `; ${r.unreadable} could not be probed` : "") +
+ "." +
+ (r.skipped.length ? ` Skipped: ${r.skipped.join("; ")}` : "")
+ );
+}
diff --git a/common/controller/evictClipWindows.test.ts b/common/controller/evictClipWindows.test.ts
@@ -277,3 +277,23 @@ test("a non-finite age is REFUSED, because clamping it would evict everything",
assert.equal(await exists(path.join(clipsDir, "10.00-40.00.mp4")), true);
});
});
+
+test("a set-aside (desynced) window is cache too: it ages out with its own sidecar", async () => {
+ // lib/clipWindowSync.ts renames a window whose picture runs off its sound to
+ // `<from>-<to>.desynced.<ext>`. No reader sees it, so if eviction did not
+ // either, its bytes would be the one thing in clips/ nothing ever removed.
+ await withTmp(async (paths) => {
+ const clipsDir = await seed(paths, "alpha", {
+ "10.00-40.00.desynced.mp4": { ageDays: 90, size: 700 },
+ "50.00-60.00.desynced.mp4": { ageDays: 1, size: 300 },
+ });
+ const r = await evictClipWindows({ paths, olderThanDays: 30 });
+ assert.equal(r.windows, 1);
+ assert.equal(r.bytes, 700);
+ assert.equal(r.kept, 1);
+ assert.equal(await exists(path.join(clipsDir, "10.00-40.00.desynced.mp4")), false);
+ assert.equal(await exists(path.join(clipsDir, "10.00-40.00.desynced.json")), false);
+ assert.equal(await exists(path.join(clipsDir, "50.00-60.00.desynced.mp4")), true);
+ assert.equal(await exists(path.join(clipsDir, "50.00-60.00.desynced.json")), true);
+ });
+});
diff --git a/common/controller/evictClipWindows.ts b/common/controller/evictClipWindows.ts
@@ -3,8 +3,10 @@ import { readdir, rm, stat } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import {
CLIPS_DIR_NAME,
+ clipWindowDesyncedSidecar,
clipWindowSidecar,
parseClipWindowName,
+ parseDesyncedClipWindowName,
} from "../lib/clipWindow";
import { inspectChannelMedia } from "../lib/channelMedia";
import { formatBytes } from "../lib/format";
@@ -133,7 +135,13 @@ async function evictChannel(
// describes and never on its own — walking them independently would let
// one pass delete a sidecar whose window survived, and a window with no
// provenance is one nobody can explain afterwards.
- const span = parseClipWindowName(name);
+ //
+ // A SET-ASIDE WINDOW (`<from>-<to>.desynced.<ext>`, lib/clipWindowSync.ts)
+ // is cache like any other and ages out the same way, with its own
+ // `.desynced.json`: no reader sees it, so nothing else ever would.
+ const live = parseClipWindowName(name);
+ const aside = live ? null : parseDesyncedClipWindowName(name);
+ const span = live ?? aside;
if (!span) continue;
const file = path.join(clipsDir, name);
let st;
@@ -162,9 +170,13 @@ async function evictChannel(
// `force` so a window whose sidecar was never written is not an error —
// an interrupted fetch leaves exactly that, and it is the most evictable
// thing in the directory.
- await rm(path.join(clipsDir, clipWindowSidecar(span.from, span.to)), {
- force: true,
- });
+ await rm(
+ path.join(
+ clipsDir,
+ aside ? clipWindowDesyncedSidecar(span.from, span.to) : clipWindowSidecar(span.from, span.to),
+ ),
+ { force: true },
+ );
}
if (sawWindow) out.videos += 1;
// The now-empty `clips/` is left in place deliberately: `rmdir` here would
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -7,7 +7,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { chmod, mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
@@ -89,6 +89,8 @@ function harness(over: Partial<FetchWindowsDeps> = {}) {
},
gapRemainingMs: () => 0,
noteGap: () => {},
+ // The fake yt-dlp's windows are not media: not judged, unless a test says.
+ probeWindow: async () => null,
...over,
};
return { rec, deps };
@@ -273,6 +275,8 @@ test("rumble windows are further apart, whatever platform their channel names",
paths: await corpus(),
items: [rumble("v1"), rumble("v2")],
provenance: { requestedBy: "test" },
+ // The remote seek's pacing, which a whole-recording run does not use.
+ wholeRecording: false,
deps: h.deps,
});
assert.equal(r.fetched.length, 2);
@@ -291,6 +295,7 @@ test("minGapSeconds replaces rumble's floor for one run, never below the global
items: [rumble("v1"), rumble("v2")],
provenance: { requestedBy: "test" },
minGapSeconds: asked,
+ wholeRecording: false,
deps: h.deps,
});
assert.equal(h.rec.sleeps.length, 1);
@@ -474,3 +479,275 @@ test("a copy whose fetch failed is recorded beside the recording (find-copy will
await go(paths, [{ slug: "c", id: "v2", from: 10, to: 20, webpageUrl: limited.url, copy: limited }], h);
assert.equal(recorded.length, 1, "a rate limit says nothing about the copy");
});
+
+// THE SYNC CHECK (lib/clipWindowSync.ts). The probe is injected: a window is
+// "desynced" when its name is in the set — the Rumble HLS shape, measured
+// 2026-10-23 (video 3.200/93.73, audio 3.140/90.58).
+const DESYNCED = [
+ { codec_type: "video", start_time: "3.200000", duration: "93.733000" },
+ { codec_type: "audio", start_time: "3.140000", duration: "90.580000" },
+];
+const IN_SYNC = [
+ { codec_type: "video", start_time: "0.000000", duration: "10.000000" },
+ { codec_type: "audio", start_time: "0.000000", duration: "10.010000" },
+];
+function probeOf(bad: Set<string>, probed: string[] = []): FetchWindowsDeps["probeWindow"] {
+ return async (file) => {
+ probed.push(path.basename(file));
+ return bad.has(path.basename(file)) ? DESYNCED : IN_SYNC;
+ };
+}
+
+test("a desynced held window is set aside and the same run fetches the span again", async () => {
+ const paths = await corpus();
+ const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips");
+ await mkdir(clips, { recursive: true });
+ await writeFile(path.join(clips, "0.00-60.00.mp4"), "mp4");
+ await writeFile(path.join(clips, "0.00-60.00.json"), JSON.stringify({ requestedBy: "umtool" }));
+ const probed: string[] = [];
+ const logs: string[] = [];
+ const h = harness({ probeWindow: probeOf(new Set(["0.00-60.00.mp4"]), probed) });
+ const before = await spawns();
+ const r = await fetchWindows({
+ paths,
+ items: [item("v1", "/a", 5, 15)],
+ provenance: { requestedBy: "test" },
+ gapMs: 1000,
+ onLog: (l) => logs.push(l),
+ deps: h.deps,
+ });
+ assert.equal(r.cached.length, 0, "a desynced window does not answer for its span");
+ assert.deepEqual(r.fetched.map((i) => i.id), ["v1"]);
+ assert.deepEqual(r.setAside, ["c/v1/clips/0.00-60.00.desynced.mp4"]);
+ assert.equal((await spawns()) - before, 1);
+ assert.deepEqual(
+ (await readdir(clips)).sort(),
+ ["0.00-60.00.desynced.json", "0.00-60.00.desynced.mp4", "5.00-15.00.json", "5.00-15.00.mp4"],
+ );
+ assert.ok(
+ logs.some((l) =>
+ l.includes(
+ "! c/v1 5.00–15.00: clips/0.00-60.00.mp4 — the picture runs 3.2 s off the sound; set aside as " +
+ "0.00-60.00.desynced.mp4, and the span is fetched again.",
+ ),
+ ),
+ logs.join(""),
+ );
+ // The fresh window was judged in sync and the verdict recorded beside it.
+ const side = parseClipProvenance(JSON.parse(await readFile(path.join(clips, "5.00-15.00.json"), "utf8")));
+ assert.equal(side?.sync?.ok, true);
+ // A second run: cached, and answered by the recorded verdict without a probe.
+ probed.length = 0;
+ const again = await go(paths, [item("v1", "/a", 5, 15)], harness({ probeWindow: probeOf(new Set(), probed) }));
+ assert.deepEqual(again.cached.map((i) => i.id), ["v1"]);
+ assert.deepEqual(probed, []);
+});
+
+test("a desynced held window covered by a saved video is cut from it instead", async () => {
+ const paths = await corpus();
+ const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips");
+ await mkdir(clips, { recursive: true });
+ await writeFile(path.join(clips, "0.00-60.00.mp4"), "mp4");
+ const cuts: number[] = [];
+ const h = harness({
+ probeWindow: probeOf(new Set(["0.00-60.00.mp4"])),
+ savedWindowSource: async () => ({
+ kind: "covers",
+ pointer: { storedAt: "", dir: "/store", file: "source-media.mp4", bytes: 1 },
+ container: "/store/source-media.mp4",
+ durationSec: 600,
+ probe: { durationSec: 600, width: 160, height: 90, hasVideo: true, hasAudio: true },
+ }),
+ cutSavedWindow: async ({ from, to }) => {
+ cuts.push(from);
+ return { file: "x.mp4", path: "/x.mp4", from, to, bytes: 1, provenance: { requestedBy: "test", source: "saved-video" } };
+ },
+ });
+ const before = await spawns();
+ const r = await go(paths, [item("v1", "/a", 5, 15)], h);
+ assert.deepEqual(r.cut.map((i) => i.id), ["v1"]);
+ assert.deepEqual(cuts, [5]);
+ assert.equal((await spawns()) - before, 0, "no network");
+ assert.deepEqual(r.setAside, ["c/v1/clips/0.00-60.00.desynced.mp4"]);
+});
+
+test("a fetch that comes out desynced is set aside and fails the item; the run goes on", async () => {
+ const paths = await corpus();
+ const logs: string[] = [];
+ const h = harness({ probeWindow: probeOf(new Set(["10.00-20.00.mp4"])) });
+ const rumble = (id: string, from: number, to: number): FetchWindowsItem => ({
+ slug: "c",
+ id,
+ from,
+ to,
+ webpageUrl: `https://rumble.com/${id}-x.html`,
+ });
+ const r = await fetchWindows({
+ paths,
+ items: [rumble("v1", 10, 20), rumble("v2", 30, 40)],
+ provenance: { requestedBy: "test" },
+ gapMs: 1000,
+ // The seek, where the check is the backstop.
+ wholeRecording: false,
+ onLog: (l) => logs.push(l),
+ deps: h.deps,
+ });
+ assert.deepEqual(r.fetched.map((i) => i.id), ["v2"]);
+ assert.equal(r.failed.length, 1);
+ assert.equal(r.failed[0].class, "desynced");
+ assert.deepEqual(r.setAside, ["c/v1/clips/10.00-20.00.desynced.mp4"]);
+ const line =
+ ' ✗ c/v1 10.00–20.00: the picture runs 3.2 s off the sound (a Rumble HLS seek); set aside as ' +
+ '10.00-20.00.desynced.mp4 — save the whole recording ("Persist source video") and fetch again to ' +
+ "cut it from the saved video\n";
+ assert.ok(logs.includes(line), logs.join(""));
+ assert.ok(logs.at(-1)?.includes("1 failed, 1 set aside as desynced"), logs.at(-1));
+ const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips");
+ assert.deepEqual((await readdir(clips)).sort(), ["10.00-20.00.desynced.json", "10.00-20.00.desynced.mp4"]);
+ const side = JSON.parse(await readFile(path.join(clips, "10.00-20.00.desynced.json"), "utf8"));
+ assert.equal(side.requestedBy, "test", "the fetch's provenance travels with it");
+ assert.equal(side.sync.ok, false);
+ assert.equal(side.sync.lagS, 3.2);
+ assert.equal(typeof side.setAsideAt, "string");
+ // The request itself succeeded: the platform is recorded clean for both.
+ assert.deepEqual(h.rec.cleans, ["rumble", "rumble"]);
+});
+
+// THE WHOLE RECORDING (settings.clips.wholeRecordingPlatforms, Rumble by
+// default): a Rumble window is cut from the saved whole video, never seeked.
+// The download and the saved tier are injected: a video is "saved" once the
+// fake download has run for it.
+function wholeHarness(opts: { fail?: Record<string, { message: string; failureClass: "network" | "per_video" | "rate_limit" }>; saved?: string[] } = {}) {
+ const savedIds = new Set(opts.saved ?? []);
+ const downloads: { slug: string; url: string; origin: { requestedBy: string; clipId?: string; reason?: string } }[] = [];
+ const cuts: { id: string; from: number }[] = [];
+ const h = harness({
+ assertMediaReachable: async () => undefined,
+ saveWholeRecording: async (o) => {
+ downloads.push({ slug: o.slug, url: o.url, origin: o.origin });
+ const id = /rumble\.com\/(\w+)-/.exec(o.url)?.[1] ?? "";
+ const failure = opts.fail?.[id];
+ if (failure) return { ok: false, ...failure };
+ savedIds.add(id);
+ return { ok: true };
+ },
+ savedWindowSource: async ({ videoDir }) =>
+ savedIds.has(path.basename(videoDir))
+ ? {
+ kind: "covers",
+ pointer: { storedAt: "", dir: "/store", file: "source-media.mp4", bytes: 1 },
+ container: "/store/source-media.mp4",
+ durationSec: 600,
+ probe: { durationSec: 600, width: 160, height: 90, hasVideo: true, hasAudio: true },
+ }
+ : { kind: "none" },
+ cutSavedWindow: async ({ videoDir, from, to }) => {
+ cuts.push({ id: path.basename(videoDir), from });
+ return { file: `${from}.mp4`, path: "/x.mp4", from, to, bytes: 1, provenance: { requestedBy: "test", source: "saved-video" } };
+ },
+ });
+ return { h, downloads, cuts };
+}
+const rumbleItem = (id: string, from: number, clipId?: string): FetchWindowsItem => ({
+ slug: "c",
+ id,
+ from,
+ to: from + 10,
+ webpageUrl: `https://rumble.com/${id}-x.html`,
+ ...(clipId ? { clipId } : {}),
+});
+
+test("whole recording: three windows of one Rumble video are ONE download, then three local cuts", async () => {
+ const { h, downloads, cuts } = wholeHarness();
+ const logs: string[] = [];
+ const before = await spawns();
+ const r = await fetchWindows({
+ paths: await corpus(),
+ items: [rumbleItem("v7en8uw", 10, "r#1"), rumbleItem("v7en8uw", 30, "r#2"), rumbleItem("v7en8uw", 50, "r#3")],
+ provenance: { requestedBy: "umtool", manifest: "m" },
+ gapMs: 1000,
+ onLog: (l) => logs.push(l),
+ deps: h.deps,
+ });
+ assert.equal(downloads.length, 1);
+ assert.equal(downloads[0].url, "https://rumble.com/v7en8uw-x.html");
+ assert.equal(downloads[0].origin.requestedBy, "umtool");
+ assert.equal(downloads[0].origin.clipId, "r#1");
+ assert.match(downloads[0].origin.reason ?? "", /cut from the whole recording/);
+ assert.deepEqual(cuts.map((c) => c.from), [10, 30, 50]);
+ assert.equal(r.cut.length, 3);
+ assert.equal(r.fetched.length, 0);
+ assert.deepEqual(r.saved, ["c/v7en8uw"]);
+ assert.equal((await spawns()) - before, 0, "no remote seek");
+ assert.ok(
+ logs.includes(
+ " ↧ c/v7en8uw: saving the whole recording (Rumble windows are cut from it), then cutting 3 window(s)\n",
+ ),
+ logs.join(""),
+ );
+ assert.deepEqual(h.rec.cleans, ["rumble"]);
+ assert.deepEqual(h.rec.sleeps, [], "one download owes no pause; the cuts owe none");
+});
+
+test("whole recording: a video already saved is cut with no download", async () => {
+ const { h, downloads, cuts } = wholeHarness({ saved: ["v1"] });
+ const r = await go(await corpus(), [rumbleItem("v1", 10), rumbleItem("v1", 40)], h);
+ assert.equal(downloads.length, 0);
+ assert.deepEqual(cuts.map((c) => c.from), [10, 40]);
+ assert.equal(r.cut.length, 2);
+});
+
+test("whole recording: a failed download fails the video's windows with its message, no seek, no retry", async () => {
+ const msg = "the whole recording was not saved: ERROR: [Rumble] v1: HTTP Error 403: Forbidden";
+ const { h, downloads } = wholeHarness({ fail: { v1: { message: msg, failureClass: "per_video" } } });
+ const before = await spawns();
+ const r = await go(await corpus(), [rumbleItem("v1", 10), rumbleItem("v1", 30), rumbleItem("v2", 10)], h);
+ assert.equal(downloads.length, 2, "v1 once, then v2");
+ assert.deepEqual(r.failed.map((f) => [f.item.id, f.class, f.message]), [
+ ["v1", "per_video", msg],
+ ["v1", "per_video", msg],
+ ]);
+ assert.deepEqual(r.cut.map((i) => i.id), ["v2"]);
+ assert.equal((await spawns()) - before, 0, "never falls back to a remote seek");
+ // A rate limit stops the run, as any 429 does.
+ const limited = wholeHarness({ fail: { v1: { message: "429", failureClass: "rate_limit" } } });
+ const r2 = await go(await corpus(), [rumbleItem("v1", 10), rumbleItem("v2", 10)], limited.h);
+ assert.equal(r2.stopped, "rate-limit");
+ assert.deepEqual(r2.notAttempted.map((i) => i.id), ["v2"]);
+ assert.deepEqual(limited.h.rec.backoffs, [["rumble", "rate_limit"]]);
+});
+
+test("whole recording: wholeRecording false restores the remote seek; a platform not listed is unchanged", async () => {
+ const { h, downloads } = wholeHarness();
+ const before = await spawns();
+ const r = await fetchWindows({
+ paths: await corpus(),
+ items: [rumbleItem("v1", 10)],
+ provenance: { requestedBy: "test" },
+ gapMs: 1000,
+ wholeRecording: false,
+ deps: h.deps,
+ });
+ assert.deepEqual(r.fetched.map((i) => i.id), ["v1"]);
+ assert.equal(downloads.length, 0);
+ assert.equal((await spawns()) - before, 1);
+ // YouTube is not on the default list: seeked as ever.
+ const yt = wholeHarness();
+ const r2 = await go(await corpus(), [item("v1", "/ok")], yt.h);
+ assert.deepEqual(r2.fetched.map((i) => i.id), ["v1"]);
+ assert.equal(yt.downloads.length, 0);
+ // ...unless the settings list it.
+ const listed = wholeHarness();
+ listed.h.deps.getSettings = () =>
+ ({ sleepBetweenDownloadsSeconds: 0, clips: { wholeRecordingPlatforms: ["youtube"] } }) as unknown as SiteSettings;
+ const r3 = await go(await corpus(), [item("v1", "/ok")], listed.h);
+ assert.equal(listed.downloads.length, 1);
+ assert.equal(r3.fetched.length, 0);
+ // An empty list turns it off for Rumble too.
+ const none = wholeHarness();
+ none.h.deps.getSettings = () =>
+ ({ sleepBetweenDownloadsSeconds: 0, clips: { wholeRecordingPlatforms: [] } }) as unknown as SiteSettings;
+ const r4 = await go(await corpus(), [rumbleItem("v1", 10)], none.h);
+ assert.equal(none.downloads.length, 0);
+ assert.deepEqual(r4.fetched.map((i) => i.id), ["v1"]);
+});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -3,13 +3,31 @@ import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
import { getSettings } from "../lib/settings";
-import type { DownloadFailureClass } from "../lib/availability";
+import {
+ classifyDownloadFailure,
+ parseUnavailableFromStderr,
+ type DownloadFailureClass,
+} from "../lib/availability";
+import type { SavedVideoOrigin } from "../lib/savedVideo";
+import { DEFAULT_CLIPS_SETTINGS } from "../lib/clipSettings";
+import { downloadOneManaged, sourceFetchFailure } from "../ytdlp/downloadOneManaged";
+import { resolveSourceVideoQuality } from "../ytdlp/downloadFormat";
import type { ClipCopy } from "../lib/clipWindow";
import { isSourceSideCopyFailure, recordFailedCopy, type FailedCopy } from "../lib/copyAttempts-server";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
-import { assertChannelTextReadable } from "../lib/channelMedia";
+import { assertChannelMediaReachable, assertChannelTextReadable } from "../lib/channelMedia";
import { detectPlatform } from "../lib/platform";
-import { findContainingClipWindow } from "../lib/clipWindow-server";
+import {
+ findInSyncContainingClipWindow,
+ judgeClipWindow,
+ probeWindowStreams,
+ setAsideDesyncedWindow,
+} from "../lib/clipWindowSync-server";
+import {
+ desyncedWindowMessage,
+ windowSyncLagText,
+ type ProbedWindowStream,
+} from "../lib/clipWindowSync";
import { channelConfigPlatform } from "../lib/videoId";
import { resolveVideoDirId } from "../lib/videoDir-server.mjs";
import {
@@ -107,6 +125,36 @@ import { findVideoSourceUrl } from "./undownloadedVideos";
// file, and the video's player page opened before its first cut in the run
// (fetchWindowManaged, one page state per run).
//
+// THE SYNC CHECK (lib/clipWindowSync.ts). A window fetched over the network can
+// come out with its picture 1–4 s off its sound (a Rumble HLS seek: 26 of 318
+// Rumble windows on 2026-10-23). So:
+// - A HELD WINDOW is judged before it counts as cached — the tightest
+// covering one first, and only the ones this run would use. A desynced one
+// is SET ASIDE (`<from>-<to>.desynced.<ext>`, never deleted) and the span
+// is missing again, so this same run fills it: from the saved video when
+// one covers it, else from the network. A window whose sidecar already
+// records `sync.ok` for its current size is not probed again.
+// - A WINDOW JUST FETCHED is judged before it counts as fetched. A desynced
+// one is set aside and the item FAILS (`desynced`), naming the remedy:
+// the saved video cuts in sync, a second fetch of the same seek likely
+// does not. The request itself succeeded, so the platform is recorded
+// clean and the network streak is broken as by any other outcome.
+// A window ffprobe cannot read is not judged: kept, as before.
+//
+// THE WHOLE RECORDING (settings.clips.wholeRecordingPlatforms, Rumble by
+// default). A window on such a platform is never fetched by a remote seek —
+// the seek is what put Rumble's pictures off their sounds, and a cut from the
+// saved whole recording measured exactly in sync. A video with no saved
+// container is SAVED ONCE, through the same download "Persist source video"
+// runs (downloadOneManaged, keepSourceVideoOverride + forceMedia, its
+// `persistOrigin` naming who asked and for which clip), paced and held as a
+// network fetch, and every window of it in the run is then cut from it by the
+// saved-video tier — three windows of one video are one download. A whole
+// download that fails fails the video's windows with its own message; it
+// never falls back to a seek. `wholeRecording: false` on a run restores the
+// seek for that run. The editor puts these items on the platform's DOWNLOAD
+// queue (fetchWindowsAction.ts), where a persist runs, not its clip queue.
+//
// A JOB OF THIS KIND SPANS CHANNELS, so runManagedFunction's per-channel text
// guard has no channel to ask. It is asked here instead, once per channel: an
// item on a channel whose text is not readable fails as `unreachable` (its
@@ -171,6 +219,9 @@ export type FetchWindowsFailureClass =
| "unreachable"
// ffmpeg could not cut the window out of a covering saved container.
| "cut-failed"
+ // Fetched, but its picture runs off its sound (lib/clipWindowSync.ts): set
+ // aside, not kept.
+ | "desynced"
// No page URL to fetch from.
| "no-url";
@@ -193,6 +244,8 @@ export type FetchWindowsResult = {
cached: FetchWindowsItem[];
// Cut from the video's saved container, not fetched (release 21 D2).
cut: FetchWindowsItem[];
+ // Videos whose whole recording this run saved (`<slug>/<id>`), each once.
+ saved: string[];
failed: FetchWindowsFailure[];
// Due a fetch but not attempted because the run stopped first (or, with a
// storedUrl mode, because the platform's lookup was limited and the item has
@@ -200,6 +253,10 @@ export type FetchWindowsResult = {
notAttempted: FetchWindowsItem[];
// Of `fetched`: the ones fetched from the stored media URL (release 32 R5).
storedUrl: FetchWindowsItem[];
+ // Every window this run set aside as desynced — held ones it then filled
+ // again, and fresh fetches that failed `desynced` — as
+ // `<slug>/<dir id>/clips/<name>.desynced.<ext>`.
+ setAside: string[];
stopped?: FetchWindowsStop;
};
@@ -244,8 +301,87 @@ export type FetchWindowsDeps = {
recordFailedCopy: (videoDir: string, failed: FailedCopy) => Promise<void>;
// The record's stored media URL (lib/storedMediaUrl-server.ts).
storedMediaUrl: (videoDir: string) => Promise<StoredMediaUrl | null>;
+ // A window's streams for the sync check (lib/clipWindowSync-server.ts), or
+ // null when they cannot be read.
+ probeWindow: (file: string, paths: Paths) => Promise<ProbedWindowStream[] | null>;
+ // The media guard a whole download needs and a window does not: it writes
+ // the big file (persist-videos declares `needsMedia`; this kind cannot).
+ assertMediaReachable: (paths: Paths, slug: string) => Promise<unknown>;
+ // Save a video's whole recording to the saved-video store (the header).
+ saveWholeRecording: (opts: SaveWholeRecordingOpts) => Promise<SaveWholeRecordingResult>;
+};
+
+export type SaveWholeRecordingOpts = {
+ paths: Paths;
+ slug: string;
+ config: ChannelConfig;
+ settings: SiteSettings;
+ url: string;
+ origin: SavedVideoOrigin;
+ onLog: (line: string) => void;
+ signal: AbortSignal;
};
+export type SaveWholeRecordingResult =
+ | { ok: true }
+ | { ok: false; message: string; failureClass: FetchWindowsFailureClass };
+
+// THE PERSIST'S OWN DOWNLOAD (videoActions.ts archiveSourceVideo, persistVideos'
+// defaultDownload): the same downloadOneManaged call, at the channel's (else
+// the global) source-video quality, its failure read by sourceFetchFailure.
+async function saveWholeRecordingManaged(o: SaveWholeRecordingOpts): Promise<SaveWholeRecordingResult> {
+ try {
+ const record = await downloadOneManaged({
+ channelSlug: o.slug,
+ channelConfig: o.config,
+ paths: o.paths,
+ videoUrl: o.url,
+ onLog: o.onLog,
+ signal: o.signal,
+ cookiePolicy: resolveCookiePolicy(o.settings, o.config),
+ inlineTranscribeOnFallback: o.settings.inlineTranscribeOnFallback,
+ globalSkipLiveDownloads: o.settings.skipLiveDownloads,
+ appendArchive: true,
+ keepSourceVideoOverride: true,
+ forceMedia: true,
+ persistOrigin: o.origin,
+ persistFormatPreset: resolveSourceVideoQuality({
+ channel: o.config.sourceVideoQuality,
+ global: o.settings.sourceVideoQuality,
+ }),
+ });
+ const failure = sourceFetchFailure(record);
+ if (!failure) return { ok: true };
+ return {
+ ok: false,
+ message: `the whole recording was not saved: ${failure}`,
+ failureClass:
+ record.failureClass ?? classifyDownloadFailure(failure, parseUnavailableFromStderr(failure)),
+ };
+ } catch (e) {
+ const message = (e as Error).message;
+ return {
+ ok: false,
+ message: `the whole recording was not saved: ${message}`,
+ failureClass: classifyDownloadFailure(message, parseUnavailableFromStderr(message)),
+ };
+ }
+}
+
+// Is this item's window cut from the whole recording? Its platform is listed,
+// the run did not say `wholeRecording: false`, and it is not a copy (find-copy's
+// URL is another recording, fetched as one).
+export function wholeRecordingFor(
+ settings: Pick<SiteSettings, "clips">,
+ platform: string,
+ item: Pick<FetchWindowsItem, "copy">,
+ wholeRecording: boolean | undefined,
+): boolean {
+ if (wholeRecording === false || item.copy) return false;
+ const list = settings.clips?.wholeRecordingPlatforms ?? DEFAULT_CLIPS_SETTINGS.wholeRecordingPlatforms;
+ return list.includes(platform);
+}
+
// Why a platform's page is not asked again in this run.
type PageLimit = { stop: "held" | "cooldown" | "rate-limit"; text: string };
@@ -285,6 +421,9 @@ const DEFAULT_DEPS: FetchWindowsDeps = {
noteGap: (key, gapMs) => notePlatformGap(key, gapMs),
recordFailedCopy,
storedMediaUrl,
+ probeWindow: (file, paths) => probeWindowStreams(file, paths.ffprobeBin),
+ assertMediaReachable: (paths, slug) => assertChannelMediaReachable(paths, slug),
+ saveWholeRecording: saveWholeRecordingManaged,
};
// THE DOOR FOR A GROUP whose platform is held or cooling down (release 32 R5):
@@ -335,6 +474,7 @@ export async function fetchWindows({
gapMs,
minGapSeconds,
storedUrl: storedMode = "never",
+ wholeRecording,
onLog,
signal,
drainSignal,
@@ -355,6 +495,9 @@ export async function fetchWindows({
minGapSeconds?: number;
// Cut from the stored media URL: never (default) | fallback | only (above).
storedUrl?: StoredUrlMode;
+ // false: this run fetches every window by a remote seek, the whole-recording
+ // platforms' too (the header). Absent = the settings decide.
+ wholeRecording?: boolean;
onLog?: (line: string) => void;
signal?: AbortSignal;
drainSignal?: AbortSignal;
@@ -373,9 +516,11 @@ export async function fetchWindows({
fetched: [],
cached: [],
cut: [],
+ saved: [],
failed: [],
notAttempted: [],
storedUrl: [],
+ setAside: [],
};
log(
`Fetch windows: ${work.length} window(s) for ${provenance.requestedBy}` +
@@ -413,8 +558,11 @@ export async function fetchWindows({
message: string,
) => {
result.failed.push({ item, class: cls, message });
- log(` ✗ ${fetchWindowsItemLabel(item)}: ${cls} — ${message}`);
+ // A desynced window's message is a sentence of its own; the class would
+ // only repeat it.
+ log(` ✗ ${fetchWindowsItemLabel(item)}: ${cls === "desynced" ? "" : `${cls} — `}${message}`);
};
+ const probe = (file: string) => deps.probeWindow(file, paths);
const stop = (why: FetchWindowsStop, from: number) => {
result.stopped = why;
result.notAttempted.push(...work.slice(from));
@@ -445,6 +593,39 @@ export async function fetchWindows({
const interrupted = (): FetchWindowsStop | null =>
signal?.aborted ? "cancel" : drainSignal?.aborted ? "drain" : null;
+ // A whole download that failed this run, by video dir: the video's other
+ // windows fail with its message, without a second attempt.
+ const wholeFailed = new Map<string, { message: string; failureClass: FetchWindowsFailureClass }>();
+ const cutFromSaved = async (
+ item: FetchWindowsItem,
+ label: string,
+ videoDir: string,
+ source: Extract<Awaited<ReturnType<typeof savedWindowSource>>, { kind: "covers" }>,
+ ): Promise<void> => {
+ try {
+ const cut = await deps.cutSavedWindow({
+ paths,
+ videoDir,
+ source,
+ 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 the saved video into clips/${cut.file}`);
+ } catch (e) {
+ fail(item, "cut-failed", (e as Error).message);
+ }
+ };
+
// THE RUN'S PAGE STATE for stored-URL cuts (release 32 R9): a video's page
// is opened before its first cut in this run, not before every window.
const pageSession = newStoredPageSession();
@@ -485,8 +666,28 @@ export async function fetchWindows({
const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId);
// THE CACHE FIRST, here rather than only inside fetchWindowManaged, so a
- // cached window owes no pause and is not counted as a network attempt.
- const hit = await findContainingClipWindow(videoDir, item.from, item.to);
+ // cached window owes no pause and is not counted as a network attempt —
+ // and IN SYNC (the header): a desynced held window is set aside here, and
+ // the span goes on below as missing.
+ let held: Awaited<ReturnType<typeof findInSyncContainingClipWindow>>;
+ try {
+ held = await findInSyncContainingClipWindow(videoDir, item.from, item.to, { probe });
+ } catch (e) {
+ // A rename refused in clips/ (read-only, gone mid-run): the window is
+ // neither usable nor out of the way, so the item is not fetched over it.
+ fail(item, "unreachable", `setting a desynced window aside failed: ${(e as Error).message}`);
+ done += 1;
+ progress();
+ continue;
+ }
+ const { hit, desynced } = held;
+ for (const d of desynced) {
+ result.setAside.push(`${item.slug}/${dirId}/clips/${d.setAsideAs}`);
+ log(
+ ` ! ${label}: clips/${d.window.file} — ${windowSyncLagText(d.sync)}; set aside as ` +
+ `${d.setAsideAs}, and the span is fetched again.`,
+ );
+ }
if (hit) {
result.cached.push(item);
log(` = ${label}: cached in clips/${hit.file}`);
@@ -511,28 +712,7 @@ export async function fetchWindows({
continue;
}
if (saved.kind === "covers") {
- try {
- const cut = await deps.cutSavedWindow({
- paths,
- videoDir,
- source: saved,
- 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 the saved video into clips/${cut.file}`);
- } catch (e) {
- fail(item, "cut-failed", (e as Error).message);
- }
+ await cutFromSaved(item, label, videoDir, saved);
done += 1;
progress();
continue;
@@ -553,6 +733,27 @@ export async function fetchWindows({
}
// The cooldown's key, as the single fetch and every download path use it.
const platform = detectPlatform(url) ?? "unknown";
+ const whole = wholeRecordingFor(settings, platform, item, wholeRecording);
+ // This video's whole download already failed this run: no second attempt.
+ const failedWhole = whole ? wholeFailed.get(videoDir) : undefined;
+ if (failedWhole) {
+ fail(item, failedWhole.failureClass, failedWhole.message);
+ done += 1;
+ progress();
+ continue;
+ }
+ // Saved already, but shorter than the window: a second whole download
+ // would be the same recording.
+ if (whole && saved.kind === "not-covering") {
+ fail(
+ item,
+ "cut-failed",
+ `the saved recording ends at ${saved.durationSec.toFixed(2)} s, before this window does`,
+ );
+ done += 1;
+ progress();
+ continue;
+ }
// Paced as the platform the URL points at, which a channel with no
// platform of its own (community-notes holds Rumble videos) does not name.
@@ -577,11 +778,27 @@ export async function fetchWindows({
);
const gapKey = `clip-window:${platform}`;
+ // A whole download writes the big file: the media guard first, before any
+ // pause is spent on it.
+ if (whole) {
+ const away = await deps.assertMediaReachable(paths, item.slug).then(
+ () => null,
+ (e: unknown) => (e as Error).message,
+ );
+ if (away) {
+ wholeFailed.set(videoDir, { message: away, failureClass: "unreachable" });
+ fail(item, "unreachable", away);
+ done += 1;
+ progress();
+ continue;
+ }
+ }
+
// THE STORED MEDIA URL (release 32 R5, lib/storedMediaUrl.ts): asked only
// when the request opted in, for an allowlisted platform whose page this
// item is, and never for a copy (find-copy's URL is another recording).
const stored =
- storedMode !== "never" && !item.copy && isStoredUrlPlatform(platform)
+ !whole && storedMode !== "never" && !item.copy && isStoredUrlPlatform(platform)
? await deps.storedMediaUrl(videoDir).then(
(s) => (s && s.platform === platform ? s : null),
() => null,
@@ -641,6 +858,96 @@ export async function fetchWindows({
}
}
+ // THE WHOLE RECORDING (the header): one download for the video, paced and
+ // held as the fetch above, then this window cut from it. The video's other
+ // windows in the run find it saved and are cut at the saved-video tier.
+ if (whole) {
+ const count = work
+ .slice(i)
+ .filter((w) => w.slug === item.slug && w.id === item.id).length;
+ const name = platform.charAt(0).toUpperCase() + platform.slice(1);
+ log(
+ ` ↧ ${item.slug}/${item.id}: saving the whole recording (${name} windows are cut from it), ` +
+ `then cutting ${count} window(s)`,
+ );
+ networkAttempts += 1;
+ let saveOut: SaveWholeRecordingResult;
+ try {
+ saveOut = await deps.saveWholeRecording({
+ paths,
+ slug: item.slug,
+ config,
+ settings,
+ url,
+ origin: {
+ requestedBy: provenance.requestedBy,
+ ...(provenance.manifest ? { manifest: provenance.manifest } : {}),
+ ...(item.clipId ? { clipId: item.clipId } : {}),
+ reason:
+ item.reason ??
+ `clip windows of a ${name} recording are cut from the whole recording, not a remote seek`,
+ requestedAt,
+ },
+ onLog: fetchLog,
+ signal: fetchSignal,
+ });
+ } finally {
+ deps.noteGap(gapKey, gap);
+ }
+ if (saveOut.ok) {
+ networkStreak = 0;
+ result.saved.push(`${item.slug}/${item.id}`);
+ const clean = await deps.recordClean(platform, paths).catch(() => null);
+ if (clean) log(clean);
+ const after = await deps.savedWindowSource({
+ paths,
+ slug: item.slug,
+ videoDir,
+ from: item.from,
+ to: item.to,
+ });
+ if (after.kind === "covers") await cutFromSaved(item, label, videoDir, after);
+ else if (after.kind === "unreadable") fail(item, "unreachable", after.error);
+ else if (after.kind === "not-covering") {
+ fail(
+ item,
+ "cut-failed",
+ `the saved recording ends at ${after.durationSec.toFixed(2)} s, before this window does`,
+ );
+ } else {
+ fail(item, "cut-failed", "the download reported success, but no saved video is on record");
+ }
+ done += 1;
+ progress();
+ continue;
+ }
+ wholeFailed.set(videoDir, { message: saveOut.message, failureClass: saveOut.failureClass });
+ fail(item, saveOut.failureClass, saveOut.message);
+ done += 1;
+ progress();
+ if (saveOut.failureClass === "rate_limit") {
+ await deps.recordBackoff(platform, paths, "rate_limit").catch(() => {});
+ log(` ${platform} rate-limited this run — stopping; the rest are left for a later run.`);
+ stop("rate-limit", i + 1);
+ break;
+ }
+ if (saveOut.failureClass === "network") {
+ networkStreak += 1;
+ if (networkStreak >= 2) {
+ await deps.recordBackoff(platform, paths, "network").catch(() => {});
+ log(
+ ` ${platform} refused ${networkStreak} fetches in a row — backing it ` +
+ `off and stopping; the rest are left for a later run.`,
+ );
+ stop("network", i + 1);
+ break;
+ }
+ } else {
+ networkStreak = 0;
+ }
+ continue;
+ }
+
const attempt = async (
target: (StoredMediaUrl & { why: StoredUrlWhy }) | null,
): Promise<{ ok: true; r: FetchWindowResult } | { ok: false; e: unknown }> => {
@@ -719,6 +1026,39 @@ export async function fetchWindows({
if (out.ok) {
networkStreak = 0;
+ // THE SYNC CHECK on what the fetch produced (the header): a desynced
+ // window is set aside and the item fails — it is not a window.
+ const got = out.r;
+ const judged = await judgeClipWindow(
+ {
+ file: path.basename(got.file),
+ path: got.file,
+ from: got.from,
+ to: got.to,
+ bytes: got.bytes,
+ provenance: got.provenance,
+ },
+ { probe },
+ );
+ if (judged.sync && !judged.sync.ok) {
+ const aside = await setAsideDesyncedWindow(
+ { file: path.basename(got.file), path: got.file, from: got.from, to: got.to, bytes: got.bytes },
+ judged.sync,
+ ).catch((e: unknown) => e as Error);
+ if (aside instanceof Error) {
+ fail(item, "desynced", `${windowSyncLagText(judged.sync)}, and setting it aside failed: ${aside.message}`);
+ } else {
+ result.setAside.push(`${item.slug}/${dirId}/clips/${aside.file}`);
+ fail(item, "desynced", desyncedWindowMessage(judged.sync, aside.file, platform));
+ }
+ if (!usedStored) {
+ const clean = await deps.recordClean(platform, paths).catch(() => null);
+ if (clean) log(clean);
+ }
+ done += 1;
+ progress();
+ continue;
+ }
(out.r.cached ? result.cached : result.fetched).push(item);
if (usedStored && !out.r.cached) result.storedUrl.push(item);
// A FETCH FROM THE STORED URL SAYS NOTHING ABOUT THE LOOKUP, which is
@@ -785,9 +1125,11 @@ export async function fetchWindows({
`Fetch windows: ${result.fetched.length} fetched` +
(result.storedUrl.length ? ` (${result.storedUrl.length} from stored media URLs)` : "") +
", " +
+ (result.saved.length ? `${result.saved.length} whole recording(s) saved, ` : "") +
(result.cut.length ? `${result.cut.length} cut from saved videos, ` : "") +
`${result.cached.length} cached, ` +
`${result.failed.length} failed` +
+ (result.setAside.length ? `, ${result.setAside.length} set aside as desynced` : "") +
(result.notAttempted.length
? `, ${result.notAttempted.length} not attempted (stopped: ${result.stopped})`
: "") +
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -171,6 +171,7 @@ const TEXT_KINDS = [
"fetch-window",
"fetch-windows",
"evict-clips",
+ "check-windows",
"metadata-scan",
"refresh-metadata",
"browser-lookup",
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -551,6 +551,23 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
needsMedia: false,
needsText: true,
},
+ // FETCHED CLIP WINDOWS, BY SYNC (lib/clipWindowSync.ts): every window in a
+ // video, a channel or the corpus probed, and one whose picture runs off its
+ // sound set aside as `<from>-<to>.desynced.<ext>` (never deleted). The fetch
+ // judges the windows it uses; this is for the ones already on disk.
+ //
+ // `needsText` for evict-clips' reason: `clips/` is the text tier's, never
+ // tiered, and it RENAMES — against an unreadable text tier the walk would
+ // report a clean check of zero windows.
+ "check-windows": {
+ kind: "check-windows",
+ label: "Check fetched windows",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "parallel",
+ needsMedia: false,
+ needsText: true,
+ },
// THE SAVED-VIDEO STORE, ONTO A LOCATION AND BACK. Same mechanism as the
// channel move (relocateDir.ts is literally the same code) over one directory
// that belongs to no channel — so no `channelSlug`, and `needsMedia: false`
diff --git a/common/lib/clipSettings.ts b/common/lib/clipSettings.ts
@@ -0,0 +1,41 @@
+// settings.clips — how clip windows are fetched (controller/fetchWindows.ts).
+// Pure: the type, its defaults, the sanitizer settingsSchema.ts runs it through
+// and the per-field docs SETTINGS.md renders.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export type ClipsSettings = {
+ wholeRecordingPlatforms: string[];
+};
+
+// RUMBLE BY DEFAULT, on the evidence (2026-10-23): a window cut by a remote
+// seek into Rumble's HLS came out with its picture 1–4 s off its sound 26 times
+// in 205; a cut from the saved whole recording measured exactly in sync. One
+// whole download per video is also fewer requests to Rumble than a window
+// fetch per clip.
+export const DEFAULT_CLIPS_SETTINGS: ClipsSettings = {
+ wholeRecordingPlatforms: ["rumble"],
+};
+
+export const CLIPS_SETTINGS_FIELD_DOCS: FieldDocs<ClipsSettings> = {
+ wholeRecordingPlatforms:
+ "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.",
+};
+
+export function sanitizeClips(value: unknown): ClipsSettings {
+ const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>;
+ const raw = r.wholeRecordingPlatforms;
+ if (!Array.isArray(raw)) return { wholeRecordingPlatforms: [...DEFAULT_CLIPS_SETTINGS.wholeRecordingPlatforms] };
+ const out: string[] = [];
+ for (const v of raw) {
+ if (typeof v !== "string") continue;
+ const p = v.trim().toLowerCase();
+ if (p && !out.includes(p)) out.push(p);
+ }
+ return { wholeRecordingPlatforms: out };
+}
diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts
@@ -33,6 +33,10 @@
// it; the filesystem half lives in clipWindow-server.ts.
import path from "node:path";
+import {
+ parseRecordedClipWindowSync,
+ type RecordedClipWindowSync,
+} from "./clipWindowSync";
// The subdirectory inside a video dir that holds fetched windows.
export const CLIPS_DIR_NAME = "clips";
@@ -132,6 +136,47 @@ export function parseClipWindowName(
return { from, to };
}
+// A WINDOW SET ASIDE, never deleted: one whose picture runs off its sound
+// (lib/clipWindowSync.ts) is renamed `<from>-<to>.desynced.<ext>`, its sidecar
+// `<from>-<to>.desynced.json`. The extra segment is what takes it out of every
+// reader at once: `parseClipWindowName` here, umtool's `windowsFromBareNames`
+// (lib/evidenceClip.mjs) and its clips-raw `windowsFromNames` all anchor on the
+// bare `<from>-<to>` stem, the way they already refuse a `.part.mp4`. So a
+// desynced window no longer covers its span — the fetch dedup, the video page
+// and a report video's corpus-window tier all stop seeing it — while the bytes
+// stay on disk for whoever wants to look at what went wrong.
+//
+// Still a CACHE: `evictClipWindows` ages these out by mtime like any window
+// (`parseDesyncedClipWindowName` is what it reads them with), and a rename
+// keeps the fetch's mtime, so a set-aside window goes when its fetch would have.
+export const DESYNCED_CLIP_WINDOW_TAG = "desynced";
+
+export function clipWindowDesyncedFile(from: number, to: number, ext = ".mp4"): string {
+ return `${clipWindowName(from, to)}.${DESYNCED_CLIP_WINDOW_TAG}${ext}`;
+}
+
+export function clipWindowDesyncedSidecar(from: number, to: number): string {
+ return `${clipWindowName(from, to)}.${DESYNCED_CLIP_WINDOW_TAG}.json`;
+}
+
+// The window extension a name wears (`.mp4`, `.mkv`, `.webm`), or null.
+export function clipWindowExtOf(name: string): string | null {
+ return CLIP_WINDOW_EXTS.find((ext) => name.endsWith(ext)) ?? null;
+}
+
+// `<from>-<to>.desynced.<ext>` back into its numbers, or null — the
+// counterpart of `parseClipWindowName` for a set-aside window. Never a sidecar.
+export function parseDesyncedClipWindowName(
+ name: string,
+): { from: number; to: number } | null {
+ const ext = clipWindowExtOf(name);
+ if (!ext) return null;
+ const tag = `.${DESYNCED_CLIP_WINDOW_TAG}`;
+ const stem = name.slice(0, -ext.length);
+ if (!stem.endsWith(tag)) return null;
+ return parseClipWindowName(stem.slice(0, -tag.length));
+}
+
// Who asked for this window, and why. Written beside the file so the video page
// can say "downloaded by umtool for <manifest>/<clipId>, because <reason>"
// without a job log — a job log is pruned, and the window is not.
@@ -175,6 +220,12 @@ export type ClipProvenance = {
// window is fetched again once; twice malformed, it is never kept). Absent when
// the check does not apply.
audioCheck?: ClipAudioCheck;
+ // THE SYNC CHECK'S VERDICT (lib/clipWindowSync.ts) and the bytes it was taken
+ // over: a window whose sidecar records `sync.ok` for its current size is not
+ // probed again. On a set-aside window's `.desynced.json`, the verdict that
+ // set it aside, and when (`setAsideAt`).
+ sync?: RecordedClipWindowSync;
+ setAsideAt?: string;
};
export type ClipAudioCheck = { verdict: "clean" | "partial"; attempts: number };
@@ -241,6 +292,10 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
const attempts = num(ac.attempts);
out.audioCheck = { verdict: ac.verdict, attempts: attempts !== undefined && attempts >= 1 ? attempts : 1 };
}
+ const sync = parseRecordedClipWindowSync(r.sync);
+ if (sync) out.sync = sync;
+ const setAsideAt = str(r.setAsideAt);
+ if (setAsideAt) out.setAsideAt = setAsideAt;
return out;
}
diff --git a/common/lib/clipWindowSync-server.test.ts b/common/lib/clipWindowSync-server.test.ts
@@ -0,0 +1,182 @@
+// The sync check's filesystem half: a real ffprobe over tiny lavfi windows
+// (one in sync, one whose picture starts 3 s in — the Rumble HLS shape), the
+// verdict recorded in the sidecar, and the set-aside every reader then ignores.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/clipWindowSync-server.test.ts
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile, lstat } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import {
+ findInSyncContainingClipWindow,
+ judgeClipWindow,
+ probeWindowStreams,
+ setAsideDesyncedWindow,
+ type WindowStreamProbe,
+} from "./clipWindowSync-server";
+import { findContainingClipWindow, listClipWindows } from "./clipWindow-server";
+import { windowSyncOf } from "./clipWindowSync";
+import { windowsFromBareNames } from "./evidenceClip.mjs";
+
+let ROOT = "";
+let GOOD = "";
+let BAD = "";
+
+function ff(args: string[]): void {
+ execFileSync("ffmpeg", ["-nostdin", "-v", "error", "-y", ...args]);
+}
+
+before(async () => {
+ ROOT = await mkdtemp(path.join(tmpdir(), "window-sync-"));
+ const fx = path.join(ROOT, "fixtures");
+ await mkdir(fx, { recursive: true });
+ GOOD = path.join(fx, "good.mp4");
+ BAD = path.join(fx, "bad.mp4");
+ ff([
+ "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=4",
+ "-f", "lavfi", "-i", "sine=frequency=440:duration=4",
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", GOOD,
+ ]);
+ // The picture 3 s into the container and 3 s longer than the sound.
+ ff([
+ "-itsoffset", "3", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=4",
+ "-f", "lavfi", "-i", "sine=frequency=440:duration=1",
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", BAD,
+ ]);
+});
+
+after(() => rm(ROOT, { recursive: true, force: true }));
+
+let n = 0;
+async function videoDir(): Promise<string> {
+ const dir = path.join(ROOT, String(++n), "channels", "c", "data", "v1");
+ await mkdir(path.join(dir, "clips"), { recursive: true });
+ return dir;
+}
+const clips = (dir: string) => path.join(dir, "clips");
+
+// A probe that counts its calls and asks the real ffprobe.
+function counting(): { probe: WindowStreamProbe; calls: string[] } {
+ const calls: string[] = [];
+ return {
+ calls,
+ probe: async (file) => {
+ calls.push(path.basename(file));
+ return probeWindowStreams(file);
+ },
+ };
+}
+
+test("ffprobe reads the two shapes the rule separates", async () => {
+ const good = await probeWindowStreams(GOOD);
+ assert.ok(good);
+ assert.equal(windowSyncOf(good).ok, true);
+ const bad = await probeWindowStreams(BAD);
+ assert.ok(bad);
+ const s = windowSyncOf(bad, 4);
+ assert.equal(s.ok, false);
+ assert.ok((s.videoStart ?? 0) > 2.9, `video start ${s.videoStart}`);
+ assert.ok(s.lagS >= 2.9, `lag ${s.lagS}`);
+ // Not a media file at all: not judged.
+ const junk = path.join(ROOT, "junk.mp4");
+ await writeFile(junk, "mp4");
+ assert.equal(await probeWindowStreams(junk), null);
+ assert.equal(await probeWindowStreams(GOOD, "/nonexistent/ffprobe"), null);
+});
+
+test("a good verdict is recorded in the sidecar, and not probed again for the same size", async () => {
+ const dir = await videoDir();
+ await copyFile(GOOD, path.join(clips(dir), "10.00-14.00.mp4"));
+ await writeFile(path.join(clips(dir), "10.00-14.00.json"), JSON.stringify({ requestedBy: "umtool", clipId: "r#1" }));
+ const { probe, calls } = counting();
+ const [w] = await listClipWindows(dir);
+ const first = await judgeClipWindow(w, { probe });
+ assert.equal(first.sync?.ok, true);
+ assert.equal(first.fromRecord, false);
+ const side = JSON.parse(await readFile(path.join(clips(dir), "10.00-14.00.json"), "utf8"));
+ assert.equal(side.clipId, "r#1", "the sidecar's other fields are kept");
+ assert.equal(side.sync.ok, true);
+ assert.equal(side.sync.bytes, w.bytes);
+ const [again] = await listClipWindows(dir);
+ assert.equal(again.provenance?.sync?.ok, true);
+ const second = await judgeClipWindow(again, { probe });
+ assert.equal(second.fromRecord, true);
+ assert.deepEqual(calls, ["10.00-14.00.mp4"], "one probe for two judgements");
+ // The bytes changed: probed again.
+ await judgeClipWindow({ ...again, bytes: again.bytes + 1 }, { probe });
+ assert.equal(calls.length, 2);
+ // `record: false` writes nothing — a window with no sidecar stays without one.
+ await copyFile(GOOD, path.join(clips(dir), "20.00-24.00.mp4"));
+ const bare = (await listClipWindows(dir)).find((x) => x.from === 20)!;
+ await judgeClipWindow(bare, { probe, record: false });
+ assert.ok(!(await readdir(clips(dir))).includes("20.00-24.00.json"));
+ // ...and with recording on, gets one holding only the verdict — still no provenance.
+ await judgeClipWindow(bare, { probe });
+ const after = (await listClipWindows(dir)).find((x) => x.from === 20)!;
+ assert.equal(after.provenance, null);
+});
+
+test("set aside: renamed with its sidecar (verdict + setAsideAt), and no reader sees it", async () => {
+ const dir = await videoDir();
+ await copyFile(BAD, path.join(clips(dir), "10.00-14.00.mp4"));
+ await writeFile(path.join(clips(dir), "10.00-14.00.json"), JSON.stringify({ requestedBy: "umtool", reason: "why" }));
+ // An older set-aside of the same span, in another container: replaced.
+ await writeFile(path.join(clips(dir), "10.00-14.00.desynced.mkv"), "old");
+ const [w] = await listClipWindows(dir);
+ const { sync } = await judgeClipWindow(w, { probe: (f) => probeWindowStreams(f) });
+ assert.equal(sync?.ok, false);
+ const at = new Date("2026-10-23T12:00:00.000Z");
+ const aside = await setAsideDesyncedWindow(w, sync!, at);
+ assert.equal(aside.file, "10.00-14.00.desynced.mp4");
+ assert.deepEqual((await readdir(clips(dir))).sort(), ["10.00-14.00.desynced.json", "10.00-14.00.desynced.mp4"]);
+ const side = JSON.parse(await readFile(path.join(clips(dir), "10.00-14.00.desynced.json"), "utf8"));
+ assert.equal(side.requestedBy, "umtool");
+ assert.equal(side.reason, "why");
+ assert.equal(side.sync.ok, false);
+ assert.equal(side.sync.bytes, w.bytes);
+ assert.equal(side.setAsideAt, at.toISOString());
+ // Every reader: the editor's lister and its dedup, and umtool's bare-name tier.
+ assert.deepEqual(await listClipWindows(dir), []);
+ assert.equal(await findContainingClipWindow(dir, 11, 13), null);
+ assert.deepEqual(windowsFromBareNames(await readdir(clips(dir)), clips(dir)), []);
+});
+
+test("a window that is a link is renamed as the link, never through it", async () => {
+ const dir = await videoDir();
+ const target = path.join(ROOT, `target-${n}.mp4`);
+ await copyFile(BAD, target);
+ await symlink(target, path.join(clips(dir), "10.00-14.00.mp4"));
+ const [w] = await listClipWindows(dir);
+ const { sync } = await judgeClipWindow(w, { probe: (f) => probeWindowStreams(f) });
+ await setAsideDesyncedWindow(w, sync!);
+ const st = await lstat(path.join(clips(dir), "10.00-14.00.desynced.mp4"));
+ assert.ok(st.isSymbolicLink());
+ assert.ok((await lstat(target)).isFile(), "the target is untouched, under its own name");
+});
+
+test("the in-sync finder skips a desynced tightest window for a good wider one, probing only what it walks", async () => {
+ const dir = await videoDir();
+ await copyFile(BAD, path.join(clips(dir), "10.00-14.00.mp4"));
+ await copyFile(GOOD, path.join(clips(dir), "0.00-60.00.mp4"));
+ await copyFile(GOOD, path.join(clips(dir), "100.00-104.00.mp4"));
+ const { probe, calls } = counting();
+ // A planner's look: judged, nothing renamed.
+ const look = await findInSyncContainingClipWindow(dir, 11, 13, { probe, setAside: false });
+ assert.equal(look.hit?.file, "0.00-60.00.mp4");
+ assert.deepEqual(look.desynced.map((d) => [d.window.file, d.setAsideAs]), [["10.00-14.00.mp4", null]]);
+ assert.ok((await readdir(clips(dir))).includes("10.00-14.00.mp4"));
+ // The run's: set aside.
+ const r = await findInSyncContainingClipWindow(dir, 11, 13, { probe });
+ assert.equal(r.hit?.file, "0.00-60.00.mp4");
+ assert.deepEqual(r.desynced.map((d) => d.setAsideAs), ["10.00-14.00.desynced.mp4"]);
+ assert.ok(!calls.includes("100.00-104.00.mp4"), "a window that does not cover the span is never probed");
+ // Nothing else covers: the span is missing.
+ await rm(path.join(clips(dir), "0.00-60.00.mp4"));
+ assert.equal((await findInSyncContainingClipWindow(dir, 11, 13, { probe })).hit, null);
+ // A window ffprobe cannot read is kept and answers, as before.
+ await writeFile(path.join(clips(dir), "5.00-20.00.mp4"), "mp4");
+ assert.equal((await findInSyncContainingClipWindow(dir, 11, 13, { probe })).hit?.file, "5.00-20.00.mp4");
+});
diff --git a/common/lib/clipWindowSync-server.ts b/common/lib/clipWindowSync-server.ts
@@ -0,0 +1,181 @@
+// The filesystem half of the sync check: probe a window, record a good
+// verdict in its sidecar, set a desynced one aside. The rule and its measured
+// numbers are lib/clipWindowSync.ts.
+
+import path from "node:path";
+import { readFile, rename, rm } from "node:fs/promises";
+import { execa } from "execa";
+import { writeJsonAtomic } from "./jsonFile-server";
+import {
+ CLIP_WINDOW_EXTS,
+ clipWindowContains,
+ clipWindowDesyncedFile,
+ clipWindowDesyncedSidecar,
+ clipWindowExtOf,
+ clipWindowSidecar,
+} from "./clipWindow";
+import { listClipWindows, type ClipWindow } from "./clipWindow-server";
+import {
+ parseRecordedClipWindowSync,
+ windowSyncOf,
+ type ClipWindowSync,
+ type ProbedWindowStream,
+ type RecordedClipWindowSync,
+} from "./clipWindowSync";
+
+// A window's streams, or null when they cannot be read. Injectable so tests
+// decide what a window holds without a real one.
+export type WindowStreamProbe = (file: string) => Promise<ProbedWindowStream[] | null>;
+
+// ONE ffprobe of the container's stream headers — no decode, so it costs a
+// fraction of a second on a window even on a platter. Null when ffprobe is
+// missing, fails, times out or prints something unparseable: a window this
+// cannot read is NOT JUDGED (kept, nothing recorded), never set aside on a
+// guess. Whether the file is corrupt is the audio check's question, not this.
+export async function probeWindowStreams(
+ file: string,
+ ffprobeBin = "ffprobe",
+ opts: { timeoutMs?: number; signal?: AbortSignal } = {},
+): Promise<ProbedWindowStream[] | null> {
+ try {
+ const r = await execa(
+ ffprobeBin,
+ [
+ "-v", "error",
+ "-show_entries", "stream=codec_type,start_time,duration:stream_disposition=attached_pic",
+ "-of", "json",
+ file,
+ ],
+ { reject: false, timeout: opts.timeoutMs ?? 15_000, ...(opts.signal ? { cancelSignal: opts.signal } : {}) },
+ );
+ if (r.exitCode !== 0) return null;
+ const doc = JSON.parse(String(r.stdout)) as { streams?: unknown };
+ return Array.isArray(doc.streams) ? (doc.streams as ProbedWindowStream[]) : null;
+ } catch {
+ return null;
+ }
+}
+
+export function ffprobeWindowProbe(ffprobeBin = "ffprobe"): WindowStreamProbe {
+ return (file) => probeWindowStreams(file, ffprobeBin);
+}
+
+async function readRawSidecar(file: string): Promise<Record<string, unknown> | null> {
+ const text = await readFile(file, "utf8").catch(() => null);
+ if (text === null) return null;
+ try {
+ const raw = JSON.parse(text) as unknown;
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : null;
+ } catch {
+ return null;
+ }
+}
+
+const sidecarOf = (win: Pick<ClipWindow, "path" | "from" | "to">) =>
+ path.join(path.dirname(win.path), clipWindowSidecar(win.from, win.to));
+
+export type ClipWindowJudgement = {
+ // Null: the window could not be probed, and is kept as it is.
+ sync: ClipWindowSync | null;
+ // Answered by the sidecar's recorded verdict, not a probe.
+ fromRecord: boolean;
+};
+
+// JUDGE ONE WINDOW. A sidecar that records `sync.ok` for the window's CURRENT
+// size answers without a probe; anything else is probed. A good verdict is
+// recorded in the sidecar (merged into it as it stands — fields this module
+// does not know are kept), unless `record: false` (a dry run writes nothing).
+// A window with no sidecar gets one holding only the verdict: it parses as no
+// provenance, exactly as the missing file did.
+export async function judgeClipWindow(
+ win: ClipWindow,
+ opts: { probe: WindowStreamProbe; record?: boolean; now?: () => Date },
+): Promise<ClipWindowJudgement> {
+ const sidecar = sidecarOf(win);
+ const raw = await readRawSidecar(sidecar);
+ const recorded = parseRecordedClipWindowSync(raw?.sync);
+ if (recorded?.ok && recorded.bytes === win.bytes) return { sync: recorded, fromRecord: true };
+ const streams = await opts.probe(win.path);
+ if (!streams) return { sync: null, fromRecord: false };
+ const sync = windowSyncOf(streams, win.to - win.from);
+ if (sync.ok && opts.record !== false) {
+ const entry: RecordedClipWindowSync = {
+ ...sync,
+ bytes: win.bytes,
+ checkedAt: (opts.now?.() ?? new Date()).toISOString(),
+ };
+ // A failed write costs the next run one probe, nothing else.
+ await writeJsonAtomic(sidecar, { ...(raw ?? {}), sync: entry }).catch(() => {});
+ }
+ return { sync, fromRecord: false };
+}
+
+// SET A DESYNCED WINDOW ASIDE: `<from>-<to>.<ext>` → `<from>-<to>.desynced.<ext>`,
+// its sidecar → `<from>-<to>.desynced.json` with the verdict and `setAsideAt`.
+// Never a delete: the bytes are evidence of what the source served, and
+// evictClipWindows ages them out as the cache they are.
+//
+// THE PATH ITSELF IS RENAMED, never a resolved target: `clips/` is never
+// tiered, but whatever a window is — a file, or a link someone made — it stays
+// that, under its new name, beside where it was. A window set aside earlier
+// for the same span (any extension) is replaced: the newest verdict is the one
+// worth keeping. The media goes first, so the window leaves every reader in one
+// step; a crash before the sidecar moves leaves a sidecar with no window, which
+// nothing reads and the next fetch of the span overwrites.
+export async function setAsideDesyncedWindow(
+ win: Pick<ClipWindow, "path" | "file" | "from" | "to" | "bytes">,
+ sync: ClipWindowSync,
+ now: Date = new Date(),
+): Promise<{ file: string; path: string }> {
+ const dir = path.dirname(win.path);
+ const ext = clipWindowExtOf(win.file) ?? ".mp4";
+ const file = clipWindowDesyncedFile(win.from, win.to, ext);
+ const dest = path.join(dir, file);
+ for (const other of CLIP_WINDOW_EXTS) {
+ if (other !== ext) await rm(path.join(dir, clipWindowDesyncedFile(win.from, win.to, other)), { force: true });
+ }
+ await rename(win.path, dest);
+ const sidecar = sidecarOf(win);
+ const raw = await readRawSidecar(sidecar);
+ const at = now.toISOString();
+ await writeJsonAtomic(path.join(dir, clipWindowDesyncedSidecar(win.from, win.to)), {
+ ...(raw ?? {}),
+ sync: { ...sync, bytes: win.bytes, checkedAt: at },
+ setAsideAt: at,
+ });
+ await rm(sidecar, { force: true });
+ return { file, path: dest };
+}
+
+export type DesyncedClipWindow = {
+ window: ClipWindow;
+ sync: ClipWindowSync;
+ // The name it was set aside as, or null when the caller asked for none.
+ setAsideAs: string | null;
+};
+
+// THE TIGHTEST CONTAINING WINDOW THAT IS IN SYNC — `findContainingClipWindow`
+// with the check in front of its answer. Candidates are judged tightest first
+// and the walk stops at the first good one, so a run probes only the windows it
+// would actually use. A desynced one is set aside (unless `setAside: false`:
+// a planner that only needs to know whether the span is held) and the next
+// candidate is asked; none left is null — the span is missing, and the caller
+// goes to the saved-video tier, then the network, as for any missing span.
+export async function findInSyncContainingClipWindow(
+ videoDir: string,
+ from: number,
+ to: number,
+ opts: { probe: WindowStreamProbe; setAside?: boolean; record?: boolean },
+): Promise<{ hit: ClipWindow | null; desynced: DesyncedClipWindow[] }> {
+ const candidates = (await listClipWindows(videoDir))
+ .filter((w) => clipWindowContains(w, from, to))
+ .sort((a, b) => a.to - a.from - (b.to - b.from));
+ const desynced: DesyncedClipWindow[] = [];
+ for (const w of candidates) {
+ const { sync } = await judgeClipWindow(w, { probe: opts.probe, record: opts.record });
+ if (!sync || sync.ok) return { hit: w, desynced };
+ const aside = opts.setAside === false ? null : await setAsideDesyncedWindow(w, sync);
+ desynced.push({ window: w, sync, setAsideAs: aside?.file ?? null });
+ }
+ return { hit: null, desynced };
+}
diff --git a/common/lib/clipWindowSync.test.ts b/common/lib/clipWindowSync.test.ts
@@ -0,0 +1,119 @@
+// The sync verdict on the numbers measured on the live corpus (2026-10-23).
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/clipWindowSync.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ desyncedWindowMessage,
+ parseRecordedClipWindowSync,
+ windowSyncOf,
+ WINDOW_SYNC_MAX_DURATION_GAP_S,
+ WINDOW_SYNC_MAX_START_S,
+ type ProbedWindowStream,
+} from "./clipWindowSync";
+import {
+ clipWindowDesyncedFile,
+ clipWindowDesyncedSidecar,
+ parseClipProvenance,
+ parseClipWindowName,
+ parseDesyncedClipWindowName,
+} from "./clipWindow";
+
+// ffprobe prints its numbers as strings.
+const streams = (v: [string, string] | null, a: [string, string] | null): ProbedWindowStream[] => [
+ ...(v ? [{ codec_type: "video", start_time: v[0], duration: v[1] }] : []),
+ ...(a ? [{ codec_type: "audio", start_time: a[0], duration: a[1] }] : []),
+];
+
+test("the costco window — video 3.200/93.73, audio 3.140/90.58 — is desynced", () => {
+ const s = windowSyncOf(streams(["3.200000", "93.733000"], ["3.140000", "90.580000"]), 93.72);
+ assert.equal(s.ok, false);
+ assert.equal(s.videoStart, 3.2);
+ assert.equal(s.audioStart, 3.14);
+ assert.equal(s.videoDuration, 93.733);
+ assert.equal(s.audioDuration, 90.58);
+ assert.equal(s.requestedLength, 93.72);
+ assert.equal(s.lagS, 3.2);
+ assert.match(s.reason ?? "", /the video track starts 3\.20 s in/);
+ assert.match(s.reason ?? "", /the audio track starts 3\.14 s in/);
+ assert.match(s.reason ?? "", /the video runs 3\.15 s longer than the audio/);
+});
+
+test("the good shape — starts ≤ 0.07 s, durations within 0.03 s — is in sync", () => {
+ const s = windowSyncOf(streams(["0.067000", "30.030000"], ["0.000000", "30.000000"]), 30);
+ assert.equal(s.ok, true);
+ assert.equal(s.reason, undefined);
+ assert.equal(s.lagS, 0.07);
+ // An encoder's negative priming start is not "in".
+ assert.equal(windowSyncOf(streams(["0.000000", "10.0"], ["-0.021333", "10.01"])).ok, true);
+});
+
+test("the borderline 0.50/0.43 window is desynced", () => {
+ const s = windowSyncOf(streams(["0.500000", "40.0"], ["0.430000", "40.0"]));
+ assert.equal(s.ok, false);
+ assert.equal(s.lagS, 0.5);
+});
+
+test("each half of the signature is enough on its own", () => {
+ assert.equal(WINDOW_SYNC_MAX_START_S, 0.25);
+ assert.equal(WINDOW_SYNC_MAX_DURATION_GAP_S, 0.25);
+ // Starts clean, durations apart.
+ const gap = windowSyncOf(streams(["0.0", "20.0"], ["0.0", "19.5"]));
+ assert.equal(gap.ok, false);
+ assert.match(gap.reason ?? "", /the video runs 0\.50 s longer than the audio/);
+ // Only the audio starts late.
+ assert.equal(windowSyncOf(streams(["0.0", "20.0"], ["0.3", "20.0"])).ok, false);
+ // A duration ffprobe has no number for (Matroska) is not a gap.
+ assert.equal(windowSyncOf(streams(["0.0", "N/A"], ["0.0", "N/A"])).ok, true);
+});
+
+test("an audio-only (or video-only) window is not judged", () => {
+ const audio = windowSyncOf(streams(null, ["2.0", "30.0"]));
+ assert.equal(audio.ok, true);
+ assert.match(audio.reason ?? "", /no video track: not judged/);
+ const video = windowSyncOf(streams(["2.0", "30.0"], null));
+ assert.equal(video.ok, true);
+ assert.match(video.reason ?? "", /no audio track: not judged/);
+ // Cover art is not a picture track.
+ const art = windowSyncOf([
+ { codec_type: "video", start_time: "5.0", duration: "1", disposition: { attached_pic: 1 } },
+ { codec_type: "audio", start_time: "0.0", duration: "30" },
+ ]);
+ assert.equal(art.ok, true);
+ assert.match(art.reason ?? "", /no video track/);
+});
+
+test("the recorded verdict round-trips through a sidecar; a malformed one is no verdict", () => {
+ const s = windowSyncOf(streams(["0.0", "20.0"], ["0.0", "20.0"]), 20);
+ const rec = { ...s, bytes: 1234, checkedAt: "2026-10-23T00:00:00.000Z" };
+ assert.deepEqual(parseRecordedClipWindowSync(JSON.parse(JSON.stringify(rec))), rec);
+ assert.equal(parseRecordedClipWindowSync({ ok: true }), undefined);
+ assert.equal(parseRecordedClipWindowSync("yes"), undefined);
+ const prov = parseClipProvenance({ requestedBy: "umtool", sync: rec, setAsideAt: "2026-10-23T01:00:00.000Z" });
+ assert.deepEqual(prov?.sync, rec);
+ assert.equal(prov?.setAsideAt, "2026-10-23T01:00:00.000Z");
+});
+
+test("the message names the lag, the cause, the new name and the remedy", () => {
+ assert.equal(
+ desyncedWindowMessage({ lagS: 3.14 }, "10.00-20.00.desynced.mp4", "rumble"),
+ 'the picture runs 3.1 s off the sound (a Rumble HLS seek); set aside as 10.00-20.00.desynced.mp4 — ' +
+ 'save the whole recording ("Persist source video") and fetch again to cut it from the saved video',
+ );
+ assert.match(desyncedWindowMessage({ lagS: 2 }, "x", "youtube"), /\(a seek into the source's stream\)/);
+});
+
+test("a set-aside name is no window to the window parser, and parses as a set-aside one", () => {
+ assert.equal(clipWindowDesyncedFile(12, 42), "12.00-42.00.desynced.mp4");
+ assert.equal(clipWindowDesyncedFile(12, 42, ".mkv"), "12.00-42.00.desynced.mkv");
+ assert.equal(clipWindowDesyncedSidecar(12, 42), "12.00-42.00.desynced.json");
+ for (const name of ["12.00-42.00.desynced.mp4", "12.00-42.00.desynced.mkv", "12.00-42.00.desynced.json"]) {
+ assert.equal(parseClipWindowName(name), null, name);
+ }
+ assert.deepEqual(parseDesyncedClipWindowName("12.00-42.00.desynced.mp4"), { from: 12, to: 42 });
+ assert.deepEqual(parseDesyncedClipWindowName("12.00-42.00.desynced.webm"), { from: 12, to: 42 });
+ for (const name of ["12.00-42.00.mp4", "12.00-42.00.desynced.json", "12.00-42.00.desynced", "x.desynced.mp4"]) {
+ assert.equal(parseDesyncedClipWindowName(name), null, name);
+ }
+});
diff --git a/common/lib/clipWindowSync.ts b/common/lib/clipWindowSync.ts
@@ -0,0 +1,174 @@
+// IS A FETCHED WINDOW'S PICTURE WHERE ITS SOUND IS?
+//
+// A clip window (lib/clipWindow.ts) fetched over the network is cut by yt-dlp
+// with `--download-sections "*from-to" --force-keyframes-at-cuts`. Over
+// Rumble's HLS — muxed renditions, served as byte ranges of a `.tar` — that
+// seek does not always land both tracks on the same second. Measured on the
+// live corpus 2026-10-23: 26 of 318 Rumble windows came out with the PICTURE
+// shifted against the SOUND by 1–4 s. Cross-correlated against overlapping
+// good windows, the audio is placed correctly and the video shows content
+// about (video start_time) seconds LATER than it should — a window a viewer
+// sees as a dub, cut into a report video as a lie about who said what when.
+//
+// THE FFPROBE SIGNATURE SEPARATES THE TWO CLEANLY, which is why this can be a
+// rule and not a review step:
+//
+// bad (26) video start_time 1.03–3.83 s, the audio's about the same, and
+// video duration − audio duration ≈ the same 1–3.8 s. The costco
+// window: video start 3.200 dur 93.73, audio start 3.140 dur
+// 90.58, for a requested length of 93.72.
+// good (292) video start_time ≤ 0.07 s and |video dur − audio dur| ≤ 0.03 s
+// — one borderline at 0.50/0.43, which this calls desynced.
+//
+// A cut taken locally from a saved whole recording (the saved-video tier,
+// lib/savedVideoWindow-server.ts) is exactly in sync: the remedy for a
+// desynced window is that tier, not a second network fetch of the same seek.
+//
+// PURE: the probe's JSON in, a verdict out, so the verdict is testable on the
+// measured numbers. Running ffprobe, and setting a desynced window aside, is
+// clipWindowSync-server.ts.
+
+// A track starting more than this far into the window is not where it was
+// asked to be. The good windows' worst was 0.07 s; the bad ones' best 1.03 s.
+export const WINDOW_SYNC_MAX_START_S = 0.25;
+// The two tracks' durations differing by more than this is the other half of
+// the same signature (good: ≤ 0.03 s; bad: 1–3.8 s, matching the start).
+export const WINDOW_SYNC_MAX_DURATION_GAP_S = 0.25;
+
+// One stream of `ffprobe -show_entries stream=codec_type,start_time,duration
+// -of json`: ffprobe prints the numbers as strings, and "N/A" (or nothing) for
+// one a container does not carry — a Matroska stream's duration, typically.
+export type ProbedWindowStream = {
+ codec_type?: string;
+ start_time?: string | number;
+ duration?: string | number;
+ disposition?: { attached_pic?: number };
+};
+
+export type ClipWindowSync = {
+ // False only for a window this rule has JUDGED and found desynced. A window
+ // it cannot judge (no audio track — audio-only windows exist — or no video
+ // track) is ok, with `reason` saying so.
+ ok: boolean;
+ // Null where the track is absent or ffprobe printed no number for it.
+ videoStart: number | null;
+ audioStart: number | null;
+ videoDuration: number | null;
+ audioDuration: number | null;
+ // How far apart the picture and the sound are, in seconds: the largest of
+ // the two starts and the duration gap (2 dp). An estimate — the measured
+ // shift sat at about the video's start_time — and the number every log line
+ // and sidecar quotes.
+ lagS: number;
+ // The window's own length (`to − from`), when the caller knew it.
+ requestedLength?: number;
+ reason?: string;
+};
+
+// The verdict as a sidecar records it: the bytes it was taken over (a window
+// whose size changed has to be probed again) and when.
+export type RecordedClipWindowSync = ClipWindowSync & {
+ bytes: number;
+ checkedAt: string;
+};
+
+const numOrNull = (v: unknown): number | null => {
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number.parseFloat(v) : Number.NaN;
+ return Number.isFinite(n) ? n : null;
+};
+const round2 = (n: number) => Math.round(n * 100) / 100;
+
+export function windowSyncOf(
+ streams: readonly ProbedWindowStream[],
+ requestedLength?: number,
+): ClipWindowSync {
+ const video = streams.find((s) => s.codec_type === "video" && !s.disposition?.attached_pic);
+ const audio = streams.find((s) => s.codec_type === "audio");
+ const videoStart = numOrNull(video?.start_time);
+ const audioStart = numOrNull(audio?.start_time);
+ const videoDuration = numOrNull(video?.duration);
+ const audioDuration = numOrNull(audio?.duration);
+ const base = {
+ videoStart,
+ audioStart,
+ videoDuration,
+ audioDuration,
+ ...(requestedLength !== undefined && Number.isFinite(requestedLength)
+ ? { requestedLength: round2(requestedLength) }
+ : {}),
+ };
+ // NOT JUDGED: a window with one track has nothing to be out of sync with.
+ if (!video || !audio) {
+ return {
+ ok: true,
+ ...base,
+ lagS: 0,
+ reason: !video && !audio ? "no tracks: not judged" : !audio ? "no audio track: not judged" : "no video track: not judged",
+ };
+ }
+ const gap =
+ videoDuration !== null && audioDuration !== null ? Math.abs(videoDuration - audioDuration) : null;
+ const offences: string[] = [];
+ if (videoStart !== null && videoStart > WINDOW_SYNC_MAX_START_S) {
+ offences.push(`the video track starts ${videoStart.toFixed(2)} s in`);
+ }
+ if (audioStart !== null && audioStart > WINDOW_SYNC_MAX_START_S) {
+ offences.push(`the audio track starts ${audioStart.toFixed(2)} s in`);
+ }
+ if (gap !== null && gap > WINDOW_SYNC_MAX_DURATION_GAP_S) {
+ const longer = (videoDuration as number) > (audioDuration as number) ? "video" : "audio";
+ offences.push(
+ `the ${longer} runs ${gap.toFixed(2)} s longer than the ${longer === "video" ? "audio" : "video"}`,
+ );
+ }
+ // Negative starts (an encoder's priming samples) are not "in", and say
+ // nothing about the lag.
+ const lagS = round2(Math.max(0, videoStart ?? 0, audioStart ?? 0, gap ?? 0));
+ if (offences.length === 0) return { ok: true, ...base, lagS };
+ return { ok: false, ...base, lagS, reason: offences.join("; ") };
+}
+
+// The sidecar's `sync`, read back. Tolerant like every sidecar parse here: a
+// hand-edited or half-written one is "no verdict", which only means one probe.
+export function parseRecordedClipWindowSync(raw: unknown): RecordedClipWindowSync | undefined {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
+ const r = raw as Record<string, unknown>;
+ if (typeof r.ok !== "boolean") return undefined;
+ const bytes = numOrNull(r.bytes);
+ const lagS = numOrNull(r.lagS);
+ if (bytes === null || lagS === null || typeof r.checkedAt !== "string") return undefined;
+ const n = (k: string) => (typeof r[k] === "number" && Number.isFinite(r[k]) ? (r[k] as number) : null);
+ const requestedLength = n("requestedLength");
+ return {
+ ok: r.ok,
+ videoStart: n("videoStart"),
+ audioStart: n("audioStart"),
+ videoDuration: n("videoDuration"),
+ audioDuration: n("audioDuration"),
+ lagS,
+ ...(requestedLength !== null ? { requestedLength } : {}),
+ ...(typeof r.reason === "string" && r.reason ? { reason: r.reason } : {}),
+ bytes,
+ checkedAt: r.checkedAt,
+ };
+}
+
+// "the picture runs 3.2 s off the sound"
+export function windowSyncLagText(sync: Pick<ClipWindowSync, "lagS">): string {
+ return `the picture runs ${sync.lagS.toFixed(1)} s off the sound`;
+}
+
+// THE SENTENCE A DESYNCED FETCH FAILS WITH — the batch's log line, the single
+// fetch's job error. It names the remedy: the saved-video tier cuts in sync, and
+// a second network fetch of the same seek is likely to come out the same.
+export function desyncedWindowMessage(
+ sync: Pick<ClipWindowSync, "lagS">,
+ setAsideAs: string,
+ platform?: string,
+): string {
+ const cause = platform === "rumble" ? "a Rumble HLS seek" : "a seek into the source's stream";
+ return (
+ `${windowSyncLagText(sync)} (${cause}); set aside as ${setAsideAs} — save the whole ` +
+ `recording ("Persist source video") and fetch again to cut it from the saved video`
+ );
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -13,6 +13,7 @@
import {
ARCHIVE_ORG_SETTINGS_FIELD_DOCS,
ARCHIVES_SETTINGS_FIELD_DOCS,
+ CLIPS_SETTINGS_FIELD_DOCS,
ARCHIVE_STORAGE_SETTINGS_FIELD_DOCS,
ATTRIBUTION_SETTINGS_FIELD_DOCS,
BACKFILL_SETTINGS_FIELD_DOCS,
@@ -318,6 +319,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "generation.triage", docs: GENERATION_TRIAGE_FIELD_DOCS, defaults: fromObject(d.generation.triage) },
{ path: "generation.frames", docs: GENERATION_FRAMES_FIELD_DOCS, defaults: fromObject(d.generation.frames) },
],
+ clips: [
+ {
+ path: "clips",
+ docs: CLIPS_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.clips),
+ },
+ ],
};
}
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -33,6 +33,7 @@ import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent";
import type { SeederSettings } from "./seederSettings";
import type { TtsSettings } from "./ttsSettings";
import type { ArchivesSettings } from "./archives/settings";
+import type { ClipsSettings } from "./clipSettings";
import type { GenerationSettings } from "./generationSettings";
import type {
AttributionSettings,
@@ -117,6 +118,8 @@ type PreSchemaSiteSettings = {
tts: TtsSettings;
// Report and video generation (release 27 S6).
generation: GenerationSettings;
+ // How clip windows are fetched: the whole-recording platforms.
+ clips: ClipsSettings;
};
// Bracketed so the conditional does not distribute (see commit 8c43231).
@@ -167,6 +170,7 @@ test("SiteSettings keeps its 41 fields, in file order", () => {
"seeder",
"tts",
"generation",
+ "clips",
]);
// A parsed object carries every key, in that order — writeSettings writes
// exactly this, so the order is the on-disk order.
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -81,6 +81,7 @@ import { sanitizeSeeder, type SeederSettings } from "./seederSettings";
export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSettings";
import { sanitizeTts, type TtsSettings } from "./ttsSettings";
import { sanitizeArchives, type ArchivesSettings } from "./archives/settings";
+import { sanitizeClips, type ClipsSettings } from "./clipSettings";
import { sanitizeGeneration, type GenerationSettings } from "./generationSettings";
export {
GENERATION_CAPS_FIELD_DOCS,
@@ -99,6 +100,7 @@ export {
} from "./generationSettings";
export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings";
+export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings";
import {
DEFAULT_COOKIE_MODE,
isCookieMode,
@@ -1929,6 +1931,9 @@ export const siteSettingsSchema = z.object({
generation: settingsField((v): GenerationSettings => sanitizeGeneration(v)).describe(
"Report and video generation (release 27): where each task runs (`code` = Claude Code, `api` = the Claude API with a key, `local` = the local model), the models, the spend caps (a job's default, its max, the day's), the API key FILE (never the key), and where video projects live. A generation runs as a `report-draft` editor job (`pnpm ops report-draft`) on `draft:api` or `draft:local`. See GenerationSettings and common/lib/generationSettings.ts.",
),
+ clips: settingsField((v): ClipsSettings => sanitizeClips(v)).describe(
+ "How clip windows are fetched (controller/fetchWindows.ts): the platforms whose windows are cut from the saved WHOLE recording rather than by a remote seek — Rumble by default, because its HLS seek put the picture 1–4 s off the sound (lib/clipWindowSync.ts). See ClipsSettings.",
+ ),
});
export type SiteSettings = z.infer<typeof siteSettingsSchema>;
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **Rumble clip windows are cut from the whole recording, and a window whose picture runs off its sound is set aside.** A window fetched by seeking into Rumble's stream came out with the picture 1 to 4 seconds behind the sound 26 times out of 318, while a cut from a saved whole recording was exactly in sync. Fetch windows (`pnpm ops fetch-windows`, a site's **Fetch missing evidence**, umtool) now saves a Rumble video once, the way **Persist source video** does and on Rumble's download queue, then cuts every window of it from that copy: three clips of one video are one download, logged as "↧ <channel>/<id>: saving the whole recording (Rumble windows are cut from it), then cutting 3 window(s)". If that download fails, its windows fail with its message and nothing falls back to a seek. Which platforms work this way is `clips.wholeRecordingPlatforms` in settings.json (default `["rumble"]`), and `"wholeRecording": false` on a run seeks as before. Every window fetched by a seek, on any platform, is now checked with ffprobe for a picture or sound that starts late or a picture and sound of different lengths. A bad one is renamed `<from>-<to>.desynced.mp4`, never deleted, and fails with "the picture runs 3.2 s off the sound (a Rumble HLS seek); set aside as … — save the whole recording ("Persist source video") and fetch again to cut it from the saved video". A bad window already on disk is set aside when a fetch would have used it, and the same run fetches those seconds again. No reader (the video page, umtool, report videos) sees a set-aside window, and **Evict fetched windows** removes them by age like any window. **Check sync** on /storage and on a channel's Storage panel (`pnpm ops check-windows`, `{"slug"?, "video"?, "dryRun"?}`) checks the windows already on disk. Needs a restart of the editor.
- **umtool's clip editor keeps a voice's pitch at any speed, and goes up to 4×.** A selection, an edge, a transcript line or the auto-audition played at 1.5× or 2× used to rise in pitch with the speed (2× was an octave up), unlike the same video at 2× in a player: the bench plays a range from decoded audio, whose speed control is a tape-speed knob. At any speed but 1× the range is now time-stretched at its own pitch first (waveform-similarity overlap-add) and played at 1×, still starting and stopping on the exact sample; a clip's selection is stretched ahead while the editor is idle, so playing it does not wait. The speed list adds 1.75×, 2.5×, 3×, 3.5× and 4×. Needs a restart of umtool.
- **A clip whose recording umtool cannot play is skipped by the clip walk, not opened broken.** A whole recording saved with **Fetch the whole recording** sits in the saved-video store, which umtool was not allowed to read: a clip it alone held counted as fetched, the walk stopped on it, and the player answered "outside the roots" (`costco-ok`). The store (`SAVED_VIDEOS_DIR`, else `transcripts/saved-videos`) is now readable, as the corpus is, so such a clip plays; and a window umtool may not read is no longer counted at all, so a clip with no window it can play is passed by and comes back once one is fetched. Needs a restart of umtool.
- **A forum thread's fetch no longer skips the pages an interrupted catch-up still owed.** When a catch-up stopped partway down a thread and new pages were posted before the next fetch, the next fetch read the new pages, met the posts the stopped run had saved, took them for the point where it was caught up, and went on to the older history: the pages between were never read (on 2026-10-23, 93 pages of a 3,798-page thread). It now continues where the stopped catch-up left off, then goes on to the history. And a page that comes back as no thread page at all just after a browser check clears is loaded once more before the fetch stops on it, as an empty page already was. Needs a restart of the editor.
diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts
@@ -113,6 +113,7 @@ test("a traversing slug is refused at the door, on every route that takes one",
["import-media", { slug: "../../escape", path: "/tmp/ops-api-never.mp4", id: "abc123" }],
["record-live", { slug: "../../escape", url: "https://rumble.com/v1abcde-x.html" }],
["keep-videos", { slug: "../../escape", ids: ["abc123"] }],
+ ["check-windows", { slug: "../../escape", dryRun: true }],
];
for (const [action, data] of cases) {
const { status, body } = await callPost((await route(action)).POST!, data);
diff --git a/editor/app/api/ops/check-windows/route.ts b/editor/app/api/ops/check-windows/route.ts
@@ -0,0 +1,27 @@
+import { checkClipWindowsAction } from "../../../storage/actions";
+import { jobResponse, ops, optBool, optString, reqVideoId } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug?: string, video?: string, dryRun?: boolean }
+// -> { ok: true, jobId }
+//
+// AN ADAPTER onto the action the /storage button posts: probe every fetched
+// clip window in one video (`video`, within `slug`), one channel or the
+// corpus, and set aside the ones whose picture runs off their sound as
+// `<from>-<to>.desynced.<ext>` — never deleted. `dryRun` only lists them. See
+// lib/clipWindowSync.ts for the rule and its measured numbers.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "video", "dryRun"], async (body) => {
+ const slug = optString(body, "slug");
+ const video = body.video === undefined ? undefined : reqVideoId(body, "video");
+ const dryRun = optBool(body, "dryRun");
+ return jobResponse(
+ await checkClipWindowsAction({
+ ...(slug ? { slug } : {}),
+ ...(video ? { video } : {}),
+ ...(dryRun ? { dryRun: true } : {}),
+ }),
+ );
+ });
+}
diff --git a/editor/app/api/ops/fetch-windows/route.test.ts b/editor/app/api/ops/fetch-windows/route.test.ts
@@ -131,14 +131,31 @@ test("a dry run answers the cache, groups by platform queue, and names what it c
);
// The window's own URL picks the queue: the mix channel's Rumble video joins
// the Rumble job rather than starting a second one beside it. The queue is
- // the platform's CLIP queue (release 19, A5), not its download queue.
- assert.deepEqual(j.groups.map((g) => g.queueKey).sort(), ["clips:rumble", "clips:youtube"]);
+ // the platform's CLIP queue (release 19, A5), not its download queue —
+ // except for a whole-recording platform (settings.clips, Rumble by
+ // default), whose job saves the whole video first, as a persist, on the
+ // platform's download queue.
+ assert.deepEqual(j.groups.map((g) => g.queueKey).sort(), ["clips:youtube", "platform:rumble"]);
const yt = j.groups.find((g) => g.platform === "youtube")!;
assert.equal(yt.items[0].webpageUrl, "https://www.youtube.com/watch?v=vid1");
assert.equal(j.unresolved.length, 1);
assert.match(j.unresolved[0].error, /Channel "no-such" not found/);
});
+test("wholeRecording: false keeps a Rumble window on the clip queue, as a remote seek", async () => {
+ const r = await post({
+ requestedBy: "test",
+ dryRun: true,
+ wholeRecording: false,
+ items: [item({ slug: "rb-chan", id: "rb1", from: 5, to: 15 })],
+ });
+ assert.equal(r.status, 200);
+ const j = r.json as { groups: { platform: string; queueKey: string }[] };
+ assert.deepEqual(j.groups.map((g) => [g.platform, g.queueKey]), [["rumble", "clips:rumble"]]);
+ const bad = await post({ requestedBy: "test", dryRun: true, wholeRecording: "no", items: [item()] });
+ assert.equal(bad.status, 400);
+});
+
test("a window a queued job will already write is answered in inFlight with that job, and joins no group", async () => {
// A fabricated queued fetch-window job for 95–130 of vid1, behind a running
// holder on its queue so it never starts: its spec is the request it was
diff --git a/editor/app/api/ops/fetch-windows/route.ts b/editor/app/api/ops/fetch-windows/route.ts
@@ -33,9 +33,9 @@ import {
export const dynamic = "force-dynamic";
-// POST { siteId, maxHeight?, storedUrl?, dryRun? }
+// POST { siteId, maxHeight?, storedUrl?, wholeRecording?, dryRun? }
// | { items: [{ slug, id, from, to, clipId?, reason?, pad?, webpageUrl?, force? }, …],
-// requestedBy, manifest?, maxHeight?, storedUrl?, minGapSeconds?, dryRun? }
+// requestedBy, manifest?, maxHeight?, storedUrl?, minGapSeconds?, wholeRecording?, dryRun? }
// dryRun -> { ok, dryRun: true, groups: [{ platform, queueKey, items }],
// cached, inFlight, unresolved[, onDisk, unfetchable] }
// else -> { ok, dryRun: false, jobs: [{ platform, queueKey, jobId, items }],
@@ -68,6 +68,13 @@ export const dynamic = "force-dynamic";
// still jittered up to half again. Shorter than the default risks Rumble's
// IP-wide Cloudflare challenge — the operator's call, per run.
//
+// `wholeRecording` (default: settings.clips.wholeRecordingPlatforms decides —
+// Rumble): a window on such a platform is cut from the video's WHOLE recording,
+// saved once to the saved-video store as "Persist source video" saves it, on
+// the platform's download queue; a failed whole download fails its windows.
+// `"wholeRecording": false` fetches every window of this run by a remote seek
+// instead, as before.
+//
// A big list goes in a file: `pnpm ops fetch-windows --file list.json`.
const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl", "force"];
@@ -175,12 +182,14 @@ function optMaxHeight(body: OpsBody): number | undefined {
export async function POST(request: Request) {
return ops(
request,
- ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "minGapSeconds", "dryRun"],
+ ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "minGapSeconds", "wholeRecording", "dryRun"],
async (body) => {
const maxHeight = optMaxHeight(body);
const storedUrl = optStoredUrl(body);
const dryRun = optBool(body, "dryRun");
const minGapSeconds = optMinGapSeconds(body);
+ const wholeRecording = optBool(body, "wholeRecording");
+ const seek = wholeRecording === false ? { wholeRecording: false } : {};
if (body.siteId !== undefined && body.items !== undefined) {
throw new OpsInputError('send either "siteId" or "items", not both');
}
@@ -198,7 +207,7 @@ export async function POST(request: Request) {
`"${siteId}" is not a valid site id (lowercase letters, digits and "-"; must start with a letter or digit)`,
);
}
- result = await fetchMissingEvidenceAction(siteId, { dryRun, maxHeight, storedUrl });
+ result = await fetchMissingEvidenceAction(siteId, { dryRun, maxHeight, storedUrl, ...seek });
} else if (body.items !== undefined) {
const items = reqWindowItems(body);
// WHO ASKED IS NOT OPTIONAL, as on the single route: a window nobody
@@ -212,6 +221,7 @@ export async function POST(request: Request) {
storedUrl,
dryRun,
...(minGapSeconds !== undefined ? { minGapSeconds } : {}),
+ ...seek,
});
} else {
throw new OpsInputError('"siteId" (a site\'s missing evidence) or "items" (a list of windows) is required');
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -82,10 +82,14 @@ import {
isFetchMaxHeight,
type ClipProvenance,
} from "yt-dlp-transcript-common/lib/clipWindow";
+import { clipWindowPath } from "yt-dlp-transcript-common/lib/clipWindow-server";
import {
- clipWindowPath,
- findContainingClipWindow,
-} from "yt-dlp-transcript-common/lib/clipWindow-server";
+ ffprobeWindowProbe,
+ findInSyncContainingClipWindow,
+ judgeClipWindow,
+ setAsideDesyncedWindow,
+} from "yt-dlp-transcript-common/lib/clipWindowSync-server";
+import { desyncedWindowMessage } from "yt-dlp-transcript-common/lib/clipWindowSync";
import {
cutSavedVideoWindow,
savedWindowSource,
@@ -1345,7 +1349,13 @@ export async function fetchWindowAction(req: {
// ASK THE CACHE FIRST, and accept a WIDER file: a report cites the same
// stream more than once, so a generous fetch for one clip must serve the
// neighbour it already covers rather than being downloaded again.
- const hit = await findContainingClipWindow(videoDir, from, to);
+ //
+ // AND IN SYNC (lib/clipWindowSync.ts): a held window whose picture runs off
+ // its sound is set aside here (`<from>-<to>.desynced.<ext>`), and the span
+ // goes on as missing — to the saved container below, else the network.
+ const { hit } = await findInSyncContainingClipWindow(videoDir, from, to, {
+ probe: ffprobeWindowProbe(paths.ffprobeBin),
+ });
if (hit) {
// The window's own height, read off its header: a window holds seconds,
// so the probe is quick, and it is the only record of how tall a window
@@ -1545,11 +1555,12 @@ export async function fetchWindowAction(req: {
signal,
onPlatformBackoff: () => recordDownloadBackoff(platform, paths),
});
+ let got: Awaited<ReturnType<typeof once>>;
if (via && stored) {
- await once({ ...stored, why: via });
+ got = await once({ ...stored, why: via });
} else {
try {
- await once(null);
+ got = await once(null);
} catch (e) {
// FALLBACK: the page lookup rate-limited (the backoff is already
// recorded) and the record stores its media URL — cut from that,
@@ -1565,9 +1576,28 @@ export async function fetchWindowAction(req: {
`(${stored.host}) instead, after ${Math.round(gapMs / 1000)}s.\n`,
);
await abortableSleep(gapMs, signal);
- await once({ ...stored, why: "rate-limited" });
+ got = await once({ ...stored, why: "rate-limited" });
}
}
+ // THE SYNC CHECK on what the fetch produced, the batch's rule
+ // (controller/fetchWindows.ts): a window whose picture runs off its sound
+ // is set aside, and the job fails naming the remedy.
+ const win = {
+ file: path.basename(got.file),
+ path: got.file,
+ from: got.from,
+ to: got.to,
+ bytes: got.bytes,
+ provenance: got.provenance,
+ };
+ const { sync } = await judgeClipWindow(win, { probe: ffprobeWindowProbe(paths.ffprobeBin) });
+ if (sync && !sync.ok) {
+ const aside = await setAsideDesyncedWindow(win, sync);
+ safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
+ throw new Error(
+ `${from.toFixed(2)}–${to.toFixed(2)} of ${videoId}: ${desyncedWindowMessage(sync, aside.file, platform)}.`,
+ );
+ }
safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
},
});
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -18,7 +18,10 @@ import {
MAX_CLIP_WINDOW_SECONDS,
isFetchMaxHeight,
} from "yt-dlp-transcript-common/lib/clipWindow";
-import { findContainingClipWindow } from "yt-dlp-transcript-common/lib/clipWindow-server";
+import {
+ ffprobeWindowProbe,
+ findInSyncContainingClipWindow,
+} from "yt-dlp-transcript-common/lib/clipWindowSync-server";
import { sourceGoneState } from "yt-dlp-transcript-common/lib/sourceGone-server";
import { savedWindowSource } from "yt-dlp-transcript-common/lib/savedVideoWindow-server";
import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig";
@@ -34,6 +37,7 @@ import {
fetchWindowsItemLabel,
dedupeFetchWindowsItems,
storedUrlDoor,
+ wholeRecordingFor,
type FetchWindowsItem,
} from "yt-dlp-transcript-common/controller/fetchWindows";
import {
@@ -89,6 +93,13 @@ import { safeRevalidate } from "../../../lib/safeRevalidate";
// they ask no page — and only the rest are refused. The default, "never",
// changes nothing.
//
+// A WHOLE-RECORDING PLATFORM'S WINDOWS (settings.clips.wholeRecordingPlatforms,
+// Rumble by default) go to the platform's DOWNLOAD queue (`platform:rumble`),
+// not its clip queue: the job saves the video's whole recording first — a
+// persist, so it waits where a persist waits, one Rumble stream at a time —
+// and cuts the windows from it (controller/fetchWindows.ts). `wholeRecording:
+// false` keeps the run on the clip queue with the remote seek.
+//
// Like the single fetch, NOT GATED BY THE DOWNLOAD PAUSE: an operator (or a
// tool they are driving) asked for these seconds by hand.
@@ -108,6 +119,8 @@ export type FetchWindowsRequest = {
storedUrl?: StoredUrlMode;
// The run's gap floor in seconds, in place of the platform's (controller).
minGapSeconds?: number;
+ // false: every window by a remote seek, the whole-recording platforms' too.
+ wholeRecording?: boolean;
};
export type FetchWindowsUnresolved = { item: FetchWindowsItem; error: string };
@@ -170,6 +183,7 @@ async function planFetchWindows(
queueOverride: string | undefined,
maxHeight: number | undefined,
storedMode: StoredUrlMode,
+ wholeRecording?: boolean,
): Promise<{
groups: FetchWindowsGroup[];
cached: FetchWindowsItem[];
@@ -179,6 +193,7 @@ async function planFetchWindows(
stored: Set<FetchWindowsItem>;
}> {
const paths = getPaths();
+ const settings = getSettings();
const configs = new Map<string, ChannelConfig | null>();
const groups = new Map<string, FetchWindowsGroup>();
const cached: FetchWindowsItem[] = [];
@@ -206,7 +221,15 @@ async function planFetchWindows(
platform: channelConfigPlatform(config),
});
const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId);
- if (await findContainingClipWindow(videoDir, item.from, item.to)) {
+ // HELD ONLY WHEN IN SYNC (lib/clipWindowSync.ts). A desynced window is not
+ // set aside HERE — the job does that, and says so in its log — but neither
+ // does it make the item cached: the span is planned as missing, so the
+ // job that sets it aside fills it.
+ const held = await findInSyncContainingClipWindow(videoDir, item.from, item.to, {
+ probe: ffprobeWindowProbe(paths.ffprobeBin),
+ setAside: false,
+ });
+ if (held.hit) {
cached.push(item);
continue;
}
@@ -279,8 +302,12 @@ async function planFetchWindows(
// whose URL is no platform's (a curated mix) can hold Rumble videos, and
// its queue would put a second Rumble job beside the first, each pacing
// only itself.
- const queueKey = resolveQueueKey(clipWindowQueueKey(queueKeyForUrl(url)), queueOverride);
const platform = detectPlatform(url) ?? "unknown";
+ const whole = wholeRecordingFor(settings, platform, item, wholeRecording);
+ const queueKey = resolveQueueKey(
+ whole ? queueKeyForUrl(url) : clipWindowQueueKey(queueKeyForUrl(url)),
+ queueOverride,
+ );
// One job per queue. Two platforms sharing a queue (an override) share a
// job too; the controller keys the cooldown per item, so each is honoured.
const group: FetchWindowsGroup = groups.get(queueKey) ?? { platform, queueKey, items: [] };
@@ -288,7 +315,7 @@ async function planFetchWindows(
group.items.push(planned);
// The controller's rule (controller/fetchWindows.ts): an allowlisted
// platform's own page, never a copy, and a stored URL of that platform.
- if (storedMode !== "never" && !item.copy && isStoredUrlPlatform(platform)) {
+ if (!whole && storedMode !== "never" && !item.copy && isStoredUrlPlatform(platform)) {
const s = await storedMediaUrl(videoDir);
if (s && s.platform === platform) stored.add(planned);
group.storedUrlItems = (group.storedUrlItems ?? 0) + (stored.has(planned) ? 1 : 0);
@@ -328,6 +355,7 @@ export async function fetchWindowsJobAction(req: {
queueKey: string;
storedUrl?: StoredUrlMode;
minGapSeconds?: number;
+ wholeRecording?: boolean;
}): Promise<StreamActionResult> {
if (req.items.length === 0) return { ok: false, error: "No windows to fetch." };
if (req.maxHeight !== undefined && !isFetchMaxHeight(req.maxHeight)) {
@@ -365,6 +393,8 @@ export async function fetchWindowsJobAction(req: {
// A Retry keeps the mode it was asked with.
...(req.storedUrl && req.storedUrl !== "never" ? { storedUrl: req.storedUrl } : {}),
...(req.minGapSeconds !== undefined ? { minGapSeconds: req.minGapSeconds } : {}),
+ // A Retry keeps the seek it was asked with.
+ ...(req.wholeRecording === false ? { wholeRecording: false } : {}),
},
},
fn: async (onLog, signal, setProgress, ctx) => {
@@ -379,6 +409,7 @@ export async function fetchWindowsJobAction(req: {
maxHeight: req.maxHeight,
storedUrl: req.storedUrl,
minGapSeconds: req.minGapSeconds,
+ ...(req.wholeRecording === false ? { wholeRecording: false } : {}),
onLog,
signal,
drainSignal: ctx.drainSignal,
@@ -423,6 +454,7 @@ export async function fetchWindowsAction(
req.queueKey,
req.maxHeight,
storedMode,
+ req.wholeRecording,
);
const base = { groups, cached, inFlight, unresolved, jobs: [], refused: [] };
if (req.dryRun) return { ok: true, dryRun: true, ...base };
@@ -473,6 +505,7 @@ export async function fetchWindowsAction(
queueKey: g.queueKey,
storedUrl: storedMode,
...(req.minGapSeconds !== undefined ? { minGapSeconds: req.minGapSeconds } : {}),
+ ...(req.wholeRecording === false ? { wholeRecording: false } : {}),
});
} catch (e) {
refused.push({ platform: g.platform, error: (e as Error).message, items: door.run.length });
@@ -515,7 +548,7 @@ export type FetchMissingEvidenceResult =
// {"siteId": …}` both run.
export async function fetchMissingEvidenceAction(
siteId: string,
- opts: { dryRun?: boolean; maxHeight?: number; storedUrl?: StoredUrlMode } = {},
+ opts: { dryRun?: boolean; maxHeight?: number; storedUrl?: StoredUrlMode; wholeRecording?: boolean } = {},
): Promise<FetchMissingEvidenceResult> {
const id = siteId.trim();
if (!isValidSiteId(id)) return { ok: false, error: `"${id}" is not a valid site id` };
@@ -542,7 +575,13 @@ export async function fetchMissingArticleEvidenceAction(
async function fetchMissingFor(
need: Awaited<ReturnType<typeof missingEvidenceWindows>>,
id: string,
- opts: { dryRun?: boolean; maxHeight?: number; siteId?: string; storedUrl?: StoredUrlMode },
+ opts: {
+ dryRun?: boolean;
+ maxHeight?: number;
+ siteId?: string;
+ storedUrl?: StoredUrlMode;
+ wholeRecording?: boolean;
+ },
): Promise<FetchMissingEvidenceResult> {
const extra = { siteId: id, onDisk: need.onDisk, unfetchable: need.unfetchable };
if (need.missing.length === 0) {
@@ -573,6 +612,7 @@ async function fetchMissingFor(
maxHeight: opts.maxHeight,
dryRun: opts.dryRun,
...(opts.storedUrl ? { storedUrl: opts.storedUrl } : {}),
+ ...(opts.wholeRecording === false ? { wholeRecording: false } : {}),
});
if (!r.ok) return r;
return { ...r, ...extra };
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -235,6 +235,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
queueKey,
// Release 32 R5: a replay keeps the stored-URL mode it was asked with.
...(isStoredUrlMode(p.storedUrl) ? { storedUrl: p.storedUrl } : {}),
+ // ...and the remote seek, when the run asked for it over the whole recording.
+ ...(p.wholeRecording === false ? { wholeRecording: false } : {}),
});
},
// Both digest lanes replay through one action; the lane comes from params so a
diff --git a/editor/app/storage/actions.ts b/editor/app/storage/actions.ts
@@ -32,6 +32,7 @@ import { channelMediaBusyReason } from "../channels/lib/mediaBusy";
import { enqueueRepointJob } from "./lib/repointJob";
import { enqueueSavedVideosRelocation } from "./lib/savedVideosJob";
import { enqueueEvictClipWindows } from "./lib/evictClipsJob";
+import { enqueueCheckClipWindows } from "./lib/checkWindowsJob";
import { savedVideosStoreBusyReason } from "./lib/storeBusy";
import { refreshLocationHealth } from "yt-dlp-transcript-common/controller/storageWatch";
import { forgetChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia";
@@ -488,6 +489,44 @@ export async function evictClipWindowsAction(opts: {
});
}
+// CHECK FETCHED CLIP WINDOWS FOR A PICTURE THAT RUNS OFF ITS SOUND
+// (lib/clipWindowSync.ts): probe every window in one video, one channel or the
+// corpus, and set a desynced one aside as `<from>-<to>.desynced.<ext>` — never
+// deleted; `dryRun` only lists. The fetch judges the windows it uses; this is
+// for the ones already on disk.
+//
+// The same door as the eviction above, for the same reason: the slug (and the
+// video) come off the wire and are path-joined under `channelsDir` before a
+// walk that RENAMES. The job's `needsText` is the channel guard.
+export async function checkClipWindowsAction(opts: {
+ slug?: string;
+ video?: string;
+ dryRun?: boolean;
+}): Promise<StreamActionResult> {
+ if (opts.video !== undefined && opts.slug === undefined) {
+ return { ok: false, error: "A video is named within a channel: give its slug too." };
+ }
+ if (opts.slug !== undefined) {
+ if (!isValidChannelSlug(opts.slug)) {
+ return { ok: false, error: `"${opts.slug}" is not a valid channel slug` };
+ }
+ if (!(await channelExists(getPaths(), opts.slug))) {
+ return { ok: false, error: `Channel "${opts.slug}" not found` };
+ }
+ }
+ if (
+ opts.video !== undefined &&
+ (opts.video === "" || opts.video === "." || opts.video === ".." || /[/\\\0]/.test(opts.video))
+ ) {
+ return { ok: false, error: `"${opts.video}" is not a video id (one path segment)` };
+ }
+ return enqueueCheckClipWindows({
+ ...(opts.slug ? { slug: opts.slug } : {}),
+ ...(opts.video ? { video: opts.video } : {}),
+ ...(opts.dryRun ? { dryRun: true } : {}),
+ });
+}
+
// ---------------------------------------------------------------------------
// The drive-health timings
// ---------------------------------------------------------------------------
diff --git a/editor/app/storage/components/ClipWindowsCard.tsx b/editor/app/storage/components/ClipWindowsCard.tsx
@@ -4,7 +4,7 @@ import { useState } from "react";
import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
import { formatBytes } from "yt-dlp-transcript-common/lib/format";
import { cancelJobAction } from "../../jobs/actions";
-import { evictClipWindowsAction } from "../actions";
+import { checkClipWindowsAction, evictClipWindowsAction } from "../actions";
// FETCHED CLIP WINDOWS — the one thing in the corpus nothing prunes.
//
@@ -53,7 +53,12 @@ import { evictClipWindowsAction } from "../actions";
// well, every time — the tick resets when the age changes, so it can never be
// left armed from an earlier, narrower choice.
//
-// ⚠️ Both panels are rendered UNCONDITIONALLY and only `disabled` changes —
+// CHECK SYNC is the card's other control (lib/clipWindowSync.ts): it probes
+// every window in scope and sets aside, never deletes, the ones whose picture
+// runs off their sound. A rename of a cache file a fetch would refill anyway
+// needs no preview gate; `pnpm ops check-windows` has the dry run.
+//
+// ⚠️ Every panel is rendered UNCONDITIONALLY and only `disabled` changes —
// `StreamActionLog` calls router.refresh() the instant a run ends, and a panel
// unmounted by its own result takes its log with it (plans/FACTS.md).
@@ -204,6 +209,15 @@ export function ClipWindowsCard({
label="Evict fetched windows"
disabled={!canEvict}
/>
+ <StreamActionLog
+ key="check-windows-log"
+ trigger={() => checkClipWindowsAction(scope)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Check sync"
+ runningLabel="Probing…"
+ label="Check fetched windows"
+ disabled={blocked}
+ />
</div>
{!canEvict && (
<p aria-label="clip eviction gate" className="text-xs text-muted-foreground">
diff --git a/editor/app/storage/lib/checkWindowsJob.ts b/editor/app/storage/lib/checkWindowsJob.ts
@@ -0,0 +1,60 @@
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ runManagedFunction,
+ type StreamActionResult,
+} from "yt-dlp-transcript-common/jobs/streamCommand";
+import {
+ checkClipWindows,
+ checkClipWindowsSummary,
+} from "yt-dlp-transcript-common/controller/checkClipWindows";
+
+// ONE ENQUEUE OF THE CLIP-WINDOW SYNC CHECK, for its callers: the button on
+// /storage (and a channel's Storage panel) and the `/api/ops/check-windows`
+// adapter. Not in `actions.ts` for evictClipsJob.ts's reason: every non-type
+// export of a "use server" file is a server action, and a shared helper there
+// would be an unguarded enqueue on the wire.
+//
+// A JOB, like the eviction: a corpus-wide pass is a readdir of every video dir
+// and an ffprobe per window, it RENAMES, and the operator is owed a log naming
+// every window it set aside. `channelSlug` only for a one-channel run, so the
+// text guard has a channel to ask.
+export async function enqueueCheckClipWindows(opts: {
+ slug?: string;
+ video?: string;
+ dryRun?: boolean;
+}): Promise<StreamActionResult> {
+ const paths = getPaths();
+ return runManagedFunction({
+ kind: "check-windows",
+ // Parallel: it touches `clips/` only, and asks no platform.
+ queueKey: "",
+ paths,
+ ...(opts.slug ? { channelSlug: opts.slug } : {}),
+ ...(opts.slug && opts.video ? { videoId: opts.video } : {}),
+ fn: async (onLog, signal) => {
+ const where = opts.video
+ ? `${opts.slug}/${opts.video}`
+ : opts.slug
+ ? `in ${opts.slug}`
+ : "across every channel";
+ onLog(
+ `${opts.dryRun ? "Listing" : "Checking"} fetched clip windows ${where} for a picture ` +
+ `that runs off its sound${opts.dryRun ? " (dry run: nothing is renamed)" : ""}.`,
+ );
+ const result = await checkClipWindows({
+ paths,
+ ...(opts.slug ? { slug: opts.slug } : {}),
+ ...(opts.video ? { video: opts.video } : {}),
+ ...(opts.dryRun ? { dryRun: true } : {}),
+ onLog,
+ signal,
+ });
+ onLog(checkClipWindowsSummary(result));
+ if (!opts.dryRun && result.setAside > 0) {
+ safeRevalidate(["/storage"]);
+ if (opts.slug) safeRevalidate([`/channels/${opts.slug}`]);
+ }
+ },
+ });
+}
diff --git a/editor/e2e/cookie-alerts.spec.ts b/editor/e2e/cookie-alerts.spec.ts
@@ -55,7 +55,9 @@ test("two Rumble embeds refused raise the banner; Recheck with fresh cookies cle
];
const post = await request.post(`${baseUrl}/api/ops/fetch-windows`, {
headers: AUTH,
- data: { requestedBy: "umtool", manifest: "cookie-alerts", items },
+ // The remote seek's refusal is what this pins; Rumble's default (the whole
+ // recording, settings.clips) is a persist's download, not a window's.
+ data: { requestedBy: "umtool", manifest: "cookie-alerts", items, wholeRecording: false },
});
expect(post.status()).toBe(200);
const body = (await post.json()) as { jobs: { platform: string; jobId: string }[] };
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -421,6 +421,9 @@ const ACTIONS = [
"relocate",
"relocate-back",
"evict-clips",
+ // Probe fetched clip windows and set aside the ones whose picture runs off
+ // their sound ({slug?, video?, dryRun?}), as a job.
+ "check-windows",
// A report site's evidence media: cut every cited clip and copy every cited
// post capture into the site's report-media cache ({siteId}).
"reports-prepare",
@@ -1162,6 +1165,13 @@ export function usage() {
' "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a',
" window; an evicted window is fetched again when asked for.",
"",
+ '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.',
+ "",
'tags edits the curated-tag vocabulary through its one writer: {"op":',
' "define", "tag": {...}} (the WHOLE definition: id, label, rules and',
' "sites", the sites it exists on, absent = every site) or {"op":',
@@ -1460,6 +1470,15 @@ export function usage() {
" fetches in place of the platform's floor (Rumble's 120 s); still jittered",
" up to half again. Shorter than the default risks Rumble's IP-wide",
" Cloudflare challenge; a Retry keeps it.",
+ ' A window on a whole-recording platform (settings.clips',
+ ' .wholeRecordingPlatforms, default Rumble) is not seeked: the video is',
+ ' saved whole once, as "Persist source video" saves it, on the platform\'s',
+ ' download queue, and its windows are cut from it — a remote Rumble seek',
+ ' put the picture 1-4 s off the sound. A failed whole download fails its',
+ ' windows with the download\'s message. "wholeRecording": false fetches',
+ ' every window of the run by a remote seek instead. A fetched window whose',
+ ' picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>)',
+ ' and fails; a held one is set aside and fetched again (check-windows).',
"",
'"preview": "<branch>" on deploy-site or build-deploy makes it a Cloudflare',
" Pages PREVIEW instead of production: the same bundle goes to a branch",
diff --git a/settings.json.example b/settings.json.example
@@ -326,5 +326,10 @@
"maxUsd": 5,
"everySeconds": 10
}
+ },
+ "clips": {
+ "wholeRecordingPlatforms": [
+ "rumble"
+ ]
}
}