commit 36586fa43bf6933e248839420813016304f9fbe4
parent d8ffb741037d903ac41d1815a6a3e84a6fbeb58f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 15:18:51 -0400
Merge branch 'main' into r36/clips-suggest
Diffstat:
77 files changed, 5851 insertions(+), 57 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -141,12 +141,12 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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". | `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. 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` |
+| `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` |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
-| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. | |
+| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). | |
| `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | |
| `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | |
| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` |
@@ -165,6 +165,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -> {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/<slug>.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` |
| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
| `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -> {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` |
+| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for <platform>" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait` |
+| `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
### Usage, flags and environment
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -90,7 +90,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `UMTOOL_MEDIA_DIR` | unset (no media root: a project link's target is kept) | umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md). | common/lib/report/delete.ts, umtool (lib/paths.mjs) |
| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, umtool (lib/paths.mjs) |
| `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does). | common/lib/report/delete.ts, umtool (song/paths.mjs) |
-| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). | editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts |
+| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled. | editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts |
| `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts |
| `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts |
| `TRANSCRIPT_LOCAL_DIR` | — | MCP server: a composed public dir on disk. | mcp/src/sources.ts |
@@ -233,6 +233,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts |
| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts |
| `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts |
+| `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts |
| `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts |
| `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
diff --git a/OPERATING.md b/OPERATING.md
@@ -113,6 +113,28 @@ pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150
- `transcribe` runs one local file (or a window of it) through the corpus's own engine and model; the result JSON
(cues, text, and with `"words": true` the word timings parakeet keeps) is printed on stdout with `--wait`.
`"out"` writes it to a file outside the corpus.
+- With the workers paused, `"whilePaused": true` on `transcribe` or `transcribe-one` runs that one job on a worker
+ the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. The video
+ page's Transcribe row says **Transcribe now (workers paused)**.
+
+## Find clips in a recording
+
+```sh
+pnpm ops find-clips --json '{"slug":"example","id":"<videoId>","dryRun":true}'
+pnpm ops find-clips --json '{"slug":"example","id":"<videoId>","target":600}' --wait
+pnpm ops find-clips --json '{"slug":"example","id":"<videoId>","segment":"s2"}' --wait
+pnpm ops fetch-chat --json '{"slug":"example","id":"<videoId>"}' --wait
+```
+
+- `find-clips` (the video page's **Find clips**) runs the clip finder's chain as one job: persist the source video,
+ the corpus transcript, word timings (`data/<id>/words.json`), the chat replay (YouTube), diarization — each
+ skipped when its output exists, each named in the log — then umtool's clip finder, which finds the narrated-video
+ segments and proposes the clips. The result names the umtool project and the segments; `"segment"` (the page's
+ **Find clips in this part**) finds clips in one of them. Needs `UMTOOL_URL` and `WORKER_TOKEN` on the editor.
+- A paused pool, diarization switched off or a held backfill lane fails the step that needs it, saying so;
+ `"whilePaused": true` (the page's **Run while paused**) runs this one video's steps past the holds.
+- `fetch-chat` fetches one video's live chat replay alone (paced, YouTube only) into `live_chat.cues.json`; the
+ video page's Media tools → **Fetch live chat**.
## Tag
diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts
@@ -0,0 +1,224 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { AttemptOutcome } from "../ytdlp/runOneYtdlp";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchLiveChat.test.ts
+//
+// One video's chat replay (release 36, lane A). The yt-dlp runner is a stub
+// that records its argv and writes the JSON-lines replay where the
+// `subtitle:` template says — no yt-dlp, no network. Every case is a temp
+// corpus; the job cases run through the real registry over it.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "fetch-chat-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const {
+ CHAT_PLATFORMS,
+ fetchLiveChat,
+ liveChatPlan,
+ noChatFetcherSentence,
+ runFetchChatJob,
+} = await import("./fetchLiveChat");
+const { liveChatOnlyArgs } = await import("../ytdlp/downloadOneManaged");
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-stream";
+const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig;
+const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const;
+
+function chatLine(sec: number, author: string, text: string): string {
+ return JSON.stringify({
+ replayChatItemAction: {
+ actions: [
+ {
+ addChatItemAction: {
+ item: {
+ liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: author } },
+ },
+ },
+ },
+ ],
+ videoOffsetTimeMsec: String(sec * 1000),
+ },
+ });
+}
+const REPLAY = [chatLine(12, "viewer1", "lol"), chatLine(14, "viewer2", "LMAO"), chatLine(30, "viewer3", "W")].join("\n") + "\n";
+
+async function video(id: string, meta: Record<string, unknown>): Promise<string> {
+ const dir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG));
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: "Synth stream", ...meta }));
+ return dir;
+}
+
+// The stub: records the argv, writes the replay under the subtitle template.
+function stubRunner(o: { writes?: string | null; exitCode?: number; stderr?: string } = {}) {
+ const calls: { cwd: string; args: string[] }[] = [];
+ const run = async (cwd: string, args: string[]): Promise<AttemptOutcome> => {
+ calls.push({ cwd, args });
+ const i = args.findIndex((a) => a.startsWith("subtitle:"));
+ if (o.writes !== null && (o.exitCode ?? 0) === 0) {
+ const base = args[i + 0].slice("subtitle:".length);
+ await writeFile(path.join(cwd, `${base}.live_chat.json`), o.writes ?? REPLAY);
+ }
+ return { exitCode: o.exitCode ?? 0, stderrTail: o.stderr ?? "", archiveLine: null, formatLine: null };
+ };
+ return { run, calls };
+}
+
+const log = () => {
+ const lines: string[] = [];
+ return { lines, onLog: (s: string) => lines.push(s) };
+};
+
+test("the chat pass is the managed download's chat-only command line, paced", () => {
+ const url = "https://www.youtube.com/watch?v=abc";
+ const args = liveChatOnlyArgs(CONFIG, undefined, url, 7);
+ assert.deepEqual(args.slice(0, 2), ["--ignore-config", "--restrict-filenames"]);
+ assert.ok(args.includes("--skip-download"));
+ assert.deepEqual(args.slice(args.indexOf("--sub-langs"), args.indexOf("--sub-langs") + 2), ["--sub-langs", "live_chat"]);
+ assert.ok(args.includes("--no-write-info-json"), "the metadata on disk is never rewritten");
+ assert.equal(args[args.indexOf("--sleep-requests") + 1], "7", "the platform's pace");
+ assert.deepEqual(args.slice(-2), ["--", url]);
+ assert.ok(CHAT_PLATFORMS.has("youtube"));
+});
+
+test("plan: YouTube fetches; another platform has no fetcher; a never-live video has no replay", async () => {
+ await video("yt1", { webpage_url: "https://www.youtube.com/watch?v=yt1", was_live: true });
+ assert.deepEqual(await liveChatPlan(paths, SLUG, "yt1", CONFIG), {
+ kind: "fetch",
+ url: "https://www.youtube.com/watch?v=yt1",
+ platform: "youtube",
+ });
+ await video("tw1", { webpage_url: "https://www.twitch.tv/videos/123" });
+ const tw = await liveChatPlan(paths, SLUG, "tw1", CONFIG);
+ assert.deepEqual(tw, { kind: "no-fetcher", platform: "twitch" });
+ assert.equal(noChatFetcherSentence("twitch"), "no chat fetcher for twitch: only YouTube's chat replay is fetched");
+ await video("nl1", { webpage_url: "https://www.youtube.com/watch?v=nl1", live_status: "not_live" });
+ assert.equal((await liveChatPlan(paths, SLUG, "nl1", CONFIG)).kind, "not-live");
+ assert.equal((await liveChatPlan(paths, SLUG, "nope", CONFIG)).kind, "refused");
+ assert.equal((await liveChatPlan(paths, SLUG, "../x", CONFIG)).kind, "refused");
+});
+
+test("a fetch writes the replay and its cues; a second plan says fresh", async () => {
+ const dir = await video("yt2", { webpage_url: "https://www.youtube.com/watch?v=yt2", was_live: true });
+ const { run, calls } = stubRunner();
+ const l = log();
+ const r = await fetchLiveChat({
+ paths,
+ slug: SLUG,
+ videoId: "yt2",
+ videoUrl: "https://www.youtube.com/watch?v=yt2",
+ channelConfig: CONFIG,
+ cookiePolicy: NO_COOKIES,
+ onLog: l.onLog,
+ signal: new AbortController().signal,
+ run,
+ paceSeconds: 3,
+ });
+ assert.equal(r.status, "fetched");
+ assert.equal(r.status === "fetched" && r.messages, 3);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].cwd, path.join(CORPUS, "channels", SLUG));
+ const cues = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8"));
+ assert.equal(cues.source, "live_chat");
+ assert.equal(cues.cues.length, 3);
+ assert.equal(cues.cues[0].start, 12);
+ assert.match(l.lines.join(""), /3 message\(s\) in live_chat\.cues\.json/);
+ assert.equal((await liveChatPlan(paths, SLUG, "yt2", CONFIG)).kind, "fresh");
+});
+
+test("a pass that writes nothing is an answer, not a failure", async () => {
+ const dir = await video("yt3", { webpage_url: "https://www.youtube.com/watch?v=yt3" });
+ const { run } = stubRunner({ writes: null });
+ const l = log();
+ const r = await fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt3", videoUrl: "https://www.youtube.com/watch?v=yt3",
+ channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run,
+ });
+ assert.deepEqual(r, { status: "none" });
+ assert.match(l.lines.join(""), /No chat replay for yt3/);
+ assert.deepEqual((await readdir(dir)).sort(), ["metadata.info.json"]);
+});
+
+test("a rate-limited pass records the cooldown and fails; an auth gate retries once with cookies", async () => {
+ await video("yt4", { webpage_url: "https://www.youtube.com/watch?v=yt4" });
+ let backoffs = 0;
+ const limited = stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] yt4: HTTP Error 429: Too Many Requests" });
+ await assert.rejects(
+ fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt4", videoUrl: "https://www.youtube.com/watch?v=yt4",
+ channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal,
+ run: limited.run, onPlatformBackoff: () => void backoffs++,
+ }),
+ /rate-limited the chat fetch/,
+ );
+ assert.equal(backoffs, 1);
+
+ const calls: string[][] = [];
+ const authThenOk = async (cwd: string, args: string[]): Promise<AttemptOutcome> => {
+ calls.push(args);
+ if (calls.length === 1) {
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] yt4: Sign in to confirm your age", archiveLine: null, formatLine: null };
+ }
+ const base = args[args.findIndex((a) => a.startsWith("subtitle:"))].slice("subtitle:".length);
+ await writeFile(path.join(cwd, `${base}.live_chat.json`), REPLAY);
+ return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
+ };
+ const r = await fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt4", videoUrl: "https://www.youtube.com/watch?v=yt4",
+ channelConfig: CONFIG, cookiePolicy: { cookies: "firefox", mode: "when-required" },
+ onLog: () => {}, signal: new AbortController().signal, run: authThenOk,
+ });
+ assert.equal(r.status, "fetched");
+ assert.equal(calls.length, 2);
+ assert.ok(!calls[0].includes("--cookies-from-browser"));
+ assert.ok(calls[1].includes("--cookies-from-browser"));
+});
+
+test("the job: refusals before any job (info for a skip), a fetch job, a normalize-only job", async () => {
+ await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG));
+ const tw = await runFetchChatJob({ paths, slug: SLUG, videoId: "tw1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.deepEqual(tw, { ok: false, info: true, error: "no chat fetcher for twitch: only YouTube's chat replay is fetched" });
+ const fresh = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.ok(!fresh.ok && fresh.info && /already here/.test(fresh.error));
+ const missing = await runFetchChatJob({ paths, slug: SLUG, videoId: "nope", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.ok(!missing.ok && !missing.info);
+
+ const dir = await video("yt5", { webpage_url: "https://www.youtube.com/watch?v=yt5", was_live: true });
+ const { run, calls } = stubRunner();
+ const job = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt5", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run });
+ assert.ok(job.ok, JSON.stringify(job));
+ void job.stream.cancel();
+ const done = await job.done;
+ assert.equal(done.status, "done");
+ assert.equal(calls.length, 1);
+ assert.ok((await readdir(dir)).includes("live_chat.cues.json"));
+
+ // The raw replay on disk with stale cues: normalized, no spawn.
+ const dir6 = await video("yt6", { webpage_url: "https://www.youtube.com/watch?v=yt6", was_live: true });
+ await writeFile(path.join(dir6, "transcript.live_chat.json"), REPLAY);
+ await writeFile(path.join(dir6, "live_chat.cues.json"), "{}");
+ const old = new Date(Date.now() - 60_000);
+ await utimes(path.join(dir6, "live_chat.cues.json"), old, old);
+ const spawn = stubRunner();
+ const norm = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt6", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run });
+ assert.ok(norm.ok);
+ void norm.stream.cancel();
+ assert.equal((await norm.done).status, "done");
+ assert.equal(spawn.calls.length, 0, "no network for a replay already here");
+ assert.equal(JSON.parse(await readFile(path.join(dir6, "live_chat.cues.json"), "utf8")).cues.length, 3);
+});
diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts
@@ -0,0 +1,312 @@
+// ONE VIDEO'S LIVE CHAT REPLAY, AND NOTHING ELSE — `pnpm ops fetch-chat
+// {slug, id}` (release 36, lane A), and the chat step of the find-clips job.
+//
+// The chat-only yt-dlp pass already existed, but only inside the managed
+// download's filter branch (a channel whose `rejectedLivestreams` is
+// "chat-only"): a video already archived for its media had no way to fetch
+// its chat alone. This runs THE SAME command line (downloadOneManaged.ts
+// liveChatOnlyArgs: the channel's args, its cookies and the platform's live
+// pace, then the refusals that keep it from fetching anything else), then
+// normalizes what landed into live_chat.cues.json (normalizeLiveChat — which
+// also tiers the raw replay, the one big file here, into media/).
+//
+// PACED LIKE EVERY YOUTUBE REQUEST: the job sits on the platform's DOWNLOAD
+// queue, so it waits behind a sync or a download on that platform rather than
+// bursting beside one; the argv carries the platform's live `--sleep-requests`;
+// a held platform or one in a rate-limit cooldown is refused before any job
+// exists (`info: true` — nothing is wrong, the source is resting); a
+// rate-limited pass records the platform's cooldown; a clean one settles it.
+// Cookies follow the channel's policy exactly as the metadata refresh's do:
+// up front for "always", once on an auth failure for "when-required".
+//
+// WHAT IS NOT A FAILURE:
+// - a video on another platform: no fetcher for its chat ("no chat fetcher
+// for twitch") — refused before a job, `info: true`;
+// - the chat already here and fresh (isLiveChatCuesFresh) — the same;
+// - a raw replay already here whose cues are stale: normalized, no network;
+// - a pass that writes nothing: chat replay is off for that stream, or it
+// was never live. The job ends `done` and says so.
+//
+// `needsMedia` (jobs/jobKinds.ts): it WRITES the raw replay, which is a
+// tierable big file, and the normalizer moves it into the channel's media/.
+
+import path from "node:path";
+import { readFile, readdir, stat } from "node:fs/promises";
+import {
+ AUTH_RETRY_CLASSES,
+ classifyDownloadFailure,
+ parseUnavailableFromStderr,
+} from "../lib/availability";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import {
+ DEFAULT_COOKIE_MODE,
+ alwaysCookies,
+ authRetryCookies,
+ type ResolvedCookiePolicy,
+} from "../lib/cookiePolicy";
+import { detectPlatform } from "../lib/platform";
+import type { Paths } from "../lib/paths";
+import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys";
+import { LIVE_CHAT_CUES_FILENAME, LIVE_CHAT_FILENAME, META_FILENAME } from "../lib/videoStatus";
+import {
+ heldPlatformRefusal,
+ platformCooldownRemainingMs,
+ recordDownloadBackoff,
+ recordPlatformClean,
+} from "../jobs/downloadBackoff";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { liveChatOnlyArgs } from "../ytdlp/downloadOneManaged";
+import { runOneYtdlp, type AttemptOutcome } from "../ytdlp/runOneYtdlp";
+import { isLiveChatCuesFresh, normalizeLiveChat, readNormalizedLiveChat } from "./normalizeLiveChat";
+import { isVideoIdSegment, notFetchedRefusal } from "./refreshVideoMetadata";
+import { findVideoSourceUrl } from "./undownloadedVideos";
+
+export const FETCH_CHAT_JOB_KIND = "fetch-chat";
+
+// The platforms whose chat replay a fetcher exists for. yt-dlp writes a
+// `live_chat` subtitle track for YouTube only.
+export const CHAT_PLATFORMS: ReadonlySet<string> = new Set(["youtube"]);
+
+/** What the chat of one video needs, from the disk and its metadata alone. */
+export type LiveChatPlan =
+ | { kind: "fresh"; cuesPath: string }
+ // The raw replay is here; its cues are missing or stale: normalize only.
+ | { kind: "normalize" }
+ | { kind: "no-fetcher"; platform: string }
+ // The metadata says the video was never live: there is no replay to ask for.
+ | { kind: "not-live"; liveStatus: string }
+ | { kind: "fetch"; url: string; platform: string }
+ | { kind: "refused"; error: string };
+
+async function isDirectory(p: string): Promise<boolean> {
+ return stat(p).then((s) => s.isDirectory(), () => false);
+}
+
+async function liveStatusOf(videoDir: string): Promise<string | null> {
+ try {
+ const meta = JSON.parse(await readFile(path.join(videoDir, META_FILENAME), "utf8")) as {
+ live_status?: unknown;
+ was_live?: unknown;
+ };
+ if (meta.was_live === true) return "was_live";
+ return typeof meta.live_status === "string" ? meta.live_status : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The sentence for a video whose chat has no fetcher. */
+export function noChatFetcherSentence(platform: string): string {
+ return `no chat fetcher for ${platform}: only YouTube's chat replay is fetched`;
+}
+
+export async function liveChatPlan(
+ paths: Paths,
+ slug: string,
+ videoId: string,
+ config: ChannelConfig,
+): Promise<LiveChatPlan> {
+ if (!isVideoIdSegment(videoId)) {
+ return { kind: "refused", error: `"${videoId}" is not a video id (one path segment)` };
+ }
+ const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
+ if (!(await isDirectory(videoDir))) return { kind: "refused", error: notFetchedRefusal(videoId, slug) };
+ const fresh = await isLiveChatCuesFresh(videoDir);
+ if (fresh.fresh) return { kind: "fresh", cuesPath: fresh.cuesPath };
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.includes(LIVE_CHAT_FILENAME) && entries.includes(META_FILENAME)) return { kind: "normalize" };
+ const url = await findVideoSourceUrl(paths, slug, videoId, config);
+ if (!url) {
+ return {
+ kind: "refused",
+ error: "Could not determine the video URL: no metadata.info.json and the playlist does not contain a matching entry.",
+ };
+ }
+ const platform = detectPlatform(url) ?? "unknown";
+ if (!CHAT_PLATFORMS.has(platform)) return { kind: "no-fetcher", platform };
+ const live = await liveStatusOf(videoDir);
+ if (live === "not_live") return { kind: "not-live", liveStatus: live };
+ return { kind: "fetch", url, platform };
+}
+
+function succeeded(exitCode: number | null): boolean {
+ // yt-dlp: 0 = clean, 101 = a clean stop.
+ return exitCode === 0 || exitCode === 101;
+}
+
+function tail(stderr: string): string {
+ return stderr.trim().split("\n").slice(-3).join(" / ");
+}
+
+export type ChatRunner = (cwd: string, args: string[]) => Promise<AttemptOutcome>;
+
+export type FetchLiveChatOpts = {
+ paths: Paths;
+ slug: string;
+ videoId: string;
+ videoUrl: string;
+ channelConfig: ChannelConfig;
+ cookiePolicy?: ResolvedCookiePolicy;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+ onPlatformBackoff?: () => Promise<void> | void;
+ onPlatformClean?: () => Promise<string | null> | string | null;
+ // Test seams: the spawn, and the platform pace in the argv.
+ run?: ChatRunner;
+ paceSeconds?: number;
+};
+
+export type FetchLiveChatResult =
+ | { status: "fetched"; messages: number; cuesPath: string }
+ | { status: "none" };
+
+/** The pass, then the normalize. Throws on a failed pass (the job ends `failed`). */
+export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveChatResult> {
+ const channelDir = path.join(opts.paths.channelsDir, opts.slug);
+ const videoDir = path.join(channelDir, "data", opts.videoId);
+ const policy: ResolvedCookiePolicy = opts.cookiePolicy ?? { cookies: undefined, mode: DEFAULT_COOKIE_MODE };
+ const run: ChatRunner =
+ opts.run ??
+ ((cwd, args) => runOneYtdlp({ ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal }, cwd, args));
+ if (!(await isDirectory(videoDir))) throw new Error(notFetchedRefusal(opts.videoId, opts.slug));
+ const pass = (cookies: string | undefined) =>
+ run(channelDir, liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl, opts.paceSeconds));
+
+ opts.onLog(`Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`);
+ const firstCookies = alwaysCookies(policy);
+ let outcome = await pass(firstCookies);
+ if (!succeeded(outcome.exitCode) && !opts.signal.aborted) {
+ const cls = parseUnavailableFromStderr(outcome.stderrTail);
+ const retryCookies = authRetryCookies(policy);
+ if (
+ classifyDownloadFailure(outcome.stderrTail, cls) !== "rate_limit" &&
+ AUTH_RETRY_CLASSES.has(cls) &&
+ retryCookies !== undefined &&
+ !firstCookies
+ ) {
+ opts.onLog(`The chat fetch needs a login (${cls}); retrying with --cookies-from-browser ${retryCookies}\n`);
+ outcome = await pass(retryCookies);
+ }
+ }
+ if (opts.signal.aborted) throw new Error("Cancelled");
+ if (!succeeded(outcome.exitCode)) {
+ const cls = parseUnavailableFromStderr(outcome.stderrTail);
+ if (classifyDownloadFailure(outcome.stderrTail, cls) === "rate_limit") {
+ await opts.onPlatformBackoff?.();
+ throw new Error(
+ `The source rate-limited the chat fetch of ${opts.videoId}; a per-platform cooldown has been recorded. ` +
+ `(${tail(outcome.stderrTail)})`,
+ );
+ }
+ throw new Error(`yt-dlp could not fetch the chat of ${opts.videoId} (exit ${outcome.exitCode ?? "null"}): ${tail(outcome.stderrTail)}`);
+ }
+ try {
+ const line = await opts.onPlatformClean?.();
+ if (line) opts.onLog(line);
+ } catch {
+ /* shared-state write is best-effort */
+ }
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (!entries.includes(LIVE_CHAT_FILENAME)) {
+ opts.onLog(`No chat replay for ${opts.videoId}: the source has none (chat replay off, or never live). Nothing written.\n`);
+ return { status: "none" };
+ }
+ return normalizeChat(opts, videoDir);
+}
+
+async function normalizeChat(
+ opts: Pick<FetchLiveChatOpts, "slug" | "videoId" | "channelConfig" | "onLog">,
+ videoDir: string,
+): Promise<FetchLiveChatResult> {
+ const out = await normalizeLiveChat({
+ videoDir,
+ channelSlug: opts.slug,
+ ...(opts.channelConfig.name ? { configName: opts.channelConfig.name } : {}),
+ force: true,
+ log: (m) => opts.onLog(`${m}\n`),
+ });
+ if (out.status === "skipped") {
+ throw new Error(`the chat of ${opts.videoId} could not be normalized (${out.reason})`);
+ }
+ const doc = await readNormalizedLiveChat(out.cuesPath);
+ const messages = doc?.cues?.length ?? 0;
+ opts.onLog(`Live chat of ${opts.videoId}: ${messages} message(s) in ${LIVE_CHAT_CUES_FILENAME}\n`);
+ return { status: "fetched", messages, cuesPath: out.cuesPath };
+}
+
+export type FetchChatJobOpts = {
+ paths: Paths;
+ slug: string;
+ videoId: string;
+ channelConfig: ChannelConfig;
+ cookiePolicy: ResolvedCookiePolicy;
+ queueKey?: string;
+ afterRun?: () => void | Promise<void>;
+ run?: ChatRunner;
+};
+
+// Every refusal before any job, in the sentences the rest of the app uses.
+export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamActionResult> {
+ const { paths, slug, videoId, channelConfig } = opts;
+ try {
+ await assertChannelTextReadable(paths, slug, channelConfig);
+ } catch (err) {
+ return { ok: false, error: (err as Error).message };
+ }
+ const plan = await liveChatPlan(paths, slug, videoId, channelConfig);
+ switch (plan.kind) {
+ case "refused":
+ return { ok: false, error: plan.error };
+ case "fresh":
+ return { ok: false, info: true, error: `the live chat of ${videoId} is already here (${LIVE_CHAT_CUES_FILENAME}, fresh)` };
+ case "no-fetcher":
+ return { ok: false, info: true, error: noChatFetcherSentence(plan.platform) };
+ case "not-live":
+ return { ok: false, info: true, error: `${videoId} was never live (live_status ${plan.liveStatus}): there is no chat replay` };
+ case "normalize":
+ case "fetch":
+ break;
+ }
+ if (plan.kind === "fetch") {
+ const held = await heldPlatformRefusal(plan.platform, "The chat fetch", paths);
+ if (held) return { ok: false, info: true, error: held };
+ const remainingMs = await platformCooldownRemainingMs(plan.platform, paths);
+ if (remainingMs > 0) {
+ return {
+ ok: false,
+ info: true,
+ error: `${plan.platform} is in a rate-limit cooldown (${Math.ceil(remainingMs / 1000)}s remaining). Fetch the chat once the cooldown lapses.`,
+ };
+ }
+ }
+ const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
+ return runManagedFunction({
+ kind: FETCH_CHAT_JOB_KIND,
+ queueKey: resolveQueueKey(downloadQueueKey(channelConfig), opts.queueKey),
+ paths,
+ channelSlug: slug,
+ videoId,
+ fn: async (onLog, signal) => {
+ if (plan.kind === "normalize") {
+ onLog(`The chat replay of ${videoId} is on disk; normalizing it (no network).`);
+ await normalizeChat({ slug, videoId, channelConfig, onLog }, videoDir);
+ } else {
+ await fetchLiveChat({
+ paths,
+ slug,
+ videoId,
+ videoUrl: plan.url,
+ channelConfig,
+ cookiePolicy: opts.cookiePolicy,
+ onLog,
+ signal,
+ onPlatformBackoff: () => recordDownloadBackoff(plan.platform, paths),
+ onPlatformClean: () => recordPlatformClean(plan.platform, paths),
+ ...(opts.run ? { run: opts.run } : {}),
+ });
+ }
+ await opts.afterRun?.();
+ },
+ });
+}
diff --git a/common/controller/findClips.test.ts b/common/controller/findClips.test.ts
@@ -0,0 +1,420 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { TranscribeFileRequest, TranscribeFileResult } from "./transcribeFile";
+import type { FindClipsDeps } from "./findClips";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/findClips.test.ts
+//
+// THE CHAIN END TO END WITH STUBS (release 36, lane A): the editor's ops
+// actions (a door that writes what each job would leave), the job registry
+// (every job done), the word timings (a fake engine result), diarization (a
+// started job that writes diarization.json) and umtool (a fetch that answers
+// the clips route's contract). No yt-dlp, no engine, no network. Every case
+// is its own video in one temp corpus.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "find-clips-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const { getSettings } = await import("../lib/settings");
+const {
+ FIND_CLIPS_RESULT_MARKER,
+ enqueueFindClips,
+ parseFindClipsBody,
+ planFindClipsSteps,
+ inspectFindClips,
+ projectSlugFor,
+ runFindClips,
+} = await import("./findClips");
+const { loadFindClipsRecord } = await import("../lib/findClipsRecord-server");
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-react";
+const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig;
+await mkdir(path.join(CORPUS, "channels", SLUG), { recursive: true });
+await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG));
+
+const SETTINGS_ON = () => {
+ const s = getSettings();
+ return {
+ ...s,
+ diarization: { ...s.diarization, enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx" },
+ autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, held: false } },
+ };
+};
+const SEGMENTS = [
+ { id: "s1", from: 290, to: 6300, subject: 4, host: 1, why: "subject 4 holds 81% of long-turn time" },
+ { id: "s2", from: 6500, to: 9278, subject: 16, host: 1, why: "subject 16 holds 77% of long-turn time" },
+];
+
+async function video(id: string, platformUrl = `https://www.youtube.com/watch?v=${id}`): Promise<string> {
+ const dir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: "Synth stream", webpage_url: platformUrl, was_live: true }));
+ return dir;
+}
+
+// Everything a finished chain leaves on disk, so every step is skipped.
+async function complete(dir: string) {
+ await writeFile(path.join(dir, "source-media.mp4"), "container");
+ await writeFile(path.join(dir, "audio.mp3"), "audio");
+ await writeFile(path.join(dir, "transcript.json"), JSON.stringify({ transcription: [] }));
+ await writeFile(path.join(dir, "words.json"), JSON.stringify({ version: 1, words: [{ w: "hello", start: 1, end: 1.4 }] }));
+ await writeFile(path.join(dir, "transcript.live_chat.json"), "\n");
+ await writeFile(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] }));
+ await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] }));
+}
+
+type Harness = {
+ deps: FindClipsDeps;
+ actions: { action: string; args: Record<string, unknown> }[];
+ umtoolCalls: { method: string; url: string; body?: unknown; auth?: string | null }[];
+ words: TranscribeFileRequest[];
+ diarized: number;
+ log: string[];
+};
+
+function harness(dir: string, o: { umtool?: "ok" | "down" | "refuses" | "fails" | "busy" | "exists"; paused?: boolean; pauseHeld?: string[]; chatFails?: boolean } = {}): Harness {
+ const h: Harness = { actions: [], umtoolCalls: [], words: [], diarized: 0, log: [], deps: null as unknown as FindClipsDeps };
+ let n = 0;
+ const editor = {
+ async run(action: string, args: Record<string, unknown>) {
+ h.actions.push({ action, args });
+ if (action === "persist-videos") await writeFile(path.join(dir, "source-media.mp4"), "container");
+ if (action === "transcribe-one") await writeFile(path.join(dir, "transcript.json"), JSON.stringify({ transcription: [] }));
+ if (action === "fetch-chat") {
+ if (o.chatFails) throw new Error("youtube is in a rate-limit cooldown (300s remaining)");
+ await writeFile(path.join(dir, "transcript.live_chat.json"), "\n");
+ await writeFile(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] }));
+ }
+ return { ok: true, jobId: `j${++n}` };
+ },
+ };
+ let polls = 0;
+ const fetchStub = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ const method = init?.method ?? "GET";
+ const auth = new Headers(init?.headers).get("authorization");
+ h.umtoolCalls.push({ method, url, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}), auth });
+ if (o.umtool === "down") throw new TypeError("fetch failed (ECONNREFUSED)");
+ if (method === "POST") {
+ if (o.umtool === "refuses") return Response.json({ error: "no diarization.json for synth-react/v" }, { status: 400 });
+ if (o.umtool === "exists") return Response.json({ error: "project v-clips already exists" }, { status: 409 });
+ if (o.umtool === "busy" && h.umtoolCalls.filter((c) => c.method === "POST").length < 3) {
+ return Response.json({ error: "a job is already running (clips-analyze)", running: { id: "u0" } }, { status: 409 });
+ }
+ return Response.json({
+ ok: true,
+ jobId: "u1",
+ job: { id: "u1" },
+ project: "v-clips",
+ created: true,
+ segments: SEGMENTS,
+ segment: "s1",
+ scope: [290, 6300],
+ href: "/projects/v-clips/clips",
+ notes: ["words.json copied in"],
+ });
+ }
+ polls++;
+ if (polls === 1) return Response.json({ state: "running", log: ["analyze: laughs 12"], next: 1 });
+ if (o.umtool === "fails") return Response.json({ state: "failed", error: "CED-mini exited 1", log: [], next: 1 });
+ return Response.json({ state: "done", log: ["propose: 18 clips, 612 s"], next: 2 });
+ }) as typeof fetch;
+ h.deps = {
+ paths,
+ editor,
+ jobOf: async () => ({ status: "done" }),
+ umtoolUrl: "http://127.0.0.1:9",
+ workerToken: "tok",
+ fetch: fetchStub,
+ settings: SETTINGS_ON,
+ pool: {
+ isPaused: () => o.paused === true,
+ enabledIds: () => (o.paused ? [] : ["gpu"]),
+ pauseHeldIds: () => o.pauseHeld ?? (o.paused ? ["gpu"] : []),
+ },
+ transcribeWords: async (req) => {
+ h.words.push(req);
+ return {
+ version: 1,
+ path: req.path,
+ window: null,
+ worker: { id: "gpu", name: "GPU", appId: "parakeet", model: "m.gguf", device: null },
+ transcriptFormat: "chough-json",
+ transcribedAt: "2026-10-19T00:00:00.000Z",
+ durationMs: 10,
+ waitedMs: 0,
+ cues: [{ start: 1, end: 2, text: "hello world" }],
+ text: "hello world",
+ words: [
+ { w: "hello", start: 1, end: 1.4 },
+ { w: "world", start: 1.5, end: 2 },
+ ],
+ } satisfies TranscribeFileResult;
+ },
+ diarize: async () => {
+ h.diarized++;
+ await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] }));
+ return { ok: true, jobId: "d1", stream: new ReadableStream<string>(), done: Promise.resolve({ status: "done" as const, jobId: "d1" }) };
+ },
+ pollMs: 1,
+ sleep: async () => {},
+ };
+ return h;
+}
+
+const run = (h: Harness, id: string, extra: Record<string, unknown> = {}) =>
+ runFindClips({ slug: SLUG, id, ...extra }, h.deps, {
+ config: CONFIG,
+ onLog: (l) => h.log.push(l),
+ signal: new AbortController().signal,
+ });
+
+test("the body: slug and id required; target, segment, project and the flags checked", () => {
+ assert.match((parseFindClipsBody({}) as { error: string }).error, /"slug" is required/);
+ assert.match((parseFindClipsBody({ slug: SLUG }) as { error: string }).error, /"id" is required/);
+ assert.match((parseFindClipsBody({ slug: SLUG, id: "v", target: 3 }) as { error: string }).error, /"target"/);
+ assert.match((parseFindClipsBody({ slug: SLUG, id: "v", segment: "s 2" }) as { error: string }).error, /"segment"/);
+ assert.match((parseFindClipsBody({ slug: SLUG, id: "v", project: "Bad_Slug" }) as { error: string }).error, /"project"/);
+ assert.match((parseFindClipsBody({ slug: SLUG, id: "v", whilePaused: "yes" }) as { error: string }).error, /"whilePaused"/);
+ assert.deepEqual(parseFindClipsBody({ slug: SLUG, id: "v", target: 600.4, segment: "s2", whilePaused: true, dryRun: false }), {
+ ok: true,
+ value: { slug: SLUG, id: "v", target: 600, segment: "s2", whilePaused: true },
+ });
+ assert.equal(projectSlugFor("fGSRhEWc9M4"), "fgsrhewc9m4-clips");
+ assert.equal(projectSlugFor("fGSRhEWc9M4", "s2"), "fgsrhewc9m4-clips-s2");
+});
+
+test("every step run: each in order, named in the log, outputs written, umtool followed", async () => {
+ const id = "runAll00001";
+ const dir = await video(id);
+ const h = harness(dir);
+ const r = await run(h, id, { target: 600, whilePaused: true });
+ assert.deepEqual(
+ h.actions.map((a) => a.action),
+ ["persist-videos", "transcribe-one", "fetch-chat"],
+ );
+ assert.deepEqual(h.actions[0].args, { items: [{ slug: SLUG, id }] });
+ assert.deepEqual(h.actions[1].args, { slug: SLUG, id, whilePaused: true });
+ assert.equal(h.words.length, 1);
+ assert.equal(h.words[0].words, true);
+ assert.equal(h.words[0].whilePaused, true);
+ assert.equal(h.words[0].path, path.join(dir, "source-media.mp4"), "the container when no audio file is here");
+ assert.equal(h.diarized, 1);
+ // words.json: the result without cues and text.
+ const words = JSON.parse(await readFile(path.join(dir, "words.json"), "utf8"));
+ assert.equal(words.words.length, 2);
+ assert.ok(!("cues" in words) && !("text" in words));
+ // umtool: the contract's body, the worker token, then the job followed.
+ const post = h.umtoolCalls[0];
+ assert.equal(post.method, "POST");
+ assert.equal(post.url, "http://127.0.0.1:9/api/report/clips");
+ assert.equal(post.auth, "Bearer tok");
+ assert.deepEqual(post.body, {
+ mode: "new",
+ slug: "runall00001-clips",
+ from: `${SLUG}/${id}`,
+ target: 600,
+ scope: "auto",
+ wordsPath: path.join(dir, "words.json"),
+ });
+ assert.match(h.umtoolCalls[1].url, /\?job=u1&since=0$/);
+ assert.match(h.umtoolCalls[2].url, /\?job=u1&since=1$/);
+ const text = h.log.join("\n");
+ for (const line of [
+ /running: saved video — no saved video/,
+ /running: corpus transcript — no corpus transcript/,
+ /running: word timings — transcribing source-media\.mp4 with word timings/,
+ /running: chat replay — fetching the chat replay/,
+ /running: diarization — no diarization\.json/,
+ /running: umtool — finding the segments and the clips/,
+ /umtool: analyze: laughs 12/,
+ /umtool: propose: 18 clips, 612 s/,
+ ]) {
+ assert.match(text, line);
+ }
+ assert.equal(r.project, "v-clips");
+ assert.equal(r.url, "http://127.0.0.1:9/projects/v-clips/clips");
+ assert.equal(r.created, true);
+ assert.equal(r.segment, "s1", "the segment auto-scope chose");
+ assert.match(text, /umtool: made project v-clips \(segment s1\) \(job u1\)/);
+ assert.match(text, /umtool: note: words\.json copied in/);
+ assert.deepEqual(r.segments.map((s) => s.id), ["s1", "s2"]);
+ assert.deepEqual(r.steps.map((s) => s.action), ["ran", "ran", "ran", "ran", "ran", "ran"]);
+});
+
+test("every step skipped: nothing asked of the editor or an engine; umtool still asked", async () => {
+ const id = "skipAll0001";
+ const dir = await video(id);
+ await complete(dir);
+ const h = harness(dir);
+ const r = await run(h, id, { segment: "s2" });
+ assert.deepEqual(h.actions, []);
+ assert.equal(h.words.length, 0);
+ assert.equal(h.diarized, 0);
+ const text = h.log.join("\n");
+ for (const line of [
+ /skipped: saved video — saved video present/,
+ /skipped: corpus transcript — transcript\.json present/,
+ /skipped: word timings — words\.json present \(1 words\)/,
+ /skipped: chat replay — live_chat\.cues\.json present/,
+ /skipped: diarization — diarization\.json present/,
+ /running: umtool — finding clips in segment s2/,
+ ]) {
+ assert.match(text, line);
+ }
+ assert.deepEqual(h.umtoolCalls[0].body, {
+ mode: "new",
+ slug: "skipall0001-clips-s2",
+ from: `${SLUG}/${id}`,
+ segment: "s2",
+ wordsPath: path.join(dir, "words.json"),
+ });
+ assert.equal(r.segment, "s2");
+ assert.deepEqual(r.steps.map((s) => s.action), ["skipped", "skipped", "skipped", "skipped", "skipped", "ran"]);
+});
+
+test("umtool down, refusing, or failing: a clear failure naming the step", async () => {
+ for (const [mode, re] of [
+ ["down", /^step umtool: umtool at http:\/\/127\.0\.0\.1:9 did not answer \(fetch failed \(ECONNREFUSED\)\) — is it running\?$/],
+ ["refuses", /^step umtool: umtool refused the clips request \(HTTP 400\): no diarization\.json/],
+ ["fails", /^step umtool: umtool job u1 failed: CED-mini exited 1$/],
+ ["exists", /^step umtool: umtool refused the clips request \(HTTP 409\): project v-clips already exists$/],
+ ] as const) {
+ const id = `um${mode}`.padEnd(11, "0");
+ const dir = await video(id);
+ await complete(dir);
+ await assert.rejects(run(harness(dir, { umtool: mode }), id), { message: re });
+ }
+});
+
+test("a busy umtool (409 naming its running job) is waited for, then asked again", async () => {
+ const id = "umbusy00001";
+ const dir = await video(id);
+ await complete(dir);
+ const h = harness(dir, { umtool: "busy" });
+ const r = await run(h, id);
+ assert.equal(r.project, "v-clips");
+ assert.equal(h.umtoolCalls.filter((c) => c.method === "POST").length, 3);
+ assert.equal(h.log.filter((l) => /umtool is busy \(a job is already running \(clips-analyze\)\); waiting for it/.test(l)).length, 1);
+});
+
+test("a twitch video skips the chat with the sentence; a refused chat fetch is logged and the chain goes on", async () => {
+ const tw = await video("twitch00001", "https://www.twitch.tv/videos/123");
+ await complete(tw);
+ await rm(path.join(tw, "live_chat.cues.json"));
+ await rm(path.join(tw, "transcript.live_chat.json"));
+ const h = harness(tw);
+ await run(h, "twitch00001");
+ assert.match(h.log.join("\n"), /skipped: chat replay — no chat fetcher for twitch: only YouTube's chat replay is fetched/);
+ assert.deepEqual(h.actions, []);
+
+ const yt = await video("chatfail001");
+ await complete(yt);
+ await rm(path.join(yt, "live_chat.cues.json"));
+ await rm(path.join(yt, "transcript.live_chat.json"));
+ const h2 = harness(yt, { chatFails: true });
+ const r = await run(h2, "chatfail001");
+ assert.match(h2.log.join("\n"), /the chat was not fetched \(step chat replay: fetch-chat refused: youtube is in a rate-limit cooldown/);
+ assert.equal(r.project, "v-clips", "the chain finished without the chat");
+});
+
+test("a paused pool fails the transcription step at once unless the run is whilePaused", async () => {
+ const id = "paused00001";
+ const dir = await video(id);
+ await writeFile(path.join(dir, "source-media.mp4"), "container");
+ await assert.rejects(run(harness(dir, { paused: true }), id), { message: /^step corpus transcript: the transcription workers are paused — run it with "while paused"/ });
+ // Paused, flagged, but no worker the pause alone switched off.
+ await assert.rejects(
+ run(harness(dir, { paused: true, pauseHeld: [] }), id, { whilePaused: true }),
+ { message: /^step corpus transcript: the workers are paused and none was switched off by the pause alone/ },
+ );
+ const h = harness(dir, { paused: true });
+ await run(h, id, { whilePaused: true });
+ assert.equal(h.actions.find((a) => a.action === "transcribe-one")?.args.whilePaused, true);
+ assert.equal(h.words[0].whilePaused, true);
+});
+
+test("diarization off or the backfill lane held fails the step with where to fix it", async () => {
+ const id = "diar0000001";
+ const dir = await video(id);
+ await complete(dir);
+ await rm(path.join(dir, "diarization.json"));
+ const off = harness(dir);
+ off.deps.settings = () => getSettings();
+ await assert.rejects(run(off, id), { message: /^step diarization: diarization is switched off, or its models are not set — set it up on \/operations\/diarization$/ });
+ const held = harness(dir);
+ held.deps.settings = () => {
+ const s = SETTINGS_ON();
+ return { ...s, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, held: true } } };
+ };
+ await assert.rejects(run(held, id), { message: /^step diarization: the backfill lane is held, and it holds a diarization run too — run Find clips "while paused"/ });
+
+ // whilePaused: the one-video diarization in this job, the lane left held.
+ let inline = 0;
+ held.deps.diarizeInline = async () => {
+ inline++;
+ await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] }));
+ return "diarized";
+ };
+ await run(held, id, { whilePaused: true });
+ assert.equal(inline, 1);
+ assert.equal(held.diarized, 0, "the lane job was not asked");
+ assert.match(held.log.join("\n"), /running: diarization — no diarization\.json: diarizing this one video in this job \(the backfill lane stays held\)/);
+ // An engine that fails names its outcome.
+ await rm(path.join(dir, "diarization.json"));
+ held.deps.diarizeInline = async () => "failed";
+ await assert.rejects(run(held, id, { whilePaused: true }), { message: /^step diarization: the one-video diarization ended "failed"$/ });
+});
+
+test("the dry run plans every step from the disk; the job writes find-clips.json and ends with the marker", async () => {
+ const id = "dryrun00001";
+ const dir = await video(id);
+ await writeFile(path.join(dir, "transcript.json"), "{}");
+ const state = await inspectFindClips(paths, SLUG, id, CONFIG);
+ assert.deepEqual(
+ planFindClipsSteps(state, {}).map((s) => [s.id, s.run]),
+ [["persist", true], ["transcript", false], ["words", true], ["chat", true], ["diarization", true], ["umtool", true]],
+ );
+ const h = harness(dir);
+ const dry = await enqueueFindClips({ slug: SLUG, id, dryRun: true }, h.deps);
+ assert.ok(dry.dryRun);
+ assert.equal(dry.plan.steps.length, 6);
+ assert.deepEqual(h.actions, [], "a dry run asks nothing");
+
+ // Refusals before a job.
+ const noUmtool = await enqueueFindClips({ slug: SLUG, id }, { ...h.deps, umtoolUrl: null });
+ assert.ok(!noUmtool.dryRun && !noUmtool.result.ok && /UMTOOL_URL is not set/.test(noUmtool.result.error));
+ const noVideo = await enqueueFindClips({ slug: SLUG, id: "nope" }, h.deps);
+ assert.ok(!noVideo.dryRun && !noVideo.result.ok && /not a video of synth-react/.test(noVideo.result.error));
+ const noChannel = await enqueueFindClips({ slug: "no-such-channel", id }, h.deps);
+ assert.ok(!noChannel.dryRun && !noChannel.result.ok && /not found/.test(noChannel.result.error));
+
+ const out = await enqueueFindClips({ slug: SLUG, id }, h.deps);
+ assert.ok(!out.dryRun && out.result.ok, JSON.stringify(out));
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ assert.equal(done.status, "done");
+ const record = await loadFindClipsRecord(dir);
+ assert.ok(record);
+ assert.equal(record.project, "v-clips");
+ assert.equal(record.url, "http://127.0.0.1:9/projects/v-clips/clips");
+ assert.equal(record.jobId, out.result.jobId);
+ assert.deepEqual(record.segments.map((s) => s.id), ["s1", "s2"]);
+ const log = await readFile(path.join(paths.jobsDir, `${out.result.jobId}.log`), "utf8");
+ const line = log.split("\n").find((l) => l.startsWith(FIND_CLIPS_RESULT_MARKER));
+ assert.ok(line, log);
+ assert.equal(JSON.parse(line.slice(FIND_CLIPS_RESULT_MARKER.length)).umtoolJob, "u1");
+});
diff --git a/common/controller/findClips.ts b/common/controller/findClips.ts
@@ -0,0 +1,718 @@
+// FIND CLIPS — the clip finder's whole chain for ONE video, as one job
+// (release 36, lane A): the video page's Find clips, `pnpm ops find-clips`.
+//
+// Release 35 ran this from a shell, step by step: persist the source video,
+// the corpus transcript, word timings (`pnpm ops transcribe {words:true}`),
+// diarization, then `umtool new --seed reactions` and `umtool clips
+// analyze`. Each of those is already an editor operation; what was missing
+// is the chain. This job runs it, in order, and SKIPS EVERY STEP WHOSE OUTPUT
+// IS ALREADY ON DISK, naming each in its log ("skipped: saved video — …",
+// "running: word timings — …"):
+//
+// persist no saved video (and no source container in the dir) →
+// `persist-videos {items: [{slug, id}]}`, waited on
+// transcript no corpus transcript (transcript.json or an English
+// caption track) → `transcribe-one {slug, id}`, waited on
+// words no words.json beside it → the file transcription with word
+// timestamps (transcribeFile.ts runTranscribeFile, words) IN
+// THIS JOB on a worker lease, written to data/<id>/words.json
+// (lib/wordTimings-server.ts) — reusable, so skippable
+// chat a YouTube video whose chat replay is not here and fresh →
+// `fetch-chat {slug, id}` (fetchLiveChat.ts), waited on; any
+// other platform is skipped with "no chat fetcher for …". The
+// chat is a signal, not a requirement: a refused or failed
+// fetch is logged and the chain goes on without it
+// diarization no diarization.json → the backfill lane's one-video run
+// (operationJobs.ts runBackfillChannelJob, the panel's Run),
+// waited on; with the lane HELD and a `whilePaused` run, the
+// one-video diarization in this job instead (diarizeOne.ts),
+// the hold left on
+// umtool `POST ${UMTOOL_URL}/api/report/clips {mode: "new", slug,
+// from, target?, scope: "auto" | segment, wordsPath}` with
+// `Authorization: Bearer WORKER_TOKEN` → {jobId, project,
+// created, segments}; then `GET ?job=<id>` followed to the end,
+// its log relayed here line by line
+//
+// The editor-side steps go through THE EDITOR'S OWN OPS ACTIONS IN PROCESS
+// (deps.editor — editor/app/api/ops/_researchEditor.ts findClipsEditor, the
+// research run's door): the same body checks, refusals and queues a `pnpm
+// ops` caller meets. Each is its own job on its own queue (the platform's
+// download queue, the transcription pool, the backfill queue), and this job
+// waits on it from the `find-clips` queue — never on a queue a step needs.
+//
+// WHAT HOLDS IT IS SAID, NOT WAITED ON FOREVER. A paused transcription pool
+// would park a transcription step until someone resumed it: unless the run
+// asked `whilePaused` (then the two transcriptions run on a worker the pause
+// alone switched off — workerPool.ts pauseHeld — and the pause stays on),
+// the step fails at once with the sentence. Diarization switched off fails
+// the same way, and so does a held backfill lane unless the run is
+// `whilePaused` ("this one video, past the holds"). umtool not answering
+// fails the umtool step with its URL.
+//
+// THE RESULT: the log ends with `@@find-clips {json}` (how `pnpm ops
+// find-clips --wait` prints it), and data/<id>/find-clips.json records it for
+// the video page — the project, its clip editor's URL, the segments umtool
+// found, and what each step did.
+
+import path from "node:path";
+import { readdir, stat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { SiteSettings } from "../lib/settings";
+import { getSettings } from "../lib/settings";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import { findSourceMedia, isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles";
+import { DIARIZATION_FILENAME, englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus";
+import { loadSavedVideo, resolveSavedVideo } from "../lib/savedVideo-server";
+import { backfillLaneOperations, DIARIZATION_OPERATION_ID } from "../lib/operations";
+import { isGateHeld } from "../lib/pauseGates";
+import { getWorkerToken } from "../lib/workerToken";
+import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl";
+import { loadWordTimings, writeWordTimings, wordTimingsSidecar, type WordTimingsRecord } from "../lib/wordTimings-server";
+import {
+ writeFindClipsRecord,
+ type FindClipsRecord,
+ type FindClipsSegment,
+ type FindClipsStepRecord,
+} from "../lib/findClipsRecord-server";
+import type { ResearchEditor } from "../lib/report/draft/research/tools";
+import { getWorkerPool, type WorkerPool } from "../jobs/workerPool";
+import { runManagedFunction, type JobRunContext, type StreamActionResult } from "../jobs/streamCommand";
+import { readChannelConfig, isValidChannelSlug } from "./channels";
+import { isVideoIdSegment } from "./refreshVideoMetadata";
+import { liveChatPlan, noChatFetcherSentence, type LiveChatPlan } from "./fetchLiveChat";
+import { runBackfillChannelJob, type BackfillChannelJobOptions } from "./operationJobs";
+import { diarizeOneVideo, type DiarizeOneOutcome } from "./diarizeOne";
+import { runTranscribeFile, type TranscribeFileRequest, type TranscribeFileResult } from "./transcribeFile";
+
+export const FIND_CLIPS_JOB_KIND = "find-clips";
+// Its own queue, one at a time: two chains over one machine would contend for
+// the same worker and the same umtool runner (which runs one job at a time).
+export const FIND_CLIPS_QUEUE = "find-clips";
+export const FIND_CLIPS_RESULT_MARKER = "@@find-clips ";
+export const FIND_CLIPS_BODY_KEYS = ["slug", "id", "target", "segment", "project", "whilePaused", "dryRun"] as const;
+// The editor actions the chain asks its door for.
+export const FIND_CLIPS_EDITOR_ACTIONS = ["persist-videos", "transcribe-one", "fetch-chat"] as const;
+
+export type FindClipsStepId = "persist" | "transcript" | "words" | "chat" | "diarization" | "umtool";
+
+export const FIND_CLIPS_STEP_LABELS: Record<FindClipsStepId, string> = {
+ persist: "saved video",
+ transcript: "corpus transcript",
+ words: "word timings",
+ chat: "chat replay",
+ diarization: "diarization",
+ umtool: "umtool",
+};
+
+export type FindClipsRequest = {
+ slug: string;
+ id: string;
+ // The cut's target length, seconds (umtool's default when absent).
+ target?: number;
+ // A segment umtool found ("s2"): find clips in that part only.
+ segment?: string;
+ // The umtool project's slug when one is made (default: from the id).
+ project?: string;
+ // Run the two transcriptions during a pause-all (workerPool.ts pauseHeld).
+ whilePaused?: boolean;
+ dryRun?: boolean;
+};
+
+type Check<T> = { ok: true; value: T } | { ok: false; error: string };
+
+const SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,31}$/i;
+const PROJECT_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
+
+/** The body's shape, judged without touching the disk. */
+export function parseFindClipsBody(body: Record<string, unknown>): Check<FindClipsRequest> {
+ const slug = body.slug;
+ if (typeof slug !== "string" || !isValidChannelSlug(slug)) {
+ return { ok: false, error: '"slug" is required: a channel slug' };
+ }
+ const id = body.id;
+ if (typeof id !== "string" || !isVideoIdSegment(id)) {
+ return { ok: false, error: '"id" is required: a video id (one path segment)' };
+ }
+ const out: FindClipsRequest = { slug, id };
+ if (body.target !== undefined) {
+ if (typeof body.target !== "number" || !Number.isFinite(body.target) || body.target < 10 || body.target > 6 * 3600) {
+ return { ok: false, error: '"target" is the cut\'s length in seconds (10 to 21600)' };
+ }
+ out.target = Math.round(body.target);
+ }
+ if (body.segment !== undefined) {
+ if (typeof body.segment !== "string" || !SEGMENT_RE.test(body.segment)) {
+ return { ok: false, error: '"segment" is a segment id umtool found ("s2")' };
+ }
+ out.segment = body.segment;
+ }
+ if (body.project !== undefined) {
+ if (typeof body.project !== "string" || !PROJECT_RE.test(body.project)) {
+ return { ok: false, error: '"project" is a umtool project slug (lowercase letters, digits and dashes)' };
+ }
+ out.project = body.project;
+ }
+ for (const key of ["whilePaused", "dryRun"] as const) {
+ const v = body[key];
+ if (v !== undefined && typeof v !== "boolean") return { ok: false, error: `"${key}" must be true or false` };
+ if (v === true) out[key] = true;
+ }
+ return { ok: true, value: out };
+}
+
+/** The umtool project slug a run makes when none is named: the id, lowercased, and the segment. */
+export function projectSlugFor(id: string, segment?: string): string {
+ const base = id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "video";
+ return `${base}-clips${segment ? `-${segment.toLowerCase()}` : ""}`.slice(0, 80);
+}
+
+/** The umtool clip editor of `project`. */
+export function umtoolProjectUrl(umtool: string, project: string): string {
+ return `${umtool}/projects/${encodeURIComponent(project)}/clips`;
+}
+
+// ─── what is on disk ───
+
+export type FindClipsState = {
+ // A saved-video pointer, or a source container in the video dir.
+ saved: boolean;
+ // What the word timings read: the preferred audio file, else the source
+ // container, else the saved video. Null when there is nothing to read.
+ audioPath: string | null;
+ // The corpus transcript's file name, or null.
+ transcript: string | null;
+ // Words in words.json, or null when it is absent.
+ words: number | null;
+ chat: LiveChatPlan;
+ diarization: boolean;
+};
+
+export async function inspectFindClips(
+ paths: Paths,
+ slug: string,
+ id: string,
+ config: ChannelConfig,
+): Promise<FindClipsState> {
+ const videoDir = path.join(paths.channelsDir, slug, "data", id);
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const pointer = await loadSavedVideo(videoDir).catch(() => null);
+ const container = findSourceMedia(entries);
+ const audio = pickPreferredAudio(entries.filter(isRealAudioFile));
+ let audioPath: string | null = audio ? path.join(videoDir, audio) : container ? path.join(videoDir, container) : null;
+ if (!audioPath && pointer) audioPath = await resolveSavedVideo(videoDir).catch(() => null);
+ const transcript = entries.includes(WHISPER_FILENAME) ? WHISPER_FILENAME : (englishVttsByPreference(entries)[0] ?? null);
+ const words = await loadWordTimings(videoDir).catch(() => null);
+ return {
+ saved: pointer !== null || container !== null,
+ audioPath,
+ transcript,
+ words: words ? words.words.length : null,
+ chat: await liveChatPlan(paths, slug, id, config),
+ diarization: entries.includes(DIARIZATION_FILENAME),
+ };
+}
+
+export type FindClipsPlanStep = { id: FindClipsStepId; label: string; run: boolean; why: string };
+
+/** What each step would do over `state` — the dry run, and the log's first lines. */
+export function planFindClipsSteps(state: FindClipsState, req: Pick<FindClipsRequest, "segment" | "target">): FindClipsPlanStep[] {
+ const step = (id: FindClipsStepId, run: boolean, why: string): FindClipsPlanStep => ({ id, label: FIND_CLIPS_STEP_LABELS[id], run, why });
+ const chat = state.chat;
+ return [
+ step("persist", !state.saved, state.saved ? "saved video present" : "no saved video: persist the source"),
+ step("transcript", state.transcript === null, state.transcript ? `${state.transcript} present` : "no corpus transcript: transcribe it"),
+ step("words", state.words === null, state.words !== null ? `words.json present (${state.words} words)` : "no words.json: transcribe with word timings"),
+ chat.kind === "fetch" || chat.kind === "normalize"
+ ? step("chat", true, chat.kind === "fetch" ? "no chat replay here: fetch it (YouTube)" : "the chat replay is here: normalize it")
+ : step(
+ "chat",
+ false,
+ chat.kind === "fresh"
+ ? "live_chat.cues.json present"
+ : chat.kind === "no-fetcher"
+ ? noChatFetcherSentence(chat.platform)
+ : chat.kind === "not-live"
+ ? "never live: no chat replay"
+ : chat.error,
+ ),
+ step("diarization", !state.diarization, state.diarization ? "diarization.json present" : "no diarization.json: diarize it"),
+ step("umtool", true, req.segment ? `find clips in segment ${req.segment}` : "find the segments and the clips"),
+ ];
+}
+
+// ─── the deps ───
+
+export type FindClipsDeps = {
+ paths: Paths;
+ // The editor's ops actions, in process (editor: _researchEditor.ts
+ // findClipsEditor). A refusal throws with the action's sentence.
+ editor: ResearchEditor;
+ // An editor job's state (researchRuns.ts jobOfPaths).
+ jobOf: (id: string) => Promise<{ status: string } | null>;
+ umtoolUrl?: string | null;
+ workerToken?: string;
+ fetch?: typeof fetch;
+ settings?: () => SiteSettings;
+ pool?: Pick<WorkerPool, "isPaused" | "enabledIds" | "pauseHeldIds">;
+ transcribeWords?: (
+ request: TranscribeFileRequest,
+ o: { onLog: (line: string) => void; signal: AbortSignal; ctx?: JobRunContext },
+ ) => Promise<TranscribeFileResult>;
+ diarize?: (o: BackfillChannelJobOptions) => Promise<StreamActionResult>;
+ // The one-video diarization in this job, for a held backfill lane and a
+ // whilePaused run (diarizeOne.ts diarizeOneVideo).
+ diarizeInline?: (o: { onLog: (line: string) => void; signal: AbortSignal }) => Promise<DiarizeOneOutcome>;
+ pollMs?: number;
+ // The pause before asking a busy umtool again (default 30 s).
+ busyWaitMs?: number;
+ sleep?: (ms: number) => Promise<void>;
+ now?: () => Date;
+ // Called inside the job after the record is written (the editor revalidates
+ // the video page here).
+ onDone?: () => void | Promise<void>;
+};
+
+const TERMINAL = new Set(["done", "failed", "cancelled"]);
+// How many times a busy umtool (409 naming its running job) is asked again,
+// `busyWaitMs` (30 s) apart: an hour.
+const UMTOOL_BUSY_TRIES = 120;
+
+class StepError extends Error {
+ constructor(step: FindClipsStepId, message: string) {
+ super(`step ${FIND_CLIPS_STEP_LABELS[step]}: ${message}`);
+ }
+}
+
+function sleeper(deps: FindClipsDeps): (ms: number) => Promise<void> {
+ return deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+}
+
+async function waitForJob(
+ deps: FindClipsDeps,
+ step: FindClipsStepId,
+ jobId: string,
+ signal: AbortSignal,
+ onLog: (line: string) => void,
+): Promise<string> {
+ const sleep = sleeper(deps);
+ const pollMs = deps.pollMs ?? 2000;
+ let misses = 0;
+ let last = "";
+ for (;;) {
+ if (signal.aborted) throw new StepError(step, `cancelled while job ${jobId} ran (it keeps running)`);
+ const j = await deps.jobOf(jobId).catch(() => null);
+ if (j && TERMINAL.has(j.status)) return j.status;
+ if (!j && ++misses > 30) throw new StepError(step, `job ${jobId} is not in the registry`);
+ if (j && j.status !== last) {
+ last = j.status;
+ if (j.status === "queued") onLog(` job ${jobId} is queued behind other work on its queue`);
+ }
+ await sleep(pollMs);
+ }
+}
+
+// Why a transcription step would park forever right now; null when it runs.
+function transcriptionBlocked(deps: FindClipsDeps, whilePaused: boolean): string | null {
+ const pool = deps.pool ?? getWorkerPool();
+ if (pool.isPaused()) {
+ if (!whilePaused) {
+ return "the transcription workers are paused — run it with \"while paused\" (whilePaused: true), or resume them on /workers";
+ }
+ if (pool.pauseHeldIds().length === 0) {
+ return "the workers are paused and none was switched off by the pause alone (a worker drained, degraded or disabled by hand is never used) — enable one on /workers";
+ }
+ return null;
+ }
+ if (pool.enabledIds().length === 0) return "no transcription worker is enabled — enable one on /workers";
+ return null;
+}
+
+function jobIdsOf(body: Record<string, unknown>): string[] {
+ if (Array.isArray(body.jobIds)) return body.jobIds.filter((x): x is string => typeof x === "string");
+ return typeof body.jobId === "string" ? [body.jobId] : [];
+}
+
+// One ops action through the door, then every job it started, waited on.
+async function runAction(
+ deps: FindClipsDeps,
+ step: FindClipsStepId,
+ action: (typeof FIND_CLIPS_EDITOR_ACTIONS)[number],
+ args: Record<string, unknown>,
+ signal: AbortSignal,
+ onLog: (line: string) => void,
+): Promise<void> {
+ let body: Record<string, unknown>;
+ try {
+ body = await deps.editor.run(action, args);
+ } catch (e) {
+ throw new StepError(step, `${action} refused: ${(e as Error).message}`);
+ }
+ for (const jobId of jobIdsOf(body)) {
+ onLog(` ${action}: job ${jobId}`);
+ const status = await waitForJob(deps, step, jobId, signal, onLog);
+ if (status !== "done") throw new StepError(step, `${action} job ${jobId} ended ${status} — its log on /jobs says why`);
+ onLog(` ${action}: job ${jobId} done`);
+ }
+}
+
+// ─── umtool ───
+
+type UmtoolNew = {
+ jobId: string;
+ project: string;
+ created: boolean;
+ segments: FindClipsSegment[];
+ // The segment umtool chose (the one asked, else auto-scope's), and the
+ // clip editor's path ("/projects/<id>/clips").
+ segment?: string;
+ href?: string;
+};
+
+function segmentsOf(v: unknown): FindClipsSegment[] {
+ if (!Array.isArray(v)) return [];
+ return v
+ .filter((s): s is Record<string, unknown> => !!s && typeof s === "object")
+ .filter((s) => typeof s.id === "string" && typeof s.from === "number" && typeof s.to === "number")
+ .map((s) => ({
+ id: s.id as string,
+ from: s.from as number,
+ to: s.to as number,
+ ...(typeof s.subject === "number" || typeof s.subject === "string" ? { subject: s.subject } : {}),
+ ...(typeof s.host === "number" || typeof s.host === "string" ? { host: s.host } : {}),
+ ...(typeof s.why === "string" ? { why: s.why } : {}),
+ }));
+}
+
+async function umtoolJson(res: Response): Promise<Record<string, unknown>> {
+ try {
+ const j = (await res.json()) as unknown;
+ return j && typeof j === "object" && !Array.isArray(j) ? (j as Record<string, unknown>) : {};
+ } catch {
+ return {};
+ }
+}
+
+async function runUmtool(
+ deps: FindClipsDeps,
+ o: { umtool: string; token: string; body: Record<string, unknown>; signal: AbortSignal; onLog: (line: string) => void },
+): Promise<UmtoolNew & { state: string }> {
+ const doFetch = deps.fetch ?? fetch;
+ const endpoint = `${o.umtool}/api/report/clips`;
+ const headers = { authorization: `Bearer ${o.token}`, "content-type": "application/json" };
+ const sleep = sleeper(deps);
+ let res!: Response;
+ let posted: Record<string, unknown> = {};
+ // umtool runs one job at a time: a 409 that names the running job is a
+ // wait, not a refusal (the run is retried until umtool is free); any other
+ // 409 (the project's slug exists) is a refusal.
+ for (let tries = 0; ; tries++) {
+ try {
+ res = await doFetch(endpoint, { method: "POST", headers, body: JSON.stringify(o.body), signal: o.signal });
+ } catch (e) {
+ if (o.signal.aborted) throw new StepError("umtool", "cancelled");
+ throw new StepError("umtool", `umtool at ${o.umtool} did not answer (${(e as Error).message}) — is it running?`);
+ }
+ posted = await umtoolJson(res);
+ if (res.status !== 409 || !posted.running || tries >= UMTOOL_BUSY_TRIES) break;
+ if (tries === 0) o.onLog(`umtool is busy (${typeof posted.error === "string" ? posted.error : "a job is running"}); waiting for it`);
+ await sleep(deps.busyWaitMs ?? 30_000);
+ if (o.signal.aborted) throw new StepError("umtool", "cancelled while waiting for umtool");
+ }
+ if (!res.ok) {
+ const why = typeof posted.error === "string" ? posted.error : `HTTP ${res.status}`;
+ throw new StepError("umtool", `umtool refused the clips request (HTTP ${res.status}): ${why}`);
+ }
+ const job = posted.job as { id?: unknown } | undefined;
+ const jobId = typeof posted.jobId === "string" ? posted.jobId : typeof job?.id === "string" ? job.id : null;
+ const project = typeof posted.project === "string" ? posted.project : null;
+ if (!jobId || !project) throw new StepError("umtool", `umtool's answer named no job or project: ${JSON.stringify(posted).slice(0, 300)}`);
+ const created = posted.created !== false;
+ let segments = segmentsOf(posted.segments);
+ const segment = typeof posted.segment === "string" && posted.segment ? posted.segment : undefined;
+ const href = typeof posted.href === "string" && posted.href.startsWith("/") ? posted.href : undefined;
+ o.onLog(`umtool: ${created ? "made" : "re-analyzing"} project ${project}${segment ? ` (segment ${segment})` : ""} (job ${jobId})`);
+ if (Array.isArray(posted.notes)) {
+ for (const n of posted.notes) if (typeof n === "string" && n.trim()) o.onLog(`umtool: note: ${n}`);
+ }
+ if (segments.length) o.onLog(`umtool: segments ${segments.map((s) => `${s.id} ${Math.round(s.from)}–${Math.round(s.to)} s`).join(", ")}`);
+
+ const pollMs = deps.pollMs ?? 2000;
+ let since = 0;
+ let failures = 0;
+ for (;;) {
+ if (o.signal.aborted) {
+ await doFetch(`${endpoint}?cancel=${encodeURIComponent(jobId)}`, { method: "POST", headers }).catch(() => null);
+ throw new StepError("umtool", `cancelled; umtool job ${jobId} was asked to stop`);
+ }
+ let view: Record<string, unknown> | null = null;
+ try {
+ const r = await doFetch(`${endpoint}?job=${encodeURIComponent(jobId)}&since=${since}`, { headers, signal: o.signal });
+ if (r.status === 404) throw new StepError("umtool", `umtool no longer knows job ${jobId} (restarted?)`);
+ if (r.ok) view = await umtoolJson(r);
+ } catch (e) {
+ if (e instanceof StepError) throw e;
+ }
+ if (!view) {
+ if (++failures >= 15) throw new StepError("umtool", `umtool at ${o.umtool} stopped answering while job ${jobId} ran`);
+ } else {
+ failures = 0;
+ const log = Array.isArray(view.log) ? view.log.filter((l): l is string => typeof l === "string") : [];
+ for (const line of log) o.onLog(`umtool: ${line.replace(/\n$/, "")}`);
+ if (typeof view.next === "number") since = view.next;
+ else since += log.length;
+ if (Array.isArray(view.segments)) segments = segmentsOf(view.segments);
+ const state = typeof view.state === "string" ? view.state : "running";
+ if (state !== "running") {
+ if (state !== "done") {
+ const why = typeof view.error === "string" && view.error ? view.error : `the job ended ${state}`;
+ throw new StepError("umtool", `umtool job ${jobId} failed: ${why}`);
+ }
+ return { jobId, project, created, segments, state, ...(segment ? { segment } : {}), ...(href ? { href } : {}) };
+ }
+ }
+ await sleep(pollMs);
+ }
+}
+
+// ─── the chain ───
+
+export type FindClipsResult = Omit<FindClipsRecord, "version" | "at" | "jobId"> & { umtoolJob: string };
+
+export async function runFindClips(
+ req: FindClipsRequest,
+ deps: FindClipsDeps,
+ o: { config: ChannelConfig; onLog: (line: string) => void; signal: AbortSignal; ctx?: JobRunContext },
+): Promise<FindClipsResult> {
+ const { paths } = deps;
+ const { onLog, signal } = o;
+ const { slug, id } = req;
+ const videoDir = path.join(paths.channelsDir, slug, "data", id);
+ const whilePaused = req.whilePaused === true;
+ const settings = (deps.settings ?? getSettings)();
+ const umtool = deps.umtoolUrl === undefined ? resolveUmtoolUrl() : deps.umtoolUrl;
+ const token = deps.workerToken ?? getWorkerToken();
+ if (!umtool) throw new StepError("umtool", "UMTOOL_URL is not set on the editor");
+ if (!token) throw new StepError("umtool", "WORKER_TOKEN is not set on the editor");
+ const steps: FindClipsStepRecord[] = [];
+ const skip = (s: FindClipsStepId, why: string) => {
+ steps.push({ id: s, label: FIND_CLIPS_STEP_LABELS[s], action: "skipped", why });
+ onLog(`skipped: ${FIND_CLIPS_STEP_LABELS[s]} — ${why}`);
+ };
+ const running = (s: FindClipsStepId, why: string) => {
+ steps.push({ id: s, label: FIND_CLIPS_STEP_LABELS[s], action: "ran", why });
+ onLog(`running: ${FIND_CLIPS_STEP_LABELS[s]} — ${why}`);
+ };
+ const inspect = () => inspectFindClips(paths, slug, id, o.config);
+ onLog(`Find clips in ${slug}/${id}${req.segment ? ` (segment ${req.segment})` : ""}${whilePaused ? " — while paused" : ""}`);
+
+ // 1. the saved video
+ let state = await inspect();
+ if (state.saved) skip("persist", "saved video present");
+ else {
+ running("persist", "no saved video: persisting the source");
+ await runAction(deps, "persist", "persist-videos", { items: [{ slug, id }] }, signal, onLog);
+ state = await inspect();
+ if (!state.saved) throw new StepError("persist", "the source video is still not saved after persist-videos");
+ }
+
+ // 2. the corpus transcript
+ if (state.transcript) skip("transcript", `${state.transcript} present`);
+ else {
+ const held = transcriptionBlocked(deps, whilePaused);
+ if (held) throw new StepError("transcript", held);
+ running("transcript", "no corpus transcript: transcribing");
+ await runAction(deps, "transcript", "transcribe-one", { slug, id, ...(whilePaused ? { whilePaused: true } : {}) }, signal, onLog);
+ state = await inspect();
+ if (!state.transcript) throw new StepError("transcript", "transcribe-one ended without a transcript");
+ }
+
+ // 3. word timings
+ let wordsPath: string | null = null;
+ if (state.words !== null) {
+ skip("words", `words.json present (${state.words} words)`);
+ wordsPath = wordTimingsSidecar.path(videoDir);
+ } else {
+ if (!state.audioPath) throw new StepError("words", "no audio, source container or saved video to read");
+ const held = transcriptionBlocked(deps, whilePaused);
+ if (held) throw new StepError("words", held);
+ running("words", `transcribing ${path.basename(state.audioPath)} with word timings`);
+ const transcribe =
+ deps.transcribeWords ??
+ ((request, t) => runTranscribeFile({ paths, request, onLog: t.onLog, signal: t.signal, ...(t.ctx ? { ctx: t.ctx } : {}) }));
+ let r: TranscribeFileResult;
+ try {
+ r = await transcribe(
+ { path: state.audioPath, words: true, ...(whilePaused ? { whilePaused: true } : {}) },
+ { onLog, signal, ...(o.ctx ? { ctx: o.ctx } : {}) },
+ );
+ } catch (e) {
+ throw new StepError("words", (e as Error).message);
+ }
+ const words = r.words ?? [];
+ if (words.length === 0) {
+ onLog(` ${r.worker.appId} [${r.worker.id}] keeps no word timestamps: the clips' edges sit on the transcript's cues`);
+ } else {
+ const { cues: _cues, text: _text, ...rest } = r;
+ const record: WordTimingsRecord = { ...rest, words } as WordTimingsRecord;
+ await writeWordTimings(videoDir, record);
+ wordsPath = wordTimingsSidecar.path(videoDir);
+ onLog(` ${words.length} words → words.json (${r.worker.appId} [${r.worker.id}])`);
+ }
+ }
+
+ // 4. the chat replay (a signal, never a requirement)
+ const chat = state.chat;
+ if (chat.kind === "fetch" || chat.kind === "normalize") {
+ running("chat", chat.kind === "fetch" ? "fetching the chat replay (YouTube, paced)" : "normalizing the chat replay on disk");
+ try {
+ await runAction(deps, "chat", "fetch-chat", { slug, id }, signal, onLog);
+ } catch (e) {
+ if (signal.aborted) throw e;
+ onLog(` the chat was not fetched (${(e as Error).message}) — going on without it`);
+ }
+ } else {
+ skip(
+ "chat",
+ chat.kind === "fresh"
+ ? "live_chat.cues.json present"
+ : chat.kind === "no-fetcher"
+ ? noChatFetcherSentence(chat.platform)
+ : chat.kind === "not-live"
+ ? "never live: no chat replay"
+ : chat.error,
+ );
+ }
+
+ // 5. diarization
+ if (state.diarization) skip("diarization", "diarization.json present");
+ else {
+ if (!backfillLaneOperations(settings).some((op) => op.id === DIARIZATION_OPERATION_ID)) {
+ throw new StepError("diarization", "diarization is switched off, or its models are not set — set it up on /operations/diarization");
+ }
+ const laneHeld = isGateHeld(settings, "backfill");
+ if (laneHeld && !whilePaused) {
+ throw new StepError(
+ "diarization",
+ "the backfill lane is held, and it holds a diarization run too — run Find clips \"while paused\" (whilePaused: true) to diarize this one video in this job, or lift the hold",
+ );
+ }
+ if (laneHeld) {
+ // PAST THE HOLD, for this one video: the one-video diarization in this
+ // job (diarizeOne.ts — what a transcription's inline pass runs), the
+ // lane's hold left on.
+ running("diarization", "no diarization.json: diarizing this one video in this job (the backfill lane stays held)");
+ const diarizeInline =
+ deps.diarizeInline ??
+ ((d: { onLog: (l: string) => void; signal: AbortSignal }) =>
+ diarizeOneVideo({ paths, videoDir, videoId: id, settings: settings.diarization, onLog: d.onLog, signal: d.signal }));
+ const outcome = await diarizeInline({ onLog, signal });
+ if (outcome !== "diarized" && outcome !== "already-exists") {
+ throw new StepError("diarization", `the one-video diarization ended "${outcome}"`);
+ }
+ } else {
+ running("diarization", "no diarization.json: diarizing (the backfill lane's one-video run)");
+ const diarize = deps.diarize ?? runBackfillChannelJob;
+ const started = await diarize({ paths, channelSlug: slug, kindIds: [DIARIZATION_OPERATION_ID], ids: [id] });
+ if (!started.ok) throw new StepError("diarization", started.error);
+ void started.stream.cancel();
+ onLog(` backfill-channel: job ${started.jobId}`);
+ const done = await started.done;
+ if (done.status !== "done") throw new StepError("diarization", `job ${started.jobId} ended ${done.status}`);
+ }
+ state = await inspect();
+ if (!state.diarization) throw new StepError("diarization", "no diarization.json was written — the log above says why");
+ }
+
+ // 6. umtool
+ const project = req.project ?? projectSlugFor(id, req.segment);
+ running("umtool", req.segment ? `finding clips in segment ${req.segment}` : "finding the segments and the clips");
+ const u = await runUmtool(deps, {
+ umtool,
+ token,
+ signal,
+ onLog,
+ body: {
+ mode: "new",
+ slug: project,
+ from: `${slug}/${id}`,
+ ...(req.target !== undefined ? { target: req.target } : {}),
+ ...(req.segment ? { segment: req.segment } : { scope: "auto" }),
+ ...(wordsPath ? { wordsPath } : {}),
+ },
+ });
+ return {
+ project: u.project,
+ url: u.href ? `${umtool}${u.href}` : umtoolProjectUrl(umtool, u.project),
+ created: u.created,
+ ...(req.segment ?? u.segment ? { segment: req.segment ?? u.segment } : {}),
+ segments: u.segments,
+ steps,
+ umtoolJob: u.jobId,
+ };
+}
+
+// ─── the job ───
+
+export type FindClipsPlan = {
+ slug: string;
+ id: string;
+ umtoolUrl: string | null;
+ workersPaused: boolean;
+ steps: FindClipsPlanStep[];
+};
+
+export type FindClipsEnqueued =
+ | { dryRun: true; plan: FindClipsPlan }
+ | { dryRun: false; result: StreamActionResult };
+
+/** Validate; a dry run's plan; else the job. Every refusal is `{ok: false}` before a job exists. */
+export async function enqueueFindClips(body: Record<string, unknown>, deps: FindClipsDeps): Promise<FindClipsEnqueued> {
+ const refuse = (error: string): FindClipsEnqueued => ({ dryRun: false, result: { ok: false, error } });
+ const parsed = parseFindClipsBody(body);
+ if (!parsed.ok) return refuse(parsed.error);
+ const req = parsed.value;
+ const { paths } = deps;
+ const config = await readChannelConfig(paths, req.slug);
+ if (!config) return refuse(`Channel "${req.slug}" not found`);
+ try {
+ await assertChannelTextReadable(paths, req.slug, config);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const videoDir = path.join(paths.channelsDir, req.slug, "data", req.id);
+ if (!(await stat(videoDir).then((s) => s.isDirectory(), () => false))) {
+ return refuse(`"${req.id}" is not a video of ${req.slug} (no data/${req.id}/): import or sync it first`);
+ }
+ const state = await inspectFindClips(paths, req.slug, req.id, config);
+ const umtool = deps.umtoolUrl === undefined ? resolveUmtoolUrl() : deps.umtoolUrl;
+ const pool = deps.pool ?? getWorkerPool();
+ if (req.dryRun) {
+ return {
+ dryRun: true,
+ plan: { slug: req.slug, id: req.id, umtoolUrl: umtool, workersPaused: pool.isPaused(), steps: planFindClipsSteps(state, req) },
+ };
+ }
+ if (!umtool) return refuse("UMTOOL_URL is not set on the editor: Find clips hands the recording to umtool's clip finder (e.g. UMTOOL_URL=http://localhost:3050)");
+ if (!(deps.workerToken ?? getWorkerToken())) return refuse("WORKER_TOKEN is not set on the editor: umtool's clips route is asked with it");
+ const now = deps.now ?? (() => new Date());
+ return {
+ dryRun: false,
+ result: await runManagedFunction({
+ kind: FIND_CLIPS_JOB_KIND,
+ queueKey: FIND_CLIPS_QUEUE,
+ paths,
+ channelSlug: req.slug,
+ videoId: req.id,
+ fn: async (onLog, signal, _setProgress, ctx) => {
+ const r = await runFindClips(req, { ...deps, umtoolUrl: umtool }, { config, onLog, signal, ctx });
+ const { umtoolJob: _u, ...kept } = r;
+ const record: FindClipsRecord = { version: 1, at: now().toISOString(), jobId: ctx.jobId, ...kept };
+ await writeFindClipsRecord(path.join(paths.channelsDir, req.slug, "data", req.id), record);
+ onLog(`Done: ${r.segments.length} segment(s); the clips are in ${r.url}`);
+ onLog(`${FIND_CLIPS_RESULT_MARKER}${JSON.stringify({ ...record, umtoolJob: r.umtoolJob })}`);
+ await deps.onDone?.();
+ },
+ }),
+ };
+}
diff --git a/common/controller/transcribeFile.test.ts b/common/controller/transcribeFile.test.ts
@@ -552,3 +552,41 @@ test("a short file goes ahead of parked transcriptions — the lane's and a manu
// before it got it after, in their own order (manual before the lane).
assert.deepEqual(order, ["batch after the file", "lane after the file"]);
});
+
+// --- run while paused (release 36, lane A) -------------------------------------
+
+test("whilePaused is a boolean, kept only when true", () => {
+ const parsed = (b: Record<string, unknown>) => parseTranscribeFileBody({ path: MEDIA, ...b });
+ assert.match((parsed({ whilePaused: 1 }) as { error: string }).error, /"whilePaused" must be true or false/);
+ const on = parsed({ whilePaused: true });
+ assert.ok(on.ok && on.value.whilePaused === true);
+ const off = parsed({ whilePaused: false });
+ assert.ok(off.ok && !("whilePaused" in off.value));
+});
+
+test("a named worker the pause alone switched off is not refused when the request runs whilePaused", async () => {
+ const workerStates = new Map([
+ ["gpu", { state: "disabled", degraded: false }],
+ ["cpu", { state: "disabled", degraded: false }],
+ ]);
+ const pauseHeldIds = new Set(["gpu"]);
+ assert.equal(await check({ workerId: "gpu", whilePaused: true }, { workerStates, pauseHeldIds }), null);
+ assert.match((await check({ workerId: "gpu" }, { workerStates, pauseHeldIds }))!, /"gpu" is disabled/);
+ // cpu was switched off by hand: never a pause-held worker.
+ assert.match((await check({ workerId: "cpu", whilePaused: true }, { workerStates, pauseHeldIds }))!, /"cpu" is disabled/);
+});
+
+test("a paused pool runs a whilePaused file job on a pause-held worker and stays paused", async () => {
+ const pool = getWorkerPool();
+ pool.pauseAll();
+ try {
+ const run = await runJob({ path: MEDIA, workerId: "gpu", whilePaused: true });
+ assert.equal(run.status, "done", run.log);
+ assert.equal(run.result.worker.id, "gpu");
+ assert.match(run.log, /The workers are paused: this one transcription may run on a worker the pause holds/);
+ assert.ok(pool.isPaused(), "the pause stays on");
+ assert.equal(pool.summary().find((w) => w.id === "gpu")?.state, "disabled");
+ } finally {
+ pool.resumeAll();
+ }
+});
diff --git a/common/controller/transcribeFile.ts b/common/controller/transcribeFile.ts
@@ -76,6 +76,7 @@ export const TRANSCRIBE_FILE_BODY_KEYS = [
"workerId",
"out",
"words",
+ "whilePaused",
] as const;
const AUDIO_NAME = "audio.wav";
@@ -113,6 +114,10 @@ export type TranscribeFileRequest = {
// True returns the engine's word timestamps as well as the cues. Only an
// engine that keeps them (parakeet) answers with any; the rest give none.
words?: boolean;
+ // True runs it during a pause-all on a worker the pause alone switched off
+ // (release 36, lane A; the pool's acquire `whilePaused`). Outside a pause it
+ // changes nothing.
+ whilePaused?: boolean;
};
// One word as the engine timed it, on the source file's clock (seconds).
@@ -196,6 +201,10 @@ export function parseTranscribeFileBody(
if (words !== undefined && typeof words !== "boolean") {
return { ok: false, error: '"words" must be true or false' };
}
+ const whilePaused = body.whilePaused;
+ if (whilePaused !== undefined && typeof whilePaused !== "boolean") {
+ return { ok: false, error: '"whilePaused" must be true or false' };
+ }
return {
ok: true,
value: {
@@ -205,6 +214,7 @@ export function parseTranscribeFileBody(
...(typeof workerId === "string" ? { workerId: workerId.trim() } : {}),
...(typeof out === "string" ? { out: path.resolve(out) } : {}),
...(words === true ? { words: true } : {}),
+ ...(whilePaused === true ? { whilePaused: true } : {}),
},
};
}
@@ -301,6 +311,9 @@ export type TranscribeFileContext = {
// The pool's runtime view (id → state). A named worker switched off on the
// Workers page is refused rather than waited for: the wait would be forever.
workerStates?: ReadonlyMap<string, { state: string; degraded: boolean }>;
+ // The workers the pause-all ALONE switched off (the pool's pauseHeldIds): a
+ // named one is not refused when the request runs `whilePaused`.
+ pauseHeldIds?: ReadonlySet<string>;
};
export async function checkTranscribeFileRequest(
@@ -369,7 +382,8 @@ export async function checkTranscribeFileRequest(
};
}
const runtime = ctx.workerStates?.get(req.workerId);
- if (runtime && (runtime.state !== "enabled" || runtime.degraded)) {
+ const heldByPause = req.whilePaused === true && ctx.pauseHeldIds?.has(req.workerId) === true;
+ if (runtime && !heldByPause && (runtime.state !== "enabled" || runtime.degraded)) {
return {
ok: false,
error: `worker "${req.workerId}" is ${
@@ -522,6 +536,7 @@ export async function runTranscribeFile(
},
skipInlineDiarization: true,
...(req.words ? { words: true } : {}),
+ ...(req.whilePaused ? { whilePaused: true } : {}),
});
const finished = Date.now();
const worker = used.worker;
@@ -573,6 +588,7 @@ export async function enqueueTranscribeFile(
workers: settings.workers,
locations: settings.storage?.locations ?? [],
workerStates,
+ pauseHeldIds: new Set(pool.pauseHeldIds()),
});
if (!checked.ok) return checked;
const req = checked.value;
diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts
@@ -589,6 +589,10 @@ export type TranscribeWithWorkerOptions = {
words?: boolean;
// See TranscribeOneOptions.salvage.
salvage?: boolean;
+ // RUN WHILE PAUSED (release 36, lane A): during a pause-all, this one manual
+ // transcription may take a worker the pause alone switched off (the pool's
+ // acquire `whilePaused`). Never passed by a lane or batch.
+ whilePaused?: boolean;
};
// Acquire a worker from the global pool and transcribe one video through it,
@@ -607,6 +611,9 @@ export async function transcribeWithWorker(
opts.signal && opts.drainSignal
? AbortSignal.any([opts.signal, opts.drainSignal])
: (opts.signal ?? opts.drainSignal);
+ if (opts.whilePaused && pool.isPaused()) {
+ log("The workers are paused: this one transcription may run on a worker the pause holds (whilePaused); the pause stays on.");
+ }
let lastErr: unknown;
for (let attempt = 0; attempt < MAX_WORKER_ATTEMPTS; attempt++) {
if (opts.signal?.aborted || opts.drainSignal?.aborted) throw abortError();
@@ -616,6 +623,7 @@ export async function transcribeWithWorker(
background: opts.background,
...(opts.tier ? { tier: opts.tier } : {}),
...(opts.only ? { only: opts.only } : {}),
+ ...(opts.whilePaused ? { whilePaused: true } : {}),
});
} catch (err) {
// An `only` no configured worker passes is refused at once — that is
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -681,6 +681,40 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
needsMedia: false,
needsText: true,
},
+ // ONE VIDEO'S LIVE CHAT REPLAY (release 36 lane A, controller/
+ // fetchLiveChat.ts — `pnpm ops fetch-chat`, and the find-clips job's chat
+ // step): the chat-only yt-dlp pass, then live_chat.cues.json. On the
+ // platform download queue, paced and cookie-aware like the metadata
+ // refresh. `needsMedia`: it WRITES the raw replay, a tierable big file the
+ // normalizer moves into media/. An ingest kind: the index reads the cues.
+ // Not replayable: a retry is the same ops call, which re-asks the plan.
+ "fetch-chat": {
+ kind: "fetch-chat",
+ label: "Fetch live chat",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "platform",
+ needsMedia: true,
+ },
+ // FIND CLIPS (release 36 lane A, controller/findClips.ts — the video page's
+ // Find clips, `pnpm ops find-clips`): the clip finder's chain for one video,
+ // each step skipped when its output exists — persist the source, the corpus
+ // transcript, word timings, the chat replay, diarization — then umtool's
+ // `POST /api/report/clips {mode: "new"}`, followed to the end. Its steps
+ // are jobs of their own (persist-videos, transcribe-one, fetch-chat,
+ // backfill-channel) on their own queues, waited on from here; the word
+ // timings run in this job on a worker lease. Its own queue (`find-clips`),
+ // so it never holds a queue its steps need. `needsMedia`: the word timings
+ // read the audio. Not replayable: the button asks again, and the steps
+ // already done are skipped.
+ "find-clips": {
+ kind: "find-clips",
+ label: "Find clips",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ },
// An Odysee video's record (or the channel's listing) read from its page in
// a headless browser (release 32 R9, controller/browserLookupJob.ts), when
// yt-dlp's lookup is refused. On the platform download queue, so it never
@@ -1243,6 +1277,9 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([
"prepare-playable",
// A gone video's audio from a copy, and the copy's provenance (release 31).
"fetch-copies",
+ // One video's live chat replay, normalized into the cues the index reads
+ // (release 36 lane A).
+ "fetch-chat",
]);
export function isIngestKind(kind: string | undefined): boolean {
diff --git a/common/jobs/workerPool.ts b/common/jobs/workerPool.ts
@@ -73,6 +73,10 @@ export type WorkerSummary = {
// GPU worker beside two explicitly CPU-pinned ones, and treating those as GPU
// contention stopped the digest lane dead for work that used no shaders at all.
device?: string;
+ // During a pause-all: this worker was switched off by the pause ALONE, so a
+ // `whilePaused` acquire may take it (release 36 lane A; see pauseHeld).
+ // Absent outside a pause and for every other worker.
+ pauseHeld?: true;
};
type PoolEntry = {
@@ -104,6 +108,9 @@ type Waiter = {
// A further restriction on WHICH worker may serve this waiter (acquire's
// opts.only). Matched alongside `requires`, never instead of it.
only?: WorkerFilter;
+ // acquire's opts.whilePaused: during a pause-all this waiter may also be
+ // served by a worker the pause alone switched off (see pauseHeld).
+ whilePaused?: boolean;
};
// Narrows an acquire to particular workers — by id, by kind — on top of the
@@ -324,13 +331,43 @@ export class WorkerPool {
return this.pausedSnapshot !== null;
}
+ // RUN WHILE PAUSED (release 36, lane A): a worker the pause-all ALONE
+ // switched off — the pool is paused, the worker is disabled, and the state
+ // the pause recorded for it is `enabled`. Such a worker may serve ONE manual
+ // acquire that asked with `whilePaused` (the video page's "Transcribe now
+ // (workers paused)", the find-clips job). Never a worker drained, degraded
+ // or turned off by hand: those record `disabled` in the snapshot (the
+ // runtime controls' syncSnapshot), or a degrade mark the eligibility check
+ // refuses on its own. The snapshot is only READ here: the lease leaves the
+ // worker `disabled`, so when it releases the worker is still paused, and
+ // resumeAll restores it exactly as before.
+ private pauseHeld(id: string, entry: PoolEntry): boolean {
+ return (
+ this.pausedSnapshot !== null &&
+ entry.state === "disabled" &&
+ this.pausedSnapshot.get(id) === "enabled"
+ );
+ }
+
+ // The ids of every worker pauseHeld would lease to a whilePaused acquire
+ // right now (busy or not) — what a refusal of a named worker asks, and what
+ // the page asks before it offers "Transcribe now (workers paused)".
+ pauseHeldIds(): string[] {
+ this.ensureInit();
+ return Array.from(this.entries.entries())
+ .filter(([id, e]) => this.pauseHeld(id, e) && !e.degraded)
+ .map(([id]) => id);
+ }
+
private eligible(
entry: PoolEntry,
requires?: readonly string[],
only?: WorkerFilter,
+ whilePaused?: boolean,
): boolean {
return (
- entry.state === "enabled" &&
+ (entry.state === "enabled" ||
+ (whilePaused === true && this.pauseHeld(entry.config.id, entry))) &&
!entry.degraded &&
!entry.busy &&
workerMatches(entry.config, requires) &&
@@ -343,10 +380,11 @@ export class WorkerPool {
private pickFree(
requires?: readonly string[],
only?: WorkerFilter,
+ whilePaused?: boolean,
): PoolEntry | null {
let best: PoolEntry | null = null;
for (const entry of this.entries.values()) {
- if (!this.eligible(entry, requires, only)) continue;
+ if (!this.eligible(entry, requires, only, whilePaused)) continue;
if (!best || entry.config.priority < best.config.priority) best = entry;
}
return best;
@@ -381,7 +419,7 @@ export class WorkerPool {
let granted = false;
for (let i = 0; i < this.waiters.length; i++) {
const waiter = this.waiters[i];
- const entry = this.pickFree(waiter.requires, waiter.only);
+ const entry = this.pickFree(waiter.requires, waiter.only, waiter.whilePaused);
if (!entry) continue;
this.waiters.splice(i, 1);
waiter.onAbort?.();
@@ -423,6 +461,9 @@ export class WorkerPool {
// caller should treat the work as unrunnable rather than wedge.
// opts.only narrows the lease further, to the workers the filter accepts (see
// WorkerFilter); a filter no configured worker passes rejects the same way.
+ // opts.whilePaused lets a MANUAL acquire run during a pause-all on a worker
+ // the pause alone switched off (see pauseHeld); outside a pause it changes
+ // nothing. Background (lane) acquires never pass it.
acquire(
signal?: AbortSignal,
opts?: {
@@ -430,6 +471,7 @@ export class WorkerPool {
background?: boolean;
requires?: readonly string[];
only?: WorkerFilter;
+ whilePaused?: boolean;
},
): Promise<Lease> {
this.ensureInit();
@@ -459,14 +501,22 @@ export class WorkerPool {
);
}
}
- const entry = this.pickFree(requires, only);
+ const whilePaused = opts?.whilePaused === true;
+ const entry = this.pickFree(requires, only, whilePaused);
if (entry && this.waiters.length === 0) {
return Promise.resolve(this.grant(entry));
}
const tier: SchedulerTier =
opts?.tier ?? (opts?.background ? "background" : "foreground");
return new Promise<Lease>((resolve, reject) => {
- const waiter: Waiter = { resolve, reject, tier, requires, only };
+ const waiter: Waiter = {
+ resolve,
+ reject,
+ tier,
+ requires,
+ only,
+ ...(whilePaused ? { whilePaused: true } : {}),
+ };
if (signal) {
const onAbort = () => {
const idx = this.waiters.indexOf(waiter);
@@ -701,6 +751,7 @@ export class WorkerPool {
? { tags: [...e.config.tags] }
: {}),
device: e.config.config?.device,
+ ...(this.pauseHeld(e.config.id, e) && !e.degraded ? { pauseHeld: true as const } : {}),
}))
.sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
}
diff --git a/common/jobs/workerPool.whilePaused.test.ts b/common/jobs/workerPool.whilePaused.test.ts
@@ -0,0 +1,143 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { Worker } from "../lib/workers";
+import { WorkerPool, type Lease } from "./workerPool";
+
+// RUN WHILE PAUSED (release 36, lane A): a manual acquire with `whilePaused`
+// may take a worker the pause-all alone switched off — never one drained,
+// degraded or disabled by hand — and the pause's snapshot is never touched.
+//
+// Each test builds a fresh pool seeded with reconfigure(…, {applyEnabled}),
+// as workerPool.test.ts does, so settings.json is never read.
+
+function worker(id: string, priority = 0, enabled = true): Worker {
+ return { id, name: id, kind: "local", enabled, priority };
+}
+
+function snapshotOf(pool: WorkerPool): string {
+ const snap = (pool as unknown as { pausedSnapshot: Map<string, string> | null }).pausedSnapshot;
+ return JSON.stringify(snap ? [...snap.entries()] : null);
+}
+
+function stateOf(pool: WorkerPool, id: string) {
+ const w = pool.summary().find((s) => s.id === id);
+ assert.ok(w, id);
+ return { state: w.state, busy: w.busy, degraded: w.degraded };
+}
+
+// Settles a promise race: the lease if it resolved within a tick, else null.
+async function settledWithin<T>(p: Promise<T>, ms = 20): Promise<T | null> {
+ return Promise.race([p, new Promise<null>((r) => setTimeout(() => r(null), ms))]);
+}
+
+test("a paused pool + whilePaused leases a pause-disabled worker; the snapshot is untouched", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0), worker("cpu", 1)], { applyEnabled: true });
+ pool.pauseAll();
+ const before = snapshotOf(pool);
+ assert.deepEqual(pool.pauseHeldIds().sort(), ["cpu", "gpu"]);
+ assert.deepEqual(pool.summary().map((w) => [w.id, w.pauseHeld ?? false]), [["gpu", true], ["cpu", true]]);
+
+ const lease = (await settledWithin(pool.acquire(undefined, { whilePaused: true }))) as Lease | null;
+ assert.ok(lease, "granted at once");
+ assert.equal(lease.worker.id, "gpu", "the highest-priority pause-held worker");
+ // Still disabled by the pause while it runs: it never left the paused set.
+ assert.deepEqual(stateOf(pool, "gpu"), { state: "disabled", busy: true, degraded: false });
+ assert.equal(snapshotOf(pool), before);
+
+ lease.release();
+ assert.deepEqual(stateOf(pool, "gpu"), { state: "disabled", busy: false, degraded: false });
+ assert.equal(snapshotOf(pool), before, "byte-equal after the job");
+ assert.ok(pool.isPaused());
+
+ // And the pause lifts exactly as it would have.
+ pool.resumeAll();
+ assert.equal(stateOf(pool, "gpu").state, "enabled");
+ assert.equal(stateOf(pool, "cpu").state, "enabled");
+});
+
+test("a worker disabled by hand before the pause is never leased while paused", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0), worker("cpu", 1)], { applyEnabled: true });
+ pool.disableWorker("gpu"); // by hand, before the pause
+ pool.pauseAll();
+ assert.deepEqual(pool.pauseHeldIds(), ["cpu"]);
+ const lease = (await settledWithin(pool.acquire(undefined, { whilePaused: true }))) as Lease | null;
+ assert.ok(lease);
+ assert.equal(lease.worker.id, "cpu");
+ lease.release();
+});
+
+test("hand-disabled, drained or degraded workers are never leased, even with the flag", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("a", 0), worker("b", 1), worker("c", 2), worker("off", 3, false)], {
+ applyEnabled: true,
+ });
+ pool.pauseAll();
+ pool.disableWorker("a"); // by hand DURING the pause: the snapshot says disabled
+ pool.drainWorker("b"); // drained during the pause
+ pool.markDegraded("c");
+ const before = snapshotOf(pool);
+ assert.deepEqual(pool.pauseHeldIds(), [], "'off' was disabled in settings, not by the pause");
+ assert.ok(pool.summary().every((w) => !("pauseHeld" in w)), "the summary marks none");
+
+ const ac = new AbortController();
+ const p = pool.acquire(ac.signal, { whilePaused: true });
+ assert.equal(await settledWithin(p), null, "parks: nothing it may take");
+ ac.abort();
+ await assert.rejects(p, { name: "AbortError" });
+ assert.equal(snapshotOf(pool), before);
+});
+
+test("without the flag a paused pool holds the acquire, as today", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0)], { applyEnabled: true });
+ pool.pauseAll();
+ const before = snapshotOf(pool);
+ const held = pool.acquire();
+ const heldBg = pool.acquire(undefined, { background: true });
+ assert.equal(await settledWithin(held), null);
+ assert.equal(await settledWithin(heldBg), null);
+
+ // A whilePaused acquire arriving later is served — the held ones stay parked.
+ const lease = (await settledWithin(pool.acquire(undefined, { whilePaused: true }))) as Lease | null;
+ assert.ok(lease, "the flagged acquire runs past the held ones");
+ lease.release();
+ assert.equal(await settledWithin(held), null, "still held after the flagged job ended");
+ assert.equal(await settledWithin(heldBg), null);
+ assert.equal(snapshotOf(pool), before);
+
+ // Resume releases the held ones in tier order.
+ pool.resumeAll();
+ const l1 = (await held) as Lease;
+ l1.release();
+ const l2 = (await heldBg) as Lease;
+ l2.release();
+});
+
+test("a parked whilePaused waiter takes the pause-held worker when its lease frees", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0)], { applyEnabled: true });
+ pool.pauseAll();
+ const first = (await pool.acquire(undefined, { whilePaused: true })) as Lease;
+ const second = pool.acquire(undefined, { whilePaused: true });
+ const bg = pool.acquire(undefined, { background: true });
+ assert.equal(await settledWithin(second), null, "one slot");
+ first.release();
+ const l2 = (await settledWithin(second)) as Lease | null;
+ assert.ok(l2, "the flagged waiter, not the background one");
+ l2.release();
+ assert.equal(await settledWithin(bg), null, "the lane stays held");
+ pool.resumeAll();
+ ((await bg) as Lease).release();
+});
+
+test("outside a pause the flag changes nothing", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0), worker("cpu", 1)], { applyEnabled: true });
+ pool.disableWorker("gpu");
+ assert.deepEqual(pool.pauseHeldIds(), []);
+ const lease = (await pool.acquire(undefined, { whilePaused: true })) as Lease;
+ assert.equal(lease.worker.id, "cpu", "a hand-disabled worker stays off");
+ lease.release();
+});
diff --git a/common/lib/clips/reactions.d.mts b/common/lib/clips/reactions.d.mts
@@ -48,3 +48,4 @@ export function readReactions(dir: string): Promise<ReactionsDoc | null>;
export function writeReactions(dir: string, doc: ReactionsDoc): Promise<string>;
export function operatorRoles(doc: ReactionsDoc | null): Record<string, Role>;
export function setSpeakerRole(dir: string, index: number, role: Role | null, opts?: { now?: () => Date }): Promise<ReactionsDoc>;
+export function setSpeakerLabel(dir: string, index: number, label: string | null): Promise<ReactionsDoc>;
diff --git a/common/lib/clips/reactions.mjs b/common/lib/clips/reactions.mjs
@@ -92,3 +92,26 @@ export async function setSpeakerRole(dir, index, role, { now = () => new Date()
await writeReactions(dir, doc);
return doc;
}
+
+/**
+ * A person's name for one speaker (release 36 lane C): what the speaker
+ * captions head that voice's lines with. Trimmed, up to 40 characters; null
+ * or empty gives back the default ("Host", "Subject", "Speaker N"), which the
+ * captions never print. A role change (setSpeakerRole) resets it.
+ *
+ * @param {string} dir the project
+ * @param {number} index the speaker (diarization cluster)
+ * @param {string|null} label
+ * @returns {Promise<any>} the document as written
+ */
+export async function setSpeakerLabel(dir, index, label) {
+ const doc = await readReactions(dir);
+ if (!doc) throw new Error(`no ${REACTIONS_FILE} in ${dir}`);
+ const s = doc.speakers.find((x) => isObj(x) && x.index === index);
+ if (!s) throw new Error(`no speaker ${index} in ${REACTIONS_FILE}`);
+ const text = label === null || label === undefined ? "" : String(label).replace(/\s+/g, " ").trim();
+ if (text.length > 40) throw new Error("a speaker's label is up to 40 characters");
+ s.label = text || labelOf(s.role, index);
+ await writeReactions(dir, doc);
+ return doc;
+}
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -126,7 +126,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "UMTOOL_MEDIA_DIR", audience: "runtime", default: "unset (no media root: a project link's target is kept)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md)." },
{ name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." },
{ name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does)." },
- { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`)." },
+ { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." },
{ name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." },
{ name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." },
{ name: "TRANSCRIPT_LOCAL_DIR", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a composed public dir on disk." },
@@ -230,6 +230,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." },
{ name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
{ name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." },
+ { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." },
{ name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." },
{ name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." },
diff --git a/common/lib/findClipsRecord-server.ts b/common/lib/findClipsRecord-server.ts
@@ -0,0 +1,56 @@
+// WHAT THE LAST "FIND CLIPS" FOUND — `data/<id>/find-clips.json` (release 36,
+// lane A). Written by the find-clips job when umtool's clip finder finished
+// (controller/findClips.ts); read by the video page's Find clips panel, which
+// links the umtool project and lists the narrated-video segments umtool found,
+// each with its own "Find clips in this part". Overwritten by the next run
+// (the newest run is the one the panel describes; a per-segment run names its
+// segment). A small text sidecar on the corpus disk; never published.
+
+import { sidecar, sidecarField } from "./sidecar-server";
+
+export const FIND_CLIPS_FILENAME = "find-clips.json";
+
+export type FindClipsSegment = {
+ id: string;
+ from: number;
+ to: number;
+ subject?: number | string;
+ host?: number | string;
+ why?: string;
+};
+
+export type FindClipsStepRecord = {
+ id: string;
+ label: string;
+ action: "ran" | "skipped";
+ why: string;
+};
+
+export type FindClipsRecord = {
+ version: 1;
+ at: string;
+ jobId: string;
+ // The umtool project, its clip editor's URL, and whether umtool made it now
+ // (false: it re-analyzed the project already cut from this recording).
+ project: string;
+ url: string;
+ created: boolean;
+ // The segment this run was scoped to: the one asked for, else the one
+ // umtool's auto-scope chose (its answer's `segment`).
+ segment?: string;
+ // Every narrated-video segment umtool found in the recording.
+ segments: FindClipsSegment[];
+ steps: FindClipsStepRecord[];
+};
+
+function coerce(value: unknown): FindClipsRecord | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const v = value as Record<string, unknown>;
+ if (v.version !== 1 || typeof v.project !== "string" || typeof v.url !== "string") return null;
+ if (!Array.isArray(v.segments) || !Array.isArray(v.steps)) return null;
+ return value as FindClipsRecord;
+}
+
+export const findClipsSidecar = sidecar(FIND_CLIPS_FILENAME, sidecarField(coerce), { indent: 2 });
+export const loadFindClipsRecord = findClipsSidecar.load;
+export const writeFindClipsRecord = findClipsSidecar.write;
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -15,6 +15,8 @@ import "./frameScan-server";
import "./metadataHistory-server";
import "./transcriptPin-server";
import "./wayback-server";
+import "./wordTimings-server";
+import "./findClipsRecord-server";
import {
availabilitySidecar,
loadAvailability,
@@ -46,7 +48,7 @@ async function scratch(): Promise<string> {
return mkdtemp(path.join(os.tmpdir(), "sidecar-"));
}
-test("every declared sidecar filename escapes SUB_FILE_RE, and all fifteen are declared", () => {
+test("every declared sidecar filename escapes SUB_FILE_RE, and all seventeen are declared", () => {
assert.deepEqual([...SIDECAR_FILENAMES].sort(), [
"ai-digest.json",
"ai-digest.overrides.json",
@@ -58,11 +60,13 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all fifteen are d
"do-not-clean.json",
"download-outcome.json",
"exclude-truncated-check.json",
+ "find-clips.json",
"frame-scan.poker.json",
"metadata.history.json",
"transcribe-outcome.json",
"transcript-pin.json",
"wayback.json",
+ "words.json",
]);
for (const name of SIDECAR_FILENAMES) {
assert.ok(!SUB_FILE_RE.test(name), name);
diff --git a/common/lib/umtoolUrl.test.ts b/common/lib/umtoolUrl.test.ts
@@ -0,0 +1,24 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { umtoolUrl } from "./umtoolUrl";
+
+test("umtoolUrl: UMTOOL_URL without its trailing slashes, null when unset; a test's loopback origin from the file", async () => {
+ assert.equal(umtoolUrl({}), null);
+ assert.equal(umtoolUrl({ UMTOOL_URL: " " }), null);
+ assert.equal(umtoolUrl({ UMTOOL_URL: "http://localhost:3050//" }), "http://localhost:3050");
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-url-"));
+ try {
+ const file = path.join(dir, ".fake-umtool-origin");
+ const env = { E2E_UMTOOL_ORIGIN_FILE: file, UMTOOL_URL: "http://localhost:3050" };
+ assert.equal(umtoolUrl(env), "http://localhost:3050", "no file yet");
+ await writeFile(file, "http://127.0.0.1:41234/\n");
+ assert.equal(umtoolUrl(env), "http://127.0.0.1:41234");
+ await writeFile(file, "https://umtool.example.com");
+ assert.equal(umtoolUrl(env), "http://localhost:3050", "not loopback: ignored");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/umtoolUrl.ts b/common/lib/umtoolUrl.ts
@@ -0,0 +1,31 @@
+// WHERE UMTOOL IS, for the editor's side of the clip finder (release 36, lane
+// A): `UMTOOL_URL`, trailing slashes dropped; null when unset. The video page
+// links to it and the find-clips job posts to its `/api/report/clips`.
+//
+// TEST-ONLY: E2E_UMTOOL_ORIGIN_FILE names a file holding ONE loopback origin
+// (`http://127.0.0.1:<port>`). While that file exists, umtool is that origin —
+// the stub umtool an editor e2e spec starts (find-clips.spec) and names in the
+// file after the test server booted; it is read per call. Anything but a
+// loopback origin in it is ignored. Unset everywhere but the editor's e2e
+// server (the Bluesky fake's pattern, social/blueskyEndpoints.ts).
+
+import { readFileSync } from "node:fs";
+
+const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/;
+
+export function umtoolUrl(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): string | null {
+ const file = env.E2E_UMTOOL_ORIGIN_FILE;
+ if (file) {
+ let origin = "";
+ try {
+ origin = readFileSync(file, "utf8").trim().replace(/\/+$/, "");
+ } catch {
+ origin = "";
+ }
+ if (LOOPBACK_ORIGIN.test(origin)) return origin;
+ }
+ const url = env.UMTOOL_URL?.trim().replace(/\/+$/, "");
+ return url ? url : null;
+}
diff --git a/common/lib/wordTimings-server.ts b/common/lib/wordTimings-server.ts
@@ -0,0 +1,59 @@
+// A VIDEO'S WORD TIMINGS — `data/<id>/words.json` (release 36, lane A).
+//
+// The clip finder cuts on words: a clip's edges snap to the word the speaker
+// starts or finishes on, never to a caption line's wrap. Release 35 made them
+// by hand (`pnpm ops transcribe {path, words: true, out: <project>/words.json}`)
+// into one umtool project. The find-clips job makes them ONCE per video,
+// here, beside the transcript they belong to, so every project cut from this
+// recording reads the same file (umtool copies it in as `<project>/words.json`)
+// and the step is skipped the next time.
+//
+// THE SHAPE IS THE TRANSCRIBE RESULT'S (controller/transcribeFile.ts
+// TranscribeFileResult) without its cues and text — {version, path, window,
+// worker, transcriptFormat, transcribedAt, durationMs, waitedMs, words} — so a
+// release-35 words.json and this file read the same (umtool reads
+// `doc.words`, umtool/lib/report/reactions.mjs loadRecording). A file with no
+// words array reads as absent; one with an EMPTY array is never written (an
+// engine that keeps no word timestamps — the job says so and goes on).
+//
+// TEXT, not media: it stays in the real data/<id>/ on the corpus disk and is
+// never tiered (lib/mediaTier.ts tiers by name; this name is not one).
+
+import { sidecar, sidecarField } from "./sidecar-server";
+
+export const WORD_TIMINGS_FILENAME = "words.json";
+
+export type TimedWord = { w: string; start: number; end: number; conf?: number };
+
+export type WordTimingsRecord = {
+ version: 1;
+ // The file the engine read (the video's audio or saved container).
+ path: string;
+ window: { start: number; end: number | null } | null;
+ worker: { id: string; name: string; appId: string; model: string | null; device: string | null };
+ transcriptFormat: string;
+ transcribedAt: string;
+ durationMs: number;
+ waitedMs: number;
+ words: TimedWord[];
+};
+
+function isWord(w: unknown): w is TimedWord {
+ if (!w || typeof w !== "object") return false;
+ const o = w as Record<string, unknown>;
+ return typeof o.w === "string" && typeof o.start === "number" && typeof o.end === "number";
+}
+
+export function coerceWordTimings(value: unknown): WordTimingsRecord | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const v = value as Record<string, unknown>;
+ if (!Array.isArray(v.words) || v.words.length === 0 || !v.words.every(isWord)) return null;
+ return value as WordTimingsRecord;
+}
+
+export const wordTimingsSidecar = sidecar(WORD_TIMINGS_FILENAME, sidecarField(coerceWordTimings), {
+ indent: 0,
+});
+
+export const loadWordTimings = wordTimingsSidecar.load;
+export const writeWordTimings = wordTimingsSidecar.write;
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -546,10 +546,29 @@ async function fetchLiveChatOnly(
channelDir: string,
cookies: string | undefined,
): Promise<AttemptOutcome> {
- return runOneYtdlp(opts, channelDir, [
+ return runOneYtdlp(
+ opts,
+ channelDir,
+ liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl),
+ );
+}
+
+// The chat-only pass's argv, run in the channel dir: the channel's own args
+// (its cookies and the platform's live pace) and then the refusals. Exported
+// for the one-video chat fetch (release 36 lane A, controller/fetchLiveChat.ts
+// — `pnpm ops fetch-chat`), so the two passes are one command line.
+export function liveChatOnlyArgs(
+ channelConfig: ChannelConfig,
+ cookies: string | undefined,
+ videoUrl: string,
+ paceSeconds?: number,
+): string[] {
+ return [
"--ignore-config",
"--restrict-filenames",
- ...channelConfigArgs(opts.channelConfig, cookies),
+ ...(paceSeconds !== undefined
+ ? channelConfigArgs(channelConfig, cookies, paceSeconds)
+ : channelConfigArgs(channelConfig, cookies)),
"--skip-download",
"--write-subs",
"--no-write-auto-subs",
@@ -559,10 +578,10 @@ async function fetchLiveChatOnly(
"--no-write-description",
"--no-write-thumbnail",
"--no-download-archive",
- ...outputArgsForUrl(opts.videoUrl),
+ ...outputArgsForUrl(videoUrl),
"--",
- opts.videoUrl,
- ]);
+ videoUrl,
+ ];
}
// Did the chat pass actually leave a chat behind? A stream with chat replay
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,8 +1,14 @@
# Changelog
## [Unreleased]
+- **Find clips: the clip finder from one button on the video page.** A video page's **Find clips** runs the whole chain umtool's clip finder needs, as one job: it saves the source video, transcribes the recording, makes its word timings (kept beside the transcript as `words.json`, so a second project from the same recording reuses them), fetches the stream's chat replay (YouTube), finds who speaks when, and then asks umtool to find the narrated-video segments and propose the clips. Each step whose output is already on disk is skipped, and the job's log says which ran and which were skipped. When it is done the panel links the umtool project and lists the segments it found, each with **Find clips in this part**. A target length can be given. When the workers are paused or the backfill lane is held, the step that needs them stops with a sentence saying so, and **Run while paused** runs this one video past them. The button is off, with a line saying why, when the editor has no `UMTOOL_URL`. The same from a terminal: `pnpm ops find-clips --json '{"slug","id"}'` (a `dryRun` lists what each step would do). Needs a restart of the editor.
+- **Transcribe one video while the workers are paused.** With the transcription workers paused, the video page's Transcribe row offers **Transcribe now (workers paused)**: that one transcription runs on a worker the pause alone switched off, and the pause stays on — the worker is paused again when it finishes. A worker you drained, disabled by hand or that is marked degraded is never used, and the lanes stay held. `pnpm ops transcribe` and `transcribe-one` take `"whilePaused": true`.
+- **Fetch a stream's chat replay on its own.** Media tools → **Fetch live chat** on a video page (`pnpm ops fetch-chat`) fetches the video's live chat and nothing else, paced like every YouTube request and on the platform's download queue, into the chat cues the index and the clip finder read. A video on another platform says there is no chat fetcher for it, as does a chat already fetched or a video that was never live.
- **The clip finder finds each narrated video in a reaction stream, and listens to the chat.** A stream that reacts to one video and then another no longer needs its scope read off the speakers by hand: `umtool new <slug> --seed reactions --from <channel>/<id> --scope auto` reads the narrated video the speaker turns show (`--segment s2` names one, else the longest), with the host's reaction after the video kept and the roles found for that video alone; `umtool clips segments <project>` lists them. When the stream's chat replay is on disk, the moments the chat laughs together (lol, KEKW, 😂, a wall of W) become proposals too, moved back by how late the chat types — found by lining the chat up against the laughs heard in the sound, else 6 seconds — and always ranked below the host's own laugh; the analysis says the delay it found. Without a chat replay nothing changes. Needs a restart of umtool.
- **Highlights of a channel that is on no site link the source and start with a clean look.** Each proposed clip links its platform page at its second (YouTube, Twitch, Rumble…), the channel's name is filled in from the video, and the cut starts with no header, no QR code, half-second fades through black and a −16 LUFS loudness target — no edits to the manifest needed. umtool's clips job also answers the editor directly (its `WORKER_TOKEN`), so the editor's Find clips makes or re-analyzes the project in one call; asking again for a video already cut analyzes that project again and leaves its cut exactly as it is, listing the new proposals (the chat's among them) for you to bring in.
+- **Set a report video's look in umtool, with captions that say who is speaking and even loudness.** The Build tab has a **Look** panel: the header, the timeline footer and the QR code on or off, the length between clips and how they join (crossfade, dip to black, dip to white, dissolve), the loudness (as recorded, −16 LUFS, or your own target) and **Speaker captions** — burned in, two to six words a line, the host's in amber on the left and the other voice's in blue on the right, broken where they pause and never across a change of speaker (from the clip finder's speakers, or the transcript's words). Voices are told apart by colour; give one a name in the panel, or beside a speaker in the clip editor's Speakers list, and its lines say it. Even loudness measures each clip and brings it to the target with a limiter, as montages already did. **Save the look** writes only what you changed; a cut with the on-screen deck keeps its own settings. A manifest without the new keys renders exactly as before. Needs a restart of umtool.
+- **Make a vertical short of any clip.** In the clip editor, **Frame the short** puts a 9:16 box on the player — drag it to the face, size it — and **Make a short** renders that clip alone at 1080×1920 into the project's `shorts/`: the box filling the frame, large speaker captions, no header or QR, even loudness. It runs as a job (one at a time, with Cancel) in the machine's heavy slot; a short made again sets the old one aside rather than overwriting it. The Deliver tab lists the shorts — play, download, make again, or open the clip to frame it — and says when a clip has moved since its short was made. From a terminal: `build-video.mjs <manifest> --short <clip>`. Needs a restart of umtool.
+- **`umtool build <project> --run` runs the build.** It starts the same build job the project page's button does on the running umtool (`UMTOOL_URL`, else `http://localhost:3050`, or `--url`), prints its log as it goes, and Ctrl-C cancels the job. `--replace` sets a newer deliverable aside. Without `--run` it prints the chain as before.
- **A report video's cut can dip through black between clips.** `render.transitionStyle: "fadeblack"` (or `fadewhite`, `dissolve`; default `fade`) changes how the crossfade looks, not its length — for highlights where every clip shares one layout and a plain dissolve hides the jump.
- **Hop in on an assistant's clips in umtool: trim, split, merge, keep or cut them, and comment.** A report video whose cut is not a montage has a **Clip editor** on its Cut tab (`/projects/<id>/clips`). It loops the selected clip from what is on disk, and under it shows the clip's neighbourhood (± 60 s, or closer): the speaker turns coloured host and subject, the laughs, the words, the other clips, and the cut with a handle at each edge. Move the edges by dragging, typing, nudging (±0.1, ±0.5, ±2 s) or **Snap to words**; **Keep** / **Cut**; **Split here** at the playhead; **Merge with next**; **Add a clip** from a span dragged on the strip; **Restore the assistant's version**; **Bring in** a proposal the assistant left out. Each clip says whether it is "by the assistant" (with its score and why) or "edited by you", with its edit history. A comment on a clip is a note anchored to it, so an agent reading `umtool notes` can act on it and its reply shows in the clip's thread. **This is the host** on a speaker's turn corrects which voice is the host. Keys: space, J/L, I/O, S, M, K, X, ←/→. A keep or cut follows its clip when an edit moves the clip's start. It works on any report video; a cut without the clip finder's speakers simply has no colours.
- **Fetch a montage's windows from umtool, and swap in another upload when Rumble refuses one.** A report video's Cut tab and its clip deck have **Fetch windows**: one button asks the editor for every clip's window (a dry run first — how many per platform, how many already on disk — then Start, with each job followed to its end and each refused window named); `umtool fetch <project>` does the same from a terminal. When a window is refused for good (a Rumble video whose lookup answers 403 every time, a deleted recording), the clip deck offers a **stand-in** — the same moment in the stream's YouTube upload (or Odysee) — and **Use stand-in** switches the clip, noting where it came from; **Restore** puts it back. `umtool fallback <project>` is the terminal form. Every run is kept in the project's `fetch-runs.json`.
diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts
@@ -108,6 +108,8 @@ test("a traversing slug is refused at the door, on every route that takes one",
["fetch-posts", { slug: "../../escape", older: true }],
["capture-posts", { slug: "../../escape", ids: ["1"] }],
["persist-videos", { items: [{ slug: "../../escape", id: "abc123" }] }],
+ ["fetch-chat", { slug: "../../escape", id: "abc123" }],
+ ["find-clips", { slug: "../../escape", id: "abc123" }],
];
for (const [action, data] of cases) {
const { status, body } = await callPost((await route(action)).POST!, data);
diff --git a/editor/app/api/ops/_findClips.ts b/editor/app/api/ops/_findClips.ts
@@ -0,0 +1,20 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { jobOfPaths } from "yt-dlp-transcript-common/controller/researchRuns";
+import type { FindClipsDeps } from "yt-dlp-transcript-common/controller/findClips";
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { findClipsEditor } from "./_researchEditor";
+
+// THE EDITOR'S SIDE OF FIND CLIPS (release 36 lane A): the chain's deps — its
+// steps through this editor's own ops actions in process (findClipsEditor),
+// its jobs from this registry, and the video page revalidated when the record
+// lands. Shared by `POST /api/ops/find-clips` and the video page's button
+// (findClipsActions.ts), so the two run one chain.
+export function findClipsDeps(slug: string, id: string): FindClipsDeps {
+ const paths = getPaths();
+ return {
+ paths,
+ editor: findClipsEditor,
+ jobOf: jobOfPaths(paths),
+ onDone: () => safeRevalidate([`/channels/${slug}/videos/${id}`]),
+ };
+}
diff --git a/editor/app/api/ops/_researchEditor.ts b/editor/app/api/ops/_researchEditor.ts
@@ -86,3 +86,16 @@ export const refreshEditor: ResearchEditor = {
return refreshDoor.run(action, args);
},
};
+
+// FIND CLIPS' EDITOR (release 36 lane A, controller/findClips.ts): the steps
+// the chain hands to the editor's own ops actions — persist the source, the
+// corpus transcript, the chat replay — through the same door.
+const FIND_CLIPS_ROUTES: Record<string, () => Promise<{ POST: Post }>> = {
+ "persist-videos": () => import("./persist-videos/route"),
+ "transcribe-one": () => import("./transcribe-one/route"),
+ "fetch-chat": () => import("./fetch-chat/route"),
+};
+
+export const FIND_CLIPS_DOOR_ACTIONS = Object.keys(FIND_CLIPS_ROUTES);
+
+export const findClipsEditor: ResearchEditor = inProcessEditor(FIND_CLIPS_ROUTES, "find-clips");
diff --git a/editor/app/api/ops/fetch-chat/route.ts b/editor/app/api/ops/fetch-chat/route.ts
@@ -0,0 +1,23 @@
+import { fetchChatAction } from "../../../channels/[slug]/videos/[id]/mediaToolsActions";
+import { jobResponse, ops, optString, reqSlug, reqVideoId } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, queueKey? } -> { ok: true, jobId }
+//
+// ONE video's live chat replay, and nothing else (release 36, lane A;
+// controller/fetchLiveChat.ts): the chat-only yt-dlp pass the managed download
+// runs for a chat-only channel — the channel's cookies and the platform's live
+// pace — on the platform's download queue, then live_chat.cues.json. The video
+// page's Media tools → "Fetch live chat", and the find-clips job's chat step.
+//
+// Answered without a job, `info: true` (a skip, not an error): a video on a
+// platform with no chat fetcher ("no chat fetcher for twitch"), a chat already
+// here and fresh, a video that was never live, a held platform or one in a
+// rate-limit cooldown. Refused: an id with no data/<id>/, a channel whose text
+// cannot be read. A pass that finds no replay ends `done` and says so.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "id", "queueKey"], async (body) =>
+ jobResponse(await fetchChatAction(reqSlug(body, "slug"), reqVideoId(body, "id"), optString(body, "queueKey"))),
+ );
+}
diff --git a/editor/app/api/ops/find-clips/route.ts b/editor/app/api/ops/find-clips/route.ts
@@ -0,0 +1,34 @@
+import { NextResponse } from "next/server";
+import { FIND_CLIPS_BODY_KEYS, enqueueFindClips } from "yt-dlp-transcript-common/controller/findClips";
+import { findClipsDeps } from "../_findClips";
+import { jobResponse, ops, reqSlug, reqVideoId } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, target?, segment?, project?, whilePaused?, dryRun? }
+// dryRun -> { ok: true, dryRun: true, plan: { steps: [{id, label, run, why}], umtoolUrl, workersPaused } }
+// else -> { ok: true, jobId }
+//
+// FIND CLIPS (release 36, lane A; controller/findClips.ts): the clip finder's
+// chain for ONE video as one job — persist the source video, the corpus
+// transcript, word timings (data/<id>/words.json), the chat replay (YouTube),
+// diarization — each step skipped when its output exists and named in the
+// log — then umtool's clips route (`mode: "new"`, `scope: "auto"`, or the
+// `segment` asked), followed to the end. The log ends `@@find-clips {json}`:
+// the project, its clip editor's URL, the segments umtool found and what each
+// step did; data/<id>/find-clips.json keeps it for the video page.
+//
+// `target` is the cut's length in seconds; `segment` a segment id umtool
+// found ("s2"); `project` names the umtool project a run makes (default from
+// the id); `whilePaused` runs the two transcriptions during a pause-all on a
+// worker the pause alone switched off. Refused before a job: an unknown
+// channel or video, UMTOOL_URL or WORKER_TOKEN unset on the editor.
+export async function POST(request: Request) {
+ return ops(request, FIND_CLIPS_BODY_KEYS, async (body) => {
+ const slug = reqSlug(body, "slug");
+ const id = reqVideoId(body, "id");
+ const out = await enqueueFindClips(body, findClipsDeps(slug, id));
+ if (out.dryRun) return NextResponse.json({ ok: true, dryRun: true, plan: out.plan });
+ return jobResponse(out.result);
+ });
+}
diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts
@@ -28,13 +28,18 @@ export const dynamic = "force-dynamic";
// disk, the download reads the media URL the record stores, the way the
// platform's player does (the managed path: the audio check, the outcome
// sidecar). Absent = the channel's `storedUrlDownloads`. Not with "file".
+// "whilePaused" (release 36, lane A): true lets this one transcription run
+// during a pause-all on a worker the pause alone switched off (never one
+// drained, degraded or disabled by hand); the pause stays on. Absent or false
+// = held by the pause, as before.
export async function POST(request: Request) {
- return ops(request, ["slug", "id", "file", "salvage", "storedUrl"], async (body) => {
+ return ops(request, ["slug", "id", "file", "salvage", "storedUrl", "whilePaused"], async (body) => {
const slug = reqSlug(body, "slug");
const id = reqVideoId(body, "id");
const file = optString(body, "file");
const salvage = optBool(body, "salvage");
const storedUrl = optStoredUrlMode(body);
+ const whilePaused = optBool(body, "whilePaused") === true;
if (storedUrl !== undefined && file !== undefined) {
return opsFail(`"storedUrl" is for a download; with "file" nothing is downloaded`);
}
@@ -45,8 +50,8 @@ export async function POST(request: Request) {
}
return jobResponse(
file !== undefined
- ? await transcribeOneAction(slug, id, file, undefined, salvage)
- : await whisperVideoAction(slug, id, undefined, salvage, storedUrl),
+ ? await transcribeOneAction(slug, id, file, undefined, salvage, whilePaused)
+ : await whisperVideoAction(slug, id, undefined, salvage, storedUrl, whilePaused),
);
});
}
diff --git a/editor/app/api/ops/transcribe/route.ts b/editor/app/api/ops/transcribe/route.ts
@@ -7,7 +7,7 @@ import { jobResponse, ops } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { path, start?, end?, workerId?, out? } -> { ok: true, jobId }
+// POST { path, start?, end?, workerId?, out?, words?, whilePaused? } -> { ok: true, jobId }
//
// Transcribe ONE local file — or the window [start, end) seconds of it — on a
// local transcription worker, as a job on /jobs: the engine, model and
@@ -26,6 +26,8 @@ export const dynamic = "force-dynamic";
// — a relative or unreadable `path`, `end` not after `start`, an unknown or
// non-local `workerId`, a named worker switched off, an `out` inside the corpus
// (resolved through symlinks) or in a directory that does not exist.
+// `whilePaused: true` (release 36, lane A) runs it during a pause-all on a
+// worker the pause alone switched off; the pause stays on.
export async function POST(request: Request) {
return ops(request, TRANSCRIBE_FILE_BODY_KEYS, async (body) =>
jobResponse(await enqueueTranscribeFile(body, { paths: getPaths() })),
diff --git a/editor/app/channels/[slug]/videos/[id]/components/FindClipsPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/FindClipsPanel.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+// FIND CLIPS (release 36, lane A): the clip finder's whole chain for this
+// video, one button — the same job as `pnpm ops find-clips`
+// (controller/findClips.ts). Each step it skips or runs is in the job's log;
+// what the last run found (data/<id>/find-clips.json) is drawn below it: the
+// umtool project, linked, and the narrated-video segments umtool found, each
+// with its own "Find clips in this part".
+//
+// TYPE-ONLY from lib/findClipsRecord-server (it reaches node:fs through
+// sidecar-server): the record arrives as a prop, read by the page.
+
+import { useState } from "react";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import type { FindClipsRecord } from "yt-dlp-transcript-common/lib/findClipsRecord-server";
+import { cancelJobAction } from "../../../../../jobs/actions";
+import { findClipsAction } from "../findClipsActions";
+
+const input = "rounded border border-border bg-card px-2 py-1 text-sm";
+
+function clock(seconds: number): string {
+ const s = Math.max(0, Math.round(seconds));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
+}
+
+export function FindClipsPanel({
+ slug,
+ videoId,
+ umtoolUrl,
+ holds,
+ record,
+}: {
+ slug: string;
+ videoId: string;
+ // UMTOOL_URL on the editor (lib/umtoolUrl.ts), read by the page. Null: the
+ // button is disabled and the status line says why.
+ umtoolUrl: string | null;
+ // What would hold a step right now ("the transcription workers are paused",
+ // "the backfill lane is held"), read by the page. Any: the "while paused"
+ // checkbox is offered — this one video's steps run past them.
+ holds: string[];
+ record: FindClipsRecord | null;
+}) {
+ const [minutes, setMinutes] = useState("");
+ const [whilePaused, setWhilePaused] = useState(false);
+ const target = Number(minutes) > 0 ? Math.round(Number(minutes) * 60) : undefined;
+ const opts = (segment?: string) => ({
+ ...(target !== undefined ? { target } : {}),
+ ...(segment ? { segment } : {}),
+ ...(holds.length > 0 && whilePaused ? { whilePaused: true } : {}),
+ });
+ const status = !umtoolUrl
+ ? "off"
+ : record
+ ? `last run ${record.at.slice(0, 10)}: ${record.segments.length} segment${record.segments.length === 1 ? "" : "s"}`
+ : "not run yet";
+ return (
+ <section aria-label="find-clips panel" className="flex flex-col gap-4 rounded border border-border p-3">
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <h2 className="text-lg font-semibold">Find clips</h2>
+ <span aria-label="find-clips status" className="text-xs text-muted-foreground">
+ {status}
+ </span>
+ </div>
+ {!umtoolUrl && (
+ <p role="status" aria-label="find-clips off" className="text-sm text-muted-foreground">
+ UMTOOL_URL is not set on the editor: Find clips hands the recording to umtool's clip finder.
+ </p>
+ )}
+ <div className="flex flex-wrap items-end gap-3 text-sm">
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">Target length (minutes; empty = umtool's default)</span>
+ <input
+ type="number"
+ min={1}
+ step={1}
+ inputMode="numeric"
+ value={minutes}
+ onChange={(e) => setMinutes(e.target.value)}
+ aria-label="target length (minutes)"
+ className={`${input} w-28`}
+ />
+ </label>
+ {holds.length > 0 && (
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={whilePaused}
+ onChange={(e) => setWhilePaused(e.target.checked)}
+ aria-label="run while paused"
+ />
+ Run while paused (this video only)
+ </label>
+ )}
+ </div>
+ {holds.length > 0 && (
+ <p role="status" aria-label="find-clips holds" className="text-xs text-muted-foreground">
+ {holds.join("; ").replace(/^./, (c) => c.toUpperCase())}.
+ </p>
+ )}
+ <StreamActionLog
+ trigger={() => findClipsAction(slug, videoId, opts())}
+ cancelAction={cancelJobAction}
+ buttonLabel="Find clips"
+ runningLabel="Finding clips…"
+ label={`Find clips in ${videoId}`}
+ disabled={!umtoolUrl}
+ />
+ {record && (
+ <div aria-label="find-clips result" className="flex flex-col gap-2 text-sm">
+ <p>
+ Clips:{" "}
+ <a href={record.url} className="underline font-mono" data-find-clips-project>
+ {record.project}
+ </a>{" "}
+ <span className="text-muted-foreground">
+ ({record.created ? "new project" : "re-analyzed"}
+ {record.segment ? `, segment ${record.segment}` : ""})
+ </span>
+ </p>
+ {record.segments.length > 0 && (
+ <ul aria-label="segments found" className="flex flex-col gap-2">
+ {record.segments.map((s) => (
+ <li key={s.id} className="flex flex-col gap-1 rounded border border-border p-2">
+ <span>
+ <span className="font-mono">{s.id}</span> {clock(s.from)}–{clock(s.to)}
+ {s.why ? <span className="text-muted-foreground"> — {s.why}</span> : null}
+ </span>
+ <StreamActionLog
+ trigger={() => findClipsAction(slug, videoId, opts(s.id))}
+ cancelAction={cancelJobAction}
+ buttonLabel="Find clips in this part"
+ runningLabel="Finding clips…"
+ label={`Find clips in segment ${s.id}`}
+ disabled={!umtoolUrl}
+ />
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx
@@ -8,6 +8,7 @@ import { cancelJobAction } from "../../../../../jobs/actions";
import {
archiveOrgRefreshAction,
attachVideoMediaAction,
+ fetchChatAction,
playableVideoAction,
waybackRefreshAction,
type RecordsRefreshResult,
@@ -41,6 +42,16 @@ export function VideoMediaTools({
<summary className="cursor-pointer text-sm font-semibold">Media tools</summary>
<div className="mt-3 flex flex-col gap-4">
<AttachFromArchive slug={slug} videoId={videoId} saved={saved} />
+ <div className="flex flex-col gap-2">
+ <h4 className="text-sm font-semibold">Live chat replay</h4>
+ <StreamActionLog
+ trigger={() => fetchChatAction(slug, videoId)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Fetch live chat"
+ runningLabel="Fetching the chat…"
+ label={`Fetch live chat of ${videoId}`}
+ />
+ </div>
{saved && (
<div className="flex flex-col gap-2">
<h4 className="text-sm font-semibold">Playable copy</h4>
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx
@@ -108,6 +108,9 @@ type Props = {
// The umtool front door, when UMTOOL_URL is set on the editor. One link:
// "open in umtool" scaffolds a report video from this exact video.
umtoolUrl?: string | null;
+ // The transcription pool is paused (getWorkerPool().isPaused(), read by the
+ // page): the Transcribe rows offer "Transcribe now (workers paused)".
+ workersPaused?: boolean;
};
export function VideoPanel({
@@ -135,6 +138,7 @@ export function VideoPanel({
umtoolUrl = null,
storedMediaHost = null,
channelStoredUrl,
+ workersPaused = false,
}: Props) {
const audioFiles = files.filter((f) => isAudioFile(f.name));
const transcodeSources = files.filter((f) => isTranscodeSource(f.name));
@@ -357,6 +361,7 @@ export function VideoPanel({
hasTranscript={hasTranscript && !autoSubsOnly}
replaceAutoSubs={autoSubsOnly}
fullAudio={fullAudioOwed}
+ workersPaused={workersPaused}
/>
))}
</div>
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/PerFileTranscribeRow.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/PerFileTranscribeRow.tsx
@@ -19,6 +19,7 @@ export function PerFileTranscribeRow({
hasTranscript,
replaceAutoSubs = false,
fullAudio = null,
+ workersPaused = false,
}: {
slug: string;
videoId: string;
@@ -32,6 +33,10 @@ export function PerFileTranscribeRow({
// (lib/fullAudioFirst.ts). Transcribe makes them first; Salvage now makes
// the partial transcript from this file at once.
fullAudio?: FullAudioState | null;
+ // The transcription pool is paused (the pool's live state, read by the page).
+ // Release 36 lane A: "Transcribe now (workers paused)" runs this one file on
+ // a worker the pause alone switched off; the pause stays on.
+ workersPaused?: boolean;
}) {
const [transcribeQueue, setTranscribeQueue] = useState("");
// `hasTranscript` is SERVER-derived (VideoPanel, the Transcribe card) and this row's own run
@@ -103,6 +108,19 @@ export function PerFileTranscribeRow({
}
/>
)}
+ {workersPaused && !hasTranscript && (
+ <StreamActionLog
+ key="transcribe-paused-run"
+ trigger={() => {
+ setRanHere(true);
+ return transcribeOneAction(slug, videoId, file.name, transcribeQueue, undefined, true);
+ }}
+ cancelAction={cancelJobAction}
+ buttonLabel="Transcribe now (workers paused)"
+ runningLabel="Transcribing…"
+ label={`Transcribe ${file.name} while paused`}
+ />
+ )}
{fullAudio && !hasTranscript && (
<StreamActionLog
key="salvage-run"
diff --git a/editor/app/channels/[slug]/videos/[id]/findClipsActions.ts b/editor/app/channels/[slug]/videos/[id]/findClipsActions.ts
@@ -0,0 +1,29 @@
+"use server";
+
+// The video page's Find clips (release 36 lane A): the same chain as `pnpm ops
+// find-clips` (controller/findClips.ts), through the same deps
+// (api/ops/_findClips.ts). NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use
+// server" file).
+
+import { enqueueFindClips } from "yt-dlp-transcript-common/controller/findClips";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import { findClipsDeps } from "../../../../api/ops/_findClips";
+
+export async function findClipsAction(
+ slug: string,
+ videoId: string,
+ opts: { target?: number; segment?: string; whilePaused?: boolean } = {},
+): Promise<StreamActionResult> {
+ const out = await enqueueFindClips(
+ {
+ slug,
+ id: videoId,
+ ...(opts.target !== undefined ? { target: opts.target } : {}),
+ ...(opts.segment ? { segment: opts.segment } : {}),
+ ...(opts.whilePaused ? { whilePaused: true } : {}),
+ },
+ findClipsDeps(slug, videoId),
+ );
+ if (out.dryRun) return { ok: false, error: "a dry run starts no job" };
+ return out.result;
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts b/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts
@@ -14,6 +14,9 @@
// this record with it; answered in the request
// archiveOrg `archilyzer archive-org refresh <slug>` — the channel's
// archive.org file records (offline); answered in the request
+// chat `pnpm ops fetch-chat` (release 36 lane A) — this video's live
+// chat replay alone, paced, into live_chat.cues.json — the
+// `fetch-chat` job
//
// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file).
@@ -22,7 +25,11 @@ import { revalidatePath } from "next/cache";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { refreshWaybackRecords } from "yt-dlp-transcript-common/controller/waybackRefresh";
import { refreshArchiveOrgRecords } from "yt-dlp-transcript-common/controller/archiveOrgRefresh";
-import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { runFetchChatJob } from "yt-dlp-transcript-common/controller/fetchLiveChat";
+import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { safeRevalidate } from "../../../../lib/safeRevalidate";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
import { attachMediaAction } from "../../attachMediaActions";
import { preparePlayableAction } from "../../playableActions";
@@ -46,6 +53,22 @@ export async function attachVideoMediaAction(
});
}
+export async function fetchChatAction(slug: string, videoId: string, queueKey?: string): Promise<StreamActionResult> {
+ if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` };
+ const paths = getPaths();
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `Channel "${slug}" not found` };
+ return runFetchChatJob({
+ paths,
+ slug,
+ videoId,
+ channelConfig: config,
+ cookiePolicy: resolveCookiePolicy(getSettings(), config),
+ ...(queueKey !== undefined ? { queueKey } : {}),
+ afterRun: () => safeRevalidate([`/channels/${slug}/videos/${videoId}`]),
+ });
+}
+
export async function playableVideoAction(slug: string, videoId: string, dryRun = false): Promise<StreamActionResult> {
return preparePlayableAction(slug, { ids: [videoId], ...(dryRun ? { dryRun: true } : {}) });
}
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -37,6 +37,8 @@ import {
queueKeyForUrl,
} from "yt-dlp-transcript-common/lib/platform";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { getWorkerPool } from "yt-dlp-transcript-common/jobs/workerPool";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { resolveSourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat";
import { liveJobRows } from "../../../../jobs/active/buildActiveJobs";
@@ -45,6 +47,9 @@ import { VideoPanel, type VideoFile } from "./components/VideoPanel";
import { OperationPanel } from "./components/OperationPanel";
import { TagsPanel } from "./components/TagsPanel";
import { FrameScanPanel } from "./components/FrameScanPanel";
+import { FindClipsPanel } from "./components/FindClipsPanel";
+import { loadFindClipsRecord } from "yt-dlp-transcript-common/lib/findClipsRecord-server";
+import { umtoolUrl as resolveUmtoolUrl } from "yt-dlp-transcript-common/lib/umtoolUrl";
import { frameScanView } from "./lib/frameScanView";
import { loadFrameScans } from "yt-dlp-transcript-common/lib/frameScan-server";
import { MetadataHistoryDetails } from "./components/MetadataHistoryDetails";
@@ -220,6 +225,9 @@ export default async function VideoDetailPage({
// profile, on the corpus disk.
const frameScans = await loadFrameScans(videoDir);
+ // What the last Find clips found (release 36 lane A): one small sidecar.
+ const findClips = await loadFindClipsRecord(videoDir);
+
// The curated tags on this video, with each one's provenance. Reads tags.json
// plus (for rule hits) ONE key out of the transcript index — not a scan.
const tagsView = await loadVideoTags(slug, id);
@@ -245,6 +253,7 @@ export default async function VideoDetailPage({
panels,
tagsView,
frameScans,
+ findClips,
};
};
const drive = config.dataDir?.trim();
@@ -279,6 +288,7 @@ export default async function VideoDetailPage({
panels,
tagsView,
frameScans,
+ findClips,
} = loaded;
const registry = getRegistry();
@@ -417,6 +427,7 @@ export default async function VideoDetailPage({
coverage={coverage}
storedMediaHost={storedMediaHost}
channelStoredUrl={config.storedUrlDownloads}
+ workersPaused={getWorkerPool().isPaused()}
/>
<TagsPanel view={tagsView} />
@@ -440,6 +451,18 @@ export default async function VideoDetailPage({
readingT={readingT}
/>
+ {/* The clip finder's chain for this video (release 36 lane A). */}
+ <FindClipsPanel
+ slug={slug}
+ videoId={id}
+ umtoolUrl={resolveUmtoolUrl()}
+ holds={[
+ ...(getWorkerPool().isPaused() ? ["the transcription workers are paused"] : []),
+ ...(isGateHeld(getSettings(), "backfill") ? ["the backfill lane is held"] : []),
+ ]}
+ record={findClips}
+ />
+
{/* The external operations' per-video surface is the pipeline stage
cards INSIDE VideoPanel above (download, transcode, transcription).
These are the registry's — one panel per entry, and a fifth entry
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -207,6 +207,9 @@ export async function transcribeOneAction(
// true forces it, false forbids it, undefined leaves it automatic (a
// corrupt-full-source video is salvaged).
salvage?: boolean,
+ // Release 36 lane A: during a pause-all, run on a worker the pause alone
+ // switched off ("Transcribe now (workers paused)"; the pool's whilePaused).
+ whilePaused?: boolean,
): Promise<StreamActionResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
@@ -231,6 +234,7 @@ export async function transcribeOneAction(
onLog,
signal,
...(salvage !== undefined ? { salvage } : {}),
+ ...(whilePaused ? { whilePaused: true } : {}),
});
safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
},
@@ -554,6 +558,8 @@ export async function whisperVideoAction(
// outcome sidecar, the corrupt-source refetch — instead of the plain
// one-video download.
storedUrl?: StoredUrlMode,
+ // See transcribeOneAction's `whilePaused`.
+ whilePaused?: boolean,
): Promise<StreamActionResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
@@ -664,6 +670,7 @@ export async function whisperVideoAction(
onLog,
signal,
...(salvage !== undefined ? { salvage } : {}),
+ ...(whilePaused ? { whilePaused: true } : {}),
});
safeRevalidate([
`/channels/${slug}/videos/${videoId}`,
diff --git a/editor/e2e/find-clips.spec.ts b/editor/e2e/find-clips.spec.ts
@@ -0,0 +1,139 @@
+import { test, expect } from "@playwright/test";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import { mkdir, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { resetData, testPaths, writeSettings } from "./helpers";
+import { umtoolOriginFile } from "./servers";
+
+// FIND CLIPS (release 36, lane A) on the video page, end to end over a STUB
+// umtool started here and named to the test server through
+// E2E_UMTOOL_ORIGIN_FILE (e2e/servers.ts, common/lib/umtoolUrl.ts). The
+// fixture video already holds everything the chain makes — the source
+// container, the transcript, words.json, the chat replay, diarization.json —
+// so every editor step is skipped (each named in the log) and the job goes
+// straight to umtool's clips route: the worker token, the contract's body,
+// the job followed. Then the panel links the project and lists the segments,
+// and "Find clips in this part" posts again with that segment.
+
+const SLUG = "test-transcribe";
+const ID = "vidFC";
+
+type Call = { method: string; url: string; auth: string | undefined; body: Record<string, unknown> | null };
+
+let server: http.Server;
+let origin = "";
+const calls: Call[] = [];
+
+test.beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", () => {
+ const body = raw ? (JSON.parse(raw) as Record<string, unknown>) : null;
+ calls.push({ method: req.method ?? "", url: req.url ?? "", auth: req.headers.authorization, body });
+ res.setHeader("content-type", "application/json");
+ if (req.method === "POST" && req.url === "/api/report/clips") {
+ const segment = typeof body?.segment === "string" ? body.segment : null;
+ res.end(
+ JSON.stringify({
+ ok: true,
+ jobId: segment ? "u2" : "u1",
+ job: { id: segment ? "u2" : "u1" },
+ project: segment ? `vidfc-clips-${segment}` : "vidfc-clips",
+ created: true,
+ segment: segment ?? "s1",
+ href: `/projects/${segment ? `vidfc-clips-${segment}` : "vidfc-clips"}/clips`,
+ notes: [],
+ segments: [
+ { id: "s1", from: 290, to: 6300, why: "subject 4 holds 81% of long-turn time" },
+ { id: "s2", from: 6500, to: 9278, why: "subject 16 holds 77% of long-turn time" },
+ ],
+ }),
+ );
+ return;
+ }
+ if (req.method === "GET" && req.url?.startsWith("/api/report/clips?job=")) {
+ res.end(JSON.stringify({ state: "done", log: ["propose: 9 clips, 598 s"], next: 1 }));
+ return;
+ }
+ res.statusCode = 404;
+ res.end(JSON.stringify({ error: "no such route" }));
+ });
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+
+test.afterAll(async () => {
+ await rm(umtoolOriginFile(testPaths().transcriptsDir), { force: true });
+ await new Promise<void>((r) => server.close(() => r()));
+});
+
+test("Find clips: every step skipped, umtool asked with the token, the project linked and its segments listed", async ({ page }) => {
+ test.setTimeout(120_000);
+ await resetData("one-transcribe-channel");
+ await writeSettings({ minFreeDiskGB: 0 });
+ const videoDir = join(testPaths().transcriptsDir, "channels", SLUG, "data", ID);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(
+ join(videoDir, "metadata.info.json"),
+ JSON.stringify({ id: ID, title: "Synthetic reaction stream", webpage_url: `https://www.youtube.com/watch?v=${ID}`, was_live: true, duration: 9278 }),
+ );
+ await writeFile(join(videoDir, "source-media.mp4"), "container");
+ await writeFile(join(videoDir, "transcript.json"), JSON.stringify({ transcription: [] }));
+ await writeFile(join(videoDir, "words.json"), JSON.stringify({ version: 1, words: [{ w: "hello", start: 1, end: 1.4 }] }));
+ await writeFile(join(videoDir, "transcript.live_chat.json"), "\n");
+ await writeFile(join(videoDir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] }));
+ await writeFile(join(videoDir, "diarization.json"), JSON.stringify({ speakers: [], turns: [] }));
+ await writeFile(umtoolOriginFile(testPaths().transcriptsDir), origin);
+
+ await page.goto(`/channels/${SLUG}/videos/${ID}`);
+ const panel = page.getByRole("region", { name: "find-clips panel" });
+ await expect(panel.getByLabel("find-clips status")).toHaveText("not run yet");
+ await panel.getByLabel("target length (minutes)").fill("10");
+ await panel.getByRole("button", { name: "Find clips", exact: true }).click();
+ const out = page.getByLabel(`Find clips in ${ID} output`);
+ await expect(out).toContainText("@@find-clips", { timeout: 60_000 });
+ for (const line of [
+ "skipped: saved video — saved video present",
+ "skipped: corpus transcript — transcript.json present",
+ "skipped: word timings — words.json present (1 words)",
+ "skipped: chat replay — live_chat.cues.json present",
+ "skipped: diarization — diarization.json present",
+ "running: umtool — finding the segments and the clips",
+ "umtool: propose: 9 clips, 598 s",
+ ]) {
+ await expect(out).toContainText(line);
+ }
+
+ // umtool was asked as the contract says.
+ const post = calls.find((c) => c.method === "POST");
+ expect(post?.auth).toBe("Bearer test-worker-token");
+ expect(post?.body).toEqual({
+ mode: "new",
+ slug: "vidfc-clips",
+ from: `${SLUG}/${ID}`,
+ target: 600,
+ scope: "auto",
+ wordsPath: join(videoDir, "words.json"),
+ });
+
+ await page.reload();
+ const result = panel.getByLabel("find-clips result");
+ await expect(result.getByRole("link", { name: "vidfc-clips", exact: true })).toHaveAttribute("href", `${origin}/projects/vidfc-clips/clips`);
+ const segments = panel.getByRole("list", { name: "segments found" });
+ await expect(segments.getByRole("listitem")).toHaveCount(2);
+ await expect(segments).toContainText("s1 4:50–1:45:00");
+ await expect(segments).toContainText("s2 1:48:20–2:34:38");
+ await expect(panel.getByLabel("find-clips status")).toContainText("2 segments");
+
+ // One part: posts again with that segment (the target typed again: a
+ // reload clears the field).
+ await panel.getByLabel("target length (minutes)").fill("10");
+ await segments.getByRole("listitem").nth(1).getByRole("button", { name: "Find clips in this part", exact: true }).click();
+ await expect(page.getByLabel("Find clips in segment s2 output")).toContainText("@@find-clips", { timeout: 60_000 });
+ const second = calls.filter((c) => c.method === "POST")[1];
+ expect(second?.body).toMatchObject({ mode: "new", slug: "vidfc-clips-s2", segment: "s2", target: 600 });
+ expect(second?.body).not.toHaveProperty("scope");
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -52,6 +52,11 @@ export function blueskyOriginFile(transcriptsDir: string): string {
return join(transcriptsDir, ".fake-bluesky-origin");
}
+/** The file naming a slot's stub umtool (common/lib/umtoolUrl.ts; find-clips.spec). */
+export function umtoolOriginFile(transcriptsDir: string): string {
+ return join(transcriptsDir, ".fake-umtool-origin");
+}
+
/** The slot's recorded Odysee page reads (browser-lookup.spec writes it). */
export function odyseePageFixtureFile(transcriptsDir: string): string {
return join(transcriptsDir, ".fake-odysee-pages.json");
@@ -205,6 +210,8 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
// Where a spec names its fake Bluesky's origin (capture-posts.spec): the
// slot's own test data, so two slots never share one.
editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir);
+ // The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts).
+ editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir);
// The browser lookup's recorded page reads (browser-lookup.spec): set on
// every slot, so the e2e server never opens a headless browser on the
// network — the player-page opener refuses under it too.
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -34,6 +34,10 @@ import { currentSlot } from "./e2e/testPaths";
// writes its fake Bluesky's loopback origin into,
// which the AppView, bsky.app and the image CDN
// then are (common/social/blueskyEndpoints.ts)
+// E2E_UMTOOL_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec
+// writes its stub umtool's loopback origin into,
+// which Find clips then posts to
+// (common/lib/umtoolUrl.ts; find-clips.spec)
// E2E_ODYSEE_PAGE_FIXTURE set per slot (e2e/servers.ts): the file of
// recorded Odysee page reads the browser lookup
// answers from (browser-lookup.spec); while it is
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10840,3 +10840,105 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
copied (`created: true`); then ONE job `clips analyze <id>` → `{ok, jobId, job, project, created, segments,
segment (the chosen one's id), scope (the project's params.scope), href "/projects/<id>/clips", notes}`. GET
`?project=` adds `segments`, `segment`, `chat {source, lagS, lag, messages, bursts}`.
+## Release 36 lane C: the look — captions, loudness, vertical shorts (verified 2026-10-19, branch `r36/clip-look`)
+
+- **`render.captions`** `{style: "speakers", labels?: {host?: string|null, subject?: string|null}, size?: "m"|"l"}`,
+ **`render.loudness`** `{target}` (−30…−8 LUFS), clip **`vertical`** `{crop: [x, y, w, h], aspect?}` (fractions of the
+ source picture; 9:16 on the source within 3 %, `aspect` = source w/h, default 16/9). Absent or `null` = off and
+ byte-identical (md5 vs main 0d471989 on a two-clip fadeblack fixture). Validated by `validateLook(manifest)`
+ (`umtool/report-to-video/look.mjs`, exported `umtool-report-to-video/look`) in build-video's validators and lint's
+ `validatorErrors`; captions are refused beside `render.chrome` or `render.montage`, loudness beside `render.montage`.
+ Lane B's seed shape `loudness: {target: -16}` validates.
+- **Captions at the clip encode** (non-deck branch only): words for [cut record start, + segment seconds] from
+ `<project>/<reactions.source.words ?? "words.json">` when `reactions.json` (version 1, with `turns`) names the clip's
+ video (and channel), else corpus `transcript.json` whisper words (`whisperWords`), else cues (`fxWordsOf`); turns and
+ speakers only from that reactions.json. `captionLines`: speaker = the turn holding the word's middle, else the nearest
+ turn edge within 0.6 s, else null ("other"); a new line on a speaker change, at 6 words, or (from 2 words) on a gap
+ ≥ 0.45 s or past `maxChars`; a line ends at its last word + 0.3 s, never past the next line. Label = `labels[role]`,
+ else the speaker's label when it is not the default (`Host`/`Subject`/`Speaker N+1`), on a turn's first line only.
+ ASS: PlayRes = the frame, `WrapStyle: 2`, `YCbCr Matrix: None`, styles `host` (&H0040C8FF, align 1), `subject`
+ (&H00FFD36F, align 3), `other` (&H00E6F1F6, align 2), font "IBM Plex Sans" from `report-to-video/fonts/` (`fontsdir`),
+ size m = 0.052 × min(W, H), l = 0.075 ×; marginV = footer + 7 % (20 % on a vertical frame). File
+ `out/<variant>/segments/<id>.captions.ass`; the cut record gains `captions: {lines, words: "words.json"|"transcript.json"|"cues"}`.
+ A path with `'`, `:` or `\` cannot be an `ass=` option: refused with a sentence.
+- **Loudness at the clip encode** (non-montage, deck or not): `measureLoudness(raw, cutA, cutB)` (now exported) →
+ `loudnessGain` → `[0:a]levelFilters(gain)[al]` (an `asplit` first when a poster's waveform reads `[0:a]`); the cut
+ record gains `loudness: {measured, gain, target}`. A cut under −40 LUFS (montage.mjs `SILENT_LUFS`) gets gain 0.
+- **`--short <clipId>`** (`buildVideo({opts: {short}})`): `only` = that clip, `manifest.render = shortRender(render)`
+ (1080×1920, header/footer 0, `qr: false`, no chrome/rail/chromeEngine/brand/montage, `captions {style, labels?, size: "l"}`,
+ `loudness {target: cut's ?? -16}`), work dir `out/shorts-work/` (dirs.dir), picture `crop=W:H:X:Y,scale=1080:1920:flags=lanczos,setsar=1,fps`
+ from `cropPixels(vertical.crop ?? centre, display w, h)` (exact 9:16, even, the box's height and centre kept, clamped).
+ Output `<manifest dir>/shorts/<id>.mp4` (tmp + rename) + `<id>.json` `{version 1, clip, video, requested {cutStart, cutEnd},
+ cut [start, end] (played), crop, width, height, loudness, captions, madeAt}`. `takesHeavySlot` is true for a short.
+- **umtool writers**: `updateRender(dir, patch, {token})` (lib/report/manifest.mjs) — keys `LOOK_KEYS` = headerHeight,
+ footerHeight (ints 0–240), qr (true removes a `false`, keeps an object; false), transition (0–3 s, 2 dp),
+ transitionStyle, loudness, captions; `null` deletes a key; `chrome` or any other key → `RenderRefused`; the merged render
+ is checked with `validateTransitionStyle` + `validateLook`; atomic, token-guarded. `lookOf(render)`. `updateClip` takes
+ `vertical` (null/"" deletes; `verticalErrors`; 4 dp). Route `GET/PUT /api/report/render`.
+- **reactions.json**: `setSpeakerLabel(dir, index, label|null)` (common/lib/clips/reactions.mjs, after setSpeakerRole):
+ trimmed, ≤ 40 chars, empty → the default label; no timestamp. setSpeakerRole still resets a label to the default.
+ The clip editor's ops gain `label {speaker, label}` and `vertical {clip, crop|null, aspect?}` (an updateClip "trim"
+ edit that leaves the cut: `assist` untouched); its view gains `clips[].vertical` and `shorts {<clipId>: {mtimeMs, size, stale}}`.
+- **Shorts**: `umtool/lib/report/shorts.mjs` — `shortSteps(project, clipId)` (one step: `node build-video.mjs <manifest>
+ --out <project>/out --short <id> --progress ndjson`, 20 min), `readShorts(dir, manifest)` (newest first; a set-aside
+ `<id>.<YYYYMMDD-HHMM>.mp4` is not listed; `stale` = the requested cut or the crop differs from the clip's now; `gone`),
+ `setShortAside(dir, id, {replace})` (the replace guard: refused with `needsReplace` unless replace, then renamed aside
+ with its record). Route `/api/report/shorts`: GET `?project` `{shorts, running}`, `?project&clip&file=1[&download=1]`
+ (ranges), `?job`; POST `{project, clip, replace?}` → job kind `short <project> <clip>`; `?cancel=`.
+- **`umtool build <project> --run`** (`lib/report/buildRun.mjs` `runBuildOverHttp`): POST `/api/report/build`
+ (`?replace=1` with `--replace`) on `--url` > `UMTOOL_URL` > `http://localhost:3050`, Bearer `WORKER_TOKEN` when set;
+ polls `?job=&since=&sinceEvent=` every 1.5 s printing the log; SIGINT posts `?cancel=<job>` (a second Ctrl-C exits
+ 130); exit 0 only for `done`. Without `--run` unchanged (prints the chain).
+
+
+## Release 36 lane A: Find clips, run while paused, one video's chat (verified 2026-10-19, branch `r36/find-clips`)
+
+- **Run while paused**: `WorkerPool.acquire(signal, {whilePaused: true})` may lease a worker that is `disabled`
+ while `pausedSnapshot.get(id) === "enabled"` (the pause ALONE switched it off; `pauseHeld`), still `!degraded`,
+ `!busy`. The snapshot is only read: the lease leaves `state: "disabled"`, so release leaves it paused and
+ `resumeAll` restores it as before. A hand disable/drain during a pause writes `disabled` into the snapshot
+ (`syncSnapshot`), so it is never leased. `pauseHeldIds()` lists them. Carried by `transcribeWithWorker
+ ({whilePaused})`, `transcribe-file` body `whilePaused` (TRANSCRIBE_FILE_BODY_KEYS; a named worker in
+ `pauseHeldIds` is not refused), `transcribe-one` body `whilePaused` (→ `transcribeOneAction`/`whisperVideoAction`
+ 6th arg). Lanes/batches never pass it.
+- **`fetch-chat {slug, id, queueKey?}`** (`common/controller/fetchLiveChat.ts`): `liveChatPlan` →
+ `fresh` (isLiveChatCuesFresh) | `normalize` (raw `transcript.live_chat.json` + metadata here, cues stale: no
+ network) | `no-fetcher` (detectPlatform(url) ∉ {youtube} → `"no chat fetcher for <platform>: only YouTube's chat
+ replay is fetched"`) | `not-live` (metadata `live_status: "not_live"` and not `was_live`) | `fetch` | `refused`.
+ The job (`fetch-chat`, platform download queue, `needsMedia`, ingest) runs `liveChatOnlyArgs(config, cookies, url,
+ pace?)` — exported from `ytdlp/downloadOneManaged.ts`, the chat-only pass's argv (channelExtraArgs: cookies + live
+ `--sleep-requests`) — with the metadata refresh's cookie retry, backoff on rate_limit, `recordPlatformClean`, then
+ `normalizeLiveChat({force: true})`. fresh / no-fetcher / not-live / held / cooldown are `{ok: false, info: true}`
+ before a job; a pass that writes nothing ends `done` ("No chat replay for <id>").
+- **`find-clips {slug, id, target?, segment?, project?, whilePaused?, dryRun?}`** (`common/controller/findClips.ts`,
+ job kind `find-clips`, queue `find-clips`, `needsMedia`). Steps in order, each `skipped:`/`running: <label> — why`:
+ `persist` (saved-video pointer or a source container → skip; else `persist-videos {items}`), `transcript`
+ (transcript.json or an English VTT → skip; else `transcribe-one {slug, id, whilePaused?}`), `words`
+ (`data/<id>/words.json` with ≥1 word → skip; else `runTranscribeFile({path: audio|container|saved, words: true,
+ whilePaused?})` IN the job, written without `cues`/`text`; 0 words → not written, no `wordsPath`), `chat`
+ (liveChatPlan fetch/normalize → `fetch-chat`; a refusal/failure is logged and the chain goes on), `diarization`
+ (`diarization.json` → skip; off/unconfigured → fail; backfill lane held and !whilePaused → fail; held + whilePaused
+ → `diarizeOneVideo` in the job; else `runBackfillChannelJob({kindIds: ["diarization"], ids: [id]})` awaited),
+ `umtool`. The editor steps go through `findClipsEditor` (`editor/app/api/ops/_researchEditor.ts`, the in-process
+ ops door) and are waited on via `jobOfPaths`. A paused pool without whilePaused, or paused with no
+ `pauseHeldIds`, fails the transcription steps at once.
+- **The umtool call** (lane B's route): `POST ${umtoolUrl()}/api/report/clips` with `authorization: Bearer
+ WORKER_TOKEN`, body `{mode: "new", slug: <project ?? projectSlugFor(id, segment)>, from: "<slug>/<id>", target?,
+ segment? | scope: "auto", wordsPath?}` → reads `jobId` (or `job.id`), `project`, `created` (≠ false), `segments`
+ `[{id, from, to, subject?, host?, why?}]`, `segment` (the chosen one, recorded when none was asked), `href`
+ (`/projects/<id>/clips`, the record's url), `notes[]` (logged `umtool: note: …`); a 409 carrying `running` (umtool
+ busy) is asked again every 30 s up to an hour, any other 409 (slug exists) refuses; then `GET ?job=<id>&since=<n>` every 2 s, relaying `log[]` as
+ `umtool: <line>`, `next` the cursor, until `state !== "running"` (`done` ok, else `error`); 15 failed polls or a
+ 404 fail the step; cancel posts `?cancel=<job>`. `projectSlugFor("fGSRhEWc9M4", "s2")` = `fgsrhewc9m4-clips-s2`.
+ `umtoolUrl()` (`common/lib/umtoolUrl.ts`) = `UMTOOL_URL` minus trailing slashes, or the loopback origin in
+ `E2E_UMTOOL_ORIGIN_FILE` (test only).
+- **Two new sidecars** (in `SIDECAR_FILENAMES`, 17 now): `words.json` (`lib/wordTimings-server.ts`; the
+ TranscribeFileResult shape minus cues/text — umtool reads `doc.words`) and `find-clips.json`
+ (`lib/findClipsRecord-server.ts`: `{version: 1, at, jobId, project, url (<umtool>/projects/<p>/clips), created,
+ segment?, segments, steps: [{id, label, action: "ran"|"skipped", why}]}`, overwritten per run). The log ends
+ `@@find-clips {record…, umtoolJob}` (FIND_CLIPS_RESULT_MARKER; `pnpm ops find-clips --wait` prints it).
+- **The video page**: `FindClipsPanel` (section `find-clips panel`, after the frame scan, before the registry
+ panels): target minutes, "Run while paused" when `holds` (pool paused, backfill held) is non-empty, `Find clips`
+ (disabled + `find-clips off` line without umtoolUrl), then the record's project link and `segments found` with
+ `Find clips in this part` each. The Transcribe row's `Transcribe now (workers paused)` shows while the pool is
+ paused. Media tools → `Fetch live chat`.
diff --git a/plans/release-35.md b/plans/release-35.md
@@ -34,7 +34,7 @@ the five affected specs 31/31 (montage-ops, clip-editor, clip-deck, article-iter
- `~/reports/nik-drop-clips`: 20 assistant clips, 614 s of a 600 s target, 92 unused proposals → render
`out/nik-drop-clips.mp4` (617 s, verify clean). Each clip's QR links the YouTube upload at its second.
-## The operator's edits (2026-10-19 morning)
+## Edits to the cut (2026-10-19 morning; the operator fixed only an invalid manifest)
- Cut after ≈9:47 (r017, the host browsing for other videos: a Cut ruling through the clip editor); the cut now ends
on "Nikandros' favourite DM". The "OSINT autist" comment (proposal p021, 1007–1050 s) brought in.
diff --git a/plans/release-36/clip-finder-2.md b/plans/release-36/clip-finder-2.md
@@ -3,7 +3,7 @@
## Context
Release 35 (main `ff6d0fbb`) made Archilyzer an assisted clipping tool. The first case, "The Nik Drop" (a reaction
-livestream, 9278 s), was cut by the clip finder and adjusted by the operator in the clip editor (one clip cut, a
+livestream, 9278 s), was cut by the clip finder and adjusted in the clip editor (one clip cut, a
comment brought in, no on-screen UI, fade-through-black joins). Running it live exposed the hand work that is still
not a button:
- the chain (persist video → word timings → transcript → speakers → `umtool new --seed reactions` → `clips analyze`)
@@ -90,7 +90,7 @@ scope?|"auto", wordsPath?}` and `{mode:"analyze"|"propose", project}` with `Auth
## The live cases (after A + B + C merge; D's pass when it lands)
1. **Re-cut of the first half** (existing project, scope s1): Find clips → steps skip what exists, chat fetched,
- segments found; s1 re-analyzed in the EXISTING project (operator edits stand; chat proposals show as unused).
+ segments found; s1 re-analyzed in the EXISTING project (the current cut kept; chat proposals show as unused).
Look: speaker captions on, loudness −16, no-UI + fadeblack kept. Render (old output kept as `.v2.mp4`) + a short.
2. **Fresh test, the second half**: Find clips → a new project scoped to s2 by auto-scope, the site-less look; review;
render + a short.
diff --git a/plans/release-36/clip-look.md b/plans/release-36/clip-look.md
@@ -0,0 +1,100 @@
+# Release 36 lane C — `r36/clip-look`: the Look panel, loudness, speaker captions, vertical shorts (as shipped)
+
+The plan of record is [clip-finder-2.md](clip-finder-2.md), lane C. The first case's render look (no header or QR,
+fadeblack joins) was a jq edit of the manifest; it had no captions, uneven loudness (−19 LUFS) and no shareable
+shorts, and `umtool build` only printed its chain. This lane makes each of those a render key a person sets in the UI,
+renders them, and adds the short and `build --run`. Rulings followed: the UI works with no model (nothing here calls
+one); every review step a umtool surface; absent keys render byte for byte as before; redesign primitives and role
+tokens; synthetic fixtures only; the live projects read only.
+
+## What
+
+1. **The keys and their validators** (`umtool/report-to-video/look.mjs`, pure; `validateLook` in build-video's
+ validators and lint's `validatorErrors`, as `validateTransitionStyle` is):
+ - `render.captions {style: "speakers", labels?: {host?, subject?}, size?: "m" | "l"}` — refused beside
+ `render.chrome` (the deck's own words) or `render.montage`.
+ - `render.loudness {target}` −30…−8 LUFS — refused beside `render.montage` (which has its own). Lane B's seed shape
+ `{target: -16}` validates.
+ - clip `vertical {crop: [x, y, w, h], aspect?}` — fractions of the source, inside it, 9:16 on the source within 3 %.
+2. **Loudness** at the clip encode, deck or not, montage excepted: the cut measured (`measureLoudness`, now exported),
+ `levelFilters(loudnessGain(measured, target))` on `[0:a]` (an `asplit` first when a poster's waveform reads it);
+ the cut record carries `loudness {measured, gain, target}`.
+3. **Speaker captions** (no deck): per segment an ASS file (`segments/<id>.captions.ass`) from the project's
+ `words.json` (the recording reactions.json names), else whisper's words, else the cues; reactions.json's turns
+ colour and place each line; 2–6 words a line, broken on 0.45 s pauses, never across a speaker change; burned with
+ `ass=` (libass; ffmpeg n9.0.2 here has it). The colours (fixed, not the palette's): **host `#FFC840` amber bottom
+ left, subject `#6FD3FF` sky bottom right, other `#F6F1E6` paper bottom centre**, black outline, IBM Plex Sans from
+ `report-to-video/fonts/`. Names only when somebody gives one (`labels[role]`, else a non-default speaker label).
+ `setSpeakerLabel(dir, index, label)` added to common/lib/clips/reactions.mjs directly after setSpeakerRole (lane B's
+ file, the one export the prelude allowed); the clip editor's Speakers list edits it.
+4. **The Look panel** — the Build tab: Header, Timeline footer, QR code, Between clips (s) + Join (crossfade, dip to
+ black, dip to white, dissolve), Loudness (as recorded / −16 / custom), Speaker captions + each role's name + size;
+ Save the look writes the diff through `updateRender(dir, patch, {token})` (lib/report/manifest.mjs, modelled on
+ updateChrome: token-guarded, the build's checks, atomic; never `render.chrome`) behind `GET/PUT /api/report/render`.
+5. **Vertical shorts** — the clip editor's side column: Frame the short (a 9:16 box over the player: drag, size slider,
+ written to the clip's `vertical` through updateClip when let go; Centre it), Make a short → a job on umtool's runner
+ (`/api/report/shorts`, `lib/report/shorts.mjs`): `build-video.mjs --short <id>` — the clip alone at 1080×1920 from
+ its crop, captions size "l", no header/footer/QR, the cut's loudness else −16 — in the heavy slot, its work in
+ `out/shorts-work/`, the file `<project>/shorts/<id>.mp4` + `<id>.json`; a short that is there is set aside
+ (`<id>.<stamp>.mp4`), never overwritten. The Deliver tab's **Shorts** list: play, download, make again, frame it;
+ "the clip moved since" when the cut or crop changed.
+6. **`umtool build <project> --run`** (`lib/report/buildRun.mjs`): the build route's job over HTTP (`--url` >
+ `UMTOOL_URL` > `http://localhost:3050`), its log followed, Ctrl-C cancels; `--replace`. Without `--run` unchanged.
+
+## Files
+
+report-to-video: `look.mjs` (new), `look.test.mjs` (new, 15), `build-video.mjs` (imports, validator, loudness and
+captions in `buildClipSegment`, the short's framing, `probeDims` / `readLookSources` / `lookWordsFor` /
+`segmentCaptions` / `placeShort`, `--short`, `takesHeavySlot`), `lint.mjs`, `package.json` (`./look`,
+`./transition`), `README.md`. umtool: `lib/report/manifest.mjs` (`updateRender`, `lookOf`, `LOOK_KEYS`,
+`RenderRefused`, updateClip's `vertical`), `lib/report/clipEditor.mjs` (ops `label`, `vertical`; view `vertical`,
+`shorts`), `lib/report/clipEditorBridge.mjs`, `lib/report/clipEditorTypes.ts`, `lib/report/shorts.mjs` (new),
+`lib/report/buildRun.mjs` (new), `lib/report/look.test.mjs` (new, 5), `lib/report/buildRun.test.mjs` (new, 3),
+`app/api/report/render/route.ts` (new), `app/api/report/shorts/route.ts` (new),
+`components/projects/report/LookPanel.tsx` (new), `components/projects/report/ShortsList.tsx` (new), `BuildTab.tsx`,
+`DeliverTab.tsx`, `components/projects/review/ClipEditor.tsx` (CropBox, SpeakerLabel, ShortMaker), `bin/umtool.mjs`,
+`e2e/clip-look.spec.ts` (new), `e2e/fixtures/clip-editor-fixture.mjs` (a `name`), `e2e/fixtures/make-fixture.mjs`,
+`docs/report-video.md` ("The look: captions, loudness, shorts"), `docs/cli.md`. common: `lib/clips/reactions.mjs` +
+`.d.mts` (`setSpeakerLabel`). `editor/CHANGELOG.md`, `plans/FACTS.md` ("Release 36 lane C").
+
+## Commits
+
+| sha | what |
+|---|---|
+| `c8355cf2` | report-to-video: look.mjs, loudness + captions at the clip encode, `--short`; 15 tests |
+| `83304773` | umtool: updateRender + /api/report/render, a clip's vertical, setSpeakerLabel, shorts job + route; 5 tests |
+| `fe6b9968` | umtool: the Look panel, Frame the short + Make a short, the Shorts list |
+| `ebdf6ab7` | umtool: `umtool build --run`; 3 tests |
+| `5004235c` | umtool e2e: clip-look.spec.ts; the clip editor's fixture takes a name |
+| `6d796dfd` | docs, FACTS, CHANGELOG |
+| (this) | plans: this record |
+
+## Gates (all through the session lock, from the worktree root)
+
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` — clean on the full tree before the commits.
+- `pnpm run test:scripts` — **1278 tests, 1274 pass, 0 fail, 4 skipped** (branch start, main 0d471989: 1255 / 1251 / 4;
+ +23: `report-to-video/look.test.mjs` 15, `lib/report/look.test.mjs` 5, `lib/report/buildRun.test.mjs` 3).
+- `pnpm --filter umtool test` — 45 / 45 (unchanged). common `lib/clips/*.test.ts` — 24 / 24 (setSpeakerLabel is
+ tested through the clip editor's `label` op in `lib/report/look.test.mjs`; lane B's test file untouched).
+- The render tests (real ffmpeg, in look.test.mjs): a caption line up on its frame (0.25 s → frame 8 of a 30 fps
+ segment, nothing on frame 6), the subject's pixels sky (mean B > R + 60) on the right only, the host's amber
+ (R > B + 80) on the left only; loudness: a −27 LUFS tone to −16 within ±0.5 LU (segment and cut); the short
+ 1080×1920, its crop's bar at x 428–642 as computed, no header, −16 within ±0.5 LU, captions at 81 px.
+- **Byte-identical without the new keys**: in-suite (absent vs `null`: final, segment, cut record); and against
+ main's build-video (`$T/r36c-scripts/bytecheck.mjs`, a two-clip fadeblack 640×360 fixture, the primary checkout's
+ build-video vs the branch's): final `49033bc6…`, segments `875fe480…` / `73cd16d7…`, cut records `ef0ece96…` /
+ `6cd4f047…` — the same both sides.
+- e2e (umtool, `E2E_MODE=dev`, no build): `clip-look.spec.ts` **1 passed** (35.8 s; wall 45 s after 3.8 min in the
+ machine's heavy queue); on the tip `6d796dfd` with `clip-editor.spec.ts`: **2 passed, 0 failed** (clip-editor 24.5 s,
+ clip-look 9.4 s; wall 43.7 s after 13 min in the heavy queue).
+- No `next build` (dev-mode e2e); no generated doc changed (umtool's CLI and env are out of COMMANDS.md /
+ ENVIRONMENT.md's scope).
+
+## Found and left
+
+- A cut quieter than −40 LUFS is not raised (montage.mjs's `SILENT_LUFS` rule, kept): a near-silent clip is a cut in
+ the wrong place, not a quiet one.
+- setSpeakerRole resets a speaker's label to the default, so a name set before a role change is lost (the analysis'
+ writer, lane B's; not changed here).
+- Words heard in no turn (or by one of the stream's small clusters) are captioned as "other", paper centre.
+- Captions are not offered under the deck (its `fx.kineticQuote` is the deck's own) or on a montage.
diff --git a/plans/release-36/find-clips.md b/plans/release-36/find-clips.md
@@ -0,0 +1,114 @@
+# Release 36 lane A — `r36/find-clips`: one button on the video page (as shipped)
+
+Release 35 ran the clip finder's chain from a shell, step by step, and forced two transcriptions through a PAUSED
+worker pool by hand. This lane makes the chain one job and one button: **Find clips** on the video page (`pnpm ops
+find-clips`), a run-while-paused path for one manual transcription, and a chat-replay fetch for one video. Rulings
+followed: the UI works with no model (nothing here calls one); every CLI operation added has a button; no yt-dlp or
+ASR by hand (every step is an editor job or a worker lease); paced YouTube requests; plain words, no lead paragraphs;
+synthetic fixtures only; commits end with the one Co-Authored-By trailer.
+
+## What
+
+1. **Run while paused** — `common/jobs/workerPool.ts`: `acquire(signal, {whilePaused: true})` may lease a worker the
+ pause-all ALONE switched off: the pool is paused, the worker is `disabled`, and its `pausedSnapshot` entry is
+ `enabled` (`pauseHeld`). Never one drained, degraded or disabled by hand (a hand control during a pause writes
+ `disabled` into the snapshot; a degrade mark fails eligibility on its own). The snapshot is only read: the lease
+ leaves the worker `disabled`, so when it releases the worker is still paused and `resumeAll` restores it exactly as
+ before. `pauseHeldIds()` lists them. The flag rides `transcribeWithWorker({whilePaused})`, the `transcribe-file`
+ body (`pnpm ops transcribe`; a NAMED worker the pause holds is not refused when the request is whilePaused) and the
+ `transcribe-one` body (both of its forms). Lane and batch acquires never pass it. The video page's Transcribe row
+ shows **Transcribe now (workers paused)** while the pool is paused.
+2. **Chat replay for one video** — `common/controller/fetchLiveChat.ts`, `pnpm ops fetch-chat {slug, id}`, Media
+ tools → **Fetch live chat**. `liveChatPlan` decides from the disk and the metadata: fresh cues → skip; the raw
+ replay here with stale cues → normalize only (no network); a platform other than YouTube → "no chat fetcher for
+ <platform>: only YouTube's chat replay is fetched"; `live_status: "not_live"` → never live. A fetch runs the
+ managed download's chat-only argv (`liveChatOnlyArgs`, now exported from `ytdlp/downloadOneManaged.ts`: the
+ channel's cookies and the platform's live pace) on the platform's DOWNLOAD queue, with the held-platform and
+ cooldown refusals, the cookie retry, the backoff record and the clean-pass settle the metadata refresh uses, then
+ `normalizeLiveChat`. The skips are `{ok: false, info: true}` before any job; a pass that writes nothing ends `done`.
+3. **Find clips** — `common/controller/findClips.ts`, job kind `find-clips` on its own `find-clips` queue. In order,
+ each step skipped when its output exists and named in the log (`skipped: <step> — why` / `running: <step> — why`):
+ persist the source (`persist-videos`), the corpus transcript (`transcribe-one`, whilePaused passed), word timings
+ (the file transcription with words IN the job, into `data/<id>/words.json`), the chat replay (`fetch-chat`; a
+ refusal or failure is logged and the chain goes on), diarization (the backfill lane's one-video run; past a held
+ lane only with whilePaused, in the job), then umtool: `POST ${UMTOOL_URL}/api/report/clips` with the worker token,
+ `{mode: "new", slug: <project>, from: "<slug>/<id>", target?, scope: "auto" | segment, wordsPath}`, and `GET
+ ?job=<id>` followed to the end with its log relayed. The editor steps go through the editor's own ops actions in
+ process (`findClipsEditor`, the research run's door) and are waited on; the job never sits on a queue a step needs.
+ What would park a step forever fails it at once with where to fix it: a paused pool without whilePaused (or with
+ no worker the pause alone holds), diarization switched off or unconfigured, a held backfill lane without
+ whilePaused. umtool down, refusing or failing fails the umtool step naming the URL or umtool's error. The log ends
+ `@@find-clips {json}`; `data/<id>/find-clips.json` keeps the project, its clip editor URL (umtool's `href`), the
+ segment (the one asked, else auto-scope's), the segments and the steps for the page. A `dryRun` answers each
+ step's plan. Lane B's final route: a 409 naming umtool's running job is asked again every 30 s (up to an hour);
+ any other 409 (the slug exists) refuses; its `notes` are logged. `pnpm ops get workers` marks the workers a
+ whilePaused job may take (`pauseHeld: true`).
+4. **The video page** — `FindClipsPanel`: a target length (minutes), **Run while paused (this video only)** when
+ something holds a step (the pool paused, the backfill lane held — named in a status line), **Find clips**
+ (disabled with "UMTOOL_URL is not set on the editor…" without one), and after a run the project linked and the
+ segments found, each with **Find clips in this part** (posts again with `segment`).
+
+## Interfaces
+
+- `WorkerPool.acquire(…, {whilePaused?})`, `WorkerPool.pauseHeldIds()`; `TranscribeWithWorkerOptions.whilePaused`;
+ `TranscribeFileRequest.whilePaused`, `TRANSCRIBE_FILE_BODY_KEYS` + `"whilePaused"`; `transcribeOneAction(…,
+ salvage, whilePaused)`, `whisperVideoAction(…, storedUrl, whilePaused)`.
+- `liveChatOnlyArgs(config, cookies, url, pace?)`; `liveChatPlan`, `fetchLiveChat`, `runFetchChatJob`,
+ `FETCH_CHAT_JOB_KIND`, `CHAT_PLATFORMS`, `noChatFetcherSentence`.
+- `parseFindClipsBody`, `inspectFindClips`, `planFindClipsSteps`, `runFindClips`, `enqueueFindClips`,
+ `projectSlugFor`, `umtoolProjectUrl`, `FIND_CLIPS_JOB_KIND`, `FIND_CLIPS_QUEUE`, `FIND_CLIPS_RESULT_MARKER`,
+ `FIND_CLIPS_BODY_KEYS`; `umtoolUrl()` (`common/lib/umtoolUrl.ts`); sidecars `words.json`
+ (`lib/wordTimings-server.ts`) and `find-clips.json` (`lib/findClipsRecord-server.ts`).
+- Routes: `POST /api/ops/fetch-chat`, `POST /api/ops/find-clips`; `transcribe` / `transcribe-one` take
+ `whilePaused`. umtool's clips route is lane B's; this lane calls it exactly as the plan's contract says.
+
+## Files
+
+common: `jobs/workerPool.ts`, `jobs/workerPool.whilePaused.test.ts`, `jobs/jobKinds.ts` (fetch-chat, find-clips),
+`controller/transcribeOne.ts`, `controller/transcribeFile.ts` (+ test), `controller/fetchLiveChat.ts` (+ test),
+`controller/findClips.ts` (+ test), `ytdlp/downloadOneManaged.ts` (the argv builder exported), `lib/umtoolUrl.ts`,
+`lib/wordTimings-server.ts`, `lib/findClipsRecord-server.ts`, `lib/sidecar-server.test.ts`, `lib/envVars.ts`.
+editor: `app/api/ops/{fetch-chat,find-clips}/route.ts`, `app/api/ops/_findClips.ts`, `app/api/ops/_researchEditor.ts`
+(findClipsEditor), `app/api/ops/{transcribe,transcribe-one}/route.ts`, `app/api/ops/_door.test.ts`, the video page
+(`page.tsx`, `videoActions.ts`, `mediaToolsActions.ts`, `findClipsActions.ts`, `components/FindClipsPanel.tsx`,
+`components/VideoMediaTools.tsx`, `components/VideoPanel.tsx`, `components/cards/PerFileTranscribeRow.tsx`),
+`e2e/find-clips.spec.ts`, `e2e/servers.ts` (E2E_UMTOOL_ORIGIN_FILE), `playwright.config.ts`.
+scripts: `archilyzer-ops.mjs` (+ test). Docs: COMMANDS.md, ENVIRONMENT.md (regenerated), OPERATING.md ("Find clips in
+a recording"), editor/CHANGELOG.md, plans/FACTS.md.
+
+## Gates
+
+All from the worktree root, through the session lock. Counts at the branch's start (main `0d471989`) → before the
+merge of main (lane B, `8938a5dd`) → after it:
+
+| Gate | Start | Before merge | After merge |
+|---|---|---|---|
+| tsc (`pnpm -r … exec tsc --noEmit`) | — | clean | clean |
+| common (`pnpm --filter yt-dlp-transcript-common test`) | 4657 (4655 pass, 2 skipped) | 4674 (4672 pass, 2 skipped) | 4688 (4686 pass, 2 skipped) |
+| editor unit (`pnpm --filter editor test`) | 346 | 346 | 346 |
+| test:scripts | 1255 (1251 pass, 4 skipped) | 1256 (1252 pass, 4 skipped) | 1264 (1260 pass, 4 skipped) |
+| docs cli / env / files, settings example `--check` | — | clean (COMMANDS.md, ENVIRONMENT.md regenerated) | clean |
+
+New unit tests: `jobs/workerPool.whilePaused.test.ts` (6), `controller/fetchLiveChat.test.ts` (6),
+`controller/findClips.test.ts` (9: every step run, every step skipped, umtool down / refusing / failing / slug taken,
+umtool busy then free, twitch chat skip + refused chat fetch, paused pool, diarization off / lane held / whilePaused
+inline / inline failure, dry run + refusals + the job's record and marker), `lib/umtoolUrl.test.ts` (1), three in
+`transcribeFile.test.ts` (whilePaused parse, the named pause-held worker, a paused pool running a whilePaused job),
+the sidecar enumeration (17), the door's traversing slug for fetch-chat and find-clips, the ops client's usage and
+marker.
+
+Editor e2e (start mode; the e2e build 894 s including the wait for the machine's heavy slot):
+`find-clips.spec.ts` 1 passed (17.5 s); `video-page.spec.ts` + `workers.spec.ts` 30 passed (57.6 s);
+after the merge of main (lane B) and the contract alignment, `find-clips.spec.ts` again: 1 passed (11.4 s; the
+rebuild took 2210 s, nearly all of it waiting for the machine's heavy slot).
+
+A common-suite run once hung over 11 minutes in `controller/seeder.test.ts` (webtorrent); it was stopped and the
+next run was clean. Not this lane's file.
+
+## Found and left
+
+- The word-timings transcription cuts its 16 kHz WAV under the OS temp dir (`runTranscribeFile`, as `pnpm ops
+ transcribe` always has): about 300 MB for a 2.5-hour recording, in RAM where `/tmp` is a tmpfs, for the length of the
+ transcription. Not changed here; the live editor's `TMPDIR` decides.
+- The backfill lane's one-video run (the diarization panel's Run) is held by the lane's gate like the sweep is; Find
+ clips says so and offers whilePaused rather than waiting. The panel's own Run is unchanged.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -41,6 +41,10 @@
// pnpm ops sync --json '{"slug":"the-quartering"}' --wait
// pnpm ops metadata-scan --json '{"slug":"the-quartering"}'
// pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait
+// pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait
+// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'
+// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait
+// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait
// pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait
// pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait
// pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait
@@ -491,6 +495,15 @@ const ACTIONS = [
// scope?, max?, force?}); one audio-audit job per channel. The damaged ones
// are the report's corruptHeldAudio bucket, which retry-bucket refetches.
"audio-audit",
+ // THE CLIP FINDER, ROUND TWO (release 36, lane A): one video's live chat
+ // replay alone ({slug, id}), paced, into live_chat.cues.json, as a fetch-chat
+ // job on the platform's download queue. And the clip finder's chain for one
+ // video ({slug, id, target?, segment?, project?, whilePaused?, dryRun?}):
+ // persist, transcript, word timings, chat, diarization, umtool — each step
+ // skipped when its output exists — as a find-clips job. With --wait the
+ // result JSON (the project, its URL, the segments) is what stdout carries.
+ "fetch-chat",
+ "find-clips",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -518,6 +531,9 @@ export const MIRROR_SCAN_RESULT_MARKER = "@@mirror-scan ";
// The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in
// common/controller/remoteListing.ts).
export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing ";
+// The same for Find clips (FIND_CLIPS_RESULT_MARKER in
+// common/controller/findClips.ts).
+export const FIND_CLIPS_RESULT_MARKER = "@@find-clips ";
// The provenance a tag write from this CLI carries. Everything else ignores it.
function agentSource() {
@@ -745,6 +761,7 @@ export function parseArgs(argv) {
...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}),
...(action === "frame-scan" ? { resultMarker: FRAME_SCAN_RESULT_MARKER } : {}),
...(action === "mirror-scan" ? { resultMarker: MIRROR_SCAN_RESULT_MARKER } : {}),
+ ...(action === "find-clips" ? { resultMarker: FIND_CLIPS_RESULT_MARKER } : {}),
...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}),
wait,
quiet,
@@ -968,6 +985,9 @@ export function usage() {
' reads it — no page request with "only", the page first with "fallback" —',
' through the audio check; one new file per platform per 20 min. Absent =',
' the channel\'s storedUrlDownloads.',
+ ' "whilePaused": true runs this one transcription during a pause-all on a',
+ ' worker the pause alone switched off; the pause stays on (the video page\'s',
+ ' "Transcribe now (workers paused)").',
"",
'delete-file deletes one file of one video, as its Files list does:',
' {"slug", "id", "file"}. A tiered media file goes with its bytes on the',
@@ -1128,6 +1148,27 @@ export function usage() {
' {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the',
' transcripts/ repo\'s own history.',
"",
+ 'fetch-chat fetches ONE video\'s live chat replay and nothing else: {"slug",',
+ ' "id"} — the chat-only yt-dlp pass (the channel\'s cookies, the platform\'s',
+ " pace) on the platform's download queue, then live_chat.cues.json. YouTube",
+ ' only: another platform answers "no chat fetcher for <platform>" (info, no',
+ " job), as do a chat already here and fresh and a video never live. A pass",
+ " that finds no replay ends done and says so.",
+ "",
+ 'find-clips runs the clip finder\'s chain for ONE video as one job: {"slug",',
+ ' "id", "target"? (the cut\'s seconds), "segment"? (one umtool found, "s2"),',
+ ' "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}.',
+ " Persist the source video, the corpus transcript, word timings",
+ " (data/<id>/words.json), the chat replay (YouTube), diarization — each step",
+ " skipped when its output exists, named in the log — then umtool's clip",
+ ' finder (POST UMTOOL_URL/api/report/clips {mode: "new"}), followed to the',
+ " end. \"whilePaused\": true runs this one video past the holds: the two",
+ " transcriptions during a pause-all on a worker the pause alone switched",
+ " off, and its diarization in the job when the backfill lane is held.",
+ " \"dryRun\": true answers each step's",
+ " plan and starts nothing. With --wait the result — {project, url, created,",
+ " segments: [{id, from, to, why}], steps} — is printed on stdout.",
+ "",
'refresh-metadata re-reads ONE video\'s metadata.info.json from its source',
' (no subtitles, no media) on the platform\'s queue: {"slug", "id"}. The',
' job\'s log ends with what the source now says — live_status, formats,',
@@ -1291,6 +1332,9 @@ export function usage() {
" 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.",
"",
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -6,6 +6,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
+ FIND_CLIPS_RESULT_MARKER,
REMOTE_LISTING_RESULT_MARKER,
TRANSCRIBE_RESULT_MARKER,
TTS_RESULT_MARKER,
@@ -810,6 +811,21 @@ test("the archival writes are POSTs to their routes, each named in the usage", (
assert.match(usage(), /"publish", "enabled"\?, "held"\?, "action"\?/);
});
+// RELEASE 36 LANE A: the clip finder's chain and one video's chat replay.
+test("fetch-chat and find-clips are POSTs named in the usage; find-clips --wait carries its marker", () => {
+ for (const action of ["fetch-chat", "find-clips"]) {
+ const p = parseArgs([action, "--json", '{"slug":"x","id":"y"}']);
+ assert.equal(p.method, "POST", action);
+ assert.equal(p.path, `/api/ops/${action}`, action);
+ assert.match(usage(), new RegExp(`^${action} `, "m"), action);
+ }
+ const w = parseArgs(["find-clips", "--json", '{"slug":"x","id":"y"}', "--wait"]);
+ assert.equal(w.resultMarker, FIND_CLIPS_RESULT_MARKER);
+ assert.equal(FIND_CLIPS_RESULT_MARKER, "@@find-clips ");
+ assert.match(usage(), /"whilePaused": true runs this one video past the holds/);
+ assert.match(usage(), /no chat fetcher for <platform>/);
+});
+
test("get remote-listing posts the job, waits, and carries the result marker", () => {
const r = parseArgs(["get", "remote-listing", "demo-odysee"]);
assert.equal(r.method, "POST");
diff --git a/umtool/app/api/report/render/route.ts b/umtool/app/api/report/render/route.ts
@@ -0,0 +1,65 @@
+import { withEditNotes } from "@/lib/report/guard";
+import { LOOK_KEYS, RenderRefused, StaleToken, lookOf, manifestToken, updateRender } from "@/lib/report/manifest.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { deckOn } from "umtool-report-to-video/deck";
+import { validateLook } from "umtool-report-to-video/look";
+import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition";
+
+export const dynamic = "force-dynamic";
+
+// THE LOOK (release 36 lane C): the render keys the Look panel sets --
+// headerHeight, footerHeight, qr, transition, transitionStyle, loudness,
+// captions -- never render.chrome (the deck's own route). The client sends a
+// project id, a PATCH of those keys (null removes one) and the token it read;
+// the writer (lib/report/manifest.mjs updateRender) validates with the
+// build's own checks, so a look this route accepts is one the build accepts.
+//
+// GET ?project=<id> { look, deck, montage, styles, keys, errors, token }
+// PUT { project, token, patch } { ok, look, token } | 409 stale | 400 { errors }
+
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const render = (r.manifest.render ?? {}) as Record<string, unknown>;
+ return Response.json(
+ {
+ look: lookOf(render),
+ deck: deckOn(render),
+ montage: render.montage !== undefined && render.montage !== null,
+ styles: TRANSITION_STYLES,
+ keys: LOOK_KEYS,
+ // A look somebody hand-edited into a state the build would refuse.
+ errors: [...validateTransitionStyle(r.manifest), ...validateLook(r.manifest)],
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function PUT(request: Request) {
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ try {
+ const { result: res, editNotes } = await withEditNotes(r.project, () =>
+ updateRender(r.project.dir, (body.patch ?? null) as Record<string, unknown>, {
+ token: body.token === undefined || body.token === null ? null : String(body.token),
+ }),
+ );
+ return Response.json({ ok: true, look: res.look, token: res.token, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) {
+ return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 });
+ }
+ if (e instanceof RenderRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/app/api/report/shorts/route.ts b/umtool/app/api/report/shorts/route.ts
@@ -0,0 +1,97 @@
+import { stat } from "node:fs/promises";
+import { cancelJob, getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { clipsOf, readManifest } from "@/lib/projects/report.mjs";
+import { rangeResponse } from "@/lib/report/serve.mjs";
+import { readShorts, setShortAside, shortFile, shortSteps } from "@/lib/report/shorts.mjs";
+
+export const dynamic = "force-dynamic";
+
+// VERTICAL SHORTS (release 36 lane C): `<project>/shorts/<clipId>.mp4`, one
+// clip at 1080x1920 (build-video.mjs --short, in the heavy slot), as ONE job
+// on the app's runner (lib/jobs.ts: one at a time, a log, Cancel) -- the
+// clip editor's Make a short and the Deliver tab's Shorts list.
+//
+// GET ?project=<id> { shorts, running }
+// GET ?project=<id>&clip=<id>&file=1 the mp4 (ranges; `download=1` as an attachment)
+// GET ?job=<id>[&since=&sinceEvent=] that job
+// POST { project, clip, replace? } make it; 409 { needsReplace } when one is there
+// ?cancel=<job> stop it
+const headers = { "cache-control": "no-store" };
+const isShortJob = (kind: string) => /^short /.test(kind);
+
+async function reportProject(id: unknown) {
+ const project = await projectRef(String(id ?? ""));
+ if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) };
+ if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "a short is made of a report video's clip" }, { status: 400, headers }) };
+ return { project };
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const jobId = url.searchParams.get("job");
+ if (jobId) {
+ const job = getJob(jobId);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers });
+ }
+ const r = await reportProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ if (url.searchParams.get("file")) {
+ const clip = url.searchParams.get("clip") ?? "";
+ const abs = shortFile(r.project.dir, clip);
+ const st = abs ? await stat(abs).catch(() => null) : null;
+ if (!abs || !st?.isFile()) return new Response(`no short of ${clip}`, { status: 404 });
+ return rangeResponse(request, {
+ abs,
+ size: st.size,
+ headers: {
+ "content-type": "video/mp4",
+ "accept-ranges": "bytes",
+ "cache-control": url.searchParams.get("v") === String(Math.round(st.mtimeMs)) ? "private, max-age=3600, immutable" : "private, no-store",
+ ...(url.searchParams.get("download") ? { "content-disposition": `attachment; filename="${clip}-short.mp4"` } : {}),
+ },
+ });
+ }
+ const manifest = await readManifest(r.project.dir);
+ const running = runningJob();
+ return Response.json(
+ {
+ shorts: await readShorts(r.project.dir, manifest),
+ running: running && running.project === r.project.id && isShortJob(running.kind) ? jobView(running) : null,
+ },
+ { headers },
+ );
+}
+
+export async function POST(request: Request) {
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) return Response.json({ cancelled: cancelJob(cancel) }, { headers });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await reportProject(body.project);
+ if ("error" in r) return r.error;
+ const manifest = await readManifest(r.project.dir);
+ if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers });
+ const clip = String(body.clip ?? "");
+ if (!clipsOf(manifest).some((e: { id: string }) => e.id === clip) || !shortFile(r.project.dir, clip)) {
+ return Response.json({ error: `no clip with id ${clip}` }, { status: 400, headers });
+ }
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers });
+ let aside: string | null = null;
+ try {
+ aside = await setShortAside(r.project.dir, clip, { replace: body.replace === true });
+ } catch (e) {
+ const needsReplace = !!(e as { needsReplace?: boolean })?.needsReplace;
+ return Response.json({ error: e instanceof Error ? e.message : String(e), needsReplace }, { status: 409, headers });
+ }
+ try {
+ const job = startJob(`short ${r.project.id} ${clip}`, shortSteps(r.project, clip), { project: r.project.id });
+ return Response.json({ ok: true, clip, aside, job: jobView(job) }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -25,6 +25,7 @@
// [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent
// umtool corrections <project> what the report got wrong, as markdown for the next pass
// umtool build <project> [--preset preview|fast|final] [--only ID] [--dry]
+// [--run [--url URL] [--replace]] run it as the app's job, follow it, Ctrl-C cancels
// umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]
// [--draft-all [--model M] [--deck]]
// an iteration's pipeline: current, windows, prepare, posts, manifest,
@@ -88,6 +89,7 @@ import { updateClip, updateStorage } from "../lib/report/manifest.mjs";
import { withEditNotes } from "../lib/report/edit-guard.mjs";
import { hms } from "umtool-report-to-video/attribution";
import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs";
+import { runBuildOverHttp, umtoolBase } from "../lib/report/buildRun.mjs";
import { CHAIN_STEP_NAMES, chainStepsOf, planChain } from "../lib/report/chain.mjs";
import { spawn } from "node:child_process";
import { openIndex, signRecord } from "../lib/projects/index-db.mjs";
@@ -698,6 +700,8 @@ function usage() {
" an empty value (--title '') deletes the field",
" umtool corrections <project> what the report got wrong + the walk's coverage",
" umtool build <project> [--preset preview|fast|final] [--only ID]",
+ " --run: the app's build job (UMTOOL_URL, else http://localhost:3050; --url), followed here;",
+ " Ctrl-C cancels it; --replace stamps a newer deliverable aside",
" umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]",
` an article iteration's pipeline, one step a process: ${CHAIN_STEP_NAMES.join(", ")}`,
" (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)",
@@ -1003,7 +1007,33 @@ async function cmdBuild() {
clipCount,
});
- if (json) return out({ project: p.id, preset, steps });
+ if (json && !has("--run")) return out({ project: p.id, preset, steps });
+
+ // --run (release 36): the app runs the chain -- its job runner owns the
+ // cancellation, the timeouts and the process-group kill -- and this follows it.
+ if (has("--run")) {
+ const base = umtoolBase(val("--url"));
+ let cancel = null;
+ let stopping = false;
+ process.on("SIGINT", async () => {
+ if (stopping || !cancel) process.exit(130);
+ stopping = true;
+ console.error("\ncancelling the build job (Ctrl-C again to leave it running)…");
+ const ok = await cancel().catch(() => false);
+ console.error(ok ? "cancel requested; waiting for the job to stop" : "the job did not take the cancel");
+ });
+ const r = await runBuildOverHttp({
+ base, project: p.id, preset, only: val("--only") ?? null, skipFetch: has("--skip-fetch"), replace: has("--replace"),
+ token: process.env.WORKER_TOKEN ?? null,
+ log: (l) => (json ? null : console.log(l)),
+ onJob: (c) => {
+ cancel = c;
+ },
+ });
+ if (json) out(r);
+ if (r.state === "done") return;
+ die(r.needsReplace ? `${r.error} (--replace)` : `build ${r.state}${r.error ? `: ${r.error}` : ""}`, 1);
+ }
// Print, never run. The app runs the chain through lib/jobs.ts, which owns the
// cancellation, the timeouts and the process-group kill; a second runner here
diff --git a/umtool/components/projects/report/BuildTab.tsx b/umtool/components/projects/report/BuildTab.tsx
@@ -2,10 +2,11 @@ import Link from "next/link";
import { fmtAgo, fmtBytes } from "@/lib/format";
import { mixHref } from "@/lib/hrefs";
import ReportBuildChain from "../ReportBuildChain";
+import LookPanel from "./LookPanel";
import type { ReportTabProps } from "./shared";
-// The Build tab: the final video and the build chain (its job on the ONE
-// JobProgress). The on-screen panel was parked here until P4b moved it to
+// The Build tab: the final video, the look (LookPanel, release 36) and the
+// build chain (its job on the ONE JobProgress). The on-screen panel was parked here until P4b moved it to
// the Media tab.
export default function BuildTab({ project, detail }: ReportTabProps) {
@@ -29,6 +30,8 @@ export default function BuildTab({ project, detail }: ReportTabProps) {
</Link>
</div>
)}
+ {/* --- the look: header, QR, joins, loudness, captions (release 36) */}
+ <LookPanel project={project.id} />
{/* --- building it ---------------------------------------------- */}
<ReportBuildChain
project={project.id}
diff --git a/umtool/components/projects/report/DeliverTab.tsx b/umtool/components/projects/report/DeliverTab.tsx
@@ -3,6 +3,7 @@ import { EXPORT_FORMATS, exportableVariants } from "@/lib/report/export.mjs";
import { podcastFor } from "@/lib/report/serve.mjs";
import DeliverSection from "../DeliverSection";
import PodcastExport from "../PodcastExport";
+import ShortsList from "./ShortsList";
import type { ReportTabProps } from "./shared";
// The Deliver tab: the deliver panel (cuts, share batches, rulings applied,
@@ -29,6 +30,9 @@ export default async function DeliverTab({ project, detail }: ReportTabProps) {
own clip files is the other, and both wait on the same walk. */}
<DeliverSection project={project} manifest={m} entries={entries} />
+ {/* --- the shorts: one clip each, 1080x1920 (release 36) ---------- */}
+ <ShortsList project={project.id} />
+
{/* --- exports --------------------------------------------------- */}
<section data-exports="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
<h2 className="micro mb-1">export</h2>
diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx
@@ -0,0 +1,230 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { Field, Input, Select } from "@/components/ui/field";
+import { Panel } from "@/components/ui/panel";
+
+// THE LOOK (release 36 lane C): the render keys a person sets for a cut with
+// no deck -- the header, the timeline footer, the QR, the crossfade's length
+// and style, the loudness target, the speaker captions -- written through
+// /api/report/render (lib/report/manifest.mjs updateRender, the build's own
+// checks). Nothing here calls a model. A deck cut keeps its own settings
+// (the Media tab); a montage levels with render.montage.
+
+type Look = {
+ headerHeight?: number;
+ footerHeight?: number;
+ qr?: unknown;
+ transition?: number;
+ transitionStyle?: string;
+ loudness?: { target: number } | null;
+ captions?: { style: "speakers"; labels?: { host?: string | null; subject?: string | null } | null; size?: "m" | "l" } | null;
+};
+type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; errors: string[]; token: string | null };
+
+const STYLE_WORDS: Record<string, string> = { fade: "crossfade", fadeblack: "dip to black", fadewhite: "dip to white", dissolve: "dissolve", blurslide: "blur slide" };
+
+type Draft = {
+ header: boolean;
+ footer: boolean;
+ qr: boolean;
+ transition: string;
+ style: string;
+ loudness: "off" | "-16" | "custom";
+ target: string;
+ captions: boolean;
+ host: string;
+ subject: string;
+ size: "m" | "l";
+};
+
+function draftOf(l: Look): Draft {
+ const t = l.loudness?.target;
+ return {
+ header: l.headerHeight !== 0,
+ footer: l.footerHeight !== 0,
+ qr: l.qr !== false,
+ transition: String(l.transition ?? 0.5),
+ style: l.transitionStyle ?? "fade",
+ loudness: typeof t !== "number" ? "off" : t === -16 ? "-16" : "custom",
+ target: typeof t === "number" ? String(t) : "-16",
+ captions: !!l.captions,
+ host: l.captions?.labels?.host ?? "",
+ subject: l.captions?.labels?.subject ?? "",
+ size: l.captions?.size ?? "m",
+ };
+}
+
+/** The patch that takes the saved look to the draft: only what changed, `null` to remove a key. */
+function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
+ const p: Record<string, unknown> = {};
+ if (d.header !== (was.headerHeight !== 0)) p.headerHeight = d.header ? null : 0;
+ if (d.footer !== (was.footerHeight !== 0)) p.footerHeight = d.footer ? null : 0;
+ if (d.qr !== (was.qr !== false)) p.qr = d.qr;
+ const tr = Number(d.transition);
+ if (tr !== (was.transition ?? 0.5)) p.transition = tr;
+ if (d.style !== (was.transitionStyle ?? "fade")) p.transitionStyle = d.style === "fade" ? null : d.style;
+ if (!view.montage) {
+ const target = d.loudness === "off" ? null : d.loudness === "-16" ? -16 : Number(d.target);
+ if (target !== (was.loudness?.target ?? null)) p.loudness = target === null ? null : { target };
+ }
+ if (!view.montage && !view.deck) {
+ const labels = { ...(d.host.trim() ? { host: d.host.trim() } : {}), ...(d.subject.trim() ? { subject: d.subject.trim() } : {}) };
+ const next = d.captions ? { style: "speakers", ...(Object.keys(labels).length ? { labels } : {}), ...(d.size === "l" ? { size: "l" } : {}) } : null;
+ if (JSON.stringify(next) !== JSON.stringify(was.captions ?? null)) p.captions = next;
+ }
+ return p;
+}
+
+export default function LookPanel({ project }: { project: string }) {
+ const [view, setView] = useState<View | null>(null);
+ const [draft, setDraft] = useState<Draft | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [status, setStatus] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/render?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = (await r.json()) as View & { error?: string };
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
+ setView(j);
+ setDraft(draftOf(j.look));
+ }, [project]);
+ useEffect(() => {
+ load().catch((e) => setError(e instanceof Error ? e.message : String(e)));
+ }, [load]);
+
+ if (!view || !draft) {
+ return (
+ <Panel title="Look" data-look-panel="loading">
+ <p className="m-0 text-[12px] text-muted">{error ?? "reading the look…"}</p>
+ </Panel>
+ );
+ }
+ const set = (k: Partial<Draft>) => {
+ setDraft({ ...draft, ...k });
+ setStatus(null);
+ };
+ const patch = patchOf(view.look, draft, view);
+ const dirty = Object.keys(patch).length > 0;
+ const save = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await fetch("/api/report/render", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, token: view.token, patch }) });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[]; stale?: boolean; look?: Look; token?: string };
+ if (r.status === 409) {
+ await load();
+ setError("the manifest changed since this was read — reloaded; check and save again");
+ return;
+ }
+ if (!r.ok) {
+ setError((j.errors ?? [j.error ?? `HTTP ${r.status}`]).join("; "));
+ return;
+ }
+ setView({ ...view, look: j.look ?? {}, token: j.token ?? null, errors: [] });
+ setDraft(draftOf(j.look ?? {}));
+ setStatus("Saved — the next render uses it");
+ } finally {
+ setBusy(false);
+ }
+ };
+ const check = (k: keyof Draft, label: string, attr: string, disabled = false) => (
+ <label className="inline-flex items-center gap-1.5 text-[12.5px] text-text">
+ <input type="checkbox" {...{ [attr]: "" }} checked={draft[k] as boolean} disabled={disabled || busy} onChange={(e) => set({ [k]: e.target.checked } as Partial<Draft>)} />
+ {label}
+ </label>
+ );
+
+ return (
+ <Panel title="Look" data-look-panel="" data-look-dirty={dirty ? "" : undefined}>
+ {view.errors.length > 0 && (
+ <p role="alert" data-look-errors="" className="m-0 mb-2 text-[12px] text-reject-text">
+ {view.errors.join("; ")}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-2">
+ {check("header", "Header", "data-look-header")}
+ {check("footer", "Timeline footer", "data-look-footer")}
+ {check("qr", "QR code", "data-look-qr")}
+ </div>
+ <div className="mt-3 flex flex-wrap items-end gap-4">
+ <Field label="Between clips, s">
+ <Input data-look-transition="" type="number" min={0} max={3} step={0.1} value={draft.transition} disabled={busy} onChange={(e) => set({ transition: e.target.value })} className="w-[6em]" />
+ </Field>
+ <Field label="Join">
+ <Select data-look-style="" value={draft.style} disabled={busy || Number(draft.transition) === 0} onChange={(e) => set({ style: e.target.value })}>
+ {view.styles.map((s) => (
+ <option key={s} value={s}>
+ {STYLE_WORDS[s] ?? s}
+ </option>
+ ))}
+ </Select>
+ </Field>
+ {!view.montage && (
+ <Field label="Loudness">
+ <span className="flex items-center gap-1.5">
+ <Select data-look-loudness="" value={draft.loudness} disabled={busy} onChange={(e) => set({ loudness: e.target.value as Draft["loudness"] })}>
+ <option value="off">as recorded</option>
+ <option value="-16">−16 LUFS (even)</option>
+ <option value="custom">custom</option>
+ </Select>
+ {draft.loudness === "custom" && (
+ <Input data-look-target="" type="number" min={-30} max={-8} step={0.5} value={draft.target} disabled={busy} onChange={(e) => set({ target: e.target.value })} className="w-[5.5em]" aria-label="Loudness target, LUFS" />
+ )}
+ </span>
+ </Field>
+ )}
+ </div>
+ <div className="mt-3 space-y-2">
+ {view.deck || view.montage ? (
+ <p className="m-0 text-[12px] text-muted" data-look-captions-off="">
+ {view.deck ? "Captions: the deck draws its own words (Media tab)." : "Captions: not for a montage."}
+ </p>
+ ) : (
+ <>
+ {check("captions", "Speaker captions", "data-look-captions")}
+ {draft.captions && (
+ <div className="flex flex-wrap items-end gap-4 pl-5">
+ <Field label="Host's name" hint="blank: told apart by colour">
+ <Input data-look-label-host="" value={draft.host} maxLength={40} disabled={busy} onChange={(e) => set({ host: e.target.value })} className="w-[12em]" />
+ </Field>
+ <Field label="Subject's name">
+ <Input data-look-label-subject="" value={draft.subject} maxLength={40} disabled={busy} onChange={(e) => set({ subject: e.target.value })} className="w-[12em]" />
+ </Field>
+ <Field label="Size">
+ <Select data-look-size="" value={draft.size} disabled={busy} onChange={(e) => set({ size: e.target.value as Draft["size"] })}>
+ <option value="m">medium</option>
+ <option value="l">large</option>
+ </Select>
+ </Field>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-3">
+ <button type="button" data-look-save="" disabled={busy || !dirty} onClick={() => void save()} className={buttonVariants({ variant: dirty ? "go" : "outline", size: "md" })}>
+ Save the look
+ </button>
+ {dirty && (
+ <button type="button" disabled={busy} onClick={() => setDraft(draftOf(view.look))} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Undo changes
+ </button>
+ )}
+ <span aria-live="polite" className="text-[12px]">
+ {error ? (
+ <span role="alert" data-look-error="" className="text-reject-text">
+ {error}
+ </span>
+ ) : status ? (
+ <span data-look-status="" className="text-muted">
+ {status}
+ </span>
+ ) : null}
+ </span>
+ </div>
+ </Panel>
+ );
+}
diff --git a/umtool/components/projects/report/ShortsList.tsx b/umtool/components/projects/report/ShortsList.tsx
@@ -0,0 +1,126 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { Panel } from "@/components/ui/panel";
+import { fmtAgo, fmtBytes } from "@/lib/format";
+import { clipEditorHref } from "@/lib/hrefs";
+
+// THE SHORTS (release 36 lane C): `<project>/shorts/<clipId>.mp4`, each one
+// clip at 1080x1920 (the clip editor's Make a short). Play one here, download
+// it, or make it again (the old one is set aside, never overwritten).
+
+type Short = { clip: string; size: number; mtimeMs: number; stale: boolean; gone: boolean; record: { cut?: [number, number] | null; captions?: { lines: number } | null; loudness?: { target: number } | null } | null };
+type Job = { id: string; state: string; error: string | null; kind?: string };
+
+export default function ShortsList({ project }: { project: string }) {
+ const [shorts, setShorts] = useState<Short[] | null>(null);
+ const [job, setJob] = useState<Job | null>(null);
+ const [playing, setPlaying] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/shorts?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = (await r.json()) as { shorts?: Short[]; running?: Job | null; error?: string };
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
+ setShorts(j.shorts ?? []);
+ if (j.running) setJob(j.running);
+ }, [project]);
+ useEffect(() => {
+ load().catch((e) => setError(e instanceof Error ? e.message : String(e)));
+ }, [load]);
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/shorts?job=${job.id}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as Job;
+ setJob(j);
+ if (j.state !== "running") await load().catch(() => {});
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job, load]);
+
+ const remake = async (clip: string) => {
+ setError(null);
+ const r = await fetch("/api/report/shorts", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip, replace: true }) });
+ const j = (await r.json().catch(() => ({}))) as { job?: Job; error?: string };
+ if (!r.ok || !j.job) setError(j.error ?? `HTTP ${r.status}`);
+ else setJob(j.job);
+ };
+ const cancel = async () => {
+ if (!job) return;
+ await fetch(`/api/report/shorts?cancel=${job.id}`, { method: "POST" }).catch(() => null);
+ };
+ const file = (s: Short, extra = "") => `/api/report/shorts?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(s.clip)}&file=1&v=${s.mtimeMs}${extra}`;
+ const running = job?.state === "running";
+
+ return (
+ <Panel title={`Shorts${shorts?.length ? ` — ${shorts.length}` : ""}`} data-shorts={shorts?.length ?? 0}>
+ {shorts === null ? (
+ <p className="m-0 text-[12px] text-muted">{error ?? "reading the shorts…"}</p>
+ ) : shorts.length === 0 && !running ? (
+ <p className="m-0 text-[12px] text-muted" data-shorts-empty="">
+ No shorts yet: the clip editor makes one of a clip (Make a short).{" "}
+ <Link href={clipEditorHref(project)} prefetch={false} className="ink-link">
+ Clip editor
+ </Link>
+ </p>
+ ) : (
+ <ul className="m-0 list-none space-y-2 p-0">
+ {shorts.map((s) => (
+ <li key={s.clip} data-short={s.clip} data-short-stale={s.stale ? "" : undefined} className="space-y-1">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-[12px] text-text-2">
+ <span className="font-mono text-[12.5px] text-text">{s.clip}</span>
+ <span className="num">
+ {fmtBytes(s.size)} · {fmtAgo(s.mtimeMs)}
+ {s.record?.cut ? ` · ${(s.record.cut[1] - s.record.cut[0]).toFixed(1)} s` : ""}
+ </span>
+ {s.stale && <span className={badgeVariants({ variant: "open", size: "sm" })}>the clip moved since</span>}
+ {s.gone && <span className={badgeVariants({ variant: "info", size: "sm" })}>no such clip now</span>}
+ <span className="ml-auto flex flex-wrap gap-1.5">
+ <button type="button" data-short-play={s.clip} onClick={() => setPlaying(playing === s.clip ? null : s.clip)} className={buttonVariants({ variant: playing === s.clip ? "pressed" : "outline", size: "sm" })}>
+ {playing === s.clip ? "Close" : "Play"}
+ </button>
+ <a href={file(s, "&download=1")} data-short-download={s.clip} className={buttonVariants({ size: "sm" })}>
+ Download
+ </a>
+ {!s.gone && (
+ <button type="button" data-short-remake={s.clip} disabled={running} onClick={() => void remake(s.clip)} className={buttonVariants({ size: "sm" })}>
+ Make again
+ </button>
+ )}
+ {!s.gone && (
+ <Link href={clipEditorHref(project, { clip: s.clip })} prefetch={false} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Frame it
+ </Link>
+ )}
+ </span>
+ </div>
+ {playing === s.clip && (
+ <video data-short-player={s.clip} src={file(s)} controls playsInline autoPlay className="max-h-[70vh] w-auto max-w-full rounded-[3px] bg-black" style={{ aspectRatio: "9 / 16" }} />
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ {job && (
+ <p data-shorts-job={job.state} className="m-0 mt-2 flex flex-wrap items-center gap-2 text-[12px] text-text-2">
+ {running ? `Making ${job.kind?.split(" ").at(-1) ?? "a short"}…` : job.state === "done" ? "Made." : `Failed${job.error ? `: ${job.error}` : ""}`}
+ {running && (
+ <button type="button" onClick={() => void cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ )}
+ </p>
+ )}
+ {error && shorts !== null && (
+ <p role="alert" className="m-0 mt-1 text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+ </Panel>
+ );
+}
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -32,6 +32,9 @@ import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy
// version, Add a clip from the selection, Bring in a proposal
// the comments a note on the clip (notes.json, anchored to it), its thread
// and an agent's replies, resolve / reopen
+// the short (release 36) a 9:16 box dragged on the player (the clip's
+// `vertical.crop`), Make a short (a job: shorts/<clip>.mp4);
+// a speaker's name for the captions in the Speakers list
//
// Every write is one POST to /api/report/clip-editor; the answer is the whole
// view again, so the page never guesses what the server did. Edge edits are
@@ -84,6 +87,7 @@ export default function ClipEditor({
const [speakerPick, setSpeakerPick] = useState<number | null>(null);
const [rolesChanged, setRolesChanged] = useState(false);
const [busy, setBusy] = useState(false);
+ const [framing, setFraming] = useState(false);
const [error, setError] = useState<string | null>(null);
const [status, setStatus] = useState<string | null>(null);
const token = useRef<string | null>(initialView.token);
@@ -263,6 +267,12 @@ export default function ClipEditor({
if (j) setRolesChanged(true);
});
};
+ const setLabel = (speaker: number, label: string) => {
+ void write({ op: "label", speaker, label: label.trim() || null }, label.trim() ? `Speaker ${speaker} is “${label.trim()}” in the captions` : `Speaker ${speaker}'s name cleared`);
+ };
+ const setCrop = (crop: number[] | null, aspect?: number) => {
+ void write({ op: "vertical", clip: clip.id, crop, ...(crop && aspect ? { aspect: Math.round(aspect * 10000) / 10000 } : {}) }, crop ? "Saved the short's framing" : "The short is framed from the centre");
+ };
// Re-propose: the clip finder's proposal pass as a job (`umtool clips
// propose`, /api/report/clips); clips a person edited are never touched.
const [proposing, setProposing] = useState<{ id: string; state: string; error: string | null } | null>(null);
@@ -412,7 +422,7 @@ export default function ClipEditor({
</p>
)}
- <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} />
+ <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} frame={framing ? { crop: clip.vertical?.crop ?? null, onChange: setCrop, busy } : null} />
{/* ---- the strip --------------------------------------------------- */}
<div className="space-y-1">
@@ -651,6 +661,7 @@ export default function ClipEditor({
{typeof s.sameAs === "number" ? ` · same voice as ${s.sameAs}` : ""}
</span>
<span className="num font-mono text-[11px] text-muted">{typeof s.seconds === "number" ? `${Math.round(s.seconds)} s` : ""}</span>
+ <SpeakerLabel speaker={s} busy={busy} onSave={(v) => setLabel(s.index, v)} />
{s.role !== "host" && (
<button type="button" data-speaker-host={s.index} disabled={busy} onClick={() => setRole(s.index, "host")} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}>
This is the host
@@ -664,6 +675,7 @@ export default function ClipEditor({
{view.reactionsError && <p className="m-0 text-[12px] text-reject-text">{view.reactionsError}</p>}
{view.rulingsError && <p className="m-0 text-[12px] text-reject-text">{view.rulingsError}</p>}
+ <ShortMaker project={project} clipId={clip.id} short={view.shorts?.[clip.id] ?? null} framed={!!clip.vertical} framing={framing} onFraming={setFraming} onCentre={() => setCrop(null)} onMade={() => void reload().catch(() => {})} busy={busy} />
<RenderTake project={project} render={render} takes={takes} takesHref={takesHref} />
</aside>
</div>
@@ -676,11 +688,14 @@ export default function ClipEditor({
// ---------------------------------------------------------------------------
type PlayerHandle = { toggle: () => void; seek: (t: number) => void };
+/** The short's framing on the player: the clip's crop (null = the centre) and its writer. */
+type Frame = { crop: number[] | null; onChange: (crop: number[] | null, aspect?: number) => void; busy: boolean };
type Target = { channel: string; video: string; from: number; to: number; project: string; clip: string };
-const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void }>(function Player({ clipId, targets, cut, onTime, onPlaying }, ref) {
+const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void; frame?: Frame | null }>(function Player({ clipId, targets, cut, onTime, onPlaying, frame = null }, ref) {
const [found, setFound] = useState<{ play: CitedPlay; from: number } | null | undefined>(undefined);
+ const [dims, setDims] = useState<{ w: number; h: number } | null>(null);
const media = useRef<HTMLMediaElement | null>(null);
// The seek to the cut on load is the player's own, not a person's: it must
// not move the playhead somebody just set by clicking a word.
@@ -765,6 +780,8 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
onLoadedMetadata: (e: React.SyntheticEvent<HTMLMediaElement>) => {
ownSeek.current = true;
e.currentTarget.currentTime = fileT(cutRef.current.cutStart);
+ const v = e.currentTarget as HTMLVideoElement;
+ if (v.videoWidth > 0 && v.videoHeight > 0) setDims({ w: v.videoWidth, h: v.videoHeight });
},
onSeeked: (e: React.SyntheticEvent<HTMLMediaElement>) => {
if (ownSeek.current) ownSeek.current = false;
@@ -783,7 +800,19 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
};
return (
<div data-editor-player={found.play.kind} className="w-full max-w-[720px]">
- {found.play.audio ? <audio {...props} className="w-full" /> : <video {...props} playsInline className="aspect-video w-full rounded-[3px] bg-black" />}
+ {found.play.audio ? (
+ <audio {...props} className="w-full" />
+ ) : (
+ <div className="relative overflow-hidden rounded-[3px]">
+ <video {...props} playsInline className="aspect-video w-full rounded-[3px] bg-black" />
+ {frame && dims && <CropBox frame={frame} aspect={dims.w / dims.h} />}
+ </div>
+ )}
+ {frame && (found.play.audio || !dims) && (
+ <span data-crop-none="" className="micro block">
+ {found.play.audio ? "no picture here to frame: the short is cut from the centre" : "reading the picture…"}
+ </span>
+ )}
<span className="micro">{found.play.label}</span>
</div>
);
@@ -1177,3 +1206,203 @@ function RenderTake({ project, render, takes, takesHref }: { project: string; re
</section>
);
}
+
+// ---------------------------------------------------------------------------
+// The short (release 36): its 9:16 box on the player, its name for a voice,
+// and Make a short.
+// ---------------------------------------------------------------------------
+
+const VERTICAL = 9 / 16;
+const r4 = (n: number) => Math.round(n * 10000) / 10000;
+/** The centred, full-height 9:16 box on a source of aspect `a` (report-to-video/look.mjs defaultCrop). */
+function centreCrop(a: number): number[] {
+ let w = VERTICAL / a;
+ let h = 1;
+ if (w > 1) {
+ h = a / VERTICAL;
+ w = 1;
+ }
+ return [r4((1 - w) / 2), r4((1 - h) / 2), r4(w), r4(h)];
+}
+/** A box of height `h` (a fraction) about the centre (cx, cy), 9:16 on the source, inside the picture. */
+function boxAt(a: number, h: number, cx: number, cy: number): number[] {
+ let hh = Math.min(1, Math.max(0.2, h));
+ let w = (hh * VERTICAL) / a;
+ if (w > 1) {
+ w = 1;
+ hh = (w * a) / VERTICAL;
+ }
+ const x = Math.min(1 - w, Math.max(0, cx - w / 2));
+ const y = Math.min(1 - hh, Math.max(0, cy - hh / 2));
+ return [r4(x), r4(y), r4(w), r4(hh)];
+}
+
+/** The short's box over the picture: drag to move it, the slider sizes it; written when let go. */
+function CropBox({ frame, aspect }: { frame: Frame; aspect: number }) {
+ const [draft, setDraft] = useState<number[] | null>(null);
+ const crop = draft ?? frame.crop ?? centreCrop(aspect);
+ const area = useRef<HTMLDivElement | null>(null);
+ const drag = useRef<{ x0: number; y0: number; crop: number[]; w: number; h: number } | null>(null);
+ useEffect(() => setDraft(null), [frame.crop]);
+ // The picture inside the 16:9 player (object-fit: contain).
+ const P = 16 / 9;
+ const content = aspect >= P ? { left: 0, top: ((1 - P / aspect) / 2) * 100, width: 100, height: (P / aspect) * 100 } : { left: ((1 - aspect / P) / 2) * 100, top: 0, width: (aspect / P) * 100, height: 100 };
+ const [x, y, w, h] = crop;
+ const commit = (c: number[]) => frame.onChange(c, aspect);
+ return (
+ <>
+ <div ref={area} className="pointer-events-none absolute" style={{ left: `${content.left}%`, top: `${content.top}%`, width: `${content.width}%`, height: `${content.height}%` }}>
+ <div
+ data-crop-box={crop.join(",")}
+ role="slider"
+ aria-label="The short's framing: drag to move"
+ aria-valuenow={x}
+ tabIndex={0}
+ onPointerDown={(e) => {
+ if (e.button !== 0 || frame.busy) return;
+ e.stopPropagation();
+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ const r = area.current!.getBoundingClientRect();
+ drag.current = { x0: e.clientX, y0: e.clientY, crop, w: Math.max(1, r.width), h: Math.max(1, r.height) };
+ }}
+ onPointerMove={(e) => {
+ const d = drag.current;
+ if (!d) return;
+ const [dx, dy, dw, dh] = d.crop;
+ setDraft(boxAt(aspect, dh, dx + dw / 2 + (e.clientX - d.x0) / d.w, dy + dh / 2 + (e.clientY - d.y0) / d.h));
+ }}
+ onPointerUp={() => {
+ const moved = drag.current && draft;
+ drag.current = null;
+ if (moved && draft) commit(draft);
+ }}
+ className="pointer-events-auto absolute cursor-move border-2 border-signal shadow-[0_0_0_9999px_color-mix(in_srgb,black_55%,transparent)]"
+ style={{ left: `${x * 100}%`, top: `${y * 100}%`, width: `${w * 100}%`, height: `${h * 100}%` }}
+ />
+ </div>
+ <div className="absolute bottom-12 left-2 flex items-center gap-2 rounded-[3px] bg-[color-mix(in_srgb,black_70%,transparent)] px-2 py-1 text-[11.5px] text-white">
+ <label htmlFor="crop-size">Size</label>
+ <input
+ id="crop-size"
+ data-crop-size=""
+ type="range"
+ min={0.3}
+ max={1}
+ step={0.01}
+ value={h}
+ disabled={frame.busy}
+ onChange={(e) => setDraft(boxAt(aspect, Number(e.target.value), x + w / 2, y + h / 2))}
+ onPointerUp={() => draft && commit(draft)}
+ onKeyUp={() => draft && commit(draft)}
+ />
+ </div>
+ </>
+ );
+}
+
+/** A speaker's name in the captions: blank is the default (told apart by colour). */
+function SpeakerLabel({ speaker, busy, onSave }: { speaker: Speaker; busy: boolean; onSave: (v: string) => void }) {
+ const fallback = speaker.role === "host" ? "Host" : speaker.role === "subject" ? "Subject" : `Speaker ${speaker.index + 1}`;
+ const saved = speaker.label && speaker.label !== fallback ? speaker.label : "";
+ const [text, setText] = useState(saved);
+ useEffect(() => setText(saved), [saved]);
+ const commit = () => {
+ if (text.trim() !== saved) onSave(text);
+ };
+ return (
+ <input
+ data-speaker-label={speaker.index}
+ aria-label={`Speaker ${speaker.index}'s name in the captions`}
+ value={text}
+ maxLength={40}
+ disabled={busy}
+ placeholder="name"
+ onChange={(e) => setText(e.target.value)}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") (e.target as HTMLInputElement).blur();
+ if (e.key === "Escape") {
+ setText(saved);
+ (e.target as HTMLInputElement).blur();
+ }
+ }}
+ className="w-[7.5em] rounded border border-seam-2 bg-ground px-1.5 py-0.5 text-[11.5px] text-text outline-none focus:border-signal"
+ />
+ );
+}
+
+/** Make a short: the clip at 1080x1920 from its box, a job; the one there is set aside, never overwritten. */
+function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy }: {
+ project: string;
+ clipId: string;
+ short: { mtimeMs: number; size: number; stale: boolean } | null;
+ framed: boolean;
+ framing: boolean;
+ onFraming: (on: boolean) => void;
+ onCentre: () => void;
+ onMade: () => void;
+ busy: boolean;
+}) {
+ const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ useEffect(() => {
+ setJob(null);
+ setErr(null);
+ }, [clipId]);
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/shorts?job=${job.id}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as { id: string; state: string; error: string | null };
+ setJob({ id: j.id, state: j.state, error: j.error });
+ if (j.state !== "running") onMade();
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job, onMade]);
+ const make = async () => {
+ setErr(null);
+ const r = await fetch("/api/report/shorts", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip: clipId, replace: !!short }) });
+ const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string; error: string | null }; error?: string };
+ if (!r.ok || !j.job) setErr(j.error ?? `HTTP ${r.status}`);
+ else setJob({ id: j.job.id, state: j.job.state, error: j.job.error });
+ };
+ const running = job?.state === "running";
+ return (
+ <section data-short-maker={clipId} data-short-made={short ? "" : undefined} className="space-y-1.5">
+ <h2 className="micro m-0">Short</h2>
+ <p className="m-0 text-[12px] text-text-2">
+ {framed ? "Framed by you" : "Framed from the centre"}
+ {short ? ` · made ${new Date(short.mtimeMs).toLocaleString()}${short.stale ? " · the clip moved since" : ""}` : ""}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ <button type="button" data-frame-short="" aria-pressed={framing} onClick={() => onFraming(!framing)} className={buttonVariants({ variant: framing ? "pressed" : "outline", size: "sm" })}>
+ {framing ? "Done framing" : "Frame the short"}
+ </button>
+ {framed && (
+ <button type="button" data-crop-centre="" disabled={busy} onClick={onCentre} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Centre it
+ </button>
+ )}
+ <button type="button" data-make-short={clipId} disabled={running || busy} onClick={() => void make()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {running ? "Making the short…" : short ? "Make the short again" : "Make a short"}
+ </button>
+ {short && (
+ <a href={`/api/report/shorts?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clipId)}&file=1&v=${short.mtimeMs}`} target="_blank" rel="noreferrer" data-short-open={clipId} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Play it
+ </a>
+ )}
+ </div>
+ {job && (
+ <p data-short-job={job.state} className="m-0 text-[12px] text-text-2">
+ {running ? "Rendering 1080×1920 in the heavy slot" : job.state === "done" ? "Made — on the Deliver tab's Shorts list" : `Failed${job.error ? `: ${job.error}` : ""}`}
+ </p>
+ )}
+ {err && (
+ <p role="alert" className="m-0 text-[12px] text-reject-text">
+ {err}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -24,6 +24,7 @@ Inbox cannot disagree about what is wrong with one.
| `folders [--json]` · `kinds [--json]` | the tree, the registry |
| `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window |
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
+| `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) |
| `index [--rebuild] [--prune] [--since MS] [--json]` | the cache |
| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold |
| `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there |
@@ -96,10 +97,11 @@ front of a twenty-minute build, and it exits non-zero so a script can gate on it
## Two deliberate limits
-**`build` prints, it does not run.** Cancellation, per-step timeouts and the
-process-group kill live in the server's job runner; a second runner here would be
-a second, worse set of those. Use **run** on the piece's Build tab, or paste the
-printed commands.
+**`build` prints, it does not run it itself.** Cancellation, per-step timeouts and
+the process-group kill live in the server's job runner; a second runner here would
+be a second, worse set of those. `build --run` asks the running app's runner to do
+it and follows the job (Ctrl-C cancels it there); otherwise use **run** on the
+piece's Build tab, or paste the printed commands.
**`check` cannot compute the song reducer.** Nine decision kinds are TypeScript
beside `readSong()`, the loudness cache and the accepted cover set. It reports how
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1204,6 +1204,56 @@ back. The writers are `lib/report/manifest.mjs` (`updateClip`, `restoreClip`,
`splitClip`, `mergeClips`, `addClip`); the editor's operations are
`lib/report/clipEditor.mjs` behind `/api/report/clip-editor`.
+## The look: captions, loudness, shorts (release 36)
+
+Three render keys and one clip key, all opt-in (absent or `null` is off, and the
+render is byte for byte what it was), validated by the build and by the lint
+(`report-to-video/look.mjs` `validateLook`, like `render.transitionStyle`):
+
+| Key | Shape | What it does |
+|---|---|---|
+| `render.captions` | `{style: "speakers", labels?: {host?, subject?}, size?: "m" \| "l"}` | Burned-in captions, 2–6 words a line, broken on pauses (0.45 s) and never across a change of speaker. Who says a word comes from `reactions.json`'s turns and roles: the **host** amber `#FFC840` bottom left, the **subject** sky `#6FD3FF` bottom right, anyone else (or a word heard in no turn) paper `#F6F1E6` bottom centre — black outline, IBM Plex Sans (vendored in `report-to-video/fonts/`). A voice is named only when somebody names it: `labels[role]`, else a speaker's own label in `reactions.json` when it is not the default ("Host", "Subject", "Speaker N"); the name heads the first line of each turn. Words: the project's `words.json` (the recording `reactions.json` describes), else the corpus's whisper words (`transcript.json`), else the cues spread by character. One ASS file per segment (`segments/<id>.captions.ass`), burned with libass (`ass=`). Not beside the deck (`render.chrome`, whose `fx.kineticQuote` is its own captions) or a montage. |
+| `render.loudness` | `{target: -16}` (−30 to −8 LUFS) | Each clip's cut measured (ffmpeg `ebur128`) and brought to the target with one gain (±20 dB at most) and a lookahead limiter at −1 dBFS — montage.mjs's `loudnessGain` + `levelFilters`, at the clip's encode. A cut quieter than −40 LUFS is taken for silence and left as it is. The cut record says `loudness: {measured, gain, target}`. Not with a montage (it levels with `render.montage.loudness`). |
+| clip `vertical` | `{crop: [x, y, w, h], aspect?}` | Fractions of the source picture: the box a vertical short is cut from, 9:16 on the source (`aspect` = the source's width / height, 16/9 when absent; within 3 %). Absent: the centred full-height box. |
+
+A site-less, one-video cut made by the clip finder starts with
+`headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5,
+transitionStyle: "fadeblack", loudness: {target: -16}` (lane B's seed).
+
+**The Look panel** (the Build tab, `/api/report/render`) sets them by hand:
+**Header**, **Timeline footer**, **QR code**, the length **Between clips** (0 is
+a hard cut) and the **Join** (crossfade, dip to black, dip to white, dissolve),
+**Loudness** (as recorded, −16 LUFS, or a custom target) and **Speaker
+captions** with each role's name and the size. **Save the look** writes only
+what changed (`lib/report/manifest.mjs` `updateRender`: token-guarded, the
+build's own checks, atomic; `null` puts a key back to the build's default). It
+never touches `render.chrome` (the deck's own settings, the Media tab); a deck
+cut offers no captions, a montage neither captions nor loudness.
+
+**A speaker's name** is set in the clip editor's Speakers list (the box beside
+each speaker; blank is the default), written into `reactions.json` through the
+clip finder's `setSpeakerLabel` (common/lib/clips/reactions.mjs). A role change
+(This is the host) gives the default name back.
+
+**Shorts.** The clip editor's side column has **Short**: **Frame the short**
+draws the 9:16 box on the player — drag it, size it with the slider; it is
+written to the clip's `vertical` when let go (**Centre it** removes it) — and
+**Make a short** renders `<project>/shorts/<clipId>.mp4`: the clip alone at
+1080×1920, its box scaled to fill the frame, speaker captions at size "l" (the
+cut's names kept), no header, footer or QR, and the cut's loudness target (else
+−16). It is a job on umtool's runner (`/api/report/shorts`: one at a time, a
+log, Cancel), `build-video.mjs <manifest> --short <clipId>` inside the heavy
+slot; its work goes to `out/shorts-work/`, never the cut's segments. A short
+that is there is set aside as `shorts/<clipId>.<stamp>.mp4` before it is made
+again, never overwritten. A record beside each (`shorts/<clipId>.json`: the
+cut asked for and the one played, the crop, the size, the loudness, the
+captions, when) lets the **Shorts** list on the Deliver tab say when the clip
+moved since; there each short plays, downloads, is made again, or opens the
+clip in the editor to frame it.
+
+From a terminal: `node umtool/report-to-video/build-video.mjs
+<project>/video.manifest.json --short <clipId>`.
+
## Operator notes, timed notes and the generated-manifest guard
Notes on a project live in `<project>/notes.json` (shape and CLI:
diff --git a/umtool/e2e/clip-look.spec.ts b/umtool/e2e/clip-look.spec.ts
@@ -0,0 +1,114 @@
+import { test, expect } from "@playwright/test";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The look of a highlights cut (release 36 lane C). The Build tab's Look
+// panel saves the header, the QR, the join, the loudness and the speaker
+// captions into the manifest (and reads them back); the clip editor's
+// Speakers list names a voice for the captions (reactions.json); Frame the
+// short drags a 9:16 box on the player (the clip's vertical.crop); Make a
+// short runs the job (build-video --short) and the Deliver tab's Shorts list
+// shows it and plays it. Fixture: e2e/fixtures/clip-editor-fixture.mjs, as
+// reports/clip-look-fixture.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/clip-look-fixture";
+const DIR = path.join(FIXTURE, "reports", "clip-look-fixture");
+const json = (name: string) => {
+ try {
+ return JSON.parse(readFileSync(path.join(DIR, name), "utf8"));
+ } catch {
+ return null;
+ }
+};
+const render = () => json("video.manifest.json")?.render ?? {};
+const clip = (id: string) => (json("video.manifest.json")?.timeline ?? []).find((e: { id: string }) => e.id === id) ?? null;
+
+test("the look: the panel saves and reads back; a voice named; a short framed, made and listed", async ({ page }) => {
+ test.setTimeout(240_000);
+ await page.setViewportSize({ width: 1366, height: 900 });
+
+ // ---- the Look panel --------------------------------------------------------
+ await page.goto(urls.section(PROJECT, "build"));
+ const panel = page.locator("[data-look-panel]");
+ await expect(panel).toHaveAttribute("data-look-panel", "");
+ await expect(page.locator("[data-look-header]")).toBeChecked();
+ await expect(page.locator("[data-look-save]")).toBeDisabled();
+ await page.locator("[data-look-header]").uncheck();
+ await page.locator("[data-look-qr]").uncheck();
+ await page.locator("[data-look-transition]").fill("0.5");
+ await page.locator("[data-look-style]").selectOption("fadeblack");
+ await page.locator("[data-look-loudness]").selectOption("-16");
+ await page.locator("[data-look-captions]").check();
+ await page.locator("[data-look-label-host]").fill("The host");
+ await page.locator("[data-look-size]").selectOption("l");
+ await page.locator("[data-look-save]").click();
+ await expect(page.locator("[data-look-status]")).toHaveText("Saved — the next render uses it");
+ const r = render();
+ expect(r.headerHeight).toBe(0);
+ expect(r.qr).toBe(false);
+ expect(r.transition).toBe(0.5);
+ expect(r.transitionStyle).toBe("fadeblack");
+ expect(r.loudness).toEqual({ target: -16 });
+ expect(r.captions).toEqual({ style: "speakers", labels: { host: "The host" }, size: "l" });
+ expect(r.width).toBe(640);
+ // Read back after a reload.
+ await page.reload();
+ await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", "");
+ await expect(page.locator("[data-look-header]")).not.toBeChecked();
+ await expect(page.locator("[data-look-qr]")).not.toBeChecked();
+ await expect(page.locator("[data-look-style]")).toHaveValue("fadeblack");
+ await expect(page.locator("[data-look-loudness]")).toHaveValue("-16");
+ await expect(page.locator("[data-look-captions]")).toBeChecked();
+ await expect(page.locator("[data-look-label-host]")).toHaveValue("The host");
+
+ // ---- the clip editor: a voice named, the short framed --------------------
+ await page.goto(urls.clipEditorHref(PROJECT, { clip: "r001" }));
+ await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r001");
+ const subject = page.locator('[data-speaker-label="1"]');
+ await subject.fill("The narrator");
+ await subject.press("Enter");
+ await expect.poll(() => json("reactions.json")?.speakers?.find((s: { index: number }) => s.index === 1)?.label).toBe("The narrator");
+
+ await expect(page.locator("[data-editor-player]")).toHaveAttribute("data-editor-player", /^(?!looking|none)/, { timeout: 20_000 });
+ await page.locator("[data-frame-short]").click();
+ const box = page.locator("[data-crop-box]");
+ await expect(box).toBeVisible();
+ const at = await box.boundingBox();
+ if (!at) throw new Error("no crop box");
+ await page.mouse.move(at.x + at.width / 2, at.y + at.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(at.x + at.width / 2 + 120, at.y + at.height / 2, { steps: 6 });
+ await page.mouse.up();
+ await expect.poll(() => clip("r001")?.vertical?.crop?.[0] ?? null).toBeGreaterThan(0.36);
+ const crop = clip("r001").vertical.crop as number[];
+ expect(crop[3]).toBe(1);
+ expect(Math.abs((crop[2] * (640 / 360)) / crop[3] - 9 / 16)).toBeLessThan(0.01);
+ await expect(page.locator("[data-short-maker]")).toContainText("Framed by you");
+
+ // ---- Make a short: the job, then the file --------------------------------
+ await page.locator('[data-make-short="r001"]').click();
+ await expect(page.locator("[data-short-job]")).toHaveAttribute("data-short-job", "done", { timeout: 180_000 });
+ expect(existsSync(path.join(DIR, "shorts", "r001.mp4"))).toBe(true);
+ const rec = json("shorts/r001.json");
+ expect(rec.width).toBe(1080);
+ expect(rec.height).toBe(1920);
+ expect(rec.crop).toEqual(crop);
+ await expect(page.locator('[data-make-short="r001"]')).toHaveText("Make the short again");
+
+ // ---- the Shorts list on the Deliver tab ----------------------------------
+ await page.goto(urls.section(PROJECT, "deliver"));
+ const row = page.locator('[data-short="r001"]');
+ await expect(row).toBeVisible();
+ await expect(page.locator("[data-shorts]")).toHaveAttribute("data-shorts", "1");
+ await row.locator('[data-short-play="r001"]').click();
+ const player = page.locator('[data-short-player="r001"]');
+ await expect(player).toBeVisible();
+ await expect.poll(() => player.evaluate((v: HTMLVideoElement) => v.videoHeight)).toBe(1920);
+ await expect(row.locator('[data-short-download="r001"]')).toHaveAttribute("href", /download=1/);
+});
diff --git a/umtool/e2e/fixtures/clip-editor-fixture.mjs b/umtool/e2e/fixtures/clip-editor-fixture.mjs
@@ -20,13 +20,16 @@ const write = (dir, name, doc) => {
};
/**
- * @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o
+ * `name`: another copy under another name (release 36: clip-look.spec.ts's
+ * clip-look-fixture), so two specs never edit one project.
+ *
+ * @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]>, name?: string, title?: string }} o
*/
-export function makeClipEditorFixture({ reports, manifest, cachedWindow, cues }) {
- const dir = path.join(reports, "clip-editor-fixture");
+export function makeClipEditorFixture({ reports, manifest, cachedWindow, cues, name = "clip-editor-fixture", title = "The Clip Editor Fixture" }) {
+ const dir = path.join(reports, name);
const assist = (p, s, e, cs, ce, score, why) => ({ by: "assistant", proposal: p, score, why, original: { start: s, end: e, cutStart: cs, cutEnd: ce }, edits: [] });
const clip = (id, s, e, cs, ce, p, score, why, quote) => ({ type: "clip", id, video: "vid1", start: s, end: e, cutStart: cs, cutEnd: ce, quote, assist: assist(p, s, e, cs, ce, score, why) });
- const doc = manifest("clip-editor-fixture", "The Clip Editor Fixture", { siteOrigin: "https://archive.example" }, [
+ const doc = manifest(name, title, { siteOrigin: "https://archive.example" }, [
clip("r001", 0.5, 3.5, 1, 3, "p001", 0.8, "host laughs at the line", "This is a complete sentence."),
clip("r002", 4, 6, 4, 6, "p002", 0.7, "a comment", "And this one runs on"),
clip("r003", 6.5, 8.5, 6.5, 8.5, "p003", 0.6, "a short comment", "of that it finishes here."),
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -1811,6 +1811,8 @@ makeClipDeckFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out",
makeMontageOpsFixture({ reports, channels: CHANNELS, manifest });
// Release 35 C2: the clip editor, an assistant's clips adjusted by hand (clip-editor.spec.ts).
makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// Release 36 lane C: the Look panel, a short's framing and Make a short (clip-look.spec.ts).
+makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "clip-look-fixture", title: "The Clip Look Fixture" });
// P4b: the bench shell's own clips, and the Media tab's fields with their draft files.
makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
diff --git a/umtool/lib/report/buildRun.mjs b/umtool/lib/report/buildRun.mjs
@@ -0,0 +1,63 @@
+// `umtool build <project> --run` (release 36 lane C): the build chain as the
+// project page runs it -- a job on the running umtool app's runner (POST
+// /api/report/build), followed from the terminal (its log, polled), cancelled
+// on Ctrl-C (POST ?cancel=<job>). The app owns the steps, the timeouts, the
+// process-group kill and the heavy slot; this only asks and watches. Without
+// `--run` the command prints the chain, as before.
+//
+// Plain ESM: the CLI runs under bare node.
+
+/** Where the app answers: `--url`, else UMTOOL_URL, else the local default. */
+export const umtoolBase = (url, env = process.env) => String(url || env.UMTOOL_URL || "http://localhost:3050").replace(/\/+$/, "");
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Start the build and follow it to the end.
+ *
+ * @param {{ base: string, project: string, preset?: string, only?: string | null, skipFetch?: boolean,
+ * replace?: boolean, token?: string | null, pollMs?: number, fetchImpl?: typeof fetch,
+ * log?: (line: string) => void, onJob?: (cancel: () => Promise<boolean>) => void }} o
+ * @returns {Promise<{ state: string, job: string | null, error: string | null, needsReplace?: boolean }>}
+ */
+export async function runBuildOverHttp({
+ base, project, preset = "fast", only = null, skipFetch = false, replace = false, token = null,
+ pollMs = 1500, fetchImpl = fetch, log = (l) => console.log(l), onJob = () => {},
+}) {
+ const headers = { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) };
+ const call = async (method, route, body) => {
+ try {
+ const res = await fetchImpl(`${base}${route}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
+ return { status: res.status, json: await res.json().catch(() => ({})) };
+ } catch (err) {
+ return { status: 0, json: { error: `umtool at ${base} did not answer: ${err?.message ?? err}` } };
+ }
+ };
+ const started = await call("POST", `/api/report/build${replace ? "?replace=1" : ""}`, { project, preset, ...(only ? { only } : {}), ...(skipFetch ? { skipFetch: true } : {}) });
+ if (started.status !== 200 || !started.json?.job?.id) {
+ const j = started.json ?? {};
+ return { state: "refused", job: null, error: String(j.error ?? `HTTP ${started.status}`), ...(j.needsReplace ? { needsReplace: true } : {}) };
+ }
+ const id = started.json.job.id;
+ log(`job ${id}: ${started.json.job.kind ?? "build"}`);
+ for (const s of started.json.steps ?? []) log(` step: ${s.label}`);
+ onJob(async () => (await call("POST", `/api/report/build?cancel=${encodeURIComponent(id)}`)).json?.cancelled === true);
+ let since = 0;
+ let sinceEvent = 0;
+ let misses = 0;
+ for (;;) {
+ const r = await call("GET", `/api/report/build?job=${encodeURIComponent(id)}&since=${since}&sinceEvent=${sinceEvent}`);
+ if (r.status !== 200) {
+ misses += 1;
+ if (misses >= 40) return { state: "lost", job: id, error: String(r.json?.error ?? `HTTP ${r.status}`) };
+ await sleep(pollMs);
+ continue;
+ }
+ misses = 0;
+ for (const line of r.json.log ?? []) log(line);
+ since = Number.isFinite(r.json.next) ? r.json.next : since + (r.json.log?.length ?? 0);
+ if (Number.isFinite(r.json.nextEvent)) sinceEvent = r.json.nextEvent;
+ if (r.json.state !== "running") return { state: r.json.state, job: id, error: r.json.error ?? null };
+ await sleep(pollMs);
+ }
+}
diff --git a/umtool/lib/report/buildRun.test.mjs b/umtool/lib/report/buildRun.test.mjs
@@ -0,0 +1,86 @@
+// `umtool build --run` (release 36 lane C): the build route as the CLI asks
+// it -- started, followed (the log as it grows), cancelled, refused -- against
+// a fake app on a local port. Synthetic.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import http from "node:http";
+import test from "node:test";
+
+import { runBuildOverHttp, umtoolBase } from "./buildRun.mjs";
+
+/** A fake umtool: the build route's POST, GET ?job= and ?cancel=. */
+async function fakeApp(handler) {
+ const seen = [];
+ const server = http.createServer(async (req, res) => {
+ let body = "";
+ for await (const c of req) body += c;
+ const url = new URL(req.url, "http://x");
+ seen.push({ method: req.method, path: url.pathname, query: Object.fromEntries(url.searchParams), body: body ? JSON.parse(body) : null, auth: req.headers.authorization ?? null });
+ const [status, json] = handler(seen.at(-1), seen);
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(json));
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ return { base, seen, close: () => new Promise((r) => server.close(r)) };
+}
+
+test("umtoolBase: --url, else UMTOOL_URL, else the local default; no trailing slash", () => {
+ assert.equal(umtoolBase("http://h:1/", {}), "http://h:1");
+ assert.equal(umtoolBase(undefined, { UMTOOL_URL: "http://u:2//" }), "http://u:2");
+ assert.equal(umtoolBase(undefined, {}), "http://localhost:3050");
+});
+
+test("runBuildOverHttp: starts the job, prints its log as it grows, ends with its state", async () => {
+ let polls = 0;
+ const app = await fakeApp((r) => {
+ if (r.method === "POST" && !r.query.cancel) return [200, { ok: true, job: { id: "j1", kind: "build reports/x (fast)" }, steps: [{ label: "check" }, { label: "build" }] }];
+ if (r.method === "GET") {
+ polls += 1;
+ const log = ["line 1", "line 2", "line 3"];
+ const since = Number(r.query.since);
+ return polls < 3
+ ? [200, { state: "running", log: log.slice(since, polls), next: polls, nextEvent: polls * 2, error: null }]
+ : [200, { state: "done", log: log.slice(since), next: 3, nextEvent: 6, error: null }];
+ }
+ return [404, {}];
+ });
+ try {
+ const lines = [];
+ const r = await runBuildOverHttp({ base: app.base, project: "reports/x", preset: "final", only: null, token: "tok", pollMs: 5, log: (l) => lines.push(l) });
+ assert.deepEqual(r, { state: "done", job: "j1", error: null });
+ assert.deepEqual(lines, ["job j1: build reports/x (fast)", " step: check", " step: build", "line 1", "line 2", "line 3"]);
+ assert.deepEqual(app.seen[0].body, { project: "reports/x", preset: "final" });
+ assert.equal(app.seen[0].auth, "Bearer tok");
+ // Each poll asks only for what it has not seen.
+ assert.deepEqual(app.seen.slice(1).map((s) => [s.query.since, s.query.sinceEvent]), [["0", "0"], ["1", "2"], ["2", "4"]]);
+ } finally {
+ await app.close();
+ }
+});
+
+test("runBuildOverHttp: a newer deliverable is refused until --replace; a running job is named; Ctrl-C cancels", async () => {
+ const app = await fakeApp((r) => {
+ if (r.method === "POST" && r.query.cancel) return [200, { cancelled: true }];
+ if (r.method === "POST" && r.query.replace !== "1") return [409, { error: "x.mp4 is newer than the manifest", needsReplace: true }];
+ if (r.method === "POST") return [200, { ok: true, job: { id: "j2", kind: "build" } }];
+ return [200, { state: "failed", log: ["** cancel requested"], next: 1, error: "cancelled" }];
+ });
+ try {
+ const refused = await runBuildOverHttp({ base: app.base, project: "reports/x", log: () => {} });
+ assert.deepEqual(refused, { state: "refused", job: null, error: "x.mp4 is newer than the manifest", needsReplace: true });
+ let cancel = null;
+ const r = await runBuildOverHttp({ base: app.base, project: "reports/x", replace: true, skipFetch: true, only: "c1", pollMs: 5, log: () => {}, onJob: (c) => (cancel = c) });
+ assert.equal(r.state, "failed");
+ assert.equal(r.error, "cancelled");
+ assert.deepEqual(app.seen[1].body, { project: "reports/x", preset: "fast", only: "c1", skipFetch: true });
+ assert.equal(await cancel(), true);
+ assert.equal(app.seen.at(-1).query.cancel, "j2");
+ } finally {
+ await app.close();
+ }
+ const gone = await runBuildOverHttp({ base: "http://127.0.0.1:9", project: "p", log: () => {} });
+ assert.equal(gone.state, "refused");
+ assert.match(gone.error, /did not answer/);
+});
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -38,7 +38,8 @@ import {
updateClip,
} from "./manifest.mjs";
import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs";
-import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs";
+import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs";
+import { readShorts } from "./shorts.mjs";
import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs";
import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
@@ -83,7 +84,8 @@ export async function readWords(dir, reactions = null) {
/**
* @typedef {{ id: string, channel: string | null, video: string, start: number, end: number,
* cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null,
- * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean }} EditorClip
+ * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean,
+ * vertical: { crop: number[], aspect?: number } | null }} EditorClip
*/
/** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */
@@ -110,8 +112,11 @@ export async function clipEditorView(project) {
key,
ruling: key ? (rulings.doc.rulings[key]?.verdict ?? null) : null,
montage: isObj(e.montage),
+ // A short's framing (release 36): fractions of the source picture.
+ vertical: isObj(e.vertical) && Array.isArray(e.vertical.crop) ? { crop: e.vertical.crop, ...(fin(e.vertical.aspect) ? { aspect: e.vertical.aspect } : {}) } : null,
};
});
+ const shorts = await readShorts(project.dir, manifest);
const doc = reactions.doc;
return {
clips,
@@ -130,6 +135,7 @@ export async function clipEditorView(project) {
}
: null,
repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE },
+ shorts: Object.fromEntries(shorts.filter((x) => !x.gone).map((x) => [x.clip, { mtimeMs: x.mtimeMs, size: x.size, stale: x.stale }])),
};
}
@@ -229,6 +235,8 @@ const num = (v, what) => {
* bring-in { proposal } one of the clip finder's unused proposals
* ruling { clip, verdict: "keep" | "cut" | null }
* role { speaker, role | null } reactions.json, through the clip finder's writer
+ * label { speaker, label | null } a speaker's name for the captions (reactions.json)
+ * vertical { clip, crop | null, aspect? } the clip's 9:16 box for its short
* with `token` (the manifest's, from the view) on every manifest edit.
* Returns `{ op, result, carried, view }`.
*/
@@ -338,8 +346,25 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
structural = false;
break;
}
+ case "label": {
+ const index = Number(body.speaker);
+ if (!Number.isInteger(index) || index < 0) throw new OpError("speaker is a speaker's index");
+ if (body.label !== null && typeof body.label !== "string") throw new OpError("label is a text, or null for the default");
+ const doc = await setSpeakerLabel(dir, index, body.label);
+ result = { speaker: doc.speakers.find((x) => x?.index === index) ?? null };
+ structural = false;
+ break;
+ }
+ case "vertical": {
+ const e = needClip();
+ const v = body.crop === null ? null : { crop: body.crop, ...(body.aspect !== undefined ? { aspect: Number(body.aspect) } : {}) };
+ // A "trim" that leaves the cut where it is: the clip's assist is not touched.
+ result = await updateClip(dir, e.id, { vertical: v }, { token, edit: "trim", now });
+ structural = false;
+ break;
+ }
default:
- throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling or role");
+ throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label or vertical");
}
let carried = null;
if (structural) {
diff --git a/umtool/lib/report/clipEditorBridge.mjs b/umtool/lib/report/clipEditorBridge.mjs
@@ -48,6 +48,13 @@ export async function readReactions(dir) {
*/
export { setSpeakerRole } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+/**
+ * A person's name for one speaker (release 36): THE CLIP FINDER'S FILE, the
+ * one other write the editor makes into it -- what the speaker captions head
+ * that voice's lines with. Empty gives the default back.
+ */
+export { setSpeakerLabel } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+
/** Re-propose is the clip finder's proposal pass: POST /api/report/clips {project, mode: "propose"} (`umtool clips propose`, a job). */
export const reproposeAvailable = true;
export const REPROPOSE_UNAVAILABLE = null;
diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts
@@ -25,6 +25,8 @@ export type EditorClip = {
key: string | null;
ruling: string | null;
montage: boolean;
+ /** A short's framing (release 36): `crop` = [x, y, w, h], fractions of the source picture. */
+ vertical: { crop: number[]; aspect?: number } | null;
};
export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator"; sameAs?: number };
@@ -45,6 +47,8 @@ export type EditorView = {
rolesChangedAt: string | null;
} | null;
repropose: { available: boolean; why: string | null };
+ /** The shorts on disk, by clip id (release 36). */
+ shorts: Record<string, { mtimeMs: number; size: number; stale: boolean }>;
};
export type Turn = { start: number; end: number; speaker: number };
diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs
@@ -0,0 +1,187 @@
+// The look in umtool (release 36 lane C): updateRender (the Look panel's
+// writer), a clip's `vertical` through updateClip and the clip editor's
+// `vertical` / `label` operations, and the shorts on disk (readShorts, the
+// replace guard, the job's step). Synthetic.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { LOOK_KEYS, MANIFEST_NAME, RenderRefused, StaleToken, lookOf, manifestToken, updateClip, updateRender } from "./manifest.mjs";
+import { clipEditorView, runClipEditorOp } from "./clipEditor.mjs";
+import { readShorts, safeClipId, setShortAside, shortFile, shortSteps } from "./shorts.mjs";
+
+const manifest = (render = {}) => ({
+ schemaVersion: 1,
+ slug: "look",
+ provenance: { channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000" }, ...render },
+ timeline: [
+ { type: "clip", id: "r001", video: "v1", start: 10, end: 20, cutStart: 11, cutEnd: 19, quote: "q", assist: { by: "assistant", proposal: "p001", original: { start: 10, end: 20, cutStart: 11, cutEnd: 19 }, edits: [] } },
+ { type: "clip", id: "r002", video: "v1", start: 30, end: 40 },
+ ],
+});
+const REACTIONS = {
+ version: 1,
+ source: { channel: "chan", video: "v1", duration: 80, words: null },
+ params: {},
+ speakers: [
+ { index: 0, role: "host", label: "Host", how: "auto" },
+ { index: 1, role: "subject", label: "Subject", how: "auto" },
+ ],
+ turns: [], laughs: [], moments: [], proposals: [],
+};
+
+async function project(render = {}) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-look-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(render), null, 2) + "\n");
+ await writeFile(path.join(dir, "reactions.json"), JSON.stringify(REACTIONS, null, 1) + "\n");
+ return { id: "reports/look", dir, kind: "report" };
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+
+test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => {
+ const p = await project({ transition: 0.4, crf: 21 });
+ try {
+ assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions"]);
+ const token = await manifestToken(p.dir);
+ const r = await updateRender(p.dir, {
+ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack",
+ loudness: { target: -16 }, captions: { style: "speakers", labels: { host: "Nik" } },
+ }, { token });
+ assert.deepEqual(r.look, {
+ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack",
+ loudness: { target: -16 }, captions: { style: "speakers", labels: { host: "Nik" } },
+ });
+ const m = await read(p.dir);
+ assert.equal(m.render.crf, 21, "the rest of the render is as it was");
+ assert.equal(m.render.width, 1920);
+ assert.deepEqual(lookOf(m.render), r.look);
+ // A stale token is refused; nothing written.
+ await assert.rejects(updateRender(p.dir, { qr: true }, { token }), StaleToken);
+ // null removes; qr: true turns the code back on (removes the false).
+ const r2 = await updateRender(p.dir, { headerHeight: null, qr: true, loudness: null, transitionStyle: null });
+ assert.equal("headerHeight" in r2.look, false);
+ assert.equal("qr" in r2.look, false);
+ assert.equal("loudness" in r2.look, false);
+ assert.equal("transitionStyle" in r2.look, false);
+ // Refusals: the build's own sentences, and nothing written.
+ const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8");
+ await assert.rejects(updateRender(p.dir, { chrome: { engine: "hyperframes" } }), (e) => e instanceof RenderRefused && /render\.chrome is the deck's/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { crf: 18 }), (e) => e instanceof RenderRefused && /render\.crf is not a look setting/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { loudness: { target: -40 } }), (e) => e instanceof RenderRefused && /target must be a number from -30 to -8/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { captions: { style: "karaoke" } }), (e) => e instanceof RenderRefused && /captions\.style/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { transitionStyle: "spin" }), (e) => e instanceof RenderRefused);
+ await assert.rejects(updateRender(p.dir, { headerHeight: 12.5 }), (e) => e instanceof RenderRefused && /whole number of pixels/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { transition: 9 }), (e) => e instanceof RenderRefused && /from 0 \(a hard cut\) to 3/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { qr: "yes" }), (e) => e instanceof RenderRefused);
+ assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("updateRender: captions beside the deck are refused (the deck draws its own words)", async () => {
+ const p = await project({ chrome: { engine: "hyperframes", layout: "deck" } });
+ try {
+ await assert.rejects(updateRender(p.dir, { captions: { style: "speakers" } }), (e) => e instanceof RenderRefused && /does not combine with render\.chrome/.test(e.errors.join(" ")));
+ // Loudness is fine under a deck.
+ const r = await updateRender(p.dir, { loudness: { target: -14 } });
+ assert.deepEqual(r.look.loudness, { target: -14 });
+ assert.deepEqual((await read(p.dir)).render.chrome, { engine: "hyperframes", layout: "deck" }, "never touches render.chrome");
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("updateClip: a clip's vertical crop, checked, rounded, removable; the assistant's clip stays the assistant's", async () => {
+ const p = await project();
+ try {
+ await updateClip(p.dir, "r001", { vertical: { crop: [0.123456, 0, 0.316406, 1], aspect: 16 / 9 } });
+ let e = (await read(p.dir)).timeline[0];
+ assert.deepEqual(e.vertical, { crop: [0.1235, 0, 0.3164, 1], aspect: 1.7778 });
+ assert.equal(e.assist.by, "assistant");
+ assert.deepEqual(e.assist.edits, []);
+ await assert.rejects(updateClip(p.dir, "r001", { vertical: { crop: [0, 0, 0.6, 1] } }), /must be 9:16 on the source/);
+ await assert.rejects(updateClip(p.dir, "r001", { vertical: { crop: [0.9, 0, 0.3164, 1] } }), /inside the picture/);
+ await updateClip(p.dir, "r001", { vertical: null });
+ e = (await read(p.dir)).timeline[0];
+ assert.equal(e.vertical, undefined);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("the clip editor: vertical and label operations; the view carries the crop and the shorts", async () => {
+ const p = await project();
+ try {
+ let view = await clipEditorView(p);
+ assert.equal(view.clips[0].vertical, null);
+ assert.deepEqual(view.shorts, {});
+ const r = await runClipEditorOp(p, { op: "vertical", clip: "r001", crop: [0.5, 0, 0.3164, 1], aspect: 1.7778, token: view.token });
+ assert.deepEqual(r.view.clips[0].vertical, { crop: [0.5, 0, 0.3164, 1], aspect: 1.7778 });
+ const r2 = await runClipEditorOp(p, { op: "vertical", clip: "r001", crop: null, token: r.view.token });
+ assert.equal(r2.view.clips[0].vertical, null);
+ // A speaker's name: the captions' label.
+ const l = await runClipEditorOp(p, { op: "label", speaker: 0, label: " Nik " });
+ assert.equal(l.result.speaker.label, "Nik");
+ assert.equal(l.result.speaker.role, "host");
+ const doc = JSON.parse(await readFile(path.join(p.dir, "reactions.json"), "utf8"));
+ assert.equal(doc.speakers[0].label, "Nik");
+ assert.equal(doc.speakers[1].label, "Subject", "only that speaker");
+ // Empty: the default again.
+ const back = await runClipEditorOp(p, { op: "label", speaker: 0, label: null });
+ assert.equal(back.result.speaker.label, "Host");
+ await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 0, label: "x".repeat(41) }), /up to 40 characters/);
+ await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 9, label: "x" }), /no speaker 9/);
+ await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 0, label: 3 }), /label is a text/);
+ // A short on disk shows in the view; stale once the clip moves.
+ await mkdir(path.join(p.dir, "shorts"), { recursive: true });
+ await writeFile(path.join(p.dir, "shorts", "r001.mp4"), "mp4");
+ await writeFile(path.join(p.dir, "shorts", "r001.json"), JSON.stringify({ version: 1, clip: "r001", requested: { cutStart: 11, cutEnd: 19 }, crop: null }));
+ view = await clipEditorView(p);
+ assert.equal(view.shorts.r001.stale, false);
+ await updateClip(p.dir, "r001", { cutStart: 12 });
+ view = await clipEditorView(p);
+ assert.equal(view.shorts.r001.stale, true);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("shorts: listed newest first, a set-aside one kept and not listed, the replace guard, the job's one step", async () => {
+ const p = await project();
+ try {
+ assert.deepEqual(await readShorts(p.dir), []);
+ await mkdir(path.join(p.dir, "shorts"), { recursive: true });
+ await writeFile(path.join(p.dir, "shorts", "r002.mp4"), "two");
+ await writeFile(path.join(p.dir, "shorts", "gone1.mp4"), "old");
+ await writeFile(path.join(p.dir, "shorts", "r002.20260101-1200.mp4"), "aside");
+ const m = await read(p.dir);
+ const list = await readShorts(p.dir, m);
+ assert.deepEqual(list.map((x) => x.clip).sort(), ["gone1", "r002"]);
+ assert.equal(list.find((x) => x.clip === "gone1").gone, true);
+ assert.equal(list.find((x) => x.clip === "r002").gone, false);
+ // The guard: there is one, so it is refused unless replace.
+ await assert.rejects(setShortAside(p.dir, "r002"), (e) => e.needsReplace === true);
+ const aside = await setShortAside(p.dir, "r002", { replace: true, now: new Date(2026, 9, 19, 9, 5) });
+ assert.equal(path.basename(aside), "r002.20261019-0905.mp4");
+ assert.equal(await stat(path.join(p.dir, "shorts", "r002.mp4")).catch(() => null), null);
+ assert.equal(await setShortAside(p.dir, "r001"), null, "nothing there: nothing to set aside");
+ // Names only.
+ assert.equal(shortFile(p.dir, "../x"), null);
+ assert.equal(safeClipId("r001-2"), true);
+ assert.equal(safeClipId("a/b"), false);
+ const [step] = shortSteps(p, "r001");
+ assert.deepEqual(step.argv.slice(-4), ["--short", "r001", "--progress", "ndjson"]);
+ assert.ok(step.argv[1].endsWith(path.join("report-to-video", "build-video.mjs")));
+ assert.equal(step.argv[2], path.join(p.dir, "video.manifest.json"));
+ assert.equal(step.ndjson, true);
+ assert.throws(() => shortSteps(p, "../etc"), /not a clip id/);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -33,6 +33,8 @@ import { isCalendarDate } from "umtool-report-to-video/attribution";
import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, validateTeasers } from "umtool-report-to-video/deck";
import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { validateLook, verticalErrors } from "umtool-report-to-video/look";
+import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition";
import { applySectionEnter } from "./sections.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
import { validateNarration } from "umtool-report-to-video/narration";
@@ -380,6 +382,23 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri
// and a row saved from the On-screen table cannot store different shapes.
if (patch.onscreen !== undefined) setOnscreen(entry, patch.onscreen);
+ // ---- the vertical short's framing (release 36 lane C) --------------------
+ //
+ // `vertical: {crop: [x, y, w, h], aspect?}` -- fractions of the source
+ // picture, 9:16 on it (look.mjs verticalErrors, the build's own check).
+ // null or "" removes it: the short is cut from the centre again.
+ if (patch.vertical !== undefined) {
+ const v = patch.vertical;
+ if (v === null || v === "") delete entry.vertical;
+ else {
+ const errors = verticalErrors(v, "vertical");
+ if (errors.length) throw new Error(errors.join("; "));
+ const r4 = (n) => Number(Number(n).toFixed(4));
+ const vv = /** @type {{ crop: number[], aspect?: number }} */ (v);
+ entry.vertical = { crop: vv.crop.map(r4), ...(vv.aspect !== undefined ? { aspect: r4(vv.aspect) } : {}) };
+ }
+ }
+
// ---- an assistant's clip, edited by a person (release 35 C2) -------------
//
// A clip the clip finder proposed carries `assist`. The first human edit
@@ -893,6 +912,100 @@ export class ChromeRefused extends Error {
// ---------------------------------------------------------------------------
+// THE LOOK (release 36 lane C): the render keys a person sets for a cut that
+// has no deck -- the header and footer heights, the QR, the crossfade's length
+// and style, the loudness target, the speaker captions. Never `render.chrome`
+// (updateChrome is its writer). Token-guarded, validated with the build's own
+// checks against the render as it will be, then written atomically.
+// ---------------------------------------------------------------------------
+
+/** The render keys the Look panel writes, in its order. */
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions"]);
+
+/** The look keys of a render block as written (absent keys left out). */
+export function lookOf(render) {
+ const r = isObj(render) ? render : {};
+ /** @type {Record<string, unknown>} */
+ const out = {};
+ for (const k of LOOK_KEYS) if (r[k] !== undefined) out[k] = r[k];
+ return out;
+}
+
+/** The build's sentences for a refused look, thrown whole so a route can return each one. */
+export class RenderRefused extends Error {
+ /** @param {string[]} errors */
+ constructor(errors) {
+ super(`render: ${errors.join("; ")}`);
+ this.name = "RenderRefused";
+ this.errors = errors;
+ }
+}
+
+const intIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
+
+/**
+ * Patch the look. Each key of `patch` is one of LOOK_KEYS; `null` removes the
+ * key (the build's default again). `qr: true` turns the code back on (removes
+ * a `false`; an object of settings is kept), `qr: false` turns it off.
+ *
+ * @param {string} dir
+ * @param {Record<string, unknown>} patch
+ * @param {{ token?: string | null }} [opts]
+ * @returns {Promise<{ look: Record<string, unknown>, token: string | null }>}
+ */
+export async function updateRender(dir, patch, { token = null } = {}) {
+ if (!isObj(patch)) throw new RenderRefused(["the patch must be an object of render keys"]);
+ const errors = [];
+ for (const k of Object.keys(patch)) {
+ if (k === "chrome") errors.push("render.chrome is the deck's: set it from the deck's settings (updateChrome), not here");
+ else if (!LOOK_KEYS.includes(k)) errors.push(`render.${k} is not a look setting (${LOOK_KEYS.join(", ")})`);
+ }
+ if (errors.length) throw new RenderRefused(errors);
+ return withManifestLock(async () => {
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ const render = { ...(isObj(manifest.render) ? manifest.render : {}) };
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === null) {
+ delete render[k];
+ continue;
+ }
+ switch (k) {
+ case "headerHeight":
+ case "footerHeight":
+ if (!intIn(v, 0, 240)) errors.push(`render.${k} must be a whole number of pixels from 0 to 240`);
+ else render[k] = v;
+ break;
+ case "qr":
+ if (v === false) render.qr = false;
+ else if (v === true) {
+ if (render.qr === false) delete render.qr;
+ } else errors.push("render.qr must be true (on) or false (off)");
+ break;
+ case "transition":
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 3) errors.push("render.transition must be a number of seconds from 0 (a hard cut) to 3");
+ else render.transition = round2(v);
+ break;
+ case "transitionStyle":
+ if (typeof v !== "string" || !TRANSITION_STYLES.includes(v)) errors.push(`render.transitionStyle must be one of ${TRANSITION_STYLES.join(", ")}`);
+ else render.transitionStyle = v;
+ break;
+ default:
+ // loudness, captions: stored as given; the build's validators below say what is wrong.
+ render[k] = v;
+ }
+ }
+ const next = { ...manifest, render };
+ errors.push(...validateTransitionStyle(next), ...validateLook(next));
+ if (errors.length) throw new RenderRefused(errors);
+ manifest.render = render;
+ const nextToken = await writeManifestAtomic(dir, manifest);
+ return { look: lookOf(render), token: nextToken };
+ });
+}
+
+// ---------------------------------------------------------------------------
// POSTS: the two things a person decides about a post once an agent has put it
// in the manifest -- which clip it rides on, and whether it is shown at all.
//
diff --git a/umtool/lib/report/shorts.mjs b/umtool/lib/report/shorts.mjs
@@ -0,0 +1,119 @@
+// VERTICAL SHORTS (release 36 lane C): one clip of a report video as a
+// 1080x1920 file, `<project>/shorts/<clipId>.mp4`, made by build-video.mjs
+// `--short <clipId>` (report-to-video/look.mjs shortRender: the clip's
+// `vertical.crop`, large speaker captions, no header or QR, the loudness
+// target) as a job through lib/jobs.ts, which build-video's CLI runs inside
+// the machine's heavy slot. A record beside each (`<clipId>.json`) says what
+// it was made from, so the list can say when the clip has moved since.
+import { readFile, readdir, rename, stat } from "node:fs/promises";
+import path from "node:path";
+import { PIPELINE_DIR } from "./driver.mjs";
+
+export const SHORTS_DIR = "shorts";
+/** A short of a clip is minutes at most; a stuck encode is not left forever. */
+export const SHORT_TIMEOUT_MS = 20 * 60_000;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+/** A clip id as a file name: letters, digits, `.`, `_`, `-` only. */
+export const safeClipId = (id) => typeof id === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/.test(id) && !id.includes("..");
+
+export const shortsDirOf = (dir) => path.join(/* turbopackIgnore: true */ dir, SHORTS_DIR);
+
+/** `<project>/shorts/<clipId>.mp4`, or null for an id that is not a file name. */
+export function shortFile(dir, clipId) {
+ return safeClipId(clipId) ? path.join(/* turbopackIgnore: true */ shortsDirOf(dir), `${clipId}.mp4`) : null;
+}
+
+/**
+ * The job's one step: build-video `--short`, NDJSON progress, beside the
+ * build's own steps (lib/report/driver.mjs). No path or argv from a client.
+ *
+ * @param {{ dir: string }} project
+ * @param {string} clipId
+ */
+export function shortSteps(project, clipId) {
+ if (!safeClipId(clipId)) throw new Error(`not a clip id: ${clipId}`);
+ return [
+ {
+ cwd: PIPELINE_DIR,
+ env: {},
+ label: `make the short of ${clipId} (1080×1920)`,
+ argv: [
+ "node", path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"),
+ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"),
+ "--out", path.join(/* turbopackIgnore: true */ project.dir, "out"),
+ "--short", clipId, "--progress", "ndjson",
+ ],
+ ndjson: true,
+ timeoutMs: SHORT_TIMEOUT_MS,
+ },
+ ];
+}
+
+const sameNums = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => Math.abs(x - b[i]) < 0.011);
+
+/**
+ * Every short on disk, newest first: `{ clip, size, mtimeMs, record, stale,
+ * gone }`. `stale`: the clip's cut or crop moved since the short was made;
+ * `gone`: no clip has that id now.
+ *
+ * @param {string} dir the project
+ * @param {any} [manifest] the manifest as read (for stale / gone)
+ */
+export async function readShorts(dir, manifest = null) {
+ const names = await readdir(shortsDirOf(dir)).catch(() => []);
+ const clips = new Map((manifest?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => [e.id, e]));
+ const out = [];
+ for (const name of names) {
+ // A short set aside (`<id>.<stamp>.mp4`) is kept, not listed.
+ if (!name.endsWith(".mp4") || /\.\d{8}-\d{4}\.mp4$/.test(name)) continue;
+ const clip = name.slice(0, -4);
+ if (!safeClipId(clip)) continue;
+ const st = await stat(path.join(/* turbopackIgnore: true */ shortsDirOf(dir), name)).catch(() => null);
+ if (!st?.isFile()) continue;
+ const record = await readFile(path.join(/* turbopackIgnore: true */ shortsDirOf(dir), `${clip}.json`), "utf8").then(JSON.parse, () => null);
+ const e = clips.get(clip) ?? null;
+ let stale = false;
+ if (e && isObj(record)) {
+ const want = [e.cutStart ?? e.start, e.cutEnd ?? e.end];
+ const had = isObj(record.requested) ? [record.requested.cutStart, record.requested.cutEnd] : null;
+ const crop = Array.isArray(e.vertical?.crop) ? e.vertical.crop : null;
+ stale = (had !== null && had.every(fin) && !sameNums(want, had)) || JSON.stringify(crop) !== JSON.stringify(record.crop ?? null);
+ }
+ out.push({ clip, size: st.size, mtimeMs: Math.round(st.mtimeMs), record: isObj(record) ? record : null, stale, gone: manifest ? !e : false });
+ }
+ return out.sort((a, b) => b.mtimeMs - a.mtimeMs);
+}
+
+/** `20260817-1408`: a short set aside before it is made again. */
+function stamp(d = new Date()) {
+ const p = (n) => String(n).padStart(2, "0");
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
+}
+
+/**
+ * The replace guard: a short that is there is never overwritten unasked.
+ * With `replace`, it is moved aside to `shorts/<clipId>.<stamp>.mp4` (its
+ * record too) and the path it went to is returned; without, an error naming
+ * `replace`. No short there: null.
+ *
+ * @param {string} dir
+ * @param {string} clipId
+ * @param {{ replace?: boolean, now?: Date }} [o]
+ */
+export async function setShortAside(dir, clipId, { replace = false, now = new Date() } = {}) {
+ const file = shortFile(dir, clipId);
+ if (!file) throw new Error(`not a clip id: ${clipId}`);
+ const st = await stat(file).catch(() => null);
+ if (!st) return null;
+ if (!replace) {
+ const err = new Error(`${clipId} has a short already — make it again to set that one aside (replace)`);
+ /** @type {any} */ (err).needsReplace = true;
+ throw err;
+ }
+ const aside = file.replace(/\.mp4$/, `.${stamp(now)}.mp4`);
+ await rename(file, aside);
+ await rename(file.replace(/\.mp4$/, ".json"), aside.replace(/\.mp4$/, ".json")).catch(() => {});
+ return aside;
+}
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -14,6 +14,7 @@ Two scripts and a manifest:
| `brand.mjs`, `brand-cards.mjs` | stable | the opt-in brand preset (`render.brand`); see [its section](#the-archilyzer-media-preset-renderbrand). |
| `montage.mjs`, `montage-styles.mjs` | stable | montage editing (`render.montage`) and its named styles; see [its section](#rendermontage--montage-editing-release-33). |
| `montage-rulings.mjs` | stable | the clip deck's rulings (`montage-rulings.json` beside the manifest), applied at render; see [its section](#montage-rulingsjson--the-clip-decks-rulings-release-34). |
+| `look.mjs` | stable | the look of a highlights cut: `render.captions`, `render.loudness`, a clip's `vertical` and the short (`--short`); see [its section](#rendercaptions-renderloudness-a-clips-vertical-and---short-release-36). |
| `<report>/video.manifest.json` | per report | the edit decision list. **This is the regeneration source of truth**, not the report. |
```
@@ -885,6 +886,30 @@ node umtool/report-to-video/montage-styles.mjs list
node umtool/report-to-video/montage-styles.mjs apply flash-count video.manifest.json --out takes/flash/video.manifest.json
```
+### `render.captions`, `render.loudness`, a clip's `vertical` and `--short` (release 36)
+
+`look.mjs` (pure) validates and plans them; build-video's hooks run only when a
+key is set, so a manifest without them renders byte for byte as before
+(md5-checked against main on a two-clip fadeblack fixture: final, segments and
+cut records).
+
+- `render.captions: {style: "speakers", labels?: {host?, subject?}, size?: "m" | "l"}`
+ — per segment an ASS file (`segments/<id>.captions.ass`) from the project's
+ `words.json` (the recording `reactions.json` names), else whisper's words, else
+ the cues; `reactions.json`'s turns colour and place each line (host `#FFC840`
+ left, subject `#6FD3FF` right, other `#F6F1E6` centre), 2–6 words a line,
+ broken on 0.45 s pauses, never across a speaker change; burned with `ass=`
+ (libass, fonts from `fonts/`). Refused beside `render.chrome` or a montage.
+- `render.loudness: {target}` (−30…−8 LUFS) — each cut measured (`ebur128`) and
+ levelled with montage.mjs's `loudnessGain` + `levelFilters` at its encode; the
+ cut record carries `loudness: {measured, gain, target}`. Refused with a montage.
+- clip `vertical: {crop: [x, y, w, h], aspect?}` — fractions of the source, 9:16
+ on it (±3 %); `cropPixels` makes it exact and even.
+- `--short <id>` — that clip alone with `shortRender(render)` (1080×1920, no
+ header/footer/QR/rail/deck, captions size "l", the cut's loudness else −16)
+ into `out/shorts-work/`, then `<manifest dir>/shorts/<id>.mp4` + `<id>.json`.
+ Takes the heavy slot.
+
### `montage-rulings.json` — the clip deck's rulings (release 34)
Beside the manifest, written by umtool's clip deck (`/projects/<id>/clips`) and
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -164,7 +164,14 @@ import { readDraftsReview } from "./drafts-review.mjs";
import { applyMontageRulings, readMontageRulings, rulingsLines } from "./montage-rulings.mjs";
import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
-import { transitionStyleOf, validateTransitionStyle } from "./transition.mjs";
+import { blurSlideEdges, validateTransitionStyle, xfadeTransitionOf } from "./transition.mjs";
+// The look of a highlights cut (release 36 lane C): render.captions,
+// render.loudness, a clip's vertical crop and the short made from it -- pure,
+// in look.mjs. Every hook below runs only when its key is set.
+import {
+ assDocument, assFilter, captionGeometry, captionLines, captionsOn, loudnessTargetOf, shortRender, validateLook,
+ verticalFilters,
+} from "./look.mjs";
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
import { pruneChromeFrames } from "./prune-frames.mjs";
@@ -180,7 +187,7 @@ import {
// An opt-in brand preset (`render.brand`). Every hook below branches on the
// brand BEFORE building an argument, so a manifest without one renders exactly
// as it did -- see brand.mjs.
-import { brandHeaderGeometry, brandManifest } from "./brand.mjs";
+import { FONTS_DIR, brandHeaderGeometry, brandManifest } from "./brand.mjs";
import { markPng, renderThumbnail, THUMB_MAX_BYTES } from "./brand-cards.mjs";
// Montage editing (`render.montage`, release 33): the tight phrase cut, the
// pieces, the cut styles, the counter and the wall -- pure, in montage.mjs.
@@ -189,7 +196,7 @@ import {
clipPhrase, cutStyleParts, locatePhrase, montageFont, montageOn, montageOverlayFilters, montagePieces,
montagePiecesGraph, montageSplit, montageWindow, parseClipDate, planMontage, refineOnset, resolveMontage,
bandFeatures, consensusLags, templateOnset,
- validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, median, nearSilent, relocateBySound, shiftAllowed, speechEnvelope, loudnessGain, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords,
+ validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, median, nearSilent, relocateBySound, shiftAllowed, speechEnvelope, loudnessGain, levelFilters, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords,
} from "./montage.mjs";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
@@ -1218,6 +1225,23 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
start: Number((fetchStart + cutA).toFixed(3)), end: Number((fetchStart + cutB).toFixed(3)),
snapped: { start: a.snapped, end: b.snapped },
};
+ // Even loudness for a cut that is not a montage (render.loudness, release
+ // 36): the cut as it will play, measured, one gain toward the target
+ // (montage.mjs loudnessGain), in the cut record. A montage levels with its
+ // own key; absent, nothing here runs.
+ if (!mont && loudnessTargetOf(render) != null) {
+ level = await montageLevel(raw, cutA, cutB, { target: loudnessTargetOf(render) });
+ cutRecord.loudness = level;
+ }
+ // The sound's graph: `[0:a]` levelled to `[al]` (an asplit first when a
+ // poster's waveform also reads it), else nothing and `0:a` as ever.
+ const leveled = !mont && level != null;
+ const levelParts = (posterParts) => (leveled
+ ? [
+ ...(posterParts ? [`[0:a]asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${levelFilters(level.gain)}[al]`] : [`[0:a]${levelFilters(level.gain)}[al]`]),
+ ]
+ : (posterParts ?? []));
+ const audioMap = leveled ? "[al]" : "0:a";
const quotePath = path.join(outDir, "segments", `${entry.id}.quote.txt`);
const attribPath = path.join(outDir, "segments", `${entry.id}.attrib.txt`);
@@ -1264,10 +1288,10 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
...cutArgs(raw, cutA, cutB),
...(pst ? pst.input : []),
"-filter_complex", [
- ...(pst ? pst.parts : []),
+ ...levelParts(pst ? pst.parts : null),
`${pst ? "[pic]" : "[0:v]"}${deckFramingFilter(render, { feed: fr.layout === "feed" })}[v]`,
].join(";"),
- "-map", "[v]", "-map", "0:a",
+ "-map", "[v]", "-map", audioMap,
...encodeArgs(render),
seg,
],
@@ -1320,7 +1344,12 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
? String(fillB)
: `${fillA}+(${fillB - fillA})*clip(t/${T},0,1)`;
- const base = [
+ // A short (look.mjs): the clip's 9:16 crop scaled to fill the frame -- no
+ // letterbox, no header. A source with no picture keeps the poster's framing.
+ const shortPicture = dirs.short && media.hasVideo
+ ? verticalFilters(entry.vertical?.crop ?? null, ...(await probeDims(raw)), { width, height, fps: render.fps })
+ : null;
+ const base = shortPicture ? shortPicture.join(",") : [
`scale=${VW}:${VH}:force_original_aspect_ratio=decrease`,
`pad=${VW}:${VH}:(ow-iw)/2:(oh-ih)/2:color=${pal.bg}`,
// Widen back to the full frame, leaving the rail column (if any) as ground.
@@ -1385,7 +1414,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const pic = mg?.v ?? (pst ? "[pic]" : "[0:v]");
const lead = mg
? [...(pst ? [`[0:a]asplit=2[mpa][mpw]`, ...pst.parts.map((p) => p.replaceAll("[0:a]", "[mpw]"))] : []), ...mg.parts]
- : (pst ? pst.parts : []);
+ : levelParts(pst ? pst.parts : null);
const parts = hasFooter
? [
@@ -1411,6 +1440,21 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
);
// A montage's cut style and its counter, over the finished frame.
if (mg) parts.push(...mg.post("[v]", "[vm]"));
+ let vOut = mg ? "[vm]" : "[v]";
+ // Speaker captions (render.captions), over the finished frame: an ASS file
+ // beside the segment, burned with libass. None when the clip has no words.
+ if (dirs.look && captionsOn(render)) {
+ const cap = await segmentCaptions({
+ entry, provenance, look: dirs.look, render, outDir,
+ from: cutRecord.start, seconds: cutB - cutA, bottom: FH,
+ });
+ if (cap) {
+ parts.push(`${vOut}${cap.filter}[vc]`);
+ vOut = "[vc]";
+ cutRecord.captions = { lines: cap.lines, words: cap.wordsFrom };
+ }
+ }
+ if (dirs.short) cutRecord.short = { crop: entry.vertical?.crop ?? null, width, height };
await execFileP(
FFMPEG,
@@ -1418,7 +1462,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
"-nostdin", "-v", "error", "-y",
...inputs,
"-filter_complex", parts.join(";"),
- "-map", mg ? "[vm]" : "[v]", "-map", mg ? mg.a : "0:a",
+ "-map", vOut, "-map", mg ? mg.a : audioMap,
...encodeArgs(render),
seg,
],
@@ -1434,6 +1478,141 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
return seg;
}
+// ---- the look (render.captions, a short; release 36 lane C) ---------------
+// The build's side of look.mjs: what needs the project's files, the corpus
+// and ffmpeg. Reached only when render.captions is set, or for a short.
+
+/** A picture's display size `[w, h]` (its sample aspect applied), for a short's crop. */
+async function probeDims(file) {
+ const { stdout } = await execFileP(FFPROBE, [
+ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,sample_aspect_ratio", "-of", "json", file,
+ ]);
+ const st = JSON.parse(stdout).streams?.[0] ?? {};
+ const [n, d] = String(st.sample_aspect_ratio ?? "1:1").split(":").map(Number);
+ const sar = n > 0 && d > 0 ? n / d : 1;
+ const w = Math.round(Number(st.width) * sar);
+ const h = Number(st.height);
+ if (!(w > 0 && h > 0)) throw new Error(`${path.basename(file)}: no picture size to crop a short from`);
+ return [w, h];
+}
+
+/**
+ * What the captions read beside the manifest: reactions.json (the clip
+ * finder's turns and roles, when it is version 1) and the words file it names
+ * (`source.words`, else words.json), read once.
+ */
+async function readLookSources(manifestDir) {
+ let reactions = null;
+ try {
+ const doc = JSON.parse(await readFile(path.join(manifestDir, "reactions.json"), "utf8"));
+ if (doc?.version === 1 && Array.isArray(doc.turns)) reactions = doc;
+ } catch {
+ reactions = null;
+ }
+ return { manifestDir, reactions, words: null, transcripts: new Map() };
+}
+
+/** Does reactions.json describe this clip's recording? */
+function lookMatches(entry, provenance, rx) {
+ if (!rx?.source?.video || hasLocalMedia(entry) || entry.video !== rx.source.video) return false;
+ const ch = entry.channel ?? provenance?.channelSlug ?? null;
+ return !rx.source.channel || !ch || ch === rx.source.channel;
+}
+
+const wordOf = (w) => ({ text: String(w?.w ?? w?.word ?? w?.text ?? ""), start: Number(w?.start), end: Number(w?.end) });
+
+/**
+ * A clip's words, turns and speakers in [from, to] (source seconds): the
+ * project's words file for the recording reactions.json describes, else the
+ * corpus's whisper words (transcript.json), else its cues spread by
+ * character. Turns and speakers only from reactions.json.
+ */
+async function lookWordsFor(entry, provenance, look, from, to) {
+ const inSpan = (w) => Number.isFinite(w.start) && Number.isFinite(w.end) && (w.start + w.end) / 2 >= from - 0.05 && (w.start + w.end) / 2 <= to + 0.05;
+ const rx = lookMatches(entry, provenance, look.reactions) ? look.reactions : null;
+ const turns = rx ? rx.turns.filter((t) => t.end > from && t.start < to) : [];
+ const speakers = rx?.speakers ?? [];
+ if (rx) {
+ look.words ??= readFile(path.join(look.manifestDir, typeof rx.source.words === "string" ? rx.source.words : "words.json"), "utf8")
+ .then((t) => {
+ const doc = JSON.parse(t);
+ return (Array.isArray(doc) ? doc : doc?.words ?? []).map(wordOf);
+ })
+ .catch(() => null);
+ const ws = await look.words;
+ if (ws?.length) {
+ const got = ws.filter(inSpan);
+ if (got.length) return { words: got, turns, speakers, wordsFrom: "words.json" };
+ }
+ }
+ if (!hasLocalMedia(entry) && FX_CHANNELS_DIR && entry.video) {
+ const slug = entry.channel ?? provenance?.channelSlug;
+ const key = `${slug}/${entry.video}`;
+ if (!look.transcripts.has(key)) {
+ look.transcripts.set(key, resolveVideoDir(FX_CHANNELS_DIR, slug, entry.video)
+ .then((dir) => readFile(path.join(dir, "transcript.json"), "utf8"))
+ .then((t) => whisperWords(JSON.parse(t)))
+ .catch(() => null));
+ }
+ const ws = await look.transcripts.get(key);
+ const got = (ws ?? []).map(wordOf).filter(inSpan);
+ if (got.length) return { words: got, turns, speakers, wordsFrom: "transcript.json" };
+ }
+ const cues = fxWordsOf(await montageCues(entry, provenance), from - 0.05, to + 0.05).map(wordOf);
+ return { words: cues, turns, speakers, wordsFrom: "cues" };
+}
+
+/**
+ * One segment's captions: the ASS file beside it (segments/<id>.captions.ass)
+ * and the filter that burns it in, or null (a note) when the clip has no
+ * words. `from` is the source second the segment starts at.
+ */
+async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, bottom }) {
+ const src = await lookWordsFor(entry, provenance, look, from, from + seconds);
+ if (!src.words.length) {
+ EMIT("note", { message: `${entry.id}: no words to caption — it plays without captions` });
+ return null;
+ }
+ const rel = (x) => ({ ...x, start: x.start - from, end: x.end - from });
+ const size = render.captions?.size ?? "m";
+ const geo = captionGeometry({ width: render.width, height: render.height, size, bottom });
+ const lines = captionLines({
+ words: src.words.map(rel), turns: src.turns.map(rel), speakers: src.speakers, captions: render.captions,
+ seconds, maxChars: geo.maxChars,
+ });
+ const file = path.join(outDir, "segments", `${entry.id}.captions.ass`);
+ await writeFile(file, assDocument(lines, { width: render.width, height: render.height, size, bottom }), "utf8");
+ return { filter: assFilter(file, FONTS_DIR), lines: lines.length, wordsFrom: src.wordsFrom };
+}
+
+/**
+ * A short's segment to <project>/shorts/<id>.mp4 (tmp + rename), with a
+ * record beside it (<id>.json: the cut, the crop, the size, the loudness,
+ * the captions, when). Returns the mp4's path.
+ */
+async function placeShort(seg, manifestDir, entry, render) {
+ const dir = path.join(manifestDir, "shorts");
+ await mkdir(dir, { recursive: true });
+ const dest = path.join(dir, `${entry.id}.mp4`);
+ const tmp = `${dest}.tmp-${process.pid}`;
+ await writeFile(tmp, await readFile(seg));
+ await rename(tmp, dest);
+ const rec = await readCutRecord(seg).catch(() => null);
+ const record = {
+ version: 1, clip: entry.id, video: entry.video ?? null,
+ // What was asked for (the clip's cut, else its extent) and what played (snapped).
+ requested: { cutStart: entry.cutStart ?? entry.start, cutEnd: entry.cutEnd ?? entry.end },
+ cut: rec ? [rec.start, rec.end] : null,
+ crop: entry.vertical?.crop ?? null,
+ width: render.width, height: render.height,
+ loudness: rec?.loudness ?? null,
+ captions: rec?.captions ?? null,
+ madeAt: new Date().toISOString(),
+ };
+ await replaceFile(path.join(dir, `${entry.id}.json`), JSON.stringify(record, null, 2) + "\n");
+ return dest;
+}
+
// ---- montage (render.montage) ---------------------------------------------
// The build's side of montage.mjs: what needs the cue source, the corpus and
// ffmpeg. Reached only when render.montage is set.
@@ -1616,7 +1795,7 @@ async function montageCheckSound({ entry, mont, raw, fetchStart, M, render, prov
* A stretch of a source's integrated loudness (LUFS, ffmpeg's ebur128), or
* null when it cannot be measured.
*/
-async function measureLoudness(raw, from, to) {
+export async function measureLoudness(raw, from, to) {
const { stderr } = await execFileP(FFMPEG, [
"-nostdin", "-hide_banner", "-ss", Math.max(0, from).toFixed(3), "-to", to.toFixed(3), "-i", raw,
"-vn", "-af", "ebur128", "-f", "null", "-",
@@ -3798,7 +3977,16 @@ export function xfadeGraph(durs, D, joins = null, render = null, { joined = fals
const len = d.toFixed(6);
const a = `[p${i}a]`;
parts.push(`${c.a}apad=whole_dur=${len},atrim=end=${len},asetpts=PTS-STARTPTS${a}`);
- return { v: c.v, a };
+ // A blur slide smears and grains each side of a plain seam (transition.mjs).
+ const special = (k) => !!(joins?.[k]?.dip || (!joined && (joins?.[k]?.wipe || joins?.[k]?.whip)));
+ const edges = blurSlideEdges(d, D, render, {
+ tail: i < durs.length - 1 && !special(i),
+ head: i > 0 && !special(i - 1),
+ });
+ if (!edges) return { v: c.v, a };
+ const v = `[p${i}e]`;
+ parts.push(`${c.v}setpts=PTS-STARTPTS,${edges}${v}`);
+ return { v, a };
});
let vlab = ins[0].v;
let alab = ins[0].a;
@@ -3816,7 +4004,7 @@ export function xfadeGraph(durs, D, joins = null, render = null, { joined = fals
const wipe = !dip && !!joins?.[i - 1]?.wipe;
// A whip cut (fx.mjs `whip`): the NOW clip slides in as the last slides out.
const whip = !dip && !wipe && !!joins?.[i - 1]?.whip;
- const vx = dip ? "transition=custom:expr='A'" : wipe ? "transition=wipeleft" : whip ? "transition=slideleft" : `transition=${transitionStyleOf(render)}`;
+ const vx = dip ? "transition=custom:expr='A'" : wipe ? "transition=wipeleft" : whip ? "transition=slideleft" : `transition=${xfadeTransitionOf(render)}`;
const ax = dip ? "c1=nofade:c2=nofade" : "c1=tri:c2=tri";
parts.push(`${vlab}${ins[i].v}xfade=${vx}:duration=${D}:offset=${off.toFixed(3)}[v${i}]`);
parts.push(`${alab}${ins[i].a}acrossfade=d=${D}:${ax}[a${i}]`);
@@ -4825,6 +5013,12 @@ export async function prepareLocalMedia(timeline, manifestDir, render = {}) {
export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } = {}) {
const variant = opts.variant ?? "sourced";
+ // A vertical short (`--short <id>`, release 36 lane C) is that one clip,
+ // built as `--only` builds it, in a look of its own (look.mjs shortRender).
+ if (opts.short) {
+ if (only && only !== opts.short) throw new Error(`--short ${opts.short} and --only ${only} name different clips`);
+ only = opts.short;
+ }
const whole = JSON.parse(await readFile(manifestPath, "utf8"));
// An `image` entry's `src` is relative to the MANIFEST, which is checked in
// beside the pictures it cites -- not to the cwd the build was started from.
@@ -4839,6 +5033,12 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
? { manifest: whole, left: [], matched: [], renumbered: false }
: applyMontageRulings(whole, await readMontageRulings(manifestDir), { keep: only ? [only] : [] });
const manifest = selectVariant(ruled.manifest, variant);
+ if (opts.short) {
+ const e = (manifest.timeline ?? []).find((x) => x.id === opts.short);
+ if (!e) throw new Error(`no timeline entry with id ${opts.short}`);
+ if (e.type !== "clip") throw new Error(`${opts.short} is a ${e.type ?? "non-clip"} entry: a short is made from a clip`);
+ manifest.render = shortRender(manifest.render ?? {});
+ }
for (const message of rulingsLines(ruled)) EMIT("note", { message });
const { render, provenance } = manifest;
// A `src` clip's file and cues, checked and measured before anything else.
@@ -4855,6 +5055,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole),
...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole),
...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole), ...validateTransitionStyle(whole),
+ ...validateLook(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
@@ -4912,6 +5113,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
});
const outRoot = out ?? path.join(path.dirname(path.resolve(manifestPath)), "out");
const dirs = variantPaths(outRoot, manifest.slug, variant);
+ // A short's work is its own: the cut's segments are never overwritten by one.
+ if (opts.short) dirs.dir = path.join(outRoot, "shorts-work");
const outDir = dirs.dir;
// Where media may already be on disk. The channels tree is the one the clip
// bench reads for this project (sources.mjs channelsDirFor): the manifest's
@@ -4925,6 +5128,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe,
});
FX_CHANNELS_DIR = channelsDir;
+ // Speaker captions read the project's reactions.json and words beside the
+ // manifest (readLookSources); a short is framed by its clip's crop.
+ if (captionsOn(render)) dirs.look = await readLookSources(manifestDir);
+ if (opts.short) dirs.short = { id: opts.short };
// A project's out/ first, through ensureOutDir: with UMTOOL_MEDIA_DIR set it
// is a link to the media root, and the recursive mkdirs below would
@@ -5387,6 +5594,12 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
}
if (only) {
+ // A short leaves its work dir for <project>/shorts/<id>.mp4 (placeShort).
+ if (opts.short && segments[0] && !failures.length) {
+ const placed = await placeShort(segments[0], manifestDir, entries[0], render);
+ EMIT("done", { out: placed, failures, short: opts.short });
+ return { out: placed, failures };
+ }
EMIT("done", { out: segments[0], failures });
return { out: segments[0], failures };
}
@@ -5626,6 +5839,8 @@ export function chromeFlags(argv) {
* chapters and the thumbnail do not.
*/
export function takesHeavySlot({ opts = {}, only = null, fetchOnly = null } = {}) {
+ // A short is a 1080x1920 encode of one clip: a render, in the slot.
+ if (opts.short && !fetchOnly) return true;
return !fetchOnly && !only && !opts.chaptersOnly && !opts.thumbnailOnly;
}
@@ -5647,7 +5862,7 @@ async function main() {
if (!manifestPath) {
console.error(
"usage: build-video.mjs <manifest.json> [--out <dir>] [--variant sourced|full]\n" +
- " [--only <id>] [--fetch-only <id>]\n" +
+ " [--only <id>] [--fetch-only <id>] [--short <id>] (a vertical short of one clip: <project>/shorts/<id>.mp4)\n" +
" [--pad <s>] [--pad-before <s>] [--pad-after <s>] [--skip-fetch] [--no-network] [--audio-fallback] [--no-xfade] [--no-chapters] [--chapters-only]\n" +
" [--progress ndjson] [--continue-on-error] [--no-reuse]\n" +
" [--no-rail] [--rail-only] [--preview <start> <dur>]\n" +
@@ -5695,6 +5910,7 @@ async function main() {
narrationUnreviewed: argv.includes("--narration-unreviewed"),
final: argv.includes("--final"),
draftsUnreviewed: argv.includes("--drafts-unreviewed"),
+ short: flag("--short") ?? null,
};
try {
Object.assign(opts, chromeFlags(argv));
@@ -5725,7 +5941,7 @@ async function main() {
process.exit(lint.errors.length ? 1 : 0);
}
- const only = flag("--only");
+ const only = flag("--only") ?? opts.short ?? undefined;
const fetchOnly = flag("--fetch-only");
const build = () => buildVideo({ manifestPath, opts, out: flag("--out"), only, fetchOnly });
const { failures } = takesHeavySlot({ opts, only, fetchOnly })
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -88,6 +88,7 @@ import { validateMontage } from "./montage.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { validateFxEntries } from "./fx.mjs";
import { validateTransitionStyle } from "./transition.mjs";
+import { validateLook } from "./look.mjs";
import { qrUrlFor } from "./render-cards.mjs";
import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs";
import { validatePodcast } from "./build-podcast.mjs";
@@ -240,6 +241,8 @@ export function validatorErrors(whole) {
...validateFxEntries(whole),
// Release 35: the crossfade's look between clips.
...validateTransitionStyle(whole),
+ // Release 36: render.captions, render.loudness and a clip's vertical crop.
+ ...validateLook(whole),
];
if (deckOn(whole.render)) {
errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`));
diff --git a/umtool/report-to-video/look.mjs b/umtool/report-to-video/look.mjs
@@ -0,0 +1,403 @@
+// THE LOOK of a highlights cut (release 36 lane C): three opt-in render keys
+// and one clip key, validated here (the build's validators and the lint call
+// validateLook, as they call validateTransitionStyle), and the pure pieces the
+// build draws them with.
+//
+// render.captions {style: "speakers", labels?: {host?, subject?}, size?: "m" | "l"}
+// burned-in captions, coloured and placed by who speaks
+// (reactions.json's turns and roles), 2-6 words a line
+// render.loudness {target: -16} (LUFS, -30 to -8)
+// each clip's cut measured (ebur128) and brought to the
+// target with one gain and a limiter (montage.mjs's
+// loudnessGain + levelFilters)
+// clip.vertical {crop: [x, y, w, h], aspect?} fractions of the source
+// picture: the box a vertical short (1080x1920) is cut from;
+// `aspect` is the source's width/height (16/9 when absent)
+//
+// Absent (or null) = off, and the render is byte for byte what it was.
+//
+// THE CAPTION COLOURS are fixed, not the palette's: a caption has to read on
+// any footage, and a person tells the voices apart by colour first.
+// host #FFC840 amber bottom left
+// subject #6FD3FF sky bottom right
+// other #F6F1E6 paper bottom centre (a third voice, or a word heard in no turn)
+// Black outline (3 px at 1080p), soft shadow. ASS colours are &HAABBGGRR.
+
+export const CAPTION_STYLES = Object.freeze(["speakers"]);
+export const CAPTION_SIZES = Object.freeze(["m", "l"]);
+export const CAPTION_ROLES = Object.freeze(["host", "subject", "other"]);
+export const CAPTION_COLOURS = Object.freeze({ host: "#FFC840", subject: "#6FD3FF", other: "#F6F1E6" });
+/** ASS alignment (numpad): host bottom-left, subject bottom-right, other bottom-centre. */
+export const CAPTION_ALIGN = Object.freeze({ host: 1, subject: 3, other: 2 });
+/** The font, vendored in fonts/ (IBM Plex Sans, OFL): libass is pointed at that directory. */
+export const CAPTION_FONT = "IBM Plex Sans";
+export const CAPTION_LABEL_MAX = 40;
+/** Words a line: at least (unless a speaker change or the clip's end forces fewer), at most. */
+export const CAPTION_MIN_WORDS = 2;
+export const CAPTION_MAX_WORDS = 6;
+/** A gap between two words this long (s) ends a line that has its minimum. */
+export const CAPTION_PAUSE = 0.45;
+/** How long a line stays up after its last word (s), never past the next line. */
+export const CAPTION_HOLD = 0.3;
+
+export const LOUDNESS_MIN = -30;
+export const LOUDNESS_MAX = -8;
+/** A short's target when the cut sets none. */
+export const SHORT_LOUDNESS = -16;
+
+export const SHORT_WIDTH = 1080;
+export const SHORT_HEIGHT = 1920;
+export const VERTICAL_RATIO = 9 / 16;
+/** How far a crop's shape may be from 9:16 (relative): the build fits it exactly. */
+export const VERTICAL_TOLERANCE = 0.03;
+export const DEFAULT_SOURCE_ASPECT = 16 / 9;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const q = (v) => JSON.stringify(v);
+
+export const captionsOn = (render) => isObj(render?.captions);
+export const loudnessOn = (render) => isObj(render?.loudness) && num(render.loudness.target);
+/** The target in LUFS, or null when the cut sets none. */
+export const loudnessTargetOf = (render) => (loudnessOn(render) ? render.loudness.target : null);
+
+/** `render.captions`: its keys and values, and what it does not combine with. */
+export function validateCaptions(manifest) {
+ const render = manifest?.render ?? {};
+ const c = render.captions;
+ if (c === undefined || c === null) return [];
+ if (!isObj(c)) return [`render.captions must be an object ({style: "speakers"}) or absent, not ${q(c)}`];
+ const errors = [];
+ for (const k of Object.keys(c)) {
+ if (!["style", "labels", "size"].includes(k)) errors.push(`render.captions.${k} is not a setting here (the settings are style, labels, size)`);
+ }
+ if (!CAPTION_STYLES.includes(c.style)) errors.push(`render.captions.style must be "speakers", not ${q(c.style)}`);
+ if (c.size !== undefined && !CAPTION_SIZES.includes(c.size)) errors.push(`render.captions.size must be "m" or "l", not ${q(c.size)}`);
+ if (c.labels !== undefined && c.labels !== null) {
+ if (!isObj(c.labels)) errors.push(`render.captions.labels must be an object ({host, subject}), not ${q(c.labels)}`);
+ else {
+ for (const [k, v] of Object.entries(c.labels)) {
+ if (k !== "host" && k !== "subject") errors.push(`render.captions.labels.${k} is not a role here (host, subject)`);
+ else if (v !== null && (typeof v !== "string" || v.length > CAPTION_LABEL_MAX)) {
+ errors.push(`render.captions.labels.${k} must be a short text (up to ${CAPTION_LABEL_MAX} characters), or null`);
+ }
+ }
+ }
+ }
+ if (isObj(render.chrome)) errors.push("render.captions does not combine with render.chrome (the deck draws its own words: render.chrome.fx.kineticQuote)");
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.captions does not combine with render.montage (a montage re-times its clips)");
+ return errors;
+}
+
+/** `render.loudness`: `{target}` in LUFS. */
+export function validateLoudness(manifest) {
+ const render = manifest?.render ?? {};
+ const l = render.loudness;
+ if (l === undefined || l === null) return [];
+ if (!isObj(l)) return [`render.loudness must be an object ({target: -16}) or absent, not ${q(l)}`];
+ const errors = [];
+ for (const k of Object.keys(l)) if (k !== "target") errors.push(`render.loudness.${k} is not a setting here (the setting is target)`);
+ if (!num(l.target) || l.target < LOUDNESS_MIN || l.target > LOUDNESS_MAX) {
+ errors.push(`render.loudness.target must be a number from ${LOUDNESS_MIN} to ${LOUDNESS_MAX} LUFS, not ${q(l.target)}`);
+ }
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.loudness does not combine with render.montage (a montage levels with render.montage.loudness)");
+ return errors;
+}
+
+/** One clip's `vertical` (null when it has none): its errors, prefixed by `who`. */
+export function verticalErrors(v, who = "vertical") {
+ if (v === undefined || v === null) return [];
+ if (!isObj(v)) return [`${who} must be an object ({crop: [x, y, w, h]}), not ${q(v)}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (k !== "crop" && k !== "aspect") errors.push(`${who}.${k} is not a setting here (crop, aspect)`);
+ if (v.aspect !== undefined && (!num(v.aspect) || v.aspect <= 0.2 || v.aspect > 5)) {
+ errors.push(`${who}.aspect must be the source's width / height (a number from 0.2 to 5), not ${q(v.aspect)}`);
+ }
+ const c = v.crop;
+ if (!Array.isArray(c) || c.length !== 4 || !c.every(num)) {
+ errors.push(`${who}.crop must be [x, y, w, h], four fractions of the source picture`);
+ return errors;
+ }
+ const [x, y, w, h] = c;
+ const E = 1e-3;
+ if (w <= 0 || h <= 0) errors.push(`${who}.crop's width and height must be above 0`);
+ if (x < -E || y < -E || x + w > 1 + E || y + h > 1 + E) errors.push(`${who}.crop must lie inside the picture (each of x, y, x + w, y + h from 0 to 1)`);
+ if (w > 0 && h > 0) {
+ const aspect = num(v.aspect) ? v.aspect : DEFAULT_SOURCE_ASPECT;
+ const shape = (w * aspect) / h;
+ if (Math.abs(shape / VERTICAL_RATIO - 1) > VERTICAL_TOLERANCE) {
+ errors.push(`${who}.crop must be 9:16 on the source (w × aspect / h ≈ 0.5625; this one is ${shape.toFixed(4)})`);
+ }
+ }
+ return errors;
+}
+
+/** Every clip's `vertical`. */
+export function validateVertical(manifest) {
+ const errors = [];
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.vertical === undefined) return;
+ const who = `timeline[${i}] (${e?.id ?? "?"}).vertical`;
+ if (e?.type !== "clip") errors.push(`${who}: only a clip has a vertical crop`);
+ else errors.push(...verticalErrors(e.vertical, who));
+ });
+ return errors;
+}
+
+/** All of the look's keys: the build's validators and the lint call this. */
+export function validateLook(manifest) {
+ return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest)];
+}
+
+// ---------------------------------------------------------------------------
+// The vertical crop.
+// ---------------------------------------------------------------------------
+
+/** The centred, full-height 9:16 box on a source of `aspect` (w/h), as fractions. */
+export function defaultCrop(aspect = DEFAULT_SOURCE_ASPECT) {
+ const a = num(aspect) && aspect > 0 ? aspect : DEFAULT_SOURCE_ASPECT;
+ let w = VERTICAL_RATIO / a;
+ let h = 1;
+ if (w > 1) {
+ h = a / VERTICAL_RATIO;
+ w = 1;
+ }
+ const r = (n) => Number(n.toFixed(4));
+ return [r((1 - w) / 2), r((1 - h) / 2), r(w), r(h)];
+}
+
+const even = (n) => Math.max(2, 2 * Math.round(n / 2));
+
+/**
+ * A crop (fractions) as pixels of a `srcW`×`srcH` picture, exactly 9:16 and
+ * even: the box's height kept (its width made 9/16 of it, about its centre),
+ * clamped inside the picture. `{x, y, w, h}`.
+ */
+export function cropPixels(crop, srcW, srcH) {
+ const [fx, fy, fw, fh] = Array.isArray(crop) && crop.length === 4 ? crop : defaultCrop(srcW / srcH);
+ let h = Math.min(srcH, Math.max(2, fh * srcH));
+ let w = (h * 9) / 16;
+ if (w > srcW) {
+ w = srcW;
+ h = (w * 16) / 9;
+ }
+ w = Math.min(even(w), srcW - (srcW % 2));
+ h = Math.min(even(h), srcH - (srcH % 2));
+ const cx = (fx + fw / 2) * srcW;
+ const cy = (fy + fh / 2) * srcH;
+ const x = Math.round(Math.max(0, Math.min(srcW - w, cx - w / 2)));
+ const y = Math.round(Math.max(0, Math.min(srcH - h, cy - h / 2)));
+ return { x, y, w, h };
+}
+
+/** The ffmpeg chain that cuts a short's picture: the crop, scaled to fill 1080x1920. */
+export function verticalFilters(crop, srcW, srcH, { width = SHORT_WIDTH, height = SHORT_HEIGHT, fps } = {}) {
+ const b = cropPixels(crop, srcW, srcH);
+ return [`crop=${b.w}:${b.h}:${b.x}:${b.y}`, `scale=${width}:${height}:flags=lanczos`, "setsar=1", ...(fps ? [`fps=${fps}`] : [])];
+}
+
+/**
+ * The render a short is made with: 1080x1920, no header, footer, QR, rail or
+ * deck; speaker captions at size "l" (the cut's labels kept); the cut's
+ * loudness target, else SHORT_LOUDNESS.
+ */
+export function shortRender(render = {}) {
+ const { chrome: _c, rail: _r, chromeEngine: _e, brand: _b, montage: _m, ...rest } = render;
+ const labels = isObj(render.captions?.labels) ? { labels: render.captions.labels } : {};
+ return {
+ ...rest,
+ width: SHORT_WIDTH,
+ height: SHORT_HEIGHT,
+ headerHeight: 0,
+ footerHeight: 0,
+ qr: false,
+ captions: { style: "speakers", ...labels, size: "l" },
+ loudness: { target: loudnessTargetOf(render) ?? SHORT_LOUDNESS },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The captions: words and turns to lines, lines to an ASS document.
+// ---------------------------------------------------------------------------
+
+/** The label reactions.json gives a speaker it was never told about (common/lib/clips/reactions.mjs labelOf). */
+export const defaultSpeakerLabel = (role, index) => (role === "host" ? "Host" : role === "subject" ? "Subject" : `Speaker ${Number(index) + 1}`);
+
+/**
+ * What a speaker's lines are headed with, or null: the cut's
+ * `render.captions.labels[role]` when set, else the speaker's own label when
+ * a person gave it one (anything but the default) -- voices are told apart by
+ * colour and side, and named only when somebody names them.
+ */
+export function speakerCaptionLabel(speaker, captions) {
+ const role = CAPTION_ROLES.includes(speaker?.role) ? speaker.role : "other";
+ const set = captions?.labels?.[role];
+ if (typeof set === "string" && set.trim()) return set.trim();
+ const own = typeof speaker?.label === "string" ? speaker.label.trim() : "";
+ if (own && own !== defaultSpeakerLabel(speaker?.role, speaker?.index)) return own;
+ return null;
+}
+
+/**
+ * Which speaker says a word: the turn its middle is in; else the turn whose
+ * edge is nearest, within `reach` seconds; else null.
+ */
+export function speakerAt(turns, start, end, reach = 0.6) {
+ const mid = (start + end) / 2;
+ let best = null;
+ let gap = Infinity;
+ for (const t of turns ?? []) {
+ if (mid >= t.start && mid <= t.end) return t.speaker;
+ const d = mid < t.start ? t.start - mid : mid - t.end;
+ if (d < gap) {
+ gap = d;
+ best = t.speaker;
+ }
+ }
+ return gap <= reach ? best : null;
+}
+
+/** A word as a caption shows it: no ASS override braces or backslashes, trimmed. */
+export const captionText = (w) => String(w ?? "").replace(/[{}\\]/g, "").replace(/\s+/g, " ").trim();
+
+/**
+ * The caption lines of one segment.
+ *
+ * @param {{ words: Array<{text: string, start: number, end: number}>, turns?: Array<{start: number, end: number, speaker: number}>,
+ * speakers?: Array<{index: number, role?: string, label?: string}>, captions?: object, seconds?: number,
+ * maxChars?: number }} o every time in the segment's seconds
+ * @returns {Array<{start: number, end: number, text: string, role: string, speaker: number|null, label: string|null}>}
+ */
+export function captionLines({ words, turns = [], speakers = [], captions = {}, seconds = Infinity, maxChars = 40 }) {
+ const roleOf = (sp) => {
+ const s = speakers.find((x) => x?.index === sp);
+ return CAPTION_ROLES.includes(s?.role) ? s.role : "other";
+ };
+ const used = (words ?? [])
+ .map((w) => ({ text: captionText(w.text), start: Number(w.start), end: Number(w.end) }))
+ .filter((w) => w.text && Number.isFinite(w.start) && Number.isFinite(w.end) && w.end > 0 && w.start < seconds)
+ .map((w) => ({ ...w, start: Math.max(0, w.start), end: Math.min(seconds, Math.max(w.start, w.end)) }))
+ .sort((a, b) => a.start - b.start);
+ const groups = [];
+ let cur = null;
+ for (const w of used) {
+ const speaker = speakerAt(turns, w.start, w.end);
+ const prev = cur?.words[cur.words.length - 1];
+ const chars = cur ? cur.words.reduce((n, x) => n + x.text.length + 1, 0) + w.text.length : 0;
+ const split =
+ !cur ||
+ speaker !== cur.speaker ||
+ cur.words.length >= CAPTION_MAX_WORDS ||
+ (cur.words.length >= CAPTION_MIN_WORDS && (w.start - prev.end >= CAPTION_PAUSE || chars > maxChars));
+ if (split) {
+ cur = { speaker, words: [w] };
+ groups.push(cur);
+ } else cur.words.push(w);
+ }
+ const lines = groups.map((g, i) => {
+ const sp = speakers.find((x) => x?.index === g.speaker) ?? (g.speaker == null ? null : { index: g.speaker });
+ const role = g.speaker == null ? "other" : roleOf(g.speaker);
+ // A label heads the first line of each turn (the first, or a change of voice).
+ const first = i === 0 || groups[i - 1].speaker !== g.speaker;
+ return {
+ start: g.words[0].start,
+ end: g.words[g.words.length - 1].end,
+ text: g.words.map((x) => x.text).join(" "),
+ role,
+ speaker: g.speaker ?? null,
+ label: first && sp ? speakerCaptionLabel({ ...sp, role }, captions) : null,
+ };
+ });
+ for (let i = 0; i < lines.length; i += 1) {
+ const next = lines[i + 1];
+ lines[i].end = Math.min(seconds, next ? Math.max(lines[i].end, Math.min(next.start, lines[i].end + CAPTION_HOLD)) : lines[i].end + CAPTION_HOLD);
+ if (lines[i].end - lines[i].start < 0.2) lines[i].end = Math.min(seconds, lines[i].start + 0.2);
+ }
+ return lines;
+}
+
+/** Seconds as an ASS time, h:mm:ss.cc (centiseconds, rounded). */
+export function assTime(t) {
+ const cs = Math.max(0, Math.round(t * 100));
+ const h = Math.floor(cs / 360000);
+ const m = Math.floor((cs % 360000) / 6000);
+ const s = Math.floor((cs % 6000) / 100);
+ const c = cs % 100;
+ return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${String(c).padStart(2, "0")}`;
+}
+
+/** `#RRGGBB` as an ASS colour, `&HAABBGGRR`. */
+export function assColour(hex, alpha = 0) {
+ const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(String(hex));
+ if (!m) throw new Error(`not a #rrggbb colour: ${hex}`);
+ const a = Math.max(0, Math.min(255, Math.round(alpha))).toString(16).padStart(2, "0");
+ return `&H${a}${m[3]}${m[2]}${m[1]}`.toUpperCase();
+}
+
+/** The caption geometry for a frame: font size, outline, margins (px). */
+export function captionGeometry({ width, height, size = "m", bottom = 0 }) {
+ const vertical = height > width;
+ const base = Math.min(width, height);
+ const fontSize = Math.round(base * (size === "l" ? 0.075 : 0.052));
+ return {
+ fontSize,
+ outline: Math.max(1, Math.round(fontSize * 0.055)),
+ shadow: Math.max(0, Math.round(fontSize * 0.03)),
+ marginH: Math.round(width * (vertical ? 0.06 : 0.05)),
+ // A short's captions sit above the bottom fifth (a phone app's own controls).
+ marginV: Math.round(bottom + height * (vertical ? 0.2 : 0.07)),
+ // Characters a line, so a line never wraps at this size (about 55 % of the width).
+ maxChars: Math.max(12, Math.floor((width * (vertical ? 0.88 : 0.55)) / (fontSize * 0.52))),
+ };
+}
+
+/**
+ * The ASS document for a segment's lines. One style per role (its colour and
+ * side); a label is the line's head, smaller. No wrapping: the lines are
+ * already short.
+ */
+export function assDocument(lines, { width, height, size = "m", bottom = 0, font = CAPTION_FONT } = {}) {
+ const g = captionGeometry({ width, height, size, bottom });
+ const style = (role) =>
+ `Style: ${role},` +
+ [
+ font, g.fontSize, assColour(CAPTION_COLOURS[role]), "&H000000FF", assColour("#000000"), assColour("#000000", 0x80),
+ -1, 0, 0, 0, 100, 100, 0, 0, 1, g.outline, g.shadow, CAPTION_ALIGN[role], g.marginH, g.marginH, g.marginV, 1,
+ ].join(",");
+ const labelSize = Math.round(g.fontSize * 0.62);
+ const events = lines.map((l) => {
+ const head = l.label ? `{\\fs${labelSize}}${captionText(l.label)}{\\fs${g.fontSize}} ` : "";
+ return `Dialogue: 0,${assTime(l.start)},${assTime(l.end)},${l.role},,0,0,0,,${head}${captionText(l.text)}`;
+ });
+ return [
+ "[Script Info]",
+ "ScriptType: v4.00+",
+ `PlayResX: ${width}`,
+ `PlayResY: ${height}`,
+ "WrapStyle: 2",
+ "ScaledBorderAndShadow: yes",
+ "YCbCr Matrix: None",
+ "",
+ "[V4+ Styles]",
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
+ ...CAPTION_ROLES.map(style),
+ "",
+ "[Events]",
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
+ ...events,
+ "",
+ ].join("\n");
+}
+
+/**
+ * A path as a filter option value, single-quoted (as the header's `fontfile`
+ * is). A path with a quote or a colon in it cannot be said this way: refused.
+ */
+export function filterPath(p) {
+ const s = String(p);
+ if (/[':\\]/.test(s)) throw new Error(`captions: ${s} has a quote, a colon or a backslash in it, which a filter option cannot carry`);
+ return `'${s}'`;
+}
+
+/** The `ass=` filter that burns a document in, its fonts from `fontsDir`. */
+export const assFilter = (file, fontsDir) => `ass=filename=${filterPath(file)}${fontsDir ? `:fontsdir=${filterPath(fontsDir)}` : ""}`;
diff --git a/umtool/report-to-video/look.test.mjs b/umtool/report-to-video/look.test.mjs
@@ -0,0 +1,391 @@
+// The look of a highlights cut (look.mjs, release 36 lane C): the validators,
+// the caption lines and their ASS document, the vertical crop -- and real
+// renders: a cut without the new keys is byte for byte what it was; loudness
+// lands within ±0.5 LU of its target; a caption appears on its frame, in its
+// speaker's colour and side; a short is 1080x1920 and shows the crop.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+// The corpus the build reads metadata and cues from: set before build-video
+// (cues.mjs) is loaded, so it is this file's own.
+const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-look-corpus-"));
+process.env.CHANNELS_DIR = CORPUS;
+
+const {
+ CAPTION_COLOURS, SHORT_HEIGHT, SHORT_WIDTH, assColour, assDocument, assTime, captionLines, cropPixels, defaultCrop,
+ loudnessTargetOf, shortRender, speakerAt, speakerCaptionLabel, validateLook, verticalErrors, verticalFilters,
+} = await import("./look.mjs");
+const { buildVideo, measureLoudness, setProgressMode, takesHeavySlot } = await import("./build-video.mjs");
+const { lintManifest } = await import("./lint.mjs");
+const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs");
+
+test.after(() => rm(CORPUS, { recursive: true, force: true }));
+
+// ---- the validators -------------------------------------------------------------
+
+const m = (render = {}, timeline = []) => ({ render, timeline });
+
+test("validateLook: absent or null says nothing; the seed's default look validates", () => {
+ assert.deepEqual(validateLook(m()), []);
+ assert.deepEqual(validateLook(m({ captions: null, loudness: null })), []);
+ // Lane B's seed for a site-less, one-video cut.
+ assert.deepEqual(validateLook(m({ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", loudness: { target: -16 } })), []);
+ assert.deepEqual(validateLook(m({ captions: { style: "speakers" } })), []);
+ assert.deepEqual(validateLook(m({ captions: { style: "speakers", size: "l", labels: { host: "Nik", subject: null } } })), []);
+});
+
+test("validateLook: captions -- each problem in a sentence naming the key", () => {
+ const e = (c, extra = {}) => validateLook(m({ captions: c, ...extra }));
+ assert.match(e("on")[0], /render\.captions must be an object/);
+ assert.match(e({ style: "karaoke" })[0], /render\.captions\.style must be "speakers", not "karaoke"/);
+ assert.match(e({ style: "speakers", size: "xl" })[0], /render\.captions\.size must be "m" or "l"/);
+ assert.match(e({ style: "speakers", colour: "red" })[0], /render\.captions\.colour is not a setting here/);
+ assert.match(e({ style: "speakers", labels: { guest: "x" } })[0], /labels\.guest is not a role here/);
+ assert.match(e({ style: "speakers", labels: { host: "x".repeat(41) } })[0], /labels\.host must be a short text/);
+ assert.match(e({ style: "speakers" }, { chrome: { engine: "hyperframes" } })[0], /does not combine with render\.chrome/);
+ assert.match(e({ style: "speakers" }, { montage: {} })[0], /does not combine with render\.montage/);
+});
+
+test("validateLook: loudness is a target from -30 to -8 LUFS", () => {
+ const e = (l, extra = {}) => validateLook(m({ loudness: l, ...extra }));
+ assert.deepEqual(e({ target: -30 }), []);
+ assert.deepEqual(e({ target: -8 }), []);
+ assert.match(e({ target: -7 })[0], /render\.loudness\.target must be a number from -30 to -8 LUFS, not -7/);
+ assert.match(e({ target: "-16" })[0], /not "-16"/);
+ assert.match(e({ target: -16, lra: 7 })[0], /render\.loudness\.lra is not a setting here/);
+ assert.match(e(-16)[0], /render\.loudness must be an object/);
+ assert.match(e({ target: -16 }, { montage: {} })[0], /render\.montage\.loudness/);
+ assert.equal(loudnessTargetOf({ loudness: { target: -14 } }), -14);
+ assert.equal(loudnessTargetOf({}), null);
+});
+
+test("validateLook: a clip's vertical crop lies inside the picture and is 9:16 on the source", () => {
+ const clip = (vertical) => ({ type: "clip", id: "c1", video: "v", start: 0, end: 5, vertical });
+ const e = (v) => validateLook(m({}, [clip(v)]));
+ assert.deepEqual(e(undefined), []);
+ assert.deepEqual(e({ crop: defaultCrop() }), []);
+ assert.deepEqual(e({ crop: [0, 0, 0.3164, 1] }), []);
+ // A 4:3 source's 9:16 box is wider in fractions.
+ assert.deepEqual(e({ crop: defaultCrop(4 / 3), aspect: 4 / 3 }), []);
+ assert.match(e({ crop: [0, 0, 0.5, 1] })[0], /timeline\[0\] \(c1\)\.vertical\.crop must be 9:16 on the source/);
+ assert.match(e({ crop: [0.8, 0, 0.3164, 1] })[0], /must lie inside the picture/);
+ assert.match(e({ crop: [0, 0, 1] })[0], /must be \[x, y, w, h\]/);
+ assert.match(e({ crop: defaultCrop(), zoom: 2 })[0], /vertical\.zoom is not a setting here/);
+ assert.match(e("centre")[0], /vertical must be an object/);
+ assert.match(validateLook(m({}, [{ type: "card", id: "k", vertical: { crop: defaultCrop() } }]))[0], /only a clip has a vertical crop/);
+ assert.deepEqual(verticalErrors(null), []);
+});
+
+test("the lint says it too", () => {
+ const lint = lintManifest({ slug: "x", title: "X", render: { width: 320, height: 180, fps: 30, captions: { style: "nope" } }, timeline: [] }, { manifestDir: os.tmpdir(), exists: () => true });
+ assert.ok(lint.errors.some((x) => /render\.captions\.style/.test(x)), lint.errors.join("; "));
+});
+
+// ---- the crop -------------------------------------------------------------------
+
+test("defaultCrop / cropPixels: centred, full height, exactly 9:16 and even", () => {
+ assert.deepEqual(defaultCrop(16 / 9), [0.3418, 0, 0.3164, 1]);
+ assert.deepEqual(cropPixels(defaultCrop(16 / 9), 1920, 1080), { x: 656, y: 0, w: 608, h: 1080 });
+ assert.deepEqual(cropPixels(null, 1920, 1080), { x: 656, y: 0, w: 608, h: 1080 });
+ // Off to the right, clamped inside.
+ assert.deepEqual(cropPixels([0.7, 0, 0.3164, 1], 1920, 1080), { x: 1312, y: 0, w: 608, h: 1080 });
+ // A smaller box: its height kept, its centre kept.
+ const b = cropPixels([0.25, 0.25, 0.1582, 0.5], 1920, 1080);
+ assert.deepEqual(b, { x: 480, y: 270, w: 304, h: 540 });
+ assert.equal(b.w / b.h, 9 / 16 + (304 / 540 - 9 / 16));
+ assert.deepEqual(verticalFilters(null, 1920, 1080, { fps: 30 }), ["crop=608:1080:656:0", "scale=1080:1920:flags=lanczos", "setsar=1", "fps=30"]);
+});
+
+test("shortRender: 1080x1920, no header, footer, QR, rail or deck; large captions; the cut's loudness, else -16", () => {
+ const r = shortRender({ width: 1920, height: 1080, fps: 30, headerHeight: 56, qr: { margin: 20 }, chrome: { engine: "hyperframes" }, rail: { width: 300 }, captions: { style: "speakers", labels: { host: "Nik" } } });
+ assert.equal(r.width, SHORT_WIDTH);
+ assert.equal(r.height, SHORT_HEIGHT);
+ assert.equal(r.headerHeight, 0);
+ assert.equal(r.footerHeight, 0);
+ assert.equal(r.qr, false);
+ assert.equal(r.chrome, undefined);
+ assert.equal(r.rail, undefined);
+ assert.deepEqual(r.captions, { style: "speakers", labels: { host: "Nik" }, size: "l" });
+ assert.deepEqual(r.loudness, { target: -16 });
+ assert.deepEqual(shortRender({ loudness: { target: -14 } }).loudness, { target: -14 });
+ assert.equal(takesHeavySlot({ opts: { short: "c1" }, only: "c1" }), true);
+ assert.equal(takesHeavySlot({ only: "c1" }), false);
+});
+
+// ---- the caption lines ----------------------------------------------------------
+
+const SPEAKERS = [
+ { index: 0, role: "host", label: "Host" },
+ { index: 1, role: "subject", label: "Subject" },
+ { index: 2, role: "other", label: "Speaker 3" },
+];
+const word = (text, start, end = start + 0.3) => ({ text, start, end });
+
+test("captionLines: 2-6 words a line, broken on pauses, never across a change of speaker", () => {
+ const words = [
+ // subject, 0-4: eight words in a run, then a pause, then two
+ ...["a", "b", "c", "d", "e", "f", "g", "h"].map((w, i) => word(w, 0.1 + i * 0.35)),
+ word("i", 3.4), word("j", 3.75),
+ // host, 4-6: one word, then the subject again
+ word("wow", 4.2),
+ word("k", 6.1), word("l", 6.45),
+ ];
+ const turns = [{ start: 0, end: 4, speaker: 1 }, { start: 4, end: 6, speaker: 0 }, { start: 6, end: 8, speaker: 1 }];
+ const lines = captionLines({ words, turns, speakers: SPEAKERS, seconds: 8 });
+ assert.deepEqual(lines.map((l) => [l.text, l.role]), [
+ ["a b c d e f", "subject"],
+ ["g h", "subject"],
+ ["i j", "subject"],
+ ["wow", "host"],
+ ["k l", "subject"],
+ ]);
+ // A line starts on its first word; it holds 0.3 s, never past the next.
+ assert.equal(lines[0].start, 0.1);
+ assert.equal(lines[1].end, Math.min(lines[2].start, 0.1 + 7 * 0.35 + 0.3 + 0.3));
+ assert.equal(lines.at(-1).end, 6.45 + 0.3 + 0.3);
+ // No labels unless somebody gave one.
+ assert.ok(lines.every((l) => l.label === null));
+});
+
+test("captionLines: a label heads each turn's first line -- the cut's, else a person's", () => {
+ const words = [word("one", 0.1), word("two", 0.5), word("three", 0.9), word("four", 2.1), word("five", 2.5)];
+ const turns = [{ start: 0, end: 1.5, speaker: 0 }, { start: 2, end: 3, speaker: 1 }];
+ const set = captionLines({ words, turns, speakers: SPEAKERS, captions: { style: "speakers", labels: { host: "Nik" } }, seconds: 4 });
+ assert.deepEqual(set.map((l) => l.label), ["Nik", null]);
+ const named = captionLines({ words, turns, speakers: [{ index: 0, role: "host", label: "Host" }, { index: 1, role: "subject", label: "The narrator" }], seconds: 4 });
+ assert.deepEqual(named.map((l) => l.label), [null, "The narrator"]);
+ assert.equal(speakerCaptionLabel({ index: 2, role: "other", label: "Speaker 3" }, {}), null);
+ assert.equal(speakerCaptionLabel({ index: 2, role: "other", label: "Chat" }, {}), "Chat");
+});
+
+test("speakerAt: the turn a word's middle is in, else the nearest within 0.6 s, else none", () => {
+ const turns = [{ start: 0, end: 1, speaker: 0 }, { start: 3, end: 4, speaker: 1 }];
+ assert.equal(speakerAt(turns, 0.2, 0.5), 0);
+ assert.equal(speakerAt(turns, 1.2, 1.4), 0);
+ assert.equal(speakerAt(turns, 2.6, 2.7), 1);
+ assert.equal(speakerAt(turns, 1.8, 2.0), null);
+ assert.equal(speakerAt([], 0, 1), null);
+});
+
+test("assDocument: a style per role in its colour and side; times in centiseconds; a label smaller", () => {
+ assert.equal(assTime(0), "0:00:00.00");
+ assert.equal(assTime(61.234), "0:01:01.23");
+ assert.equal(assTime(3725.996), "1:02:06.00");
+ assert.equal(assColour("#FFC840"), "&H0040C8FF");
+ assert.equal(assColour("#000000", 0x80), "&H80000000");
+ const doc = assDocument(
+ [{ start: 1.5, end: 2.25, text: "hello {there}", role: "host", label: "Nik" }, { start: 2.5, end: 3, text: "hi", role: "subject", label: null }],
+ { width: 1920, height: 1080, size: "m" },
+ );
+ assert.match(doc, /PlayResX: 1920\nPlayResY: 1080/);
+ assert.match(doc, new RegExp(`Style: host,IBM Plex Sans,56,${assColour(CAPTION_COLOURS.host).replace("&", "&")},.*,1,\\d+,\\d+,1,96,96,76,1`));
+ assert.match(doc, /Style: subject,IBM Plex Sans,56,&H00FFD36F,.*,3,96,96,76,1/);
+ assert.match(doc, /Style: other,IBM Plex Sans,56,&H00E6F1F6,.*,2,96,96,76,1/);
+ assert.match(doc, /Dialogue: 0,0:00:01\.50,0:00:02\.25,host,,0,0,0,,\{\\fs35\}Nik\{\\fs56\} {2}hello there/);
+ assert.match(doc, /Dialogue: 0,0:00:02\.50,0:00:03\.00,subject,,0,0,0,,hi\n/);
+ const big = assDocument([], { width: 1080, height: 1920, size: "l" });
+ assert.match(big, /Style: host,IBM Plex Sans,81,/);
+});
+
+// ---- real renders ---------------------------------------------------------------
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0)
+ && /\bass\b/.test(String(spawnSync("ffmpeg", ["-hide_banner", "-filters"]).stdout));
+const FPS = 30;
+const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" };
+const RENDER = {
+ width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0,
+ headerHeight: 0, footerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE,
+ fetchPad: 0, snapWindow: 0.05, silenceMinDur: 0.1,
+};
+const CHANNEL = "synth";
+const VIDEO = "vid1";
+
+// The corpus record the build reads the clip's metadata from.
+{
+ const dir = path.join(CORPUS, CHANNEL, "data", VIDEO);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(CORPUS, CHANNEL, "config.json"), JSON.stringify({ name: "Synth" }));
+ writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: VIDEO, title: "Synthetic", duration: 12, uploadDate: "20240102", cues: [{ start: 0.2, end: 11.8, text: "filler words only" }] }));
+ writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: VIDEO, title: "Synthetic", duration: 12 }));
+}
+
+/**
+ * A project: one clip of vid1 (1-7 s), its window in out/clips-raw (12 s of a
+ * 640x360 black picture with a white bar at x 400-440, and a 440 Hz tone,
+ * lavfi sine's 1/8 times `amp`), reactions.json (the subject 0-4 s and 8-12 s, the host 4-8 s) and
+ * words.json (a word every half second).
+ */
+async function project(render = {}, { clip = {}, amp = 0.5, rx = true } = {}) {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-look-"));
+ mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true });
+ const raw = path.join(root, "out", "clips-raw", `${VIDEO}_0.00-12.00.mp4`);
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=black:s=640x360:r=${FPS}:d=12`,
+ "-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:duration=12`,
+ "-filter_complex", `[0:v]drawbox=x=400:y=0:w=40:h=360:color=white:t=fill[v];[1:a]volume=${amp}[a]`,
+ "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ if (rx) {
+ await writeFile(path.join(root, "reactions.json"), JSON.stringify({
+ version: 1,
+ source: { channel: CHANNEL, video: VIDEO, duration: 12, words: "words.json" },
+ speakers: [{ index: 0, role: "host", label: "Host", how: "auto" }, { index: 1, role: "subject", label: "Subject", how: "auto" }],
+ turns: [{ start: 0, end: 4, speaker: 1 }, { start: 4, end: 8, speaker: 0 }, { start: 8, end: 12, speaker: 1 }],
+ laughs: [], moments: [], proposals: [],
+ }));
+ const words = [];
+ for (let t = 0.25; t < 11.5; t += 0.5) words.push({ w: `w${Math.round(t * 2)}`, start: t, end: t + 0.3 });
+ await writeFile(path.join(root, "words.json"), JSON.stringify({ words }));
+ }
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "look", title: "Look",
+ provenance: { channelSlug: CHANNEL, channelsDir: CORPUS },
+ render: { ...RENDER, ...render },
+ timeline: [{ type: "clip", id: "c1", channel: CHANNEL, video: VIDEO, start: 1, end: 7, cite: 1, quote: "q", ...clip }],
+ }));
+ return { root, manifestPath, raw };
+}
+
+const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0];
+const quiet = () => setProgressMode(() => {});
+
+/** One frame of `file` as rgb24: `{ w, h, px(x, y) => [r, g, b] }`. */
+function frame(file, n) {
+ const p = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]);
+ const [w, h] = String(p.stdout).trim().split(",").map(Number);
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `select='eq(n,${n})'`, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 1 << 26 });
+ assert.equal(r.status, 0, String(r.stderr));
+ const buf = r.stdout;
+ return { w, h, px: (x, y) => { const i = (y * w + x) * 3; return [buf[i], buf[i + 1], buf[i + 2]]; } };
+}
+
+/** The mean colour of the bright pixels (max channel > 140) in a box, and how many. */
+function brightIn(f, x0, y0, x1, y1) {
+ let n = 0;
+ const sum = [0, 0, 0];
+ for (let y = y0; y < y1; y += 1) {
+ for (let x = x0; x < x1; x += 1) {
+ const c = f.px(x, y);
+ if (Math.max(...c) > 140) {
+ n += 1;
+ sum[0] += c[0]; sum[1] += c[1]; sum[2] += c[2];
+ }
+ }
+ }
+ return { n, mean: n ? sum.map((v) => v / n) : null };
+}
+
+test("render: without the new keys (absent or null) the cut is byte for byte the same", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ const a = await project({});
+ const b = await project({ captions: null, loudness: null });
+ try {
+ await buildVideo({ manifestPath: a.manifestPath, opts: { noNetwork: true } });
+ await buildVideo({ manifestPath: b.manifestPath, opts: { noNetwork: true } });
+ for (const f of ["look.mp4", "sourced/segments/c1.mp4", "sourced/segments/c1.cut.json"]) {
+ assert.equal(md5(path.join(a.root, "out", f)), md5(path.join(b.root, "out", f)), f);
+ }
+ const rec = JSON.parse(await readFile(path.join(a.root, "out", "sourced", "segments", "c1.cut.json"), "utf8"));
+ assert.equal(rec.loudness, undefined);
+ assert.equal(rec.captions, undefined);
+ } finally {
+ await rm(a.root, { recursive: true, force: true });
+ await rm(b.root, { recursive: true, force: true });
+ }
+});
+
+test("render: render.loudness brings a quiet clip to its target within ±0.5 LU", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ const p = await project({ loudness: { target: -16 } }, { amp: 0.5 });
+ try {
+ const before = await measureLoudness(p.raw, 1, 7);
+ assert.ok(before < -24 && before > -40, `the source is quiet, not silent: ${before}`);
+ const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ const seg = path.join(p.root, "out", "sourced", "segments", "c1.mp4");
+ const after = await measureLoudness(seg, 0, 6);
+ assert.ok(Math.abs(after - -16) <= 0.5, `segment ${after} LUFS`);
+ assert.ok(Math.abs((await measureLoudness(r.out, 0, 6)) - -16) <= 0.5, "the cut");
+ const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8"));
+ assert.equal(rec.loudness.target, -16);
+ assert.ok(Math.abs(rec.loudness.gain - (-16 - before)) < 0.6, JSON.stringify(rec.loudness));
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("render: speaker captions -- on their frame, the subject sky on the right, the host amber on the left", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ const p = await project({ width: 640, height: 360, captions: { style: "speakers" } });
+ try {
+ await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ const segDir = path.join(p.root, "out", "sourced", "segments");
+ const rec = JSON.parse(await readFile(path.join(segDir, "c1.cut.json"), "utf8"));
+ assert.deepEqual([rec.start, rec.end], [1, 7]);
+ assert.equal(rec.captions.words, "words.json");
+ const ass = await readFile(path.join(segDir, "c1.captions.ass"), "utf8");
+ const events = ass.split("\n").filter((l) => l.startsWith("Dialogue:"));
+ // Source 1.25 is the first word: 0.25 s into the segment; the host's first (4.25) at 3.25.
+ assert.match(events[0], /^Dialogue: 0,0:00:00\.25,[^,]+,subject,/);
+ const host = events.find((l) => /,host,/.test(l));
+ assert.match(host, /^Dialogue: 0,0:00:03\.25,/);
+ const seg = path.join(segDir, "c1.mp4");
+ // The bar (x 400-440 of 640) is white in every frame; the captions are under y 260.
+ const box = (f, side) => (side === "left" ? brightIn(f, 0, 260, 300, 345) : brightIn(f, 445, 260, 640, 345));
+ // To the frame: nothing on frame 6 (0.2 s), the subject's line on frame 8 (0.267 s).
+ assert.equal(box(frame(seg, 6), "right").n, 0, "no caption before its first word");
+ const sub = box(frame(seg, 8), "right");
+ assert.ok(sub.n > 30, `the subject's line is up: ${sub.n} px`);
+ assert.ok(sub.mean[2] > sub.mean[0] + 60, `sky: ${sub.mean.map(Math.round)}`);
+ assert.equal(box(frame(seg, 8), "left").n, 0, "the subject is on the right only");
+ // The host from 3.25 s: frame 99 (3.3 s) amber on the left.
+ const h = box(frame(seg, 99), "left");
+ assert.ok(h.n > 30, `the host's line is up: ${h.n} px`);
+ assert.ok(h.mean[0] > h.mean[2] + 80, `amber: ${h.mean.map(Math.round)}`);
+ assert.equal(box(frame(seg, 99), "right").n, 0, "the host is on the left only");
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("render: a short -- 1080x1920, its crop, large captions, loudness, in <project>/shorts/", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ // The crop's centre on the bar (x 400-440 of 640): [0.5, 0, 0.3164, 1] centres at x 421.
+ const p = await project({ headerHeight: 56, qr: { margin: 10 } }, { clip: { vertical: { crop: [0.5, 0, 0.3164, 1] } } });
+ try {
+ const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, short: "c1" } });
+ const out = path.join(p.root, "shorts", "c1.mp4");
+ assert.equal(r.out, out);
+ const probe = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", out]);
+ assert.equal(String(probe.stdout).trim(), "1080,1920");
+ // The crop: 202x360 at x 320, so the bar is at 80-120 of 202 -> 428-642 of 1080.
+ const f = frame(out, 15);
+ assert.ok(Math.min(...f.px(535, 400)) > 200, `the bar in the middle: ${f.px(535, 400)}`);
+ assert.ok(Math.max(...f.px(200, 400)) < 40, "black left of it");
+ assert.ok(Math.max(...f.px(900, 400)) < 40, "black right of it");
+ // No header: the top rows are the picture (black beside the bar).
+ assert.ok(Math.max(...f.px(100, 10)) < 40, "no header");
+ const rec = JSON.parse(await readFile(path.join(p.root, "shorts", "c1.json"), "utf8"));
+ assert.deepEqual(rec.crop, [0.5, 0, 0.3164, 1]);
+ assert.equal(rec.width, 1080);
+ assert.equal(rec.loudness.target, -16);
+ assert.ok(rec.captions.lines > 0);
+ // Large captions on the subject's side.
+ const ass = await readFile(path.join(p.root, "out", "shorts-work", "segments", "c1.captions.ass"), "utf8");
+ assert.match(ass, /Style: subject,IBM Plex Sans,81,/);
+ assert.ok(Math.abs((await measureLoudness(out, 0, 6)) - -16) <= 0.5, "loudness");
+ // The cut's own segments are untouched.
+ assert.equal(spawnSync("test", ["-e", path.join(p.root, "out", "sourced", "segments", "c1.mp4")]).status, 1);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -34,6 +34,7 @@
"./montage-rulings": "./montage-rulings.mjs",
"./lint": "./lint.mjs",
"./local-media": "./local-media.mjs",
+ "./look": "./look.mjs",
"./mute": "./mute.mjs",
"./narration": "./narration.mjs",
"./narration-review": "./narration-review.mjs",
@@ -46,6 +47,7 @@
"./shoot-page": "./shoot-page.mjs",
"./social": "./social.mjs",
"./sources": "./sources.mjs",
+ "./transition": "./transition.mjs",
"./verify-build": "./verify-build.mjs",
"./youtube": "./youtube.mjs"
}
diff --git a/umtool/report-to-video/transition.mjs b/umtool/report-to-video/transition.mjs
@@ -5,11 +5,47 @@
// The length is still `render.transition`; a THEN/NOW wipe, a whip and a
// teaser's dip keep their own look.
-export const TRANSITION_STYLES = Object.freeze(["fade", "fadeblack", "fadewhite", "dissolve"]);
+// "blurslide" is not an xfade name: the next clip slides in from the left
+// (xfade `slideright`) while both sides of the seam are smeared sideways and
+// grained -- each clip's last and first `render.transition` seconds get a
+// horizontal blur (stronger in the half nearest the seam) and a light temporal
+// noise, in the clip's own time, so a batched build's joins get it too.
+export const TRANSITION_STYLES = Object.freeze(["fade", "fadeblack", "fadewhite", "dissolve", "blurslide"]);
-/** The xfade transition name for a plain join. */
+/** The style a plain join uses (`render.transitionStyle`, default "fade"). */
export const transitionStyleOf = (render) => render?.transitionStyle ?? "fade";
+/** The xfade transition name for a plain join. */
+export const xfadeTransitionOf = (render) => (transitionStyleOf(render) === "blurslide" ? "slideright" : transitionStyleOf(render));
+
+// The blur slide's smear and grain: sigma across the whole edge, more in the
+// half nearest the seam (they compound: ~sqrt(10² + 16²) ≈ 19 at the seam),
+// vertical sigma kept tiny so it reads as motion, not focus.
+export const BLUR_SLIDE = Object.freeze({ sigma: 10, seamSigma: 16, sigmaV: 0.6, noise: 7 });
+
+/**
+ * The filters a blur slide puts on one input `d` seconds long, joined over `D`
+ * seconds: on its tail when a plain join follows it, on its head when one
+ * precedes it. "" when the style is not "blurslide", `D` is 0, or neither edge
+ * is a plain join (a dip, a wipe and a whip keep their own look).
+ */
+export function blurSlideEdges(d, D, render, { tail = false, head = false } = {}) {
+ if (transitionStyleOf(render) !== "blurslide" || !(D > 0) || (!tail && !head)) return "";
+ const win = (full) => {
+ const w = full ? D : D / 2;
+ const parts = [];
+ if (tail) parts.push(`gte(t,${(d - w).toFixed(3)})`);
+ if (head) parts.push(`lt(t,${w.toFixed(3)})`);
+ return parts.join("+");
+ };
+ const b = BLUR_SLIDE;
+ return [
+ `gblur=sigma=${b.sigma}:sigmaV=${b.sigmaV}:enable='${win(true)}'`,
+ `gblur=sigma=${b.seamSigma}:sigmaV=${b.sigmaV}:enable='${win(false)}'`,
+ `noise=alls=${b.noise}:allf=t+u:enable='${win(true)}'`,
+ ].join(",");
+}
+
/** @param {{ render?: { transitionStyle?: unknown } }} manifest */
export function validateTransitionStyle(manifest) {
const s = manifest?.render?.transitionStyle;
diff --git a/umtool/report-to-video/transition.test.mjs b/umtool/report-to-video/transition.test.mjs
@@ -4,7 +4,9 @@
import assert from "node:assert/strict";
import test from "node:test";
import { xfadeGraph } from "./build-video.mjs";
-import { TRANSITION_STYLES, transitionStyleOf, validateTransitionStyle } from "./transition.mjs";
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { TRANSITION_STYLES, blurSlideEdges, transitionStyleOf, validateTransitionStyle, xfadeTransitionOf } from "./transition.mjs";
const RENDER = { width: 1920, height: 1080, fps: 30, transition: 0.5, audioRate: 48000, audioChannels: 2 };
const xfades = (g) => g.parts.filter((p) => p.includes("xfade="));
@@ -39,3 +41,55 @@ test("validateTransitionStyle: xfade's names only", () => {
assert.equal(validateTransitionStyle({ render: { transitionStyle: "spin" } }).length, 1);
assert.equal(validateTransitionStyle({ render: { transitionStyle: 3 } }).length, 1);
});
+
+test("transitionStyle: blurslide slides the next clip in from the left over smeared, grained edges", () => {
+ const R = { ...RENDER, transition: 0.4, transitionStyle: "blurslide" };
+ assert.equal(xfadeTransitionOf(R), "slideright");
+ const g = xfadeGraph([10, 12, 4], 0.4, null, R);
+ assert.deepEqual(xfades(g), [
+ "[p0e][p1e]xfade=transition=slideright:duration=0.4:offset=9.600[v1]",
+ "[v1][p2e]xfade=transition=slideright:duration=0.4:offset=21.200[v2]",
+ ]);
+ // The first clip's tail only, the middle one's head and tail, the last one's head only -- in each clip's own time.
+ const edge = (i) => g.parts.find((p) => p.endsWith(`[p${i}e]`));
+ assert.match(edge(0), /^\[0:v\]setpts=PTS-STARTPTS,gblur=sigma=10:sigmaV=0.6:enable='gte\(t,9.600\)',gblur=sigma=16:sigmaV=0.6:enable='gte\(t,9.800\)',noise=alls=7:allf=t\+u:enable='gte\(t,9.600\)'\[p0e\]$/);
+ assert.match(edge(1), /enable='gte\(t,11.600\)\+lt\(t,0.400\)'/);
+ assert.match(edge(2), /enable='lt\(t,0.400\)'/);
+ assert.doesNotMatch(edge(2), /gte/);
+ assert.ok(g.parts.includes("[p0a][p1a]acrossfade=d=0.4:c1=tri:c2=tri[a1]"));
+});
+
+test("transitionStyle: blurslide leaves a dip, a wipe and a whip alone, and every other style untouched", () => {
+ const R = { ...RENDER, transitionStyle: "blurslide" };
+ const g = xfadeGraph([10, 12, 4], 0.5, [{ wipe: true }, null, null], R);
+ assert.match(xfades(g)[0], /transition=wipeleft/);
+ assert.doesNotMatch(g.parts.find((p) => p.endsWith("[p0e]")) ?? "", /gte/);
+ assert.match(g.parts.find((p) => p.endsWith("[p1e]")), /enable='gte\(t,11.500\)'/);
+ assert.equal(blurSlideEdges(10, 0.5, { transitionStyle: "fadeblack" }, { tail: true }), "");
+ assert.equal(blurSlideEdges(10, 0, { transitionStyle: "blurslide" }, { tail: true }), "");
+ for (const s of ["fade", "fadeblack", "fadewhite", "dissolve"]) {
+ assert.ok(!xfadeGraph([10, 12], 0.5, null, { ...RENDER, transitionStyle: s }).parts.some((p) => p.includes("gblur")));
+ }
+});
+
+test("transitionStyle: blurslide renders in ffmpeg; frames outside the seam are a plain slide's, inside they differ", () => {
+ const run = (style) => {
+ const R = { ...RENDER, width: 320, height: 180, transition: 0.4, transitionStyle: style };
+ const g = xfadeGraph([1.5, 1.5], 0.4, null, R);
+ const src = (c) => ["-f", "lavfi", "-i", `testsrc2=s=320x180:r=30:d=1.5,hue=h=${c}`];
+ const tone = ["-f", "lavfi", "-i", "sine=f=440:d=1.5:sample_rate=48000"];
+ const args = ["-v", "error", ...src(0), ...src(120), ...tone, ...tone,
+ "-filter_complex", [...g.parts.map((p) => p.replace("[0:a]", "[2:a]").replace("[1:a]", "[3:a]"))].join(";"),
+ "-map", g.vlab, "-map", g.alab, "-f", "framemd5", "-"];
+ return execFileSync("ffmpeg", args, { encoding: "utf8" }).split("\n").filter((l) => /^0,/.test(l)).map((l) => l.split(",").pop().trim());
+ };
+ const plain = run("fade");
+ const blur = run("blurslide");
+ assert.equal(blur.length, Math.round((1.5 + 1.5 - 0.4) * 30));
+ // Frame 10 (0.33 s) is before the window and frame 70 after it: untouched by the blur, same as any style.
+ const md5 = (s) => createHash("md5").update(s).digest("hex");
+ assert.equal(md5(blur[10]), md5(plain[10]));
+ assert.equal(md5(blur[70]), md5(plain[70]));
+ // Frame 40 (1.33 s) is mid-seam: blurred, grained and slid, not a dissolve.
+ assert.notEqual(blur[40], plain[40]);
+});