Archilyzer · Source

archilyzer

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

commit a0732b20c03a073f1bc83428b385b2d1f256075a
parent 3ac23a385d51d4c22009f8f33313aa3f4942d7cb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 16:12:26 -0400

Merge r36/blur-slide: room at the clip edges (render.room — sound to the first silence, a muted picture tail/head for the join), the site-less look's blur slide

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

# Conflicts:
#	editor/CHANGELOG.md
#	plans/FACTS.md

Diffstat:
Meditor/CHANGELOG.md | 2++
Mplans/FACTS.md | 39+++++++++++++++++++++++++++++++++++++++
Aplans/release-36/clip-edges.md | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/LookPanel.tsx | 24+++++++++++++++++++++++-
Mumtool/components/projects/review/ClipEditor.tsx | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/e2e/clip-look.spec.ts | 26++++++++++++++++++++++----
Mumtool/e2e/create.spec.ts | 2+-
Mumtool/lib/projects/scaffold.mjs | 19++++++++++++-------
Mumtool/lib/report/clipEditor.mjs | 46++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/clipEditorTypes.ts | 5+++++
Mumtool/lib/report/look.test.mjs | 2+-
Mumtool/lib/report/manifest.mjs | 21+++++++++++++++++++--
Mumtool/lib/report/reactions-r36.test.mjs | 4++--
Aumtool/lib/report/room.test.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 136++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/report-to-video/lint.mjs | 3+++
Mumtool/report-to-video/look.mjs | 5++++-
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/room-render.test.mjs | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/room.mjs | 283+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/room.test.mjs | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
22 files changed, 1236 insertions(+), 37 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -3,6 +3,8 @@ ## [Unreleased] - **The clip editor can ask an assistant to label and rank the clip finder's proposals — optionally.** A **Suggest** button in the clip editor's side column asks the model your generation settings choose (the local model, the Claude API, or a Claude Code session through `/gen`) to name each proposal in at most six words, say in one line what makes it land, and rank them; the labels show on every clip and unused proposal, and **Sort by the assistant's rank** orders both lists by them. Labels made before the clips were proposed again are marked stale, not hidden. Nothing in the cut changes: the labels are suggestions. Without a model, or with no labels, the clip editor works as before. From a shell: `pnpm ops report-draft '{"task":"clips-suggest","project":"<dir>","dryRun":true}'` shows how many proposals and what it would cost first. - **Ask the assistant about a clip, and apply what it suggests with one click.** On a comment in the clip editor, **Ask the assistant** has the model read your comment, the clip's words and the clips around it, and reply in the thread (badged "agent"). When it suggests a concrete edit — new edges, a merge with the next clip, or leaving the clip out — the reply shows an **Apply** button; nothing changes until you click it, and Apply does exactly what the clip editor's own buttons do. The editor needs `UMTOOL_URL` set to post the reply. +- **Room at a report video's clip edges: a join no longer eats the end of a sentence.** With `render.room` (the Build tab's Look panel: **Room at the clips' edges**, Tail and Head), each clip's sound runs on past its cut to the first pause in its words — never more than 2.5 s — and fades there, then its picture keeps going, muted, for the length of the join, so the transition plays over quiet video; the clip after it starts the same length early, muted, when its first word comes straight away, so that word is not faded in under the join either. The words come from the project's word timings, else the transcript, else the sound's own silences. Captions stop where the sound does, and even loudness measures only what is heard. A clip cut from a downloaded window has only as much room as the window holds (the check says so; a saved whole video has plenty). The clip editor shades each clip's muted tail and head on the strip and has **Room at its edges** to turn it off for one clip. Highlights of a channel on no site now start with it on, and with 0.4 s blur slides. A manifest without `render.room` renders exactly as before. Needs a restart of umtool. +- **A report video's clips can blur-slide into each other.** `render.transitionStyle: "blurslide"` (the Look panel's Join: **blur slide**) slides the next clip in from the left while both sides of the cut are smeared sideways and lightly grained, for the join's length. A dip, a THEN/NOW wipe and a whip keep their own look. - **Find clips: the clip finder from one button on the video page.** A video page's **Find clips** runs the whole chain umtool's clip finder needs, as one job: it saves the source video, transcribes the recording, makes its word timings (kept beside the transcript as `words.json`, so a second project from the same recording reuses them), fetches the stream's chat replay (YouTube), finds who speaks when, and then asks umtool to find the narrated-video segments and propose the clips. Each step whose output is already on disk is skipped, and the job's log says which ran and which were skipped. When it is done the panel links the umtool project and lists the segments it found, each with **Find clips in this part**. A target length can be given. When the workers are paused or the backfill lane is held, the step that needs them stops with a sentence saying so, and **Run while paused** runs this one video past them. The button is off, with a line saying why, when the editor has no `UMTOOL_URL`. The same from a terminal: `pnpm ops find-clips --json '{"slug","id"}'` (a `dryRun` lists what each step would do). Needs a restart of the editor. - **Transcribe one video while the workers are paused.** With the transcription workers paused, the video page's Transcribe row offers **Transcribe now (workers paused)**: that one transcription runs on a worker the pause alone switched off, and the pause stays on — the worker is paused again when it finishes. A worker you drained, disabled by hand or that is marked degraded is never used, and the lanes stay held. `pnpm ops transcribe` and `transcribe-one` take `"whilePaused": true`. - **Fetch a stream's chat replay on its own.** Media tools → **Fetch live chat** on a video page (`pnpm ops fetch-chat`) fetches the video's live chat and nothing else, paced like every YouTube request and on the platform's download queue, into the chat cues the index and the clip finder read. A video on another platform says there is no chat fetcher for it, as does a chat already fetched or a video that was never live. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10990,3 +10990,42 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **MCP `generate`**: task `clips-suggest` with `project` (no article); routed to code with no model/via/answers, it posts the plan (`dryRun`) and answers the request for the session to label; `answers` go straight to the editor (no policy read). Test kit: `common/testing/clips/reactionProject.mjs`. + +## Release 36 lane E: room at the clip edges, the blur slide (verified 2026-10-19, branch `r36/blur-slide`) + +- **`render.room`** `{tail?: boolean, head?: boolean, minGap?: 0.1–2 (0.35), maxS?: 0–10 (2.5)}`; clip **`room`** + `false | {tail?: boolean, head?: boolean}` (beats the cut's per edge; `false` = none). An edge is on iff its key is + `true` (`{}` = off). Absent / `null` / neither edge = byte-identical (md5, in-suite). `validateRoom` + (`umtool/report-to-video/room.mjs`, export `umtool-report-to-video/room`) is called by `validateLook`, so the build's + validators, the lint and `updateRender` all check it; refused beside `render.montage`. `LOOK_KEYS` gains `room`. +- **When it applies**: build-video sets `dirs.room = {D, first}` only when `D > 0` (not `--no-xfade`, not a montage, + `render.transition` not 0), not a `--short`, and some clip has `clipRoom(e, render)`; `dirs.look` is read for its + words. `first` = `manifest.timeline[0].id` (that clip gets no head). Deck cuts get it too. +- **The rule** (file seconds; `cutA/cutB` = the snapped cut): words from `lookWordsFor(entry, …, src(cutA) − 1, + src(cutB) + maxS + 1)` (words.json → transcript.json → cues). TAIL `tailFromWords`: first word with `end > cutB`; if it + starts ≥ `cutB + minGap` → `cutB`; else extend through words while the gap to the next < `minGap`; cap `cutB + maxS`. + Cues whose run is capped, or no words → `silencedetect=noise=-35dB:d=0.3` over [min(cutA, cutB) − 0.5, + min(dur, cutB + maxS + 0.5)] (an open silence runs to the span's end): in a silence → `cutB`; else the next silence + start within maxS; none → `cutB`. HEAD (not the first clip): speech start = first word with `end > cutA` + (`max(cutA, start)`), from silences the end of the one holding cutA; muted head iff speech < `cutA + D`. + `roomPlan`: `picA = cutA − D` (clamped ≥ 0), `soundB = max(cutB, tail)`, `picB = soundB + D + 0.1` (clamped to the + file's duration → `clamped: ["tail"]`). Audio, after any `levelFilters(gain)`: `afade=t=in:st=head−0.06:d=0.06`, + `afade=t=out:st=soundB−picA:d=0.06` (afade silences before an in / after an out). +- **The cut record**: `start/end` = the PICTURE's span (`fetchStart + picA/picB`; muteFrom maps from it as before) + + `room: {sound: [srcA, srcB], head, tail, via: "words.json"|"transcript.json"|"cues"|"cues+silence"|"silence", + capped?, clamped?}`. Loudness measures `[cutA, soundB]`; captions read words of `[src(cutA), src(soundB)]` and + `seconds = soundB − picA` (`segmentCaptions({audible})`). Joins, chapters and offsets come from probed segment + lengths, unchanged. +- **Lint** `roomWindowWarnings`: a clip whose `cutEnd + maxS + D + 0.1 > end + fetchPad` (or head before + `start − fetchPad`) is warned "a fetched source clamps it"; room with `transition: 0` is warned "room does nothing". +- **Seed** `SITELESS_LOOK` = `{headerHeight: 0, footerHeight: 0, qr: false, transition: 0.4, transitionStyle: + "blurslide", loudness: {target: -16}, room: {tail: true, head: true}}` (was 0.5 / fadeblack, no room). +- **Clip editor**: op `room {clip, room: false | {tail?, head?} | null}` (updateClip "trim" edit, cut untouched; null + deletes); view `clips[].room` (as written), `clips[].roomEdges` (`{tail, head}` or null), `room {tail, head, minGap, + maxS, join}` (join = render.transition ?? 0.5, 0 in a montage). The strip draws `[data-strip-room="head"|"tail"]` from + `roomShade` (the rule on the unsnapped cut; no words → nominal D + 0.1 tail); toggle `[data-clip-room]`. Look panel: + `[data-look-room-tail]`, `[data-look-room-head]`. +- **The blur slide** (`transitionStyle: "blurslide"`, orchestrator's commit a012e9ff): xfade `slideright`; each + segment's last/first D s (only at a plain join: not a dip, wipe or whip) get `gblur=sigma=10:sigmaV=0.6` over D, + `gblur=sigma=16:sigmaV=0.6` over the D/2 nearest the seam, `noise=alls=7:allf=t+u` over D (`BLUR_SLIDE`, + `blurSlideEdges`, `enable=` windows in the segment's own `t`). diff --git a/plans/release-36/clip-edges.md b/plans/release-36/clip-edges.md @@ -0,0 +1,95 @@ +# Release 36 lane E — `r36/blur-slide`: room at the clip edges, and the blur slide (as shipped) + +The operator, watching the first highlights cut: the edges are tight — a join fades over the end of one clip's last +sentence and the start of the next one's first. Ruled: the sound runs on to the first silence, and muted picture +carries the join. This lane makes that a render key, `render.room`, and records the blur slide (the orchestrator's +commit `a012e9ff`) that the site-less seed now starts with. Rulings followed: the UI works with no model (nothing here +calls one); every step a umtool surface (the Look panel, the clip editor's toggle and strip); absent keys render byte +for byte as before; deterministic code; synthetic fixtures only; the live project read only. + +## What + +1. **`render.room {tail?, head?, minGap? (0.35), maxS? (2.5)}`** and clip **`room: false | {tail?, head?}`** + (`umtool/report-to-video/room.mjs`, pure; `validateRoom` inside `validateLook`, so the build, the lint and + `updateRender` check it; refused beside a montage). An edge is on when its key is `true`; the clip's key beats the + cut's. +2. **The rule** (file seconds, on the snapped cut). TAIL: the sound runs to the end of the run of words that crosses + the cut's end or starts within `minGap` after it, stopping at the first gap ≥ `minGap`, never more than `maxS` + past it, a 60 ms fade there; the picture runs on muted for D + 0.1 s. HEAD (not the cut's first entry): when speech + starts within D of the cut's start the picture starts D earlier, muted, the sound fading in over the 60 ms before + the cut. Words: the project's words.json (the recording reactions.json describes) → corpus transcript.json → cues + (`lookWordsFor`, lane C's resolver); none, or a run of cues that reaches the cap → `silencedetect` −35 dB / 0.3 s on + the clip's source (in a silence → the cut's end; else the next silence within maxS; none → the cut's end, noted). +3. **In the build** (`segmentRoom`, `detectRoomSilences`, buildClipSegment): only with a join (D > 0, not a montage, + not a short); the segment is cut over the picture's span, clamped to the source file (a fetched window clamps, a + note says so; the lint's `roomWindowWarnings` warns when a clip's room can reach past `extent + fetchPad`); the + fades follow any loudness gain; loudness measures `[cut start, silence point]`; captions read only the words heard + and end at the silence point; the cut record's `start/end` are the picture's (muteFrom still maps) plus + `room {sound, head, tail, via, capped?, clamped?}`. Joins, chapters and offsets come from probed segment lengths + as before. +4. **umtool**: `LOOK_KEYS` + `room` (the Look panel's Room at the clips' edges: Tail, Head); `updateClip` takes + `room` (validated; null deletes); the clip editor's op `room {clip, room}` and view `clips[].room`, + `clips[].roomEdges`, `room {tail, head, minGap, maxS, join}`; the strip shades the muted head/tail + (`roomShade`, the rule on the unsnapped cut), a per-clip **Room at its edges** checkbox and a line saying where the + sound stops. Additive to lane D's clip-editor work: one new op, two view fields, one prop on Strip, one row. +5. **The seed**: `SITELESS_LOOK` = 0.4 s `blurslide` joins + `room {tail, head}` (was 0.5 s `fadeblack`). +6. **The blur slide, recorded** (`transition.mjs`, commit `a012e9ff`): `transitionStyle: "blurslide"` → xfade + `slideright`, and on each side of a plain join the segment's last/first D s get `gblur sigma 10 / sigmaV 0.6` over + D, `gblur sigma 16 / sigmaV 0.6` more over the D/2 nearest the seam (≈ 19 at the seam), `noise alls 7, allf t+u` + over D — `BLUR_SLIDE = {sigma: 10, seamSigma: 16, sigmaV: 0.6, noise: 7}`, in the clip's own time (batched joins + too); dips, wipes and whips keep their own look. + +## Files + +report-to-video: `room.mjs` (new), `room.test.mjs` (new, 12), `room-render.test.mjs` (new, 4), `build-video.mjs` +(imports, `segmentRoom`, `detectRoomSilences`, buildClipSegment's span/sound/captions, `segmentCaptions({audible})`, +`dirs.room`), `look.mjs` (validateLook calls validateRoom), `lint.mjs` (roomWindowWarnings), `package.json` +(`./room`). umtool: `lib/projects/scaffold.mjs` (SITELESS_LOOK), `lib/report/manifest.mjs` (LOOK_KEYS, updateClip +`room`), `lib/report/clipEditor.mjs` (view + op), `lib/report/clipEditorTypes.ts`, `lib/report/room.test.mjs` (new, 4), +`lib/report/look.test.mjs` + `lib/report/reactions-r36.test.mjs` (the new key and seed), `components/projects/review/ +ClipEditor.tsx`, `components/projects/report/LookPanel.tsx`, `e2e/clip-look.spec.ts` (room in the panel and the +editor), `e2e/create.spec.ts` (the seed's look), `docs/report-video.md` ("Room at the clips' edges, and the blur +slide"). `plans/FACTS.md` ("Release 36 lane E"), `editor/CHANGELOG.md`. + +## Commits + +| sha | what | +|---|---| +| `8d503692` | report-to-video: render.room — room.mjs, the build, the lint; 16 tests | +| `21473c70` | umtool: the Look panel's room, a clip's override, the strip's shading, the seed; 4 tests; e2e specs | +| `182dc04b` | docs, FACTS, CHANGELOG | +| `7d801566` | umtool: the clip room toggle shows the choice at once | +| (this) | plans: this record | + +## Gates (through the session lock, from the worktree root) + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` — clean except one umtool JSDoc typing (fixed; + umtool's tsc then clean, and again after the last code commit). +- `pnpm run test:scripts` — **1310 tests, 1306 pass, 0 fail, 4 skipped** (branch start a012e9ff: 1289 / 1285 / 4; + +20 here — room 12, room-render 4, lib/report/room 4 — and +1 from main's lane A merge). +- `pnpm --filter umtool test` — 45 / 45 (unchanged). +- Render tests (real ffmpeg): the first clip's words run past its end to 4.75 → segment [1, 5.25] (4.25 s, ±1 frame), + heard (RMS > 1500) to the silence point, silent (< 30) after it; the second clip's muted head 0.4 s (silent before, + heard after its cut); the cut = sum − one join (±2 frames), the join silent, the second clip's sound on its picture; + loudness of the audible part −16 ± 0.6; the last caption ends by 3.75 s; no words → silencedetect found the 4.6 s + silence (±0.05) and the picture ran 0.5 s past it; a clip's `room: false` kept its cut. +- **Byte-identical without the key**: in-suite (absent, `null`, `{tail: false, head: false}`: final, both segments, + both cut records); and against main's build-video (`$T/r36e-bytecheck.mjs`, a two-clip blurslide 320×180 fixture with + loudness): final `06b3d852…`, segments `8e09b095…` / `5a9556ce…`, cut records `3bd732e2…` / `7150b74f…` — the same + both sides. +- e2e (umtool, `E2E_MODE=dev`): `clip-look.spec.ts` + `clip-editor.spec.ts` — first run 1 passed, 1 failed (the + controlled checkbox; fixed in `7d801566`), then **2 passed, 0 failed** (wall 51.8 s); `create.spec.ts` (the seed's + look) **13 passed** (wall 85.2 s). +- A trial on a copy of the first case's inputs (`--only r018`, room on, the saved full video, no network): words.json, + the sound ran 496.0 → 498.08 (the next word 0.4 s later), head 0.4 s, tail 0.5 s, segment 50.0 s, −16.1 LUFS. + The copy's output was deleted. + +## Found and left + +- The room extends the sound past the cut a person set (up to `maxS`): words they trimmed off can come back, ending + at the next pause. A clip's `room: false` (or `{tail: false}`) keeps the cut as set. +- The strip's shading is the rule on the cut as drawn; the build snaps the cut to a silence first, so the rendered + edge can differ by up to `snapWindow`. +- No room in a short (no join), a montage (refused) or with `transition: 0` (the lint says it does nothing). +- Detection with no words uses an absolute −35 dB floor; on loud game audio it can find no silence, and the sound + then stops at the cut (noted in the build log). diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx @@ -7,7 +7,8 @@ import { Panel } from "@/components/ui/panel"; // THE LOOK (release 36 lane C): the render keys a person sets for a cut with // no deck -- the header, the timeline footer, the QR, the crossfade's length -// and style, the loudness target, the speaker captions -- written through +// and style, the loudness target, the speaker captions, room at the clips' +// edges (release 36 lane E) -- written through // /api/report/render (lib/report/manifest.mjs updateRender, the build's own // checks). Nothing here calls a model. A deck cut keeps its own settings // (the Media tab); a montage levels with render.montage. @@ -20,6 +21,7 @@ type Look = { transitionStyle?: string; loudness?: { target: number } | null; captions?: { style: "speakers"; labels?: { host?: string | null; subject?: string | null } | null; size?: "m" | "l" } | null; + room?: { tail?: boolean; head?: boolean; minGap?: number; maxS?: number } | null; }; type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; errors: string[]; token: string | null }; @@ -37,6 +39,8 @@ type Draft = { host: string; subject: string; size: "m" | "l"; + roomTail: boolean; + roomHead: boolean; }; function draftOf(l: Look): Draft { @@ -53,6 +57,8 @@ function draftOf(l: Look): Draft { host: l.captions?.labels?.host ?? "", subject: l.captions?.labels?.subject ?? "", size: l.captions?.size ?? "m", + roomTail: l.room?.tail === true, + roomHead: l.room?.head === true, }; } @@ -74,6 +80,14 @@ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> { const next = d.captions ? { style: "speakers", ...(Object.keys(labels).length ? { labels } : {}), ...(d.size === "l" ? { size: "l" } : {}) } : null; if (JSON.stringify(next) !== JSON.stringify(was.captions ?? null)) p.captions = next; } + if (!view.montage) { + // Room at the clips' edges (release 36 lane E): its settings kept as written. + const was0 = was.room ?? null; + const on = d.roomTail || d.roomHead; + const next = on ? { ...(was0 ?? {}), tail: d.roomTail, head: d.roomHead } : null; + const same = (was0?.tail === true) === d.roomTail && (was0?.head === true) === d.roomHead; + if (!same) p.room = next; + } return p; } @@ -177,6 +191,14 @@ export default function LookPanel({ project }: { project: string }) { </Field> )} </div> + {!view.montage && ( + <div className="mt-3 flex flex-wrap items-center gap-x-5 gap-y-2" data-look-room=""> + <span className="text-[12.5px] text-text-2">Room at the clips&rsquo; edges</span> + {check("roomTail", "Tail: sound to the first silence, then muted", "data-look-room-tail", Number(draft.transition) === 0)} + {check("roomHead", "Head: muted lead-in", "data-look-room-head", Number(draft.transition) === 0)} + {Number(draft.transition) === 0 && <span className="text-[12px] text-muted">no join to make room for</span>} + </div> + )} <div className="mt-3 space-y-2"> {view.deck || view.montage ? ( <p className="m-0 text-[12px] text-muted" data-look-captions-off=""> diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -11,6 +11,7 @@ import type { CitedPlay } from "@/lib/clips/types"; import { edgeClock, provenanceWords, quoteBetween, roleOf, snapCut, snapPoints } from "@/lib/report/clipEditorModel.mjs"; import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Speaker, Turn } from "@/lib/report/clipEditorTypes"; import { cn } from "@/lib/utils"; +import { ROOM, roomShade } from "umtool-report-to-video/room"; import { startTakeJob } from "../NewTakePanel"; // Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional). import type { ReplyProposal } from "@/lib/annotations/types"; @@ -270,6 +271,16 @@ export default function ClipEditor({ const setLabel = (speaker: number, label: string) => { void write({ op: "label", speaker, label: label.trim() || null }, label.trim() ? `Speaker ${speaker} is “${label.trim()}” in the captions` : `Speaker ${speaker}'s name cleared`); }; + // Room at this clip's edges (release 36 lane E): off writes `room: false`; + // on again removes the override when the cut has room, else turns both edges on. + // The box shows the choice at once (roomDraft) until the view comes back. + const [roomDraft, setRoomDraft] = useState<{ clip: string; on: boolean } | null>(null); + const setRoom = (on: boolean) => { + const cutHas = !!(view.room?.tail || view.room?.head); + const room = on ? (cutHas ? null : { tail: true, head: true }) : cutHas ? false : null; + setRoomDraft({ clip: clip.id, on }); + void write({ op: "room", clip: clip.id, room }, on ? "Room at this clip's edges" : "No room at this clip's edges").finally(() => setRoomDraft(null)); + }; const setCrop = (crop: number[] | null, aspect?: number) => { void write({ op: "vertical", clip: clip.id, crop, ...(crop && aspect ? { aspect: Math.round(aspect * 10000) / 10000 } : {}) }, crop ? "Saved the short's framing" : "The short is framed from the centre"); }; @@ -386,6 +397,18 @@ export default function ClipEditor({ const prov = provenanceWords(assist); const canRestore = !!assist?.original && (assist.original.cutStart ?? assist.original.start) !== undefined; const edits = assist?.edits ?? []; + // What the strip shades as muted: the build's rule on the cut as drawn (the + // build snaps it first). The first clip has nothing before it, so no head. + const join = view.room?.join ?? 0; + const roomEdges = clip.roomEdges ?? null; + const shade = roomShade({ + cutStart: cut.cutStart, + cutEnd: cut.cutEnd, + room: roomEdges ? { tail: roomEdges.tail, head: roomEdges.head && index > 0, minGap: view.room?.minGap ?? ROOM.minGap, maxS: view.room?.maxS ?? ROOM.maxS } : null, + D: join, + words: hoodHere?.words ?? null, + cues: hoodHere?.cues ?? null, + }); const quoteNow = hoodHere ? quoteBetween({ words: hoodHere.words, cues: hoodHere.cues }, cut.cutStart, cut.cutEnd) : null; const pickRole = speakerPick !== null ? roleOf(speakers, speakerPick) : null; @@ -462,6 +485,7 @@ export default function ClipEditor({ to={viewTo} cut={cut} hood={hoodHere} + room={shade} speakers={speakers} others={clips.filter((c) => c.id !== clip.id && c.video === clip.video && c.channel === clip.channel)} playhead={playhead} @@ -524,6 +548,26 @@ export default function ClipEditor({ ))} </div> + {/* ---- room at the edges (release 36 lane E) ---------------------- */} + {join > 0 && !clip.montage && ( + <div className="flex flex-wrap items-center gap-3 text-[12px] text-text-2" data-editor-room={roomEdges ? `${roomEdges.tail ? "tail" : ""}${roomEdges.head ? " head" : ""}`.trim() : "off"}> + <label className="inline-flex items-center gap-1.5 text-text"> + <input type="checkbox" data-clip-room="" checked={roomDraft?.clip === clip.id ? roomDraft.on : !!roomEdges} disabled={busy} onChange={(e) => setRoom(e.target.checked)} /> + Room at its edges + </label> + {shade.tail && ( + <span className="num font-mono text-[11.5px] text-muted" data-room-tail={`${shade.tail[0]}-${shade.tail[1]}`}> + sound to {edgeClock(shade.tail[0])}, muted to {edgeClock(shade.tail[1])} + </span> + )} + {shade.head && ( + <span className="num font-mono text-[11.5px] text-muted" data-room-head={`${shade.head[0]}-${shade.head[1]}`}> + muted from {edgeClock(shade.head[0])} + </span> + )} + </div> + )} + {/* ---- the decisions ----------------------------------------------- */} <div className="flex flex-wrap items-center gap-2" data-editor-actions=""> <button type="button" data-rule="keep" aria-pressed={clip.ruling === "keep"} disabled={busy} onClick={() => rule(clip.ruling === "keep" ? null : "keep")} className={buttonVariants({ variant: clip.ruling === "keep" ? "pressed" : "outline", size: "md" })}> @@ -828,6 +872,7 @@ function Strip({ to, cut, hood, + room = null, speakers, others, playhead, @@ -843,6 +888,8 @@ function Strip({ to: number; cut: Cut; hood: Neighbourhood | null; + /** Room at the edges (release 36 lane E): the muted head and tail to shade. */ + room?: { head: number[] | null; tail: number[] | null } | null; speakers: Speaker[]; others: EditorClip[]; playhead: number | null; @@ -954,6 +1001,20 @@ function Strip({ })} {/* the selection to add */} {selection && <span data-selection={`${selection.cutStart}-${selection.cutEnd}`} style={{ left: pct(selection.cutStart), width: width(selection.cutStart, selection.cutEnd) }} className="pointer-events-none absolute inset-y-0 border-x border-dashed border-text bg-[color-mix(in_srgb,var(--text)_10%,transparent)]" />} + {/* room at the edges: muted picture either side of the cut */} + {(["head", "tail"] as const).map((edge) => { + const sp = room?.[edge]; + if (!sp) return null; + return ( + <span + key={edge} + data-strip-room={edge} + title={edge === "tail" ? `muted ${edgeClock(sp[0])}–${edgeClock(sp[1])}: room for the join` : `muted ${edgeClock(sp[0])}–${edgeClock(sp[1])}: room for the join before it`} + style={{ left: pct(sp[0]), width: width(sp[0], sp[1]) }} + className="pointer-events-none absolute inset-y-0 border-y border-dashed border-signal bg-[color-mix(in_srgb,var(--signal)_6%,transparent)]" + /> + ); + })} {/* the cut */} <span data-strip-cut="" style={{ left: pct(cut.cutStart), width: width(cut.cutStart, cut.cutEnd) }} className="pointer-events-none absolute inset-y-0 border-y-2 border-signal bg-[color-mix(in_srgb,var(--signal)_14%,transparent)]" /> {(["in", "out"] as const).map((edge) => ( diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1088,7 +1088,8 @@ YouTube `&t=<s>s`, Twitch `?t=<h>h<m>m<s>s`, Rumble `?start=<s>`, anything else `t=<s>`), and a moved clip's link follows it (a link you wrote stays). The seed writes `provenance.channel` from the metadata and the look chosen for a one-video cut: `render` `headerHeight: 0, footerHeight: 0, qr: false, -transition: 0.5, transitionStyle: "fadeblack", loudness: {target: -16}`. With +transition: 0.4, transitionStyle: "blurslide", loudness: {target: -16}, room: +{tail: true, head: true}` (lane E; before it, 0.5 s `"fadeblack"`). With every clip linked, an empty `siteOrigin` is not a blocking decision. **From the editor** (release 36): `POST /api/report/clips {mode: "new", slug, @@ -1260,12 +1261,14 @@ render is byte for byte what it was), validated by the build and by the lint | clip `vertical` | `{crop: [x, y, w, h], aspect?}` | Fractions of the source picture: the box a vertical short is cut from, 9:16 on the source (`aspect` = the source's width / height, 16/9 when absent; within 3 %). Absent: the centred full-height box. | A site-less, one-video cut made by the clip finder starts with -`headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, -transitionStyle: "fadeblack", loudness: {target: -16}` (lane B's seed). +`headerHeight: 0, footerHeight: 0, qr: false, transition: 0.4, +transitionStyle: "blurslide", loudness: {target: -16}, room: {tail: true, +head: true}` (lane B's seed, with lane E's join and room). **The Look panel** (the Build tab, `/api/report/render`) sets them by hand: **Header**, **Timeline footer**, **QR code**, the length **Between clips** (0 is -a hard cut) and the **Join** (crossfade, dip to black, dip to white, dissolve), +a hard cut) and the **Join** (crossfade, dip to black, dip to white, dissolve, +blur slide), **Room at the clips' edges** (Tail, Head — below), **Loudness** (as recorded, −16 LUFS, or a custom target) and **Speaker captions** with each role's name and the size. **Save the look** writes only what changed (`lib/report/manifest.mjs` `updateRender`: token-guarded, the @@ -1297,6 +1300,59 @@ clip in the editor to frame it. From a terminal: `node umtool/report-to-video/build-video.mjs <project>/video.manifest.json --short <clipId>`. +## Room at the clips' edges, and the blur slide (release 36 lane E) + +A join of `render.transition` seconds fades over the last seconds of one clip +and the first of the next, so a tight cut loses the end of its last sentence +and the start of the next clip's first. **`render.room`** makes the join play +over quiet picture instead (`report-to-video/room.mjs`, validated by the build +and the lint through `validateLook`): + +| Key | Shape | What it does | +|---|---|---| +| `render.room` | `{tail?: true, head?: true, minGap?: 0.35, maxS?: 2.5}` | An edge is on when its key is `true`. **Tail:** from the cut's end the SOUND runs on to the first silence — the end of the run of words that crosses the cut's end or starts within `minGap` after it, the run stopping at the first gap of at least `minGap` between two words, never more than `maxS` past the cut's end — with a 60 ms fade there; the PICTURE then runs on, muted, for the join's length + 0.1 s. **Head:** when speech starts within the join's length of the cut's start, the picture starts that much earlier, muted, the sound fading in over the 60 ms before the cut's start (not on the cut's first clip). Not with a montage. | +| clip `room` | `false`, or `{tail?: boolean, head?: boolean}` | This clip's edges, whatever the cut says (`false`: none). | + +Absent, `null` or with neither edge on, the render is byte for byte what it +was. Room needs a join: with `render.transition` 0 it does nothing (the lint +says so), and a short has none. + +**The words** the rule reads: the project's `words.json` when the clip is from +the recording `reactions.json` describes, else the corpus transcript's whisper +words, else its cues spread over their words. With none — or a run of cues that +reaches the cap, which says the cues abut rather than that anyone talks on — +`silencedetect` on the clip's source (−35 dB, 0.3 s): the silence the cut's end +is in, else the next to start within `maxS`; none found leaves the sound at the +cut's end (a note says so). + +**Inside its source:** a saved whole video has room to spare; a fetched window +(the extent plus `fetchPad`) clamps the extension at its edge — the build notes +it, and the lint warns when a clip's room can reach past its window (widen the +extent, or fetch the source whole). + +The segment is the picture's span, and everything downstream measures it: the +cut record's `start`/`end` are the picture's (so a `muteFrom` still lands), and +`room: {sound: [from, to], head, tail, via, capped?, clamped?}` says what is +heard; captions are only the words heard and stop at the silence point; +`render.loudness` measures the audible part; the joins, the chapters and the +sound's sync come from the segments' lengths as ever (the cut is their sum less +the joins). + +**The clip editor** shades a clip's muted head and tail on the strip (the rule +on the cut as drawn; the build snaps the cut first) and says where its sound +stops; **Room at its edges** turns this clip's room off (`room: false`) or on +again. The Look panel's **Room at the clips' edges** sets `render.room`. + +**The blur slide** (`render.transitionStyle: "blurslide"`, the Join menu's +"blur slide"): the next clip slides in from the left (xfade `slideright`) while +both sides of the seam are smeared sideways and grained — each clip's last and +first `render.transition` seconds get a horizontal Gaussian blur (σ 10 across +the whole edge, and σ 16 more in the half nearest the seam, so ≈ 19 at it; +vertical σ 0.6, so it reads as motion, not focus) and a light temporal noise +(strength 7) — in the clip's own time, so a batched build's joins get it too +(`transition.mjs` `BLUR_SLIDE`). A dip, a THEN/NOW wipe and a whip keep their +own look. With room at both edges the slide runs over muted picture. + ## Operator notes, timed notes and the generated-manifest guard Notes on a project live in `<project>/notes.json` (shape and CLI: diff --git a/umtool/e2e/clip-look.spec.ts b/umtool/e2e/clip-look.spec.ts @@ -7,7 +7,9 @@ import * as urls from "./urls"; // --------------------------------------------------------------------------- // The look of a highlights cut (release 36 lane C). The Build tab's Look // panel saves the header, the QR, the join, the loudness and the speaker -// captions into the manifest (and reads them back); the clip editor's +// captions and room at the clips' edges into the manifest (and reads them +// back); the clip editor's strip shades a clip's muted tail and its own +// toggle writes `room: false`; the clip editor's // Speakers list names a voice for the captions (reactions.json); Frame the // short drags a 9:16 box on the player (the clip's vertical.crop); Make a // short runs the job (build-video --short) and the Deliver tab's Shorts list @@ -42,7 +44,10 @@ test("the look: the panel saves and reads back; a voice named; a short framed, m await page.locator("[data-look-header]").uncheck(); await page.locator("[data-look-qr]").uncheck(); await page.locator("[data-look-transition]").fill("0.5"); - await page.locator("[data-look-style]").selectOption("fadeblack"); + await page.locator("[data-look-style]").selectOption("blurslide"); + // Room at the clips' edges (release 36 lane E). + await page.locator("[data-look-room-tail]").check(); + await page.locator("[data-look-room-head]").check(); await page.locator("[data-look-loudness]").selectOption("-16"); await page.locator("[data-look-captions]").check(); await page.locator("[data-look-label-host]").fill("The host"); @@ -53,7 +58,8 @@ test("the look: the panel saves and reads back; a voice named; a short framed, m expect(r.headerHeight).toBe(0); expect(r.qr).toBe(false); expect(r.transition).toBe(0.5); - expect(r.transitionStyle).toBe("fadeblack"); + expect(r.transitionStyle).toBe("blurslide"); + expect(r.room).toEqual({ tail: true, head: true }); expect(r.loudness).toEqual({ target: -16 }); expect(r.captions).toEqual({ style: "speakers", labels: { host: "The host" }, size: "l" }); expect(r.width).toBe(640); @@ -62,7 +68,9 @@ test("the look: the panel saves and reads back; a voice named; a short framed, m await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", ""); await expect(page.locator("[data-look-header]")).not.toBeChecked(); await expect(page.locator("[data-look-qr]")).not.toBeChecked(); - await expect(page.locator("[data-look-style]")).toHaveValue("fadeblack"); + await expect(page.locator("[data-look-style]")).toHaveValue("blurslide"); + await expect(page.locator("[data-look-room-tail]")).toBeChecked(); + await expect(page.locator("[data-look-room-head]")).toBeChecked(); await expect(page.locator("[data-look-loudness]")).toHaveValue("-16"); await expect(page.locator("[data-look-captions]")).toBeChecked(); await expect(page.locator("[data-look-label-host]")).toHaveValue("The host"); @@ -75,6 +83,16 @@ test("the look: the panel saves and reads back; a voice named; a short framed, m await subject.press("Enter"); await expect.poll(() => json("reactions.json")?.speakers?.find((s: { index: number }) => s.index === 1)?.label).toBe("The narrator"); + // Room at the edges: the strip shades the clip's muted tail; the clip's own toggle writes its override. + await expect(page.locator('[data-strip-room="tail"]')).toBeVisible(); + await expect(page.locator("[data-clip-room]")).toBeChecked(); + await page.locator("[data-clip-room]").uncheck(); + await expect.poll(() => clip("r001")?.room ?? null).toBe(false); + await expect(page.locator('[data-strip-room="tail"]')).toHaveCount(0); + await page.locator("[data-clip-room]").check(); + await expect.poll(() => clip("r001")?.room === undefined).toBe(true); + await expect(page.locator('[data-strip-room="tail"]')).toBeVisible(); + await expect(page.locator("[data-editor-player]")).toHaveAttribute("data-editor-player", /^(?!looking|none)/, { timeout: 20_000 }); await page.locator("[data-frame-short]").click(); const box = page.locator("[data-crop-box]"); diff --git a/umtool/e2e/create.spec.ts b/umtool/e2e/create.spec.ts @@ -287,7 +287,7 @@ test("Find clips from the editor (release 36): mode new with the worker token sc // A channel on no site: each clip links its YouTube page at its second; the site-less look. const m = manifestOf("p36-find"); expect(m.provenance.channel).toBe("Synth Two"); - expect(m.render).toMatchObject({ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", loudness: { target: -16 } }); + expect(m.render).toMatchObject({ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.4, transitionStyle: "blurslide", loudness: { target: -16 }, room: { tail: true, head: true } }); for (const c of m.timeline) expect(c.citeUrl).toBe(`https://www.youtube.com/watch?v=two001&t=${c.cite}s`); const done = async (id: string) => (await (await request.get(`/api/report/clips?job=${id}`)).json()).state; await expect.poll(() => done(made.jobId), { timeout: 60_000 }).toBe("done"); diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs @@ -17,8 +17,14 @@ export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/; export const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; export const SEEDS = ["chapters", "frames", "phrase", "reactions"]; -/** The render keys a site-less, one-video reactions cut starts with (release 36: the operator's choice on the first case). */ -export const SITELESS_LOOK = Object.freeze({ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", loudness: Object.freeze({ target: -16 }) }); +/** + * The render keys a site-less, one-video reactions cut starts with (release 36: the operator's choice on the first + * case; lane E: 0.4 s blur slides with room at each clip's edges, so a join never eats the end of a sentence). + */ +export const SITELESS_LOOK = Object.freeze({ + headerHeight: 0, footerHeight: 0, qr: false, transition: 0.4, transitionStyle: "blurslide", + loudness: Object.freeze({ target: -16 }), room: Object.freeze({ tail: true, head: true }), +}); /** * A manifest skeleton, and deliberately an EMPTY timeline. @@ -405,12 +411,11 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site if (pass.siteLess) { // Release 36: a channel on no site — each clip links its platform page at // its second (no QR to an archive that does not have it), and the look the - // operator chose for a one-video cut: no header, no QR, fades through black, - // even loudness (render.loudness is lane C's; until its validator lands it - // is a key the build ignores). - Object.assign(doc.render, SITELESS_LOOK, { loudness: { ...SITELESS_LOOK.loudness } }); + // operator chose for a one-video cut: no header, no QR, blur slides with + // room at each clip's edges (render.room), even loudness. + Object.assign(doc.render, SITELESS_LOOK, { loudness: { ...SITELESS_LOOK.loudness }, room: { ...SITELESS_LOOK.room } }); const platform = /^youtube/i.test(pass.rec.meta?.extractor ?? "") ? "YouTube" : pass.rec.meta?.extractor ?? "its platform"; - notes.push(`no site carries ${src.channel}: each clip links ${platform}'s page at its second (citeUrl); the look: no header, no QR, ${SITELESS_LOOK.transition} s fades through black, ${SITELESS_LOOK.loudness.target} LUFS`); + notes.push(`no site carries ${src.channel}: each clip links ${platform}'s page at its second (citeUrl); the look: no header, no QR, ${SITELESS_LOOK.transition} s blur slides with room at each clip's edges, ${SITELESS_LOOK.loudness.target} LUFS`); } else { // Hard cuts: a highlights reel. doc.render.transition = 0; diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -42,6 +42,7 @@ import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLab import { readShorts } from "./shorts.mjs"; import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs"; import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; +import { clipRoom } from "umtool-report-to-video/room"; export { StaleToken, StructureRefused }; @@ -85,7 +86,8 @@ export async function readWords(dir, reactions = null) { * @typedef {{ id: string, channel: string | null, video: string, start: number, end: number, * cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null, * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean, - * vertical: { crop: number[], aspect?: number } | null }} EditorClip + * vertical: { crop: number[], aspect?: number } | null, + * room: false | { tail?: boolean, head?: boolean } | null, roomEdges: { tail: boolean, head: boolean } | null }} EditorClip */ /** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */ @@ -114,6 +116,10 @@ export async function clipEditorView(project) { montage: isObj(e.montage), // A short's framing (release 36): fractions of the source picture. vertical: isObj(e.vertical) && Array.isArray(e.vertical.crop) ? { crop: e.vertical.crop, ...(fin(e.vertical.aspect) ? { aspect: e.vertical.aspect } : {}) } : null, + // Room at its edges (release 36 lane E): the clip's own override as + // written, and the edges it gets with the cut's render.room. + room: e.room === false ? false : isObj(e.room) ? e.room : null, + roomEdges: roomEdgesOf(e, manifest.render), }; }); const shorts = await readShorts(project.dir, manifest); @@ -136,6 +142,32 @@ export async function clipEditorView(project) { : null, repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE }, shorts: Object.fromEntries(shorts.filter((x) => !x.gone).map((x) => [x.clip, { mtimeMs: x.mtimeMs, size: x.size, stale: x.stale }])), + room: roomViewOf(manifest.render), + }; +} + +/** A clip's room edges (room.mjs clipRoom), or null when it has none. */ +function roomEdgesOf(entry, render) { + const r = clipRoom(entry, render); + return r ? { tail: r.tail, head: r.head } : null; +} + +/** + * The cut's room, for the strip (release 36 lane E): render.room's edges, its + * settings and the join's length -- null when the cut has no room and no + * join (a montage's, or transition 0). + */ +function roomViewOf(render) { + const r = isObj(render) ? render : {}; + // The build's join (deck.mjs transitionOf): 0.5 s unless the render says; none in a montage. + const D = r.montage !== undefined && r.montage !== null ? 0 : fin(r.transition) ? r.transition : 0.5; + const room = isObj(r.room) ? r.room : null; + return { + tail: room?.tail === true, + head: room?.head === true, + minGap: fin(room?.minGap) ? room.minGap : null, + maxS: fin(room?.maxS) ? room.maxS : null, + join: D, }; } @@ -237,6 +269,8 @@ const num = (v, what) => { * role { speaker, role | null } reactions.json, through the clip finder's writer * label { speaker, label | null } a speaker's name for the captions (reactions.json) * vertical { clip, crop | null, aspect? } the clip's 9:16 box for its short + * room { clip, room: false | {tail?, head?} | null } room at this clip's edges + * (null: the cut's render.room again) * with `token` (the manifest's, from the view) on every manifest edit. * Returns `{ op, result, carried, view }`. */ @@ -363,8 +397,16 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { structural = false; break; } + case "room": { + const e = needClip(); + if (body.room !== null && body.room !== false && !isObj(body.room)) throw new OpError("room is false, {tail?, head?}, or null for the cut's"); + // A "trim" that leaves the cut where it is, as `vertical` is. + result = await updateClip(dir, e.id, { room: body.room }, { token, edit: "trim", now }); + structural = false; + break; + } default: - throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label or vertical"); + throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical or room"); } let carried = null; if (structural) { diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -27,6 +27,9 @@ export type EditorClip = { montage: boolean; /** 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. */ + room?: false | { tail?: boolean; head?: boolean } | null; + roomEdges?: { tail: boolean; head: boolean } | null; }; export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator"; sameAs?: number }; @@ -49,6 +52,8 @@ export type EditorView = { repropose: { available: boolean; why: string | null }; /** The shorts on disk, by clip id (release 36). */ shorts: Record<string, { mtimeMs: number; size: number; stale: boolean }>; + /** The cut's render.room and its join's length (release 36 lane E). */ + room?: { tail: boolean; head: boolean; minGap: number | null; maxS: number | null; join: number }; }; export type Turn = { start: number; end: number; speaker: number }; diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs @@ -46,7 +46,7 @@ const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NA test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => { const p = await project({ transition: 0.4, crf: 21 }); try { - assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions"]); + assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room"]); const token = await manifestToken(p.dir); const r = await updateRender(p.dir, { headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -34,6 +34,7 @@ import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, valid import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs"; import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; import { validateLook, verticalErrors } from "umtool-report-to-video/look"; +import { validateRoom } from "umtool-report-to-video/room"; import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition"; import { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; @@ -399,6 +400,22 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri } } + // ---- room at the clip's edges (release 36 lane E) ------------------------ + // + // `room: false` (none for this clip) or `{tail?, head?}` (that edge, whatever + // the cut's render.room says) -- room.mjs validateRoom, the build's own + // check. null or "" removes it: the cut's room again. + if (patch.room !== undefined) { + const v = patch.room; + if (v === null || v === "") delete entry.room; + else { + const errors = validateRoom({ timeline: [{ ...entry, room: v }] }); + if (errors.length) throw new Error(errors.join("; ")); + const vv = /** @type {false | { tail?: boolean, head?: boolean }} */ (v); + entry.room = vv === false ? false : { ...(typeof vv.tail === "boolean" ? { tail: vv.tail } : {}), ...(typeof vv.head === "boolean" ? { head: vv.head } : {}) }; + } + } + // ---- an assistant's clip, edited by a person (release 35 C2) ------------- // // A clip the clip finder proposed carries `assist`. The first human edit @@ -920,7 +937,7 @@ export class ChromeRefused extends Error { // --------------------------------------------------------------------------- /** The render keys the Look panel writes, in its order. */ -export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions"]); +export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room"]); /** The look keys of a render block as written (absent keys left out). */ export function lookOf(render) { @@ -992,7 +1009,7 @@ export async function updateRender(dir, patch, { token = null } = {}) { else render.transitionStyle = v; break; default: - // loudness, captions: stored as given; the build's validators below say what is wrong. + // loudness, captions, room: stored as given; the build's validators below say what is wrong. render[k] = v; } } diff --git a/umtool/lib/report/reactions-r36.test.mjs b/umtool/lib/report/reactions-r36.test.mjs @@ -217,8 +217,8 @@ test("a channel on no site: each clip links its platform page, provenance.channe assert.equal(m.provenance.channel, "Synth Reacts Channel"); assert.equal(m.provenance.siteOrigin, ""); assert.deepEqual( - { headerHeight: m.render.headerHeight, footerHeight: m.render.footerHeight, qr: m.render.qr, transition: m.render.transition, transitionStyle: m.render.transitionStyle, loudness: m.render.loudness }, - { ...SITELESS_LOOK, loudness: { target: -16 } }, + { headerHeight: m.render.headerHeight, footerHeight: m.render.footerHeight, qr: m.render.qr, transition: m.render.transition, transitionStyle: m.render.transitionStyle, loudness: m.render.loudness, room: m.render.room }, + { ...SITELESS_LOOK, loudness: { target: -16 }, room: { tail: true, head: true } }, ); assert.ok(r.notes.some((n) => /no site carries synth-reacts: each clip links YouTube's page/.test(n)), r.notes.join("\n")); // The build's validators and lint take it (render.loudness is a key they do not refuse). diff --git a/umtool/lib/report/room.test.mjs b/umtool/lib/report/room.test.mjs @@ -0,0 +1,102 @@ +// Room at a clip's edges in umtool (release 36 lane E): render.room through +// updateRender (the Look panel's writer), a clip's `room` through updateClip +// and the clip editor's `room` operation, and what the clip editor's view +// says of it. Synthetic. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { MANIFEST_NAME, RenderRefused, manifestToken, updateClip, updateRender } from "./manifest.mjs"; +import { clipEditorView, runClipEditorOp } from "./clipEditor.mjs"; +import { SITELESS_LOOK } from "../projects/scaffold.mjs"; +import { validateLook } from "umtool-report-to-video/look"; + +const manifest = (render = {}) => ({ + schemaVersion: 1, + slug: "room", + provenance: { channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000" }, ...render }, + timeline: [ + { type: "clip", id: "r001", video: "v1", start: 10, end: 20, cutStart: 11, cutEnd: 19, quote: "q" }, + { type: "clip", id: "r002", video: "v1", start: 30, end: 40 }, + ], +}); + +async function project(render = {}) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-room-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(render), null, 2) + "\n"); + return { id: "reports/room", dir, kind: "report" }; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + +test("the site-less seed's look: 0.4 s blur slides with room at both edges, and the build's validators take it", () => { + assert.equal(SITELESS_LOOK.transition, 0.4); + assert.equal(SITELESS_LOOK.transitionStyle, "blurslide"); + assert.deepEqual(SITELESS_LOOK.room, { tail: true, head: true }); + assert.deepEqual(validateLook({ render: { ...SITELESS_LOOK }, timeline: [] }), []); +}); + +test("updateRender: render.room is a look key; null removes it; a bad one is refused in the build's words", async () => { + const p = await project({ transition: 0.4 }); + try { + const r = await updateRender(p.dir, { room: { tail: true, head: false } }, { token: await manifestToken(p.dir) }); + assert.deepEqual(r.look.room, { tail: true, head: false }); + assert.deepEqual((await read(p.dir)).render.room, { tail: true, head: false }); + await assert.rejects(updateRender(p.dir, { room: { tail: "on" } }), (e) => e instanceof RenderRefused && /render\.room\.tail must be true or false/.test(e.errors.join(";"))); + await updateRender(p.dir, { room: null }); + assert.equal((await read(p.dir)).render.room, undefined); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("updateClip: a clip's room -- false, per-edge booleans, null removes it; a bad one refused", async () => { + const p = await project({ room: { tail: true, head: true } }); + try { + await updateClip(p.dir, "r001", { room: false }); + assert.equal((await read(p.dir)).timeline[0].room, false); + await updateClip(p.dir, "r001", { room: { tail: false } }); + assert.deepEqual((await read(p.dir)).timeline[0].room, { tail: false }); + await updateClip(p.dir, "r001", { room: null }); + assert.equal("room" in (await read(p.dir)).timeline[0], false); + await assert.rejects(updateClip(p.dir, "r001", { room: { middle: true } }), /room\.middle is not a setting here/); + // The cut itself is untouched by a room edit. + const e = (await read(p.dir)).timeline[0]; + assert.deepEqual([e.cutStart, e.cutEnd], [11, 19]); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("the clip editor: the view says each clip's edges and the cut's room; the room op writes the override", async () => { + const p = await project({ transition: 0.4, room: { tail: true, head: true } }); + try { + let view = await clipEditorView(p); + assert.deepEqual(view.room, { tail: true, head: true, minGap: null, maxS: null, join: 0.4 }); + assert.deepEqual(view.clips.map((c) => c.roomEdges), [{ tail: true, head: true }, { tail: true, head: true }]); + assert.equal(view.clips[0].room, null); + const off = await runClipEditorOp(p, { op: "room", clip: "r001", room: false, token: view.token }); + view = off.view; + assert.equal(view.clips[0].room, false); + assert.equal(view.clips[0].roomEdges, null); + const on = await runClipEditorOp(p, { op: "room", clip: "r001", room: null, token: view.token }); + assert.equal(on.view.clips[0].roomEdges.tail, true); + await assert.rejects(runClipEditorOp(p, { op: "room", clip: "r001", room: "yes" }), /room is false, \{tail\?, head\?\}, or null/); + // A cut with no room: a clip can still ask for its own. + const q = await project({ transition: 0 }); + try { + const v = await clipEditorView(q); + assert.deepEqual(v.room, { tail: false, head: false, minGap: null, maxS: null, join: 0 }); + const r = await runClipEditorOp(q, { op: "room", clip: "r002", room: { tail: true, head: true }, token: v.token }); + assert.deepEqual(r.view.clips[1].roomEdges, { tail: true, head: true }); + } finally { + await rm(q.dir, { recursive: true, force: true }); + } + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -172,6 +172,12 @@ import { assDocument, assFilter, captionGeometry, captionLines, captionsOn, loudnessTargetOf, shortRender, validateLook, verticalFilters, } from "./look.mjs"; +// Room at a clip's edges (release 36 lane E, render.room): the rule is pure, +// in room.mjs; the build finds the words or silences and cuts the segment. +import { + ROOM, clipRoom, roomAudioFilter, roomPlan, speechStartFromSilences, speechStartFromWords, tailFromSilences, + tailFromWords, +} from "./room.mjs"; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; import { pruneChromeFrames } from "./prune-frames.mjs"; @@ -1217,28 +1223,42 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const cutA = mont ? mont.win.cutA : Math.min(a.at, wantB - 1); const cutB = mont ? mont.win.cutB : Math.max(b.at, cutA + 1); EMIT("snap", { id: entry.id, start: a.snapped, end: b.snapped, seconds: cutB - cutA }); + // Room at the edges (render.room, room.mjs): the picture widened past the + // snapped cut -- to the first silence and a join's length beyond, muted -- + // the sound heard over [cutA, soundB] only. Null when off: the cut as ever. + const room = dirs.room && !mont && !dirs.short + ? await segmentRoom({ entry, raw, render, provenance, look: dirs.look, D: dirs.room.D, first: dirs.room.first === entry.id, fetchStart, cutA, cutB }) + : null; + const segA = room ? room.plan.picA : cutA; + const segB = room ? room.plan.picB : cutB; // 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). + // function is gone (`--chrome-only` rebuilds no segment). With room, the + // picture's span; `room.sound` is the part that is heard. const cutRecord = { version: 1, id: entry.id, video: entry.video, - start: Number((fetchStart + cutA).toFixed(3)), end: Number((fetchStart + cutB).toFixed(3)), + start: Number((fetchStart + segA).toFixed(3)), end: Number((fetchStart + segB).toFixed(3)), snapped: { start: a.snapped, end: b.snapped }, + ...(room ? { room: room.record } : {}), }; // Even loudness for a cut that is not a montage (render.loudness, release // 36): the cut as it will play, measured, one gain toward the target // (montage.mjs loudnessGain), in the cut record. A montage levels with its // own key; absent, nothing here runs. if (!mont && loudnessTargetOf(render) != null) { - level = await montageLevel(raw, cutA, cutB, { target: loudnessTargetOf(render) }); + // With room, the audible part: the muted edges would only pull it down. + level = await montageLevel(raw, cutA, room ? room.plan.soundB : cutB, { target: loudnessTargetOf(render) }); cutRecord.loudness = level; } // The sound's graph: `[0:a]` levelled to `[al]` (an asplit first when a // poster's waveform also reads it), else nothing and `0:a` as ever. - const leveled = !mont && level != null; + // Room's fades (muted head and tail) after the gain. + const roomAf = room ? roomAudioFilter(room.plan) : ""; + const soundChain = [!mont && level != null ? levelFilters(level.gain) : "", roomAf].filter(Boolean).join(","); + const leveled = !mont && soundChain !== ""; const levelParts = (posterParts) => (leveled ? [ - ...(posterParts ? [`[0:a]asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${levelFilters(level.gain)}[al]`] : [`[0:a]${levelFilters(level.gain)}[al]`]), + ...(posterParts ? [`[0:a]asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${soundChain}[al]`] : [`[0:a]${soundChain}[al]`]), ] : (posterParts ?? [])); const audioMap = leveled ? "[al]" : "0:a"; @@ -1270,7 +1290,7 @@ 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(cutB, media.duration) : cutB) - cutA); + const posterSeconds = Math.max(1 / render.fps, (media.duration != null ? Math.min(segB, media.duration) : segB) - segA); 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 @@ -1285,7 +1305,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, FFMPEG, [ "-nostdin", "-v", "error", "-y", - ...cutArgs(raw, cutA, cutB), + ...cutArgs(raw, segA, segB), ...(pst ? pst.input : []), "-filter_complex", [ ...levelParts(pst ? pst.parts : null), @@ -1373,9 +1393,9 @@ 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, cutB - cutA - 0.25); + const barT = Math.max(0.2, segB - segA - 0.25); - const inputs = cutArgs(raw, cutA, cutB); + const inputs = cutArgs(raw, segA, segB); let nextIdx = 1; let footerIdx, markerIdx, barIdx, qrIdx; if (hasFooter) { @@ -1446,7 +1466,9 @@ 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: cutB - cutA, bottom: FH, + from: cutRecord.start, seconds: segB - segA, bottom: FH, + // With room: only the words heard -- none over a muted edge. + ...(room ? { audible: { from: fetchStart + cutA, to: fetchStart + room.plan.soundB } } : {}), }); if (cap) { parts.push(`${vOut}${cap.filter}[vc]`); @@ -1567,8 +1589,10 @@ async 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 }) { - const src = await lookWordsFor(entry, provenance, look, from, from + seconds); +async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, bottom, audible = null }) { + // `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); if (!src.words.length) { EMIT("note", { message: `${entry.id}: no words to caption — it plays without captions` }); return null; @@ -1585,6 +1609,87 @@ async function segmentCaptions({ entry, provenance, look, render, outDir, from, return { filter: assFilter(file, FONTS_DIR), lines: lines.length, wordsFrom: src.wordsFrom }; } +// ---- room at the edges (render.room; release 36 lane E) -------------------- +// The build's side of room.mjs: the words (or the silences) around a clip's +// edges, and the plan its segment is cut by. + +/** + * silencedetect at a fixed floor (ROOM.detectDb, ROOM.detectD) over [from, to] + * of a file (its own seconds), for a clip with no words. A silence still open + * when the span ends runs to its end. + */ +async function detectRoomSilences(file, from, to) { + const a = Math.max(0, from); + const { stderr } = await execFileP( + FFMPEG, + ["-nostdin", "-ss", a.toFixed(3), "-to", to.toFixed(3), "-i", file, "-vn", "-af", `silencedetect=noise=${ROOM.detectDb}dB:d=${ROOM.detectD}`, "-f", "null", "-"], + { maxBuffer: 1 << 26 }, + ).catch((e) => ({ stderr: e.stderr ?? "" })); + const out = []; + let open = null; + for (const line of String(stderr ?? "").split("\n")) { + const s = line.match(/silence_start:\s*(-?[\d.]+)/); + if (s) open = Number(s[1]) + a; + const e = line.match(/silence_end:\s*(-?[\d.]+)/); + if (e && open !== null) { + out.push({ s: open, e: Number(e[1]) + a }); + open = null; + } + } + if (open !== null) out.push({ s: open, e: to }); + return out; +} + +/** + * One clip's room (room.mjs's rule): where its sound stops and whether its + * head is muted, from its words -- the project's words.json, the corpus + * transcript, the cues (lookWordsFor) -- else silencedetect; the plan, in + * the file's seconds; and what its cut record says. Null when the clip has + * no room (or nothing moves). `first`: nothing comes before it, so no head. + */ +async function segmentRoom({ entry, raw, render, provenance, look, D, first, fetchStart, cutA, cutB }) { + const room = clipRoom(entry, render); + if (!room) return null; + const head = room.head && !first; + if (!room.tail && !head) return null; + const media = await probeMedia(raw); + const got = look + ? await lookWordsFor(entry, provenance, look, fetchStart + cutA - 1, fetchStart + cutB + room.maxS + 1).catch(() => null) + : null; + const words = (got?.words ?? []).map((w) => ({ start: w.start - fetchStart, end: w.end - fetchStart })); + let via = words.length ? got.wordsFrom : "silence"; + let tail = room.tail && words.length ? tailFromWords(words, cutB, room) : null; + let speech = head && words.length ? speechStartFromWords(words, cutA) : null; + // Cues abut: a run of them that reaches the cap says nothing about where + // anybody stops, so the sound decides that edge instead. + const detectTail = room.tail && (!words.length || (via === "cues" && tail?.capped)); + if (detectTail || (head && !words.length)) { + const end = Math.min(media.duration ?? Infinity, cutB + room.maxS + 0.5); + const sil = await detectRoomSilences(raw, Math.min(cutA, cutB) - 0.5, end); + if (detectTail) { + tail = tailFromSilences(sil, cutB, room); + via = words.length ? `${via}+silence` : "silence"; + if (!tail.found) EMIT("note", { message: `${entry.id}: no silence within ${room.maxS} s of its end — its sound stops at the cut` }); + } + if (head && !words.length) speech = speechStartFromSilences(sil, cutA); + } + const plan = roomPlan({ cutA, cutB, D, soundEnd: tail ? tail.at : null, speechStart: head ? speech : null, duration: media.duration }); + if (plan.picA === cutA && plan.picB === cutB) return null; + if (tail?.capped) EMIT("note", { message: `${entry.id}: still talking ${room.maxS} s past its end — its sound fades there (render.room.maxS)` }); + for (const edge of plan.clamped) { + EMIT("note", { message: `${entry.id}: its ${edge === "tail" ? "tail" : "head"} room is clamped to ${path.basename(raw)}'s ${edge === "tail" ? "end" : "start"} (a fetched window; widen the extent or fetch it whole)` }); + } + const s3 = (t) => Number((fetchStart + t).toFixed(3)); + return { + plan, + record: { + sound: [s3(plan.soundA), s3(plan.soundB)], head: plan.head, tail: plan.tail, via, + ...(tail?.capped ? { capped: true } : {}), + ...(plan.clamped.length ? { clamped: plan.clamped } : {}), + }, + }; +} + /** * A short's segment to <project>/shorts/<id>.mp4 (tmp + rename), with a * record beside it (<id>.json: the cut, the crop, the size, the loudness, @@ -5304,6 +5409,13 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly EMIT("note", { message: "render.montage: the cut styles are in the segments, so they are joined with hard cuts (render.transition is not used)" }); } const D = opts.noXfade || montage || (render.transition ?? 0.5) === 0 ? 0 : render.transition ?? 0.5; + // Room at the clips' edges (render.room or a clip's own room): only with a + // join to make room for, never in a montage or a short. Its words are read + // where the captions' are (readLookSources). + if (D > 0 && !montage && !opts.short && manifest.timeline.some((e) => e?.type === "clip" && clipRoom(e, render))) { + dirs.room = { D, first: manifest.timeline[0]?.id ?? null }; + dirs.look ??= await readLookSources(manifestDir); + } // The montage's plan across the WHOLE cut (a clip's place, its year, its // ramp cap), so an `--only` rebuild cuts a clip as the full build would. // A clip with no date of its own takes its record's upload date. diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -89,6 +89,7 @@ import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; import { validateFxEntries } from "./fx.mjs"; import { validateTransitionStyle } from "./transition.mjs"; import { validateLook } from "./look.mjs"; +import { roomWindowWarnings } from "./room.mjs"; import { qrUrlFor } from "./render-cards.mjs"; import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs"; import { validatePodcast } from "./build-podcast.mjs"; @@ -305,6 +306,8 @@ export function lintManifest(manifest, { // The social posts and the video's URL are not the video's: a problem there // is said, never a refusal (release 29 G2's review). warnings.push(...publishWarnings(whole)); + // Room at the clips' edges (render.room): a fetched window it can reach past. + warnings.push(...roomWindowWarnings(only ? { ...manifest, timeline: (manifest.timeline ?? []).filter((e) => e?.id === only) } : manifest)); for (const { where, src } of imageSrcsOf(manifest, { only })) { if (path.isAbsolute(src) || src.startsWith("~")) { diff --git a/umtool/report-to-video/look.mjs b/umtool/report-to-video/look.mjs @@ -23,6 +23,8 @@ // other #F6F1E6 paper bottom centre (a third voice, or a word heard in no turn) // Black outline (3 px at 1080p), soft shadow. ASS colours are &HAABBGGRR. +import { validateRoom } from "./room.mjs"; + export const CAPTION_STYLES = Object.freeze(["speakers"]); export const CAPTION_SIZES = Object.freeze(["m", "l"]); export const CAPTION_ROLES = Object.freeze(["host", "subject", "other"]); @@ -146,7 +148,8 @@ export function validateVertical(manifest) { /** All of the look's keys: the build's validators and the lint call this. */ export function validateLook(manifest) { - return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest)]; + // render.room and a clip's room (room.mjs, release 36 lane E) are part of the look. + return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest)]; } // --------------------------------------------------------------------------- diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -44,6 +44,7 @@ "./prune-frames": "./prune-frames.mjs", "./render-cards": "./render-cards.mjs", "./resolve-windows": "./resolve-windows.mjs", + "./room": "./room.mjs", "./shoot-page": "./shoot-page.mjs", "./social": "./social.mjs", "./sources": "./sources.mjs", diff --git a/umtool/report-to-video/room-render.test.mjs b/umtool/report-to-video/room-render.test.mjs @@ -0,0 +1,205 @@ +// Room at a clip's edges (render.room, release 36 lane E), rendered for real: +// a clip's sound runs on to the end of its words and is silent after it while +// its picture runs the join's length further; the next clip's picture starts +// a join's length early, muted; the joined cut is the segments' sum less the +// joins, with each clip's sound still on its picture; captions stop at the +// silence point; loudness is measured on what is heard; with no words the +// silence is found in the sound. Absent, null or with neither edge on, the +// render is byte for byte what it was. +// +// 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-room-corpus-")); +process.env.CHANNELS_DIR = CORPUS; + +const { buildVideo, measureLoudness, probeDuration, setProgressMode } = await import("./build-video.mjs"); +const { lintManifest } = await import("./lint.mjs"); +const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs"); + +test.after(() => rm(CORPUS, { recursive: true, force: true })); + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0) + && /\bass\b/.test(String(spawnSync("ffmpeg", ["-hide_banner", "-filters"]).stdout)); +const FPS = 30; +const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" }; +const RENDER = { + width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0.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"; + +// vid1 has cues (one long one); vid2 an empty cue list. +for (const [video, cues] of [["vid1", true], ["vid2", false]]) { + const dir = path.join(CORPUS, CHANNEL, "data", video); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(CORPUS, CHANNEL, "config.json"), JSON.stringify({ name: "Synth" })); + writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: video, title: "Synthetic", duration: 12, uploadDate: "20240102", cues: cues ? [{ start: 0.2, end: 11.8, text: "filler words only and more filler words here" }] : [] })); + writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: video, title: "Synthetic", duration: 12 })); +} + +// c1's words run on past its end (4.0) to 4.75, then a gap; c2's first word +// is 0.05 s after its start (6.0); nothing near c2's end (9.0). +const WORDS = [[1.1, 1.5], [2, 2.4], [3.5, 3.9], [3.95, 4.3], [4.4, 4.75], [5.5, 5.8], [6.05, 6.4], [6.6, 7], [8, 8.5]] + .map(([start, end], i) => ({ w: `w${i}`, start, end })); + +/** + * A project: two clips of `video` (c1 1-4 s, c2 6-9 s), cut from one window + * in out/clips-raw (12 s, a grey picture, a 440 Hz tone -- silent over + * `gap` when given), with reactions.json + words.json for vid1 when `words`. + */ +async function project(render = {}, { video = "vid1", words = true, gap = null, clips = [{}, {}] } = {}) { + const root = mkdtempSync(path.join(os.tmpdir(), "rtv-room-")); + mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); + const raw = path.join(root, "out", "clips-raw", `${video}_0.00-12.00.mp4`); + const vol = gap ? `volume=enable='between(t,${gap[0]},${gap[1]})':volume=0,volume=0.5` : "volume=0.5"; + 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", `[1:a]${vol}[a]`, + "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, + ]); + assert.equal(r.status, 0, String(r.stderr)); + if (words) { + await writeFile(path.join(root, "reactions.json"), JSON.stringify({ + version: 1, + source: { channel: CHANNEL, video, duration: 12, words: "words.json" }, + speakers: [{ index: 0, role: "host", label: "Host", how: "auto" }, { index: 1, role: "subject", label: "Subject", how: "auto" }], + turns: [{ start: 0, end: 12, speaker: 1 }], + laughs: [], moments: [], proposals: [], + })); + await writeFile(path.join(root, "words.json"), JSON.stringify({ words: WORDS })); + } + const manifestPath = path.join(root, "video.manifest.json"); + await writeFile(manifestPath, JSON.stringify({ + slug: "room", title: "Room", + provenance: { channelSlug: CHANNEL, channelsDir: CORPUS }, + render: { ...RENDER, ...render }, + timeline: [ + { type: "clip", id: "c1", channel: CHANNEL, video, start: 1, end: 4, cite: 1, quote: "q", ...clips[0] }, + { type: "clip", id: "c2", channel: CHANNEL, video, start: 6, end: 9, cite: 6, quote: "q", ...clips[1] }, + ], + })); + return { root, manifestPath, raw, 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")); + +/** The RMS of a file's sound over [a, b] (s), mono 8 kHz, 16-bit. */ +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; +} +const LOUD = 1500; +const SILENT = 30; +const near = (a, b, tol, what) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +test("render: without room (absent, null, or neither edge on) the cut is byte for byte the same", { skip: !have && "needs ffmpeg with libass" }, async () => { + quiet(); + const ps = [await project({}), await project({ room: null }), await project({ room: { tail: false, head: false } })]; + try { + for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + for (const f of ["room.mp4", "sourced/segments/c1.mp4", "sourced/segments/c2.mp4", "sourced/segments/c1.cut.json", "sourced/segments/c2.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")).room, undefined); + } finally { + for (const p of ps) await rm(p.root, { recursive: true, force: true }); + } +}); + +test("render: the sound runs to the end of the words and is silent after; the picture runs D + pad past it; a muted head; sum − joins", { skip: !have && "needs ffmpeg with libass" }, async () => { + quiet(); + const p = await project({ room: { tail: true, head: true }, loudness: { target: -16 }, captions: { style: "speakers" } }); + try { + const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + const c1 = await record(p, "c1"); + const c2 = await record(p, "c2"); + // c1: the first clip, so no head; its words run to 4.75; picture to 4.75 + 0.4 + 0.1. + assert.deepEqual([c1.start, c1.end], [1, 5.25]); + assert.deepEqual(c1.room.sound, [1, 4.75]); + assert.equal(c1.room.via, "words.json"); + assert.equal(c1.room.head, 0); + assert.equal(c1.room.tail, 0.5); + // c2: speech 0.05 s after its start -> 0.4 s of muted head; no word near its end. + assert.deepEqual([c2.start, c2.end], [5.6, 9.5]); + assert.deepEqual(c2.room.sound, [6, 9]); + assert.equal(c2.room.head, 0.4); + const d1 = await probeDuration(p.seg("c1"), FPS); + const d2 = await probeDuration(p.seg("c2"), FPS); + near(d1, 4.25, 1 / FPS + 1e-6, "c1's length"); + near(d2, 3.9, 1 / FPS + 1e-6, "c2's length"); + // The tail: heard to the silence point (3.75 s into c1), silent after it. + assert.ok(rms(p.seg("c1"), 3.2, 3.7) > LOUD, "c1 heard before the silence point"); + assert.ok(rms(p.seg("c1"), 3.85, 4.2) < SILENT, `c1 silent after it: ${rms(p.seg("c1"), 3.85, 4.2)}`); + // The head: silent until the cut's start (0.4 s into c2), heard after. + assert.ok(rms(p.seg("c2"), 0, 0.33) < SILENT, "c2's head muted"); + assert.ok(rms(p.seg("c2"), 0.45, 1) > LOUD, "c2 heard from its cut"); + // Loudness measured on what is heard. + near(await measureLoudness(p.seg("c1"), 0, 3.7), -16, 0.6, "c1's audible loudness"); + // Captions stop at the silence point: c1's last line ends by 3.75 s. + const ass = await readFile(p.seg("c1").replace(/\.mp4$/, ".captions.ass"), "utf8"); + const ends = ass.split("\n").filter((l) => l.startsWith("Dialogue:")).map((l) => { + const [h, m, s] = l.split(",")[2].split(":").map(Number); + return h * 3600 + m * 60 + s; + }); + assert.ok(ends.length > 0 && Math.max(...ends) <= 3.751, `caption ends ${ends}`); + // The cut: the sum less one join; the join plays over silence; c2's sound on its picture. + const total = await probeDuration(r.out, FPS); + near(total, d1 + d2 - 0.4, 2 / FPS, "the cut's length"); + const join = d1 - 0.4; // c2 starts here in the cut + assert.ok(rms(r.out, join + 0.02, d1 - 0.1) < SILENT, "the join is quiet"); + assert.ok(rms(r.out, join + 0.5, join + 1) > LOUD, "c2 heard from its cut, in the cut"); + assert.ok(rms(r.out, 2.5, 3.6) > LOUD, "c1 heard in the cut"); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("render: no words -- the silence is found in the sound; a clip's room: false keeps its edge", { skip: !have && "needs ffmpeg with libass" }, async () => { + quiet(); + // vid2 has no cues and no words file; its tone is silent 4.6-5.6 s. + const p = await project({ room: { tail: true, head: true } }, { video: "vid2", words: false, gap: [4.6, 5.6], clips: [{}, { room: false }] }); + try { + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + const c1 = await record(p, "c1"); + assert.equal(c1.room.via, "silence"); + near(c1.room.sound[1], 4.6, 0.05, "c1's sound stops where the silence starts"); + near(c1.end, c1.room.sound[1] + 0.5, 0.002, "and its picture 0.5 s later"); + const c2 = await record(p, "c2"); + assert.equal(c2.room, undefined); + assert.deepEqual([c2.start, c2.end], [6, 9]); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("the lint: a fetched window the room can reach past; validators refuse a bad room", () => { + const m = { + slug: "x", title: "x", provenance: { channelSlug: CHANNEL }, render: { ...RENDER, fetchPad: 1, room: { tail: true } }, + timeline: [{ type: "clip", id: "c1", video: "v", start: 1, end: 4 }], + }; + const lint = lintManifest(m, { manifestDir: os.tmpdir() }); + assert.ok(lint.warnings.some((w) => /c1: its room can run 3 s past the cut but a fetched window ends 1 s after it/.test(w)), lint.warnings.join("; ")); + const bad = lintManifest({ ...m, render: { ...m.render, room: { tail: "yes" } } }, { manifestDir: os.tmpdir() }); + assert.ok(bad.errors.some((x) => /render\.room\.tail must be true or false/.test(x)), bad.errors.join("; ")); +}); diff --git a/umtool/report-to-video/room.mjs b/umtool/report-to-video/room.mjs @@ -0,0 +1,283 @@ +// ROOM AT A CLIP'S EDGES (release 36 lane E): a join plays over quiet picture, +// never over the end of a sentence or the start of the next one. +// +// render.room {tail?: true, head?: true, minGap?: 0.35, maxS?: 2.5} +// clip.room false (no room for this clip), or {tail?: boolean, head?: boolean} +// (that edge for this clip, whatever the cut says) +// +// An edge is on when its key is `true` (the clip's key, else the cut's). +// Absent (or null, or neither edge on) = off, and the render is byte for byte +// what it was. Room needs a join: with `render.transition` 0 (or a montage, +// or a short) it does nothing. +// +// THE RULE, in the source's seconds (D = render.transition): +// +// TAIL From the cut's end, the SOUND runs on to the first silence: the end +// of the run of words that crosses the cut's end or starts within +// `minGap` after it, the run stopping at the first gap between two +// words of at least `minGap`; never more than `maxS` past the cut's +// end. A 60 ms fade starts there. The PICTURE then keeps going, muted, +// for D + 0.1 s, so the join's D seconds lie wholly over quiet video. +// HEAD When speech starts within D of the cut's start (a word crosses it or +// begins less than D after it), the picture starts D earlier, muted, +// and the sound fades in over the 60 ms that end at the cut's start. +// Only when something comes before the clip in the cut. +// +// The words: the project's words.json when the clip is from the recording +// reactions.json describes, else the corpus transcript's whisper words, +// else the cues spread over their words. When there are none -- or the +// cues' run reaches the cap, which says the cues abut rather than that +// anyone talks on -- silencedetect on the source (-35 dB, 0.3 s): the +// silence the cut's end is in (the sound stops there), else the next one +// to start within maxS; no silence found leaves the sound at the cut's end. +// +// Every extension stays inside the file the clip is cut from: a saved +// whole video has room to spare, a fetched window (the extent plus the +// fetch pad) clamps it -- the build says so, and the lint warns when the +// room can reach past the window. + +export const ROOM = Object.freeze({ + /** A gap between two words this long (s) is the silence the sound stops at. */ + minGap: 0.35, + /** The sound never runs more than this (s) past the cut's end. */ + maxS: 2.5, + /** The fade at the silence point, and the fade in at a muted head (s). */ + fade: 0.06, + /** Muted picture past D, so the fade is done before the join begins (s). */ + pad: 0.1, + /** silencedetect, when there are no words: noise floor (dB) and least length (s). */ + detectDb: -35, + detectD: 0.3, +}); +export const ROOM_EDGES = Object.freeze(["tail", "head"]); +const MIN_GAP = [0.1, 2]; +const MAX_S = [0, 10]; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const num = (v) => typeof v === "number" && Number.isFinite(v); +const q = (v) => JSON.stringify(v); +const r3 = (n) => Math.round(n * 1000) / 1000; + +/** Does the cut's render block turn room on for either edge? */ +export const roomOn = (render) => isObj(render?.room) && (render.room.tail === true || render.room.head === true); + +/** + * One clip's room: `{tail, head, minGap, maxS}` with at least one edge on, or + * null. The clip's `room` (false, or per-edge booleans) beats the cut's. + */ +export function clipRoom(entry, render) { + const r = isObj(render?.room) ? render.room : null; + const c = entry?.room; + if (c === false) return null; + const edge = (k) => (isObj(c) && typeof c[k] === "boolean" ? c[k] : r?.[k] === true); + const tail = edge("tail"); + const head = edge("head"); + if (!tail && !head) return null; + return { + tail, + head, + minGap: num(r?.minGap) ? r.minGap : ROOM.minGap, + maxS: num(r?.maxS) ? r.maxS : ROOM.maxS, + }; +} + +/** `render.room` and every clip's `room`: each problem in a sentence naming the key. */ +export function validateRoom(manifest) { + const render = manifest?.render ?? {}; + const errors = []; + const room = render.room; + if (room !== undefined && room !== null) { + if (!isObj(room)) errors.push(`render.room must be an object ({tail: true, head: true}) or absent, not ${q(room)}`); + else { + for (const k of Object.keys(room)) { + if (!["tail", "head", "minGap", "maxS"].includes(k)) errors.push(`render.room.${k} is not a setting here (tail, head, minGap, maxS)`); + } + for (const k of ROOM_EDGES) { + if (room[k] !== undefined && typeof room[k] !== "boolean") errors.push(`render.room.${k} must be true or false, not ${q(room[k])}`); + } + if (room.minGap !== undefined && (!num(room.minGap) || room.minGap < MIN_GAP[0] || room.minGap > MIN_GAP[1])) { + errors.push(`render.room.minGap must be seconds from ${MIN_GAP[0]} to ${MIN_GAP[1]}, not ${q(room.minGap)}`); + } + if (room.maxS !== undefined && (!num(room.maxS) || room.maxS < MAX_S[0] || room.maxS > MAX_S[1])) { + errors.push(`render.room.maxS must be seconds from ${MAX_S[0]} to ${MAX_S[1]}, not ${q(room.maxS)}`); + } + if (render.montage !== undefined && render.montage !== null) errors.push("render.room does not combine with render.montage (a montage cuts to its phrases)"); + } + } + (manifest?.timeline ?? []).forEach((e, i) => { + if (e?.room === undefined) return; + const who = `timeline[${i}] (${e?.id ?? "?"}).room`; + if (e?.type !== "clip") errors.push(`${who}: only a clip has room at its edges`); + else if (e.room === false || e.room === null) return; + else if (!isObj(e.room)) errors.push(`${who} must be false or {tail?, head?}, not ${q(e.room)}`); + else { + for (const [k, v] of Object.entries(e.room)) { + if (!ROOM_EDGES.includes(k)) errors.push(`${who}.${k} is not a setting here (tail, head)`); + else if (typeof v !== "boolean") errors.push(`${who}.${k} must be true or false, not ${q(v)}`); + } + } + }); + return errors; +} + +/** Timed words, in time order (any of the transcribers' keys for the text is fine; only times are read). */ +function timed(words) { + return (Array.isArray(words) ? words : []) + .map((w) => ({ start: Number(w?.start), end: Number(w?.end) })) + .filter((w) => Number.isFinite(w.start) && Number.isFinite(w.end) && w.end >= w.start) + .sort((a, b) => a.start - b.start); +} + +/** + * Where a clip's SOUND stops, from its words: the end of the run of words + * that crosses `cutEnd` or starts within `minGap` after it, the run ending at + * the first gap of at least `minGap`; never more than `maxS` past `cutEnd`. + * `cutEnd` itself when no word is in reach. + * + * @returns {{ at: number, extended: boolean, capped: boolean }} + */ +export function tailFromWords(words, cutEnd, { minGap = ROOM.minGap, maxS = ROOM.maxS } = {}) { + const ws = timed(words); + const i = ws.findIndex((w) => w.end > cutEnd); + if (i < 0 || ws[i].start >= cutEnd + minGap) return { at: cutEnd, extended: false, capped: false }; + let end = ws[i].end; + for (let j = i + 1; j < ws.length; j += 1) { + if (ws[j].start - end >= minGap) break; + end = Math.max(end, ws[j].end); + } + const cap = cutEnd + maxS; + return { at: r3(Math.min(end, cap)), extended: end > cutEnd, capped: end > cap }; +} + +/** Where speech starts at a clip's head, from its words: the first word not over before `cutStart` (Infinity: none). */ +export function speechStartFromWords(words, cutStart) { + const w = timed(words).find((x) => x.end > cutStart); + return w ? Math.max(cutStart, w.start) : Infinity; +} + +/** + * The same two answers from silences (`[{s, e}]`, silencedetect's), when + * there are no words: the sound stops at `cutEnd` when it is in a silence, + * else where the next silence within `maxS` begins; no silence in reach + * leaves it at `cutEnd` (nothing says where the speech ends). + * + * @returns {{ at: number, extended: boolean, capped: boolean, found: boolean }} + */ +export function tailFromSilences(silences, cutEnd, { maxS = ROOM.maxS } = {}) { + const sil = (Array.isArray(silences) ? silences : []).filter((x) => num(x?.s) && num(x?.e)).sort((a, b) => a.s - b.s); + if (sil.some((x) => x.s <= cutEnd && x.e > cutEnd)) return { at: cutEnd, extended: false, capped: false, found: true }; + const next = sil.find((x) => x.s > cutEnd && x.s <= cutEnd + maxS); + if (!next) return { at: cutEnd, extended: false, capped: false, found: false }; + return { at: r3(next.s), extended: true, capped: false, found: true }; +} + +/** Where speech starts at a clip's head, from silences: the end of the silence `cutStart` is in, else `cutStart`. */ +export function speechStartFromSilences(silences, cutStart) { + const hit = (Array.isArray(silences) ? silences : []).find((x) => num(x?.s) && num(x?.e) && x.s <= cutStart && x.e > cutStart); + return hit ? hit.e : cutStart; +} + +/** + * The segment a clip with room plays, in the seconds of the file it is cut + * from (`cutA`/`cutB`: the snapped cut; `soundEnd`: tailFromWords' or + * tailFromSilences' `at`, or null with the tail off; `speechStart`: where + * speech begins, or null with the head off; `duration`: the file's length, + * when known). The picture is [picA, picB]; the sound is heard over + * [cutA, soundB] (muted before and after, with the fades). + * + * @returns {{ picA: number, picB: number, soundA: number, soundB: number, head: number, tail: number, + * clamped: Array<"head" | "tail"> }} head/tail: the muted seconds before cutA / after soundB + */ +export function roomPlan({ cutA, cutB, D, soundEnd = null, speechStart = null, duration = null }) { + const len = num(duration) && duration > 0 ? duration : Infinity; + const clamped = []; + let picA = cutA; + if (speechStart !== null && speechStart < cutA + D) { + picA = cutA - D; + if (picA < 0) { + picA = 0; + clamped.push("head"); + } + } + let soundB = soundEnd === null ? cutB : Math.max(cutB, soundEnd); + let picB = soundEnd === null ? cutB : soundB + D + ROOM.pad; + if (picB > len) { + picB = len; + soundB = Math.min(soundB, len); + clamped.push("tail"); + } + picA = r3(picA); + picB = r3(picB); + soundB = r3(soundB); + return { picA, picB, soundA: cutA, soundB, head: r3(cutA - picA), tail: r3(picB - soundB), clamped }; +} + +/** + * The sound's filters for a plan, in the segment's own clock (0 = picA): a + * fade in ending at the cut's start when the head is muted, a fade out from + * the silence point when the tail is. "" when neither edge moved. + */ +export function roomAudioFilter(plan, { fade = ROOM.fade } = {}) { + const parts = []; + if (plan.head > 0) parts.push(`afade=t=in:st=${Math.max(0, plan.head - fade).toFixed(3)}:d=${fade}`); + if (plan.picB > plan.soundB) parts.push(`afade=t=out:st=${(plan.soundB - plan.picA).toFixed(3)}:d=${fade}`); + return parts.join(","); +} + +/** + * What the clip editor's strip shades for one clip (its unsnapped cut, the + * neighbourhood's words or cues): the muted head [a, b] and the muted tail + * [soundEnd, end], each null when that edge is off or does not move. The + * build snaps the cut first, so this is the rule on the cut as drawn. + * + * @param {{ cutStart: number, cutEnd: number, room: { tail: boolean, head: boolean, minGap?: number, maxS?: number } | null, + * D: number, words?: Array<{ start: number, end: number }> | null, cues?: Array<{ start: number, end: number }> | null }} o + * @returns {{ head: number[] | null, tail: number[] | null, soundEnd: number | null }} + */ +export function roomShade({ cutStart, cutEnd, room, D, words = null, cues = null }) { + if (!room || !(D > 0)) return { head: null, tail: null, soundEnd: null }; + const ws = Array.isArray(words) && words.length ? words : Array.isArray(cues) ? cues : []; + let tail = null; + let soundEnd = null; + if (room.tail) { + soundEnd = ws.length ? tailFromWords(ws, cutEnd, room).at : cutEnd; + tail = [soundEnd, r3(soundEnd + D + ROOM.pad)]; + } + let head = null; + if (room.head && (!ws.length || speechStartFromWords(ws, cutStart) < cutStart + D)) head = [r3(Math.max(0, cutStart - D)), cutStart]; + return { head, tail, soundEnd }; +} + +/** + * The lint's word on a clip's room: a fetched window (the extent plus the + * fetch pad) that the room can reach past -- the build clamps it there; a + * saved whole video would not. + */ +export function roomWindowWarnings(manifest) { + const render = manifest?.render ?? {}; + const D = render.transition ?? 0.5; + const out = []; + const timeline = manifest?.timeline ?? []; + const anyRoom = timeline.some((e) => e?.type === "clip" && clipRoom(e, render)); + if (!anyRoom) return out; + if (!(D > 0)) { + out.push("render.room: the cut has no transition (render.transition 0), so there is no join to make room for -- room does nothing"); + return out; + } + const pad = render.fetchPad ?? 3.0; + for (const e of timeline) { + if (e?.type !== "clip") continue; + const room = clipRoom(e, render); + if (!room || !num(e.start) || !num(e.end)) continue; + const cutStart = num(e.cutStart) ? e.cutStart : e.start; + const cutEnd = num(e.cutEnd) ? e.cutEnd : e.end; + const reach = cutEnd + room.maxS + D + ROOM.pad; + if (room.tail && reach > e.end + pad + 1e-6) { + out.push(`${e.id}: its room can run ${r3(reach - cutEnd)} s past the cut but a fetched window ends ${r3(e.end + pad - cutEnd)} s after it -- a fetched source clamps the tail there (a saved whole video does not)`); + } + if (room.head && cutStart - D < Math.max(0, e.start - pad) - 1e-6) { + out.push(`${e.id}: its muted head (${D} s) starts before a fetched window does -- a fetched source clamps it`); + } + } + return out; +} diff --git a/umtool/report-to-video/room.test.mjs b/umtool/report-to-video/room.test.mjs @@ -0,0 +1,128 @@ +// Room at a clip's edges (room.mjs, release 36 lane E): the silence rule on +// synthetic words and silences, the plan, the sound's filters, the +// validators, the strip's shading and the lint's window warning. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + ROOM, clipRoom, roomAudioFilter, roomOn, roomPlan, roomShade, roomWindowWarnings, speechStartFromSilences, + speechStartFromWords, tailFromSilences, tailFromWords, validateRoom, +} from "./room.mjs"; + +/** Words at the given [start, end] pairs. */ +const W = (...pairs) => pairs.map(([start, end], i) => ({ w: `w${i}`, start, end })); + +test("tailFromWords: a cut through a word runs to the end of its run, stopping at the first gap of minGap", () => { + // 10.0 cuts "w1" (9.8-10.2); w2 follows 0.1 s later; then a 0.5 s gap. + const words = W([9.0, 9.5], [9.8, 10.2], [10.3, 10.9], [11.4, 11.8]); + assert.deepEqual(tailFromWords(words, 10.0), { at: 10.9, extended: true, capped: false }); +}); + +test("tailFromWords: a word starting within minGap after the cut belongs to the run; one starting later does not", () => { + assert.equal(tailFromWords(W([9, 9.9], [10.2, 10.6]), 10.0).at, 10.6); + assert.deepEqual(tailFromWords(W([9, 9.9], [10.5, 10.9]), 10.0), { at: 10.0, extended: false, capped: false }); + // A narrower minGap: the same word is out of reach. + assert.equal(tailFromWords(W([9, 9.9], [10.2, 10.6]), 10.0, { minGap: 0.15 }).at, 10.0); +}); + +test("tailFromWords: the cap -- never more than maxS past the cut", () => { + const words = []; + for (let t = 9.8; t < 16; t += 0.3) words.push({ start: t, end: t + 0.25 }); + assert.deepEqual(tailFromWords(words, 10.0), { at: 12.5, extended: true, capped: true }); + assert.equal(tailFromWords(words, 10.0, { maxS: 1 }).at, 11.0); +}); + +test("tailFromWords: no words at all leaves the sound at the cut", () => { + assert.deepEqual(tailFromWords([], 10), { at: 10, extended: false, capped: false }); + assert.deepEqual(tailFromWords(null, 10), { at: 10, extended: false, capped: false }); +}); + +test("silences (no words): in a silence the sound stops at the cut; else at the next silence within maxS; none found, at the cut", () => { + const sil = [{ s: 4, e: 4.6 }, { s: 11.2, e: 11.9 }]; + assert.deepEqual(tailFromSilences(sil, 4.2), { at: 4.2, extended: false, capped: false, found: true }); + assert.deepEqual(tailFromSilences(sil, 10.0), { at: 11.2, extended: true, capped: false, found: true }); + assert.deepEqual(tailFromSilences(sil, 6.0), { at: 6.0, extended: false, capped: false, found: false }); + assert.equal(speechStartFromSilences(sil, 4.1), 4.6); + assert.equal(speechStartFromSilences(sil, 5), 5); +}); + +test("speechStartFromWords: the first word not over before the cut's start", () => { + const words = W([1, 1.4], [2.1, 2.5], [2.6, 3]); + assert.equal(speechStartFromWords(words, 2.0), 2.1); + assert.equal(speechStartFromWords(words, 2.2), 2.2); + assert.equal(speechStartFromWords(words, 5), Infinity); +}); + +test("roomPlan: the picture runs D + pad past the silence point; a head starts D early; both clamped into the file", () => { + const p = roomPlan({ cutA: 2, cutB: 6, D: 0.4, soundEnd: 6.8, speechStart: 2.1, duration: 20 }); + assert.deepEqual(p, { picA: 1.6, picB: 7.3, soundA: 2, soundB: 6.8, head: 0.4, tail: 0.5, clamped: [] }); + // Speech starts later than D after the cut: no head. + assert.equal(roomPlan({ cutA: 2, cutB: 6, D: 0.4, soundEnd: null, speechStart: 2.5, duration: 20 }).picA, 2); + // A window that ends early clamps the tail; one that starts late clamps the head. + const c = roomPlan({ cutA: 0.2, cutB: 6, D: 0.4, soundEnd: 6.8, speechStart: 0.2, duration: 7 }); + assert.equal(c.picA, 0); + assert.equal(c.picB, 7); + assert.deepEqual(c.clamped, ["head", "tail"]); + // Tail off: the cut's own end. + assert.equal(roomPlan({ cutA: 2, cutB: 6, D: 0.4, soundEnd: null, speechStart: null }).picB, 6); +}); + +test("roomAudioFilter: a fade in ending at the cut, a fade out from the silence point, in the segment's clock", () => { + const p = roomPlan({ cutA: 2, cutB: 6, D: 0.4, soundEnd: 6.8, speechStart: 2.1, duration: 20 }); + assert.equal(roomAudioFilter(p), `afade=t=in:st=0.340:d=${ROOM.fade},afade=t=out:st=5.200:d=${ROOM.fade}`); + assert.equal(roomAudioFilter(roomPlan({ cutA: 2, cutB: 6, D: 0.4 })), ""); +}); + +test("clipRoom / roomOn: an edge is on when its key is true; a clip's room beats the cut's", () => { + const render = { room: { tail: true, head: true } }; + assert.equal(roomOn({}), false); + assert.equal(roomOn({ room: {} }), false); + assert.equal(roomOn(render), true); + assert.deepEqual(clipRoom({}, render), { tail: true, head: true, minGap: ROOM.minGap, maxS: ROOM.maxS }); + assert.equal(clipRoom({ room: false }, render), null); + assert.deepEqual(clipRoom({ room: { tail: false } }, render), { tail: false, head: true, minGap: 0.35, maxS: 2.5 }); + assert.equal(clipRoom({ room: { tail: false, head: false } }, render), null); + assert.deepEqual(clipRoom({ room: { tail: true } }, {}), { tail: true, head: false, minGap: 0.35, maxS: 2.5 }); + assert.equal(clipRoom({}, { room: { tail: true, minGap: 0.5, maxS: 1 } }).maxS, 1); + assert.equal(clipRoom({}, {}), null); +}); + +test("validateRoom: absent or null says nothing; each problem in a sentence naming the key", () => { + const m = (room, timeline = [], extra = {}) => ({ render: { room, ...extra }, timeline }); + assert.deepEqual(validateRoom(m(undefined)), []); + assert.deepEqual(validateRoom(m(null)), []); + assert.deepEqual(validateRoom(m({ tail: true, head: true, minGap: 0.35, maxS: 2.5 })), []); + assert.match(validateRoom(m(true))[0], /render\.room must be an object/); + assert.match(validateRoom(m({ tail: "yes" }))[0], /render\.room\.tail must be true or false/); + assert.match(validateRoom(m({ tail: true, pad: 1 }))[0], /render\.room\.pad is not a setting here/); + assert.match(validateRoom(m({ tail: true, minGap: 5 }))[0], /render\.room\.minGap must be seconds from 0\.1 to 2/); + assert.match(validateRoom(m({ tail: true, maxS: -1 }))[0], /render\.room\.maxS must be seconds from 0 to 10/); + assert.match(validateRoom(m({ tail: true }, [], { montage: {} }))[0], /does not combine with render\.montage/); + const clip = (room) => ({ type: "clip", id: "c1", room }); + assert.deepEqual(validateRoom(m(undefined, [clip(false), clip({ tail: false })])), []); + assert.match(validateRoom(m(undefined, [clip("off")]))[0], /timeline\[0\] \(c1\)\.room must be false or/); + assert.match(validateRoom(m(undefined, [clip({ middle: true })]))[0], /\.room\.middle is not a setting here/); + assert.match(validateRoom(m(undefined, [{ type: "card", id: "k", room: false }]))[0], /only a clip has room/); +}); + +test("roomShade: the strip's muted head and tail, from the words; nothing with room off or no join", () => { + const room = clipRoom({}, { room: { tail: true, head: true } }); + const words = W([2.05, 2.4], [5.6, 6.1], [6.2, 6.7], [7.5, 8]); + assert.deepEqual(roomShade({ cutStart: 2, cutEnd: 6, room, D: 0.4, words }), { head: [1.6, 2], tail: [6.7, 7.2], soundEnd: 6.7 }); + assert.deepEqual(roomShade({ cutStart: 2, cutEnd: 6, room: null, D: 0.4, words }), { head: null, tail: null, soundEnd: null }); + assert.deepEqual(roomShade({ cutStart: 2, cutEnd: 6, room, D: 0, words }), { head: null, tail: null, soundEnd: null }); + // No words: the nominal room. + assert.deepEqual(roomShade({ cutStart: 2, cutEnd: 6, room, D: 0.4 }), { head: [1.6, 2], tail: [6, 6.5], soundEnd: 6 }); +}); + +test("roomWindowWarnings: room that can reach past a fetched window; no transition", () => { + const clip = { type: "clip", id: "c1", video: "v", start: 10, end: 20, cutStart: 10, cutEnd: 20 }; + assert.deepEqual(roomWindowWarnings({ render: { transition: 0.4 }, timeline: [clip] }), []); + assert.deepEqual(roomWindowWarnings({ render: { transition: 0.4, room: { tail: true, head: true } }, timeline: [clip] }), []); + const w = roomWindowWarnings({ render: { transition: 0.4, fetchPad: 1, room: { tail: true } }, timeline: [clip] }); + assert.equal(w.length, 1); + assert.match(w[0], /c1: its room can run 3 s past the cut but a fetched window ends 1 s after it/); + assert.match(roomWindowWarnings({ render: { transition: 0, room: { tail: true } }, timeline: [clip] })[0], /room does nothing/); +});