Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 22e74ee6b0427668702747774a6b62774ad1e08b
parent dc2444a2ecd589c4cdaa2c69fe078f3f24966d97
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 30 Oct 2026 17:26:17 -0400

Merge integration/gaps-render-mode: gaps inside a clip + the bench waveform's zoom, and render mode (umtool take --priority, umtool render-mode, pnpm ops render-mode)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	umtool/docs/knobs.md
#	umtool/lib/report/knobsCli.mjs
#	umtool/lib/report/manifest.mjs

Diffstat:
MAGENTS.md | 27+++++++++++++++++++++++++--
MCOMMANDS.md | 1+
MENVIRONMENT.md | 3+++
MWORKTREES.md | 46++++++++++++++++++++++++++++++++++++----------
Mcommon/controller/recordLive.ts | 4+++-
Mcommon/lib/envVars.ts | 3+++
Acommon/lib/renderPriority.mjs | 452+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/renderPriority.test.ts | 240+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Aeditor/app/api/ops/_renderMode.test.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/render-mode/route.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/jobs/actions.ts | 16++++++++++++++++
Aeditor/app/jobs/components/EndRenderModeButton.tsx | 38++++++++++++++++++++++++++++++++++++++
Aeditor/app/jobs/components/RenderModeBanner.tsx | 39+++++++++++++++++++++++++++++++++++++++
Meditor/app/jobs/page.tsx | 2++
Aeditor/app/operations/renderMode.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/scheduler/heartbeat.ts | 9+++++++++
Meditor/e2e/servers.ts | 3+++
Mscripts/archilyzer-ops.mjs | 23+++++++++++++++++++++++
Mscripts/queue-lock.mjs | 149++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mscripts/queue-lock.test.mjs | 146++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/app/api/render-mode/route.ts | 37+++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/clip-editor/route.ts | 3+++
Mumtool/app/api/report/clip/route.ts | 2++
Mumtool/app/api/report/window/route.ts | 7+++++++
Mumtool/bin/umtool.mjs | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ClipBench.tsx | 487++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/components/projects/ClipBenchPage.tsx | 4++++
Mumtool/components/projects/NewTakePanel.tsx | 9+++++++--
Aumtool/components/projects/RenderModeBanner.tsx | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/bench/GapsZoom.tsx | 392+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/bench/RenderGhosts.tsx | 11++++++++---
Mumtool/components/projects/review/LiveDeckPreview.tsx | 4++--
Mumtool/components/projects/review/PlayCut.tsx | 4+++-
Mumtool/components/projects/review/ReelStrip.tsx | 16+++++++++++++++-
Mumtool/components/projects/review/playEngine/engine.ts | 20+++++++++++++++-----
Mumtool/docs/cli.md | 13+++++++++++++
Mumtool/docs/knobs.md | 44++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 19+++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 16++++++++++++++++
Aumtool/e2e/gaps-zoom.spec.ts | 289++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/takes.spec.ts | 61++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/inbox/groups.mjs | 1+
Mumtool/lib/inbox/what.mjs | 1+
Mumtool/lib/projects/report.mjs | 12++++++++++++
Aumtool/lib/report/benchZoom.mjs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/benchZoom.test.mjs | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/clipEditor.mjs | 16++++++++++++----
Mumtool/lib/report/clipEditorTypes.ts | 2++
Mumtool/lib/report/cutPoints.mjs | 16+++++++++++++---
Aumtool/lib/report/gaps-writer.test.mjs | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/knobsCli.mjs | 27++++++++++++++++++++++++++-
Mumtool/lib/report/liveClock.mjs | 18+++++++++++++-----
Mumtool/lib/report/manifest.mjs | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/playCut.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Aumtool/lib/report/playGaps.test.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playSchedule.mjs | 44++++++++++++++++++++++++++++++++++++--------
Mumtool/lib/report/playView.mjs | 2++
Aumtool/lib/report/renderMode.mjs | 288+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/renderMode.test.mjs | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeCli.mjs | 59+++++++++++++++++++++++++++++++++++++++--------------------
Mumtool/lib/report/takeMaker.mjs | 10+++++++---
Mumtool/lib/report/takeRender.mjs | 5++++-
Mumtool/lib/report/timelineCli.mjs | 6+++++-
Mumtool/playwright.config.ts | 4++++
Mumtool/report-to-video/build-video.mjs | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/report-to-video/clip-blur.mjs | 11+++++++----
Mumtool/report-to-video/deck.mjs | 36+++++++++++++++++++++++++-----------
Mumtool/report-to-video/factcheck.mjs | 4+++-
Mumtool/report-to-video/fx.mjs | 18+++++++++++-------
Aumtool/report-to-video/gaps-render.test.mjs | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/gaps.mjs | 426+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/gaps.test.mjs | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/heavy-gate.test.mjs | 3+++
Mumtool/report-to-video/lint.mjs | 3+++
Mumtool/report-to-video/mute.mjs | 11++++++++---
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/snap.mjs | 38+++++++++++++++++++++++++++++---------
Mumtool/report-to-video/stats.mjs | 11+++++++----
Mumtool/report-to-video/trailer.mjs | 15++++++++++++++-
81 files changed, 5356 insertions(+), 213 deletions(-)

diff --git a/AGENTS.md b/AGENTS.md @@ -76,8 +76,31 @@ MemorySwapMax 2G) unless it carries its own cap or its caller already sits under units, a capped scope); `HEAVY_CAP=0` turns that off. Bypasses: `HEAVY=0`, `HEAVY_MIN_FREE_MB=<MB>`, `HEAVY_TIMEOUT=<seconds>`. -See [WORKTREES.md](WORKTREES.md) for the port scheme, the queue, the heavy slot, and the -shared-data caveat. +# Render mode + +**When the operator is waiting for a render, give it the machine — from any session:** + +```sh +umtool take <project> --id <take> … --priority # for that take's lifetime +umtool render-mode on [--for 90m] [--note "…"] # a window, for a chain of renders (default 2h) +umtool render-mode status | off +pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same with only pnpm ops; get render-mode +``` + +While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other +renders) waits at the heavy slot's door — `queue-lock: held for a render (umtool take <p> --id +<t>, since 13:31) — waiting` is the gate working — while the render runs on the floor 4000 MB +and the cap 10240 MB; the editor's transcription and download lanes are held (only the ones +not already held; only those are released). It turns itself off: at the take's end, failure +or signal, at the window's `until`, or when its process is gone (the editor's heartbeat +releases the lanes). Then tell the operator to **close Firefox and other heavy apps**, and +put the render before any merge or ship it does not need. A job already running is not +stopped — do not start e2e or builds yourself meanwhile. The umtool take panel's **Give +renders the machine** toggle is the same `--priority`; `/jobs` and the take panel show a +banner. `RENDER_PRIORITY=0` runs a job anyway. Details: WORKTREES.md, "Render mode". + +See [WORKTREES.md](WORKTREES.md) for the port scheme, the queue, the heavy slot, render mode, +and the shared-data caveat. # Working this repo with no local corpus diff --git a/COMMANDS.md b/COMMANDS.md @@ -146,6 +146,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "&lt;id&gt;"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` | | `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` | | `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` | +| `render-mode` | render-mode gives a render the operator is waiting for the machine: {"on": true, "for"?: "90m" \| &lt;minutes&gt;, "note"?} opens a window (default 2h) in which every other heavy job — e2e suites, next builds, the publish stages, other renders — waits at the heavy slot's door, and holds the transcription and download lanes (only the ones not already held; only those are released). The answer's "join" (RENDER\_PRIORITY\_TOKEN=…) lets a render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take` joins by itself. {"on": false} ends it ("force": true ends a running take's hold, which otherwise ends with the take). `umtool take … --priority` is the same for one take. `get render-mode` says whether it is on, for what, since when, which lanes it holds. Close Firefox and other heavy apps while it renders. | `pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'`<br>`pnpm ops render-mode --json '{"on":false}'` | | `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "&lt;id&gt;"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` | | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | | `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -133,6 +133,9 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `HEAVY_CAP` | on | An admitted `pnpm heavy` / `queue-lock --heavy` command runs in a memory-capped systemd user scope of its own (`systemd-run --user --scope`, MemoryMax + MemorySwapMax, never MemoryHigh), so a runaway dies in its scope instead of taking the session down. Not wrapped when the command carries its own `MemoryMax=`, when the caller already sits under a finite memory.max (the live units, a capped scope, a container), or with no `systemd-run`. `0` turns it off. | scripts/queue-lock.mjs | | `HEAVY_CAP_MB` | `8192` | The heavy cap's MemoryMax in MB; a larger `--estimate` raises it to the estimate. The cap never changes admission: an undeclared job still runs alone. | scripts/queue-lock.mjs | | `HEAVY_CAP_SWAP_MB` | `2048` | The heavy cap's MemorySwapMax in MB. | scripts/queue-lock.mjs | +| `RENDER_PRIORITY` | on | `0` runs a heavy job without waiting for render mode: while a render the operator waits for holds the machine (`umtool take … --priority`, `umtool render-mode on`, `pnpm ops render-mode`), every other heavy job — e2e suites, `next build`s, the publish stages, other renders — waits at the heavy slot's door. For an emergency; `HEAVY=0` skips the wait too. AGENTS.md "Render mode". | scripts/queue-lock.mjs (common/lib/renderPriority.mjs) | +| `RENDER_PRIORITY_TOKEN` | — | The render-mode hold a heavy job belongs to: a job carrying the hold's token is the render (admitted while the others wait, on the floor 4000 MB and the cap 10240 MB unless `HEAVY_MIN_FREE_MB` / `HEAVY_CAP_MB` say). `umtool take` sets it for its render; `umtool render-mode on` and `pnpm ops render-mode` print it for another command to join. | scripts/queue-lock.mjs (common/lib/renderPriority.mjs) | +| `RENDER_PRIORITY_FILE` | `<heavy lock>.render.json` | Render mode's state file — by default beside the heavy slot's lock (`HEAVY_LOCK_FILE`, else `<git common dir>/heavy-queue.lock`), so one per machine. The e2e servers and the tests point it at their own. | common/lib/renderPriority.mjs | | `HEAVY_TIMEOUT` | wait forever | Seconds a `pnpm heavy` run waits for the slot, and then for the floor, before giving up (exit 3). An e2e run uses `E2E_QUEUE_TIMEOUT` for both. | scripts/queue-lock.mjs | ## Ports diff --git a/WORKTREES.md b/WORKTREES.md @@ -278,6 +278,7 @@ alone — it is a safety net, not a correctness lock. | `HEAVY=0` | Skip the heavy slot AND the memory floor | | `HEAVY_MIN_FREE_MB=<MB>` | Move the floor (`0` turns it off; the build rule still holds) | | `HEAVY_TIMEOUT=<seconds>` | Give up waiting (line, slot, memory) after N seconds; an e2e run uses `E2E_QUEUE_TIMEOUT` | +| `RENDER_PRIORITY=0` | Do not wait for a render in render mode (below) | | `HEAVY_CAP=0` | Run a `--heavy` command without the default memory cap | | `HEAVY_CAP_MB=<MB>` / `HEAVY_CAP_SWAP_MB=<MB>` | Size the cap (8192 / 2048) | | `UMTOOL_RENDER_ESTIMATE_MB=<MB>` | What a render declares (`0`: nothing — it runs alone) | @@ -339,21 +340,46 @@ counts the browser (it measured the whole process tree); the cap cannot. render to finish as before. A build that declares (`systemd-run … -p MemoryMax=5G … next build`, or `--build`) is the one that runs beside a render. -### A render and the transcription lane +### Render mode: a render the operator waits for gets the machine -A render competes with the transcription lane for memory and CPU, and the lane is not a heavy -slot holder. -Hold the lane for the render's duration, and release it whatever the render's outcome: +The slot admits by memory. A render someone is watching is slowed by **CPU** instead — +measured 2026-10-30, the render peaked under 1 GB in its scope while cutting and about 200 MB +per Chromium worker while capturing, and what dragged it was parakeet ASR from the +transcription lane, the editor, and e2e servers and browsers beside it. **Render mode** +(`common/lib/renderPriority.mjs`) gives that render the machine: ```sh -pnpm ops lane --json '{"lane":"transcription","held":true}' -node umtool/report-to-video/build-video.mjs <manifest> … ; \ - pnpm ops lane --json '{"lane":"transcription","held":false}' +umtool take <project> --id <take> … --priority # for this take's lifetime (on at start; off at end, failure, signal) +umtool render-mode on [--for 90m] [--note …] # a window for a chain of renders (default 2h) +umtool render-mode status | off [--force] +pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same from a session with only pnpm ops +pnpm ops get render-mode ``` -A hold stops new dispatches, not a transcription already running; and the release -resumes the lane even if someone else held it for another reason — check `/operations` -first. +While it is on: + +- **every other heavy job waits at the door** — e2e suites, `next build`s, the publish + stages, other renders: `queue-lock: held for a render (umtool take <p> --id <t>, since + 13:31) — waiting`. It waits *before* the line, so it never holds the line the render is + admitted through. A job already admitted is not stopped; a nested one (`HEAVY_HELD`) + passes as before; a live stream's sniff (`--urgent`) never waits. +- **the render is admitted**: it and everything under it carry the hold's token + (`RENDER_PRIORITY_TOKEN`), on the floor **4000 MB** and the cap **10240 MB** unless + `HEAVY_MIN_FREE_MB` / `HEAVY_CAP_MB` say otherwise. Every `umtool take` started inside a + manual window joins it; another command joins with the token `on` prints. +- **the editor's transcription and download lanes are held** — only the ones not already + held, and only those are released at the end (a hold someone else made stays). With no + editor to ask, render mode still holds the door and says the lanes were not held. +- the umtool take panel and the editor's `/jobs` show a banner; **close Firefox and other + heavy apps** while it renders. + +The state is one file beside the slot's lock, `<git common dir>/heavy-queue.lock.render.json` +(`{token, since, until, by, note, holder: {pid, cmd, project, take}, lanesHeld, +lanesSkipped, editor}`). **A crash leaves no hold:** a holder pid that is gone (or reused), +or an `until` in the past, is not held — the gate ignores it at once — and its lanes are +released by the editor's heartbeat, `/jobs`'s End button, or the next `umtool render-mode +status`/`on`. `RENDER_PRIORITY=0` runs a job anyway (an emergency); `HEAVY=0` skips the +wait with everything else. ## Data directories diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -470,7 +470,9 @@ export const sniffLivePlaylist: LiveSniffer = async ({ paths, pageUrl, onLog, si if (!xvfb) onLog("xvfb-run is not installed: the page is opened headless, which Rumble's Cloudflare refuses.\n"); const gate = path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs"); const gated = await stat(gate).then((s) => s.isFile(), () => false); - const [bin, ...args] = gated ? [process.execPath, gate, "--heavy", "--estimate", "1000", "--", ...inner] : inner; + // --urgent: a stream does not wait for a render in render mode — a few + // seconds of browser now, or the recording misses its start. + const [bin, ...args] = gated ? [process.execPath, gate, "--heavy", "--estimate", "1000", "--urgent", "--", ...inner] : inner; onLog(`Opening ${pageUrl} in a browser for its playlist${gated ? " (the heavy slot)" : ""}.\n`); const r = await execa(bin!, args, { reject: false, cancelSignal: signal, cwd: paths.monorepoRoot }); const line = String(r.stdout).trim().split("\n").filter((l) => l.startsWith("{")).pop(); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -169,6 +169,9 @@ const DECLARED: EnvVarDecl[] = [ { name: "HEAVY_CAP", audience: "runtime", default: "on", readBy: "scripts/queue-lock.mjs", doc: "An admitted `pnpm heavy` / `queue-lock --heavy` command runs in a memory-capped systemd user scope of its own (`systemd-run --user --scope`, MemoryMax + MemorySwapMax, never MemoryHigh), so a runaway dies in its scope instead of taking the session down. Not wrapped when the command carries its own `MemoryMax=`, when the caller already sits under a finite memory.max (the live units, a capped scope, a container), or with no `systemd-run`. `0` turns it off." }, { name: "HEAVY_CAP_MB", audience: "runtime", default: "`8192`", readBy: "scripts/queue-lock.mjs", doc: "The heavy cap's MemoryMax in MB; a larger `--estimate` raises it to the estimate. The cap never changes admission: an undeclared job still runs alone." }, { name: "HEAVY_CAP_SWAP_MB", audience: "runtime", default: "`2048`", readBy: "scripts/queue-lock.mjs", doc: "The heavy cap's MemorySwapMax in MB." }, + { name: "RENDER_PRIORITY", audience: "runtime", default: "on", readBy: "scripts/queue-lock.mjs (common/lib/renderPriority.mjs)", doc: "`0` runs a heavy job without waiting for render mode: while a render the operator waits for holds the machine (`umtool take … --priority`, `umtool render-mode on`, `pnpm ops render-mode`), every other heavy job — e2e suites, `next build`s, the publish stages, other renders — waits at the heavy slot's door. For an emergency; `HEAVY=0` skips the wait too. AGENTS.md \"Render mode\"." }, + { name: "RENDER_PRIORITY_TOKEN", audience: "runtime", default: "—", readBy: "scripts/queue-lock.mjs (common/lib/renderPriority.mjs)", doc: "The render-mode hold a heavy job belongs to: a job carrying the hold's token is the render (admitted while the others wait, on the floor 4000 MB and the cap 10240 MB unless `HEAVY_MIN_FREE_MB` / `HEAVY_CAP_MB` say). `umtool take` sets it for its render; `umtool render-mode on` and `pnpm ops render-mode` print it for another command to join." }, + { name: "RENDER_PRIORITY_FILE", audience: "runtime", default: "`<heavy lock>.render.json`", readBy: "common/lib/renderPriority.mjs", doc: "Render mode's state file — by default beside the heavy slot's lock (`HEAVY_LOCK_FILE`, else `<git common dir>/heavy-queue.lock`), so one per machine. The e2e servers and the tests point it at their own." }, { name: "HEAVY_TIMEOUT", audience: "runtime", default: "wait forever", readBy: "scripts/queue-lock.mjs", doc: "Seconds a `pnpm heavy` run waits for the slot, and then for the floor, before giving up (exit 3). An e2e run uses `E2E_QUEUE_TIMEOUT` for both." }, // ── internal: the pipeline sets these for a process it spawns ────────── diff --git a/common/lib/renderPriority.mjs b/common/lib/renderPriority.mjs @@ -0,0 +1,452 @@ +// RENDER MODE — a render the operator is waiting for gets the machine. +// +// The heavy slot (scripts/queue-lock.mjs) admits by MEMORY. A render the +// operator is watching is slowed by CPU, not memory: measured 2026-10-30, the +// render peaked under 1 GB in its scope while cutting and ~200 MB per Chromium +// worker while capturing, and what dragged it was parakeet ASR from the +// transcription lane, the editor, and e2e servers and browsers beside it. So +// render mode is a machine-global flag, one small JSON file, that: +// +// - makes every OTHER heavy job wait at the slot's door (queue-lock.mjs +// withHeavy: e2e suites, `next build`s, the publish stages, other renders) +// with `queue-lock: held for a render (umtool take <p> --id <t>, since +// 13:31) — waiting`; a job carrying the hold's token (the render and its +// subprocesses: RENDER_PRIORITY_TOKEN) is admitted, with the floor 4000 MB +// and the cap 10240 MB unless HEAVY_MIN_FREE_MB / HEAVY_CAP_MB say +// otherwise; +// - holds the editor's transcription and download lanes, remembering which +// ones IT held (`lanesHeld`), so ending it releases only those — a lane +// someone else held before stays held. +// +// Turned on by `umtool take … --priority` (for the take's lifetime), +// `umtool render-mode on [--for 90m]` (a window, e.g. a chain of renders) or +// `pnpm ops render-mode {"on": true}`; AGENTS.md "Render mode". +// +// THE FILE sits beside the heavy slot's lock: `<heavy lock>.render.json`, i.e. +// `<git common dir>/heavy-queue.lock.render.json` on this machine (one for +// every worktree), beside a HEAVY_LOCK_FILE when one is set (so the gate's +// tests have their own), or wherever RENDER_PRIORITY_FILE says. Its shape: +// +// { version: 1, token, since, until | null, by, note | null, +// holder: { pid, pidStart, cmd, project, take } | null, +// lanesHeld: ["transcription", …], lanesSkipped: [...], editor | null } +// +// LIVENESS, so a crash never leaves a hold: a holder whose pid is gone (or +// reused: pidStart), or an `until` in the past, is NOT held — queue-lock +// ignores it at once. Its lanes are released by whoever next looks with an +// editor in hand (`reapRenderMode`: the editor's heartbeat, /jobs, `render-mode +// status`, the next `on`). A manual window always carries an `until` (2 h by +// default), so a forgotten one ends by itself. +// +// Plain JS with JSDoc, no dependencies: queue-lock.mjs runs it under bare node, +// umtool's CLI and app and the editor import it as it is. + +import { execFileSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +/** The memory floor a render in render mode is admitted on, absent HEAVY_MIN_FREE_MB. */ +export const RENDER_PRIORITY_FLOOR_MB = 4000; +/** The render's heavy cap (MemoryMax) in render mode, absent HEAVY_CAP_MB. */ +export const RENDER_PRIORITY_CAP_MB = 10240; +/** The editor lanes render mode holds. */ +export const RENDER_MODE_LANES = Object.freeze(["transcription", "download"]); +/** A manual window with no --for ends after this. */ +export const DEFAULT_RENDER_MODE_WINDOW_MS = 2 * 60 * 60 * 1000; +/** The env var a render (and everything under it) carries the hold's token in. */ +export const RENDER_PRIORITY_TOKEN_ENV = "RENDER_PRIORITY_TOKEN"; +/** The one line said to the operator when render mode goes on. */ +export const RENDER_MODE_REMINDER = "close Firefox and other heavy apps while this renders"; + +const HEAVY_LOCK_NAME = "heavy-queue.lock"; +const STATE_SUFFIX = ".render.json"; + +/** + * @typedef {{ pid: number, pidStart?: string | null, cmd?: string | null, project?: string | null, take?: string | null }} RenderHolder + * @typedef {{ + * version: 1, token: string, since: string, until: string | null, by: string | null, note: string | null, + * holder: RenderHolder | null, lanesHeld: string[], lanesSkipped?: string[], lanesError?: string | null, + * editor?: string | null, ended?: boolean, + * }} RenderPriorityState + * @typedef {{ held: boolean, state: RenderPriorityState | null, stale: null | "expired" | "holder-gone" | "no-end" }} RenderPriorityStatus + * @typedef {{ isHeld: (lane: string) => Promise<boolean>, hold: (lane: string) => Promise<void>, release: (lane: string) => Promise<void> }} RenderModeLanes + */ + +// ---------------------------------------------------------------- the file + +/** The git common dir of `cwd` (one for every worktree), or null. */ +function gitCommonDir(cwd) { + try { + const out = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); + return out || null; + } catch { + return null; + } +} + +/** + * Where render mode's state lives: RENDER_PRIORITY_FILE; else beside the heavy + * slot's lock — `heavyLock` (queue-lock hands its own), HEAVY_LOCK_FILE, or the + * one in the git common dir of `root` (default: the cwd; a CLI run from a + * report workspace passes its checkout) — as queue-lock.mjs finds it, a tmpdir + * outside a git checkout (a container). + * @param {Record<string, string | undefined>} [env] + * @param {{ heavyLock?: string | null, root?: string }} [opts] + */ +export function renderPriorityFile(env = process.env, { heavyLock = null, root = process.cwd() } = {}) { + if (env.RENDER_PRIORITY_FILE) return env.RENDER_PRIORITY_FILE; + const lock = + heavyLock ?? + env.HEAVY_LOCK_FILE ?? + path.join(/* turbopackIgnore: true */ gitCommonDir(root) ?? os.tmpdir(), HEAVY_LOCK_NAME); + return `${lock}${STATE_SUFFIX}`; +} + +/** The file's JSON, or null (missing, half-written, not ours). */ +export function readRenderPriorityState(file) { + try { + const s = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ file, "utf8")); + return s && typeof s === "object" && typeof s.token === "string" ? /** @type {RenderPriorityState} */ (s) : null; + } catch { + return null; + } +} + +/** tmp + rename, so a reader never sees half a file. */ +function writeState(file, state) { + fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`; + fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`); + fs.renameSync(tmp, file); +} + +/** + * Create the file only if there is none: a hard link of a written temp file + * fails with EEXIST when another hold got there first, so two `on`s at once + * cannot both win. True when created. + */ +function createState(file, state) { + fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`; + fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`); + try { + fs.linkSync(tmp, file); + return true; + } catch (err) { + if (/** @type {NodeJS.ErrnoException} */ (err).code === "EEXIST") return false; + throw err; + } finally { + fs.rmSync(/* turbopackIgnore: true */ tmp, { force: true }); + } +} + +/** Remove the file only while it is still the hold `token` names. */ +function removeIfToken(file, token) { + const cur = readRenderPriorityState(file); + if (cur && cur.token !== token) return false; + fs.rmSync(/* turbopackIgnore: true */ file, { force: true }); + return true; +} + +// ---------------------------------------------------------------- liveness + +/** /proc/<pid>/stat's start time (field 22), so a reused pid is not the holder. Null off Linux. */ +export function pidStartTime(pid) { + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); + return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null; + } catch { + return null; + } +} + +/** Whether the holder's process is still the one that took the hold. */ +export function holderAlive(holder) { + if (!holder || !Number.isInteger(holder.pid)) return false; + try { + process.kill(holder.pid, 0); + } catch (err) { + if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EPERM") return false; + } + return holder.pidStart == null || pidStartTime(holder.pid) === holder.pidStart; +} + +/** + * Whether a state is a hold now, pure but for `isAlive`. A holder pid that is + * gone, an `until` in the past, or a state with neither (a hold nothing would + * ever end) is not held — `stale` says which. + * @param {RenderPriorityState | null} state + * @param {{ now?: number, isAlive?: (h: RenderHolder) => boolean }} [opts] + * @returns {RenderPriorityStatus} + */ +export function renderPriorityStatus(state, { now = Date.now(), isAlive = holderAlive } = {}) { + if (!state) return { held: false, state: null, stale: null }; + const untilMs = state.until ? Date.parse(state.until) : NaN; + if (Number.isFinite(untilMs) && untilMs <= now) return { held: false, state, stale: "expired" }; + if (state.holder && state.holder.pid != null) { + if (!isAlive(state.holder)) return { held: false, state, stale: "holder-gone" }; + } else if (!Number.isFinite(untilMs)) { + return { held: false, state, stale: "no-end" }; + } + return { held: true, state, stale: null }; +} + +/** + * Render mode as it stands: `{held, state, stale}`. + * @param {string} file + * @param {{ now?: number, isAlive?: (h: RenderHolder) => boolean }} [opts] + */ +export function readRenderPriority(file, opts = {}) { + return renderPriorityStatus(readRenderPriorityState(file), opts); +} + +// ------------------------------------------------------- what the gate asks + +/** + * Whether render mode makes a heavy job wait: it is held, the job does not + * carry its token, and nobody said RENDER_PRIORITY=0. `urgent` (a live + * stream's few seconds of browser) never waits. + * @param {RenderPriorityStatus} status + * @param {Record<string, string | undefined>} [env] + * @param {{ urgent?: boolean }} [opts] + */ +export function renderPriorityBlocks(status, env = process.env, { urgent = false } = {}) { + if (!status?.held || !status.state || urgent || env.RENDER_PRIORITY === "0") return false; + return env[RENDER_PRIORITY_TOKEN_ENV] !== status.state.token; +} + +/** Whether `env` carries the token of the hold `status` names (the render itself). */ +export function carriesRenderPriority(status, env = process.env) { + return Boolean(status?.held && status.state && env[RENDER_PRIORITY_TOKEN_ENV] === status.state.token); +} + +/** + * The render's own defaults, into `env` where it leaves them unset: the floor + * 4000 MB, the cap 10240 MB. Returns the names it set. + * @param {Record<string, string | undefined>} env + */ +export function applyRenderPriorityDefaults(env) { + const set = []; + if (env.HEAVY_MIN_FREE_MB == null || env.HEAVY_MIN_FREE_MB === "") { + env.HEAVY_MIN_FREE_MB = String(RENDER_PRIORITY_FLOOR_MB); + set.push("HEAVY_MIN_FREE_MB"); + } + if (env.HEAVY_CAP_MB == null || env.HEAVY_CAP_MB === "") { + env.HEAVY_CAP_MB = String(RENDER_PRIORITY_CAP_MB); + set.push("HEAVY_CAP_MB"); + } + return set; +} + +/** "13:31", local time, or "?". */ +export function clockOf(iso) { + const ms = Date.parse(String(iso ?? "")); + if (!Number.isFinite(ms)) return "?"; + const d = new Date(ms); + return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; +} + +/** + * What the hold is, in a waiter's words: "umtool take <p> --id <t>, since + * 13:31" or "render mode on (by umtool) — a chain, since 13:31, until 15:31". + * @param {RenderPriorityState} state + */ +export function describeRenderPriority(state) { + const h = state.holder; + const what = h?.cmd + ? String(h.cmd).slice(0, 100) + : h?.project + ? `umtool take ${h.project}${h.take ? ` --id ${h.take}` : ""}` + : h + ? `pid ${h.pid}` + : `render mode on${state.by ? ` (by ${state.by})` : ""}`; + const note = state.note ? ` — ${state.note}` : ""; + const until = state.until ? `, until ${clockOf(state.until)}` : ""; + return `${what}${note}, since ${clockOf(state.since)}${until}`; +} + +// ------------------------------------------------------------ on and off + +/** + * "90m", "2h", "1h30m", "45s", or a number of minutes -> ms; null when it is + * none of those. + * @param {unknown} v + */ +export function parseDurationMs(v) { + if (typeof v === "number") return Number.isFinite(v) && v > 0 ? Math.round(v * 60_000) : null; + const s = String(v ?? "").trim().toLowerCase(); + if (/^\d+(\.\d+)?$/.test(s)) return parseDurationMs(Number(s)); + const m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m)?(?:(\d+(?:\.\d+)?)s)?$/.exec(s); + if (!s || !m || (!m[1] && !m[2] && !m[3])) return null; + const ms = (Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0)) * 1000; + return ms > 0 ? Math.round(ms) : null; +} + +/** + * Release each of `lanes` through the editor; the ones that would not be. + * @param {string[]} names + * @param {RenderModeLanes | null} lanes + */ +async function releaseLanes(names, lanes) { + const released = []; + const failed = []; + for (const lane of names ?? []) { + if (!lanes) { + failed.push({ lane, error: "no editor to release it through" }); + continue; + } + try { + await lanes.release(lane); + released.push(lane); + } catch (err) { + failed.push({ lane, error: err instanceof Error ? err.message : String(err) }); + } + } + return { released, failed }; +} + +/** + * Turn render mode on. `holder` is the render's process (`umtool take + * --priority`: the hold ends with it); null is a manual window, which ends at + * `forMs` (default 2 h). A hold already on is NOT taken over: `{ok: false, + * held}`. A stale one is ended first (its lanes released). Then each of + * RENDER_MODE_LANES the editor does not already hold is held, and recorded as + * ours — the record is written after each, so a crash never forgets one. + * + * @param {{ file: string, holder?: RenderHolder | null, forMs?: number | null, note?: string | null, + * by?: string | null, editor?: string | null, lanes?: RenderModeLanes | null, now?: () => number, + * isAlive?: (h: RenderHolder) => boolean, token?: string }} o + */ +export async function renderModeOn({ + file, + holder = null, + forMs = null, + note = null, + by = null, + editor = null, + lanes = null, + now = Date.now, + isAlive = holderAlive, + token = randomBytes(8).toString("hex"), +}) { + let reaped = null; + for (let attempt = 0; attempt < 3; attempt += 1) { + const cur = readRenderPriority(file, { now: now(), isAlive }); + if (cur.held && cur.state) return { ok: false, held: cur.state, reaped }; + // A stale hold is ended first. A lane it could not release (no editor + // answering) is still render mode's: this hold inherits it, to release at + // its own end, rather than leave a record nothing will ever clear. + let inherited = []; + if (cur.state) { + reaped = await renderModeOff({ file, token: cur.state.token, lanes }); + inherited = reaped.failed.map((f) => f.lane); + if (inherited.length) removeIfToken(file, cur.state.token); + } + const t = now(); + const ms = forMs ?? (holder ? null : DEFAULT_RENDER_MODE_WINDOW_MS); + /** @type {RenderPriorityState} */ + const state = { + version: 1, + token, + since: new Date(t).toISOString(), + until: ms ? new Date(t + ms).toISOString() : null, + by, + note: note ? String(note).slice(0, 200) : null, + holder: holder ? { pidStart: pidStartTime(holder.pid), ...holder } : null, + lanesHeld: [...inherited], + lanesSkipped: [], + editor, + }; + if (!createState(file, state)) continue; // another `on` won the race: look again + const failed = []; + for (const lane of lanes ? RENDER_MODE_LANES : []) { + if (state.lanesHeld.includes(lane)) continue; // inherited: ours already + try { + if (await /** @type {RenderModeLanes} */ (lanes).isHeld(lane)) { + state.lanesSkipped?.push(lane); // someone else's hold: never ours to release + } else { + await /** @type {RenderModeLanes} */ (lanes).hold(lane); + state.lanesHeld.push(lane); + } + } catch (err) { + failed.push(`${lane}: ${err instanceof Error ? err.message : String(err)}`); + } + writeState(file, state); + } + if (!lanes) state.lanesError = "no editor: the lanes were not held"; + else if (failed.length) state.lanesError = failed.join("; "); + writeState(file, state); + return { ok: true, state, reaped }; + } + const cur = readRenderPriority(file, { now: now(), isAlive }); + return { ok: false, held: cur.state, reaped }; +} + +/** + * Turn render mode off: release the lanes IT held (only those), then remove + * the file. `token` names the hold being ended — a different one is left alone + * (`{ok: false, notOurs}`) unless `force`. A lane the editor would not release + * keeps the record, ended (`until` now, no holder): not a hold any more, and + * the next reaper with an editor releases it. + * + * @param {{ file: string, token?: string | null, lanes?: RenderModeLanes | null, force?: boolean, now?: () => number }} o + */ +export async function renderModeOff({ file, token = null, lanes = null, force = false, now = Date.now }) { + const state = readRenderPriorityState(file); + if (!state) return { ok: true, was: null, released: [], failed: [] }; + if (token && state.token !== token && !force) return { ok: false, notOurs: state, released: [], failed: [] }; + const { released, failed } = await releaseLanes(state.lanesHeld, lanes); + if (failed.length) { + const cur = readRenderPriorityState(file); + if (!cur || cur.token === state.token) { + writeState(file, { + ...state, + holder: null, + until: new Date(now()).toISOString(), + ended: true, + lanesHeld: failed.map((f) => f.lane), + lanesError: failed.map((f) => `${f.lane}: ${f.error}`).join("; "), + }); + } + } else { + removeIfToken(file, state.token); + } + return { ok: true, was: state, released, failed }; +} + +/** + * End a hold that is no longer one (its holder gone, its window over): its + * lanes released, its file removed. Null when there is nothing stale. Called + * by whoever has an editor to release through. `owns(state)`, when given, says + * whether the lanes it records are that editor's (its `editor`): another + * editor's stale hold is left for that one. + * @param {{ file: string, lanes: RenderModeLanes | null, now?: () => number, isAlive?: (h: RenderHolder) => boolean, owns?: (s: RenderPriorityState) => boolean }} o + */ +export async function reapRenderMode({ file, lanes, now = Date.now, isAlive = holderAlive, owns }) { + const s = readRenderPriority(file, { now: now(), isAlive }); + if (!s.state || s.held) return null; + if (owns && s.state.lanesHeld?.length && !owns(s.state)) return null; + return renderModeOff({ file, token: s.state.token, lanes, now }); +} + +/** + * Whether an `editor` a hold records (the URL its lanes were held through) is + * the editor listening on `port` here: a loopback host and that port. + * @param {string | null | undefined} editor + * @param {string | number} port + */ +export function isLocalEditor(editor, port) { + try { + const u = new URL(String(editor ?? "")); + const host = u.hostname.replace(/^\[|\]$/g, ""); + const p = u.port || (u.protocol === "https:" ? "443" : "80"); + return ["localhost", "127.0.0.1", "::1", "0.0.0.0"].includes(host) && p === String(port); + } catch { + return false; + } +} diff --git a/common/lib/renderPriority.test.ts b/common/lib/renderPriority.test.ts @@ -0,0 +1,240 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { + DEFAULT_RENDER_MODE_WINDOW_MS, + RENDER_PRIORITY_TOKEN_ENV, + applyRenderPriorityDefaults, + carriesRenderPriority, + describeRenderPriority, + holderAlive, + isLocalEditor, + parseDurationMs, + readRenderPriority, + readRenderPriorityState, + reapRenderMode, + renderModeOff, + renderModeOn, + renderPriorityBlocks, + renderPriorityFile, + renderPriorityStatus, + type RenderModeLanes, + type RenderPriorityState, +} from "./renderPriority.mjs"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common test +// +// Render mode's state file and its lanes, all against temp files and a fake +// editor — nothing here touches the machine's state or a live editor's lanes. + +function tmpFile() { + return path.join(mkdtempSync(path.join(os.tmpdir(), "render-priority-")), "heavy.lock.render.json"); +} + +/** A fake editor's lanes: `held` is what it holds; `calls` what was asked. */ +function fakeLanes(held: Record<string, boolean> = {}, { failRelease = false } = {}) { + const calls: string[] = []; + const lanes: RenderModeLanes = { + async isHeld(lane) { + return held[lane] === true; + }, + async hold(lane) { + calls.push(`hold ${lane}`); + held[lane] = true; + }, + async release(lane) { + calls.push(`release ${lane}`); + if (failRelease) throw new Error("editor gone"); + held[lane] = false; + }, + }; + return { lanes, held, calls }; +} + +function state(over: Partial<RenderPriorityState> = {}): RenderPriorityState { + return { + version: 1, + token: "tok", + since: new Date(0).toISOString(), + until: null, + by: null, + note: null, + holder: null, + lanesHeld: [], + ...over, + }; +} + +test("renderPriorityFile: RENDER_PRIORITY_FILE, else beside the heavy slot's lock", () => { + assert.equal(renderPriorityFile({ RENDER_PRIORITY_FILE: "/x/state.json", HEAVY_LOCK_FILE: "/y/heavy.lock" }), "/x/state.json"); + assert.equal(renderPriorityFile({ HEAVY_LOCK_FILE: "/y/heavy.lock" }), "/y/heavy.lock.render.json"); + assert.equal(renderPriorityFile({}, { heavyLock: "/z/heavy-queue.lock" }), "/z/heavy-queue.lock.render.json"); + // A git checkout: its common dir, the heavy lock's own place. + assert.match(renderPriorityFile({}, { root: process.cwd() }), /heavy-queue\.lock\.render\.json$/); +}); + +test("liveness: a gone holder, a past until, or no end at all is not a hold", () => { + const now = Date.parse("2026-10-30T12:00:00Z"); + const alive = () => true; + const dead = () => false; + assert.deepEqual(renderPriorityStatus(null), { held: false, state: null, stale: null }); + const take = state({ holder: { pid: 123 } }); + assert.equal(renderPriorityStatus(take, { now, isAlive: alive }).held, true); + assert.equal(renderPriorityStatus(take, { now, isAlive: dead }).stale, "holder-gone"); + const window = state({ until: "2026-10-30T13:00:00Z" }); + assert.equal(renderPriorityStatus(window, { now, isAlive: dead }).held, true); + assert.equal(renderPriorityStatus(window, { now: Date.parse("2026-10-30T13:00:01Z") }).stale, "expired"); + // A take's hold with an until past it is over too, holder or not. + assert.equal(renderPriorityStatus(state({ holder: { pid: 1 }, until: "2026-10-30T11:00:00Z" }), { now, isAlive: alive }).stale, "expired"); + assert.equal(renderPriorityStatus(state(), { now }).stale, "no-end"); +}); + +test("holderAlive: this process is; a dead pid, or a live pid that started at another time, is not", async () => { + assert.equal(holderAlive({ pid: process.pid }), true); + assert.equal(holderAlive({ pid: process.pid, pidStart: "not-its-start" }), os.platform() !== "linux"); + const child = spawn(process.execPath, ["-e", ""]); + const pid = child.pid as number; + await new Promise((r) => child.on("exit", r)); + assert.equal(holderAlive({ pid }), false); +}); + +test("the gate's question: held, the token not carried, no bypass", () => { + const held = { held: true, state: state(), stale: null } as const; + assert.equal(renderPriorityBlocks(held, {}), true); + assert.equal(renderPriorityBlocks(held, { [RENDER_PRIORITY_TOKEN_ENV]: "tok" }), false); + assert.equal(renderPriorityBlocks(held, { [RENDER_PRIORITY_TOKEN_ENV]: "other" }), true); + assert.equal(renderPriorityBlocks(held, { RENDER_PRIORITY: "0" }), false); + assert.equal(renderPriorityBlocks(held, {}, { urgent: true }), false); + assert.equal(renderPriorityBlocks({ held: false, state: state(), stale: "expired" }, {}), false); + assert.equal(carriesRenderPriority(held, { [RENDER_PRIORITY_TOKEN_ENV]: "tok" }), true); + assert.equal(carriesRenderPriority(held, {}), false); +}); + +test("the render's own defaults fill only what the environment leaves unset", () => { + const env: Record<string, string | undefined> = { HEAVY_CAP_MB: "9000" }; + assert.deepEqual(applyRenderPriorityDefaults(env), ["HEAVY_MIN_FREE_MB"]); + assert.equal(env.HEAVY_MIN_FREE_MB, "4000"); + assert.equal(env.HEAVY_CAP_MB, "9000"); + const bare: Record<string, string | undefined> = {}; + applyRenderPriorityDefaults(bare); + assert.deepEqual(bare, { HEAVY_MIN_FREE_MB: "4000", HEAVY_CAP_MB: "10240" }); +}); + +test("describeRenderPriority and parseDurationMs", () => { + assert.match(describeRenderPriority(state({ holder: { pid: 1, cmd: "umtool take ember --id t1" } })), /^umtool take ember --id t1, since \d\d:\d\d$/); + assert.match(describeRenderPriority(state({ by: "umtool render-mode", note: "a chain", until: new Date(0).toISOString() })), /^render mode on \(by umtool render-mode\) — a chain, since \d\d:\d\d, until \d\d:\d\d$/); + assert.equal(parseDurationMs("90m"), 90 * 60_000); + assert.equal(parseDurationMs("2h"), 2 * 3_600_000); + assert.equal(parseDurationMs("1h30m"), 90 * 60_000); + assert.equal(parseDurationMs("45"), 45 * 60_000); + assert.equal(parseDurationMs(10), 10 * 60_000); + assert.equal(parseDurationMs("soon"), null); + assert.equal(parseDurationMs("0m"), null); + assert.equal(parseDurationMs(""), null); +}); + +test("on holds only the lanes not held already, and off releases only those", async () => { + const file = tmpFile(); + const ed = fakeLanes({ download: true }); // someone else's hold + const on = await renderModeOn({ file, holder: { pid: process.pid, cmd: "umtool take p --id t", project: "p", take: "t" }, lanes: ed.lanes, editor: "http://localhost:3001" }); + assert.equal(on.ok, true); + assert.deepEqual(on.state?.lanesHeld, ["transcription"]); + assert.deepEqual(on.state?.lanesSkipped, ["download"]); + assert.equal(on.state?.until, null); // a take's hold ends with its process + assert.deepEqual(ed.calls, ["hold transcription"]); + const onDisk = readRenderPriorityState(file); + assert.equal(onDisk?.token, on.state?.token); + assert.equal(readRenderPriority(file).held, true); + + // A second `on` does not take it over. + const again = await renderModeOn({ file, lanes: ed.lanes }); + assert.equal(again.ok, false); + assert.equal(again.held?.token, on.state?.token); + + // Another hold's token is not ours to end. + const notOurs = await renderModeOff({ file, token: "someone-else", lanes: ed.lanes }); + assert.equal(notOurs.ok, false); + assert.equal(existsSync(file), true); + + const off = await renderModeOff({ file, token: on.state?.token, lanes: ed.lanes }); + assert.deepEqual(off.released, ["transcription"]); + assert.deepEqual(ed.calls, ["hold transcription", "release transcription"]); + assert.equal(ed.held.download, true, "the hold it found stays"); + assert.equal(existsSync(file), false); +}); + +test("a manual window has an until (2 h by default, or --for); with no editor it still holds the door", async () => { + const file = tmpFile(); + const t0 = Date.parse("2026-10-30T13:31:00Z"); + const on = await renderModeOn({ file, now: () => t0, note: "a chain" }); + assert.equal(on.ok, true); + assert.equal(Date.parse(on.state!.until!) - t0, DEFAULT_RENDER_MODE_WINDOW_MS); + assert.deepEqual(on.state!.lanesHeld, []); + assert.match(on.state!.lanesError ?? "", /no editor/); + assert.equal(readRenderPriority(file, { now: t0 + 60_000 }).held, true); + assert.equal(readRenderPriority(file, { now: t0 + DEFAULT_RENDER_MODE_WINDOW_MS + 1 }).held, false); + await renderModeOff({ file }); + const sized = await renderModeOn({ file, now: () => t0, forMs: 90 * 60_000 }); + assert.equal(Date.parse(sized.state!.until!) - t0, 90 * 60_000); +}); + +test("a stale hold (its render killed) is reaped: its lanes released, its file gone; a live one is left", async () => { + const file = tmpFile(); + const ed = fakeLanes(); + writeFileSync(file, JSON.stringify(state({ holder: { pid: 999_999_999 }, lanesHeld: ["transcription", "download"], editor: "http://localhost:3001" }))); + assert.equal(readRenderPriority(file).stale, "holder-gone"); + // Another editor's stale hold is left for that editor. + assert.equal(await reapRenderMode({ file, lanes: ed.lanes, owns: (s) => isLocalEditor(s.editor, 3101) }), null); + assert.deepEqual(ed.calls, []); + const r = await reapRenderMode({ file, lanes: ed.lanes, owns: (s) => isLocalEditor(s.editor, 3001) }); + assert.deepEqual(r?.released, ["transcription", "download"]); + assert.equal(existsSync(file), false); + + await renderModeOn({ file, holder: { pid: process.pid }, lanes: ed.lanes }); + assert.equal(await reapRenderMode({ file, lanes: ed.lanes }), null); + assert.equal(existsSync(file), true); +}); + +test("a lane the editor would not release stays recorded, ended — and the next hold inherits it", async () => { + const file = tmpFile(); + const broken = fakeLanes({}, { failRelease: true }); + const on = await renderModeOn({ file, holder: { pid: process.pid }, lanes: broken.lanes }); + const off = await renderModeOff({ file, token: on.state!.token, lanes: broken.lanes }); + assert.equal(off.failed.length, 2); + const ended = readRenderPriorityState(file)!; + assert.equal(ended.ended, true); + assert.deepEqual(ended.lanesHeld, ["transcription", "download"]); + assert.equal(readRenderPriority(file).held, false, "not a hold any more: the gate ignores it"); + + // Still no editor: the next `on` takes the lanes over rather than strand them. + const next = await renderModeOn({ file, holder: { pid: process.pid }, lanes: broken.lanes }); + assert.equal(next.ok, true); + assert.deepEqual(next.state!.lanesHeld, ["transcription", "download"]); + // The editor is back: the next off releases them. + const fixed = fakeLanes({ transcription: true, download: true }); + const done = await renderModeOff({ file, token: next.state!.token, lanes: fixed.lanes }); + assert.deepEqual(done.released, ["transcription", "download"]); + assert.equal(existsSync(file), false); +}); + +test("isLocalEditor: a loopback host on that port", () => { + assert.equal(isLocalEditor("http://localhost:3001", 3001), true); + assert.equal(isLocalEditor("http://127.0.0.1:3001/", "3001"), true); + assert.equal(isLocalEditor("http://localhost:3101", 3001), false); + assert.equal(isLocalEditor("https://editor.example:3001", 3001), false); + assert.equal(isLocalEditor(null, 3001), false); +}); + +test("two `on`s at once: one wins, the other is told", async () => { + const file = tmpFile(); + const [a, b] = await Promise.all([ + renderModeOn({ file, holder: { pid: process.pid } }), + renderModeOn({ file, holder: { pid: process.pid } }), + ]); + assert.equal([a.ok, b.ok].filter(Boolean).length, 1); + assert.equal(JSON.parse(readFileSync(file, "utf8")).token, (a.ok ? a : b).state!.token); +}); diff --git a/common/package.json b/common/package.json @@ -48,6 +48,7 @@ "./lib/montage/phraseSource.mjs": "./lib/montage/phraseSource.mjs", "./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs", "./lib/ports.mjs": "./lib/ports.mjs", + "./lib/renderPriority.mjs": "./lib/renderPriority.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", "./lib/report/look.mjs": "./lib/report/look.mjs", "./lib/report/intro.mjs": "./lib/report/intro.mjs", diff --git a/editor/app/api/ops/_renderMode.test.ts b/editor/app/api/ops/_renderMode.test.ts @@ -0,0 +1,87 @@ +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_renderMode.test.ts" +// +// `pnpm ops render-mode` / `get render-mode` against the route handlers, over a +// temp corpus and a temp state file (RENDER_PRIORITY_FILE) — never the +// machine's render mode, never the live editor's lanes. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { callGet, callPost, setupOpsCorpus } from "./_testCorpus"; + +const corpus = await setupOpsCorpus(null); +const STATE = path.join(corpus.root, "render-priority.json"); +process.env.RENDER_PRIORITY_FILE = STATE; +const { GET, POST } = await import("./render-mode/route"); +const { getSettings } = await import("yt-dlp-transcript-common/lib/settings"); +const { getWorkerPool } = await import("yt-dlp-transcript-common/jobs/workerPool"); +const { renderModeReapTick } = await import("../../operations/renderMode"); +test.after(() => corpus.cleanup()); + +const held = (lane: "transcription" | "download") => getSettings().autoQueue[lane].held === true; + +test("on holds the lanes not already held (and says so), off releases only those", async () => { + await corpus.writeSettings({ minFreeDiskGB: 0, autoQueue: { ...getSettings().autoQueue, download: { ...getSettings().autoQueue.download, held: true } } }); + assert.equal(held("download"), true); + assert.equal(held("transcription"), false); + + const on = await callPost(POST!, { on: true, for: "90m", note: "the Ember cut" }); + assert.equal(on.status, 200, JSON.stringify(on.body)); + const state = on.body.state as { token: string; lanesHeld: string[]; lanesSkipped: string[]; until: string; editor: string }; + assert.deepEqual(state.lanesHeld, ["transcription"]); + assert.deepEqual(state.lanesSkipped, ["download"]); + assert.match(String(on.body.join), /^RENDER_PRIORITY_TOKEN=[0-9a-f]{16}$/); + assert.match(state.editor, /^http:\/\/localhost:\d+$/); + assert.equal(held("transcription"), true); + assert.equal(getWorkerPool().isPaused(), true, "the transcription pool's live hold too"); + assert.equal(JSON.parse(readFileSync(STATE, "utf8")).token, state.token); + + const again = await callPost(POST!, { on: true }); + assert.equal(again.status, 409); + assert.match(String(again.body.error), /already on: render mode on \(by pnpm ops render-mode\) — the Ember cut/); + + const got = await callGet(GET!, "http://localhost/api/ops/render-mode"); + assert.equal(got.status, 200); + assert.equal(got.body.held, true); + assert.equal(got.body.token, undefined, "the read side carries no token"); + assert.deepEqual(got.body.lanesHeld, ["transcription"]); + + const off = await callPost(POST!, { on: false }); + assert.equal(off.status, 200, JSON.stringify(off.body)); + assert.deepEqual(off.body.released, ["transcription"]); + assert.equal(held("transcription"), false); + assert.equal(getWorkerPool().isPaused(), false); + assert.equal(held("download"), true, "someone else's hold stays"); + assert.equal(existsSync(STATE), false); +}); + +test("a running take's hold is not ended without force; bad bodies are 400s", async () => { + writeFileSync(STATE, JSON.stringify({ version: 1, token: "take", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "umtool take p --id t" }, lanesHeld: [] })); + const off = await callPost(POST!, { on: false }); + assert.equal(off.status, 409); + assert.match(String(off.body.error), /held by a running render \(umtool take p --id t/); + assert.equal((await callPost(POST!, { on: false, force: true })).status, 200); + assert.equal(existsSync(STATE), false); + assert.equal((await callPost(POST!, {})).status, 400); + assert.equal((await callPost(POST!, { on: true, for: "soon" })).status, 400); + assert.equal((await callPost(POST!, { on: false, note: "x" })).status, 400); + assert.equal((await callPost(POST!, { on: true, lanes: ["x"] })).status, 400); +}); + +test("the heartbeat ends a stale hold this editor made: its lanes released; another editor's is left", async () => { + const port = process.env.EDITOR_PORT || process.env.PORT || "3001"; + await callPost(POST!, { on: true }); + assert.equal(held("transcription"), true); + // Its window over (a killed session's): stale. + const s = JSON.parse(readFileSync(STATE, "utf8")); + writeFileSync(STATE, JSON.stringify({ ...s, until: new Date(Date.now() - 1000).toISOString() })); + await renderModeReapTick(); + assert.equal(held("transcription"), false); + assert.equal(existsSync(STATE), false); + + // Another worktree's editor's stale hold: not this one's lanes to release. + writeFileSync(STATE, JSON.stringify({ ...s, until: new Date(Date.now() - 1000).toISOString(), editor: `http://localhost:${Number(port) + 100}`, lanesHeld: ["download"] })); + await renderModeReapTick(); + assert.equal(existsSync(STATE), true); +}); diff --git a/editor/app/api/ops/render-mode/route.ts b/editor/app/api/ops/render-mode/route.ts @@ -0,0 +1,85 @@ +import { NextResponse } from "next/server"; +import { + RENDER_MODE_REMINDER, + RENDER_PRIORITY_TOKEN_ENV, + describeRenderPriority, + parseDurationMs, + type RenderPriorityState, +} from "yt-dlp-transcript-common/lib/renderPriority.mjs"; +import { renderModeNow, renderModeOffHere, renderModeOnHere } from "../../../operations/renderMode"; +import { OpsInputError, ops, opsFail, optBool, optString } from "../_lib"; +import { readRoute } from "../_read"; + +export const dynamic = "force-dynamic"; + +// RENDER MODE (common/lib/renderPriority.mjs; AGENTS.md "Render mode"): a +// render the operator is waiting for gets the machine — every other heavy job +// waits at the heavy slot's door, and this editor's transcription and download +// lanes are held (only the ones not held already; only those are released). +// The same switch as `umtool render-mode`, for a session that has only `pnpm ops`. +// +// GET /api/ops/render-mode +// -> { ok, held, what?, since, until, holder, lanesHeld, lanesSkipped, +// lanesError, note, stale, reaped? } (no token) +// POST { on: true, for?: "90m" | <minutes>, note? } +// -> { ok, state: {…, token}, reminder, join } a window (default 2 h); +// a hold already on is a 409 naming it +// POST { on: false, force? } +// -> { ok, was, released, failed } a running take's hold only with force + +function view(state: RenderPriorityState | null) { + if (!state) return null; + const rest: Partial<RenderPriorityState> = { ...state }; + delete rest.token; + return { ...rest, what: describeRenderPriority(state) }; +} + +export async function GET(request: Request) { + return readRoute(request, [], async () => { + const now = await renderModeNow(); + return { + held: now.held, + ...(view(now.held ? now.state : null) ?? {}), + stale: now.stale, + last: now.held ? null : view(now.state), + reaped: now.reaped ? { released: now.reaped.released, failed: now.reaped.failed } : null, + reminder: RENDER_MODE_REMINDER, + }; + }); +} + +export async function POST(request: Request) { + return ops(request, ["on", "for", "note", "force"], async (body) => { + const on = optBool(body, "on"); + if (on === undefined) throw new OpsInputError('"on" is required: true or false'); + if (on) { + if (body.force !== undefined) throw new OpsInputError('"force" is for {"on": false}'); + let forMs: number | null = null; + if (body.for !== undefined) { + forMs = parseDurationMs(body.for); + if (!forMs) throw new OpsInputError('"for" is a duration: "90m", "2h", "1h30m", or a number of minutes'); + } + const r = await renderModeOnHere({ forMs, note: optString(body, "note") ?? null, by: "pnpm ops render-mode" }); + if (!r.ok || !r.state) { + return opsFail(`render mode is already on: ${r.held ? describeRenderPriority(r.held) : "?"}`, 409, { held: view(r.held ?? null) }); + } + return NextResponse.json({ + ok: true, + state: r.state, + reminder: RENDER_MODE_REMINDER, + join: `${RENDER_PRIORITY_TOKEN_ENV}=${r.state.token}`, + }); + } + if (body.for !== undefined || body.note !== undefined) throw new OpsInputError('"for" and "note" are for {"on": true}'); + const force = optBool(body, "force") === true; + const now = await renderModeNow(); + if (now.held && now.state?.holder && !force) { + return opsFail( + `render mode is held by a running render (${describeRenderPriority(now.state)}) — it ends with it; "force": true ends it now`, + 409, + ); + } + const r = await renderModeOffHere(); + return NextResponse.json({ ok: true, was: view(r.was ?? null), released: r.released, failed: r.failed }); + }); +} diff --git a/editor/app/jobs/actions.ts b/editor/app/jobs/actions.ts @@ -316,3 +316,19 @@ export async function clearFinishedLogsAction( revalidatePath("/jobs"); return { deleted }; } + +// The /jobs render-mode banner's End button: a manual window ended, its lanes +// released (operations/renderMode.ts). A running render's hold ends with the +// render, so the banner offers no button for it. +export async function endRenderModeAction(): Promise<{ ok: boolean; error?: string }> { + const { renderModeNow, renderModeOffHere } = await import("../operations/renderMode"); + const now = await renderModeNow(); + if (now.held && now.state?.holder) { + return { ok: false, error: "a running render holds it — it ends with the render" }; + } + const r = await renderModeOffHere(); + revalidatePath("/jobs"); + return r.failed.length + ? { ok: false, error: `not released: ${r.failed.map((f) => `${f.lane} (${f.error})`).join(", ")}` } + : { ok: true }; +} diff --git a/editor/app/jobs/components/EndRenderModeButton.tsx b/editor/app/jobs/components/EndRenderModeButton.tsx @@ -0,0 +1,38 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { endRenderModeAction } from "../actions"; + +// Ends a manual render-mode window (`umtool render-mode on`, `pnpm ops +// render-mode`) before its time: the lanes it held are released. +export function EndRenderModeButton({ until }: { until: string | null }) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const router = useRouter(); + return ( + <span className="flex items-center gap-2"> + {until && <span className="text-xs text-muted-foreground">until {until}</span>} + <button + type="button" + data-action="end-render-mode" + disabled={busy} + onClick={async () => { + setBusy(true); + setError(null); + try { + const r = await endRenderModeAction(); + if (!r.ok) setError(r.error ?? "could not end it"); + router.refresh(); + } finally { + setBusy(false); + } + }} + className="px-2 py-1 rounded-md border border-warning/30 text-xs font-medium text-warning hover:bg-warning-soft disabled:opacity-50" + > + {busy ? "Ending…" : "End render mode"} + </button> + {error && <span className="text-xs text-destructive">{error}</span>} + </span> + ); +} diff --git a/editor/app/jobs/components/RenderModeBanner.tsx b/editor/app/jobs/components/RenderModeBanner.tsx @@ -0,0 +1,39 @@ +import { + RENDER_MODE_REMINDER, + clockOf, + describeRenderPriority, + readRenderPriority, +} from "yt-dlp-transcript-common/lib/renderPriority.mjs"; +import { renderModeFile } from "../../operations/renderMode"; +import { EndRenderModeButton } from "./EndRenderModeButton"; + +// RENDER MODE on /jobs (common/lib/renderPriority.mjs; AGENTS.md "Render +// mode"): while a render the operator waits for holds the machine, say so — +// which lanes it holds and for what — since the lanes' quiet and every heavy +// job waiting at the door would otherwise look like a stall. Read only: the +// heartbeat ends a hold whose render is gone. +export function RenderModeBanner() { + const s = readRenderPriority(renderModeFile()); + if (!s.held || !s.state) return null; + const st = s.state; + const lanes = st.lanesHeld.length ? `${st.lanesHeld.join(" and ")} lane${st.lanesHeld.length > 1 ? "s" : ""} held` : "Heavy jobs held"; + return ( + <div + data-render-mode-banner="" + role="status" + className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/30 bg-warning-soft px-3 py-2 text-sm" + > + <span> + <strong>Render mode:</strong> {lanes} for {describeRenderPriority(st)}. + {st.lanesSkipped?.length ? ` ${st.lanesSkipped.join(", ")} already held — left alone.` : ""} + {st.lanesError ? ` (${st.lanesError})` : ""} Other heavy jobs (e2e, builds) wait for it;{" "} + {RENDER_MODE_REMINDER}. + </span> + {st.holder ? ( + <span className="text-xs text-muted-foreground">ends with the render</span> + ) : ( + <EndRenderModeButton until={st.until ? clockOf(st.until) : null} /> + )} + </div> + ); +} diff --git a/editor/app/jobs/page.tsx b/editor/app/jobs/page.tsx @@ -11,6 +11,7 @@ import { import { ClearLogsMenu } from "./components/ClearLogsMenu"; import { DrainAllButton } from "./components/DrainAllButton"; import { JobsTable } from "./components/JobsTable"; +import { RenderModeBanner } from "./components/RenderModeBanner"; import { RetryAllFailedButton } from "./components/RetryAllFailedButton"; import { PauseLaneButton } from "../components/lanes/pauseControl"; @@ -63,6 +64,7 @@ export default async function JobsPage({ <DrainAllButton /> </div> </div> + <RenderModeBanner /> <JobsTable initial={initial} history={rows} total={total} /> {hasMore && ( <div className="flex items-center justify-center gap-3 text-sm"> diff --git a/editor/app/operations/renderMode.ts b/editor/app/operations/renderMode.ts @@ -0,0 +1,105 @@ +import { revalidatePath } from "next/cache"; +import { getWorkerPool } from "yt-dlp-transcript-common/jobs/workerPool"; +import { isGateHeld, withGateHeld } from "yt-dlp-transcript-common/lib/pauseGates"; +import { + isLocalEditor, + readRenderPriority, + reapRenderMode, + renderModeOff, + renderModeOn, + renderPriorityFile, + type RenderModeLanes, + type RenderPriorityState, +} from "yt-dlp-transcript-common/lib/renderPriority.mjs"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { saveSettings } from "../settings/saveSettings"; + +// RENDER MODE, the editor's side (common/lib/renderPriority.mjs; AGENTS.md +// "Render mode"). `pnpm ops render-mode` turns it on and off here, /jobs shows +// it, and the heartbeat ends a hold that is no longer one — the render's +// process gone, its window over — by releasing the lanes IT held. +// +// The lanes are held in-process, the way the lane buttons hold them +// (operations/actions.ts setLaneHeld): the transcription pool first (its live +// hold), then the stored gate. Not through that server action itself: the +// heartbeat is no request, and its revalidatePath has none to revalidate. +// +// The state file is the one queue-lock reads: beside the heavy slot's lock in +// this checkout's git common dir (the editor runs from editor/), or +// RENDER_PRIORITY_FILE — the e2e servers set their own. + +type RenderLane = "transcription" | "download"; + +export function renderModeFile(): string { + return renderPriorityFile(process.env, { root: process.cwd() }); +} + +// WHICH EDITOR'S LANES. A hold records the editor its lanes were held through: +// umtool its ARCHILYZER_EDITOR_URL, this editor its own loopback URL. Another +// worktree's dev editor shares the state file (one common dir for every +// worktree) but not the lanes, so it reaps only a hold that names its own +// port — never the live editor's. A hold made through a URL that is not a +// loopback one is reaped by `umtool render-mode status|on`, not by a heartbeat. +const ownPort = () => process.env.EDITOR_PORT || process.env.PORT || "3001"; +const selfUrl = () => `http://localhost:${ownPort()}`; +const owns = (s: RenderPriorityState) => isLocalEditor(s.editor, ownPort()); + +async function setHeld(lane: RenderLane, held: boolean): Promise<void> { + if (lane === "transcription") { + if (held) getWorkerPool().pauseAll(); + else getWorkerPool().resumeAll(); + } + const cur = getSettings(); + if (isGateHeld(cur, lane) !== held) { + await saveSettings({ autoQueue: withGateHeld(cur, lane, held).autoQueue }); + } + try { + revalidatePath("/jobs"); + revalidatePath("/workers"); + revalidatePath("/operations/[id]", "page"); + } catch { + /* outside a request (the heartbeat): nothing to revalidate */ + } +} + +/** The editor's own lanes, for renderModeOn / renderModeOff. */ +export function editorRenderLanes(): RenderModeLanes { + return { + async isHeld(lane) { + const l = lane as RenderLane; + return isGateHeld(getSettings(), l) || (l === "transcription" && getWorkerPool().isPaused()); + }, + hold: (lane) => setHeld(lane as RenderLane, true), + release: (lane) => setHeld(lane as RenderLane, false), + }; +} + +/** Render mode as it stands; a stale hold is ended first (its lanes released). */ +export async function renderModeNow() { + const file = renderModeFile(); + const reaped = await reapRenderMode({ file, lanes: editorRenderLanes(), owns }).catch(() => null); + return { ...readRenderPriority(file), reaped: reaped?.was ? reaped : null, file }; +} + +/** On, as a manual window: `pnpm ops render-mode {"on": true, "for"?, "note"?}`. */ +export async function renderModeOnHere(o: { forMs: number | null; note: string | null; by: string }) { + const file = renderModeFile(); + return renderModeOn({ file, holder: null, forMs: o.forMs, note: o.note, by: o.by, editor: selfUrl(), lanes: editorRenderLanes() }); +} + +/** Off, whoever turned it on (the caller checked a running take's hold). */ +export async function renderModeOffHere() { + return renderModeOff({ file: renderModeFile(), lanes: editorRenderLanes() }); +} + +/** + * The heartbeat's look: a stale hold's lanes released, its file removed. Never + * throws. A live hold is left alone. + */ +export async function renderModeReapTick(): Promise<void> { + try { + await reapRenderMode({ file: renderModeFile(), lanes: editorRenderLanes(), owns }); + } catch { + /* the next beat looks again */ + } +} diff --git a/editor/app/scheduler/heartbeat.ts b/editor/app/scheduler/heartbeat.ts @@ -85,6 +85,15 @@ async function fire(generation: number): Promise<void> { // the scan records its own outcomes on the runs it reads } + // Render mode whose render is gone (killed, crashed) or whose window is over + // is no hold: the lanes it held here are released (operations/renderMode.ts). + try { + const { renderModeReapTick } = await import("../operations/renderMode"); + await renderModeReapTick(); + } catch { + // the next beat looks again + } + // Re-read the cadence each fire so a live settings change is honored without a // restart. If it has been turned off (0), the loop simply stops here. if (generation !== state.generation) return; diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -248,6 +248,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env) // every slot, so the e2e server never opens a headless browser on the // network — the player-page opener refuses under it too. editorEnv.E2E_ODYSEE_PAGE_FIXTURE = odyseePageFixtureFile(paths.transcriptsDir); + // Render mode's state (common/lib/renderPriority.mjs): the slot's own, so + // its heartbeat never ends — and its /jobs never shows — the machine's. + editorEnv.RENDER_PRIORITY_FILE = join(paths.transcriptsDir, ".render-priority.json"); // A start-mode server runs the stamped build (shared, read-only); a second // `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`). if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR; diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -84,6 +84,9 @@ // pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}' // pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}' // pnpm ops lane --json '{"lane":"download","held":true}' +// pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}' +// pnpm ops render-mode --json '{"on":false}' +// pnpm ops get render-mode // pnpm ops refresh-report --json '{"all":true}' // pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter"}' // pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter","dryRun":true}' @@ -269,6 +272,9 @@ const GETTERS = { // The dashboard's cookie refresh alerts: each service whose cookies look // stale (or are OK again, with the jobs the alert stopped). services: () => "/api/ops/services", + // Render mode (AGENTS.md "Render mode"): whether a render holds the machine, + // for what, since when, and which lanes it held. No token. + "render-mode": () => "/api/ops/render-mode", // The X login an X job would use and whether one would start now: the // source, the exported jar's age, social.x.maxCookieAgeMinutes and the // network guard's verdict (common/jobs/networkGuard.ts xSessionReport). @@ -325,6 +331,7 @@ const GET_ARG_OPTIONAL = new Set([ "services", "x-session", "generation-usage", + "render-mode", ]); // The flags each noun takes beyond the shared ones; any other is refused. @@ -461,6 +468,9 @@ const ACTIONS = [ // an evidence pack ({siteId, reportId?, formats?}). "reports-export", "lane", + // RENDER MODE (AGENTS.md "Render mode"): a render the operator waits for + // gets the machine — {on: true, for?, note?} | {on: false, force?}. + "render-mode", // The curated-tag writers. `tags` edits the vocabulary (define/remove); // `tag-videos` pins, unpins, suppresses or unsuppresses one tag over a batch // of videos in ONE write. @@ -1142,6 +1152,19 @@ export function usage() { ' "publish", "enabled"?, "held"?, "action"?: "start"|"stop"|"drain"}, or', ' {"lane": "report-schedule", "held"}: the recurring reports\' gate, its only key.', "", + 'render-mode gives a render the operator is waiting for the machine:', + ' {"on": true, "for"?: "90m" | <minutes>, "note"?} opens a window (default', + ' 2h) in which every other heavy job — e2e suites, next builds, the publish', + ' stages, other renders — waits at the heavy slot\'s door, and holds the', + ' transcription and download lanes (only the ones not already held; only', + ' those are released). The answer\'s "join" (RENDER_PRIORITY_TOKEN=…) lets a', + ' render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take`', + ' joins by itself. {"on": false} ends it ("force": true ends a running', + ' take\'s hold, which otherwise ends with the take). `umtool take …', + ' --priority` is the same for one take. `get render-mode` says whether it', + ' is on, for what, since when, which lanes it holds. Close Firefox and', + ' other heavy apps while it renders.', + "", '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.', "", diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs @@ -17,7 +17,7 @@ // // node scripts/queue-lock.mjs [--name e2e-<pkg>] [--estimate <MB>] [--prebuild <pkg>] // [--ports PORT:3011,...] -- <cmd...> -// node scripts/queue-lock.mjs --heavy [--estimate <MB>] [--build] -- <cmd...> +// node scripts/queue-lock.mjs --heavy [--estimate <MB>] [--build] [--urgent] -- <cmd...> // (`pnpm heavy -- <cmd>`) // // THE HEAVY SLOT. Two OOMs on this machine (2026-10-08) took Xwayland and dbus @@ -53,8 +53,20 @@ // still runs alone. HEAVY_CAP=0 turns it off; HEAVY_CAP_MB / HEAVY_CAP_SWAP_MB // size it (a larger --estimate raises it to the estimate). // -// Bypasses: HEAVY=0 (no slot, no floor), HEAVY_MIN_FREE_MB=0 (no floor), -// HEAVY_TIMEOUT=<seconds>. E2E_QUEUE=0 skips the slot as it skips the queue; +// RENDER MODE (common/lib/renderPriority.mjs; AGENTS.md "Render mode"). While +// a render the operator is waiting for holds it (`umtool take … --priority`, +// `umtool render-mode on`, `pnpm ops render-mode`), every OTHER heavy job waits +// at the door — before the line, so it never holds the line the render needs: +// `queue-lock: held for a render (umtool take <p> --id <t>, since 13:31) — +// waiting`. The render and everything under it carry the hold's token +// (RENDER_PRIORITY_TOKEN) and are admitted, on the floor 4000 MB and the cap +// 10240 MB unless HEAVY_MIN_FREE_MB / HEAVY_CAP_MB say otherwise. A job already +// admitted is not stopped; a nested one (HEAVY_HELD) passes as before; an +// `--urgent` one (a live stream's sniff) never waits. RENDER_PRIORITY=0 runs +// anyway. The state is `<heavy lock>.render.json`, beside the lock. +// +// Bypasses: HEAVY=0 (no slot, no floor, no render wait), HEAVY_MIN_FREE_MB=0 (no floor), +// RENDER_PRIORITY=0 (no render wait), HEAVY_TIMEOUT=<seconds>. E2E_QUEUE=0 skips the slot as it skips the queue; // the floor still applies. A machine whose MemTotal is under the floor is not // made to wait forever: it is told, and runs one job at a time. The slot is a // safety net, not a correctness lock: with no usable `flock` it warns and runs @@ -89,6 +101,14 @@ import net from "node:net"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { + applyRenderPriorityDefaults, + carriesRenderPriority, + describeRenderPriority, + readRenderPriority, + renderPriorityBlocks, + renderPriorityFile, +} from "../common/lib/renderPriority.mjs"; const SELF = fileURLToPath(import.meta.url); @@ -124,6 +144,8 @@ function parseArgv(argv) { portSpec: null, hold: false, heavy: false, + // `--urgent`: a job that cannot wait for a render (a live stream's sniff). + urgent: false, // The heavy slot's admission (S4): a job's memory estimate in MB, whether // it is a `next build`, and the package whose e2e build to ensure first. // Unset means "infer from the command" (resolveJob). @@ -145,6 +167,7 @@ function parseArgv(argv) { const f = flags[i]; if (f === "--hold") opts.hold = true; else if (f === "--heavy") opts.heavy = true; + else if (f === "--urgent") opts.urgent = true; else if (f === "--name") opts.name = flags[++i]; else if (f === "--ports") opts.portSpec = flags[++i]; else if (f === "--timeout") opts.timeoutMs = Number(flags[++i]) * 1000; @@ -1200,6 +1223,75 @@ async function admitOrExit(opts) { } } +// ------------------------------------------------------------- render mode + +/** + * Wait while render mode holds the machine for a render this job is not + * (renderPriorityBlocks). Every input is injectable for the unit tests; `read` + * returns readRenderPriority's `{held, state}`. Resolves `{waitedMs}`; throws + * `{timeout: true}` past `timeoutMs` (0 = never). + */ +export async function waitForRenderPriority({ + read, + env = process.env, + urgent = false, + pollMs = memPollMs(), + tickMs = TICK_MS, + timeoutMs = 0, + log = (line) => process.stderr.write(line), + now = Date.now, + sleep = (ms) => new Promise((r) => setTimeout(r, ms)), +}) { + let s = read(); + if (!renderPriorityBlocks(s, env, { urgent })) return { waitedMs: 0 }; + const t0 = now(); + let lastTick = t0; + log( + `queue-lock: held for a render (${describeRenderPriority(s.state)}) — waiting\n` + + " (render mode: `umtool render-mode off` ends it; RENDER_PRIORITY=0 to run anyway)\n", + ); + for (;;) { + await sleep(pollMs); + s = read(); + const waited = now() - t0; + if (!renderPriorityBlocks(s, env, { urgent })) { + log(`queue-lock: the render let go after ${humanDuration(waited)} — going on\n`); + return { waitedMs: waited }; + } + if (timeoutMs > 0 && waited >= timeoutMs) { + throw Object.assign(new Error(`queue-lock: gave up after ${humanDuration(waited)} waiting for the render`), { + timeout: true, + }); + } + if (now() - lastTick >= tickMs) { + lastTick = now(); + log(`queue-lock: still waiting for the render (${humanDuration(waited)}; ${describeRenderPriority(s.state)})\n`); + } + } +} + +async function renderGateOrExit(read, { urgent = false, timeoutMs = 0 } = {}) { + try { + return await waitForRenderPriority({ read, urgent, timeoutMs }); + } catch (err) { + if (!err.timeout) throw err; + process.stderr.write(`\n${err.message}\n Raise or unset the timeout, or set RENDER_PRIORITY=0.\n`); + process.exit(EXIT_TIMEOUT); + } +} + +// The render itself (it carries the hold's token): its floor and cap, unless +// the environment names them — set in process.env, so its command inherits them. +function renderOwnDefaults(read) { + if (!carriesRenderPriority(read())) return; + const set = applyRenderPriorityDefaults(process.env); + if (set.length) { + process.stderr.write( + `heavy: render mode — this render runs on the floor ${process.env.HEAVY_MIN_FREE_MB} MB, capped at ${process.env.HEAVY_CAP_MB} MB\n`, + ); + } +} + // ------------------------------------------------------------ the entry points /** @@ -1211,9 +1303,13 @@ async function admitOrExit(opts) { export async function withHeavy(opts, fn) { if (process.env.HEAVY === "0") return fn(); const cmd = opts.cmd ?? [HEAVY_NAME]; - const job = resolveJob(opts, cmd); const heavyLock = lockFileFor(HEAVY_NAME); const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs("HEAVY_TIMEOUT"); + const renderFile = renderPriorityFile(process.env, { heavyLock }); + const readRender = () => readRenderPriority(renderFile); + // Before the job is resolved: the render's cap is an estimate's floor. + if (!process.env[HEAVY_HELD_ENV]) renderOwnDefaults(readRender); + const job = resolveJob(opts, cmd); // Inside an admitted run: pass through — except a build, which still waits // for the build slot (one build at a time is hard), and says so. @@ -1246,21 +1342,30 @@ export async function withHeavy(opts, fn) { const releases = []; try { let releaseLine = null; - try { - releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, timeoutMs, { - ...HEAVY_LOCK, - describe: () => - `${describeSlot(heavyLock)}; next in line: ${describeHolder(admitLockFor(heavyLock), true)}`, - }); - } catch (err) { - // No usable flock (a container image without util-linux): the slot is a - // safety net, so run on the floor alone rather than not at all. - process.stderr.write( - `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`, - ); - await memoryFloorOrExit(timeoutMs); - process.env[HEAVY_HELD_ENV] = "1"; - return await fn(); + // RENDER MODE first, outside the line: a job waiting for the render must + // not hold the line the render is admitted through. Looked at again once in + // line — a render that went on meanwhile sends this job back to wait. + for (;;) { + await renderGateOrExit(readRender, { urgent: opts.urgent === true, timeoutMs: remaining() }); + try { + releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, remaining(), { + ...HEAVY_LOCK, + describe: () => + `${describeSlot(heavyLock)}; next in line: ${describeHolder(admitLockFor(heavyLock), true)}`, + }); + } catch (err) { + // No usable flock (a container image without util-linux): the slot is a + // safety net, so run on the floor alone rather than not at all. + process.stderr.write( + `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`, + ); + await memoryFloorOrExit(timeoutMs); + process.env[HEAVY_HELD_ENV] = "1"; + return await fn(); + } + if (!renderPriorityBlocks(readRender(), process.env, { urgent: opts.urgent === true })) break; + await releaseLine(); + releaseLine = null; } try { const slotWait = { ...HEAVY_LOCK, describe: () => describeSlot(heavyLock) }; @@ -1342,6 +1447,8 @@ export async function withQueue(opts, fn) { if (process.env.E2E_QUEUE === "0") { await preflight(ports, graceMs); if (process.env.HEAVY !== "0" && !process.env[HEAVY_HELD_ENV]) { + const renderFile = renderPriorityFile(process.env, { heavyLock: lockFileFor(HEAVY_NAME) }); + await renderGateOrExit(() => readRenderPriority(renderFile), { timeoutMs }); await memoryFloorOrExit(timeoutMs); } return fn(); @@ -1425,12 +1532,12 @@ async function main() { if (cmd.length === 0) { process.stderr.write( "usage: queue-lock.mjs [--name e2e-<pkg>] [--estimate <MB>] [--prebuild <pkg>] [--ports PORT:3011,...] -- <cmd...>\n" + - " queue-lock.mjs --heavy [--estimate <MB>] [--build] [--timeout <s>] -- <cmd...>\n", + " queue-lock.mjs --heavy [--estimate <MB>] [--build] [--urgent] [--timeout <s>] -- <cmd...>\n", ); process.exit(2); } const code = opts.heavy - ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd, estimateMb: opts.estimateMb, build: opts.build }, () => + ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd, estimateMb: opts.estimateMb, build: opts.build, urgent: opts.urgent }, () => runCommand(capHeavy(cmd, resolveJob(opts, cmd)), null, { forwardTerm: true }), ) : await withQueue({ ...opts, cmd }, () => runCommand(cmd, opts.name)); diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs @@ -26,6 +26,7 @@ import { workerScale, waitForAdmission, waitForMemory, + waitForRenderPriority, } from "./queue-lock.mjs"; const SCRIPT = fileURLToPath(new URL("./queue-lock.mjs", import.meta.url)); @@ -41,7 +42,7 @@ function tmpDir() { // `pnpm heavy -- pnpm test:scripts`) is dropped unless the test sets it. function lockEnv(env) { const out = { E2E_PORT_CHECK: "0", HEAVY: "0", HEAVY_CAP: "0", ...process.env, ...env }; - for (const k of ["HEAVY_HELD", "QUEUE_LOCK_HELD", "E2E_QUEUE"]) { + for (const k of ["HEAVY_HELD", "QUEUE_LOCK_HELD", "E2E_QUEUE", "RENDER_PRIORITY", "RENDER_PRIORITY_TOKEN", "RENDER_PRIORITY_FILE"]) { if (!(k in env)) delete out[k]; } return out; @@ -944,3 +945,146 @@ test("an admitted --heavy command runs under systemd-run's cap by default; HEAVY assert.match(bare.stdout, /ran/); assert.equal(fs.existsSync(log), false, "no systemd-run at all with the cap off"); }); + +// ------------------------------------------------------------- render mode + +// A render-mode hold (common/lib/renderPriority.mjs) beside the test's heavy +// lock, held by `pid` (a live process unless the test says otherwise). +function renderHold(env, { pid, token = "render-tok", cmd = "umtool take ember --id t1", until = null } = {}) { + const file = `${env.HEAVY_LOCK_FILE}.render.json`; + fs.writeFileSync( + file, + JSON.stringify({ + version: 1, token, since: new Date().toISOString(), until, by: "test", note: null, + holder: pid == null ? null : { pid, cmd }, lanesHeld: [], + }), + ); + return file; +} + +// A process that lives until killed: a render's stand-in holder. +function sleeper() { + const child = spawn(process.execPath, ["-e", "setInterval(()=>{},1000)"], { stdio: "ignore" }); + return child; +} + +test("waitForRenderPriority waits while a render holds the machine, then goes on; the token, an urgent job and RENDER_PRIORITY=0 never wait", async () => { + const held = { held: true, state: { token: "tok", since: new Date().toISOString(), holder: { pid: 1, cmd: "umtool take p --id t" } }, stale: null }; + const free = { held: false, state: null, stale: null }; + const reads = [held, held, free]; + const lines = []; + let t = 0; + const r = await waitForRenderPriority({ + read: () => reads.shift() ?? free, + env: {}, + pollMs: 10, + log: (l) => lines.push(l), + now: () => t, + sleep: async (ms) => { + t += ms; + }, + }); + assert.equal(r.waitedMs, 20); + assert.match(lines[0], /^queue-lock: held for a render \(umtool take p --id t, since \d\d:\d\d\) — waiting/); + assert.match(lines.at(-1), /the render let go after/); + for (const opts of [{ env: { RENDER_PRIORITY_TOKEN: "tok" } }, { env: { RENDER_PRIORITY: "0" } }, { env: {}, urgent: true }]) { + const quiet = []; + assert.deepEqual(await waitForRenderPriority({ read: () => held, log: (l) => quiet.push(l), ...opts }), { waitedMs: 0 }); + assert.deepEqual(quiet, []); + } + await assert.rejects( + waitForRenderPriority({ read: () => held, env: {}, pollMs: 10, timeoutMs: 15, log: () => {}, now: () => t, sleep: async (ms) => { t += ms; } }), + (err) => err.timeout === true, + ); +}); + +test("render mode: a heavy job waits for the render, named, and starts when it lets go; a stale hold is no hold", async (t) => { + const dir = tmpDir(); + const env = heavyEnv(dir); + const holder = sleeper(); + t.after(() => holder.kill("SIGKILL")); + const file = renderHold(env, { pid: holder.pid }); + const run = startLock(["--heavy", "--", process.execPath, "-e", 'console.log("ran")'], env); + await run.waitFor(/queue-lock: held for a render \(umtool take ember --id t1, since \d\d:\d\d\) — waiting/); + await delay(150); + fs.rmSync(file); + const res = await run.done; + assert.equal(res.code, 0, res.stderr); + assert.match(res.stdout, /ran/); + assert.match(res.stderr, /the render let go after/); + + // The holder gone (a killed take): not a hold — nothing waits. + renderHold(env, { pid: 999_999_999 }); + const stale = await runLock(["--heavy", "--", "true"], env); + assert.equal(stale.code, 0, stale.stderr); + assert.doesNotMatch(stale.stderr, /held for a render/); + // A window whose until is past: the same. + renderHold(env, { pid: null, until: new Date(Date.now() - 1000).toISOString() }); + const over = await runLock(["--heavy", "--", "true"], env); + assert.doesNotMatch(over.stderr, /held for a render/); +}); + +test("render mode: an e2e suite and a build wait too; RENDER_PRIORITY=0 and HEAVY=0 run anyway; a nested job passes", async (t) => { + const dir = tmpDir(); + const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock") }); + const holder = sleeper(); + t.after(() => holder.kill("SIGKILL")); + const file = renderHold(env, { pid: holder.pid }); + const suite = startLock(["--name", "e2e-umtool", "--estimate", "1500", "--", "true"], env); + await suite.waitFor(/held for a render/); + const build = startLock(["--heavy", "--build", "--", "true"], env); + await build.waitFor(/held for a render/); + // E2E_QUEUE=0 skips the queue and the slot, not the render. + const unqueued = startLock(["--name", "e2e-editor", "--", "true"], { ...env, E2E_QUEUE: "0" }); + await unqueued.waitFor(/held for a render/); + + const bypass = await runLock(["--heavy", "--", "true"], { ...env, RENDER_PRIORITY: "0" }); + assert.equal(bypass.code, 0); + assert.doesNotMatch(bypass.stderr, /held for a render/); + const off = await runLock(["--heavy", "--", "true"], { ...env, HEAVY: "0" }); + assert.equal(off.code, 0); + assert.equal(off.stderr, ""); + const nested = await runLock(["--heavy", "--", "true"], { ...env, HEAVY_HELD: "1" }); + assert.equal(nested.code, 0); + assert.doesNotMatch(nested.stderr, /held for a render/); + const urgent = await runLock(["--heavy", "--urgent", "--", "true"], env); + assert.equal(urgent.code, 0); + assert.doesNotMatch(urgent.stderr, /held for a render/); + + fs.rmSync(file); + for (const w of [suite, build, unqueued]) assert.equal((await w.done).code, 0); +}); + +test("render mode: the render (its token) is admitted at once, on the floor 4000 MB and capped at 10240 MB", async (t) => { + const dir = tmpDir(); + const bin = path.join(dir, "bin"); + fs.mkdirSync(bin); + const log = path.join(dir, "systemd-run.log"); + fs.writeFileSync( + path.join(bin, "systemd-run"), + `#!/bin/sh\nprintf '%s\\n' "$*" >> '${log}'\nwhile [ "$1" != "--" ] && [ $# -gt 0 ]; do shift; done\n[ "$1" = "--" ] && shift\n[ $# -gt 0 ] && exec "$@"\nexit 0\n`, + { mode: 0o755 }, + ); + const cgroup = path.join(dir, "cgroup"); + fs.writeFileSync(cgroup, "0::/queue-lock-test-not-a-cgroup.scope\n"); + const env = heavyEnv(dir, { HEAVY_CAP: undefined, HEAVY_PROC_CGROUP: cgroup, PATH: `${bin}:${process.env.PATH}` }); + meminfo(env.HEAVY_MEMINFO_FILE, 4500); // under the usual 6000 floor, over the render's 4000 + const holder = sleeper(); + t.after(() => holder.kill("SIGKILL")); + renderHold(env, { pid: holder.pid, token: "render-tok" }); + const render = await runLock( + ["--heavy", "--estimate", "2000", "--", "sh", "-c", 'echo "floor=$HEAVY_MIN_FREE_MB cap=$HEAVY_CAP_MB"'], + { ...env, RENDER_PRIORITY_TOKEN: "render-tok" }, + ); + assert.equal(render.code, 0, render.stderr); + assert.doesNotMatch(render.stderr, /held for a render|waiting for memory/); + assert.match(render.stderr, /render mode — this render runs on the floor 4000 MB, capped at 10240 MB/); + // Its command (and so its subprocesses) inherits them. + assert.match(render.stdout, /floor=4000 cap=10240/); + assert.match(fs.readFileSync(log, "utf8"), /-p MemoryMax=10240M/); + // The environment's own numbers win. + const own = await runLock(["--heavy", "--", "sh", "-c", 'echo "floor=$HEAVY_MIN_FREE_MB"'], { + ...env, RENDER_PRIORITY_TOKEN: "render-tok", HEAVY_MIN_FREE_MB: "1000", + }); + assert.match(own.stdout, /floor=1000/); +}); diff --git a/umtool/app/api/render-mode/route.ts b/umtool/app/api/render-mode/route.ts @@ -0,0 +1,37 @@ +import { + RENDER_MODE_REMINDER, + clockOf, + describeRenderPriority, + readRenderPriority, + renderPriorityFile, +} from "yt-dlp-transcript-common/lib/renderPriority.mjs"; +import { REPO_ROOT } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// RENDER MODE as it stands (common/lib/renderPriority.mjs; AGENTS.md "Render +// mode"), for the take panel's banner. Read only: it is turned on by a take +// started with "Give renders the machine" (`umtool take … --priority`), by +// `umtool render-mode on`, or by `pnpm ops render-mode`. The token is not +// answered — a page has no use for it. +// +// GET -> { held, what, since, until, take, lanesHeld, lanesSkipped, lanesError, note, reminder } +export async function GET() { + const s = readRenderPriority(renderPriorityFile(process.env, { root: REPO_ROOT })); + const st = s.held ? s.state : null; + return Response.json( + { + held: Boolean(st), + what: st ? describeRenderPriority(st) : null, + since: st ? clockOf(st.since) : null, + until: st?.until ? clockOf(st.until) : null, + take: st?.holder ? { project: st.holder.project ?? null, take: st.holder.take ?? null } : null, + lanesHeld: st?.lanesHeld ?? [], + lanesSkipped: st?.lanesSkipped ?? [], + lanesError: st?.lanesError ?? null, + note: st?.note ?? null, + reminder: RENDER_MODE_REMINDER, + }, + { headers: { "cache-control": "no-store" } }, + ); +} diff --git a/umtool/app/api/report/clip-editor/route.ts b/umtool/app/api/report/clip-editor/route.ts @@ -12,6 +12,7 @@ export const dynamic = "force-dynamic"; // // GET ?project=<id> the view: clips, token, speakers, unused proposals // GET ?project=<id>&clip=<id>&from=<s>&to=<s> the strip for a span: turns, laughs, words | cues +// [&video=<id>] words only when they are that recording's (the bench's zoom) // POST { project, op, token?, … } one operation (clipEditor.mjs runClipEditorOp): // trim | restore | split | merge | add | bring-in | ruling | role | … | audio | blur // -> { op, result, carried, view }; 409 on a stale token (reload), 400 with @@ -35,6 +36,8 @@ export async function GET(request: Request) { clip: url.searchParams.get("clip"), from: Number(url.searchParams.get("from")), to: Number(url.searchParams.get("to")), + // The clip bench, zoomed in: that recording's words only. + video: url.searchParams.get("video") || null, }); return Response.json(n, { headers }); } diff --git a/umtool/app/api/report/clip/route.ts b/umtool/app/api/report/clip/route.ts @@ -67,6 +67,8 @@ export async function GET(request: Request) { cutEnd: clip.cutEnd ?? null, lockCut: !!clip.lockCut, muteFrom: clip.muteFrom ?? null, + // Seconds cut out of its middle (gaps.mjs). + gaps: Array.isArray(clip.gaps) ? clip.gaps : [], }, view, // `v`: the version of each window's bytes, for the media URLs -- a refetch diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -62,6 +62,13 @@ export async function PUT(request: Request) { // The clip this one re-plays on purpose (a callback, a flash-forward), so // their overlap is not flagged or trimmed; empty or null clears it. "repeatOf", + // Seconds taken out of the clip's middle (gaps.mjs): the whole list + // (`gaps`, empty clears), one span added (`gapAdd`: {from, to} or + // "12.3-15.1"), or the gap holding a source second removed (`gapRemove`). + // Checked by the writer against the cut and the marks. + "gaps", + "gapAdd", + "gapRemove", // Whether the walk has looked at this clip: "confirmed", or empty to clear // it. A non-empty `correction` is the other answer and needs no value. "verdict", diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -23,6 +23,7 @@ // [--title T] [--date YYYY-MM-DD] [--cite S] [--cite-url U] [--quote Q] // [--correction TEXT] [--verdict confirmed|incorrect|''] // [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent +// [--gap FROM-TO]… [--gap-remove S] [--gaps 'A-B,C-D' | ''] seconds cut out of its middle // [--take <id>] a take's clip: the edit goes into the take's patch (walk a take) // umtool walk <project> [--take <id>] [--all] [--json] the walk: clips in walk order, verdicts, fetched // umtool set <project> <clip> key=value … a clip's knobs: claim.at|hold|stamp|count|label, @@ -63,7 +64,9 @@ // umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …] // [--at S --dur S | --full] [--force] [--from TAKE] [--keep-frames] | --id <id> --rebuild make one take // [--draft] record it without rendering (walk it first) · --id <id> --promote [--anyway] make it the cut +// [--priority] render mode for the take's lifetime: the machine is the render's (AGENTS.md "Render mode") // umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] +// umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render gets the machine // umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] // [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master // umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>] @@ -115,6 +118,7 @@ import path from "node:path"; import { updateArticleLink, updateClip, updateStorage } from "../lib/report/manifest.mjs"; import { withEditNotes } from "../lib/report/edit-guard.mjs"; import { hms } from "umtool-report-to-video/attribution"; +import { gappedLength, gapSpan, gapsOf, gapsText, parseGapSpec } from "umtool-report-to-video/gaps"; import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs"; import { sourceCountOf } from "umtool-report-to-video/manifest-sources"; import { runBuildOverHttp, umtoolBase } from "../lib/report/buildRun.mjs"; @@ -736,6 +740,9 @@ function usage() { " --correction TEXT what the REPORT got wrong here (never rendered)", " --verdict confirmed|incorrect what the walk said; incorrect needs --correction", " --cut-start S --cut-end E --lock-cut the cut the video renders", + " --gap FROM-TO (repeatable) cut those source seconds out of the clip's middle: it plays", + " as ONE segment of jump cuts (gaps.mjs; inside the cut, ≥ 0.2 s, 0.5 s kept between);", + " --gap-remove S the gap holding source second S · --gaps 'A-B,C-D' the whole list ('' clears)", " an empty value (--title '') deletes the field", " --take <id> a take's clip (walk a take): the edit goes into takes/<id>/take.json's", " patch, an undo point first (`umtool timeline <p> --take <id> undo`); the manifest is untouched", @@ -799,9 +806,14 @@ function usage() { " --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)", " --draft (--no-render): record the take, render nothing -- walk it, edit it, render it later", " (`umtool take <p> --id <id> --full` renders a draft from its stored patch)", + " --priority: render mode for the take's lifetime -- every other heavy job waits for it, the", + " editor's transcription and download lanes are held; all let go at its end, failure or signal", " umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the", " manifest, one undo point (revisions/…-auto-before-promote-take)", " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", + " umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render the", + " operator waits for gets the machine (other heavy jobs wait; the editor's transcription and", + " download lanes held); `on` is a window for a chain of renders (default 2h)", " umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]", " a trailer cut from the take's finished master: the master's own frames, so the deck shows the", " whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)", @@ -905,6 +917,8 @@ const COMMANDS = { // The take maker (release 33): lib/report/takeCli.mjs. take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))), takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))), + // Render mode (2026-10-30): lib/report/renderMode.mjs. + "render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))), trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), // The clip deck's rulings (release 34): lib/report/rulingsCli.mjs. rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))), @@ -1000,6 +1014,23 @@ async function cmdWindow() { if (has(`--no-${flag.slice(2)}`)) patch[key] = false; } if (val("--note") !== undefined) patch.note = val("--note"); + // Gaps inside the clip (gaps.mjs): seconds taken out of its middle, so it + // renders as one segment of jump cuts. `--gap` adds one (repeatable), + // `--gap-remove S` takes out the gap holding S, `--gaps` sets the list + // ('' clears it). Applied by the writer to the list as it is now. + const gapAdds = argv.flatMap((a, i) => (a === "--gap" ? [argv[i + 1] ?? ""] : [])); + if (gapAdds.length) { + const bad = gapAdds.find((g) => !parseGapSpec(g)); + if (bad !== undefined) die(`--gap ${bad}: a gap is FROM-TO in source seconds, e.g. --gap 12.3-15.1`); + patch.gapAdd = gapAdds; + } + if (val("--gap-remove") !== undefined) patch.gapRemove = Number(val("--gap-remove")); + if (val("--gaps") !== undefined) { + const list = String(val("--gaps")).split(",").map((s) => s.trim()).filter(Boolean); + const parsed = list.map(parseGapSpec); + if (parsed.some((g) => !g)) die(`--gaps ${val("--gaps")}: a comma-separated list of FROM-TO in source seconds, or '' to clear`); + patch.gaps = parsed; + } // The attribution: what the burned-in header and the QR will say. An empty // value DELETES the field, the same rule the flags keep -- `--title ''` is how // you go back to the archived record's own title. @@ -1032,6 +1063,7 @@ async function cmdWindow() { if (json) return out({ ok: true, take, ...res }); console.log(`${clipId} (take ${take}): ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`); if (res.entry.cutStart != null) console.log(` cut: ${res.entry.cutStart}–${res.entry.cutEnd}`); + if (gapsText(res.entry)) console.log(` gaps: ${gapsText(res.entry)}`); if (patch.verdict !== undefined || patch.correction !== undefined) console.log(` review: ${clipVerdict(res.entry)}`); if (res.entry.correction) console.log(` correction: ${res.entry.correction}`); console.log(` undo point: takes/${take}/${res.revision.rel} (umtool timeline ${p.id} --take ${take} undo)`); @@ -1060,6 +1092,13 @@ async function cmdWindow() { } else if (patch.cutStart !== undefined || patch.cutEnd !== undefined) { console.log(" cut cleared — the build will use the whole extent"); } + if (gapsText(res.entry)) { + const span = gapSpan(res.entry); + const g = gapsOf(res.entry); + console.log(` gaps: ${gapsText(res.entry)} — the cut plays ${gappedLength(span.from, span.to, g).toFixed(2)}s of ${(span.to - span.from).toFixed(2)}s, one segment of jump cuts`); + } else if (patch.gaps !== undefined || patch.gapRemove !== undefined) { + console.log(" no gaps — the cut plays whole"); + } const marks = ["lock", "lockStart", "lockEnd", "lockCut"].filter((k) => res.entry[k]); if (marks.length) console.log(` ${marks.join(", ")}`); // The line the renderer will burn in, printed so an attribution edit is diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -20,6 +20,7 @@ import { BenchBody, VerdictBar } from "./bench/BenchShell"; import CopyCitation from "./bench/CopyCitation"; import EdgeStrip from "./bench/EdgeStrip"; import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts"; +import { GapLayer, ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom"; import TakeWalkStrip from "./bench/TakeWalkStrip"; // The renderer's own line, imported rather than re-written. A preview that // disagrees with the header by a character is worth less than no preview: you @@ -36,6 +37,9 @@ import { playheadAt, } from "@/lib/report/playback.mjs"; import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs"; +import { DETAIL_SPAN } from "@/lib/report/benchZoom.mjs"; +// Gaps inside a clip: the rule (the writer's and the build's) and the pieces that play. +import { GAP_FADE, GAP_LIMITS, editGaps, gapSpan, gappedLength, gapsWithin, inGap, keptSpans, validateGaps } from "umtool-report-to-video/gaps"; import { DeckFrame, NeutralFrame, @@ -133,6 +137,12 @@ type Clip = { * before a finale's ending sound. Absent means the clip plays with its sound. */ muteFrom: number | null; + /** + * GAPS: source seconds cut out of the clip's middle (gaps.mjs), so it plays + * as one segment of jump cuts. Written at once (Cut gap, a click on a band), + * not drafted like the edges; every playback here skips them. + */ + gaps: Span[]; /** "confirmed" / "incorrect", or null for "nobody has looked at this yet". */ verdict: "confirmed" | "incorrect" | null; /** What the on-screen panel says over this clip. Absent means the auto text. */ @@ -214,6 +224,7 @@ const fromEntry = (prev: Clip, e: Record<string, unknown>): Clip => ({ cutEnd: e.cutEnd == null ? null : Number(e.cutEnd), lockCut: !!e.lockCut, muteFrom: e.muteFrom == null ? null : Number(e.muteFrom), + gaps: Array.isArray(e.gaps) ? (e.gaps as Span[]) : [], verdict: e.verdict === "confirmed" || e.verdict === "incorrect" ? e.verdict : null, onscreen: (e.onscreen as Onscreen | undefined) ?? null, }); @@ -487,6 +498,8 @@ type Session = { ctxStop: number; /** The element's own mute, put back when the picture stops following. */ mutedBefore: boolean; + /** A playback across gaps: the later pieces' nodes (the first is `node`). */ + more?: AudioBufferSourceNode[]; }; export default function ClipBench({ data }: { data: ClipBenchData }) { @@ -883,6 +896,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // Read by play() at the moment it schedules, so a mark moved since the last // render is the one you hear -- without re-creating play() on every nudge. const muteRef = useRef<number | null>(data.clip.muteFrom); + // The gaps as SAVED: what every playback skips. Read at the moment it schedules, like the mark. + const gapsRef = useRef<Span[]>(data.clip.gaps ?? []); + gapsRef.current = clip.gaps ?? []; const [audio, setAudio] = useState<{ state: "idle" | "loading" | "ready" | "failed"; why?: string }>({ state: "idle", }); @@ -1012,16 +1028,17 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { session.current = null; cancelAnimationFrame(s.raf); for (const t of s.timers) clearTimeout(t); - if (s.node) { - s.node.onended = null; + for (const node of [s.node, ...(s.more ?? [])]) { + if (!node) continue; + node.onended = null; try { - s.node.stop(); + node.stop(); } catch { /* never started, or already stopped */ } - s.node.disconnect(); - s.gain?.disconnect(); + node.disconnect(); } + s.gain?.disconnect(); const el = video.current; if (el) { pauseVideo(el); @@ -1038,7 +1055,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { * element can do, and the bench says that this is what is playing. */ const playElement = useCallback( - (from: number, to: number, gen: number) => { + (from: number, to: number, gen: number, gaps: Span[] = []) => { const el = video.current; if (!el || !cached) return; const rate = playback.rate; @@ -1083,6 +1100,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { if (session.current !== s) return; const t = el.currentTime + fetchStart; setPlayhead(t); + // A gap: on past it, as near as a frame tick gets it. + const g = inGap(t, gaps); + if (g && !el.seeking) el.currentTime = g.to - fetchStart; // The mark, as near as a frame tick gets it. const m = muteRef.current; el.muted = s.mutedBefore || (m != null && t >= m); @@ -1108,11 +1128,20 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { [cached, fetchStart, playback.rate, pauseVideo], ); + /** + * Play [from, to], skipping the clip's GAPS as the cut will (gaps.mjs): each + * piece that plays is its own node, abutting the next on the context's + * clock, the join faded out and in by the build's GAP_FADE; the picture is + * seeked at each join. `through` plays the gaps too (a span being chosen for + * one is heard as it is); `extra` is one more span to skip (Hear it: a + * selection heard as cut, before it is written). + */ const play = useCallback( - async (from: number, to: number) => { + async (from: number, to: number, { through = false, extra = null }: { through?: boolean; extra?: Span | null } = {}) => { const gen = (playGen.current += 1); stopPlayback(); if (!cached || !(to > from)) return; + const gaps = through ? [] : gapsWithin([...gapsRef.current, ...(extra ? [extra] : [])].sort((a, b) => a.from - b.from), from, to); const rate = playback.rate; // The context is opened HERE, inside the click or the key that asked: // that gesture is what lets it start. @@ -1127,14 +1156,14 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { if (!ac) throw new Error("this browser has no Web Audio"); d = await ensureDecoded({ from, to }); } catch { - if (gen === playGen.current) playElement(from, to, gen); + if (gen === playGen.current) playElement(from, to, gen, gaps); return; } if (gen !== playGen.current) return; // Longer than one decode: the element, rather than a second decode in // the middle of a click. if (!covers(d.span, from, to)) { - playElement(from, to, gen); + playElement(from, to, gen, gaps); return; } if (resumed) await Promise.race([resumed, new Promise((res) => setTimeout(res, 300))]); @@ -1143,38 +1172,90 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // just as silent. if (gen !== playGen.current || ac!.state !== "running") return; const ctx = ac!; - const sch = bufferSchedule(d.span, d.buf.duration, from, to, rate); - if (!sch) return; + // The pieces that play: the whole range without gaps. + const pieces = keptSpans(from, to, gaps) + .map((p) => ({ p, sch: bufferSchedule(d.span, d.buf.duration, p.from, p.to, rate) })) + .filter((x): x is { p: Span; sch: NonNullable<ReturnType<typeof bufferSchedule>> } => !!x.sch); + if (!pieces.length) return; // At a speed but 1x the range is stretched at its own pitch and played // at 1x; a buffer's playbackRate is tape speed, an octave up at 2x. const stretched = wantsStretch(rate); - const buf = stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf; + const bufs = pieces.map(({ sch }) => (stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf)); if (gen !== playGen.current) return; - const node = ctx.createBufferSource(); - node.buffer = buf; - node.playbackRate.value = stretched ? 1 : rate; const gain = ctx.createGain(); - node.connect(gain); gain.connect(ctx.destination); // Ahead of now, so start and stop stay on the clock they were computed // on: a start in the past begins late at the SAME offset. const t0 = ctx.currentTime + START_LEAD; - const ctxStop = t0 + sch.wall; - const m = muteRamp(muteRef.current, from, from + sch.duration, rate); - if (m) { - if (m.at <= 0) gain.gain.setValueAtTime(0, t0); - else { - gain.gain.setValueAtTime(1, t0 + m.at); - gain.gain.linearRampToValueAtTime(0, t0 + m.at + m.fade); + // Each piece's place on the wall clock, from t0. + let acc = 0; + const placed = pieces.map(({ p, sch }) => { + const w0 = acc; + acc += sch.wall; + return { p, sch, w0, w1: acc }; + }); + const ctxStop = t0 + acc; + const end = placed[placed.length - 1].p.from + placed[placed.length - 1].sch.duration; + const nodes = placed.map(({ sch, w0 }, k) => { + const node = ctx.createBufferSource(); + node.buffer = bufs[k]; + node.playbackRate.value = stretched ? 1 : rate; + node.connect(gain); + // The stop is a TIME on the context's clock, not start()'s duration + // argument: that one is buffer content, and a clock time means the same + // thing at every speed. + node.start(t0 + w0, stretched ? 0 : sch.offset); + node.stop(t0 + w0 + sch.wall); + return node; + }); + if (placed.length === 1) { + const m = muteRamp(muteRef.current, from, from + placed[0].sch.duration, rate); + if (m) { + if (m.at <= 0) gain.gain.setValueAtTime(0, t0); + else { + gain.gain.setValueAtTime(1, t0 + m.at); + gain.gain.linearRampToValueAtTime(0, t0 + m.at + m.fade); + } + } + } else { + // Across gaps: the joins' fades and the mute mark, as one level on the wall clock. + const fadeW = GAP_FADE / rate; + const mark = muteRef.current; + let markW: number | null = null; + if (mark != null) { + if (mark <= from) markW = 0; + else { + const k = placed.findIndex((x) => mark <= x.p.from + x.sch.duration); + if (k >= 0) markW = placed[k].w0 + Math.max(0, mark - placed[k].p.from) / rate; + } } + const muteFadeW = MUTE_FADE / rate; + const level = (w: number) => { + let v = 1; + placed.forEach((x, k) => { + if (w < x.w0 || w > x.w1) return; + if (k > 0 && w < x.w0 + fadeW) v = Math.min(v, (w - x.w0) / fadeW); + if (k < placed.length - 1 && w > x.w1 - fadeW) v = Math.min(v, (x.w1 - w) / fadeW); + }); + if (markW != null) { + if (w >= markW) v = 0; + else if (w > markW - muteFadeW) v = Math.min(v, (markW - w) / muteFadeW); + } + return Math.max(0, Math.min(1, v)); + }; + const pts = new Set<number>([0, acc]); + placed.forEach((x, k) => { + if (k > 0) [x.w0, x.w0 + fadeW].forEach((w) => pts.add(w)); + if (k < placed.length - 1) [x.w1 - fadeW, x.w1 - 1e-4].forEach((w) => pts.add(w)); + }); + if (markW != null) [markW - muteFadeW, markW].forEach((w) => pts.add(Math.max(0, w))); + const ws = [...pts].filter((w) => w >= 0 && w <= acc).sort((a, b) => a - b); + gain.gain.setValueAtTime(level(ws[0]), t0 + ws[0]); + for (const w of ws.slice(1)) gain.gain.linearRampToValueAtTime(level(w), t0 + w); } - // The stop is a TIME on the context's clock, not start()'s duration - // argument: that one is buffer content, and a clock time means the same - // thing at every speed. - node.start(t0, stretched ? 0 : sch.offset); - node.stop(ctxStop); + const node = nodes[0]; const el = video.current; const s: Session = { @@ -1185,11 +1266,12 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { raf: 0, timers: [], from, - to: from + sch.duration, + to: end, rate, t0, ctxStop, mutedBefore: el?.muted ?? false, + ...(nodes.length > 1 ? { more: nodes.slice(1) } : {}), }; session.current = s; setPlayInfo({ @@ -1203,6 +1285,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { ctxStop, endedAt: null, }); + /** The source second playing `w` wall seconds in: its piece's, from its first. */ + const posAt = (w: number) => { + const x = placed.find((q) => w <= q.w1) ?? placed[placed.length - 1]; + return Math.min(x.p.from + x.sch.duration, x.p.from + Math.max(0, w - x.w0) * rate); + }; // The picture follows, muted. It is not what is being judged; a few // milliseconds of drift between the two is not worth a sync loop. @@ -1215,9 +1302,18 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { if (session.current === s) void el.play().catch(() => {}); }, START_LEAD * 1000), ); + // Each join: the picture jumps with the sound. + for (const x of placed.slice(1)) { + s.timers.push( + window.setTimeout(() => { + if (session.current === s) el.currentTime = Math.max(0, x.p.from - fetchStart); + }, (START_LEAD + x.w0) * 1000), + ); + } } - node.onended = () => { + const last = nodes[nodes.length - 1]; + last.onended = () => { if (session.current !== s) return; // How late the context clock reads at `ended`, mapped back onto the // source: what the playback measured, for the bench's own record. @@ -1225,7 +1321,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { session.current = null; cancelAnimationFrame(s.raf); for (const t of s.timers) clearTimeout(t); - node.disconnect(); + for (const n of nodes) n.disconnect(); gain.disconnect(); if (el) { pauseVideo(el); @@ -1247,7 +1343,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const tick = () => { if (session.current !== s) return; const now = ctx.currentTime; - const pos = playheadAt(from, t0, now, rate, sch.duration); + const pos = placed.length === 1 ? playheadAt(from, t0, now, rate, placed[0].sch.duration) : posAt(Math.max(0, now - t0)); if (now - painted >= 1 / 30) { painted = now; setPlayhead(pos); @@ -1747,6 +1843,146 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { placeMute(at, false); }, [sel.from, sel.to, placeMute]); + // ---- gaps inside the clip -------------------------------------------------- + // + // Seconds cut out of the clip's middle (gaps.mjs): it renders as ONE segment + // of jump cuts rather than as two clips with a crossfade, a second pip and a + // second card. A span is dragged on the waveform with Alt held (or after `g` + // / Select a gap) and written by Cut gap (or `g`); a click on a gap's band + // puts it back. Unlike the edges these are WRITTEN AT ONCE, through the one + // window writer (`gapAdd` / `gapRemove`), which refuses what the build would + // -- and leaves an undo point (auto-before-gaps) -- and Undo here writes the + // list back as it was. The rule is checked here first, with the same + // sentences, so a refusal is said before anything is sent. + const [gapSel, setGapSel] = useState<Span | null>(null); + const [gapPick, setGapPick] = useState(false); + const [gapUndo, setGapUndo] = useState<{ gaps: Span[]; what: string } | null>(null); + // A different clip: nothing selected, nothing to undo. + useEffect(() => { + setGapSel(null); + setGapPick(false); + setGapUndo(null); + }, [clip.id]); + /** Why `gaps` cannot be written on this clip as saved (the writer's own check), or null. */ + const gapRefusal = useCallback( + (gaps: Span[]) => { + const errs = validateGaps({ type: "clip", id: clip.id, start: clip.start, end: clip.end, cutStart: clip.cutStart, cutEnd: clip.cutEnd, muteFrom: clip.muteFrom, gaps }, "gap"); + return errs.length ? errs[0].replace(/^gap\.gaps\[\d+\] /, "the gap ").replace(/^gap\.muteFrom/, "the mute mark").replace(/^gap: /, "") : null; + }, + [clip.id, clip.start, clip.end, clip.cutStart, clip.cutEnd, clip.muteFrom], + ); + const writeGaps = useCallback( + async (patch: Record<string, unknown>, next: Span[], what: string) => { + const why = gapRefusal(next); + if (why) { + setNote(`not cut: ${why}`); + return false; + } + const before = clip.gaps ?? []; + const ok = await save(patch); + if (ok) { + setGapUndo({ gaps: before, what }); + setNote(`${what} — the cut plays ${gappedLength(gapSpan(clip).from, gapSpan(clip).to, next).toFixed(2)} s, one segment`); + } + return ok; + }, + [gapRefusal, save, clip], + ); + const cutGap = useCallback(async () => { + const s = gapSel; + if (!s) return; + const g = { from: round2(s.from), to: round2(s.to) }; + let next: Span[]; + try { + next = editGaps(clip.gaps ?? [], { add: g }); + } catch (e) { + setNote(e instanceof Error ? e.message : String(e)); + return; + } + const ok = await writeGaps({ gapAdd: g }, next, `cut ${hms(g.from)}–${hms(g.to)} out`); + if (ok) { + setGapSel(null); + setGapPick(false); + } + }, [gapSel, clip.gaps, writeGaps]); + const removeGap = useCallback( + (g: Span) => { + const next = (clip.gaps ?? []).filter((x) => x.from !== g.from || x.to !== g.to); + void writeGaps({ gapRemove: (g.from + g.to) / 2 }, next, `put ${hms(g.from)}–${hms(g.to)} back`); + }, + [clip.gaps, writeGaps], + ); + /** `G`: the gap the playhead is in (or at the edge of). */ + const removeGapAt = useCallback( + (t: number | null) => { + const g = t == null ? null : (clip.gaps ?? []).find((x) => t >= x.from - 0.05 && t <= x.to + 0.05); + if (!g) { + setNote("the playhead is not on a gap — play to it, or click its band"); + return; + } + removeGap(g); + }, + [clip.gaps, removeGap], + ); + const undoGap = useCallback(() => { + const u = gapUndo; + if (!u) return; + void save({ gaps: u.gaps }).then((ok) => { + if (!ok) return; + setGapUndo(null); + setNote(`undone — ${u.what} is reversed`); + }); + }, [gapUndo, save]); + /** A span dragged for a gap: kept inside the cut; under the shortest gap on release, dropped and said. */ + const selectGap = useCallback( + (s: Span, done: boolean) => { + const span = gapSpan(clip); + const from = Math.max(span.from, s.from); + const to = Math.min(span.to, s.to); + if (!done) { + setGapSel(to > from ? { from, to } : null); + return; + } + if (to - from < GAP_LIMITS.min) { + setGapSel(null); + if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span`); + return; + } + setGapSel({ from, to }); + const why = gapRefusal(editGaps(clip.gaps ?? [], { add: { from: round2(from), to: round2(to) } })); + setNote(why ? `this span cannot be cut: ${why}` : `${(to - from).toFixed(2)} s selected — Cut gap (g) to take it out, Hear it to listen first`); + }, + [clip, gapRefusal], + ); + // Alt + drag on the waveform selects a gap's span without arming anything. + const altDrag = useRef<{ id: number; at: number } | null>(null); + + // ---- the zoom ---------------------------------------------------------------- + // What the waveform shows of the cached window (bench/GapsZoom.tsx). Fit -- the + // whole window, today's view -- on every clip's arrival. + const zoom = useWaveZoom(view); + // Close in: the pauses between words, when the project has its words for this recording (the clip editor's). + const [nearWords, setNearWords] = useState<{ key: string; words: { start: number; end: number }[] | null } | null>(null); + const close = zoom.vis.to - zoom.vis.from <= DETAIL_SPAN; + const wordsKey = close ? `${clip.id}|${Math.floor(zoom.vis.from / 10) * 10}|${Math.ceil(zoom.vis.to / 10) * 10}` : null; + useEffect(() => { + if (!wordsKey || nearWords?.key === wordsKey) return; + let live = true; + const [, a, b] = wordsKey.split("|"); + const q = new URLSearchParams({ project: data.project, clip: clip.id, from: a, to: b, video: clip.video }); + fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" }) + .then((r) => (r.ok ? (r.json() as Promise<{ words?: { start: number; end: number }[] | null }>) : null)) + .then((j) => { + if (live) setNearWords({ key: wordsKey, words: j?.words ?? null }); + }) + .catch(() => { + if (live) setNearWords({ key: wordsKey, words: null }); + }); + return () => { + live = false; + }; + }, [wordsKey, nearWords?.key, data.project, clip.id, clip.video]); + // ---- keyboard ----------------------------------------------------------- useEffect(() => { const nudge = (which: "from" | "to", by: number) => @@ -1766,6 +2002,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const el = e.target as HTMLElement | null; if (el && /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)) return; const step = e.shiftKey ? 0.5 : 0.05; + // The zoom's and the gaps' keys leave the browser's own (Ctrl+F, Ctrl+Z …) alone. + if ((e.ctrlKey || e.metaKey || e.altKey) && "zZfFgG".includes(e.key)) return; switch (e.key) { // The SHIFTED character too, on every edge key. `e.shiftKey` selects // the 0.5 s step, but shift also changes what the key IS -- `Shift+.` @@ -1843,7 +2081,33 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { } placeMute(mute + (e.key === ";" || e.key === ":" ? -step : step), true); break; + // The waveform's zoom: z in, Z out (at the playhead when it is in view), f fit, F to the selection. + case "z": + zoom.zoomIn(playheadRef.current != null && playheadRef.current >= zoom.vis.from && playheadRef.current <= zoom.vis.to ? playheadRef.current : null); + break; + case "Z": + zoom.zoomOut(playheadRef.current != null && playheadRef.current >= zoom.vis.from && playheadRef.current <= zoom.vis.to ? playheadRef.current : null); + break; + case "f": + zoom.fit(); + break; + case "F": + zoom.to(gapSel ?? sel); + break; + // Gaps: g cuts the selected span (or starts selecting one), G puts back the gap at the playhead. + case "g": + if (gapSel) void cutGap(); + else setGapPick((v) => !v); + break; + case "G": + removeGapAt(playheadRef.current); + break; case "Escape": + if (gapPick || gapSel) { + setGapPick(false); + setGapSel(null); + break; + } if (!mutePick) return; setMutePick(false); break; @@ -1874,6 +2138,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { muteAtPlayhead, clearMute, placeMute, + zoom, + gapSel, + gapPick, + cutGap, + removeGapAt, ]); const refresh = useCallback(async (): Promise<ClipBenchData | null> => { @@ -2139,6 +2408,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const span = Math.max(1e-6, view.to - view.from); const pct = (t: number) => `${((t - view.from) / span) * 100}%`; + // What the waveform shows (the zoom's), for everything drawn over it. + const zspan = Math.max(1e-6, zoom.vis.to - zoom.vis.from); + const zpct = (t: number) => `${((t - zoom.vis.from) / zspan) * 100}%`; const previewLine = attributionLine( { @@ -3211,9 +3483,45 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { {/* ---- the instrument ---- On a phone the edge strip is the instrument; this one is still there, folded under Window, for the mute mark. */} - <div className={cn("relative", secBody("window", "max-md:order-[52]"))}> + <div className={cn("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}> + {/* Zoomed: round ticks over what is shown. */} + {zoom.zoomed && <ZoomRuler vis={zoom.vis} />} + <div + ref={zoom.ref} + data-wave-box="" + data-wave-vis={`${zoom.vis.from}-${zoom.vis.to}`} + className="relative" + // Alt + drag: a span for a gap, never an edge (the waveform's own drag is held off). + onPointerDownCapture={(e) => { + if (!e.altKey || gapPick || mutePick) return; + e.preventDefault(); + e.stopPropagation(); + e.currentTarget.setPointerCapture(e.pointerId); + const r = e.currentTarget.getBoundingClientRect(); + const at = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; + altDrag.current = { id: e.pointerId, at }; + selectGap({ from: at, to: at }, false); + }} + onPointerMoveCapture={(e) => { + const d = altDrag.current; + if (!d || d.id !== e.pointerId) return; + e.stopPropagation(); + const r = e.currentTarget.getBoundingClientRect(); + const t = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; + selectGap({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, false); + }} + onPointerUpCapture={(e) => { + const d = altDrag.current; + if (!d || d.id !== e.pointerId) return; + e.stopPropagation(); + altDrag.current = null; + const r = e.currentTarget.getBoundingClientRect(); + const t = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; + selectGap({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, true); + }} + > <Waveform - view={view} + view={zoom.vis} sel={sel} cand={{ from: clip.start, to: clip.end }} words={cues.map((c) => ({ start: c.start, end: c.end, w: c.text.slice(0, 24) }))} @@ -3229,20 +3537,32 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { and a hatch over what is silent to the end of the selection. In the interaction colour, like the handles -- it is an edit, not a reading -- and never in the way of a drag. */} - {mute != null && mute >= view.from && mute <= view.to && ( + {/* The gaps, the span being selected for one, and close in the silences and the pauses between words. */} + <GapLayer + vis={zoom.vis} + gaps={clip.gaps ?? []} + selection={gapSel} + picking={gapPick && !mutePick} + silences={renderEdges?.silences ?? null} + words={nearWords?.words ?? null} + busy={!!busy} + onRemove={removeGap} + onSelect={selectGap} + /> + {mute != null && mute >= zoom.vis.from && mute <= zoom.vis.to && ( <> <div data-mute-span="" className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-dim)_22%,transparent)_0_3px,transparent_3px_7px)]" style={{ - left: pct(mute), - width: `calc(${pct(Math.max(mute, sel.to))} - ${pct(mute)})`, + left: zpct(mute), + width: `calc(${zpct(Math.max(mute, Math.min(sel.to, zoom.vis.to)))} - ${zpct(mute)})`, }} /> <div data-mute-marker={mute} className="pointer-events-none absolute top-0 h-full border-l-2 border-dashed border-[var(--color-sel)]" - style={{ left: pct(mute) }} + style={{ left: zpct(mute) }} > <span className="absolute left-1 top-0.5 rounded bg-[var(--color-panel-2)] px-1 font-mono text-[9px] leading-tight text-[var(--color-sel)]"> mute @@ -3251,20 +3571,95 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { </> )} {/* Where the render will actually cut: each edge snapped to its silence, faint. */} - <RenderGhosts edges={renderEdges} view={view} /> + <RenderGhosts edges={renderEdges} view={zoom.vis} /> {/* Armed: the next click places the mark rather than an edge. */} {mutePick && ( <div data-mute-pick-layer="" - className="absolute inset-0 cursor-crosshair rounded-md outline outline-1 outline-[var(--color-sel)]" + className="absolute inset-0 z-[8] cursor-crosshair rounded-md outline outline-1 outline-[var(--color-sel)]" onPointerDown={(e) => { const r = e.currentTarget.getBoundingClientRect(); const frac = Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))); - placeMute(view.from + frac * span, true); + placeMute(zoom.vis.from + frac * zspan, true); }} /> )} </div> + {/* Zoomed: the whole cached window, what is shown of it -- drag to pan. */} + {zoom.zoomed && <ZoomOverview zoom={zoom} whole={view} peaks={peaks} sel={sel} gaps={clip.gaps ?? []} />} + {/* Under the waveform: its zoom, and the clip's gaps (the waveform keeps its place on the page). */} + <div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> + {/* ---- GAPS inside the clip ---- + Seconds cut out of its middle: it renders as one segment of + jump cuts. Written at once (not drafted like the edges), and + every playback here skips them, as the cut will. */} + <span data-gaps={(clip.gaps ?? []).map((g) => `${g.from}-${g.to}`).join(",")} className="flex flex-wrap items-center gap-1.5"> + {(clip.gaps ?? []).length ? ( + <span data-gaps-summary="" className="num text-[var(--color-text)]"> + {(clip.gaps ?? []).length} gap{(clip.gaps ?? []).length === 1 ? "" : "s"}{" "} + <span className="text-[var(--color-dim)]"> + (the cut plays {gappedLength(gapSpan(clip).from, gapSpan(clip).to, clip.gaps ?? []).toFixed(2)} s of{" "} + {(gapSpan(clip).to - gapSpan(clip).from).toFixed(2)} s, one segment) + </span> + </span> + ) : ( + <span className="text-[var(--color-dim)]">no gaps — the cut plays whole</span> + )} + <button + type="button" + data-gap-pick={gapPick ? "armed" : ""} + aria-pressed={gapPick} + className={`${buttonVariants({ variant: "outline", size: "sm" })}${gapPick ? " bg-panel-2 border-muted" : ""}`} + title="drag on the waveform to select seconds to cut out of the clip (g; or hold Alt and drag; Esc cancels)" + onClick={() => setGapPick((v) => !v)} + > + {gapPick ? "Drag on the waveform…" : "Select a gap"} + </button> + {gapSel && ( + <> + <button + type="button" + data-gap-cut="" + className={buttonVariants({ size: "sm" })} + disabled={!!busy || gapSel.to - gapSel.from < GAP_LIMITS.min} + title="cut the selected seconds out of the clip (g)" + onClick={() => void cutGap()} + > + Cut gap {hms(gapSel.from)}–{hms(gapSel.to)} ({(gapSel.to - gapSel.from).toFixed(2)} s) + </button> + <button + type="button" + data-gap-hear="" + className={buttonVariants({ variant: "outline", size: "sm" })} + title="two seconds either side, the selection skipped: the jump as the cut will play it" + onClick={() => void play(Math.max(sel.from, gapSel.from - 2), Math.min(sel.to, gapSel.to + 2), { extra: gapSel })} + > + Hear it + </button> + <button + type="button" + data-gap-play-span="" + className={buttonVariants({ variant: "outline", size: "sm" })} + title="play what the selection would take out" + onClick={() => void play(gapSel.from, gapSel.to, { through: true })} + > + Play the span + </button> + </> + )} + {gapUndo && ( + <button type="button" data-gap-undo="" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={!!busy} onClick={undoGap} title={`undo: ${gapUndo.what}`}> + Undo + </button> + )} + </span> + <span className="micro max-md:hidden"> + <kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "} + <kbd>g</kbd> (or Alt + drag) select a gap, <kbd>g</kbd> cut it, <kbd>G</kbd> put back the one at the playhead + </span> + <ZoomControls zoom={zoom} whole={view} selection={gapSel ?? sel} playhead={playhead} /> + </div> + </div> {/* Offered at the edge of the cache, as always -- and also whenever the rail has something to read past it. Having just read the next @@ -3383,6 +3778,16 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { </div> ); })} + {/* The GAPS: cut out of the clip's middle. */} + {(clip.gaps ?? []).map((g) => ( + <div + key={`rail-gap-${g.from}`} + data-rail-gap={`${g.from}-${g.to}`} + aria-hidden + className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-dirty)_26%,transparent)_0_4px,transparent_4px_8px)]" + style={{ left: rpct(g.from), width: `calc(${rpct(g.to)} - ${rpct(g.from)})` }} + /> + ))} {/* The CUT, as an inner pair of markers: what plays, inside what was reviewed. */} {clip.cutStart != null && clip.cutEnd != null && ( diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -108,6 +108,10 @@ export default async function ClipBenchPage({ muteFrom: ((manifest.timeline ?? []) as { id: string; muteFrom?: number }[]).find((e) => e.id === clipId) ?.muteFrom ?? null, + // Seconds cut out of its middle (gaps.mjs), likewise from the manifest's own entry. + gaps: + ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) + ?.gaps ?? [], verdict: entry.verdict === "confirmed" || entry.verdict === "incorrect" ? entry.verdict : null, // From the manifest's own entry: what the on-screen panel says over this diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx @@ -5,6 +5,7 @@ import { useRouter } from "next/navigation"; import { buttonVariants } from "@/components/ui/button"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import { JobProgress, type JobStepState } from "@/components/ui/job-progress"; +import RenderModeBanner, { renderPriorityPref } from "./RenderModeBanner"; // New take, Make all styles -- and the job either starts (or a card's Rebuild // starts), watched here until it ends, then the page re-reads the takes. @@ -38,12 +39,15 @@ export function announceTakeJob(job: unknown) { window.dispatchEvent(new CustomEvent(TAKE_JOB_EVENT, { detail: job })); } -/** POST /api/report/takes/make; the job, or the error in words. */ +/** + * POST /api/report/takes/make; the job, or the error in words. "Give renders + * the machine" (RenderModeBanner) adds `priority` unless the body says. + */ export async function startTakeJob(body: Record<string, unknown>): Promise<{ job?: JobView; error?: string }> { const r = await fetch("/api/report/takes/make", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify(body), + body: JSON.stringify(body.priority === undefined && renderPriorityPref() ? { ...body, priority: true } : body), cache: "no-store", }); const j = (await r.json().catch(() => ({}))) as { job?: JobView; error?: string }; @@ -157,6 +161,7 @@ export default function NewTakePanel({ return ( <section data-new-take="" className="space-y-2"> + <RenderModeBanner /> <details className="rounded border border-[var(--color-line)] bg-[var(--color-panel)]"> <summary data-action="new-take-open" className="cursor-pointer px-3 py-2 text-[12.5px] text-text"> New take diff --git a/umtool/components/projects/RenderModeBanner.tsx b/umtool/components/projects/RenderModeBanner.tsx @@ -0,0 +1,107 @@ +"use client"; + +import { useEffect, useState } from "react"; + +// RENDER MODE on the take panel (common/lib/renderPriority.mjs; AGENTS.md +// "Render mode"): the "Give renders the machine" toggle, and a banner while a +// render holds the machine. +// +// The toggle is this browser's: a take this page starts (New take, Make all +// styles, a card's Rebuild / Render) carries `priority`, which runs it as +// `umtool take … --priority` — every other heavy job waits for its render, the +// editor's transcription and download lanes are held, both let go at its end. +// The banner reads /api/render-mode (the state file), whoever turned it on. + +const PREF_KEY = "umtool:render-priority"; + +/** Whether this browser gives its renders the machine. Off when storage cannot be read. */ +export function renderPriorityPref(): boolean { + try { + return localStorage.getItem(PREF_KEY) === "on"; + } catch { + return false; + } +} + +function setRenderPriorityPref(on: boolean) { + try { + if (on) localStorage.setItem(PREF_KEY, "on"); + else localStorage.removeItem(PREF_KEY); + } catch { + /* a private window: the toggle lasts this page only */ + } +} + +type RenderModeView = { + held: boolean; + what: string | null; + since: string | null; + until: string | null; + lanesHeld: string[]; + lanesSkipped: string[]; + lanesError: string | null; + reminder: string; +}; + +export default function RenderModeBanner() { + const [ready, setReady] = useState(false); + const [on, setOn] = useState(false); + const [mode, setMode] = useState<RenderModeView | null>(null); + + // Read storage after hydration: reading it during render would differ from the server's. + useEffect(() => { + setOn(renderPriorityPref()); + setReady(true); + }, []); + + useEffect(() => { + let alive = true; + const look = () => + fetch("/api/render-mode", { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : null)) + .then((j: RenderModeView | null) => alive && setMode(j)) + .catch(() => {}); + void look(); + const t = setInterval(look, 4000); + return () => { + alive = false; + clearInterval(t); + }; + }, []); + + return ( + <div className="space-y-1.5"> + <label + className="flex items-center gap-1.5 text-[12px] text-text-2" + title="Renders started here run as `umtool take … --priority`: other heavy jobs (e2e, builds, other renders) wait for them, and the editor's transcription and download lanes are held until they end." + > + <input + type="checkbox" + data-render-priority="" + checked={on} + disabled={!ready} + onChange={(e) => { + setOn(e.target.checked); + setRenderPriorityPref(e.target.checked); + }} + /> + Give renders the machine + </label> + {mode?.held ? ( + <p + data-render-mode-banner="" + role="status" + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px] text-text" + > + <strong>Render mode:</strong>{" "} + {mode.lanesHeld.length ? `${mode.lanesHeld.join(" and ")} lane${mode.lanesHeld.length > 1 ? "s" : ""} held` : "the machine held"} for {mode.what} + {mode.lanesError ? <span className="text-text-2"> ({mode.lanesError})</span> : null}. {capitalize(mode.reminder)}. + </p> + ) : null} + </div> + ); +} + +function capitalize(s: string) { + return s ? s[0].toUpperCase() + s.slice(1) : s; +} diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx @@ -0,0 +1,392 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import type { Peaks } from "@/components/Waveform"; +import { buttonVariants } from "@/components/ui/button"; +import { alpha, usePalette } from "@/components/ui/use-palette"; +import { cn } from "@/lib/utils"; +import { + DETAIL_SPAN, ZOOM_STEP, centreOn, clampVis, isFit, panBy, quietPoints, rulerFor, tickLabel, wheelFactor, zoomAt, zoomTo, +} from "@/lib/report/benchZoom.mjs"; + +// --------------------------------------------------------------------------- +// THE BENCH WAVEFORM, CLOSER (ClipBench.tsx's desk): a zoom on the waveform +// where edges, the mute mark and a clip's GAPS (umtool-report-to-video +// gaps.mjs: seconds cut out of its middle) are set. +// +// zoom Ctrl/⌘ + wheel (a trackpad's pinch is one) at the pointer, the +// second under it staying there; − / + / Fit / Zoom to selection; +// z in, Z out, f fit, F to the selection. The waveform, every mark +// over it and the handles' drags all work on what is shown. +// pan the wheel (either axis) while zoomed; a drag on the overview +// strip under it, which shows the whole cached window, what is +// shown in it, the selection and the gaps; a two-finger pinch on it. +// closer a ruler of round ticks, and at DETAIL_SPAN seconds or less the +// measured silences (the cut-points route's, the build's own) and +// the pauses between words, so a gap's edge goes between two words. +// gaps each a hatched band over the waveform, `cut` on it; a click on +// one removes it. A span for a new one is dragged with Alt held +// (or after `g` / Select a gap); Cut gap (or `g`) writes it. +// +// At fit -- the default, and on every clip's arrival -- the waveform is exactly +// what it was: no ruler, no overview, nothing moved. +// --------------------------------------------------------------------------- + +export type Span = { from: number; to: number }; + +/** + * What the waveform shows (`vis`) and the zoom's moves, over `whole` (the + * cached window). Null state is fit. `ref` goes on the element the wheel is + * read over. + */ +export function useWaveZoom(whole: Span) { + const [zv, setZv] = useState<Span | null>(null); + // A different window (a fetch widened it, the next clip): what was shown, kept inside it. + const wholeKey = `${whole.from}|${whole.to}`; + const lastWhole = useRef(wholeKey); + useEffect(() => { + if (lastWhole.current === wholeKey) return; + lastWhole.current = wholeKey; + setZv((v) => (v ? (isFit(clampVis(v, whole), whole) ? null : clampVis(v, whole)) : null)); + // `whole` is read through its key. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [wholeKey]); + const vis = zv ?? whole; + const zoomed = !isFit(zv, whole); + const set = useCallback((v: Span) => setZv(isFit(v, whole) ? null : v), [whole]); + const zoomIn = useCallback((at?: number | null) => set(zoomAt(zv, whole, at ?? (vis.from + vis.to) / 2, ZOOM_STEP)), [zv, whole, vis.from, vis.to, set]); + const zoomOut = useCallback((at?: number | null) => set(zoomAt(zv, whole, at ?? (vis.from + vis.to) / 2, 1 / ZOOM_STEP)), [zv, whole, vis.from, vis.to, set]); + const fit = useCallback(() => setZv(null), []); + const to = useCallback((range: Span) => set(zoomTo(range, whole)), [whole, set]); + const pan = useCallback((dt: number) => set(panBy(zv, whole, dt)), [zv, whole, set]); + const centre = useCallback((t: number) => set(centreOn(zv, whole, t)), [zv, whole, set]); + + // The wheel, read natively: React's is passive, and a zoom must not also scroll the page. + const el = useRef<HTMLDivElement | null>(null); + const state = useRef({ zv, whole, vis, zoomed, set }); + state.current = { zv, whole, vis, zoomed, set }; + // Attached as the element mounts (a callback ref: the waveform is not on the page at the first render). + const detach = useRef<(() => void) | null>(null); + const ref = useCallback((node: HTMLDivElement | null) => { + detach.current?.(); + detach.current = null; + el.current = node; + if (!node) return; + const on = (e: WheelEvent) => { + const s = state.current; + const r = node.getBoundingClientRect(); + const at = s.vis.from + ((e.clientX - r.left) / Math.max(1, r.width)) * (s.vis.to - s.vis.from); + if (e.ctrlKey || e.metaKey) { + e.preventDefault(); + s.set(zoomAt(s.zv, s.whole, at, wheelFactor(e.deltaY, e.deltaMode))); + return; + } + if (!s.zoomed) return; + // Zoomed: the wheel pans, either axis (shift turns a vertical wheel sideways on most systems already). + const d = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY; + if (!d) return; + e.preventDefault(); + const px = e.deltaMode === 1 ? d * 16 : e.deltaMode === 2 ? d * 400 : d; + s.set(panBy(s.zv, s.whole, (px / Math.max(1, r.width)) * (s.vis.to - s.vis.from))); + }; + node.addEventListener("wheel", on, { passive: false }); + detach.current = () => node.removeEventListener("wheel", on); + }, []); + + return { vis, zoomed, ref, zoomIn, zoomOut, fit, to, pan, centre, set }; +} + +export type WaveZoom = ReturnType<typeof useWaveZoom>; + +const btn = buttonVariants({ variant: "outline", size: "sm" }); + +/** − / + / Fit / Zoom to selection, and how much is shown. */ +export function ZoomControls({ zoom, whole, selection, playhead }: { zoom: WaveZoom; whole: Span; selection: Span | null; playhead: number | null }) { + const at = playhead != null && playhead >= zoom.vis.from && playhead <= zoom.vis.to ? playhead : null; + const shown = zoom.vis.to - zoom.vis.from; + return ( + <span data-wave-zoom={zoom.zoomed ? `${zoom.vis.from.toFixed(2)}-${zoom.vis.to.toFixed(2)}` : "fit"} className="flex flex-wrap items-center gap-1"> + <span className="micro">zoom</span> + <button type="button" data-zoom-out="" className={btn} disabled={!zoom.zoomed} title="zoom out (Z; Ctrl/⌘ + wheel)" onClick={() => zoom.zoomOut(at)}> + − + </button> + <button type="button" data-zoom-in="" className={btn} title="zoom in at the playhead, else the middle (z; Ctrl/⌘ + wheel at the pointer)" onClick={() => zoom.zoomIn(at)}> + + + </button> + <button type="button" data-zoom-fit="" className={btn} disabled={!zoom.zoomed} title="the whole cached window (f)" onClick={zoom.fit}> + Fit + </button> + <button + type="button" + data-zoom-selection="" + className={btn} + disabled={!selection} + title="zoom to the gap you are selecting, else the selection (F)" + onClick={() => selection && zoom.to(selection)} + > + Zoom to selection + </button> + <span className="num text-[11px] text-[var(--color-dim)]" data-zoom-shown={shown.toFixed(2)}> + {zoom.zoomed ? `${shown < 10 ? shown.toFixed(2) : shown.toFixed(1)} s of ${(whole.to - whole.from).toFixed(0)} s` : "whole window"} + </span> + </span> + ); +} + +/** The ruler over the zoomed waveform: round ticks, labelled. */ +export function ZoomRuler({ vis }: { vis: Span }) { + const { step, ticks } = rulerFor(vis); + const span = Math.max(1e-6, vis.to - vis.from); + return ( + <div data-zoom-ruler={step} aria-hidden className="relative h-4 w-full select-none overflow-hidden font-mono text-[9.5px] leading-4 text-[var(--color-dim)]"> + {ticks.map((t) => ( + <span key={t} className="absolute top-0 h-full border-l border-[var(--color-line)] pl-0.5" style={{ left: `${((t - vis.from) / span) * 100}%` }}> + {tickLabel(t, step)} + </span> + ))} + </div> + ); +} + +/** + * Over the waveform (absolutely placed, the waveform's box): the gaps, the + * span being selected for one, and -- close in -- the silences and the pauses + * between words. `onRemove` on a gap's click; while `picking` (or with Alt + * held over the waveform, the caller's capture handler) a drag selects a span. + */ +export function GapLayer({ + vis, + gaps, + selection, + picking, + silences, + words, + busy, + onRemove, + onSelect, +}: { + vis: Span; + gaps: Span[]; + selection: Span | null; + picking: boolean; + silences: Span[] | null; + words: { start: number; end: number }[] | null; + busy: boolean; + onRemove: (g: Span) => void; + onSelect: (s: Span, done: boolean) => void; +}) { + const span = Math.max(1e-6, vis.to - vis.from); + const pct = (t: number) => `${((Math.min(vis.to, Math.max(vis.from, t)) - vis.from) / span) * 100}%`; + const width = (a: number, b: number) => `calc(${pct(b)} - ${pct(a)})`; + const inView = (s: Span) => s.to > vis.from && s.from < vis.to; + const close = vis.to - vis.from <= DETAIL_SPAN; + const quiet = close ? quietPoints({ words, silences }, vis.from, vis.to) : []; + const drag = useRef<{ id: number; at: number } | null>(null); + const tAt = (el: HTMLElement, clientX: number) => { + const r = el.getBoundingClientRect(); + return vis.from + Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))) * span; + }; + return ( + <> + {close && + (silences ?? []).filter(inView).map((s) => ( + <div + key={`sil-${s.from}`} + data-wave-silence={`${s.from.toFixed(2)}-${s.to.toFixed(2)}`} + aria-hidden + className="pointer-events-none absolute bottom-0 h-2 rounded-sm bg-[color-mix(in_srgb,var(--color-meter)_35%,transparent)]" + style={{ left: pct(s.from), width: width(s.from, s.to) }} + /> + ))} + {quiet.map((t) => ( + <div key={`q-${t}`} data-wave-quiet={t} aria-hidden className="pointer-events-none absolute top-0 h-full border-l border-dotted border-[color-mix(in_srgb,var(--color-meter)_55%,transparent)]" style={{ left: pct(t) }} /> + ))} + {gaps.filter(inView).map((g) => ( + <button + key={`gap-${g.from}`} + type="button" + data-gap-band={`${g.from}-${g.to}`} + disabled={busy} + title={`a gap: ${g.from.toFixed(2)}–${g.to.toFixed(2)} (${(g.to - g.from).toFixed(2)} s) is cut out of the clip — click to put it back`} + onPointerDown={(e) => e.stopPropagation()} + onClick={() => onRemove(g)} + className="absolute top-0 z-[5] h-full cursor-pointer overflow-hidden border-x border-[var(--color-dirty)] p-0 text-left [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-ground)_70%,transparent)_0_5px,color-mix(in_srgb,var(--color-dirty)_22%,transparent)_5px_9px)]" + style={{ left: pct(g.from), width: width(g.from, g.to) }} + > + <span className="pointer-events-none absolute left-1 top-0.5 rounded bg-[var(--color-panel-2)] px-1 font-mono text-[9px] leading-tight text-[var(--color-dirty)]">cut</span> + </button> + ))} + {selection && inView(selection) && ( + <div + data-gap-selection={`${selection.from.toFixed(2)}-${selection.to.toFixed(2)}`} + aria-hidden + className="pointer-events-none absolute top-0 z-[6] h-full border-x-2 border-dashed border-[var(--color-dirty)] bg-[color-mix(in_srgb,var(--color-dirty)_14%,transparent)]" + style={{ left: pct(selection.from), width: width(selection.from, selection.to) }} + /> + )} + {picking && ( + <div + data-gap-pick-layer="" + className="absolute inset-0 z-[7] cursor-crosshair rounded-md outline outline-1 outline-[var(--color-dirty)]" + onPointerDown={(e) => { + e.currentTarget.setPointerCapture(e.pointerId); + const at = tAt(e.currentTarget, e.clientX); + drag.current = { id: e.pointerId, at }; + onSelect({ from: at, to: at }, false); + }} + onPointerMove={(e) => { + const d = drag.current; + if (!d || d.id !== e.pointerId) return; + const t = tAt(e.currentTarget, e.clientX); + onSelect({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, false); + }} + onPointerUp={(e) => { + const d = drag.current; + if (!d || d.id !== e.pointerId) return; + drag.current = null; + const t = tAt(e.currentTarget, e.clientX); + onSelect({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, true); + }} + onPointerCancel={() => { + drag.current = null; + }} + /> + )} + </> + ); +} + +const OVERVIEW_H = 22; + +/** + * The whole cached window under a zoomed waveform: its peaks small, the + * selection, the gaps, and the stretch shown -- dragged to pan, clicked + * elsewhere to centre there, pinched (two fingers) to zoom. + */ +export function ZoomOverview({ zoom, whole, peaks, sel, gaps }: { zoom: WaveZoom; whole: Span; peaks: Peaks | null; sel: Span; gaps: Span[] }) { + const pal = usePalette(); + const box = useRef<HTMLDivElement | null>(null); + const canvas = useRef<HTMLCanvasElement | null>(null); + const [width, setWidth] = useState(600); + useEffect(() => { + const el = box.current; + if (!el) return; + const ro = new ResizeObserver(() => setWidth(el.clientWidth || 600)); + ro.observe(el); + setWidth(el.clientWidth || 600); + return () => ro.disconnect(); + }, []); + const W = Math.max(1e-6, whole.to - whole.from); + const pct = (t: number) => `${((Math.min(whole.to, Math.max(whole.from, t)) - whole.from) / W) * 100}%`; + useEffect(() => { + const cv = canvas.current; + if (!cv) return; + const dpr = window.devicePixelRatio || 1; + cv.width = Math.max(1, Math.floor(width * dpr)); + cv.height = Math.floor(OVERVIEW_H * dpr); + const g = cv.getContext("2d"); + if (!g) return; + g.setTransform(dpr, 0, 0, dpr, 0, 0); + g.clearRect(0, 0, width, OVERVIEW_H); + const mid = OVERVIEW_H / 2; + const toX = (t: number) => ((t - whole.from) / W) * width; + g.fillStyle = alpha(pal.signal, 0.12); + g.fillRect(toX(sel.from), 0, Math.max(1, toX(sel.to) - toX(sel.from)), OVERVIEW_H); + if (peaks && peaks.max.length) { + const n = peaks.max.length; + const pSpan = Math.max(1e-6, peaks.to - peaks.from); + g.fillStyle = pal["seam-2"]; + for (let i = 0; i < n; i += 1) { + const t0 = peaks.from + (i / n) * pSpan; + const x = toX(t0); + if (x < -1 || x > width + 1) continue; + const y0 = mid - peaks.max[i] * (mid - 2); + const y1 = mid - peaks.min[i] * (mid - 2); + g.fillRect(x, Math.min(y0, y1), Math.max(1, width / n), Math.max(1, Math.abs(y1 - y0))); + } + } + g.fillStyle = alpha(pal.reject, 0.45); + for (const gp of gaps) g.fillRect(toX(gp.from), 0, Math.max(1, toX(gp.to) - toX(gp.from)), OVERVIEW_H); + }, [peaks, width, whole.from, W, sel.from, sel.to, gaps, pal]); + + const drag = useRef<{ id: number; grab: number } | null>(null); + const tAt = (clientX: number) => { + const r = box.current?.getBoundingClientRect(); + if (!r) return whole.from; + return whole.from + Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))) * W; + }; + // Two fingers: the distance between them is the zoom, about their middle. + const pinch = useRef<{ d: number; mid: number } | null>(null); + useEffect(() => { + const el = box.current; + if (!el) return; + const dist = (e: TouchEvent) => Math.abs(e.touches[0].clientX - e.touches[1].clientX); + const midOf = (e: TouchEvent) => (e.touches[0].clientX + e.touches[1].clientX) / 2; + const start = (e: TouchEvent) => { + if (e.touches.length !== 2) return; + e.preventDefault(); + drag.current = null; + pinch.current = { d: Math.max(8, dist(e)), mid: midOf(e) }; + }; + const move = (e: TouchEvent) => { + const p = pinch.current; + if (!p || e.touches.length !== 2) return; + e.preventDefault(); + const d = Math.max(8, dist(e)); + const r = el.getBoundingClientRect(); + const at = whole.from + ((midOf(e) - r.left) / Math.max(1, r.width)) * W; + zoom.set(zoomAt(zoom.vis, whole, at, d / p.d)); + pinch.current = { d, mid: midOf(e) }; + }; + const end = () => { + pinch.current = null; + }; + el.addEventListener("touchstart", start, { passive: false }); + el.addEventListener("touchmove", move, { passive: false }); + el.addEventListener("touchend", end); + return () => { + el.removeEventListener("touchstart", start); + el.removeEventListener("touchmove", move); + el.removeEventListener("touchend", end); + }; + }, [zoom, whole, W]); + + return ( + <div + ref={box} + data-zoom-overview="" + className="relative w-full touch-none select-none overflow-hidden rounded border border-[var(--color-line)] bg-[var(--color-panel-2)]" + style={{ height: OVERVIEW_H }} + onPointerDown={(e) => { + if (pinch.current) return; + e.currentTarget.setPointerCapture(e.pointerId); + const t = tAt(e.clientX); + const inside = t >= zoom.vis.from && t <= zoom.vis.to; + // On the shown stretch: grab it where it was taken. Elsewhere: centre there, then drag. + if (!inside) zoom.centre(t); + const from = inside ? zoom.vis.from : t - (zoom.vis.to - zoom.vis.from) / 2; + drag.current = { id: e.pointerId, grab: t - from }; + }} + onPointerMove={(e) => { + const d = drag.current; + if (!d || d.id !== e.pointerId || pinch.current) return; + const span = zoom.vis.to - zoom.vis.from; + zoom.set(clampVis({ from: tAt(e.clientX) - d.grab, to: tAt(e.clientX) - d.grab + span }, whole)); + }} + onPointerUp={() => { + drag.current = null; + }} + onPointerCancel={() => { + drag.current = null; + }} + > + <canvas ref={canvas} aria-hidden className="absolute inset-0 h-full w-full" /> + <div + data-zoom-window={`${zoom.vis.from.toFixed(2)}-${zoom.vis.to.toFixed(2)}`} + aria-hidden + className={cn("pointer-events-none absolute top-0 h-full rounded-sm border-2 border-[var(--color-sel)] bg-[color-mix(in_srgb,var(--color-sel)_12%,transparent)]")} + style={{ left: pct(zoom.vis.from), width: `calc(${pct(zoom.vis.to)} - ${pct(zoom.vis.from)})` }} + /> + </div> + ); +} diff --git a/umtool/components/projects/bench/RenderGhosts.tsx b/umtool/components/projects/bench/RenderGhosts.tsx @@ -38,7 +38,8 @@ function playWindowOf(sel: { from: number; to: number }, cut: { cutStart: number /** One edge as the render will cut it: where (source s), how far from the edge drawn, and whether a silence moved it. */ export type GhostEdge = { at: number; offset: number; snapped: boolean }; -export type RenderEdges = { start: GhostEdge; end: GhostEdge } | null; +/** The two edges, and the silences they were snapped to (source seconds: the zoomed waveform draws them). */ +export type RenderEdges = { start: GhostEdge; end: GhostEdge; silences: { from: number; to: number }[] } | null; /** "render: +0.52 s" (or "render: here"): a ghost's words. */ export const ghostLabel = (g: GhostEdge) => @@ -52,7 +53,7 @@ export const ghostLabel = (g: GhostEdge) => */ export function useRenderEdges( project: string, - clip: { id: string; start: number; end: number; cutStart: number | null; cutEnd: number | null }, + clip: { id: string; start: number; end: number; cutStart: number | null; cutEnd: number | null; gaps?: { from: number; to: number }[] }, sel: { from: number; to: number }, /** Walking a take: the clip is the take's (the cut-points route reads its manifest). */ take: string | null = null, @@ -81,10 +82,14 @@ export function useRenderEdges( snapLead: got.knobs.snapLead ?? undefined, snapTail: got.knobs.snapTail ?? undefined, }; - const cut = renderCut({ sil: row.silences, fetchStart: row.fetchStart, playFrom: pw.from, playTo: pw.to, render, locked: row.locked ?? null }); + // The clip's gaps: no edge snaps across one (snap.mjs, as the build). + const gaps = clip.gaps?.length ? clip.gaps : null; + const cut = renderCut({ sil: row.silences, fetchStart: row.fetchStart, playFrom: pw.from, playTo: pw.to, render, locked: row.locked ?? null, gaps }); + const fs = row.fetchStart; return { start: { at: cut.start, offset: Number((cut.start - pw.from).toFixed(3)), snapped: cut.snapped.start }, end: { at: cut.end, offset: Number((cut.end - pw.to).toFixed(3)), snapped: cut.snapped.end }, + silences: row.silences.map((x) => ({ from: fs + x.s, to: fs + x.e })), }; } diff --git a/umtool/components/projects/review/LiveDeckPreview.tsx b/umtool/components/projects/review/LiveDeckPreview.tsx @@ -155,8 +155,8 @@ export default function LiveDeckPreview({ // ---- the clock --------------------------------------------------------------- const schedule = doc?.schedule ?? null; const clock = useMemo( - () => (schedule ? liveClock(schedule, { id: clip.id, start: clip.start, end: clip.end, cutStart: cut.cutStart, cutEnd: cut.cutEnd }, { leadIn: doc?.leadIn ?? 0.4 }) : null), - [schedule, clip.id, clip.start, clip.end, cut.cutStart, cut.cutEnd, doc?.leadIn], + () => (schedule ? liveClock(schedule, { id: clip.id, start: clip.start, end: clip.end, cutStart: cut.cutStart, cutEnd: cut.cutEnd, gaps: clip.gaps ?? null }, { leadIn: doc?.leadIn ?? 0.4 }) : null), + [schedule, clip.id, clip.start, clip.end, cut.cutStart, cut.cutEnd, clip.gaps, doc?.leadIn], ); const clockRef = useRef(clock); clockRef.current = clock; diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -99,6 +99,8 @@ export type PlayEntry = { end?: number; cutStart?: number | null; cutEnd?: number | null; + /** Seconds taken out of its middle (gaps.mjs): one item of jump cuts. */ + gaps?: { from: number; to: number }[]; blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null; media?: (MediaRef & { from: number; to: number }) | null; /** Ruled incorrect by the walk: its correction (skipped unless "Show clips marked incorrect"). */ @@ -257,7 +259,7 @@ export default function PlayCut({ const segments = schedule?.segments ?? view.segments; const leadIn = doc?.leadIn ?? view.leadIn; // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change. - const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd])), [view.entries]); + const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd, e.gaps ?? null])), [view.entries]); const edges = useRenderCuts(project, take, edgesKey); // Clips ruled incorrect (the walk's verdict) are SKIPPED unless asked for: // the cut the operator means to ship does not hold them (umtool check diff --git a/umtool/components/projects/review/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx @@ -2,7 +2,7 @@ import { useMemo, useRef, useState } from "react"; import { cn } from "@/lib/utils"; -import { counterAt, dateRamp, playPlan, rulerTicks, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; +import { counterAt, dateRamp, gapJoins, playPlan, rulerTicks, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; type PlayItem = ReturnType<typeof playPlan>["items"][number]; @@ -198,6 +198,20 @@ export default function ReelStrip({ ); })} + {/* a clip's gaps (gaps.mjs): a jump cut inside its cell, where the seconds it leaves out were */} + {items.flatMap((it) => + gapJoins(it).map((g) => ( + <span + key={`gap:${it.id}:${g.from}`} + data-play-gap={`${it.id}@${g.at}`} + title={`${it.id}: ${(g.to - g.from).toFixed(2)} s cut out (${g.from.toFixed(2)}–${g.to.toFixed(2)}) — a jump cut`} + aria-hidden + className="pointer-events-none absolute top-0 z-[1] h-full w-0 border-l border-dashed border-[var(--color-dirty)]" + style={{ left: pctOf(g.at, total) }} + /> + )), + )} + {/* the entries skipped (ruled incorrect): a greyed, struck-through tag where they would play */} {skipped.map((x) => ( <span diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -1,5 +1,6 @@ import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; -import { itemIndexAt, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; +import { inGap } from "umtool-report-to-video/gaps"; +import { cutAtSource, itemIndexAt, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; import { audioSpans, decodeSpanOf, scheduleFrom } from "@/lib/report/playSchedule.mjs"; import { drawFootageLayers, type FootageLayer } from "../footageCanvas"; import { AudioBank, type ClipSound } from "./audioBank"; @@ -180,7 +181,7 @@ export class PlayEngine { this.t = plan.items[same].from; } else if (it?.clip && same >= 0 && plan.items[same].clip) { const src = sourceAt(it, this.now()); - this.t = Math.max(plan.items[same].from, Math.min(plan.items[same].to - 0.001, plan.items[same].start + ((src ?? 0) - plan.items[same].clip!.sourceFrom))); + this.t = Math.max(plan.items[same].from, Math.min(plan.items[same].to - 0.001, cutAtSource(plan.items[same], src ?? 0))); } else this.t = Math.min(this.now(), Math.max(0, plan.total - 0.001)); } else this.t = Math.min(this.t, Math.max(0, plan.total - 0.001)); this.cur = Math.max(0, itemIndexAt(plan, this.t)); @@ -341,8 +342,10 @@ export class PlayEngine { private spanSound(id: string): { media: MediaRef; span: { from: number; to: number } } | null { const e = this.entries.get(id); - const s = this.spans.find((x) => x.id === id); - if (!e?.media || !s) return null; + // A clip with gaps is several spans (one per piece that plays): ONE decode covers them all. + const all = this.spans.filter((x) => x.id === id); + if (!e?.media || !all.length) return null; + const s = { src: Math.min(...all.map((x) => x.src)), srcTo: Math.max(...all.map((x) => x.srcTo)) }; return { media: e.media, span: decodeSpanOf(s) }; } @@ -639,9 +642,16 @@ export class PlayEngine { missing = true; continue; } - drawn.push({ i: l.i, mediaTime: l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp / 1e6 }); + const mediaTime = l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp / 1e6; const it = items[l.i]; const e = this.entries.get(it.id); + // A clip's gap (gaps.mjs) never plays: the frames a decoder (or a seeking element) passes + // on its way across one are not drawn -- the last picture holds until the far side's is here. + if (it.clip?.gaps?.length && inGap(mediaTime + (e?.media?.from ?? 0), it.clip.gaps)) { + missing = true; + continue; + } + drawn.push({ i: l.i, mediaTime }); const src = sourceAt(it, t); const b = e?.blur && this.blurRendered ? e.blur : null; const blur = b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity) diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -48,6 +48,7 @@ Inbox cannot disagree about what is wrong with one. | `notes …` | operator notes: list, read, reply, resolve ([notes.md](notes.md)) | | `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--effect NAME] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) | | `take <project> --id <id> --label L [--patch F \| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]` | a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)) | +| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json]` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints. `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") | | `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed | | `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` | | `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) | @@ -152,6 +153,18 @@ c01: 43.12–61.48 -> 43.12–61.48 `--no-lock-end` **removes** the key rather than writing `false`: these manifests are read by humans, and `"lockEnd": false` reads like a decision. +Gaps — seconds cut out of a clip's middle, so it renders as one segment of jump cuts +(knobs.md, "Gaps inside a clip") — go through the same writer, applied to the list as +it is when the write lands, each an undo point (`umtool timeline <p> undo`): + +``` +$ umtool window ferret-rescue c01 --gap 50.2-52.9 --gap 57.1-57.8 +c01: 43.12–61.48 -> 43.12–61.48 + gaps: −50.20–52.90, −57.10–57.80 — the cut plays 14.96s of 18.36s, one segment of jump cuts +``` + +`--gap-remove 51` takes out the gap holding that second; `--gaps ''` clears them all. + ## `link` names the article a project is the video of An article links to a project its iterations made, to one whose manifest names it diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -33,6 +33,7 @@ that generates it ([notes.md](notes.md)). | `layout` — `finale`: the deck's finale layout for this clip (`render.chrome.deck.finale`); `clip` is the default | — | `umtool set <p> <clip> layout=finale` | — | | `fx.zoom` — `{shot, focus, at?, hold?}`: a screenshot (a file in the project; a bare name under its `shots/` is written as `shots/<name>`) that comes up over the footage and pushes in on `focus` (`[left, top, right, bottom]`, fractions of the shot) — drawn once `render.chrome.fx.zoom` is on ([Effects](#effects)). **How long it stays**: up 0.2 s into the clip's clean span (rising in over 0.38 s), its focus box drawn 0.55 s later, the push at `at` (seconds into the clip; default as soon as the box has drawn) over 1 s, then a slow drift on the detail; it leaves with a 0.3 s fade 0.3 s before the clip's clean span ends — or, with `hold` (0.5–10 s), that long after the push lands (never past the clip's own leave) | — | `umtool set <p> <clip> fx.zoom='{"shot":"shots/x.png","focus":[0.1,0.2,0.9,0.4],"at":5.9,"hold":4}'` (`fx.zoom=` clears it) | `PUT /api/report/window {project, clip, "fx.zoom": {…} \| null}` | | `fx.receipts`, `fx.punch`, `fx.quote`, `fx.punchIn`, `fx.speakers` — the clip's other effect fields (`[{shot, mark?}]` 1–4; the words to punch; `false`: no line; 1–8 source seconds inside the clip; `[{at, who: 0\|1}]`), each inert until its effect is on; `fx` is all of them at once. Checked by the build's own `validateFxEntries` | — | `fx.punch="the words"` `fx.punchIn='[231.4]'` · `fx='{…}'` sets them all, `fx=` clears every one | `PUT /api/report/window {project, clip, fx}` (or one `"fx.<field>"`) | +| `gaps` — `[{from, to}]`, SOURCE seconds cut out of the clip's middle: it renders as ONE segment of jump cuts (one pip, one card), not two clips with a crossfade ([below](#gaps-inside-a-clip)) | clip bench (Edit this clip), the waveform: **Select a gap** (`g`) or Alt + drag a span, **Cut gap** (`g`), **Hear it**; a click on a gap's band puts it back (`G`: the one at the playhead); **Undo** | `umtool window <p> <clip> --gap 12.3-15.1` (repeatable) · `--gap-remove 12.3` · `--gaps '12.3-15.1,20-20.6'` (`--gaps ''` clears) · `umtool set <p> <clip> gap.add=12.3-15.1 gap.remove=12.3 gaps=` | `PUT /api/report/window {project, clip, token, gapAdd \| gapRemove \| gaps}` | `key=` (nothing after the `=`) clears a knob; in umtool, **Clear** beside a field (Audio: **Clear all**). A claim's knobs are read from the clip that **stamps** it — the last clip carrying the claim id; the box on any other @@ -40,6 +41,49 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the claim's id and verdict and keeps its knobs while the id stays the same. +## Gaps inside a clip + +A clip may leave seconds out of its middle: you suggest one long clip and cut a gap or two out of it, rather than +making two clips (a crossfade, a second rail pip, a second subtitle card). `gaps: [{from, to}]` on the clip, in SOURCE +seconds (`report-to-video/gaps.mjs` is the rule and both clocks). + +- **The rule** (the writer's, the build's validators' and `umtool check`'s `clip-gap-invalid`, blocking): each gap + inside the clip's cut (`cutStart`–`cutEnd`, else its extent), at least 0.2 s, at most 12 of them, in order, apart, + and at least 0.5 s of material before the first, between any two and after the last. A window, cut or mark save that + would leave a gap outside the cut is refused, as the mute mark's is. **A `muteFrom` or a claim mark's `at` strictly + inside a gap is refused** (on its edge is fine: it lands at the join) — it names a second the cut never plays, and + clamping it to the join would move a decision made by ear. A split inside a gap is refused (split at its edge); a + split gives each half the gaps on its side; a merge keeps both lists. +- **The render**: one segment whose footage is the kept pieces joined with hard cuts — the picture trimmed on the frame + grid, the sound cut at the same instants with a 25 ms fade out and in at each join so nothing clicks. Its length is + the kept seconds. The cut record (`segments/<id>.cut.json`) names the `gaps` it left out, and everything that maps a + source second onto the cut reads them: the mute mark and a locked edge's silence, a claim stamped at a source second, + a deck claim check, the stats region, the effects' words and punch-ins, captions, a partial blur, room's muted tail, + the estimate's length, a trailer's beats (a beat across a gap plays the master's jump cut). The QR, the pip and the + header are the clip's, unchanged; the subtitle's clock part is the clip's `cite` — a fixed second, so it does not + move (a `cite` inside a gap is noted at build). No edge snaps across a gap, nor nearer one than 0.5 s. Loudness is + measured over the whole cut, gaps included. A gap changed re-renders that clip's segment only. A montage cuts to its + phrase: gaps are not applied there (noted). Absent or `[]`, the render is byte for byte what it was. +- **The bench** draws each gap as a hatched band on the waveform (and on the cue rail); every playback there skips + them as the cut will. Gap writes go through the one window writer at once (not drafted like the edges), each an undo + point (`auto-before-gaps`: `umtool timeline <p> undo`), and **Undo** beside them writes the list back. +- **Play the cut** plays the clip as one item: its sound one span per kept piece on the cut's clock with the same + fades, the picture past the gap at the join, the clock and the scrub bar in cut seconds, a dashed tick on the reel + strip at each jump. +- **`umtool timeline <p> ls`** shows a clip's gaps and what it then plays. + +### The bench waveform's zoom + +Where edges, the mute mark and gaps are set. **Ctrl/⌘ + wheel** (a trackpad pinch is one) zooms at the pointer — the +second under it stays there; **−** / **+** / **Fit** / **Zoom to selection** (the gap being selected, else the +selection); keys `z` in, `Z` out, `f` fit, `F` to the selection. Zoomed, the wheel pans (either axis), and an +**overview** strip under the waveform shows the whole cached window with what is shown, the selection and the gaps: +drag it to pan, click elsewhere to centre, pinch it with two fingers. A ruler of round ticks sits over a zoomed +waveform; at 20 s across or closer it also draws the measured silences (the cut-points route's, the build's own) and +the pauses between words (when the project's words file is this recording's), so a gap's edge goes between two words. +At fit — the default, on every clip — the waveform is what it always was. (Play the cut's reel strip is a scrubber; +nothing is trimmed there, so it has no zoom.) + ## A clip's picture, blurred For footage a platform's graphic-content rules would refuse (the operator's case: a clip showing a dog having a diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -42,6 +42,7 @@ travel. umtool never reorders as a side effect of a window edit. "start": 32980.24, "end": 32994.19, // the reviewed EXTENT, absolute source seconds, 2 dp "cutStart": 32986.1, "cutEnd": 32992.4, // the CUT that plays, inside the extent "lockCut": true, // the cut is deliberate; the resolver leaves it + "gaps": [{ "from": 32988.4, "to": 32990.1 }], // optional: seconds cut out of the cut's middle -- one segment of jump cuts "cite": 32989, // the second shown in the attribution line "citeUrl": "https://…", // optional: overrides the derived QR target "quote": "…", // the words this clip exists for @@ -159,6 +160,17 @@ incorrect** is ticked. - **`lock` is about the extent; `lockCut` is about the cut.** The resolver honours both, and never overwrites existing cut fields without `--force-cut`. +### Gaps — seconds cut out of the cut's middle + +`gaps: [{from, to}]` (source seconds) takes seconds out of the middle of a clip, which then renders as ONE segment of +jump cuts — one header, one pip, one subtitle card — rather than as two clips with a crossfade. Each gap lies inside +the CUT (the extent when there is none), at least 0.2 s, at most 12, apart, with 0.5 s kept at the edges and between +them; a mute mark or claim mark inside one is refused. `umtool check` reports a malformed gap as `clip-gap-invalid`, +**blocking**, as it does `clip-cut-outside`. The build trims the kept pieces on the frame grid and joins them with a +25 ms sound fade at each join; the cut record names the gaps, and every source-to-cut mapping reads it. Written by the +bench (a span dragged on its waveform), `umtool window --gap/--gap-remove/--gaps` and `umtool set gap.add=…`; the +whole of it is in [knobs.md, "Gaps inside a clip"](knobs.md#gaps-inside-a-clip). + The matcher is deliberately loose, because a quote is prose a human wrote about speech a machine transcribed: case and punctuation are dropped, `[bracketed]` editorial words and `[Speaker]` markers are dropped, and an **ellipsis splits @@ -1064,6 +1076,34 @@ the one the take was made from (its `baseHash`), the card says **The project cha take was made** and the pick waits for **Use anyway**. A take that does not record its base asks the same. + +### Render mode: giving a render the machine + +A render you are waiting for is slowed by what else the machine does — the transcription +lane's ASR, the editor, e2e servers and browsers — more than by memory (measured 2026-10-30: +under 1 GB in its scope while cutting, ~200 MB per Chromium worker while capturing). So a take +can ask for the machine: + +```sh +umtool take <project> --id <take> … --priority # this take's lifetime +umtool render-mode on --for 90m --note "the Ember cut" # a window for a chain of renders +umtool render-mode status +umtool render-mode off +``` + +On the Takes page, **Give renders the machine** (this browser's toggle) starts every take — +New take, Make all styles, a card's Render — with `--priority`, and a banner says while a +render holds the machine. + +While render mode is on, every other heavy job waits at the heavy slot's door (e2e suites, +`next build`s, the publish stages, other renders); the render is admitted on the floor +4000 MB and the cap 10240 MB; the editor's transcription and download lanes are held — only +the ones that were not held already, and only those are let go. A take's hold ends with the +take: done, failed, or stopped (Ctrl-C, the job's Stop). A window ends at its `until` +(2 h unless `--for`), or with `off`. A hold whose process died is no hold: the gate ignores +it at once, and the editor's heartbeat releases its lanes. Close Firefox and other heavy +apps while it renders. + ### A take's work files, and pruning them A take's build leaves behind what makes the NEXT build fast: its clip segments, the chrome diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -928,7 +928,26 @@ function readBody(req, then) { }); } +// The lanes' gates, as render mode (lib/report/renderMode.mjs) reads and holds +// them: `GET /api/ops/settings?key=autoQueue` and `POST /api/ops/lane`. +// download starts held, so a spec sees render mode leave someone else's hold alone. +const lanes = { transcription: { held: false }, download: { held: true }, digest: { held: false }, backfill: { held: false } }; + function generationRoute(req, res, url, auth) { + if (req.method === "GET" && url.pathname === "/api/ops/settings" && url.searchParams.get("key") === "autoQueue") { + req.resume(); + return json(res, 200, { ok: true, key: "autoQueue", value: lanes }); + } + if (req.method === "POST" && url.pathname === "/api/ops/lane") { + return readBody(req, (body) => { + requests.push({ route: "lane", ...(body ?? {}), authorization: auth }); + record(); + const lane = lanes[body?.lane]; + if (!lane || typeof body?.held !== "boolean") return json(res, 400, { ok: false, error: '"lane" and "held"' }); + lane.held = body.held; + return json(res, 200, { ok: true, lane: body.lane }); + }); + } if (req.method === "GET" && url.pathname === "/api/ops/settings") { req.resume(); const value = { ...generation, apiKeyFile: "<redacted>" }; diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1865,6 +1865,22 @@ makeMarksFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "cl makeLivePreviewFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // The Play view: the whole cut (and a take) played with no render, notes at the playhead (play-cut.spec.ts). makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut, +// undone, put back): its own project on gapvid, a recording id of its own (the fixture's vid1 +// window -- tone, silences at 2.9-3.1 and 5.9-6.1 -- so nothing another spec fetches moves it). +// g01 gapvid 0.5-8.5 (locked: its edges are where they are written, in the tone) +// g02 gapvid 1.0-3.0 (locked) +// No deck: Play the cut plays it on the estimate's clock and the render's edges. +{ + const g = manifest("gaps-fixture", "The Gaps Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "clip", id: "g01", video: "gapvid", start: 0.5, end: 8.5, cite: 1, section: 0, lock: true, quote: "a clip with a gap" }, + { type: "clip", id: "g02", video: "gapvid", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "the clip after it" }, + ]); + g.render.fetchPad = 0; + const dir = writeProject("gaps-fixture", g); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "gapvid_0.00-9.00.mp4")); +} // The same cut for Play → Edit this clip → Back (phone-walk.spec.ts), which WRITES // an edge: its own copy, so play-cut.spec's clock is never moved. makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-edit-fixture", title: "The Play Edit Fixture", video: "vid1" }); diff --git a/umtool/e2e/gaps-zoom.spec.ts b/umtool/e2e/gaps-zoom.spec.ts @@ -0,0 +1,289 @@ +import { test, expect, type APIRequestContext, type Page } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Gaps inside a clip (umtool-report-to-video gaps.mjs) and the bench +// waveform's zoom (components/projects/bench/GapsZoom.tsx): +// +// - the waveform zooms (+ / − / Fit, Ctrl + wheel at the pointer, the keys) +// and pans (the wheel, the overview strip); close in it draws the measured +// silences; at fit it is what it always was +// - a span selected on the waveform (Select a gap, or Alt + drag) is cut out +// of the clip through the window writer; Undo puts the list back; a click +// on a gap's band removes it; a span the build would refuse is refused here +// - the bench's playback skips a gap, as the cut will +// - Play the cut plays the clip as ONE item of jump cuts: the render's +// footage less the gap, one sound node per kept piece, the picture past +// the gap at the join, a tick on the reel strip +// +// Fixture: gaps-fixture (make-fixture.mjs), which this spec WRITES: g01 +// gapvid 0.5-8.5 and g02 1.0-3.0, both locked, on the fixture's tone window +// (silences 2.9-3.1, 5.9-6.1) cached as gapvid_0.00-9.00.mp4; 15 fps. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const PROJECT = "reports/gaps-fixture"; +const MANIFEST = path.join(HERE, "..", ".e2e-song", "reports", "gaps-fixture", "video.manifest.json"); +type Gap = { from: number; to: number }; +const clipOf = (id: string) => + (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: { id: string; start: number; end: number; gaps?: Gap[] }[] }).timeline.find((e) => e.id === id)!; + +const token = async (request: APIRequestContext, clip = "g01") => + ((await (await request.get(`/api/report/clip?project=${encodeURIComponent(PROJECT)}&clip=${clip}`)).json()) as { token: string }).token; +const putWindow = async (request: APIRequestContext, data: Record<string, unknown>, clip = "g01") => + request.put("/api/report/window", { data: { project: PROJECT, clip, token: await token(request, clip), ...data } }); + +/** The bench, with its waveform scrolled on screen (the mouse only reaches what is in the viewport). */ +const openBench = async (page: Page, clip = "g01") => { + await page.goto(urls.clipBenchHref(PROJECT, clip)); + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + await expect(page.locator("[data-wave-box]")).toBeInViewport(); +}; + +/** The waveform's shown span, [from, to] (data-wave-vis). */ +const visOf = async (page: Page) => { + const v = (await page.locator("[data-wave-box]").getAttribute("data-wave-vis"))!; + const [a, b] = v.split("-").map(Number); + return { from: a, to: b }; +}; +/** A source second's x on the waveform, as shown now. */ +const xAt = async (page: Page, t: number) => { + const b = (await page.locator("[data-wave-box]").boundingBox())!; + const v = await visOf(page); + return b.x + ((t - v.from) / (v.to - v.from)) * b.width; +}; +const tAtX = async (page: Page, x: number) => { + const b = (await page.locator("[data-wave-box]").boundingBox())!; + const v = await visOf(page); + return v.from + ((x - b.x) / b.width) * (v.to - v.from); +}; +const midY = async (page: Page) => { + const b = (await page.locator("[data-wave-box]").boundingBox())!; + return b.y + b.height / 2; +}; +/** Drag on the waveform from source second a to b. */ +const dragSpan = async (page: Page, a: number, b: number) => { + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + const y = await midY(page); + await page.mouse.move(await xAt(page, a), y); + await page.mouse.down(); + await page.mouse.move((await xAt(page, a) + (await xAt(page, b))) / 2, y, { steps: 3 }); + await page.mouse.move(await xAt(page, b), y, { steps: 3 }); + await page.mouse.up(); +}; +const spanOf = (s: string | null) => (s ?? "").split("-").map(Number); + +/** The bench's keyboard is attached on hydration: prove it with `x` (focuses the correction box, writes nothing). */ +const keyboardLive = async (page: Page) => { + const box = page.locator("[data-attrib-field=correction]"); + await expect(async () => { + await page.locator("body").press("x"); + await expect(box).toBeFocused({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); + await box.blur(); +}; + +test.beforeEach(async ({ request }) => { + test.setTimeout(120_000); + // Every test starts from no gaps. + const r = await putWindow(request, { gaps: [] }); + expect(r.ok(), await r.text()).toBeTruthy(); +}); + +test("the bench waveform zooms at the pointer, pans, and fits back to what it always was", async ({ page }) => { + await openBench(page); + const zoom = page.locator("[data-wave-zoom]"); + await expect(zoom).toHaveAttribute("data-wave-zoom", "fit"); + await expect(page.locator("[data-zoom-ruler]")).toHaveCount(0); + await expect(page.locator("[data-zoom-overview]")).toHaveCount(0); + const whole = await visOf(page); + + // + zooms in (about the playhead, else the middle): a ruler and the overview appear. + await page.locator("[data-zoom-in]").click(); + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + await expect(zoom).not.toHaveAttribute("data-wave-zoom", "fit"); + await expect(page.locator("[data-zoom-ruler]")).toBeVisible(); + await expect(page.locator("[data-zoom-overview]")).toBeVisible(); + let v = await visOf(page); + expect(v.to - v.from).toBeCloseTo((whole.to - whole.from) / 1.6, 2); + + // Ctrl + wheel at the pointer: the second under it stays under it. + const x3 = await xAt(page, 3); + await page.mouse.move(x3, await midY(page)); + await page.keyboard.down("Control"); + await page.mouse.wheel(0, -240); + await page.keyboard.up("Control"); + await expect.poll(async () => (await visOf(page)).to - (await visOf(page)).from).toBeLessThan(v.to - v.from - 0.5); + expect(await tAtX(page, x3)).toBeCloseTo(3, 1); + v = await visOf(page); + + // The wheel alone pans while zoomed. + await page.mouse.wheel(0, 120); + await expect.poll(async () => (await visOf(page)).from).toBeGreaterThan(v.from + 0.05); + const panned = await visOf(page); + expect(panned.to - panned.from).toBeCloseTo(v.to - v.from, 2); + + // The overview: its window is what is shown; dragging it pans back. + await page.locator("[data-zoom-overview]").scrollIntoViewIfNeeded(); + const win = page.locator("[data-zoom-window]"); + const wb = (await win.boundingBox())!; + await page.mouse.move(wb.x + wb.width / 2, wb.y + wb.height / 2); + await page.mouse.down(); + await page.mouse.move(wb.x + wb.width / 2 - 60, wb.y + wb.height / 2, { steps: 4 }); + await page.mouse.up(); + await expect.poll(async () => (await visOf(page)).from).toBeLessThan(panned.from - 0.1); + + // Close in, the measured silences are drawn (the cut-points route's: 2.9-3.1 on this window). + await page.locator("[data-zoom-fit]").click(); + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + await expect(zoom).toHaveAttribute("data-wave-zoom", "fit"); + await page.mouse.move(await xAt(page, 3), await midY(page)); + await page.keyboard.down("Control"); + for (let i = 0; i < 3; i += 1) await page.mouse.wheel(0, -300); + await page.keyboard.up("Control"); + await expect.poll(async () => (await visOf(page)).to - (await visOf(page)).from).toBeLessThan(3); + await expect(page.locator("[data-wave-silence]").first()).toBeVisible({ timeout: 30_000 }); + const sil = spanOf(await page.locator("[data-wave-silence]").first().getAttribute("data-wave-silence")); + expect(sil[0]).toBeGreaterThan(2.8); + expect(sil[1]).toBeLessThan(3.2); + // Finer ticks: under a second apart. + expect(Number(await page.locator("[data-zoom-ruler]").getAttribute("data-zoom-ruler"))).toBeLessThan(1); + + // The keys: f fits, z zooms in, Z out. + await keyboardLive(page); + await page.locator("body").press("f"); + await expect(zoom).toHaveAttribute("data-wave-zoom", "fit"); + await page.locator("body").press("z"); + await expect(zoom).not.toHaveAttribute("data-wave-zoom", "fit"); + await page.locator("body").press("Shift+Z"); + await expect(zoom).toHaveAttribute("data-wave-zoom", "fit"); +}); + +test("a gap: selected on the waveform, cut, undone; Alt + drag and g; a click on its band puts it back; refusals", async ({ page, request }) => { + await openBench(page); + await expect(page.locator("[data-gaps]")).toHaveAttribute("data-gaps", ""); + const before = clipOf("g01"); + + // Select a gap, drag 3.5 → 5.5 on the waveform. + await page.locator("[data-gap-pick]").click(); + await expect(page.locator("[data-gap-pick=armed]")).toBeVisible(); + await dragSpan(page, 3.5, 5.5); + const sel = spanOf(await page.locator("[data-gap-selection]").getAttribute("data-gap-selection")); + expect(sel[0]).toBeCloseTo(3.5, 1); + expect(sel[1]).toBeCloseTo(5.5, 1); + await expect(page.locator("[data-bench-note]")).toContainText("selected"); + await page.locator("[data-gap-cut]").click(); + await expect.poll(() => clipOf("g01").gaps?.length ?? 0).toBe(1); + const g = clipOf("g01").gaps![0]; + expect(g.from).toBeCloseTo(3.5, 1); + expect(g.to).toBeCloseTo(5.5, 1); + // The edges did not move; the band is drawn; the summary says what plays. + expect([clipOf("g01").start, clipOf("g01").end]).toEqual([before.start, before.end]); + await expect(page.locator("[data-gap-band]")).toHaveCount(1); + await expect(page.locator("[data-gaps-summary]")).toContainText(/the cut plays \d\.\d\d s of 8\.00 s, one segment/); + await expect(page.locator("[data-rail-gap]")).toHaveCount(1); + + // Undo writes the list back as it was. + await page.locator("[data-gap-undo]").click(); + await expect.poll(() => clipOf("g01").gaps).toBeUndefined(); + await expect(page.locator("[data-gap-band]")).toHaveCount(0); + + // Alt + drag selects without arming, and never moves an edge; `g` cuts it. + await page.keyboard.down("Alt"); + await dragSpan(page, 4, 5); + await page.keyboard.up("Alt"); + await expect(page.locator("[data-gap-selection]")).toBeVisible(); + expect([clipOf("g01").start, clipOf("g01").end]).toEqual([before.start, before.end]); + await expect(page.locator("[data-save-window]")).toBeDisabled(); + await keyboardLive(page); + await page.locator("body").press("g"); + await expect.poll(() => clipOf("g01").gaps?.length ?? 0).toBe(1); + expect(clipOf("g01").gaps![0].from).toBeCloseTo(4, 1); + + // A click on the band puts the seconds back. + await page.locator("[data-gap-band]").click(); + await expect.poll(() => clipOf("g01").gaps).toBeUndefined(); + + // Too close to the clip's start: said, and nothing written. + await page.locator("[data-gap-pick]").click(); + await dragSpan(page, 0.7, 1.4); + await expect(page.locator("[data-bench-note]")).toContainText("cannot be cut"); + await page.locator("[data-gap-cut]").click(); + await expect(page.locator("[data-bench-note]")).toContainText("keep at least 0.5 s"); + expect(clipOf("g01").gaps).toBeUndefined(); + + // The writer's own refusals, through the route. + let r = await putWindow(request, { gapAdd: "0.6-1" }); + expect(r.status()).toBe(400); + expect(((await r.json()) as { error: string }).error).toMatch(/keep at least 0.5 s/); + r = await putWindow(request, { gapAdd: "3.5-5.5" }); + expect(r.ok()).toBeTruthy(); + r = await putWindow(request, { muteFrom: 4 }); + expect(r.status()).toBe(400); + expect(((await r.json()) as { error: string }).error).toMatch(/inside the gap 3\.5–5\.5, which never plays/); +}); + +test("the bench plays across a gap the way the cut will: the gap is skipped", async ({ page, request }) => { + expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy(); + await page.goto(urls.clipBenchHref(PROJECT, "g01")); + const playback = page.locator("[data-playback]"); + await expect(playback).toHaveAttribute("data-audio-state", "ready", { timeout: 15_000 }); + await expect(page.locator("[data-gap-band]")).toHaveCount(1); + await keyboardLive(page); + await page.locator("body").press(" "); + await expect(playback).toHaveAttribute("data-play-state", "playing", { timeout: 10_000 }); + expect(await playback.getAttribute("data-play-engine")).toBe("webaudio"); + const a = Number(await playback.getAttribute("data-play-ctx-start")); + const b = Number(await playback.getAttribute("data-play-ctx-stop")); + // 0.5-8.5 less the 2 s gap: six seconds of sound, not eight. + expect(b - a).toBeCloseTo(6, 2); + expect(Number(await playback.getAttribute("data-play-to"))).toBeCloseTo(8.5, 2); + await page.locator("body").press(" "); +}); + +test("Play the cut plays a gapped clip as one item of jump cuts", async ({ page, request }) => { + expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy(); + // The render's cut: the gap on the frame grid, the footage the kept seconds. + const got = await (await request.get(`/api/report/cut-points?project=${encodeURIComponent(PROJECT)}`)).json(); + const g01 = got.clips.find((c: { id: string }) => c.id === "g01"); + expect(g01).toMatchObject({ cutStart: 0.5, cutEnd: 8.5, gaps: [{ from: 3.5, to: 5.5 }], footage: 6 }); + + await page.goto(urls.playHref(PROJECT)); + const root = page.locator("[data-play-cut]"); + await expect(root).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + await expect(root).toHaveAttribute("data-play-item", "g01"); + // The jump cut on the reel strip, 3 s into the clip. + await expect(page.locator("[data-play-gap]")).toHaveAttribute("data-play-gap", "g01@3"); + await page.locator("[data-play-toggle]").click(); + await expect(root).toHaveAttribute("data-play-sound", "webaudio", { timeout: 15_000 }); + // Past the join: the picture is the material after the gap (5.5 on), never 3.5-5.5. Every + // frame drawn while g01 plays is said (data-play-drawn): none from inside the gap. + const seen: string[] = []; + await expect + .poll(async () => { + const t = Number(await root.getAttribute("data-play-t")); + const d = (await page.locator("[data-play-footage]").getAttribute("data-play-drawn")) ?? ""; + seen.push(`${t.toFixed(2)}=${d}`); + const [id, at] = d.split(":"); + return id === "g01" && t > 3.2 ? Number(at) : -1; + }, { timeout: 20_000, intervals: [100] }) + .toBeGreaterThan(5.5); + console.log(`gaps-zoom: drawn ${seen.join(" ")}`); + const inGap = seen.map((x) => x.split("=")[1]).filter((d) => d.startsWith("g01:")).map((d) => Number(d.split(":")[1])).filter((at) => at > 3.6 && at < 5.4); + expect(inGap, "no frame from inside the gap").toEqual([]); + // Two sound nodes for g01, abutting at the join (cut second 3), and g02 after its six seconds. + const s = await page.evaluate( + () => (window as unknown as { __umtoolPlayEngine: { stats: { scheduled: { id: string; from: number; to: number; run: number }[] } } }).__umtoolPlayEngine.stats, + ); + const mine = s.scheduled.filter((n) => n.id === "g01"); + const run = mine[mine.length - 1].run; + const pieces = mine.filter((n) => n.run === run).sort((x, y) => x.from - y.from); + expect(pieces.length).toBe(2); + expect(pieces[0].to).toBeCloseTo(3, 2); + expect(pieces[1].from).toBeCloseTo(3, 2); + expect(pieces[1].to).toBeCloseTo(6, 2); + await page.keyboard.press("k"); +}); diff --git a/umtool/e2e/takes.spec.ts b/umtool/e2e/takes.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { readFileSync, writeFileSync } from "node:fs"; +import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; @@ -240,6 +240,65 @@ test("the take maker: New take with a style, the take appears, Use this take mak await expect(page.locator("[data-take='soft'] [data-take-picked]")).toBeVisible(); }); +test("Give renders the machine: the take runs with --priority, holds the lane it found free, lets it go, and the banner says so", async ({ page, request }) => { + test.setTimeout(240_000); + const SONG = path.join(HERE, "..", ".e2e-song"); + const STATE = path.join(SONG, "render-priority.json"); + // The stub writes its log on its first request after the fixture is built: none yet is no asks. + const laneAsks = () => { + let asks: Array<{ route: string; lane?: string; held?: boolean }> = []; + try { + asks = JSON.parse(readFileSync(path.join(SONG, "editor-stub.requests.json"), "utf8")); + } catch { + /* not written yet */ + } + return asks.filter((x) => x.route === "lane").map((x) => `${x.lane}:${x.held}`); + }; + const before = laneAsks().length; + + // The toggle is this browser's: every take the page starts carries priority. + await page.goto(MAKE_PAGE); + const toggle = page.locator("[data-render-priority]"); + await expect(toggle).toBeEnabled(); + await toggle.check(); + expect(await page.evaluate(() => localStorage.getItem("umtool:render-priority"))).toBe("on"); + await page.reload(); + await expect(page.locator("[data-render-priority]")).toBeChecked(); + + // The route the form posts: priority makes it `umtool take … --priority`. + const r = await request.post("/api/report/takes/make", { + data: { project: "reports/takes-make-fixture", take: { label: "Prio", window: "full" }, priority: true }, + }); + expect(r.status()).toBe(200); + const { job } = (await r.json()) as { job: { id: string; steps: Array<{ argv: string[] }> } }; + expect(job.steps[0].argv).toContain("--priority"); + await expect + .poll(async () => ((await (await request.get(`/api/report/takes/make?job=${job.id}`)).json()) as { state: string }).state, { timeout: 180_000 }) + .toBe("done"); + // The stub's download lane was held already: left alone, never released. + expect(laneAsks().slice(before)).toEqual(["transcription:true", "transcription:false"]); + expect(existsSync(STATE)).toBe(false); + + // While a render holds it, the panel says so (this process is the holder: alive). + writeFileSync( + STATE, + JSON.stringify({ + version: 1, token: "e2e", since: new Date().toISOString(), until: null, by: "e2e", note: null, + holder: { pid: process.pid, cmd: "umtool take takes-make-fixture --id prio" }, + lanesHeld: ["transcription"], lanesSkipped: ["download"], + }), + ); + try { + await page.reload(); + const banner = page.locator("[data-render-mode-banner]"); + await expect(banner).toContainText("transcription lane held for umtool take takes-make-fixture --id prio"); + await expect(banner).toContainText("Close Firefox and other heavy apps"); + } finally { + rmSync(STATE, { force: true }); + } + await expect(page.locator("[data-render-mode-banner]")).toHaveCount(0, { timeout: 10_000 }); +}); + test("the Takes page with the New take form open fits a phone", async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }); await page.goto(MAKE_PAGE); diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -124,6 +124,7 @@ const ACTION_LABEL = { "clip-mid-sentence": "Trim to the sentence", "clip-cue-gap": "Fix the window", "clip-cut-outside": "Fix the cut", + "clip-gap-invalid": "Fix the gaps", "clip-incorrect": "Remove or fix the clip", "window-overlap": "Fix the windows", "no-punctuation": "Check the windows", diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -29,6 +29,7 @@ export const WHAT = { "clip-mid-sentence": "clips end mid-sentence", "clip-cue-gap": "clips over a cue gap", "clip-cut-outside": "cuts outside the window", + "clip-gap-invalid": "gaps the build refuses", "clip-incorrect": "clips marked incorrect", "window-overlap": "windows overlap", "no-punctuation": "windows without punctuation", diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -39,6 +39,7 @@ const segmentDirs = (outDir) => [ import { adjudicationGaps, ledgerTotals, unadjudicatedOf } from "umtool-report-to-video/ledger-totals"; import { widen } from "umtool-report-to-video/resolve-windows"; import { montageOn } from "umtool-report-to-video/montage"; +import { validateGaps } from "umtool-report-to-video/gaps"; import { fileSig, pathCache } from "../pathCache.mjs"; // widen() and the cache's window naming are IMPORTED, never reimplemented. The @@ -983,6 +984,11 @@ export const REPORT_DECISION_KINDS = [ // written -- silently ignore it and render the whole extent instead. Both // are the render disagreeing with the manifest about what the clip IS. "clip-cut-outside", + // A clip's `gaps` (seconds taken out of its middle, gaps.mjs) that the build + // refuses: outside the cut, overlapping, too short, too close together, or a + // mark inside one. BLOCKING for the same reason: the render would refuse the + // whole manifest, or cut seconds nobody chose. + "clip-gap-invalid", // A clip ruled `incorrect` (the walk's verdict, with its correction) that is // still in the timeline. BLOCKING: the build would render it, the counter // would count its marks, and the video would cite a clip somebody already @@ -1281,6 +1287,12 @@ export async function reportDecisions(ctx, summary) { } } + // GAPS INSIDE A CLIP keep the build's rule (gaps.mjs validateGaps): inside + // the cut, in order, apart, and no mark in one. + for (const e of clips) { + for (const why of validateGaps(e, e.id)) add("clip-gap-invalid", e.id, why, "blocking", { href: clipHref(e.id) }); + } + // A clip with no numeric window cannot be built, widened or benched. The // scaffold's `--seed chapters` writes one when the last chapter has no // duration to end at, and says so; this is where it stays visible. diff --git a/umtool/lib/report/benchZoom.mjs b/umtool/lib/report/benchZoom.mjs @@ -0,0 +1,120 @@ +// THE BENCH WAVEFORM'S ZOOM, as arithmetic (ClipBench.tsx, bench/GapsZoom.tsx): +// which stretch of the cached window the waveform shows, moved by a zoom at a +// point (the pointer's second stays under the pointer), a pan, a fit and a +// zoom to a span; the ruler's ticks for what is shown; and the pauses between +// words, drawn once the waveform is close enough to place a gap (or an edge) +// in one. Pure: no DOM, no React, so it is unit-tested (benchZoom.test.mjs) +// and the component only applies it. +// +// EVERYTHING IS IN ABSOLUTE SOURCE SECONDS, like the bench. `whole` is the +// cached window (what the waveform shows at fit -- today's view); `vis` the +// stretch of it shown now. + +/** The closest the waveform zooms: a quarter of a second across its width. */ +export const MIN_ZOOM_SPAN = 0.25; +/** One step of + / − (and of a wheel notch, scaled by its delta). */ +export const ZOOM_STEP = 1.6; +/** At or under this many seconds shown, the measured silences and the words' boundaries are drawn. */ +export const DETAIL_SPAN = 20; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const round4 = (v) => Math.round(v * 10000) / 10000; + +/** `vis` kept inside `whole`, at least MIN_ZOOM_SPAN (or the whole) wide. */ +export function clampVis(vis, whole) { + const W = Math.max(1e-6, whole.to - whole.from); + const span = Math.min(W, Math.max(Math.min(MIN_ZOOM_SPAN, W), vis.to - vis.from)); + let from = Math.max(whole.from, Math.min(vis.from, whole.to - span)); + if (!fin(from)) from = whole.from; + return { from: round4(from), to: round4(Math.min(whole.to, from + span)) }; +} + +/** Is `vis` the whole window (no zoom)? */ +export const isFit = (vis, whole) => !vis || (vis.from <= whole.from + 1e-3 && vis.to >= whole.to - 1e-3); + +/** + * Zoom by `factor` (> 1 in, < 1 out) about source second `at`: the second + * under the pointer stays under it. At fit and zooming out, fit. + */ +export function zoomAt(vis, whole, at, factor) { + const v = vis ?? whole; + const span = v.to - v.from; + const next = Math.min(whole.to - whole.from, Math.max(MIN_ZOOM_SPAN, span / (factor > 0 ? factor : 1))); + const a = fin(at) ? Math.min(v.to, Math.max(v.from, at)) : (v.from + v.to) / 2; + const frac = span > 0 ? (a - v.from) / span : 0.5; + return clampVis({ from: a - frac * next, to: a - frac * next + next }, whole); +} + +/** Move what is shown by `dt` seconds (clamped to the window). */ +export function panBy(vis, whole, dt) { + const v = vis ?? whole; + return clampVis({ from: v.from + dt, to: v.to + dt }, whole); +} + +/** Show `range` with `margin` of its length either side (at least MIN_ZOOM_SPAN). */ +export function zoomTo(range, whole, margin = 0.15) { + const len = Math.max(MIN_ZOOM_SPAN, range.to - range.from); + const pad = len * margin; + return clampVis({ from: range.from - pad, to: range.to + pad }, whole); +} + +/** Centre what is shown on `t`, keeping its width. */ +export function centreOn(vis, whole, t) { + const v = vis ?? whole; + const span = v.to - v.from; + return clampVis({ from: t - span / 2, to: t + span / 2 }, whole); +} + +/** A wheel notch as a zoom factor: deltaY < 0 zooms in; a trackpad's small deltas zoom a little. */ +export function wheelFactor(deltaY, deltaMode = 0) { + const px = deltaMode === 1 ? deltaY * 16 : deltaMode === 2 ? deltaY * 400 : deltaY; + return Math.exp(-px * 0.0025); +} + +const STEPS = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600]; + +/** + * The ruler for what is shown: a round step that gives at most `maxTicks` + * ticks, and each tick's second (a multiple of the step). + */ +export function rulerFor(vis, maxTicks = 10) { + const span = Math.max(1e-6, vis.to - vis.from); + const step = STEPS.find((s) => span / s <= maxTicks) ?? STEPS[STEPS.length - 1]; + const ticks = []; + for (let k = Math.ceil(vis.from / step - 1e-9); k * step <= vis.to + 1e-9; k += 1) ticks.push(round4(k * step) + 0); + return { step, ticks }; +} + +/** A tick's label: `m:ss` for a step of a second or more, else `m:ss.s` / `m:ss.ss`. */ +export function tickLabel(t, step) { + const s = Math.max(0, t); + const m = Math.floor(s / 60); + const sec = s - m * 60; + const dp = step >= 1 ? 0 : step >= 0.1 ? 1 : 2; + const text = sec.toFixed(dp).padStart(dp ? 3 + dp : 2, "0"); + const h = Math.floor(m / 60); + return h ? `${h}:${String(m % 60).padStart(2, "0")}:${text}` : `${m}:${text}`; +} + +/** + * The gaps between words, as places an edge or a gap's edge can go: for each + * pause between consecutive words (or cues), its middle; and every measured + * silence's middle. Sorted, deduplicated within 20 ms. In [from, to]. + * + * @param {{ words?: Array<{ start: number, end: number }> | null, silences?: Array<{ from: number, to: number }> | null }} o + * @param {number} from + * @param {number} to + */ +export function quietPoints({ words = null, silences = null }, from, to) { + const pts = []; + const ws = (words ?? []).filter((w) => fin(w.start) && fin(w.end)).sort((a, b) => a.start - b.start); + for (let i = 1; i < ws.length; i += 1) { + if (ws[i].start >= ws[i - 1].end) pts.push((ws[i - 1].end + ws[i].start) / 2); + } + for (const s of silences ?? []) if (fin(s.from) && fin(s.to)) pts.push((s.from + s.to) / 2); + const out = []; + for (const p of pts.filter((x) => x >= from && x <= to).sort((a, b) => a - b)) { + if (!out.length || p - out[out.length - 1] > 0.02) out.push(round4(p)); + } + return out; +} diff --git a/umtool/lib/report/benchZoom.test.mjs b/umtool/lib/report/benchZoom.test.mjs @@ -0,0 +1,68 @@ +// The bench waveform's zoom (benchZoom.mjs): a zoom keeps the pointer's second +// under the pointer, never past the window or closer than MIN_ZOOM_SPAN; a pan +// stops at the window's edges; fit is the whole; the ruler's round ticks; the +// pauses between words. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { MIN_ZOOM_SPAN, centreOn, clampVis, isFit, panBy, quietPoints, rulerFor, tickLabel, wheelFactor, zoomAt, zoomTo } from "./benchZoom.mjs"; + +const W = { from: 10, to: 40 }; +const near = (a, b, what, tol = 1e-3) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +test("zoomAt: the second under the pointer stays there; never closer than MIN_ZOOM_SPAN, never wider than the window", () => { + const v = zoomAt(null, W, 16, 2); + near(v.to - v.from, 15, "half the window"); + near((16 - v.from) / (v.to - v.from), (16 - 10) / 30, "the pointer's fraction"); + const out = zoomAt(v, W, 16, 1 / 4); + assert.deepEqual(out, W, "out past the whole: the whole"); + assert.equal(isFit(out, W), true); + let z = W; + for (let i = 0; i < 40; i += 1) z = zoomAt(z, W, 25, 3); + near(z.to - z.from, MIN_ZOOM_SPAN, "the closest"); + assert.ok(z.from <= 25 && z.to >= 25); + // Near an edge: kept inside the window. + const e = zoomAt({ from: 10, to: 12 }, W, 10, 1 / 2); + assert.ok(e.from >= 10 && e.to <= 40); +}); + +test("panBy, centreOn, zoomTo, clampVis: inside the window, the width kept", () => { + assert.deepEqual(panBy({ from: 20, to: 25 }, W, 3), { from: 23, to: 28 }); + assert.deepEqual(panBy({ from: 20, to: 25 }, W, 100), { from: 35, to: 40 }); + assert.deepEqual(panBy({ from: 20, to: 25 }, W, -100), { from: 10, to: 15 }); + assert.deepEqual(centreOn({ from: 20, to: 24 }, W, 30), { from: 28, to: 32 }); + assert.deepEqual(zoomTo({ from: 20, to: 30 }, W), { from: 18.5, to: 31.5 }); + assert.deepEqual(clampVis({ from: 5, to: 5.01 }, W), { from: 10, to: 10.25 }); + assert.equal(isFit(null, W), true); + assert.equal(isFit({ from: 10, to: 39 }, W), false); +}); + +test("wheelFactor: a notch up zooms in, down out; a trackpad's small delta a little", () => { + assert.ok(wheelFactor(-100) > 1); + assert.ok(wheelFactor(100) < 1); + near(wheelFactor(-100) * wheelFactor(100), 1, "symmetric"); + assert.ok(Math.abs(wheelFactor(-4) - 1) < 0.02); + assert.ok(wheelFactor(-3, 1) > 1.1, "a line-mode notch"); +}); + +test("rulerFor / tickLabel: round steps, finer as it zooms; labels to the step's precision", () => { + assert.deepEqual(rulerFor({ from: 0, to: 9 }), { step: 1, ticks: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] }); + const r = rulerFor({ from: 2.53, to: 3.4 }); + assert.equal(r.step, 0.1); + assert.deepEqual(r.ticks, [2.6, 2.7, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4]); + assert.equal(rulerFor({ from: 0, to: 600 }).step, 60); + assert.equal(tickLabel(65, 5), "1:05"); + assert.equal(tickLabel(65.25, 0.05), "1:05.25"); + assert.equal(tickLabel(3.5, 0.5), "0:03.5"); + assert.equal(tickLabel(3725, 60), "1:02:05"); +}); + +test("quietPoints: the middle of each pause between words, and of each silence, in the span, once", () => { + const words = [{ start: 1, end: 1.4 }, { start: 1.6, end: 2 }, { start: 2, end: 2.5 }, { start: 3.1, end: 3.3 }]; + assert.deepEqual(quietPoints({ words }, 0, 10), [1.5, 2, 2.8]); + assert.deepEqual(quietPoints({ words, silences: [{ from: 2.7, to: 2.91 }, { from: 5, to: 6 }] }, 0, 5.4), [1.5, 2, 2.8]); + assert.deepEqual(quietPoints({ silences: [{ from: 5, to: 6 }] }, 0, 10), [5.5]); + assert.deepEqual(quietPoints({}, 0, 10), []); +}); diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -94,7 +94,8 @@ export async function readWords(dir, reactions = null) { * 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, * vertical: { crop: number[], aspect?: number } | null, - * room: false | { tail?: boolean, head?: boolean } | null, roomEdges: { tail: boolean, head: boolean } | null }} EditorClip + * room: false | { tail?: boolean, head?: boolean } | null, roomEdges: { tail: boolean, head: boolean } | null, + * gaps?: Array<{ from: number, to: number }> }} EditorClip */ /** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */ @@ -115,6 +116,8 @@ export async function clipEditorView(project) { end: e.end, cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null, + // Seconds cut out of its middle (gaps.mjs): the live preview's clock jumps with them. + ...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}), quote: typeof e.quote === "string" ? e.quote : null, title: typeof e.title === "string" ? e.title : typeof e.onscreen?.title === "string" ? e.onscreen.title : null, assist: isObj(e.assist) ? e.assist : null, @@ -249,12 +252,17 @@ const overlapping = (list, from, to) => /** * What the strip draws for [from, to] around one clip: turns, laughs, words * (or cues when the project has no word timings), and the source's length - * when known. + * when known. `video` (the clip bench, zoomed in): the words only when they + * are THAT recording's (`reactions.source.video`) -- a project's words file + * is one recording's, and another's words would be drawn in the wrong places. + * + * @param {{ id: string, dir: string }} project + * @param {{ clip?: string | null, from: number, to: number, video?: string | null }} opts */ -export async function clipNeighbourhood(project, { clip, from, to }) { +export async function clipNeighbourhood(project, { clip, from, to, video = null }) { if (!fin(from) || !fin(to) || to <= from) throw new Error("from and to must be seconds, from < to"); const { doc } = await readReactions(project.dir); - const words = await readWords(project.dir, doc); + const words = video && doc?.source?.video !== video ? null : await readWords(project.dir, doc); const turns = overlapping(doc?.turns, from, to).map((t) => ({ start: t.start, end: t.end, speaker: t.speaker })); const laughs = overlapping(doc?.laughs, from, to).map((l) => ({ start: l.start, end: l.end, score: fin(l.score) ? l.score : null, speaker: fin(l.speaker) ? l.speaker : null })); let cues = 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; + /** Seconds cut out of its middle (gaps.mjs), when it has any. */ + gaps?: { from: number; to: number }[]; /** A short's framing (release 36): `crop` = [x, y, w, h], fractions of the source picture. */ vertical: { crop: number[]; aspect?: number } | null; /** Room at its edges (release 36 lane E): the clip's own `room` as written (false: none), and the edges it gets. */ diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -36,6 +36,7 @@ import { loudnessGain, montageOn, parseIntegratedLoudness } from "umtool-report- import { loudnessTargetOf } from "umtool-report-to-video/look"; import { ROOM, clipRoom } from "umtool-report-to-video/room"; import { lockedEdges, soundOnSegment } from "umtool-report-to-video/mute"; +import { gapSeconds, gapsOnSegment, renderGaps } from "umtool-report-to-video/gaps"; import { renderCut, snapKnobs } from "umtool-report-to-video/snap"; import { transitionStyleOf } from "umtool-report-to-video/transition"; import { CACHE_DIR } from "../paths.mjs"; @@ -130,6 +131,9 @@ async function cutContext(project, take) { * snapped { start, end }: which edge moved to a silence * sound [from, to] the sound is heard over, when room mutes * an edge (else the whole segment) + * gaps [{from, to}] the seconds its segment leaves out + * (gaps.mjs; the build's frame-grid edges), absent + * without any -- `footage` is already less them * gainDb render.loudness's gain for the cut (none: absent) * audio the clip's own audio knobs (clip-audio.mjs), absent when none * playFrom / playTo the play window it was snapped from (deck.mjs playWindow) @@ -198,7 +202,9 @@ async function clipCutPoints(entry, ctx) { ); const pw = playWindow(entry, render); const locked = lockedEdges(entry, render); - const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked }); + // A clip's gaps (gaps.mjs): no edge snaps across one, as in the build. None in a montage. + const clipGaps = montage ? [] : renderGaps(entry, render); + const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}) }); const { cutA, cutB } = cut.file; let segA = cutA; let segB = cutB; @@ -228,10 +234,13 @@ async function clipCutPoints(entry, ctx) { // begun counted (the build's cutOffsets sums the probed frames; measured on // the Huck walk, 34 of 51 segments exactly this, the rest one frame more). const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30; + // The gaps as the build applies them: on the segment's frame grid (build-video.mjs buildClipSegment). + const segGaps = clipGaps.length ? gapsOnSegment(clipGaps, fetchStart + segA, segB - segA, fps) : []; + const gaps = segGaps.map((g) => ({ from: r3(fetchStart + segA + g.from), to: r3(fetchStart + segA + g.to) })); const row = { id: entry.id, window: path.basename(src.path), - footage: Number((Math.ceil((segB - segA) * fps - 1e-6) / fps).toFixed(6)), + footage: Number((Math.ceil((segB - segA - gapSeconds(segGaps)) * fps - 1e-6) / fps).toFixed(6)), fetchStart: r3(fetchStart), silences: sil, playFrom: pw.from, @@ -242,6 +251,7 @@ async function clipCutPoints(entry, ctx) { // Which edges are the author's (mute.mjs lockedEdges): the bench snaps a dragged edge with them. ...(locked.start || locked.end ? { locked } : {}), ...(sound ? { sound } : {}), + ...(gaps.length ? { gaps } : {}), ...(montage ? { montage: true } : {}), }; const target = loudnessTargetOf(render); @@ -258,7 +268,7 @@ async function clipCutPoints(entry, ctx) { // Where the sound is heard (mute.mjs soundOnSegment, the build's join rule): // the mute mark (a finale's ending sound), or a locked end the segment // reaches past -- silent from it -- and a locked start it reaches before. - const on = soundOnSegment(entry, render, row.cutStart, row.footage); + const on = soundOnSegment(entry, render, row.cutStart, row.footage, gaps.length ? gaps : null); if (on.mute != null && on.edges.muteFrom != null) row.muteFrom = on.edges.muteFrom; if (on.soundFrom != null && on.edges.soundFrom != null) row.soundFrom = on.edges.soundFrom; return row; diff --git a/umtool/lib/report/gaps-writer.test.mjs b/umtool/lib/report/gaps-writer.test.mjs @@ -0,0 +1,154 @@ +// Gaps inside a clip, written (umtool-report-to-video gaps.mjs; the one writer, +// manifest.mjs patchClipEntry): `gaps` / `gapAdd` / `gapRemove` through +// updateClip, checked against the entry after the patch -- a window, cut or +// mark save that leaves a gap outside, or a mark in one, is refused and the +// file is left as it was; an undo point first; split and merge carry them; +// `umtool set gap.add=…`; `umtool check`'s clip-gap-invalid row. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-gaps-writer-")); +process.env.REPORTS_DIR = ROOT; +const { MANIFEST_NAME, mergeClips, splitClip, updateClip, updateMarks } = await import("./manifest.mjs"); +const { setCommand } = await import("./knobsCli.mjs"); +const { timelineLines, timelineRows } = await import("./timelineCli.mjs"); + +const MANIFEST = { + schemaVersion: 1, + slug: "gaps", + title: "Gaps", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline: [ + { type: "clip", id: "c01", video: "v1", start: 10, end: 30, cutStart: 12, cutEnd: 28 }, + { type: "clip", id: "c02", video: "v1", start: 30, end: 40 }, + ], +}; + +let n = 0; +async function project(manifest = MANIFEST) { + const dir = path.join(ROOT, `p${(n += 1)}`); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + return dir; +} +const raw = (dir) => readFile(path.join(dir, MANIFEST_NAME), "utf8"); +const read = async (dir) => JSON.parse(await raw(dir)); +const clip = async (dir, id) => (await read(dir)).timeline.find((e) => e.id === id); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("updateClip: gapAdd (a span or a list), merged with a gap it touches; gapRemove by a second inside; gaps sets, [] or '' clears", async () => { + const dir = await project(); + let r = await updateClip(dir, "c01", { gapAdd: "15.004-17.333" }); + assert.deepEqual(r.entry.gaps, [{ from: 15, to: 17.33 }]); + r = await updateClip(dir, "c01", { gapAdd: [{ from: 20, to: 21 }, "17-17.6"] }); + assert.deepEqual(r.entry.gaps, [{ from: 15, to: 17.6 }, { from: 20, to: 21 }]); + r = await updateClip(dir, "c01", { gapRemove: 16 }); + assert.deepEqual(r.entry.gaps, [{ from: 20, to: 21 }]); + r = await updateClip(dir, "c01", { gaps: [{ from: 22, to: 23 }, { from: 14, to: 14.5 }] }); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 14, to: 14.5 }, { from: 22, to: 23 }], "sorted on write"); + await updateClip(dir, "c01", { gaps: [] }); + assert.equal("gaps" in (await clip(dir, "c01")), false, "an empty list removes the key"); + await updateClip(dir, "c01", { gapAdd: "15-16" }); + await updateClip(dir, "c01", { gaps: "" }); + assert.equal("gaps" in (await clip(dir, "c01")), false); + // Removing the last gap removes the key too. + await updateClip(dir, "c01", { gapAdd: "15-16" }); + await updateClip(dir, "c01", { gapRemove: 15.5 }); + assert.equal("gaps" in (await clip(dir, "c01")), false); +}); + +test("updateClip: a gap the build would refuse is refused, and the file is left byte for byte", async () => { + const dir = await project(); + await updateClip(dir, "c01", { gapAdd: "15-17" }); + const before = await raw(dir); + const refuses = async (patch, re) => { + await assert.rejects(updateClip(dir, "c01", patch), re); + assert.equal(await raw(dir), before, `${JSON.stringify(patch)} left the file as it was`); + }; + await refuses({ gapAdd: "11-13" }, /outside the clip's cut 12–28/); + await refuses({ gapAdd: "12.2-13" }, /after the cut's start; keep at least 0.5 s/); + await refuses({ gapAdd: "20-20.1" }, /under 0.2 s/); + await refuses({ gapAdd: "17.2-18" }, /merge|keep at least/); + await refuses({ gapAdd: "nonsense" }, /a gap is FROM-TO/); + await refuses({ gapRemove: 25 }, /no gap at 25/); + await refuses({ gaps: "15-17" }, /must be a list/); + // A cut save that leaves the gap outside (or too close to the new edge). + await refuses({ cutStart: 16, cutEnd: 28 }, /outside the clip's cut 16–28/); + await refuses({ cutStart: 14.8 }, /after the cut's start/); + // A mute mark inside the gap. + await refuses({ muteFrom: 16 }, /muteFrom 16 lies inside the gap 15–17, which never plays/); + // On its edge it is fine. + const r = await updateClip(dir, "c01", { muteFrom: 17 }); + assert.equal(r.entry.muteFrom, 17); +}); + +test("updateClip: a gap edit leaves an undo point (auto-before-gaps); another edit does not", async () => { + const dir = await project(); + await updateClip(dir, "c01", { title: "x" }); + const has = async () => (await readdir(path.join(dir, "revisions")).catch(() => [])).some((f) => f.includes("auto-before-gaps")); + assert.equal(await has(), false); + const r = await updateClip(dir, "c01", { gapAdd: "15-17" }); + assert.equal(await has(), true); + assert.ok(r.snapshot, "the answer names it"); +}); + +test("updateMarks: a mark's second inside a gap is refused", async () => { + const dir = await project(); + await updateClip(dir, "c01", { gapAdd: "15-17" }); + const before = await raw(dir); + await assert.rejects(updateMarks(dir, "c01", { add: { verdict: "CONTRADICTED", at: 16 } }), /lies inside the gap 15–17, which never plays.* nothing was written/); + assert.equal(await raw(dir), before); + const r = await updateMarks(dir, "c01", { add: { verdict: "CONTRADICTED", at: 18 } }); + assert.equal(r.marks.length, 1); +}); + +test("splitClip: each half keeps the gaps on its side; a split inside a gap is refused; merge joins them", async () => { + const dir = await project(); + await updateClip(dir, "c01", { gapAdd: ["14-15", "24-25"] }); + await assert.rejects(splitClip(dir, "c01", 14.5), /inside the gap 14–15/); + const s = await splitClip(dir, "c01", 20); + const a = await clip(dir, "c01"); + const b = await clip(dir, s.second); + assert.deepEqual(a.gaps, [{ from: 14, to: 15 }]); + assert.deepEqual(b.gaps, [{ from: 24, to: 25 }]); + // Too close to the new edge: refused, by the gap rule. + const dir2 = await project(); + await updateClip(dir2, "c01", { gapAdd: "18-19.8" }); + await assert.rejects(splitClip(dir2, "c01", 20), /split at 20: .*keep at least 0.5 s/); + // Merge back: both lists, in order. + await mergeClips(dir, "c01"); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 14, to: 15 }, { from: 24, to: 25 }]); +}); + +test("umtool set: gap.add=, gap.remove=, gaps= (a list, JSON, or empty); timeline ls shows them", async () => { + const dir = await project(); + const lines = []; + const run = (...args) => setCommand(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }); + const name = path.basename(dir); + assert.equal(await run(name, "c01", "gap.add=15-17", "gap.add=20-21"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 15, to: 17 }, { from: 20, to: 21 }]); + assert.match(lines.at(-1), /c01: gaps 15–17, 20–21/); + assert.equal(await run(name, "c01", "gap.remove=20.5"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 15, to: 17 }]); + const rows = timelineRows(await read(dir)); + assert.deepEqual(rows[0].gaps, [{ from: 15, to: 17 }]); + assert.equal(rows[0].plays, 14); + assert.match(timelineLines(rows)[0], /gaps −15\.00–17\.00 \(plays 14\.00s\)/); + assert.equal(await run(name, "c01", "gaps=13-14,22-23"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 13, to: 14 }, { from: 22, to: 23 }]); + assert.equal(await run(name, "c01", 'gaps=[{"from":18,"to":19}]'), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 18, to: 19 }]); + assert.equal(await run(name, "c01", "gaps="), 0); + assert.equal("gaps" in (await clip(dir, "c01")), false); + assert.match(lines.at(-1), /no gaps/); + assert.equal(await run(name, "c01", "gaps=12-zz"), 2); + assert.equal(await run(name, "c01", "gap.add=11-12.5"), 1); + assert.match(lines.at(-1), /^ERR .*outside the clip's cut/); +}); diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -42,6 +42,7 @@ import { import { CLAIM_KNOBS, STAMP_KNOB_DEFAULTS, VARIANTS_DEFAULT, rawMarksOf, stampingEntryId, variantsOf } from "./knobs.mjs"; import { variantsSteps } from "./driver.mjs"; import { buildFileOf, outDirOf, variantsState } from "./variantsView.mjs"; +import { parseGapSpec } from "umtool-report-to-video/gaps"; export const AUDIO_KNOBS = Object.freeze(["offset", "gain", "fadeIn", "fadeOut"]); export const BLUR_KNOBS = Object.freeze(["on", "caption", "strength", "from", "to"]); @@ -50,7 +51,12 @@ const MARK_KEYS = ["marks", "mark.add", "mark.remove", "mark.verdict"]; const REVIEW_KEYS = ["verdict", "reason", "correction"]; /** The clip's effects (report-to-video fx.mjs): `fx=<json>` whole (`fx=` clears it), `fx.<field>=<json>` one field. */ const FX_KEYS = ["fx", ...FX_ENTRY_FIELDS.map((k) => `fx.${k}`)]; -const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, ...FX_KEYS]; +/** Seconds taken out of the clip's middle (gaps.mjs): the whole list, one added, one removed. */ +const GAP_KEYS = ["gaps", "gap.add", "gap.remove"]; +const SET_KEYS = [ + ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, + ...FX_KEYS, ...GAP_KEYS, +]; export const SET_USAGE = [ "usage: umtool set <project> <clip> key=value … [--mark <id>] [--json]", @@ -80,6 +86,9 @@ export const SET_USAGE = [ " detail, absent: to the clip's end); fx.receipts='[{\"shot\":\"shots/a.png\",\"mark\":[0,0.4,1,0.5]}]' (1–4);", " fx.punch=\"the words\"; fx.quote=false; fx.punchIn='[231.4]' (source seconds);", " fx.speakers='[{\"at\":231,\"who\":1}]'; fx='{…}' sets them all, `fx=` clears every one, `fx.<field>=` that one.", + " gap.add=12.3-15.1 cuts those source seconds out of the clip's middle (one segment of jump cuts; inside", + " the cut, ≥ 0.2 s, 0.5 s kept between); gap.remove=<sec> the gap holding it; gaps=12.3-15.1,20-20.6 (or", + " a JSON list of {from,to}) the whole list, `gaps=` none. The same as `umtool window --gap/--gap-remove/--gaps`.", ].join("\n"); export const LOOK_USAGE = [ @@ -190,6 +199,18 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso entryPatch[key] = value === null || value === undefined ? "" : String(value); continue; } + if (GAP_KEYS.includes(key)) { + if (key === "gap.add") (entryPatch.gapAdd ??= []).push(String(value ?? "")); + else if (key === "gap.remove") entryPatch.gapRemove = Number(value); + else if (value === null || (Array.isArray(value) && !value.length)) entryPatch.gaps = []; + else if (Array.isArray(value)) entryPatch.gaps = value; + else { + const list = String(value).split(",").map((s) => s.trim()).filter(Boolean).map(parseGapSpec); + if (list.some((g) => !g)) throw new CliError(`gaps=${value}: a comma-separated list of FROM-TO in source seconds, or a JSON list of {from,to}`); + entryPatch.gaps = list; + } + continue; + } if (MARK_KEYS.includes(key)) { markChanges.push(markChangeOf(key, value, mark)); continue; @@ -226,6 +247,9 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso if ("blur" in entryPatch) results.blur = result.entry.blur ?? null; if ("layout" in entryPatch) results.layout = result.entry.layout ?? "clip"; if (FX_KEYS.some((k) => k in entryPatch)) results.fx = result.entry.fx ?? null; + if ("gaps" in entryPatch || "gapAdd" in entryPatch || "gapRemove" in entryPatch) { + results.gaps = result.entry.gaps ?? []; + } if (REVIEW_KEYS.some((k) => k in entryPatch)) { results.review = { verdict: result.entry.verdict ?? null, reason: result.entry.reason ?? null, correction: result.entry.correction ?? null }; } @@ -247,6 +271,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso if ("blur" in results) out(`${clipId}: blur ${results.blur ? JSON.stringify(results.blur) : "none (the picture as recorded)"}`); if ("layout" in results) out(`${clipId}: layout ${results.layout}`); if ("fx" in results) out(`${clipId}: fx ${results.fx ? JSON.stringify(results.fx) : "none"}`); + if ("gaps" in results) out(`${clipId}: ${results.gaps.length ? `gaps ${results.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "no gaps (the cut plays whole)"}`); if (results.review) { const r = results.review; out(`${clipId}: ${r.verdict ?? "not reviewed"}${r.reason ? ` (${r.reason})` : ""}${r.correction ? ` — ${r.correction}` : ""}`); diff --git a/umtool/lib/report/liveClock.mjs b/umtool/lib/report/liveClock.mjs @@ -13,8 +13,14 @@ // does that this does not: it snaps each edge to a nearby silence (up to // `render.snapWindow`), so the deck's handover at a join can land that much // off; the preview says so. +// +// A clip's GAPS (gaps.mjs: source seconds its segment leaves out) are on the +// clock too: the footage is the kept seconds, a source second after a gap +// plays that much earlier, and one inside a gap plays at its join. + +import { gappedLength, gapsWithin, offsetIn, sourceAtOffset } from "umtool-report-to-video/gaps"; -/** @typedef {{ start: number, end: number, cutStart?: number | null, cutEnd?: number | null }} ClipSpan */ +/** @typedef {{ start: number, end: number, cutStart?: number | null, cutEnd?: number | null, gaps?: Array<{ from: number, to: number }> | null }} ClipSpan */ /** @typedef {{ id: string, start: number, duration: number, end?: number, hold?: number }} Segment */ /** * @typedef {{ claim: string, verdict: string, segment: string, at: number, landed: number, @@ -59,7 +65,8 @@ export function liveClock(schedule, clip, { leadIn = 0.4 } = {}) { const seg = schedule.segments[i]; const pw = livePlayWindow(clip, leadIn); const hold = fin(seg.hold) && /** @type {number} */ (seg.hold) > 0 ? /** @type {number} */ (seg.hold) : 0; - const playEnd = seg.start + Math.max(0, pw.to - pw.from); + const gaps = gapsWithin(Array.isArray(clip.gaps) ? clip.gaps : [], pw.from, pw.to); + const playEnd = seg.start + Math.max(0, gappedLength(pw.from, pw.to, gaps)); return { id: clip.id, index: i, @@ -70,6 +77,7 @@ export function liveClock(schedule, clip, { leadIn = 0.4 } = {}) { playEnd: round(playEnd), hold, end: round(playEnd + hold), + ...(gaps.length ? { gaps } : {}), }; } @@ -88,7 +96,7 @@ export function cutTimeAt(clock, sourceT) { if (!clock || !fin(sourceT)) return { t: clock?.start ?? 0, where: "before" }; if (sourceT < clock.sourceFrom) return { t: clock.start, where: "before" }; if (sourceT > clock.sourceTo) return { t: clock.playEnd, where: "after" }; - return { t: round(clock.start + (sourceT - clock.sourceFrom)), where: "inside" }; + return { t: round(clock.start + offsetIn(sourceT, clock.sourceFrom, clock.gaps)), where: "inside" }; } /** @@ -100,7 +108,7 @@ export function cutTimeAt(clock, sourceT) { */ export function sourceTimeAt(clock, t) { if (!clock || !fin(t) || t < clock.start || t > clock.playEnd) return null; - return round(clock.sourceFrom + (t - clock.start)); + return round(sourceAtOffset(t - clock.start, clock.sourceFrom, clock.gaps)); } /** @@ -164,7 +172,7 @@ export function clipStamps(schedule, clock) { verdict: s.verdict, drawn: s.stamp !== false && !s.finale, landed: s.landed, - sourceLanded: round(clock.sourceFrom + (s.landed - clock.start)), + sourceLanded: round(sourceAtOffset(s.landed - clock.start, clock.sourceFrom, clock.gaps)), })); } diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -49,6 +49,7 @@ import { counterOrder } from "umtool-report-to-video/counter"; import { validateFinaleEntries } from "umtool-report-to-video/finale"; import { validateFxEntries } from "umtool-report-to-video/fx"; import { validateClipAudio } from "umtool-report-to-video/clip-audio"; +import { editGaps, parseGapSpec, validateGaps } from "umtool-report-to-video/gaps"; import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH, validateClipBlur, validateClipBlurEntries } from "umtool-report-to-video/clip-blur"; import { CLAIM_KNOBS, CLAIM_MARKS_MAX, claimKnobsOf, claimKnobValue, freshMarkId, marksCopyOf, normalizeClaimKnobPatch, rawMarksOf, setMarks, stampingEntryId, @@ -191,7 +192,7 @@ const WIN_EPS = 0.02; * @param {string} clipId * @param {Record<string, unknown>} patch * @param {{ token?: string | null }} [opts] - * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null }>} + * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null, snapshot?: Record<string, unknown> }>} */ export async function updateClip(dir, clipId, patch, { token = null, edit = "trim", now = null } = {}) { return withManifestLock(async () => { @@ -202,13 +203,19 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri const raw = await readFile(manifestFile(dir), "utf8"); const manifest = JSON.parse(raw); const { entry, before } = patchClipEntry(manifest, clipId, patch, { edit, now, raw, dir }); + // A gap cut or removed (gaps.mjs) changes what the clip IS in the cut, as a + // split does: an undo point first (`umtool timeline <p> undo`, the Cut tab's Undo). + const snapshot = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined) ? await autoSnapshot(dir, "gaps") : null; const nextToken = await writeManifestAtomic(dir, manifest); // A moved extent may need a new bench excerpt: queued, never waited for. if (entry.start !== before.start || entry.end !== before.end) benchPrepAfterWrite(dir, [clipId]); - return { entry, before, token: nextToken }; + return { entry, before, token: nextToken, ...(snapshot ? { snapshot } : {}) }; }); } +/** The patch keys that edit a clip's gaps (patchClipEntry, "gaps inside the clip"). */ +export const GAP_PATCH_KEYS = Object.freeze(["gaps", "gapAdd", "gapRemove"]); + /** * updateClip's rules over a manifest held in memory: the ONE place a clip * patch is checked and applied. updateClip runs it on the project's file @@ -432,6 +439,52 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n }); } + // ---- gaps inside the clip (gaps.mjs) ------------------------------------- + // + // `gaps: [{from, to}]` -- source seconds taken out of the middle of the cut; + // the clip then renders as ONE segment of jump cuts. Three ways to write + // them, all applied to the list as it is NOW (inside the lock): `gaps` the + // whole list (null, "" or [] clears it), `gapAdd` a span (`{from, to}` or + // "12.3-15.1", or a list of them; merged with a gap it touches), `gapRemove` + // the gap holding a source second. Then the rule (validateGaps, the build's own check) on the + // entry AFTER the patch, as for the mute mark: a window, cut or mark save + // that leaves a gap outside the cut, or a mark inside a gap, is refused. + if (patch.gaps !== undefined || patch.gapAdd !== undefined || patch.gapRemove !== undefined) { + let list = Array.isArray(entry.gaps) ? entry.gaps : []; + if (patch.gaps !== undefined) { + const v = patch.gaps; + if (v === null || v === "") list = []; + else if (!Array.isArray(v)) throw new Error("gaps must be a list of { from, to } in source seconds, or empty to clear them"); + else { + list = editGaps([], { + set: v.map((g, k) => { + const from = Number(g?.from); + const to = Number(g?.to); + if (!Number.isFinite(from) || !Number.isFinite(to)) throw new Error(`gaps[${k}] must be { from, to } in source seconds`); + return { from, to }; + }), + }); + } + } + if (patch.gapAdd !== undefined) { + for (const one of Array.isArray(patch.gapAdd) ? patch.gapAdd : [patch.gapAdd]) { + const g = typeof one === "string" ? parseGapSpec(one) : one; + if (!isObj(g)) throw new Error(`a gap is FROM-TO in source seconds, e.g. 12.3-15.1 (got ${JSON.stringify(one)})`); + list = editGaps(list, { add: { from: Number(g.from), to: Number(g.to) } }); + } + } + if (patch.gapRemove !== undefined) list = editGaps(list, { remove: Number(patch.gapRemove) }); + if (list.length) entry.gaps = list; + else delete entry.gaps; + } + if ( + entry.gaps !== undefined && + ["start", "end", "cutStart", "cutEnd", "muteFrom", "gaps", "gapAdd", "gapRemove"].some((k) => patch[k] !== undefined) + ) { + const errors = validateGaps(entry, clipId); + if (errors.length) throw new Error(errors.join("; ")); + } + // ---- the clip's sound (video knobs) ------------------------------------- // // `audio: { offset, gain, fadeIn, fadeOut }` -- applied at the segment @@ -816,6 +869,11 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no const from = cutOf(e); const hasCut = e.cutStart != null && e.cutEnd != null; const b = JSON.parse(JSON.stringify(e)); + // Gaps go with the half they are in; a split inside one is refused (the + // second it names never plays -- split at the gap's edge instead). + const gaps = Array.isArray(e.gaps) ? e.gaps : []; + const across = gaps.find((g) => t > g.from && t < g.to); + if (across) throw new Error(`${t} is inside the gap ${across.from}–${across.to}, which never plays — split at its edge`); // The first half: up to the split. e.end = t; if (hasCut) e.cutEnd = t; @@ -831,6 +889,16 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no if (b.muteFrom != null && b.muteFrom < t) delete b.muteFrom; delete b.claim; delete b.claims; + const ga = gaps.filter((g) => g.to <= t); + const gb = gaps.filter((g) => g.from >= t); + if (ga.length) e.gaps = ga; + else delete e.gaps; + if (gb.length) b.gaps = gb; + else delete b.gaps; + for (const x of [e, b]) { + const errors = validateGaps(x, x.id); + if (errors.length) throw new Error(`split at ${t}: ${errors.join("; ")}`); + } const qb = textOr(quotes.second, b.quote ?? null); if (qb) b.quote = qb; else delete b.quote; @@ -878,6 +946,14 @@ export async function mergeClips(dir, clipId, { token = null, quote, now = null } if (e.muteFrom != null) delete e.muteFrom; if (b.muteFrom != null) e.muteFrom = b.muteFrom; + // Both clips' gaps, in order: the seconds between them now play. + const gaps = [...(Array.isArray(e.gaps) ? e.gaps : []), ...(Array.isArray(b.gaps) ? b.gaps : [])].sort((x, y) => x.from - y.from); + if (gaps.length) e.gaps = gaps; + else delete e.gaps; + { + const errors = validateGaps(e, e.id); + if (errors.length) throw new Error(`merge ${clipId} + ${b.id}: ${errors.join("; ")}`); + } const q = quote !== undefined ? textOr(quote, null) : [e.quote, b.quote].filter((x) => typeof x === "string" && x.trim()).join(" ") || null; if (q) e.quote = q; else delete e.quote; @@ -2355,6 +2431,11 @@ export async function updateClaimKnobs(dir, entryId, patch, { token = null, mark // The renderer's own check -- each knob, `at` inside the entry's window, no two stamps over each other -- on this entry's rows. const bad = validateClaims(manifest).filter((e) => e.includes(`(${entryId})`)); if (bad.length) throw new Error(`${bad.join("; ")} — nothing was written`); + // A mark's second inside one of the clip's gaps never plays (gaps.mjs). + for (const e of entries) { + const g = validateGaps(e, entryId); + if (g.length) throw new Error(`${g.join("; ")} — nothing was written`); + } const nextToken = await writeManifestAtomic(dir, manifest); const claim = pick(entries[0]); const stampsOn = stampingEntryId(manifest, claim.id); @@ -2450,6 +2531,10 @@ export async function updateMarks(dir, entryId, change, { token = null } = {}) { // The renderer's own check: refused when this change adds a problem. const bad = validateClaims(manifest).filter((x) => !before.has(x)); if (bad.length) throw new Error(`${bad.join("; ")} — nothing was written`); + for (const e of entries) { + const g = validateGaps(e, entryId); + if (g.length) throw new Error(`${g.join("; ")} — nothing was written`); + } const nextToken = await writeManifestAtomic(dir, manifest); const stored = marksCopyOf(entries[0]); return { diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs @@ -15,6 +15,15 @@ // clip's hold) its last frame holds. import { clockText, livePlayWindow } from "./liveClock.mjs"; +import { gappedLength, gapsOf, gapsWithin, offsetIn, sourceAtOffset } from "umtool-report-to-video/gaps"; + +// GAPS INSIDE A CLIP (umtool-report-to-video gaps.mjs): a clip's `gaps` are +// source seconds its segment leaves out, so it plays as one item of jump cuts. +// An item's `clip.gaps` (only when it has any) are those inside its play +// window -- the render's (the cut-points route's `gaps`, on the frame grid) +// with its edges, else the manifest's -- and every cut ↔ source mapping below +// goes through them: the footage is the kept seconds, and a second inside a +// gap plays at its join. // THE RENDER'S EDGES (`cuts`, lib/report/cutPoints.mjs): the build snaps every // clip edge to a silence, so the clip it renders is longer or shorter than @@ -34,7 +43,7 @@ import { clockText, livePlayWindow } from "./liveClock.mjs"; * id: string, index: number, type: string, * start: number, end: number, the segment, in the cut's seconds * from: number, to: number, what the page shows of it: midpoint to midpoint - * clip: null | { sourceFrom: number, sourceTo: number, playEnd: number, hold: number }, + * clip: null | { sourceFrom: number, sourceTo: number, playEnd: number, hold: number, gaps?: Array<{ from: number, to: number }> }, * est?: { start: number, end: number, from: number, to: number, sourceFrom?: number, sourceTo?: number, playEnd?: number }, * with the render's edges: the item on the estimate's clock * }} PlayItem @@ -45,7 +54,8 @@ const round = (v) => Math.round(v * 1000) / 1000; /** * @typedef {{ cutStart: number, cutEnd: number, footage?: number, snapped?: { start: boolean, end: boolean }, - * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number }} RenderCut + * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number, + * gaps?: Array<{ from: number, to: number }> }} RenderCut */ /** @@ -69,16 +79,15 @@ export function playPlan(segments, entries, { leadIn = 0.4, cuts = null } = {}) const before = shift; const c = it.clip ? cutOf(it.id) : null; const ok = !!c && fin(c.cutStart) && fin(c.cutEnd) && c.cutEnd > c.cutStart; - const estAt = { - start: it.start, end: it.end, from: it.from, to: it.to, - ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}), - }; + const estAt = estOf(it); if (!ok) { return { ...it, start: round(it.start + before), end: round(it.end + before), from: round(it.from + before), to: round(it.to + before), clip: it.clip ? { ...it.clip, playEnd: round(it.clip.playEnd + before) } : null, est: estAt }; } - // Its length in the cut: the encode's whole frames when the route said (`footage`), else the span. - const foot = fin(c.footage) && /** @type {number} */ (c.footage) > 0 ? /** @type {number} */ (c.footage) : c.cutEnd - c.cutStart; + // Its gaps as the render takes them out (the route's), else none. + const gaps = Array.isArray(c.gaps) ? gapsWithin(c.gaps, c.cutStart, c.cutEnd) : []; + // Its length in the cut: the encode's whole frames when the route said (`footage`), else the span (less its gaps). + const foot = fin(c.footage) && /** @type {number} */ (c.footage) > 0 ? /** @type {number} */ (c.footage) : gappedLength(c.cutStart, c.cutEnd, gaps); // The estimate's segment is its footage (at least a second) and its hold; the render's, its cut and the same hold. const delta = foot + it.clip.hold - (it.end - it.start); shift += delta; @@ -97,6 +106,7 @@ export function playPlan(segments, entries, { leadIn = 0.4, cuts = null } = {}) ...(c.snapped ? { snapped: c.snapped } : {}), ...(fin(c.muteFrom) ? { muteFrom: c.muteFrom } : {}), ...(fin(c.soundFrom) ? { soundFrom: c.soundFrom } : {}), + ...(gaps.length ? { gaps } : {}), }, est: estAt, }; @@ -123,7 +133,7 @@ export function chromeTime(plan, t) { if (it.clip && fin(e.sourceFrom)) { if (t > it.clip.playEnd) return clampTo(e.playEnd + (t - it.clip.playEnd), e.from, e.to); const src = /** @type {number} */ (sourceAt(it, t)); - return clampTo(e.start + (src - e.sourceFrom), e.from, it.clip.hold > 0 ? e.playEnd : e.to); + return clampTo(e.start + offsetIn(src, e.sourceFrom, e.gaps), e.from, it.clip.hold > 0 ? e.playEnd : e.to); } return clampTo(e.from + (t - it.from), e.from, e.to); } @@ -150,7 +160,7 @@ export function playTimeOfChrome(plan, tc) { const clampTo = (v) => round(Math.min(it.to, Math.max(it.from, v))); if (it.clip && fin(e.sourceFrom)) { if (tc > e.playEnd) return clampTo(it.clip.playEnd + (tc - e.playEnd)); - return clampTo(cutAtSource(it, e.sourceFrom + (tc - e.start))); + return clampTo(cutAtSource(it, sourceAtOffset(tc - e.start, e.sourceFrom, e.gaps))); } return clampTo(it.from + (tc - e.from)); } @@ -184,10 +194,7 @@ export function skipEntries(plan, ids) { shift += Math.max(0, it.to - it.from); continue; } - const est = it.est ?? { - start: it.start, end: it.end, from: it.from, to: it.to, - ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}), - }; + const est = it.est ?? estOf(it); const s = (v) => round(v - shift); items.push({ ...it, @@ -203,6 +210,15 @@ export function skipEntries(plan, ids) { return { ...plan, items, total: items.length ? items[items.length - 1].end : 0, skipped }; } +/** An item's place on the estimate's clock (`est`), its gaps with it when it has any. */ +function estOf(it) { + return { + start: it.start, end: it.end, from: it.from, to: it.to, + ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}), + ...(it.clip?.gaps ? { gaps: it.clip.gaps } : {}), + }; +} + /** The plan on the estimate's clock alone (playPlan without the render's edges). */ function estimatePlan(segments, entries, { leadIn = 0.4 } = {}) { const byId = new Map((entries ?? []).map((e) => [e?.id, e])); @@ -219,7 +235,11 @@ function estimatePlan(segments, entries, { leadIn = 0.4 } = {}) { if (e?.type === "clip" && fin(e.start) && fin(e.end)) { const pw = livePlayWindow(/** @type {any} */ (e), leadIn); const hold = fin(s.hold) && /** @type {number} */ (s.hold) > 0 ? /** @type {number} */ (s.hold) : 0; - clip = { sourceFrom: pw.from, sourceTo: pw.to, playEnd: round(s.start + Math.max(0, pw.to - pw.from)), hold }; + const gaps = gapsWithin(gapsOf(e), pw.from, pw.to); + clip = { + sourceFrom: pw.from, sourceTo: pw.to, playEnd: round(s.start + Math.max(0, gappedLength(pw.from, pw.to, gaps))), hold, + ...(gaps.length ? { gaps } : {}), + }; } return { id: s.id, index: i, type: String(e?.type ?? "entry"), start: round(s.start), end: round(end), from: round(from), to: round(to), clip }; }); @@ -247,13 +267,27 @@ export function itemIndexAt(plan, t) { export function sourceAt(item, t) { if (!item?.clip || !fin(t)) return null; const c = item.clip; - return round(Math.min(c.sourceTo, Math.max(c.sourceFrom, c.sourceFrom + (t - item.start)))); + return round(Math.min(c.sourceTo, Math.max(c.sourceFrom, sourceAtOffset(t - item.start, c.sourceFrom, c.gaps)))); } -/** The cut second a clip item's source second plays at (the inverse inside its footage). */ +/** The cut second a clip item's source second plays at (the inverse inside its footage; inside a gap, its join). */ export function cutAtSource(item, src) { if (!item?.clip || !fin(src)) return item?.start ?? 0; - return round(item.start + (src - item.clip.sourceFrom)); + return round(item.start + offsetIn(src, item.clip.sourceFrom, item.clip.gaps)); +} + +/** + * Where a clip item's gaps fall on the cut's clock: one cut second per gap + * (its join), with the source span it leaves out -- the strip's tick and the + * readout's "jump". [] without gaps. + * + * @param {PlayItem} item + * @returns {Array<{ at: number, from: number, to: number }>} + */ +export function gapJoins(item) { + const c = item?.clip; + if (!c?.gaps?.length) return []; + return c.gaps.map((g) => ({ at: cutAtSource(item, g.from), from: g.from, to: g.to })); } /** Is cut second t past the clip's footage, in its hold (its last frame shown)? */ diff --git a/umtool/lib/report/playGaps.test.mjs b/umtool/lib/report/playGaps.test.mjs @@ -0,0 +1,102 @@ +// Play the cut with gaps inside a clip (gaps.mjs): the plan plays the kept +// seconds as one item -- its footage the cut less its gaps, the cut ↔ source +// mapping jumping at each join (on the estimate's clock and on the render's, +// from the cut-points route's `gaps`), the chrome seeked by source second +// through them; the sound is one span per kept piece, abutting on the cut's +// clock, with the build's join fades; the clip editor's live clock agrees. +// Without gaps every number is the one it was. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { estimateSchedule } from "umtool-report-to-video/deck"; +import { GAP_FADE } from "umtool-report-to-video/gaps"; +import { chromeTime, cutAtSource, gapJoins, playPlan, playTimeOfChrome, skipEntries, sourceAt } from "./playCut.mjs"; +import { audioSpans, levelAt, scheduleFrom } from "./playSchedule.mjs"; +import { cutTimeAt, liveClock, sourceTimeAt } from "./liveClock.mjs"; + +const GAPS = [{ from: 12, to: 13 }, { from: 15, to: 15.5 }]; +const manifest = (gaps) => ({ + slug: "t", + render: { width: 1920, height: 1080, fps: 30, transition: 0 }, + timeline: [ + { type: "clip", id: "a", video: "v1", start: 10, end: 18, ...(gaps ? { gaps } : {}) }, + { type: "clip", id: "b", video: "v2", start: 100, end: 103 }, + ], +}); +const planOf = (gaps, cuts = null) => { + const m = manifest(gaps); + return playPlan(estimateSchedule(m).segments, m.timeline, { cuts }); +}; +const near = (a, b, what, tol = 1e-6) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +test("the estimate: a gapped clip is one item, its footage the kept seconds; b moves up by the gaps", () => { + const plain = planOf(null); + const p = planOf(GAPS); + assert.equal(plain.items[0].clip.playEnd, 8); + assert.equal(p.items[0].clip.playEnd, 6.5); + assert.deepEqual(p.items[0].clip.gaps, GAPS); + assert.equal("gaps" in plain.items[0].clip, false, "no key without gaps"); + assert.equal(p.items[1].start, 6.5); + assert.equal(p.total, 9.5); +}); + +test("sourceAt / cutAtSource jump at each join; a second inside a gap plays at its join", () => { + const it = planOf(GAPS).items[0]; + assert.equal(sourceAt(it, 1.9), 11.9); + assert.equal(sourceAt(it, 2), 13, "the join shows the material after the gap"); + assert.equal(sourceAt(it, 3.5), 14.5); + assert.equal(sourceAt(it, 4.2), 15.7); + assert.equal(sourceAt(it, 6.5), 18); + assert.equal(cutAtSource(it, 12.5), 2, "inside the first gap: its join"); + assert.equal(cutAtSource(it, 14), 3); + assert.equal(cutAtSource(it, 16), 4.5); + assert.deepEqual(gapJoins(it), [{ at: 2, from: 12, to: 13 }, { at: 4, from: 15, to: 15.5 }]); + // Without gaps: the subtraction it always was. + const plain = planOf(null).items[0]; + assert.equal(sourceAt(plain, 2.5), 12.5); + assert.equal(cutAtSource(plain, 12.5), 2.5); + assert.deepEqual(gapJoins(plain), []); +}); + +test("the render's edges: the route's gaps and footage; the chrome (on the estimate's clock) is seeked by source second", () => { + const cuts = { a: { cutStart: 9.9, cutEnd: 18.1, footage: 6.7, gaps: [{ from: 12, to: 13 }, { from: 15, to: 15.5 }] }, b: { cutStart: 100, cutEnd: 103 } }; + const p = planOf(GAPS, cuts); + const it = p.items[0]; + assert.equal(it.clip.sourceFrom, 9.9); + assert.equal(it.clip.playEnd, 6.7); + assert.equal(sourceAt(it, 2.1), 13, "9.9 + 2.1 is the first gap's start: the join"); + // Source 14 plays at Play 3.1 (render) and at estimate 3 -- the chrome is seeked there. + near(chromeTime(p, cutAtSource(it, 14)), 3, "chromeTime"); + near(playTimeOfChrome(p, 3), 3.1, "and back"); + // Skipping b keeps a's gaps on its estimate. + const s = skipEntries(p, ["b"]); + assert.deepEqual(s.items[0].est.gaps, GAPS); +}); + +test("the sound: one span per kept piece, abutting; the join fades; a seek into a later piece reads its own source", () => { + const spans = audioSpans(planOf(GAPS)).filter((s) => s.id === "a"); + assert.deepEqual(spans.map((s) => [s.from, s.to, s.src, s.srcTo]), [[0, 2, 10, 12], [2, 4, 13, 15], [4, 6.5, 15.5, 18]]); + // The fades: out over the last GAP_FADE of a piece before a join, in over the first after it; full level between. + near(levelAt(spans[0].env, 2 - GAP_FADE / 2), 0.5, "fading out into the first join", 1e-3); + near(levelAt(spans[1].env, 2 + GAP_FADE / 2), 0.5, "fading in out of it", 1e-3); + assert.equal(levelAt(spans[1].env, 3), 1); + assert.equal(levelAt(spans[0].env, 0), 1, "the clip's own first sample is not faded"); + const sch = scheduleFrom(audioSpans(planOf(GAPS)), 3); + assert.deepEqual(sch.slice(0, 2).map((x) => [x.atWall, x.src]), [[0, 14], [1, 15.5]]); + // Without gaps: one span, as ever. + assert.deepEqual(audioSpans(planOf(null)).filter((s) => s.id === "a").map((s) => [s.from, s.to, s.src]), [[0, 8, 10]]); +}); + +test("the clip editor's live clock: the footage less the gaps, the jump at each join", () => { + const sched = estimateSchedule(manifest(GAPS)); + const clock = liveClock(sched, { id: "a", start: 10, end: 18, gaps: GAPS }); + assert.equal(clock.playEnd, 6.5); + assert.deepEqual(cutTimeAt(clock, 14), { t: 3, where: "inside" }); + assert.deepEqual(cutTimeAt(clock, 12.4), { t: 2, where: "inside" }); + assert.equal(sourceTimeAt(clock, 4.5), 16); + const plain = liveClock(estimateSchedule(manifest(null)), { id: "a", start: 10, end: 18 }); + assert.equal(plain.playEnd, 8); + assert.equal("gaps" in plain, false); +}); diff --git a/umtool/lib/report/playSchedule.mjs b/umtool/lib/report/playSchedule.mjs @@ -18,6 +18,7 @@ // (cut seconds divided by the speed). import { MUTE_FADE } from "umtool-report-to-video/mute"; +import { GAP_FADE, gappedLength, keptSpans, offsetIn } from "umtool-report-to-video/gaps"; import { ROOM } from "yt-dlp-transcript-common/lib/report/look.mjs"; /** Room's afade at a muted edge (the build's roomAudioFilter): the look's own number. */ @@ -73,9 +74,15 @@ const ramp = (a, b, down = false) => (b > a ? [[a, down ? 1 : 0], [b, down ? 0 : * gain a constant multiplier: the loudness gain and the clip's * own `audio.gain`, in dB, as amplitude * + * A clip with GAPS (`clip.gaps`, gaps.mjs) is several spans, one per piece + * that plays, abutting on the cut's clock: each reads its own source seconds, + * with the build's GAP_FADE out at the end of the piece before a join and in + * at the start of the piece after it -- a jump in the sound with no click. + * * @param {{ items: Array<{ id: string, start: number, end: number, clip: null | { * sourceFrom: number, sourceTo: number, playEnd: number, hold: number, - * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number } }> }} plan + * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number, + * gaps?: Array<{ from: number, to: number }> } }> }} plan * @returns {Array<{ id: string, index: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>} */ export function audioSpans(plan) { @@ -86,7 +93,9 @@ export function audioSpans(plan) { if (!c || !(c.playEnd > it.start)) return; const from = it.start; // Its source's length: the encode pads a segment to whole frames with SILENCE (apad), and a hold is silent too. - const to = Math.min(c.playEnd, it.start + Math.max(0, c.sourceTo - c.sourceFrom)); + // Less its gaps: they never play. + const gaps = c.gaps?.length ? c.gaps : null; + const to = Math.min(c.playEnd, it.start + Math.max(0, gaps ? gappedLength(c.sourceFrom, c.sourceTo, gaps) : c.sourceTo - c.sourceFrom)); if (!(to > from)) return; const prev = items[i - 1]; const next = items[i + 1]; @@ -96,7 +105,7 @@ export function audioSpans(plan) { // The crossfades: up over the overlap with the clip before, down over the one after (on the segment, hold included). if (dIn > 0) envs.push(ramp(from, from + dIn)); if (dOut > 0) envs.push(ramp(it.end - dOut, it.end, true)); - const at = (src) => from + (src - c.sourceFrom); + const at = (src) => from + offsetIn(src, c.sourceFrom, gaps); // Room: heard over [sound[0], sound[1]] only -- a fade in ending at its start, a fade out from its end. if (Array.isArray(c.sound) && fin(c.sound[0]) && fin(c.sound[1])) { const [sa, sb] = c.sound; @@ -114,11 +123,30 @@ export function audioSpans(plan) { if (fin(c.soundFrom)) envs.push(ramp(at(/** @type {number} */ (c.soundFrom)), at(/** @type {number} */ (c.soundFrom)) + MUTE_FADE)); const db = (fin(c.gainDb) ? /** @type {number} */ (c.gainDb) : 0) + (fin(a.gain) ? a.gain : 0); const shift = fin(a.offset) ? a.offset / 1000 : 0; - out.push({ - id: it.id, index: i, from, to, - src: r6(c.sourceFrom - shift), srcTo: r6(c.sourceFrom - shift + (to - from)), - env: multiply(envs, from, to), - gain: r6(10 ** (db / 20)), + if (!gaps) { + out.push({ + id: it.id, index: i, from, to, + src: r6(c.sourceFrom - shift), srcTo: r6(c.sourceFrom - shift + (to - from)), + env: multiply(envs, from, to), + gain: r6(10 ** (db / 20)), + }); + return; + } + // One span per piece that plays; the joins faded out and in (the build's gapFilterParts). + const pieces = keptSpans(c.sourceFrom, c.sourceTo, gaps) + .map((p) => ({ src: p.from, a: at(p.from), b: Math.min(to, at(p.to)) })) + .filter((p) => p.b > p.a + 1e-6); + pieces.forEach((p, k) => { + const d = Math.min(GAP_FADE, (p.b - p.a) / 2); + const joins = []; + if (k > 0) joins.push(ramp(p.a, p.a + d)); + if (k < pieces.length - 1) joins.push(ramp(p.b - d, p.b, true)); + out.push({ + id: it.id, index: i, from: r6(p.a), to: r6(p.b), + src: r6(p.src - shift), srcTo: r6(p.src - shift + (p.b - p.a)), + env: multiply([...envs, ...joins], p.a, p.b), + gain: r6(10 ** (db / 20)), + }); }); }); return out; diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -76,6 +76,8 @@ export async function playView(project, { take = null } = {}) { end: e.end, cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null, + // Seconds taken out of its middle (gaps.mjs): the plan plays it as one item of jump cuts. + ...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}), blur: e.blur && typeof e.blur === "object" ? e.blur : null, // Ruled incorrect (the walk's verdict): its correction -- Play skips it unless asked to show it. incorrect: clipVerdict(e) === "incorrect" ? text(e.correction) || (e.reason === "wrong-speaker" ? "wrong speaker" : "marked incorrect") : null, diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs @@ -0,0 +1,288 @@ +// RENDER MODE from umtool (common/lib/renderPriority.mjs; AGENTS.md "Render +// mode"): a render the operator is waiting for gets the machine. +// +// umtool take <p> --id <t> … --priority on for the take's lifetime: on at +// the start, off at the end, on a +// failure and on a signal +// umtool render-mode on [--for 90m] [--note …] [--json] a window (a chain of renders) +// umtool render-mode off [--force] [--json] +// umtool render-mode status [--json] +// +// On: the state file (beside the heavy slot's lock), then the editor's +// transcription and download lanes held through its ops — the `lane` action +// `pnpm ops lane` posts — each only if it was not held already, and recorded, +// so off releases only those. The editor is ARCHILYZER_EDITOR_URL with +// WORKER_TOKEN, read as `pnpm ops` reads them (fetchWindows.mjs editorConfig). +// With no editor to ask, render mode still holds the heavy slot's door; it +// says the lanes were not held. +// +// A take inside a manual window joins it (its render carries the window's +// token); a take with --priority while another render holds it renders +// without it, and its render waits at the door like any other heavy job. + +import { + RENDER_MODE_LANES, + RENDER_MODE_REMINDER, + RENDER_PRIORITY_TOKEN_ENV, + clockOf, + describeRenderPriority, + parseDurationMs, + readRenderPriority, + reapRenderMode, + renderModeOff, + renderModeOn, + renderPriorityFile, +} from "yt-dlp-transcript-common/lib/renderPriority.mjs"; +import { REPO_ROOT } from "../paths.mjs"; +import { editorConfig } from "./fetchWindows.mjs"; + +/** The state file, as the checkout's queue-lock finds it (not the cwd's: a CLI may run in a workspace). */ +export function renderModeFile(env = process.env) { + return renderPriorityFile(env, { root: REPO_ROOT }); +} + +/** + * The editor's lanes over its ops: read through `GET /api/ops/settings?key=autoQueue`, + * held and released through `POST /api/ops/lane`. Null with no token to ask with. + * @param {{ url: string, token: string, fetch?: typeof fetch }} cfg + * @returns {import("yt-dlp-transcript-common/lib/renderPriority.mjs").RenderModeLanes | null} + */ +export function editorLanes(cfg) { + if (!cfg?.token) return null; + const ask = async (route, body) => { + const f = cfg.fetch ?? fetch; + let res; + try { + res = await f(`${cfg.url}${route}`, { + method: body ? "POST" : "GET", + headers: { authorization: `Bearer ${cfg.token}`, ...(body ? { "content-type": "application/json" } : {}) }, + ...(body ? { body: JSON.stringify(body) } : {}), + cache: "no-store", + signal: AbortSignal.timeout(15_000), + }); + } catch (e) { + throw new Error(`could not reach the editor at ${cfg.url}: ${e instanceof Error ? e.message : String(e)}`); + } + const j = await res.json().catch(() => ({})); + if (!res.ok || j?.ok === false) throw new Error(`the editor refused (HTTP ${res.status}): ${j?.error ?? "no reason given"}`); + return j; + }; + return { + async isHeld(lane) { + const j = await ask("/api/ops/settings?key=autoQueue"); + return j?.value?.[lane]?.held === true; + }, + async hold(lane) { + await ask("/api/ops/lane", { lane, held: true }); + }, + async release(lane) { + await ask("/api/ops/lane", { lane, held: false }); + }, + }; +} + +/** The lanes line of a hold: "lanes held: transcription, download (… already held: left alone)". */ +export function lanesLine(state) { + const held = state.lanesHeld?.length ? `lanes held: ${state.lanesHeld.join(", ")}` : "no lanes held"; + const skipped = state.lanesSkipped?.length ? ` (${state.lanesSkipped.join(", ")} already held — left alone)` : ""; + const error = state.lanesError ? ` — ${state.lanesError}` : ""; + return `${held}${skipped}${error}`; +} + +/** + * Run `fn` (a take's make) in render mode, as `umtool take … --priority` asks. + * + * --priority, render mode off on for this process (holder: its pid), off + * after `fn` — done, failed or signalled + * a manual window on joined: the render carries its token; the + * window stays on afterwards (with or without --priority) + * --priority, another render run as is; its render waits at the door + * + * The token goes into process.env, so the render queue-lock starts inherits it. + * + * @template T + * @param {{ priority: boolean, project: string, take?: string | null, cmd?: string, log: (s: string) => void, + * env?: Record<string, string | undefined>, file?: string, lanes?: any, signals?: boolean }} o + * @param {() => Promise<T>} fn + * @returns {Promise<T>} + */ +export async function withTakePriority(o, fn) { + const env = o.env ?? process.env; + const file = o.file ?? renderModeFile(env); + const status = readRenderPriority(file); + if (status.held && status.state) { + if (!status.state.holder) { + env[RENDER_PRIORITY_TOKEN_ENV] = status.state.token; + o.log(`render mode is on (${describeRenderPriority(status.state)}) — this take renders in it`); + return fn(); + } + if (o.priority) o.log(`render mode is held by another render (${describeRenderPriority(status.state)}) — this one waits for it`); + return fn(); + } + if (!o.priority) return fn(); + + const lanes = o.lanes !== undefined ? o.lanes : editorLanes(editorConfig(env)); + const cmd = o.cmd ?? `umtool take ${o.project}${o.take ? ` --id ${o.take}` : ""}`; + const on = await renderModeOn({ + file, + holder: { pid: process.pid, cmd, project: o.project, take: o.take ?? null }, + by: "umtool take --priority", + editor: lanes ? editorConfig(env).url : null, + lanes, + }); + if (!on.ok || !on.state) { + // Another hold went on between the look and the claim: render as any job. + o.log(`render mode is held by another render${on.held ? ` (${describeRenderPriority(on.held)})` : ""} — this one waits for it`); + return fn(); + } + const token = on.state.token; + env[RENDER_PRIORITY_TOKEN_ENV] = token; + o.log(`render mode on for this take — ${lanesLine(on.state)}`); + o.log(` ${RENDER_MODE_REMINDER}`); + + let ended = false; + const end = async () => { + if (ended) return; + ended = true; + if (env[RENDER_PRIORITY_TOKEN_ENV] === token) delete env[RENDER_PRIORITY_TOKEN_ENV]; + try { + const off = await renderModeOff({ file, token, lanes }); + o.log( + `render mode off${off.released.length ? ` — lanes released: ${off.released.join(", ")}` : ""}` + + (off.failed.length ? `; NOT released: ${off.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks` : ""), + ); + } catch (e) { + o.log(`render mode: could not end it (${e instanceof Error ? e.message : String(e)}) — it ends by itself, this process being gone`); + } + }; + // A signal ends the hold before this process goes (the job runner's Cancel + // signals the group; Ctrl-C the same). Then exit as the signal would. + /** @type {Array<[NodeJS.Signals, () => void]>} */ + const handlers = []; + if (o.signals !== false) { + for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) { + const h = () => { + const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[sig] ?? 0); + setTimeout(() => process.exit(code), 10_000).unref(); + void end().finally(() => process.exit(code)); + }; + handlers.push([sig, h]); + process.on(sig, h); + } + } + try { + return await fn(); + } finally { + for (const [sig, h] of handlers) process.off(sig, h); + await end(); + } +} + +const USAGE = [ + "usage: umtool render-mode on [--for 90m] [--note TEXT] [--json]", + " umtool render-mode off [--force] [--json]", + " umtool render-mode status [--json]", + "", + "Render mode gives a render the operator is waiting for the machine: every other heavy job", + "(e2e suites, next builds, the publish stages, other renders) waits at the heavy slot's door", + `while it is on, and the editor's ${RENDER_MODE_LANES.join(" and ")} lanes are held — only the`, + "ones not held already, and only those are released at off. `on` is a window (default 2h; --for", + "90m, 1h30m, 45 = minutes) for a chain of renders: every `umtool take` started in it renders in it;", + "another command joins with the RENDER_PRIORITY_TOKEN it prints. For one take, `umtool take …", + "--priority` turns it on for the take's lifetime instead. `off` ends it (a running take's hold", + "only with --force). A hold whose process is gone or whose window is over is no hold: its lanes", + "are released by the editor's heartbeat, /jobs, or the next `status`/`on`.", + "The same from the editor: pnpm ops render-mode --json '{\"on\": true, \"for\": \"90m\"}' / get render-mode.", +].join("\n"); + +/** + * `umtool render-mode on|off|status`. + * @param {string[]} args + * @param {{ log?: (s: string) => void, err?: (s: string) => void, env?: Record<string, string | undefined>, file?: string, lanes?: any }} [opts] + * @returns {Promise<number>} + */ +export async function renderModeCommand(args, { log = console.log, err = console.error, env = process.env, file, lanes } = {}) { + const valued = new Set(["--for", "--note"]); + const sub = args.find((a, i) => !a.startsWith("--") && !valued.has(args[i - 1])); + const flag = (n) => { + const i = args.indexOf(n); + return i >= 0 ? args[i + 1] : undefined; + }; + const json = args.includes("--json"); + if (args.includes("--help")) { + log(USAGE); + return 0; + } + if (!sub || !["on", "off", "status"].includes(sub)) { + err(USAGE); + return 2; + } + const where = file ?? renderModeFile(env); + const cfg = editorConfig(env); + const editor = lanes !== undefined ? lanes : editorLanes(cfg); + const out = (v) => log(JSON.stringify(v, null, 2)); + + if (sub === "status") { + const reaped = editor ? await reapRenderMode({ file: where, lanes: editor }).catch(() => null) : null; + const s = readRenderPriority(where); + if (json) { + out({ ok: true, held: s.held, state: s.state, stale: s.stale, reaped: reaped?.was ? reaped : null, file: where }); + return 0; + } + if (reaped?.was) log(`a stale render mode was ended${reaped.released.length ? ` — lanes released: ${reaped.released.join(", ")}` : ""}`); + if (!s.held || !s.state) { + log(s.state ? `render mode is off (the last hold is stale: ${s.stale}; ${lanesLine(s.state)})` : "render mode is off"); + return 0; + } + log(`render mode is ON: ${describeRenderPriority(s.state)}`); + log(` ${lanesLine(s.state)}`); + log(` ${RENDER_MODE_REMINDER}`); + return 0; + } + + if (sub === "on") { + const raw = flag("--for"); + const forMs = raw === undefined ? null : parseDurationMs(raw); + if (raw !== undefined && !forMs) { + err(`--for wants a duration: 90m, 2h, 1h30m, or minutes — not "${raw}"`); + return 2; + } + const r = await renderModeOn({ file: where, holder: null, forMs, note: flag("--note") ?? null, by: "umtool render-mode", editor: editor ? cfg.url : null, lanes: editor }); + if (!r.ok || !r.state) { + if (json) out({ ok: false, error: "render mode is already on", held: r.held }); + else err(`render mode is already on: ${r.held ? describeRenderPriority(r.held) : "?"}`); + return 1; + } + if (json) { + out({ ok: true, state: r.state, file: where, reminder: RENDER_MODE_REMINDER }); + return 0; + } + log(`render mode ON until ${clockOf(r.state.until)} — ${lanesLine(r.state)}`); + log(` ${RENDER_MODE_REMINDER}`); + log(" every `umtool take` started now renders in it; another command joins with:"); + log(` export ${RENDER_PRIORITY_TOKEN_ENV}=${r.state.token}`); + log(" end it: umtool render-mode off"); + return 0; + } + + // off + const s = readRenderPriority(where); + if (s.held && s.state?.holder && !args.includes("--force")) { + const msg = `render mode is held by a running render (${describeRenderPriority(s.state)}) — it ends with it; --force ends it now`; + if (json) out({ ok: false, error: msg }); + else err(msg); + return 1; + } + const r = await renderModeOff({ file: where, lanes: editor }); + if (json) { + out({ ok: true, was: r.was, released: r.released, failed: r.failed }); + return r.failed.length ? 1 : 0; + } + if (!r.was) log("render mode was off"); + else log(`render mode off${r.released.length ? ` — lanes released: ${r.released.join(", ")}` : ""}`); + if (r.failed.length) { + err(`NOT released: ${r.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks`); + return 1; + } + return 0; +} diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs @@ -0,0 +1,255 @@ +// Render mode from umtool (renderMode.mjs): `umtool take … --priority`'s +// lifetime hold, `umtool render-mode on|off|status`, and the editor lanes over +// ops. Every test uses a temp state file and a fake editor — never the +// machine's render mode or a live editor's lanes. Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { readRenderPriority, readRenderPriorityState } from "yt-dlp-transcript-common/lib/renderPriority.mjs"; +import { editorLanes, renderModeCommand, withTakePriority } from "./renderMode.mjs"; +import { takeCommand } from "./takeCli.mjs"; +import { takeSteps } from "./takeMaker.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +function tmpFile() { + return path.join(mkdtempSync(path.join(tmpdir(), "render-mode-")), "heavy.lock.render.json"); +} + +/** A fake editor's lanes: `held` what it holds, `calls` what was asked. */ +function fakeLanes(held = {}) { + const calls = []; + return { + held, + calls, + lanes: { + isHeld: async (lane) => held[lane] === true, + hold: async (lane) => { + calls.push(`hold ${lane}`); + held[lane] = true; + }, + release: async (lane) => { + calls.push(`release ${lane}`); + held[lane] = false; + }, + }, + }; +} + +test("take --priority: on for the take (its lanes held, its token in the env), off at its end", async () => { + const file = tmpFile(); + const ed = fakeLanes({ download: true }); + const env = {}; + const lines = []; + let during = null; + const r = await withTakePriority({ priority: true, project: "ember", take: "t1", log: (l) => lines.push(l), env, file, lanes: ed.lanes, signals: false }, async () => { + during = { status: readRenderPriority(file), token: env.RENDER_PRIORITY_TOKEN }; + return "made"; + }); + assert.equal(r, "made"); + assert.equal(during.status.held, true); + assert.equal(during.status.state.holder.pid, process.pid); + assert.equal(during.status.state.holder.cmd, "umtool take ember --id t1"); + assert.equal(during.token, during.status.state.token, "the render inherits the token"); + assert.deepEqual(ed.calls, ["hold transcription", "release transcription"], "download was held already: left alone"); + assert.equal(ed.held.download, true); + assert.equal(existsSync(file), false); + assert.equal(env.RENDER_PRIORITY_TOKEN, undefined); + assert.ok(lines.some((l) => /close Firefox and other heavy apps/.test(l))); + assert.ok(lines.some((l) => /render mode off — lanes released: transcription/.test(l))); +}); + +test("take --priority: a failed take lets go too", async () => { + const file = tmpFile(); + const ed = fakeLanes(); + await assert.rejects( + withTakePriority({ priority: true, project: "ember", take: "t1", log: () => {}, env: {}, file, lanes: ed.lanes, signals: false }, async () => { + throw new Error("build-video exited 1"); + }), + /build-video exited 1/, + ); + assert.deepEqual(ed.calls, ["hold transcription", "hold download", "release transcription", "release download"]); + assert.equal(existsSync(file), false); +}); + +test("take --priority killed by a signal: the hold ends before the process does", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "render-mode-sig-")); + const file = path.join(dir, "state.json"); + const log = path.join(dir, "lanes.log"); + const script = path.join(dir, "take.mjs"); + writeFileSync( + script, + `import { appendFileSync } from "node:fs"; +import { withTakePriority } from ${JSON.stringify(path.join(HERE, "renderMode.mjs"))}; +const lanes = { + isHeld: async () => false, + hold: async (l) => appendFileSync(${JSON.stringify(log)}, "hold " + l + "\\n"), + release: async (l) => appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"), +}; +await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => console.log(l), env: {}, file: ${JSON.stringify(file)}, lanes }, () => new Promise(() => setInterval(() => {}, 1000))); +`, + ); + const child = spawn(process.execPath, [script], { stdio: ["ignore", "pipe", "pipe"] }); + let out = ""; + child.stdout.on("data", (d) => (out += d)); + child.stderr.on("data", (d) => (out += d)); + const t0 = Date.now(); + while (!/render mode on for this take/.test(out)) { + if (Date.now() - t0 > 15_000) throw new Error(`never went on: ${out}`); + await new Promise((r) => setTimeout(r, 20)); + } + assert.equal(readRenderPriority(file).held, true); + child.kill("SIGTERM"); + const code = await new Promise((r) => child.on("exit", (c) => r(c))); + assert.equal(code, 143); + assert.equal(existsSync(file), false); + assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nrelease transcription\nrelease download\n"); +}); + +test("a take inside a manual window joins it (flag or not) and leaves it on; beside another render it takes nothing", async () => { + const file = tmpFile(); + const ed = fakeLanes(); + assert.equal(await renderModeCommand(["on", "--for", "30m", "--note", "a chain"], { log: () => {}, err: () => {}, env: {}, file, lanes: ed.lanes }), 0); + const window = readRenderPriorityState(file); + for (const priority of [false, true]) { + const env = {}; + const lines = []; + await withTakePriority({ priority, project: "p", take: "t", log: (l) => lines.push(l), env, file, lanes: ed.lanes, signals: false }, async () => { + assert.equal(env.RENDER_PRIORITY_TOKEN, window.token); + }); + assert.match(lines[0], /render mode is on \(render mode on \(by umtool render-mode\) — a chain, since/); + } + assert.equal(readRenderPriority(file).held, true, "the window outlives the takes"); + assert.deepEqual(ed.calls, ["hold transcription", "hold download"]); + + // A different render's hold: a --priority take renders without a token; nothing changes. + const other = tmpFile(); + writeFileSync(other, JSON.stringify({ version: 1, token: "theirs", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "umtool take x --id y" }, lanesHeld: [] })); + const env = {}; + const lines = []; + await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => lines.push(l), env, file: other, lanes: ed.lanes, signals: false }, async () => { + assert.equal(env.RENDER_PRIORITY_TOKEN, undefined); + }); + assert.match(lines[0], /held by another render \(umtool take x --id y/); + assert.equal(readRenderPriorityState(other).token, "theirs"); +}); + +test("without --priority and no window, a take is untouched", async () => { + const file = tmpFile(); + const ed = fakeLanes(); + const env = {}; + await withTakePriority({ priority: false, project: "p", take: "t", log: () => {}, env, file, lanes: ed.lanes, signals: false }, async () => {}); + assert.deepEqual(ed.calls, []); + assert.equal(existsSync(file), false); + assert.equal(env.RENDER_PRIORITY_TOKEN, undefined); +}); + +test("umtool render-mode on | status | off, with --json; off of a running take's hold needs --force", async () => { + const file = tmpFile(); + const ed = fakeLanes({ download: true }); + const out = []; + const err = []; + const io = { log: (l) => out.push(l), err: (l) => err.push(l), env: {}, file, lanes: ed.lanes }; + assert.equal(await renderModeCommand(["status"], io), 0); + assert.equal(out.at(-1), "render mode is off"); + assert.equal(await renderModeCommand(["on", "--for", "soon"], io), 2); + assert.equal(await renderModeCommand(["on", "--for", "90m"], io), 0); + assert.match(out.join("\n"), /render mode ON until \d\d:\d\d — lanes held: transcription \(download already held — left alone\)/); + assert.match(out.join("\n"), /export RENDER_PRIORITY_TOKEN=[0-9a-f]{16}/); + assert.equal(await renderModeCommand(["on"], io), 1, "already on"); + out.length = 0; + assert.equal(await renderModeCommand(["status", "--json"], io), 0); + const st = JSON.parse(out.join("\n")); + assert.equal(st.held, true); + assert.deepEqual(st.state.lanesHeld, ["transcription"]); + assert.equal(await renderModeCommand(["off"], io), 0); + assert.deepEqual(ed.calls, ["hold transcription", "release transcription"]); + assert.equal(ed.held.download, true); + assert.equal(existsSync(file), false); + + // A running take's hold (this process) ends with the take, unless --force. + writeFileSync(file, JSON.stringify({ version: 1, token: "take", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "umtool take p --id t" }, lanesHeld: [] })); + assert.equal(await renderModeCommand(["off"], io), 1); + assert.match(err.at(-1), /held by a running render .* --force ends it now/); + assert.equal(await renderModeCommand(["off", "--force"], io), 0); + assert.equal(existsSync(file), false); + + // A stale hold's lanes are released by the next status. + writeFileSync(file, JSON.stringify({ version: 1, token: "dead", since: new Date().toISOString(), until: null, holder: { pid: 999999999 }, lanesHeld: ["transcription"] })); + ed.held.transcription = true; + out.length = 0; + assert.equal(await renderModeCommand(["status"], io), 0); + assert.match(out[0], /a stale render mode was ended — lanes released: transcription/); + assert.equal(ed.held.transcription, false); + assert.equal(await renderModeCommand(["bogus"], io), 2); +}); + +test("editorLanes asks the editor's ops: settings?key=autoQueue to read, lane to hold and release; none without a token", async () => { + assert.equal(editorLanes({ url: "http://e", token: "" }), null); + const asked = []; + const fetch = async (url, init) => { + asked.push(`${init.method} ${url} ${init.body ?? ""} ${init.headers.authorization}`); + if (String(url).includes("settings")) return new Response(JSON.stringify({ ok: true, key: "autoQueue", value: { download: { held: true }, transcription: { held: false } } })); + return new Response(JSON.stringify({ ok: true })); + }; + const lanes = editorLanes({ url: "http://e", token: "tok", fetch }); + assert.equal(await lanes.isHeld("download"), true); + assert.equal(await lanes.isHeld("transcription"), false); + await lanes.hold("transcription"); + await lanes.release("transcription"); + assert.deepEqual(asked, [ + "GET http://e/api/ops/settings?key=autoQueue Bearer tok", + "GET http://e/api/ops/settings?key=autoQueue Bearer tok", + 'POST http://e/api/ops/lane {"lane":"transcription","held":true} Bearer tok', + 'POST http://e/api/ops/lane {"lane":"transcription","held":false} Bearer tok', + ]); + const refusing = editorLanes({ url: "http://e", token: "tok", fetch: async () => new Response(JSON.stringify({ ok: false, error: "nope" }), { status: 400 }) }); + await assert.rejects(refusing.hold("download"), /the editor refused \(HTTP 400\): nope/); +}); + +test("takeSteps: priority runs every kind of take job with --priority", () => { + const proj = { id: "reports/proj" }; + const ctx = { styles: { flash: { label: "Flash" } }, existing: [{ id: "flash", window: "full" }], clipCount: 3 }; + assert.ok(takeSteps(proj, { take: { label: "P" }, priority: true }, ctx).steps[0].argv.includes("--priority")); + assert.ok(!takeSteps(proj, { take: { label: "P" } }, ctx).steps[0].argv.includes("--priority")); + assert.ok(takeSteps(proj, { rebuild: "flash", priority: true }, ctx).steps[0].argv.includes("--priority")); + assert.ok(takeSteps(proj, { allStyles: { group: "m" }, priority: true }, ctx).steps[0].argv.includes("--priority")); +}); + +test("umtool take --priority: the take is made inside render mode, and render mode ends with it — done or failed", async () => { + const root = mkdtempSync(path.join(tmpdir(), "render-mode-take-")); + const dir = path.join(root, "reports", "proj"); + await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true }); + await writeFile( + path.join(dir, "video.manifest.json"), + JSON.stringify({ slug: "proj", render: { crf: 30 }, timeline: [{ id: "s01", type: "clip", channel: "c", video: "v", start: 0, end: 13 }] }, null, 2) + "\n", + ); + const file = path.join(root, "state.json"); + const ed = fakeLanes(); + let heldDuring = null; + const render = async (job) => { + heldDuring = readRenderPriority(file).held; + const out = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(out, "render"); + return { file: out }; + }; + const io = { reportsRoot: path.join(root, "reports"), log: () => {}, err: () => {}, deps: { render, styles: {}, probe: async () => 1 }, renderMode: { file, lanes: ed.lanes, signals: false } }; + try { + assert.equal(await takeCommand(["proj", "--id", "p1", "--label", "P", "--set", "render.crf=31", "--full", "--priority"], io), 0); + assert.equal(heldDuring, true); + assert.equal(existsSync(file), false); + assert.deepEqual(ed.calls, ["hold transcription", "hold download", "release transcription", "release download"]); + const failing = { ...io, deps: { ...io.deps, render: async () => { throw new Error("cut failed"); } } }; + assert.equal(await takeCommand(["proj", "--id", "p2", "--label", "P2", "--set", "render.crf=32", "--full", "--priority"], failing), 1); + assert.equal(existsSync(file), false); + assert.equal(ed.calls.length, 8); + assert.ok(JSON.parse(await readFile(path.join(dir, "takes", "p1", "take.json"), "utf8"))); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -5,8 +5,11 @@ // umtool take <project> --id <id> --label "<l>" [--group G] [--kind K] [--summary S] // [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …] // [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson] -// [--from TAKE] [--keep-frames] +// [--from TAKE] [--keep-frames] [--priority] // umtool take <project> --id <id> --rebuild made again from its own take.json +// --priority: render mode for the take's lifetime (renderMode.mjs) — every +// other heavy job waits for this render, the editor's transcription and +// download lanes are held, and both are let go at its end, failure or signal. // umtool takes effects <project> [--json] the effect presets this cut offers (report-to-video/fx.mjs) // umtool takes make <project> [--recipe FILE] [--only ID,ID] [--force] [--progress ndjson] // umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--force] @@ -32,14 +35,15 @@ import { } from "./takeMaker.mjs"; import { TAKE_FILE, takesDirOf } from "./takes.mjs"; import { fxPresetsFor } from "umtool-report-to-video/fx"; +import { withTakePriority } from "./renderMode.mjs"; import { mergePatch } from "umtool-report-to-video/montage-styles"; export const TAKE_USAGE = [ "usage: umtool take <project> --id <id> --label \"<label>\" [--group G] [--kind similar|different]", " [--summary S] [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]", " [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]", - " [--from TAKE] [--keep-frames]", - " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames]", + " [--from TAKE] [--keep-frames] [--priority]", + " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames] [--priority]", " made again from its own take.json (its stored patch, walked edits included); a window", " flag renders it over that window instead of its own", " umtool take <project> --id <id> --label L [--patch F | …] --draft (or --no-render) the take RECORDED,", @@ -62,6 +66,11 @@ export const TAKE_USAGE = [ "them, and marks the take (out/.keep-frames/asked.json): a later build of it without the flag sets its", "frames aside in out/.keep-frames/ instead of pruning them. Without it they are pruned, and a --from twin", "captures the chrome again.", + "--priority gives this render the machine (render mode, `umtool render-mode`): every other heavy job", + "(e2e suites, next builds, the publish stages, other renders) waits for it, the editor's transcription", + "and download lanes are held (only the ones not held already), and both end with the take — done,", + "failed or stopped. Close Firefox and other heavy apps while it renders. A take started inside a", + "`umtool render-mode on` window renders in that window, flag or not.", ].join("\n"); export const TAKES_USAGE = [ @@ -69,6 +78,7 @@ export const TAKES_USAGE = [ ` the recipe's takes, one at a time (default: takes/${RECIPE_FILE}); a take that`, " exists is skipped unless --force", " umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--quick] [--force]", + " [--priority] (either form: render mode for the whole batch, as `umtool take --priority`)", ` one take per montage style (writes takes/${ALL_STYLES_RECIPE})`, " umtool takes styles [--json] the montage styles: name, label, summary", " umtool takes pick <project> <take> [--anyway] use this take: its manifest over the project's", @@ -195,7 +205,7 @@ async function realDeps() { * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: Record<string, unknown> }} [opts] * @returns {Promise<number>} */ -export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps } = {}) { +export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps, renderMode } = {}) { try { const p = parse(args); if (p.has("--help") || !p.positional.length) { @@ -254,14 +264,19 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons out.log(`render it: umtool take ${project.id} --id ${id} --full`); return 0; } - const r = await makeTake(project.dir, spec, { - force: p.has("--force") || fromStored, - from: p.one("--from") ?? null, - keepFrames: p.has("--keep-frames"), - emit: out.emit, - log: out.log, - ...(deps ?? (await realDeps())), - }); + const make = async () => + makeTake(project.dir, spec, { + force: p.has("--force") || fromStored, + from: p.one("--from") ?? null, + keepFrames: p.has("--keep-frames"), + emit: out.emit, + log: out.log, + ...(deps ?? (await realDeps())), + }); + const r = await withTakePriority( + { priority: p.has("--priority"), project: project.id, take: id, log: out.log, ...(renderMode ?? {}) }, + make, + ); if (r.skipped) out.log(`take ${id} exists — pass --force to make it again`); return 0; } catch (e) { @@ -302,7 +317,7 @@ async function promote(project, id, p, log, err) { * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: Record<string, unknown> }} [opts] * @returns {Promise<number>} */ -export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps } = {}) { +export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps, renderMode } = {}) { try { const p = parse(args); const [sub, ...rest] = p.positional; @@ -369,13 +384,17 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con } } const only = p.one("--only")?.split(",").map((s) => s.trim()).filter(Boolean) ?? null; - const results = await makeTakes(project.dir, recipe, { - force: p.has("--force"), - only, - emit: out.emit, - log: out.log, - ...(deps ?? (await realDeps())), - }); + const results = await withTakePriority( + { priority: p.has("--priority"), project: project.id, take: null, cmd: `umtool takes make ${project.id}`, log: out.log, ...(renderMode ?? {}) }, + async () => + makeTakes(project.dir, recipe, { + force: p.has("--force"), + only, + emit: out.emit, + log: out.log, + ...(deps ?? (await realDeps())), + }), + ); const failed = results.filter((r) => r.status === "failed"); const made = results.filter((r) => r.status === "made").length; const skipped = results.filter((r) => r.status === "skipped").length; diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -994,6 +994,7 @@ const windowArgs = (w) => (w === "full" ? ["--full"] : ["--at", String(w.at), "- * { take: { id?, label, group?, style?, patch?, window?, summary?, kind?, quick? }, force? } New take * { allStyles: { group?, window?, quick? }, force? } Make all styles * { rebuild: "<take id>" } Rebuild + * any of them with `priority: true`: --priority, render mode for the render (renderMode.mjs) * * @param {{ id: string }} project * @param {Record<string, any>} req @@ -1005,6 +1006,9 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds = const base = { cwd: UMTOOL_DIR, env: {}, ndjson: /** @type {const} */ (true) }; const cli = ["node", umtoolCli()]; const force = req.force === true ? ["--force"] : []; + // "Give renders the machine" (the take panel's toggle): render mode for the + // job's render (renderMode.mjs; `umtool take … --priority`). + const priority = req.priority === true ? ["--priority"] : []; if (typeof req.rebuild === "string") { const t = existing.find((x) => x.id === req.rebuild); if (!t) throw new Error(`no take ${req.rebuild}`); @@ -1018,7 +1022,7 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds = steps: [{ ...base, label: `${/** @type {any} */ (t).draft ? "render" : "rebuild"} take ${t.id}`, - argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", ...(win ? windowArgs(win) : []), "--progress", "ndjson"], + argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", ...(win ? windowArgs(win) : []), ...priority, "--progress", "ndjson"], timeoutMs: takeTimeoutMs(full, clipCount, seconds), }], }; @@ -1036,7 +1040,7 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds = steps: [{ ...base, label: `make ${recipe.takes.length} take(s), one per style`, - argv: [...cli, "takes", "make", project.id, "--all-styles", ...group, ...windowArgs(recipe.window), ...(recipe.quick ? ["--quick"] : []), ...force, "--progress", "ndjson"], + argv: [...cli, "takes", "make", project.id, "--all-styles", ...group, ...windowArgs(recipe.window), ...(recipe.quick ? ["--quick"] : []), ...force, ...priority, "--progress", "ndjson"], timeoutMs: recipe.takes.length * takeTimeoutMs(recipe.window === "full", clipCount, seconds), }], }; @@ -1053,7 +1057,7 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds = ...(spec.summary ? ["--summary", spec.summary] : []), ...(spec.style ? ["--style", spec.style] : []), ...(spec.patch ? ["--patch-json", JSON.stringify(spec.patch)] : []), - ...windowArgs(spec.window), ...(spec.quick ? ["--quick"] : []), ...force, "--progress", "ndjson", + ...windowArgs(spec.window), ...(spec.quick ? ["--quick"] : []), ...force, ...priority, "--progress", "ndjson", ]; return { kind: `take ${project.id} ${spec.id}`, diff --git a/umtool/lib/report/takeRender.mjs b/umtool/lib/report/takeRender.mjs @@ -20,7 +20,10 @@ // build may run beside it while MemAvailable allows; an override of 0 declares // none, and it runs alone. // Inside a slot already held (HEAVY_HELD: an e2e run) it passes straight -// through. A copy of umtool without the checkout's scripts/ runs +// through. In render mode (`umtool take … --priority`, renderMode.mjs) the +// take's process carries the hold's RENDER_PRIORITY_TOKEN, and the render +// inherits it with the rest of the environment: admitted while every other +// heavy job waits, on the render's floor and cap. A copy of umtool without the checkout's scripts/ runs // build-video directly, which takes the slot itself (heavy-gate.mjs). import { execFile, spawn } from "node:child_process"; import { existsSync } from "node:fs"; diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -39,6 +39,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { isCalendarDate } from "umtool-report-to-video/attribution"; import { deckOn } from "umtool-report-to-video/deck"; +import { gappedLength, gapSpan, gapsOf } from "umtool-report-to-video/gaps"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -150,6 +151,8 @@ export function timelineRows(manifest) { start: e.start ?? null, end: e.end ?? null, ...(e.cutStart != null && e.cutEnd != null ? { cutStart: e.cutStart, cutEnd: e.cutEnd } : {}), + // Seconds taken out of its middle (gaps.mjs), and how long it then plays. + ...(gapsOf(e).length ? { gaps: gapsOf(e), plays: Number(gappedLength(gapSpan(e).from, gapSpan(e).to, gapsOf(e)).toFixed(2)) } : {}), } : {}), date: typeof e.date === "string" ? e.date : null, @@ -164,7 +167,8 @@ export function timelineLines(rows) { return rows.map((r) => { const span = r.type === "clip" - ? `${String(r.video ?? "?").padEnd(14)} ${fmt(r.start)}–${fmt(r.end)}${r.cutStart != null ? ` (cut ${fmt(r.cutStart)}–${fmt(r.cutEnd)})` : ""}` + ? `${String(r.video ?? "?").padEnd(14)} ${fmt(r.start)}–${fmt(r.end)}${r.cutStart != null ? ` (cut ${fmt(r.cutStart)}–${fmt(r.cutEnd)})` : ""}` + + (r.gaps?.length ? ` gaps ${r.gaps.map((g) => `−${fmt(g.from)}–${fmt(g.to)}`).join(" ")} (plays ${fmt(r.plays)}s)` : "") : "".padEnd(14); const label = [r.date, r.title].filter(Boolean).join(" "); return `${String(r.index).padStart(3)} ${r.id.padEnd(w)} ${r.type.padEnd(tw)} ${span}${label ? ` ${label}` : ""}`; diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -206,6 +206,10 @@ export default defineConfig({ // with. Set here rather than in a step's env: jobView() echoes a step's // env back to the browser, and this is a token. `ARCHILYZER_EDITOR_URL=http://127.0.0.1:${STUB_PORT} WORKER_TOKEN=umtool-e2e-token ` + + // Render mode's state (common/lib/renderPriority.mjs): the fixture's own, + // so a take made here never joins — and the banner never shows — the + // machine's render mode, and a --priority take holds the stub's lanes. + `RENDER_PRIORITY_FILE=${FIXTURE}/render-priority.json ` + // Two seconds of pacing per CUT, so the deliver spec can press Stop in // the middle of a job and prove that cancelling abandons the rest while // the next run resumes. Read only by bin/cut-from-cache.mjs. diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -162,6 +162,10 @@ import { marksOf, stampsDrawn, validateClaims } from "./factcheck.mjs"; import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs"; import { blurCaptionLayout, blurPictureFilters, blurProblems, blurRecordOf, blurSpan, clipBlurOf, fittedSize, validateClipBlurEntries } from "./clip-blur.mjs"; import { validateFinaleEntries } from "./finale.mjs"; +// Seconds taken out of a clip's middle (gaps.mjs): pure; the segment's graph is built there too. +import { + gapFilterParts, gapSeconds, gapsOnSegment, inGap, offsetIn, recordGaps, renderGaps, validateGapEntries, +} from "./gaps.mjs"; import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -1298,9 +1302,19 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, entry, mont, raw, fetchStart, M: dirs.montage, render, provenance, sil, wantA, wantB, win, })); } + // GAPS (gaps.mjs): seconds taken out of the clip's middle, so it plays as one + // segment of jump cuts. A montage cuts to its phrase: none there. + const clipGaps = mont ? [] : renderGaps(entry, render); + if (mont && Array.isArray(entry.gaps) && entry.gaps.length) { + EMIT("note", { message: `${entry.id}: a montage cuts to its phrase — its gaps are not applied` }); + } // Snapped, and never inverted or collapsed (snap.mjs snapCut: the cut-points route's own). - // A locked edge snaps only outward, inside the silence it sits in (mute.mjs lockedEdges). - const snapped = mont ? null : snapCut({ sil, wantA, wantB, render, locked: lockedEdges(entry, render) }); + // A locked edge snaps only outward, inside the silence it sits in (mute.mjs lockedEdges); + // and no edge snaps across a gap (a gap's edges are exact). + const snapped = mont ? null : snapCut({ + sil, wantA, wantB, render, locked: lockedEdges(entry, render), + ...(clipGaps.length ? { gaps: clipGaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), + }); const a = mont ? mont.win.start : snapped.a; const b = mont ? mont.win.end : snapped.b; const cutA = mont ? mont.win.cutA : snapped.cutA; @@ -1314,6 +1328,22 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, : null; const segA = room ? room.plan.picA : cutA; const segB = room ? room.plan.picB : cutB; + // The gaps on the segment's own clock, on the frame grid (gapsOnSegment), and + // in source seconds as applied (the cut record's `gaps`: what every later + // mapping of a source second onto this segment reads). `segSeconds` is what + // the segment lasts: its span less its gaps -- the span itself without any. + const segGaps = clipGaps.length ? gapsOnSegment(clipGaps, fetchStart + segA, segB - segA, render.fps ?? 30) : []; + const gapTotal = gapSeconds(segGaps); + const segSeconds = segGaps.length ? segB - segA - gapTotal : segB - segA; + if (clipGaps.length) { + EMIT("gaps", { + id: entry.id, gaps: segGaps.length, cut: Number(gapTotal.toFixed(3)), seconds: Number(segSeconds.toFixed(3)), + ...(segGaps.length < clipGaps.length ? { dropped: clipGaps.length - segGaps.length } : {}), + }); + const at = entry.cite ?? entry.start; + const g = inGap(at, clipGaps); + if (g) EMIT("note", { message: `${entry.id}: cite ${at} is inside the gap ${g.from}–${g.to}, which never plays — kept as written; move it` }); + } // Where in the SOURCE this segment really starts and ends, snapped: what a // `muteFrom` (source seconds) is measured from at the join, long after this // function is gone (`--chrome-only` rebuilds no segment). With room, the @@ -1323,6 +1353,10 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, start: Number((fetchStart + segA).toFixed(3)), end: Number((fetchStart + segB).toFixed(3)), snapped: { start: a.snapped, end: b.snapped }, ...(room ? { room: room.record } : {}), + // Only with gaps, so a clip without them records what it always did. + ...(segGaps.length + ? { gaps: segGaps.map((g) => ({ from: Number((fetchStart + segA + g.from).toFixed(3)), to: Number((fetchStart + segA + g.to).toFixed(3)) })) } + : {}), }; // 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 @@ -1336,7 +1370,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // 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. // Room's fades (muted head and tail) after the gain. - const roomAf = room ? roomAudioFilter(room.plan) : ""; + // With gaps, the muted tail is that much earlier on the segment's clock (the gaps are inside the cut). + const roomAf = room ? roomAudioFilter(gapTotal ? { ...room.plan, soundB: room.plan.soundB - gapTotal, picB: room.plan.picB - gapTotal } : room.plan) : ""; // First, the sound laid on its own clock (AUDIO_ON_CLOCK): a cut that starts // before its source's sound does, or a source with a hole in its sound, // makes a segment whose audio is continuous from 0 -- in sync by samples, @@ -1358,7 +1393,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ? [...(shifted.from < 0 ? ["-itsoffset", (-shifted.from).toFixed(3)] : []), ...cutArgs(raw, Math.max(0, shifted.from), shifted.to)] : null; const soundChain = [ - AUDIO_ON_CLOCK, !mont && level != null ? levelFilters(level.gain) : "", roomAf, ...clipAudioFilters(knobs, segB - segA), + AUDIO_ON_CLOCK, !mont && level != null ? levelFilters(level.gain) : "", roomAf, ...clipAudioFilters(knobs, segSeconds), ].filter(Boolean).join(","); const leveled = !mont && soundChain !== ""; // `ain`: the sound's input -- `[0:a]`, or the offset's own. @@ -1398,7 +1433,11 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // about it. Same cut, same audio map, same encode as every other segment. // No picture in the source: a poster stands in for `[0:v]` (see above). const media = await probeMedia(raw); - const posterSeconds = Math.max(1 / render.fps, (media.duration != null ? Math.min(segB, media.duration) : segB) - segA); + const posterSeconds = Math.max(1 / render.fps, (media.duration != null ? Math.min(segB, media.duration) : segB) - segA - gapTotal); + // The gaps taken out first (gaps.mjs gapFilterParts): every later filter + // reads `v` for the picture and `a` for the sound in place of the input's. + // `ain` is the sound's input. Without gaps, the inputs as they always were. + const gapped = (ain) => gapFilterParts({ gaps: segGaps, seconds: segB - segA, vIn: media.hasVideo ? "[0:v]" : null, aIn: ain }); if (!media.hasVideo) EMIT("note", { message: `${entry.id}: no picture in ${path.basename(raw)} — a poster plays under its sound` }); const poster = (box, posterIdx) => media.hasVideo @@ -1413,7 +1452,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // render.blur "off"): every chain below is the one it always was. const blur = clipBlurOf(entry, render); if (blur && !media.hasVideo) EMIT("note", { message: `${entry.id}: no picture to blur in ${path.basename(raw)} — the poster plays as it is` }); - const span = media.hasVideo ? blurSpan(blur, fetchStart + segA, segB - segA) : null; + const span = media.hasVideo ? blurSpan(blur, fetchStart + segA, segSeconds, cutRecord.gaps) : null; if (blur) cutRecord.blur = blurRecordOf(blur); /** The blur's filters for a picture fitted into `bw` × `bh` (empty: none). */ const blurPicture = async (bw, bh) => { @@ -1434,6 +1473,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const fr = framing ?? segmentFraming(render); const pst = await poster(fr.box, 1); const picture = await blurPicture(fr.box.width, fr.box.height); + const g = gapped(soundInput ? `[${pst ? 2 : 1}:a]` : "[0:a]"); // The box it was framed into, so --chrome-only can refuse another layout's. await encodeClipSegment({ seg, outDir, render, opts, id: entry.id, record: { ...cutRecord, framing: fr }, @@ -1443,8 +1483,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ...(pst ? pst.input : []), ...(soundInput ?? []), "-filter_complex", [ - ...levelParts(pst ? pst.parts : null, soundInput ? `[${pst ? 2 : 1}:a]` : "[0:a]"), - `${pst ? "[pic]" : "[0:v]"}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}[v]`, + ...g.parts, + ...levelParts(pst ? pst.parts : null, g.a), + `${pst ? "[pic]" : g.v}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}[v]`, ].join(";"), "-map", "[v]", "-map", audioMap, ...encodeArgs(render), @@ -1519,7 +1560,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // the main extends the output, and the fix for that (shortest=1) would instead // truncate the clip to the strip. Ending early is free: overlay's default // eof_action=repeat holds the strip's last frame, which is the parked bar. - const barT = Math.max(0.2, segB - segA - 0.25); + const barT = Math.max(0.2, segSeconds - 0.25); const inputs = cutArgs(raw, segA, segB); let nextIdx = 1; @@ -1564,10 +1605,12 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // shares it through an asplit. // Even loudness (render.montage.loudness): the cut's sound measured, one gain. const mg = mont ? montageSegmentGraph({ mont, render, box: { w: VW, h: VH }, hasVideo: media.hasVideo, cutA, cutB, gainDb: level?.gain ?? null }) : null; - const pic = mg?.v ?? (pst ? "[pic]" : "[0:v]"); + // The gaps out first (none in a montage: segGaps is empty there). + const g = gapped(ain); + const pic = mg?.v ?? (pst ? "[pic]" : g.v); const lead = mg ? [...(pst ? [`[0:a]asplit=2[mpa][mpw]`, ...pst.parts.map((p) => p.replaceAll("[0:a]", "[mpw]"))] : []), ...mg.parts] - : levelParts(pst ? pst.parts : null, ain); + : [...g.parts, ...levelParts(pst ? pst.parts : null, g.a)]; const parts = hasFooter ? [ @@ -1599,7 +1642,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, if (dirs.look && captionsOn(render)) { const cap = await segmentCaptions({ entry, provenance, look: dirs.look, render, outDir, - from: cutRecord.start, seconds: segB - segA, bottom: FH, + from: cutRecord.start, seconds: segB - segA, bottom: FH, gaps: cutRecord.gaps ?? [], // With room: only the words heard -- none over a muted edge. ...(room ? { audible: { from: fetchStart + cutA, to: fetchStart + room.plan.soundB } } : {}), }); @@ -1680,15 +1723,23 @@ function lookWordsFor(entry, provenance, look, from, to) { * 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, audible = null }) { +async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, bottom, audible = null, gaps = [] }) { // `audible` (room at the edges): the words of that span only, and no line past its end. const src = await lookWordsFor(entry, provenance, look, audible ? audible.from : from, audible ? audible.to : from + seconds); if (audible) seconds = Math.min(seconds, audible.to - from); + // `gaps` (source seconds, the cut record's): a word said in one is not + // heard, and every later one plays that much earlier. + if (gaps.length) { + seconds = offsetIn(from + seconds, from, gaps); + src.words = src.words.filter((w) => !inGap((w.start + w.end) / 2, gaps)); + } 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 rel = gaps.length + ? (x) => ({ ...x, start: offsetIn(x.start, from, gaps), end: offsetIn(x.end, from, gaps) }) + : (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({ @@ -5314,12 +5365,23 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du if (Number.isFinite(rec?.start)) clipClock.set(entries[i].id, rec.start); } } + // A clip with gaps (gaps.mjs): the gaps its segment really left out, from + // its cut record. Read only for those: a cut without gaps measures what it did. + let clipGaps = null; + for (let i = 0; i < entries.length; i += 1) { + if (entries[i].type !== "clip" || !Array.isArray(entries[i].gaps) || !entries[i].gaps.length || !segments[i]) continue; + const rec = await readCutRecord(segments[i]).catch(() => null); + if (!rec) continue; + clipGaps ??= new Map(); + clipGaps.set(entries[i].id, recordGaps(rec)); + } // The variant's posts, placed on the clips this cut plays with their real // upload dates. A manifest without posts writes the schedule it always did. return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [], frameScan: manifest.frameScan ?? null, ...(fx ? { fxWords: fx.words, fxClock: fx.clock } : {}), ...(clipClock ? { clipClock } : {}), + ...(clipGaps ? { clipGaps } : {}), ...(estimated ? { estimated: true } : {}), }); } @@ -5336,12 +5398,16 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du export async function fxClipWords({ entries, segments, provenance = {}, render }) { const words = new Map(); const clock = new Map(); + const clipGaps = new Map(); for (let i = 0; i < entries.length; i += 1) { const e = entries[i]; if (e.type !== "clip") continue; const rec = segments[i] ? await readCutRecord(segments[i]).catch(() => null) : null; const from = Number.isFinite(rec?.start) ? rec.start : playWindow(e, render).from; clock.set(e.id, from); + // A clip's gaps (the record's as applied, else the manifest's): a word in one is not said in the cut. + const gaps = rec ? recordGaps(rec) : renderGaps(e, render); + if (gaps.length) clipGaps.set(e.id, gaps); const span = fxQuoteSpan(e); let got = null; // The captions first when they mark who speaks (">>", a dash) and the @@ -5359,9 +5425,14 @@ export async function fxClipWords({ entries, segments, provenance = {}, render } } } if (!got?.length) got = cueWords; - if (got.length) words.set(e.id, got.map((w) => ({ text: w.text, start: w.start - from, end: w.end - from, ...(w.turn ? { turn: true } : {}) }))); + if (gaps.length) got = got.filter((w) => !inGap((w.start + w.end) / 2, gaps)); + if (got.length) { + words.set(e.id, got.map((w) => ({ + text: w.text, start: offsetIn(w.start, from, gaps), end: offsetIn(w.end, from, gaps), ...(w.turn ? { turn: true } : {}), + }))); + } } - return { words, clock }; + return { words, clock, ...(clipGaps.size ? { gaps: clipGaps } : {}) }; } /** @@ -5670,6 +5741,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole, { schedule: false }), ...validateTransitionStyle(whole), ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole), + ...validateGapEntries(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } diff --git a/umtool/report-to-video/clip-blur.mjs b/umtool/report-to-video/clip-blur.mjs @@ -35,6 +35,7 @@ // cut's switch (`render.blur`) is one of the look's keys: its rules are the // common look.mjs's, re-exported here. import { RENDER_BLUR_VALUES, renderBlurOn, validateRenderBlur } from "yt-dlp-transcript-common/lib/report/look.mjs"; +import { offsetIn } from "./gaps.mjs"; export { RENDER_BLUR_VALUES, renderBlurOn, validateRenderBlur }; @@ -139,13 +140,15 @@ const f3 = (n) => String(Number(n.toFixed(3))); /** * Where a blur lands in a segment that starts at source second `segStart` and * runs `seconds`: `{ whole: true }` (all of it), `{ a, b }` (the segment's - * own seconds), or null (the span misses the segment entirely). + * own seconds), or null (the span misses the segment entirely). `gaps` + * (source seconds, gaps.mjs): the segment's left-out seconds, so an edge + * after one lands that much earlier, and an edge inside one at its join. */ -export function blurSpan(blur, segStart, seconds) { +export function blurSpan(blur, segStart, seconds, gaps = null) { if (!blur) return null; if (blur.from === null && blur.to === null) return { whole: true }; - const a = Math.max(0, (blur.from ?? -Infinity) - segStart); - const b = Math.min(seconds, (blur.to ?? Infinity) - segStart); + const a = Math.max(0, blur.from === null || blur.from === undefined ? -Infinity : offsetIn(blur.from, segStart, gaps)); + const b = Math.min(seconds, blur.to === null || blur.to === undefined ? Infinity : offsetIn(blur.to, segStart, gaps)); if (!(b > a)) return null; if (a <= 0 && b >= seconds) return { whole: true }; return { a, b }; diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -16,6 +16,7 @@ // build-video.mjs or compose-chrome.mjs instead. import { createHash } from "node:crypto"; import { playEdges, soundEdges as soundEdgesOf, soundOnSegment } from "./mute.mjs"; +import { gappedLength, offsetIn, recordGaps, renderGaps } from "./gaps.mjs"; import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; @@ -864,7 +865,8 @@ export function scheduleFrom(durs, D) { export function estimatedDuration(entry, render = {}, D = transitionOf(render)) { if (entry.type === "clip") { const { from, to } = playWindow(entry, render); - return Math.max(1, to - from); + // Less its gaps (gaps.mjs): the seconds taken out of its middle never play. + return Math.max(1, gappedLength(from, to, renderGaps(entry, render))); } if (entry.type === "image") return Number(entry.seconds ?? 4); // The brand intro (intro.mjs) is exactly its `seconds` (introEntry fills the default). @@ -1005,9 +1007,15 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin */ export function deckSchedule({ entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], frameScan = null, - fxWords = null, fxClock = null, clipClock = null, + fxWords = null, fxClock = null, clipClock = null, clipGaps = null, }) { const deck = resolveDeck(render); + // A clip's gaps (gaps.mjs) on its segment: its cut record's as built + // (`clipGaps`), else its own. A source second after one plays that much + // earlier in the cut; only a segment with any carries `gaps`, so a cut + // without them places everything as it always did. + const gapsFor = (e) => clipGaps?.get(e.id) ?? renderGaps(e, render); + const withGaps = (s, e) => (gapsFor(e).length ? { ...s, gaps: gapsFor(e) } : s); const fps = render.fps ?? 30; // The series a mark may count (counter.mjs): the counter's, else the verdicts. const series = resolveCounter(render).order; @@ -1048,7 +1056,7 @@ export function deckSchedule({ const many = marks.length > 1 ? { claims: marks } : {}; if (!marks.some((c) => c.at !== undefined)) return { ...s, claim, ...many }; const e = entries[i]; - return { ...s, claim, ...many, sourceFrom: clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from }; + return withGaps({ ...s, claim, ...many, sourceFrom: clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from }, e); }), D, total, render, }); @@ -1073,7 +1081,7 @@ export function deckSchedule({ const e = entries[i]; if (!statsWanted(e, render)) return s; const points = overlayPointsOf({ frameScan }, e.id); - return points.length ? { ...s, points, sourceFrom: playWindow(e, render).from } : s; + return points.length ? withGaps({ ...s, points, sourceFrom: playWindow(e, render).from }, e) : s; }), D, total, render, }); @@ -1085,6 +1093,7 @@ export function deckSchedule({ ? fxSchedule({ segments: segs, entries, metas, render, D, total, words: fxWords, fps, sourceFrom: (e) => fxClock?.get(e.id) ?? playWindow(e, render).from, + gapsOf: gapsFor, hidden: (e) => hidesDeck(e, deck), }) : null; @@ -1093,6 +1102,7 @@ export function deckSchedule({ const deckClaims = claimsSchedule({ entries, segments: segs, D, total, metas, render, stamps, sourceFrom: (e) => clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from, + gapsOf: gapsFor, }); const claimClips = deckClaims ? deckClaimClips(render) : new Set(); const doc = { @@ -1193,7 +1203,7 @@ export function deckSchedule({ * * `n` is each item's index in `deck.claims`, for messages. */ -export function claimsSchedule({ entries, segments, D, total, metas = [], render, stamps = [], sourceFrom }) { +export function claimsSchedule({ entries, segments, D, total, metas = [], render, stamps = [], sourceFrom, gapsOf = () => null }) { const list = render?.chrome?.deck?.claims; if (!Array.isArray(list) || !list.length || deckClaimShapeErrors(list).length) return null; const verdicts = resolveFactcheck(render).verdicts; @@ -1208,7 +1218,7 @@ export function claimsSchedule({ entries, segments, D, total, metas = [], render const cutAt = (id, t) => { const i = idx.get(id); const s = segments[i]; - return round(Math.min(s.start + s.duration, Math.max(s.start, s.start + (t - sourceFrom(entries[i]))))); + return round(Math.min(s.start + s.duration, Math.max(s.start, s.start + offsetIn(t, sourceFrom(entries[i]), gapsOf(entries[i]))))); }; const untilOf = (id) => { const i = idx.get(id); @@ -2519,14 +2529,16 @@ export const endFadeOf = (render) => (numIn(render?.endFade, 0, END_FADE_MAX) ? */ export function muteSegmentSeconds({ entry, record = null, render = {}, seconds = null, source = entry.muteFrom }) { const fps = render.fps ?? 30; + // A segment with gaps (gaps.mjs) is its span less them: the record says which it left out. + const recGaps = recordGaps(record); const ok = record && record.video === entry.video && Number.isFinite(record.start) && Number.isFinite(record.end) && - (seconds == null || Math.abs(record.end - record.start - seconds) <= 2 / fps); - const at = (from) => Math.max(0, Math.round((source - from) * 1000) / 1000); - if (ok) return { at: at(record.start), source: "record" }; + (seconds == null || Math.abs(gappedLength(record.start, record.end, recGaps) - seconds) <= 2 / fps); + const at = (from, gaps = null) => Math.max(0, Math.round(offsetIn(source, from, gaps) * 1000) / 1000); + if (ok) return { at: at(record.start, recGaps), source: "record" }; const { from } = playWindow(entry, render); return { - at: at(from), + at: at(from, renderGaps(entry, render)), source: "window", note: `${entry.id}: ${record ? "the cut record does not match the segment" : "no cut record beside the segment"} — ` + @@ -2556,7 +2568,9 @@ export function segmentSoundEdits({ entry, record = null, render = {}, seconds } const probe = muteSegmentSeconds({ entry, record, render, seconds, source: se.muteFrom ?? se.soundFrom }); const fromRecord = probe.source === "record"; if (probe.note && entry.muteFrom != null) out.notes.push(probe.note); - const on = soundOnSegment(entry, render, fromRecord ? record.start : playEdges(entry, render).from, seconds); + const on = fromRecord + ? soundOnSegment(entry, render, record.start, seconds, recordGaps(record)) + : soundOnSegment(entry, render, playEdges(entry, render).from, seconds, renderGaps(entry, render)); if (se.muteFrom != null && !se.implicit) { const from = fromRecord ? "from its cut record" : "from the unsnapped start"; // Validation allows the clip's whole extent, but only the played window is diff --git a/umtool/report-to-video/factcheck.mjs b/umtool/report-to-video/factcheck.mjs @@ -34,6 +34,7 @@ // verdicts, their default labels and colours and the override rules are one // copy shared with report.json and the export site's report pages. This file // re-exports the list and lays the stamp and tally settings beside the labels. +import { offsetIn } from "./gaps.mjs"; import { isIsoDate } from "./claims.mjs"; import { resolveCounter, VERDICT_SHAPES } from "./counter.mjs"; import { COUNTER_CELL } from "./modules/design.mjs"; @@ -593,7 +594,8 @@ export function stampSchedule({ segments, D, total, render }) { // plays at, inside the segment and before its stamp has to leave. const timed = (c) => { const stay = c.hold ?? seconds; - const want = seg.start + (c.at - seg.sourceFrom); + // A segment with gaps (gaps.mjs `gaps`, source seconds): the seconds that play. + const want = seg.start + offsetIn(c.at, seg.sourceFrom, seg.gaps); const landed = Math.min(Math.max(seg.start, want), out[0]); const at = Math.max(seg.start, landed - STAMP_MOTION.slam); const leave = Math.min(at + stay, out[0]); diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs @@ -37,6 +37,7 @@ // deck.mjs), so the few date and phrase helpers it needs are its own. import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; +import { offsetIn, sourceAtOffset } from "./gaps.mjs"; /** Each effect's key under `render.chrome.fx`, in the order the page stacks them (later on top). */ export const FX_KEYS = Object.freeze(["scrubber", "receipts", "zoom", "kineticQuote", "redact", "odometer", "punchIn", "thenNow", "whip", "glitch"]); @@ -637,9 +638,9 @@ export function quotePages(words, max) { * * @param {{ segments: Array<{id: string, start: number, duration: number}>, entries: any[], metas?: any[], * render: any, D: number, total: number, words?: Map<string, Array<{text: string, start: number, end: number}>> | null, - * sourceFrom: (entry: any) => number, hidden: (entry: any) => boolean, fps?: number }} args + * sourceFrom: (entry: any) => number, gapsOf?: (entry: any) => Array<{ from: number, to: number }> | null, hidden: (entry: any) => boolean, fps?: number }} args */ -export function fxSchedule({ segments, entries, metas = [], render, D, total, words = null, sourceFrom, hidden, fps = 30 }) { +export function fxSchedule({ segments, entries, metas = [], render, D, total, words = null, sourceFrom, gapsOf = () => null, hidden, fps = 30 }) { const keys = fxKeysOn(render); if (!keys.length) return null; const out = { keys }; @@ -666,7 +667,8 @@ export function fxSchedule({ segments, entries, metas = [], render, D, total, wo if (!ws || !ws.length) { const fb = fxQuoteFallback(c.entry); const f0 = sourceFrom(c.entry); - ws = fb.map((w) => ({ ...w, start: w.start - f0, end: w.end - f0 })); + const g = gapsOf(c.entry); + ws = fb.map((w) => ({ ...w, start: offsetIn(w.start, f0, g), end: offsetIn(w.end, f0, g) })); } const placed = (ws ?? []) .map((w) => ({ text: w.text, at: r3(c.start + w.start), end: r3(c.start + w.end), ...(w.turn ? { turn: true } : {}) })) @@ -691,7 +693,7 @@ export function fxSchedule({ segments, entries, metas = [], render, D, total, wo const ws = wordsOf(c); if (!ws) continue; const mask = punchMask(ws, fxPunchOf(c.entry)); - const who = style === "kinetic" && cfg.speakers === "auto" ? speakersOf(ws, c, sourceFrom) : null; + const who = style === "kinetic" && cfg.speakers === "auto" ? speakersOf(ws, c, sourceFrom, gapsOf) : null; const marked = ws.map((w, j) => ({ ...w, punch: mask[j], ...(who ? { speaker: who[j] } : {}) })); // A page holds one speaker's words: a turn starts a new page. const runs = []; @@ -830,7 +832,8 @@ export function fxSchedule({ segments, entries, metas = [], render, D, total, wo const rows = []; for (const c of vclips) { const f0 = sourceFrom(c.entry); - const seconds = new Set((Array.isArray(c.entry.fx?.punchIn) ? c.entry.fx.punchIn : []).map((t) => r3(t - f0))); + const g = gapsOf(c.entry); + const seconds = new Set((Array.isArray(c.entry.fx?.punchIn) ? c.entry.fx.punchIn : []).map((t) => r3(offsetIn(t, f0, g)))); // A laugh written in the captions, when `auto`: the word's start. if (pi.auto) for (const w of wordsOf(c) ?? []) if (FX_LAUGH_RE.test(fxNorm(w.text))) seconds.add(r3(w.at - c.start)); // In the segment's clock, inside the clip's clean span; two closer than @@ -949,13 +952,14 @@ export function fxZoomJoins(schedule) { * the line has one voice. It says WHICH of two voices, never whose: the * labels are the manifest's (`kineticQuote.voices`). */ -export function speakersOf(words, c, sourceFrom) { +export function speakersOf(words, c, sourceFrom, gapsOf = () => null) { const marks = Array.isArray(c.entry?.fx?.speakers) ? [...c.entry.fx.speakers].sort((a, b) => a.at - b.at) : null; let who; if (marks?.length) { const f0 = sourceFrom(c.entry); + const g = gapsOf(c.entry); who = words.map((w) => { - const src = w.at - c.start + f0; + const src = g?.length ? sourceAtOffset(w.at - c.start, f0, g) : w.at - c.start + f0; let v = marks[0].who; for (const m of marks) if (m.at <= src + 1e-6) v = m.who; return v; diff --git a/umtool/report-to-video/gaps-render.test.mjs b/umtool/report-to-video/gaps-render.test.mjs @@ -0,0 +1,207 @@ +// Gaps inside a clip (gaps.mjs), rendered for real and on the schedule: a clip +// with a gap is ONE segment, the kept seconds long, with the gap's picture and +// sound gone and its cut record naming what it left out; the cut is the +// segments' sum less the joins, as ever; absent or `[]` the render is byte for +// byte what it was. And every mapping of a source second onto the cut that +// reads the record -- the mute mark at the join, a claim stamped at a source +// second, the estimate's length -- jumps with the gap. +// +// 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-gaps-corpus-")); +process.env.CHANNELS_DIR = CORPUS; + +const { buildVideo, probeDuration, setProgressMode } = await import("./build-video.mjs"); +const { deckSchedule, estimatedDuration, muteSegmentSeconds, segmentSoundEdits } = await import("./deck.mjs"); +const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs"); +const { renderCut, snapCut } = await import("./snap.mjs"); + +test.after(() => rm(CORPUS, { recursive: true, force: true })); + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +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.4, + 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 dir = path.join(CORPUS, CHANNEL, "data", "vid1"); + 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: "vid1", title: "Synthetic", duration: 12, uploadDate: "20240102", cues: [{ start: 0.2, end: 11.8, text: "words" }] })); + writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 12 })); +} + +/** + * A project: c1 1–6 s and c2 7–10 s of one 12 s window in out/clips-raw: a + * grey picture and a tone, BLACK and SILENT over 3–4 s (the gap c1 may take + * out), so what the render kept can be seen and heard. + */ +async function project(c1 = {}) { + const root = mkdtempSync(path.join(os.tmpdir(), "rtv-gaps-")); + mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); + const raw = path.join(root, "out", "clips-raw", "vid1_0.00-12.00.mp4"); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=320x180:r=${FPS}:d=12`, + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", + "-filter_complex", "[0:v]drawbox=c=black:t=fill:enable='between(t,3,3.99)'[v];[1:a]volume=enable='between(t,3,3.99)':volume=0,volume=0.5[a]", + "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, + ]); + assert.equal(r.status, 0, String(r.stderr)); + const manifestPath = path.join(root, "video.manifest.json"); + await writeFile(manifestPath, JSON.stringify({ + slug: "gaps", title: "Gaps", + provenance: { channelSlug: CHANNEL, channelsDir: CORPUS }, + render: RENDER, + timeline: [ + { type: "clip", id: "c1", channel: CHANNEL, video: "vid1", start: 1, end: 6, cite: 1, quote: "q", ...c1 }, + { type: "clip", id: "c2", channel: CHANNEL, video: "vid1", start: 7, end: 10, cite: 7, quote: "q" }, + ], + })); + return { root, manifestPath, seg: (id) => path.join(root, "out", "sourced", "segments", `${id}.mp4`) }; +} + +const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0]; +const quiet = () => setProgressMode(() => {}); +const record = async (p, id) => JSON.parse(await readFile(p.seg(id).replace(/\.mp4$/, ".cut.json"), "utf8")); +const near = (a, b, tol, what) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +/** Each frame's mean luma. */ +function lumas(file) { + const st = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"], { maxBuffer: 1 << 24 }); + return st.stdout.toString().split("\n").filter((l) => l.includes("YAVG")).map((l) => Number(l.split("=")[1])); +} +/** The RMS of a file's sound over [a, b] (s), mono 8 kHz. */ +function rms(file, a, b) { + const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 26 }); + const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, Math.floor(r.stdout.length / 2)); + let sum = 0; + let n = 0; + for (let i = Math.floor(a * 8000); i < Math.min(pcm.length, Math.floor(b * 8000)); i += 1) { + sum += pcm[i] * pcm[i]; + n += 1; + } + return n ? Math.sqrt(sum / n) : 0; +} + +test("render: without gaps (absent or []) the cut is byte for byte the same, and the record says nothing new", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const ps = [await project({}), await project({ gaps: [] })]; + try { + for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + for (const f of ["gaps.mp4", "sourced/segments/c1.mp4", "sourced/segments/c2.mp4", "sourced/segments/c1.cut.json"]) { + const sums = ps.map((p) => md5(path.join(p.root, "out", f))); + assert.equal(new Set(sums).size, 1, `${f}: ${sums.join(" ")}`); + } + assert.equal((await record(ps[0], "c1")).gaps, undefined); + // The black and the silence are in c1 without the gap (2–3 s into it). + assert.ok(Math.min(...lumas(ps[0].seg("c1"))) < 30, "the gap's black plays without gaps"); + } finally { + for (const p of ps) await rm(p.root, { recursive: true, force: true }); + } +}); + +test("render: a gap is taken out of ONE segment -- the kept seconds long, no black, no silence; the record names it; the cut is the sum less the join", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const p = await project({ gaps: [{ from: 3, to: 4 }] }); + try { + const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + const rec = await record(p, "c1"); + assert.deepEqual([rec.start, rec.end], [1, 6]); + assert.deepEqual(rec.gaps, [{ from: 3, to: 4 }]); + const d1 = await probeDuration(p.seg("c1"), FPS); + near(d1, 4, 1 / FPS + 1e-6, "c1 is its 5 s less the 1 s gap"); + const y = lumas(p.seg("c1")); + assert.ok(Math.min(...y) > 60, `no black frame left in c1 (min YAVG ${Math.min(...y)})`); + // Heard all through: before the join, across it (its fades are 25 ms), after. + assert.ok(rms(p.seg("c1"), 0.2, 1.9) > 800, "before the join"); + assert.ok(rms(p.seg("c1"), 1.9, 2.1) > 600, "across the join"); + assert.ok(rms(p.seg("c1"), 2.1, 3.8) > 800, "after the join"); + const d2 = await probeDuration(p.seg("c2"), FPS); + near(await probeDuration(r.out, FPS), d1 + d2 - 0.4, 2 / FPS, "the cut's length"); + // A gap changed is that segment re-rendered, and only that one. + const c2Before = md5(p.seg("c2")); + const m = JSON.parse(await readFile(p.manifestPath, "utf8")); + m.timeline[0].gaps = [{ from: 2, to: 2.5 }]; + await writeFile(p.manifestPath, JSON.stringify(m)); + const events = []; + setProgressMode((e) => events.push(e)); + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + near(await probeDuration(p.seg("c1"), FPS), 4.5, 1 / FPS + 1e-6, "c1 with the new gap"); + assert.equal(md5(p.seg("c2")), c2Before, "c2 untouched"); + const reused = events.filter((e) => e.ev === "note" && / segment unchanged /.test(e.message)).map((e) => e.message.split(":")[0]); + assert.ok(reused.includes("c2"), `c2 was reused (${JSON.stringify(reused)})`); + assert.ok(!reused.includes("c1"), `c1 was rebuilt (${JSON.stringify(reused)})`); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +// ---- the schedule's mappings, no ffmpeg ------------------------------------------ + +const CLIP = { type: "clip", id: "c1", video: "v", start: 100, end: 120, cutStart: 102, cutEnd: 118 }; +const GAPS = [{ from: 105, to: 107 }]; + +test("estimatedDuration: the play window less its gaps (and none in a montage)", () => { + const r = { leadIn: 0.4 }; + assert.ok(Math.abs(estimatedDuration(CLIP, r) - 16.4) < 1e-9); + assert.ok(Math.abs(estimatedDuration({ ...CLIP, gaps: GAPS }, r) - 14.4) < 1e-9); + assert.ok(Math.abs(estimatedDuration({ ...CLIP, gaps: GAPS }, { ...r, montage: { style: "wall" } }) - 16.4) < 1e-9); +}); + +test("the mute mark on the segment's clock: after a gap, that much earlier (from the record's gaps)", () => { + const e = { ...CLIP, gaps: GAPS, muteFrom: 110 }; + const record = { video: "v", start: 101.6, end: 118, gaps: GAPS }; + // The segment is 16.4 s less 2 s of gap. + const m = muteSegmentSeconds({ entry: e, record, render: { fps: 30 }, seconds: 14.4 }); + assert.equal(m.source, "record"); + assert.equal(m.at, Number((110 - 101.6 - 2).toFixed(3))); + // A record from before the gaps (no `gaps`, the old length) is not believed: the window's estimate, gap-aware. + const old = muteSegmentSeconds({ entry: e, record: { video: "v", start: 101.6, end: 118 }, render: { fps: 30 }, seconds: 14.4 }); + assert.equal(old.source, "window"); + assert.equal(old.at, Number((110 - 101.6 - 2).toFixed(3))); + // The joins' rule agrees. + const ed = segmentSoundEdits({ entry: e, record, render: { fps: 30 }, seconds: 14.4 }); + assert.equal(ed.mute, m.at); +}); + +test("a claim stamped at a source second lands that much earlier after a gap; without gaps exactly where it did", () => { + const render = { fps: 30, transition: 0.5, leadIn: 0.4, chrome: { engine: "hyperframes", layout: "deck" } }; + const claim = { id: "k1", verdict: "CONTRADICTED", at: 110 }; + const entries = [{ ...CLIP, claim }]; + const plain = deckSchedule({ entries, durs: [16.4], D: 0.5, render }); + const gapped = deckSchedule({ entries: [{ ...CLIP, claim, gaps: GAPS }], durs: [14.4], D: 0.5, render }); + const landed = (s) => s.factcheck.stamps[0].landed; + assert.ok(Math.abs(landed(plain) - (110 - 101.6)) < 1e-6, `plain ${landed(plain)}`); + assert.ok(Math.abs(landed(gapped) - (110 - 101.6 - 2)) < 1e-6, `gapped ${landed(gapped)}`); + // The record's gaps win over the manifest's (the frame grid's edges). + const fromRecord = deckSchedule({ + entries: [{ ...CLIP, claim, gaps: GAPS }], durs: [14.4], D: 0.5, render, + clipClock: new Map([["c1", 101.6]]), clipGaps: new Map([["c1", [{ from: 105, to: 106 }]]]), + }); + assert.ok(Math.abs(landed(fromRecord) - (110 - 101.6 - 1)) < 1e-6); +}); + +test("snapCut: no edge snaps across a gap, nor nearer it than half a second", () => { + // A silence right after the start that would pull it inward, past the gap at 1.0 (file seconds). + const sil = [{ s: 0.6, e: 1.4 }]; + const free = snapCut({ sil, wantA: 0.5, wantB: 5, render: { snapWindow: 1.6 } }); + assert.ok(free.a.at > 1, `without the gap it snaps inward (${free.a.at})`); + const held = snapCut({ sil, wantA: 0.5, wantB: 5, render: { snapWindow: 1.6 }, gaps: [{ from: 1.2, to: 2 }] }); + assert.deepEqual(held.a, { at: 0.5, snapped: false }); + // renderCut takes source seconds. + const rc = renderCut({ sil, fetchStart: 100, playFrom: 100.5, playTo: 105, render: { snapWindow: 1.6 }, gaps: [{ from: 101.2, to: 102 }] }); + assert.equal(rc.start, 100.5); +}); diff --git a/umtool/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs @@ -0,0 +1,426 @@ +// GAPS INSIDE A CLIP: seconds taken out of the middle of one clip, which then +// plays as ONE segment of jump cuts -- one header, one pip, one subtitle card -- +// rather than as two clips with a crossfade between them. +// +// timeline entry: "gaps": [{ "from": 32988.4, "to": 32990.1 }, ...] +// +// SOURCE seconds, like `start`/`end`/`cutStart`/`cutEnd`. Each gap lies inside +// the clip's CUT (its `cutStart`–`cutEnd`, else its extent), at least +// GAP_LIMITS.min long, at most GAP_LIMITS.max of them, sorted, apart, and with +// at least GAP_LIMITS.keep seconds of material before the first, between any +// two and after the last: a sliver of picture between two jumps reads as a +// glitch, not a cut. A `muteFrom` or a claim mark's `at` strictly INSIDE a gap +// is refused: it names a second the cut never plays, and moving it to the +// join would move a decision somebody made by ear (an `at`, or the mark, on +// a gap's edge is fine -- it lands at the join). +// +// Absent (or empty), every number below is the one a clip without gaps always +// had: `offsetIn(src, from, [])` is `src - from`, byte for byte. +// +// THE CLOCKS. A segment's picture starts at source second `from` (its cut +// record's `start`); the gapped clock counts only the seconds that PLAY. +// `offsetIn` maps a source second onto it (a second inside a gap lands on the +// join, where the gap was), `sourceAtOffset` maps back (the join shows the +// material after the gap). +// +// Dependency-free, so a client bundle (Play the cut, the clip editor, the live +// preview) takes it alone; the writer (umtool lib/report/manifest.mjs), the +// build's validators (lint.mjs, build-video.mjs) and `umtool check` share +// `validateGaps`. + +/** The rules a clip's gaps keep: seconds (min, keep) and a count (max). */ +export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 12, keep: 0.5 }); + +/** Each join's fade, in seconds: out over the end of the piece before, in over the start of the piece after -- short enough to keep a word, long enough not to click. */ +export const GAP_FADE = 0.025; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const EPS = 1e-6; +/** The writer's tolerance for a stored 2 dp edge (manifest.mjs WIN_EPS). */ +const WIN_EPS = 0.02; + +/** + * The span a clip's gaps must lie in: its cut when it has both fields, else + * its extent. + * + * @param {Record<string, any>} entry + * @returns {{ from: number, to: number }} + */ +export function gapSpan(entry) { + const hasCut = fin(entry?.cutStart) && fin(entry?.cutEnd); + return { from: hasCut ? entry.cutStart : entry?.start, to: hasCut ? entry.cutEnd : entry?.end }; +} + +/** + * A clip's gaps as the arithmetic reads them: the well-formed ones, sorted. + * [] for none -- and for anything that is not a list (validateGaps says why; + * the build refuses it before it gets here). + * + * @param {Record<string, any> | null | undefined} entry + * @returns {Array<{ from: number, to: number }>} + */ +export function gapsOf(entry) { + const g = entry?.gaps; + if (!Array.isArray(g) || !g.length) return []; + return g + .filter((x) => isObj(x) && fin(x.from) && fin(x.to) && x.to > x.from) + .map((x) => ({ from: x.from, to: x.to })) + .sort((a, b) => a.from - b.from); +} + +/** Does this clip carry any gap? */ +export const hasGaps = (entry) => gapsOf(entry).length > 0; + +/** + * The gaps a render of this block applies to a clip: its own, except in a + * montage (render.montage), which cuts every clip to its phrase. + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + */ +export function renderGaps(entry, render = {}) { + if (entry?.type !== "clip") return []; + if (render?.montage != null && typeof render.montage === "object" && !Array.isArray(render.montage)) return []; + return gapsOf(entry); +} + +/** + * The marks a clip carries, raw (`claims`, else `claim`) -- what an `at` + * inside a gap is looked for in. + */ +const marksAt = (entry) => (Array.isArray(entry?.claims) ? entry.claims : isObj(entry?.claim) ? [entry.claim] : []) + .filter((m) => isObj(m) && fin(m.at)); + +/** The gap a source second lies strictly inside, or null. */ +export function inGap(src, gaps) { + if (!fin(src)) return null; + for (const g of gaps ?? []) if (src > g.from + EPS && src < g.to - EPS) return g; + return null; +} + +/** + * Every reason a clip's `gaps` cannot be built, as sentences naming `where` + * (empty: it can). Absent or null is none; `[]` is none too (the writer + * removes it). + * + * @param {Record<string, any>} entry + * @param {string} [where] + * @returns {string[]} + */ +export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}`) { + const v = entry?.gaps; + if (v === undefined || v === null) return []; + if (entry.type !== "clip") return [`${where}.gaps: only a clip has seconds to take out`]; + if (!Array.isArray(v)) return [`${where}.gaps must be a list of { from, to } in source seconds`]; + if (!v.length) return []; + const errors = []; + if (v.length > GAP_LIMITS.max) errors.push(`${where}.gaps: at most ${GAP_LIMITS.max} gaps in one clip (it has ${v.length}) — split it into clips`); + const ok = []; + v.forEach((g, k) => { + if (!isObj(g) || !fin(g.from) || !fin(g.to)) { + errors.push(`${where}.gaps[${k}] must be { from, to } in source seconds`); + return; + } + if (g.to - g.from < GAP_LIMITS.min - EPS) { + errors.push(`${where}.gaps[${k}] ${g.from}–${g.to} is under ${GAP_LIMITS.min} s — too short to hear as a cut`); + return; + } + ok.push({ ...g, k }); + }); + if (errors.length) return errors; + for (let i = 1; i < ok.length; i += 1) { + if (ok[i].from < ok[i - 1].from) { + errors.push(`${where}.gaps must be in order (gaps[${ok[i].k}] ${ok[i].from} starts before gaps[${ok[i - 1].k}] ${ok[i - 1].from})`); + return errors; + } + } + const span = gapSpan(entry); + const keep = GAP_LIMITS.keep; + // The span is the cut when the clip has one, else its extent: say which. + const whose = fin(entry.cutStart) && fin(entry.cutEnd) ? "cut" : "clip"; + ok.forEach((g, i) => { + if (fin(span.from) && fin(span.to) && (g.from < span.from - WIN_EPS || g.to > span.to + WIN_EPS)) { + errors.push(`${where}.gaps[${g.k}] ${g.from}–${g.to} lies outside the clip's ${whose} ${span.from}–${span.to} — widen the ${whose}, or remove the gap`); + return; + } + const before = i === 0 ? span.from : ok[i - 1].to; + const what = i === 0 ? `the ${whose}'s start` : `gaps[${ok[i - 1].k}]`; + if (fin(before) && g.from - before < keep - WIN_EPS) { + errors.push( + i > 0 && g.from < before + ? `${where}.gaps[${g.k}] ${g.from}–${g.to} overlaps ${what} — merge them into one gap` + : `${where}.gaps[${g.k}] ${g.from}–${g.to} leaves ${Math.max(0, g.from - before).toFixed(2)} s after ${what}; keep at least ${keep} s between cuts`, + ); + } + }); + const last = ok[ok.length - 1]; + if (!errors.length && fin(span.to) && span.to - last.to < keep - WIN_EPS) { + errors.push(`${where}.gaps[${last.k}] ${last.from}–${last.to} leaves ${Math.max(0, span.to - last.to).toFixed(2)} s before the ${whose}'s end; keep at least ${keep} s`); + } + if (errors.length) return errors; + // A mark that names a second the cut never plays. + if (fin(entry.muteFrom) && inGap(entry.muteFrom, ok)) { + const g = inGap(entry.muteFrom, ok); + errors.push(`${where}.muteFrom ${entry.muteFrom} lies inside the gap ${g.from}–${g.to}, which never plays — move the mark to the gap's edge, or remove the gap`); + } + for (const m of marksAt(entry)) { + const g = inGap(m.at, ok); + const name = typeof m.id === "string" && m.id ? `the mark ${m.id}'s second` : "the stamp's second"; + if (g) errors.push(`${where}: ${name} (at ${m.at}) lies inside the gap ${g.from}–${g.to}, which never plays — move it, or remove the gap`); + } + return errors; +} + +/** Every clip's gaps in the timeline, checked: the build refuses with these before it fetches. */ +export function validateGapEntries(manifest) { + const errors = []; + (manifest?.timeline ?? []).forEach((e, i) => { + errors.push(...validateGaps(e, `timeline[${i}] (${e?.id ?? "?"})`)); + }); + return errors; +} + +/** + * A list of gaps as the writer stores it: each edge at 2 dp, sorted by its + * start. Not validated (validateGaps on the entry is). + * + * @param {Array<{ from: number, to: number }>} list + */ +export function normalizeGaps(list) { + const r2 = (n) => Number(Number(n).toFixed(2)); + return (list ?? []) + .map((g) => ({ from: r2(g.from), to: r2(g.to) })) + .sort((a, b) => a.from - b.from || a.to - b.to); +} + +/** + * The gaps that fall in [from, to], clipped to it: what a segment cut from + * `from` to `to` actually leaves out. A gap the snapped edge has moved past + * is dropped; one it cuts into is clipped. + * + * @param {Array<{ from: number, to: number }>} gaps + * @param {number} from + * @param {number} to + */ +export function gapsWithin(gaps, from, to) { + const out = []; + for (const g of gaps ?? []) { + const a = Math.max(g.from, from); + const b = Math.min(g.to, to); + if (b - a > EPS) out.push({ from: a, to: b }); + } + return out; +} + +/** How many seconds of [from, to] the gaps take out. */ +export function gapSeconds(gaps, from = -Infinity, to = Infinity) { + let s = 0; + for (const g of gaps ?? []) { + const a = Math.max(g.from, from); + const b = Math.min(g.to, to); + if (b > a) s += b - a; + } + return s; +} + +/** The seconds [from, to] plays with its gaps taken out (`to - from` without any). */ +export function gappedLength(from, to, gaps) { + return gaps?.length ? Math.max(0, to - from - gapSeconds(gaps, from, to)) : to - from; +} + +/** + * Source second `src` on the gapped clock of a segment whose picture starts + * at source second `from`: the seconds that PLAY between them. A second + * inside a gap lands on the join. Without gaps, `src - from`. + * + * @param {number} src + * @param {number} from + * @param {Array<{ from: number, to: number }> | null | undefined} gaps + */ +export function offsetIn(src, from, gaps) { + if (!gaps?.length) return src - from; + return src - from - gapSeconds(gaps, from, Math.max(from, src)); +} + +/** + * The inverse: the source second that plays `off` seconds into a segment + * whose picture starts at source second `from`. A join shows the material + * after its gap. Without gaps, `from + off`. + * + * @param {number} off + * @param {number} from + * @param {Array<{ from: number, to: number }> | null | undefined} gaps + */ +export function sourceAtOffset(off, from, gaps) { + if (!gaps?.length) return from + off; + let s = from + off; + for (const g of gaps) { + if (g.to <= from) continue; + const a = Math.max(g.from, from); + if (s >= a - EPS) s += g.to - a; + else break; + } + return s; +} + +/** + * The pieces of [from, to] that play, in order (the whole span without gaps). + * + * @param {number} from + * @param {number} to + * @param {Array<{ from: number, to: number }> | null | undefined} gaps + * @returns {Array<{ from: number, to: number }>} + */ +export function keptSpans(from, to, gaps) { + if (!gaps?.length) return [{ from, to }]; + const out = []; + let at = from; + for (const g of gapsWithin(gaps, from, to)) { + if (g.from - at > EPS) out.push({ from: at, to: g.from }); + at = Math.max(at, g.to); + } + if (to - at > EPS) out.push({ from: at, to }); + return out; +} + +/** + * A segment's gaps on its OWN clock, for the encode: each gap's edges in + * seconds from the segment's first frame (`segStart`, source seconds), put on + * the render's frame grid -- so the picture's trim and the sound's cut the + * same instants and every piece is whole frames -- and clipped into the + * segment's `seconds`. A gap that rounds to nothing is dropped; two that + * round to touching are one. (One that reaches a snapped edge -- the writer + * keeps GAP_LIMITS.keep from the cut's, and no edge snaps across a gap -- + * simply ends or starts the segment's footage there.) + * + * @param {Array<{ from: number, to: number }>} gaps source seconds + * @param {number} segStart source second of the segment's first frame + * @param {number} seconds the segment's length before the gaps + * @param {number} fps + * @returns {Array<{ from: number, to: number }>} + */ +export function gapsOnSegment(gaps, segStart, seconds, fps) { + const f = fps > 0 ? fps : 30; + const frame = (t) => Math.round(t * f) / f; + const out = []; + for (const g of gaps ?? []) { + const a = frame(Math.max(0, g.from - segStart)); + const b = frame(Math.min(seconds, g.to - segStart)); + if (b - a < 1 / f - EPS) continue; + const last = out[out.length - 1]; + if (last && a - last.to < 1 / f - EPS) { + last.to = Number(Math.max(last.to, b).toFixed(6)); + continue; + } + out.push({ from: Number(a.toFixed(6)), to: Number(b.toFixed(6)) }); + } + // Nothing left to play is not a segment: the gaps do not apply. + return gapSeconds(out) >= seconds - 1 / f + EPS ? [] : out; +} + +const n3 = (v) => Number(v.toFixed(6)).toString(); + +/** + * The filtergraph that takes a segment's gaps out (`gaps` on its own clock, + * gapsOnSegment's): the picture trimmed into its kept pieces and joined with + * hard cuts, the sound cut at the same instants with a GAP_FADE out and in at + * each join, so nothing clicks. Picture and sound come out the same length -- + * the kept seconds -- and every later filter reads `v` / `a` in place of the + * input's streams. Either input may be null (a clip with no picture: the + * poster stands in; no sound: none). Empty `parts` without gaps. + * + * @param {{ gaps: Array<{ from: number, to: number }>, seconds: number, vIn?: string | null, aIn?: string | null, + * vOut?: string, aOut?: string, fade?: number }} o + * @returns {{ parts: string[], v: string | null, a: string | null }} + */ +export function gapFilterParts({ gaps, seconds, vIn = "[0:v]", aIn = "[0:a]", vOut = "[gv]", aOut = "[ga]", fade = GAP_FADE }) { + if (!gaps?.length) return { parts: [], v: vIn, a: aIn }; + const pieces = keptSpans(0, seconds, gaps); + const K = pieces.length; + const parts = []; + if (vIn) { + const outs = pieces.map((_, k) => `[gvs${k}]`); + parts.push(`${vIn}split=${K}${outs.join("")}`); + pieces.forEach((p, k) => { + parts.push(`${outs[k]}trim=start=${n3(p.from)}:end=${n3(p.to)},setpts=PTS-STARTPTS[gvp${k}]`); + }); + parts.push(`${pieces.map((_, k) => `[gvp${k}]`).join("")}concat=n=${K}:v=1:a=0${vOut}`); + } + if (aIn) { + const outs = pieces.map((_, k) => `[gas${k}]`); + parts.push(`${aIn}asplit=${K}${outs.join("")}`); + pieces.forEach((p, k) => { + const len = p.to - p.from; + const d = Math.min(fade, len / 2); + const f = [`atrim=start=${n3(p.from)}:end=${n3(p.to)}`, "asetpts=PTS-STARTPTS"]; + // Only at a join: the segment's own edges are the crossfade's and room's. + if (k > 0) f.push(`afade=t=in:st=0:d=${n3(d)}`); + if (k < K - 1) f.push(`afade=t=out:st=${n3(Math.max(0, len - d))}:d=${n3(d)}`); + parts.push(`${outs[k]}${f.join(",")}[gap${k}]`); + }); + parts.push(`${pieces.map((_, k) => `[gap${k}]`).join("")}concat=n=${K}:v=0:a=1${aOut}`); + } + return { parts, v: vIn ? vOut : null, a: aIn ? aOut : null }; +} + +/** + * The gaps of a clip that a cut record (`<id>.cut.json`) says its segment + * left out -- source seconds -- or [] (none, or a record from before gaps). + */ +export function recordGaps(record) { + const g = record?.gaps; + if (!Array.isArray(g)) return []; + return g.filter((x) => isObj(x) && fin(x.from) && fin(x.to) && x.to > x.from); +} + +/** + * Edit a clip's gaps list, as the CLI and the clip editor ask: `add` a span + * (merged with any gap it touches or overlaps), `remove` the gap holding a + * source second (or starting nearest it, within `tolerance`), or `set` the + * whole list (`[]` clears it). Returns the new list, normalized; the caller + * validates it on the entry. + * + * @param {Array<{ from: number, to: number }>} gaps the clip's now + * @param {{ add?: { from: number, to: number }, remove?: number, set?: Array<{ from: number, to: number }> }} op + * @param {{ tolerance?: number }} [opts] + */ +export function editGaps(gaps, op, { tolerance = 0.05 } = {}) { + if (op.set !== undefined) return normalizeGaps(op.set); + let list = [...(gaps ?? [])].sort((a, b) => a.from - b.from); + if (op.add) { + let { from, to } = op.add; + if (!(fin(from) && fin(to)) || to <= from) throw new Error(`a gap needs from < to in source seconds (got ${from}–${to})`); + // A span that touches or overlaps a gap grows it: two gaps a hair apart are one cut. + const keepList = []; + for (const g of list) { + if (g.to >= from - EPS && g.from <= to + EPS) { + from = Math.min(from, g.from); + to = Math.max(to, g.to); + } else keepList.push(g); + } + list = [...keepList, { from, to }]; + } + if (op.remove !== undefined) { + const t = Number(op.remove); + if (!fin(t)) throw new Error(`which gap? a source second inside it (got ${op.remove})`); + const k = list.findIndex((g) => t >= g.from - tolerance && t <= g.to + tolerance); + if (k < 0) throw new Error(`no gap at ${t}${list.length ? ` (gaps: ${list.map((g) => `${g.from}–${g.to}`).join(", ")})` : " — the clip has none"}`); + list = list.filter((_, i) => i !== k); + } + return normalizeGaps(list); +} + +/** `12.3-15.1` (or `12.3–15.1`, `12.3..15.1`) as a gap; null when it is not one. */ +export function parseGapSpec(text) { + const m = String(text ?? "").trim().match(/^(\d+(?:\.\d+)?)\s*(?:-|–|\.\.)\s*(\d+(?:\.\d+)?)$/); + if (!m) return null; + const from = Number(m[1]); + const to = Number(m[2]); + return fin(from) && fin(to) && to > from ? { from, to } : null; +} + +/** A clip's gaps in words, for a listing: `−12.30–15.10, −20.00–20.50` ("" without any). */ +export function gapsText(entry) { + return gapsOf(entry).map((g) => `−${g.from.toFixed(2)}–${g.to.toFixed(2)}`).join(", "); +} diff --git a/umtool/report-to-video/gaps.test.mjs b/umtool/report-to-video/gaps.test.mjs @@ -0,0 +1,209 @@ +// Gaps inside a clip (gaps.mjs): the rule a clip's `gaps` keep, the two clocks +// (source ↔ the gapped segment), the pieces that play, the frame grid, the +// edits the CLI and the bench ask for, and the filtergraph that takes them out +// -- the strings, and a real ffmpeg run on a synthetic clip: the picture and +// the sound come out the kept seconds long, the gap's black and silence gone. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + GAP_FADE, GAP_LIMITS, editGaps, gapFilterParts, gapSeconds, gappedLength, gapsOf, gapsOnSegment, gapsText, gapsWithin, + inGap, keptSpans, normalizeGaps, offsetIn, parseGapSpec, recordGaps, renderGaps, sourceAtOffset, validateGapEntries, validateGaps, +} from "./gaps.mjs"; + +const CLIP = { type: "clip", id: "c1", video: "v", start: 100, end: 120, cutStart: 102, cutEnd: 118 }; +const G = [{ from: 105, to: 107 }, { from: 110, to: 110.5 }]; + +// ---- validation ------------------------------------------------------------- + +test("validateGaps: absent, null or [] is none; a list inside the cut, apart and long enough is fine", () => { + assert.deepEqual(validateGaps(CLIP), []); + assert.deepEqual(validateGaps({ ...CLIP, gaps: null }), []); + assert.deepEqual(validateGaps({ ...CLIP, gaps: [] }), []); + assert.deepEqual(validateGaps({ ...CLIP, gaps: G }), []); + // No cut: the extent is the span. + const { cutStart: _a, cutEnd: _b, ...noCut } = CLIP; + assert.deepEqual(validateGaps({ ...noCut, gaps: [{ from: 100.5, to: 101 }] }), []); + assert.match(validateGaps({ ...CLIP, gaps: [{ from: 100.5, to: 101 }] })[0], /outside the clip's cut 102–118/); +}); + +test("validateGaps: each refusal names what is wrong", () => { + const one = (gaps, extra = {}) => validateGaps({ ...CLIP, ...extra, gaps }); + assert.match(one({ from: 105, to: 106 })[0], /must be a list/); + assert.match(one([{ from: 105 }])[0], /gaps\[0\] must be \{ from, to \}/); + assert.match(one([{ from: 105, to: 105.1 }])[0], /under 0.2 s/); + assert.match(one([{ from: 110, to: 111 }, { from: 105, to: 106 }])[0], /in order/); + assert.match(one([{ from: 105, to: 107 }, { from: 106.5, to: 108 }])[0], /overlaps gaps\[0\]/); + assert.match(one([{ from: 105, to: 107 }, { from: 107.2, to: 108 }])[0], /leaves 0.20 s after gaps\[0\]; keep at least 0.5 s/); + assert.match(one([{ from: 102.3, to: 103 }])[0], /after the cut's start/); + assert.match(one([{ from: 117, to: 117.8 }])[0], /before the cut's end/); + assert.match(one([{ from: 117, to: 119 }])[0], /outside the clip's cut/); + const many = Array.from({ length: 13 }, (_, k) => ({ from: 100 + k * 1.5, to: 100.3 + k * 1.5 })); + assert.match(validateGaps({ ...CLIP, start: 0, end: 200, cutStart: 99, cutEnd: 130, gaps: many })[0], /at most 12 gaps/); + assert.match(validateGaps({ type: "card", id: "k", gaps: G })[0], /only a clip/); +}); + +test("validateGaps: a mute mark or a claim mark strictly inside a gap is refused; on its edge it is fine", () => { + assert.match(validateGaps({ ...CLIP, gaps: G, muteFrom: 106 })[0], /muteFrom 106 lies inside the gap 105–107/); + assert.deepEqual(validateGaps({ ...CLIP, gaps: G, muteFrom: 107 }), [], "at the gap's end: the join"); + assert.deepEqual(validateGaps({ ...CLIP, gaps: G, muteFrom: 105 }), [], "at its start"); + assert.match(validateGaps({ ...CLIP, gaps: G, claim: { id: "k1", verdict: "FALSE", at: 110.2 } })[0], /the mark k1's second \(at 110.2\) lies inside the gap 110–110.5/); + assert.match(validateGaps({ ...CLIP, gaps: G, claims: [{ id: "a", verdict: "FALSE", at: 103 }, { id: "b", verdict: "FALSE", at: 106 }] })[0], /mark b's/); + assert.deepEqual(validateGaps({ ...CLIP, gaps: G, claim: { id: "k1", verdict: "FALSE", at: 108 } }), []); +}); + +test("validateGapEntries: every clip of the timeline, named by index", () => { + const errs = validateGapEntries({ timeline: [CLIP, { ...CLIP, id: "c2", gaps: [{ from: 1, to: 2 }] }] }); + assert.equal(errs.length, 1); + assert.match(errs[0], /^timeline\[1\] \(c2\)\.gaps\[0\]/); +}); + +// ---- the clocks --------------------------------------------------------------- + +test("offsetIn / sourceAtOffset: the seconds that play; without gaps the subtraction it always was", () => { + // Byte for byte: no gaps is `src - from`, and its inverse `from + off`. + for (const [src, from] of [[105.37, 101.6], [0.1 + 0.2, 0.1], [32989.123, 32986.1]]) { + assert.equal(offsetIn(src, from, []), src - from); + assert.equal(offsetIn(src, from, null), src - from); + assert.equal(sourceAtOffset(src - from, from, undefined), from + (src - from)); + } + const from = 101.6; + assert.equal(offsetIn(104, from, G), 104 - from); + assert.ok(Math.abs(offsetIn(108, from, G) - (108 - from - 2)) < 1e-9, "after the first gap: 2 s earlier"); + assert.ok(Math.abs(offsetIn(106, from, G) - (105 - from)) < 1e-9, "inside a gap: at its join"); + assert.ok(Math.abs(offsetIn(112, from, G) - (112 - from - 2.5)) < 1e-9, "after both"); + // The inverse lands after each gap, and round-trips every second that plays. + assert.ok(Math.abs(sourceAtOffset(105 - from, from, G) - 107) < 1e-9, "the join shows the material after the gap"); + for (const src of [101.6, 103, 104.99, 107, 109.3, 110.5, 115]) { + assert.ok(Math.abs(sourceAtOffset(offsetIn(src, from, G), from, G) - src) < 1e-9, `round trip ${src}`); + } +}); + +test("keptSpans, gappedLength, gapSeconds, gapsWithin", () => { + assert.deepEqual(keptSpans(102, 118, []), [{ from: 102, to: 118 }]); + assert.deepEqual(keptSpans(102, 118, G), [{ from: 102, to: 105 }, { from: 107, to: 110 }, { from: 110.5, to: 118 }]); + assert.equal(gappedLength(102, 118, []), 16); + assert.equal(gappedLength(102, 118, G), 13.5); + assert.equal(gapSeconds(G), 2.5); + assert.equal(gapSeconds(G, 106, 120), 1.5); + // A snapped edge that moved into a gap clips it; one past it drops it. + assert.deepEqual(gapsWithin(G, 106, 110.2), [{ from: 106, to: 107 }, { from: 110, to: 110.2 }]); + assert.deepEqual(gapsWithin(G, 108, 118), [{ from: 110, to: 110.5 }]); + assert.equal(inGap(106, G), G[0]); + assert.equal(inGap(105, G), null); +}); + +test("gapsOf / renderGaps / recordGaps: the well-formed ones, sorted; none in a montage", () => { + assert.deepEqual(gapsOf({ ...CLIP, gaps: [G[1], G[0], { from: 1 }] }), G); + assert.deepEqual(gapsOf(CLIP), []); + assert.deepEqual(renderGaps({ ...CLIP, gaps: G }, {}), G); + assert.deepEqual(renderGaps({ ...CLIP, gaps: G }, { montage: { style: "wall" } }), []); + assert.deepEqual(recordGaps({ start: 1, end: 2 }), []); + assert.deepEqual(recordGaps({ gaps: G }), G); +}); + +test("gapsOnSegment: on the segment's clock, on the frame grid, clipped", () => { + // The segment starts at 101.6 (the lead-in before 102) and runs 16.4 s. + const g = gapsOnSegment(G, 101.6, 16.4, 30); + assert.deepEqual(g.map((x) => [Math.round(x.from * 30), Math.round(x.to * 30)]), [[102, 162], [252, 267]]); + for (const x of g) { + assert.ok(Math.abs(x.from * 30 - Math.round(x.from * 30)) < 1e-6 && Math.abs(x.to * 30 - Math.round(x.to * 30)) < 1e-6, "whole frames"); + } + // A gap past the segment's end is dropped; one cut into is clipped. + assert.deepEqual(gapsOnSegment([{ from: 105, to: 107 }], 101.6, 4, 30).map((x) => [Math.round(x.from * 30), Math.round(x.to * 30)]), [[102, 120]], "cut into by the end: clipped"); + assert.deepEqual(gapsOnSegment([{ from: 105, to: 107 }], 108, 4, 30), []); +}); + +// ---- the edits ---------------------------------------------------------------- + +test("editGaps: add (merging what it touches), remove by a second inside, set; parseGapSpec; gapsText", () => { + assert.deepEqual(editGaps([], { add: { from: 105, to: 106 } }), [{ from: 105, to: 106 }]); + assert.deepEqual(editGaps([{ from: 105, to: 106 }], { add: { from: 105.5, to: 107 } }), [{ from: 105, to: 107 }]); + assert.deepEqual(editGaps([{ from: 110, to: 111 }], { add: { from: 105.004, to: 106.006 } }), [{ from: 105, to: 106.01 }, { from: 110, to: 111 }]); + assert.deepEqual(editGaps(G, { remove: 106.2 }), [G[1]]); + assert.throws(() => editGaps(G, { remove: 108 }), /no gap at 108 \(gaps: 105–107, 110–110.5\)/); + assert.throws(() => editGaps([], { add: { from: 3, to: 2 } }), /from < to/); + assert.deepEqual(editGaps(G, { set: [] }), []); + assert.deepEqual(normalizeGaps([{ from: 110.004, to: 111 }, { from: 105, to: 106.333 }]), [{ from: 105, to: 106.33 }, { from: 110, to: 111 }]); + assert.deepEqual(parseGapSpec("12.3-15.1"), { from: 12.3, to: 15.1 }); + assert.deepEqual(parseGapSpec(" 12.3 – 15.1 "), { from: 12.3, to: 15.1 }); + assert.deepEqual(parseGapSpec("12..13"), { from: 12, to: 13 }); + assert.equal(parseGapSpec("15-12"), null); + assert.equal(parseGapSpec("12"), null); + assert.equal(gapsText({ ...CLIP, gaps: G }), "−105.00–107.00, −110.00–110.50"); + assert.equal(GAP_LIMITS.min, 0.2); +}); + +// ---- the filtergraph ------------------------------------------------------------ + +test("gapFilterParts: nothing without gaps; trim + concat with a fade at each join with", () => { + assert.deepEqual(gapFilterParts({ gaps: [], seconds: 10 }), { parts: [], v: "[0:v]", a: "[0:a]" }); + assert.deepEqual(gapFilterParts({ gaps: [], seconds: 10, aIn: "[2:a]" }), { parts: [], v: "[0:v]", a: "[2:a]" }); + const g = gapFilterParts({ gaps: [{ from: 2, to: 3 }], seconds: 10 }); + assert.equal(g.v, "[gv]"); + assert.equal(g.a, "[ga]"); + assert.deepEqual(g.parts, [ + "[0:v]split=2[gvs0][gvs1]", + "[gvs0]trim=start=0:end=2,setpts=PTS-STARTPTS[gvp0]", + "[gvs1]trim=start=3:end=10,setpts=PTS-STARTPTS[gvp1]", + "[gvp0][gvp1]concat=n=2:v=1:a=0[gv]", + "[0:a]asplit=2[gas0][gas1]", + `[gas0]atrim=start=0:end=2,asetpts=PTS-STARTPTS,afade=t=out:st=${2 - GAP_FADE}:d=${GAP_FADE}[gap0]`, + `[gas1]atrim=start=3:end=10,asetpts=PTS-STARTPTS,afade=t=in:st=0:d=${GAP_FADE}[gap1]`, + "[gap0][gap1]concat=n=2:v=0:a=1[ga]", + ]); + // No picture (a poster stands in): the sound alone. + const a = gapFilterParts({ gaps: [{ from: 2, to: 3 }], seconds: 10, vIn: null }); + assert.equal(a.v, null); + assert.ok(a.parts.every((p) => !p.includes("[0:v]"))); +}); + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); + +test("gapFilterParts on a real clip: the kept seconds, the gap's black and silence gone, picture and sound one length", { skip: !have && "needs ffmpeg" }, () => { + const dir = mkdtempSync(path.join(os.tmpdir(), "gaps-graph-")); + try { + const src = path.join(dir, "src.mp4"); + // 6 s of grey picture and a tone; black and silent over 2-3 s (the gap to take out). + let r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=160x90:r=30:d=6", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=6", + "-filter_complex", "[0:v]drawbox=c=black:t=fill:enable='between(t,2,2.99)'[v];[1:a]volume=enable='between(t,2,2.99)':volume=0[a]", + "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", src, + ]); + assert.equal(r.status, 0, String(r.stderr)); + const out = path.join(dir, "out.mp4"); + const g = gapFilterParts({ gaps: gapsOnSegment([{ from: 2, to: 3 }], 0, 6, 30), seconds: 6 }); + r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-ss", "0", "-to", "6", "-i", src, "-filter_complex", g.parts.join(";"), + "-map", g.v, "-map", g.a, "-c:v", "libx264", "-preset", "ultrafast", "-r", "30", "-c:a", "aac", "-ar", "48000", out, + ]); + assert.equal(r.status, 0, String(r.stderr)); + const probe = (sel) => Number(spawnSync("ffprobe", ["-v", "error", "-select_streams", sel, "-show_entries", "stream=duration", "-of", "csv=p=0", out]).stdout.toString().trim()); + assert.ok(Math.abs(probe("v:0") - 5) <= 1 / 30 + 1e-3, `picture ${probe("v:0")}`); + assert.ok(Math.abs(probe("a:0") - 5) <= 0.03, `sound ${probe("a:0")}`); + // No black frame left: the darkest frame is the grey. + const st = spawnSync("ffmpeg", ["-v", "error", "-i", out, "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"]); + const yavg = st.stdout.toString().split("\n").filter((l) => l.includes("YAVG")).map((l) => Number(l.split("=")[1])); + assert.ok(yavg.length >= 149, `frames ${yavg.length}`); + assert.ok(Math.min(...yavg) > 60, `no black frame: min YAVG ${Math.min(...yavg)}`); + // No silence left either: every 100 ms but the join's own fades is loud. + const pcmR = spawnSync("ffmpeg", ["-v", "error", "-i", out, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 24 }); + const pcm = new Int16Array(pcmR.stdout.buffer, pcmR.stdout.byteOffset, Math.floor(pcmR.stdout.length / 2)); + for (let k = 1; k < 48; k += 1) { + const a = k * 800; + let sum = 0; + for (let i = a; i < a + 800 && i < pcm.length; i += 1) sum += pcm[i] * pcm[i]; + const rms = Math.sqrt(sum / 800); + assert.ok(rms > 1000, `loud at ${(k / 10).toFixed(1)} s: ${rms.toFixed(0)}`); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/heavy-gate.test.mjs b/umtool/report-to-video/heavy-gate.test.mjs @@ -119,6 +119,9 @@ test("with no HEAVY_LOCK_FILE the lock is pinned to the checkout's git common di execFileSync("git", ["init", "-q", repo]); mkdirSync(path.join(repo, "scripts")); copyFileSync(path.join(checkoutRoot(), "scripts", "queue-lock.mjs"), path.join(repo, "scripts", "queue-lock.mjs")); + // ...and render mode's state module, which the gate imports. + mkdirSync(path.join(repo, "common", "lib"), { recursive: true }); + copyFileSync(path.join(checkoutRoot(), "common", "lib", "renderPriority.mjs"), path.join(repo, "common", "lib", "renderPriority.mjs")); const lock = path.join(repo, ".git", "heavy-queue.lock"); const seen = await withEnv( { HEAVY: undefined, HEAVY_HELD: undefined, HEAVY_LOCK_FILE: undefined, HEAVY_MIN_FREE_MB: "0" }, diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -83,6 +83,7 @@ import { import { validateClaims } from "./factcheck.mjs"; import { validateClipAudioEntries } from "./clip-audio.mjs"; import { validateClipBlurEntries } from "./clip-blur.mjs"; +import { validateGapEntries } from "./gaps.mjs"; import { validateFinaleEntries } from "./finale.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -308,6 +309,8 @@ export function validatorErrors(whole) { ...validateFinaleEntries(whole), // A clip's blurred picture and the cut's render.blur (clip-blur.mjs). ...validateClipBlurEntries(whole), + // Seconds taken out of a clip's middle (gaps.mjs). + ...validateGapEntries(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/mute.mjs b/umtool/report-to-video/mute.mjs @@ -1,9 +1,11 @@ -// The mute mark's fade, and where a clip's sound is heard, alone: no imports, +// The mute mark's fade, and where a clip's sound is heard, alone: no imports but gaps.mjs (none of its own), // so a client bundle (umtool's clip bench previews the mute as the build makes // it; Play the cut's schedule) can take it without pulling in deck.mjs and // what deck.mjs imports (node:crypto, attribution). deck.mjs re-exports it; // the build, the cut-points route and Play the cut read the same numbers. +import { offsetIn } from "./gaps.mjs"; + /** The fade into a `muteFrom`'s silence, in seconds: long enough not to click, short enough to keep the next word out. */ export const MUTE_FADE = 0.04; @@ -94,15 +96,18 @@ export function soundEdges(entry, render = {}) { * reach before. The clip's own `muteFrom` is placed wherever it falls, as it * always was. The build's joins (deck.mjs segmentSoundEdits, from the cut * record) and the cut-points route (from the cut it computes) both call this. + * `gaps` (source seconds, gaps.mjs): the seconds the segment leaves out, so a + * mark after one lands that much earlier on its clock. * * @param {Record<string, any>} entry * @param {Record<string, any>} render * @param {number} segStart * @param {number} seconds + * @param {Array<{ from: number, to: number }> | null} [gaps] */ -export function soundOnSegment(entry, render, segStart, seconds) { +export function soundOnSegment(entry, render, segStart, seconds, gaps = null) { const se = soundEdges(entry, render); - const at = (src) => Math.max(0, Math.round((src - segStart) * 1000) / 1000); + const at = (src) => Math.max(0, Math.round(offsetIn(src, segStart, gaps) * 1000) / 1000); let mute = null; let soundFrom = null; if (se.muteFrom != null) { diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -36,6 +36,7 @@ "./finale": "./finale.mjs", "./frames-cut": "./frames-cut.mjs", "./fx": "./fx.mjs", + "./gaps": "./gaps.mjs", "./ladder-chunks": "./ladder-chunks.mjs", "./ledger-totals": "./ledger-totals.mjs", "./montage": "./montage.mjs", diff --git a/umtool/report-to-video/snap.mjs b/umtool/report-to-video/snap.mjs @@ -12,6 +12,8 @@ // the clock the build snaps on, and the same float arithmetic on the same // clock is what makes the route's edges the build's to the millisecond. +import { GAP_LIMITS } from "./gaps.mjs"; + /** The render's defaults for the snap knobs (render.snapWindow, snapLead, snapTail, silence*). */ export const SNAP_DEFAULTS = Object.freeze({ snapWindow: 1.6, @@ -73,20 +75,35 @@ export function snap(desired, intervals, kind, window, render = {}, { pinned = f } /** + * How close (seconds) a snapped edge may come to a clip's gap: the writer's + * own rule for the material kept beside one (gaps.mjs GAP_LIMITS.keep). + */ +export const GAP_KEEP = GAP_LIMITS.keep; + +/** * A clip's two edges as the render cuts them: each snapped (`snap`), then * never inverted or collapsed -- the start at least a second before the * desired end, the end at least a second after the start. * * @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any>, - * locked?: { start?: boolean, end?: boolean } | null }} o + * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o * `wantA`/`wantB`: the play window's edges in the file's seconds; `locked`: * which of them are the author's, exact (mute.mjs lockedEdges) -- each - * snapped only outward, inside its own silence + * snapped only outward, inside its own silence; `gaps`: the clip's gaps + * (gaps.mjs) in the file's seconds -- a gap's edges are exact, so neither + * edge snaps across one (nor nearer it than GAP_KEEP): such a snap is not + * taken and the edge stays where it was asked */ -export function snapCut({ sil, wantA, wantB, render = {}, locked = null }) { +export function snapCut({ sil, wantA, wantB, render = {}, locked = null, gaps = null }) { const win = render.snapWindow ?? SNAP_DEFAULTS.snapWindow; - const a = snap(wantA, sil, "start", win, render, { pinned: !!locked?.start }); - const b = snap(wantB, sil, "end", win, render, { pinned: !!locked?.end }); + let a = snap(wantA, sil, "start", win, render, { pinned: !!locked?.start }); + let b = snap(wantB, sil, "end", win, render, { pinned: !!locked?.end }); + if (gaps?.length) { + const first = gaps.reduce((m, g) => Math.min(m, g.from), Infinity); + const last = gaps.reduce((m, g) => Math.max(m, g.to), -Infinity); + if (a.at > wantA && a.at > first - GAP_KEEP) a = { at: wantA, snapped: false }; + if (b.at < wantB && b.at < last + GAP_KEEP) b = { at: wantB, snapped: false }; + } const cutA = Math.min(a.at, wantB - 1); const cutB = Math.max(b.at, cutA + 1); return { win, a, b, cutA, cutB }; @@ -100,13 +117,16 @@ export const recordSecond = (fetchStart, t) => Number((fetchStart + t).toFixed(3 * file it is cut from: what `<id>.cut.json` records (`start`, `end`, * `snapped`) for a clip with no room and no montage. `playFrom`/`playTo` are * the play window (deck.mjs playWindow); `fetchStart` the file's first - * second in the recording. + * second in the recording; `gaps` the clip's (gaps.mjs), source seconds. * * @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any>, - * locked?: { start?: boolean, end?: boolean } | null }} o + * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o */ -export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null }) { - const c = snapCut({ sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render, locked }); +export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null, gaps = null }) { + const c = snapCut({ + sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render, locked, + ...(gaps?.length ? { gaps: gaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), + }); return { start: recordSecond(fetchStart, c.cutA), end: recordSecond(fetchStart, c.cutB), diff --git a/umtool/report-to-video/stats.mjs b/umtool/report-to-video/stats.mjs @@ -16,6 +16,7 @@ // ffmpeg. deck.mjs imports this file -- never the other way round. import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; +import { offsetIn, sourceAtOffset } from "./gaps.mjs"; /** Where the stats sit in the footage box. */ export const STATS_POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]); @@ -171,11 +172,13 @@ export function statsSchedule({ segments, D, total, render }) { const lo = s.start + (i > 0 ? D / 2 : 0); const hi = next ? next.start + D / 2 : total; if (!(hi > lo)) return; - const end = s.sourceFrom + (hi - s.start); - const states = [{ at: r3(lo), values: valuesAt(s.points, s.sourceFrom + (lo - s.start), cfg.fields) }]; + // A segment with gaps (gaps.mjs, source seconds): its clock counts only what plays. + const end = sourceAtOffset(hi - s.start, s.sourceFrom, s.gaps); + const first = sourceAtOffset(lo - s.start, s.sourceFrom, s.gaps); + const states = [{ at: r3(lo), values: valuesAt(s.points, first, cfg.fields) }]; for (const p of s.points) { - if (p.at <= s.sourceFrom + (lo - s.start) || p.at >= end) continue; - const at = r3(s.start + (p.at - s.sourceFrom)); + if (p.at <= first || p.at >= end) continue; + const at = r3(s.start + offsetIn(p.at, s.sourceFrom, s.gaps)); const values = valuesAt(s.points, p.at, cfg.fields); const last = states[states.length - 1]; if (cfg.fields.every((f) => last.values[f] === values[f])) continue; diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -53,6 +53,7 @@ import path from "node:path"; import { promisify } from "node:util"; import { encodeArgs } from "./build-video.mjs"; +import { offsetIn, recordGaps } from "./gaps.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -195,7 +196,19 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = } const s = Math.max(beat.start, rec.start); const e = Math.min(beat.end, rec.end); - want.push({ kind: "clip", id: beat.id, beat, rec, seg, a: seg.start + (s - rec.start), b: seg.start + (e - rec.start) }); + // A clip with gaps (gaps.mjs; the record's, as its segment left them out): + // a beat across one plays the master's jump cut, and is that much shorter; + // an edge inside one lands on its join. + const gaps = recordGaps(rec); + const a = seg.start + offsetIn(s, rec.start, gaps); + const b = seg.start + offsetIn(e, rec.start, gaps); + if (gaps.length && b - a < 0.2) { + throw new TrailerError(`beat ${n + 1}: ${beat.id} ${beat.start}–${beat.end} lies inside the clip's gaps — nothing of it plays in the master`); + } + if (gaps.some((g) => g.from < e && g.to > s)) { + notes.push(`beat ${n + 1}: ${beat.id} ${beat.start}–${beat.end} spans a gap — it plays the master's jump cut (${fmt(b - a)} s)`); + } + want.push({ kind: "clip", id: beat.id, beat, rec, seg, a, b }); }); if (finale != null) { if (!Number.isFinite(finale) || finale <= 0) throw new TrailerError(`--finale ${finale}: seconds > 0`);