Archilyzer · Source

archilyzer

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

commit fac655eba798ac8197b02d73cfd1c75dedfd56b3
parent 2b1b60819e4b00eb4628f994451082af3a748ecc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 16:22:30 -0500

Merge lane/video-entry: a video timeline entry -- a project file played full frame (fit contain|cover) from/to with its own sound (audio.bass, audio.gain; levelled to the cut, limited), no chrome over it by default, entered by a fade (the item before and its chrome to black, the video up), the cut ending on its last frame when it is last; render and Play; umtool timeline <p> [--take <t>] add-video <src> … | set-video <id> … (operator, 5 Nov: "splice the end of that video as the end of ours … End on the final frame"; "amp the bass sound a bit to make it sillier"; "cut off all the chrome and play it full screen"; "fade out from the chrome and in to it")

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Mumtool/components/projects/review/PlayCut.tsx | 39++++++++++++++++++++++++++++++++++++++-
Aumtool/components/projects/review/VideoEntryPlayer.tsx | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/playEngine/elementPicture.ts | 3+++
Mumtool/components/projects/review/playEngine/engine.ts | 11+++++++++++
Mumtool/components/projects/review/playEngine/usePlayEngine.ts | 3++-
Mumtool/docs/cli.md | 1+
Mumtool/docs/knobs.md | 17+++++++++++++++++
Mumtool/docs/report-video.md | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/video-entry-fixture.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/video-entry.spec.ts | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 27+++++++++++++++++++++++++++
Aumtool/lib/report/playVideo.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/playVideo.test.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playView.mjs | 36++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeEdit.mjs | 27+++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 3+++
Mumtool/lib/report/timelineCli.mjs | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/build-video.mjs | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mumtool/report-to-video/clip-audio.mjs | 3++-
Mumtool/report-to-video/deck.mjs | 10++++++++++
Mumtool/report-to-video/lint.mjs | 3++-
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/video-entry.mjs | 330+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/video-entry.test.mjs | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
26 files changed, 1339 insertions(+), 21 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **umtool: a report video can end on a video of the project, full frame, with its own sound.** A meme the subject posted (the Puss in Boots clip of the Mr. Obvious cut) could not be played as itself: `image` is a still and a clip is a corpus window inside the deck. A `video` timeline entry plays a project file's span (`from`, `to`; absent: the file's end) as the whole frame (`fit: contain`, pillarboxed on black, or `cover`), with NOTHING drawn over it -- no deck, header, QR, rail, counters, captions or any overlay layer, in the render and in Play. The item before it (its chrome too) fades to black and the video fades up (`enter`, 0.5 s each; `"cut"` opts out), without shortening the video; as the last entry the cut ends on its final frame (no end fade). Its sound is levelled like a clip's, with an optional bass boost before the level (`audio.bass`, dB). `umtool timeline <p> [--take <t>] add-video <src> --from 32.26 --bass 8` adds one; `set-video <id> key=value` sets its knobs. - **`posts reread --pause "@71.2=0.45"`: a pause at a time of the take.** A read whose word timings drift (a script word said as several -- "45" as "forty-five") put a word-named pause inside the next word. `@<seconds>` names the time instead; the cut is the quietest point within 0.15 s of it, kept on later re-cuts. - **umtool: a slur can be masked by its first and last letter, so its form is told apart.** The slur filter's pill showed one mask per slur for every form ("n*****" for the "-a" form as for the "-er" one). `umtool posts slurs <p> edges <word>` (a slur's word, id or any form names it; `--off` takes it back) now masks every form of that slur as its first letter, stars and its last letter, in the case the post wrote it -- "n***a", "n****s", "f****t", "f*****s", "N***A" (`render.posts.slurs.edges`). The one mask per word is what the card's pill, Play, the bench, a chapter line, a caption and `posts slurs ls` show (`ls` says `edges: …`, by mask); the Cut tab's Options → Reads and voices → Slur filter has **Edge mask** and **First letter only** beside a word. A cut without `edges` renders exactly as before; the read's stand-in ("n-word") is unchanged. - **A reply that is only a video with sound now plays its sound, and plays to its end.** A picture-only reply whose attachment is a video with audio (the "It's time to stop" meme from its original upload) used to play silent, cut to 4 s. Now its sound plays through its beat before the reply is read, mixed like any attachment's sound and never ducked under the read. The beat lasts the whole clip, up to 8 s. Play unmutes it on its own clock during the beat. A GIF stays silent, and the same post carried up as context shows a still with no sound. The cut's picture-only rule now has a command: `umtool posts picture-reply <p> [on=] [image=] [min=] [max=] [maxSound=] [--in-take <take>]`. diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -32,6 +32,8 @@ import { AddClipToggle } from "../AddClip"; import { Options, PanelSlot } from "@/components/ui/disclosure"; import PostItemPlayer, { postItemAssets, type PostPlan } from "./PostItemPlayer"; import SidePostOverlay from "./SidePostOverlay"; +import VideoEntryPlayer from "./VideoEntryPlayer"; +import { videoStageAt, type VideoEntryPlay } from "@/lib/report/playVideo.mjs"; import ComboBadge, { type ComboInfo } from "./ComboBadge"; // --------------------------------------------------------------------------- @@ -134,6 +136,8 @@ export type PlayEntry = { postCombo?: ComboInfo; /** Its media scene (post-media-scene.mjs): which, its place in it, its items, the anchor. */ postScene?: { key: string; n: number; of: number; ids: string[]; anchor: string }; + /** A VIDEO entry (video-entry.mjs, lib/report/playView.mjs videoPlayEntry): a file of the project, full frame. */ + videoEntry?: VideoEntryPlay; }; export type PlayViewData = { @@ -376,6 +380,7 @@ export default function PlayCut({ } }, []); const hasPosts = useMemo(() => view.entries.some((e) => e.type === "post"), [view.entries]); + const hasVideoEntries = useMemo(() => view.entries.some((e) => e.type === "video" && !!e.videoEntry), [view.entries]); useEffect(() => { try { // The URL first (Back from the bench lands on the URL Play left), then this browser's choice. @@ -445,6 +450,7 @@ export default function PlayCut({ plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring", gate, }); const { ui, rate, failed, now } = engine; + const setDuck = engine.setDuck; const setRate = engine.setRate; // `?clip=&at=` (back from the clip bench): that clip, that far in -- the @@ -878,7 +884,15 @@ export default function PlayCut({ const broken = !!item && !!failed[item.id]; // A post item plays its card and attachments (PostItemPlayer), not a placeholder. const postNow = item && entry?.type === "post" && entry.post && entry.postPlan ? { item, entry } : null; - const placeholder = item && !postNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null; + // A VIDEO entry (lib/report/playVideo.mjs): its file, the whole frame -- and the item before it darkening into it. + const vstage = hasVideoEntries ? videoStageAt(plan, entryOf, t) : null; + const videoNow = vstage?.video ? { ...vstage, video: vstage.video } : null; + const placeholder = item && !postNow && !videoNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null; + // The clips' sound fades with the picture into a video entry and is off over it (its element plays its own). + const duck = vstage ? vstage.duck : 1; + useEffect(() => { + if (hasVideoEntries) setDuck(duck); + }, [hasVideoEntries, duck, setDuck]); const pct = (n: number, of: number) => `${(n / of) * 100}%`; // A clip's side post (lane vertical): its card over the clip for the side's span (SidePostOverlay). const sideEntry = item && entry?.type === "clip" ? (entry as { side?: { from: number; to: number; place?: string | null } }).side : undefined; @@ -975,6 +989,23 @@ export default function PlayCut({ playing={ui.playing && !ui.waiting} /> ) : null; + // The video on screen: over EVERYTHING when the chrome is off over it (the default), else as the footage under it. + const videoPlayer = videoNow ? ( + <VideoEntryPlayer + key={videoNow.id} + project={project} + id={videoNow.id} + video={videoNow.video} + src={videoNow.src ?? videoNow.video.from} + opacity={videoNow.opacity} + run={ui.playing && !ui.waiting && videoNow.playing} + speed={rate} + /> + ) : null; + const videoOver = videoNow?.video.noChrome ? <div className="pointer-events-none absolute inset-0 z-30">{videoPlayer}</div> : null; + const videoUnder = videoNow && !videoNow.video.noChrome ? videoPlayer : null; + // The item before a video entry, darkening into it: the whole stage, its chrome with it. + const dipVeil = vstage && vstage.dark > 0 ? <div data-play-dip={vstage.id} className="pointer-events-none absolute inset-0 z-30 bg-black" style={{ opacity: vstage.dark }} /> : null; const placeholderCard = placeholder ? ( <div data-play-placeholder={placeholder.kind} @@ -1061,6 +1092,8 @@ export default function PlayCut({ data-play-state={ui.ended ? "ended" : ui.playing ? (ui.waiting ? "waiting" : "playing") : "paused"} data-play-t={String(Math.round(t * 100) / 100)} data-play-item={item?.id ?? ""} + // A video entry with the chrome off over it is on screen (video-entry.mjs): nothing of the deck shows. + data-play-chrome={videoNow?.video.noChrome ? "off" : undefined} data-play-compose={composeState} data-play-edges={edges.state} data-play-sound={engine.info?.sound ?? ""} @@ -1122,6 +1155,7 @@ export default function PlayCut({ <DeckFrame preview={doc} t={tc} texts={{}} testid="play-deck"> <div className="absolute inset-0" style={{ background: bg }} /> {footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)} + {videoUnder} {postNow && rect && ( <div className="absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H), background: bg }}> {postPlayer({ width: box.width, height: box.height })} @@ -1145,10 +1179,13 @@ export default function PlayCut({ <div className="relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0" style={{ aspectRatio: "16 / 9" }} data-testid="play-plain"> {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)} {postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>} + {videoUnder} {placeholderCard} {sideNow} </div> )} + {dipVeil} + {videoOver} {ui.playing && ui.waiting && ( // The clock held (engine.ts): a clip's sound decoding, a post item loading -- it plays in full once here. <span data-play-loading="" className="pointer-events-none absolute right-2 top-2 z-40 rounded-full bg-black/70 px-2 py-0.5 text-[11px] text-white"> diff --git a/umtool/components/projects/review/VideoEntryPlayer.tsx b/umtool/components/projects/review/VideoEntryPlayer.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { useEffect, useRef } from "react"; +import type { VideoEntryPlay } from "@/lib/report/playVideo.mjs"; + +// A VIDEO entry in Play (report-to-video/video-entry.mjs; lib/report/playVideo.mjs +// says what the stage shows when): the project's file in a <video>, the whole +// frame on black, letter/pillarboxed (`fit: "contain"`) or filling it +// (`"cover"`), slaved to Play's clock -- re-seeked when it drifts, at Play's +// speed, its pitch kept -- and unmuted while it plays. Its bass (and gain) go +// through a Web Audio low shelf at 100 Hz, as the render's `bass` filter does, +// once the page's audio context runs; without one the element plays its sound +// as it is. + +/** How far the element may drift from Play's clock before it is re-seeked (times the speed, above 1x). */ +const DRIFT = 0.3; + +let audioCtx: AudioContext | null = null; +const wired = new WeakMap<HTMLMediaElement, { shelf: BiquadFilterNode; gain: GainNode }>(); + +/** The element through a low shelf and a gain (wired once: createMediaElementSource takes it for good). */ +function shelfGraph(el: HTMLMediaElement, bass: number, gainDb: number) { + let g = wired.get(el); + if (!g) { + if (typeof window === "undefined" || typeof window.AudioContext === "undefined") return null; + audioCtx ??= new window.AudioContext(); + try { + const src = audioCtx.createMediaElementSource(el); + const shelf = audioCtx.createBiquadFilter(); + shelf.type = "lowshelf"; + shelf.frequency.value = 100; + const gain = audioCtx.createGain(); + src.connect(shelf).connect(gain).connect(audioCtx.destination); + g = { shelf, gain }; + wired.set(el, g); + } catch { + return null; + } + } + g.shelf.gain.value = bass; + g.gain.gain.value = Math.pow(10, gainDb / 20); + return g; +} + +export function videoFileUrl(project: string, src: string) { + return `/api/report/file?${new URLSearchParams({ project, path: src }).toString()}`; +} + +export default function VideoEntryPlayer({ project, id, video, src, opacity, run, speed }: { + project: string; + id: string; + video: VideoEntryPlay; + /** The source second Play's clock wants. */ + src: number; + /** 0 (black: its entrance's lead) to 1. */ + opacity: number; + /** Play is playing and the clock is inside its span. */ + run: boolean; + speed: number; +}) { + const ref = useRef<HTMLVideoElement | null>(null); + const shaped = video.bass !== 0 || video.gain !== 0; + useEffect(() => { + const v = ref.current; + if (!v || !shaped) return; + shelfGraph(v, video.bass, video.gain); + if (run && audioCtx?.state === "suspended") void audioCtx.resume().catch(() => {}); + }, [shaped, video.bass, video.gain, run]); + useEffect(() => { + const v = ref.current; + if (!v) return; + const want = Number.isFinite(speed) && speed > 0 ? speed : 1; + const m = v as HTMLVideoElement & { preservesPitch?: boolean }; + if (m.preservesPitch !== true) m.preservesPitch = true; + if (Math.abs(v.defaultPlaybackRate - want) > 1e-3) v.defaultPlaybackRate = want; + if (Math.abs(v.playbackRate - want) > 1e-3) v.playbackRate = want; + if (Math.abs(v.currentTime - src) > DRIFT * Math.max(1, want) || !run) { + // Paused: on the frame (within half a frame); playing: pulled back only when it drifted. + if (run || Math.abs(v.currentTime - src) > 1 / 60) { + try { + v.currentTime = src; + } catch { + // not seekable yet: the next tick tries again + } + } + } + if (run && v.paused) void v.play().catch(() => {}); + if (!run && !v.paused) v.pause(); + }, [src, run, speed]); + return ( + <div className="pointer-events-none absolute inset-0 bg-black" data-play-video={id} data-play-video-fit={video.fit} data-play-video-playing={run ? "1" : "0"}> + <video + ref={ref} + src={videoFileUrl(project, video.src)} + preload="auto" + playsInline + muted={!run} + className="absolute inset-0 h-full w-full" + style={{ objectFit: video.fit === "cover" ? "cover" : "contain", opacity }} + /> + </div> + ); +} diff --git a/umtool/components/projects/review/playEngine/elementPicture.ts b/umtool/components/projects/review/playEngine/elementPicture.ts @@ -32,6 +32,8 @@ export class ElementPicture { private slots: Slot[] = [0, 1].map(() => ({ el: null, index: -1, url: "", presented: null, presentedAt: 0, rvfc: 0, frame: 0 })); /** The element's sound is the fallback's (no Web Audio): unmuted on the clip the clock follows. */ soundFromElement = false; + /** The fallback's level (0-1): a video entry's entrance fades the clip before it out (PlayCut.tsx). */ + duck = 1; attach(k: number, el: HTMLVideoElement | null) { const s = this.slots[k]; @@ -141,6 +143,7 @@ export class ElementPicture { private hold(s: Slot, w: Want, rate: number, lead: boolean) { const v = s.el!; v.muted = !(this.soundFromElement && lead && w.play); + if (Math.abs(v.volume - this.duck) > 0.01) v.volume = Math.max(0, Math.min(1, this.duck)); if (v.readyState < 1) return; const at = s.presented !== null && performance.now() - s.presentedAt < 250 && !v.paused ? s.presented : v.currentTime; const drift = at - w.mediaTime; diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -290,6 +290,17 @@ export class PlayEngine { this.publish(); } + /** + * The level of every clip's sound, 0-1 (1: as planned): a VIDEO entry's entrance (video-entry.mjs) fades the + * item before it out with its picture, and the video's own element plays its sound (PlayCut.tsx). A cut without + * a video entry never calls this. + */ + setDuck(v: number) { + const level = Math.max(0, Math.min(1, Number.isFinite(v) ? v : 1)); + this.elements.duck = level; + if (this.ctx && this.master && Math.abs(this.master.gain.value - level) > 0.005) this.master.gain.setTargetAtTime(level, this.ctx.currentTime, 0.02); + } + setRate(r: number) { if (r === this.rate) return; const t = this.now(); diff --git a/umtool/components/projects/review/playEngine/usePlayEngine.ts b/umtool/components/projects/review/playEngine/usePlayEngine.ts @@ -106,6 +106,7 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, return e ? { t: e.now(), cur: e.cur, playing: e.playing, rate: e.rate } : { t: 0, cur: 0, playing: false, rate: 1 }; }, []); const stats = useCallback(() => eng.current?.stats ?? null, []); + const setDuck = useCallback((v: number) => eng.current?.setDuck(v), []); - return { ui, failed, info, rate, setRate, seekTo, setPlaying, now, stats, canvasRef, slotRef0, slotRef1, onMediaError }; + return { ui, failed, info, rate, setRate, seekTo, setPlaying, now, stats, setDuck, canvasRef, slotRef0, slotRef1, onMediaError }; } diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -115,6 +115,7 @@ Inbox cannot disagree about what is wrong with one. | `posts attach <project> [<item> … \| --all] [--dry-run] [--json]` | a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words | | `posts combo <project> [on=on\|off] [label=L] [position=top-right\|top-left\|bottom-right\|bottom-left\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\|hit\|coin] [minCount=2-20] [match=id\|file\|audio] [--json]` · `posts combo <project> <item> off\|on\|auto\|label=…\|position=…\|color=…\|scale=…\|sfx=… [--json]` | the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**) | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | +| `timeline <project> [--take <t>] add-video <src> [--from S] [--to S] [--fit contain\|cover] [--bass dB] [--gain dB] [--enter cut\|<out>,<in>] [--hold S] [--title T] [--id ID] [--after <id>\|-] [--dry-run] [--json]` · `timeline <project> [--take <t>] set-video <id> <key>=<value>…` | **a video entry** ([report-video.md](report-video.md#a-video-entry)): a file of the project (`src`, relative; probed, its `fileSeconds` written) played FULL FRAME with its own sound, nothing drawn over it, at the end unless `--after` (`-`: the start), into the cut or the take's timeline only (`--take`, an undo point of the take's); `set-video` sets `from= to= fit= audio.bass= audio.gain= enter=cut\|<out>,<in> enter.out= enter.in= holdLast= deck=hidden\|shown title= note= src=` (`key=` clears). `--dry-run`: the entry and its place, nothing written. `--json`: `{ok, op, take?, inserted\|updated {id, at, entry}, revision?}`. **Exit 0 · 1 refused (no such file, take or entry; the build would not take it) · 2 usage** | | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one | | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post-json:<json>\|post-json:@<file> [--id ID]` | **a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>` | | `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -678,6 +678,23 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused | move, remove, a section, a group | the Cut tab's row (⠿, ⋯, the section bars), Play's reel strip | `umtool timeline <p> move\|remove\|section-move\|section-add …` | as a clip's | | the card's page, an attachment, the faces | Play the cut, the post bench | — | `GET /api/report/post-item?project&id&w&h[&phase][&take]` · `?project&file=posts-media/…` · `?project&font=regular\|bold` | +## A video entry (a file of the project, full frame, nothing over it) + +A video of the project played as the whole frame with its own sound, the chrome off over it +([report-video.md](report-video.md#a-video-entry): the shape, the entrance, the end, the sound). Made and set +by the timeline's writers, refused in the build's words (`validateVideoEntry`); on a take with `--take <t>` +(the take's patch, an undo point of the take's own). `key=` clears a knob. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| a video entry: `src` (a file of the project), at the end unless `--after` (`-`: the start); the file probed (`fileSeconds`) | Play plays it (full frame, its sound); the strip shows it as an item | `umtool timeline <p> [--take <t>] add-video <src> [--from S] [--to S] [--fit contain\|cover] [--bass dB] [--gain dB] [--enter cut\|<out>,<in>] [--hold S] [--title T] [--id ID] [--after <id>\|-] [--dry-run] [--json]` | `POST /api/report/timeline {op: "insert", …}` with the entry | +| `from`, `to` — the source seconds it plays (`to` absent: the file's end) | — | `umtool timeline <p> [--take <t>] set-video <id> from=32.26 to=46.32` (`to=`: the end) | — | +| `fit` — `contain` (default: pillar/letterboxed on black) or `cover` (fills the frame, cropped) | — | `set-video <id> fit=cover` | — | +| `audio.bass` — dB of low shelf at 100 Hz (−12…24), before the loudness level; `audio.gain` — dB (−20…20), after it | — | `set-video <id> audio.bass=8 audio.gain=-2` | — | +| `enter` — the join into it: `{out, in}` seconds (default 0.5, 0.5: the item before and its chrome fade to black, then the video fades up); `cut`: the cut's own transition | — | `set-video <id> enter=0.8,0.4` · `enter.out=1` · `enter=cut` | — | +| `holdLast` — seconds on its last frame after `to` (0–10; default 0: the cut ends ON its final frame) | — | `set-video <id> holdLast=1.5` | — | +| `deck` — `hidden` (default: nothing drawn over it) or `shown` (the chrome as over a clip) | — | `set-video <id> deck=shown` | — | + ## A narrated post item A post item read aloud, its attachment muffled under the read ([report-video.md](report-video.md#narrated-post-items): diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -402,6 +402,60 @@ A still **never derives** a QR target. A clip's code is derived from the archive that serves it; a screenshot has no such archive, and a code that resolves to the wrong place is worse than no code — so only an explicit `citeUrl` draws one. +### A video entry + +```jsonc +{ "type": "video", "id": "finale-puss", + "src": "posts-media/ObviousRises-x/2117366108705767779/2117366108705767779_1.mp4", // a file of the project + "from": 32.26, // source seconds; default 0 + "to": 46.32, // source seconds; absent = the file's end + "fit": "contain", // default: letter/pillarboxed on black · "cover": fills, cropped + "audio": { "bass": 8, "gain": 0 }, // dB: a low shelf at 100 Hz (ffmpeg bass=g=8:f=100:w=0.7), a gain + "enter": { "out": 0.5, "in": 0.5 },// the join into it (default); "cut": the cut's own transition + "holdLast": 0, // seconds on its last frame after `to`; default 0 + "deck": "hidden", // default: NOTHING over it · "shown": the chrome as over a clip + "fileSeconds": 46.324, // the file's probed length (written by add-video; the estimate's `to`) + "title": "…", "note": "…" } +``` + +A plain video of the project played as the **whole 1920x1080 frame, with its own sound** -- a meme +the cut ends on, a reaction the subject posted. Where `image` is a still and a `clip` is a corpus +window framed into the deck's box, a video entry is drawn over by **nothing**: no deck or footer, +no header or date line, no QR, no rail, markers or section titles, no counters, captions, clock, +thread map, watermark or any overlay layer. The build lays every chrome region (the deck's shell, +the feed, the posts windows, stamps, stats, effects, the finale) with an `enable` that leaves the +entry's span out (`video-entry.mjs videoBlackouts`: from the frame the entrance's dip has made black +to its end -- mid-dissolve into the next entry, or the cut's end), and the deck hides over it as over +a teaser. Play draws it the same way. `deck: "shown"` keeps the chrome. + +**The entrance** (`enter`, default `{out: 0.5, in: 0.5}`): the item before -- its picture and every +overlay, and its sound -- fades to black over its last `out` seconds (the teaser's dip, with no held +black), then the video fades up from black over its first `in` seconds, its sound with it. Its +segment starts with the cut's dissolve as black and silence (its **lead**), so the dissolve is black on +black and the fades never eat the span: the video still plays `from`→`to` whole. `enter: "cut"` is the +cut's own transition into it. There is **no fade at its end**: as the LAST entry the cut **ends on its +final frame** -- `render.endFade` is not applied, and nothing is appended after it. + +**Its sound** is levelled like a clip's: the bass boost first, the span measured through it (ebur128), +one gain toward the cut's level (`videoLoudnessTarget`): `render.loudness`'s target when it has one, +else the level the cut's own voice sits at -- its post items' narration (`render.postNarration.lufs`, +default −21 LUFS) or a narrated card's (−17.7) -- so a hot meme (the Puss in Boots clip is −8.8 LUFS) +does not jump 9 dB out of the cut, and a boosted video is bassier, not louder; `audio.gain` after that, as a clip's `audio.gain` is; a boosted or gained sound is limited under +−1 dBFS (`alimiter`), because the AAC encoder squashes what goes past full scale (measured: an 8 dB boost +of the Puss in Boots clip peaked at +8 dBFS and came out with its lows +2 dB and its mids −3 dB). + +**Its segment** is `lead + (to − from) + holdLast` (`videoSeconds`), the source span scaled per `fit`, +and is rebuilt only when its key changes (`segments/<id>.video.json`: the file's path, size and mtime, +`from`, `to`, `fit`, `audio`, `enter`, `holdLast`, the lead, the frame and the loudness target); every +file is written through a rename, so a take `--from` another reuses it. The schedule carries it +(`type: "video"`, `hideDeck`, `noChrome`, `enter`, its dip). Nothing to fetch (`--fetch-only` says +so); `src` is relative to the project and may not climb out of it. + +```sh +umtool timeline <p> --take mid-22 add-video posts-media/…/2117366108705767779_1.mp4 --from 32.26 --bass 8 +umtool timeline <p> --take mid-22 set-video video audio.bass=10 enter=0.8,0.4 +``` + ### Post items: a post as an entry of the cut A post card laid OVER a clip (`posts[]`, the deck's feed and popups) says what was diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -50,6 +50,7 @@ import { makeModulesFixture } from "./modules-fixture.mjs"; import { makeMarksFixture } from "./marks-fixture.mjs"; import { makeLivePreviewFixture } from "./live-preview-fixture.mjs"; import { makePlayCutFixture } from "./play-cut-fixture.mjs"; +import { makeVideoEntryFixture } from "./video-entry-fixture.mjs"; import { makeCutEditingFixture } from "./cut-editing-fixture.mjs"; import { makeReelFixture } from "./reel-fixture.mjs"; import { makeIntakeFixture } from "./intake-fixture.mjs"; @@ -1908,6 +1909,8 @@ makeMarksFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "cl makeLivePreviewFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // The Play view: the whole cut (and a take) played with no render, notes at the playhead (play-cut.spec.ts). makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// A cut ending on a video entry (a file of the project, full frame), and a take the CLI adds one to (video-entry.spec.ts). +makeVideoEntryFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Editing the cut (UI notes 2026-10-30): sections, flash-forward, the trailer's beats, take housekeeping // (cut-sections, cut-flash, trailer-beats and take-housekeeping specs). makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); diff --git a/umtool/e2e/fixtures/video-entry-fixture.mjs b/umtool/e2e/fixtures/video-entry-fixture.mjs @@ -0,0 +1,55 @@ +// What video-entry.spec.ts plays and writes (report-to-video/video-entry.mjs; umtool/docs/report-video.md, +// "A video entry"): a short deck cut that ENDS on a video entry -- a file of the project played full frame, +// its chrome off -- and a take with its own timeline that the CLI's `timeline --take add-video` writes into. +// +// c01 playvid 1.0-3.0 k01 card 1.5 s fin video media/fin.mp4 1.0-3.0 (bass 6, the default entrance) +// +// media/fin.mp4 is synthetic (testsrc2 1080x1200, a 60 Hz tone under a 1 kHz one, 3 s), made here with ffmpeg. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; + +/** + * @param {{ reports: string, deckManifest: Function, cachedWindow: string }} o + */ +export function makeVideoEntryFixture({ reports, deckManifest, cachedWindow }) { + const name = "video-entry-fixture"; + const dir = path.join(reports, name); + mkdirSync(path.join(dir, "media"), { recursive: true }); + const r = spawnSync("ffmpeg", [ + "-nostdin", "-v", "error", "-y", + "-f", "lavfi", "-i", "testsrc2=size=1080x1200:rate=30:duration=3", + "-f", "lavfi", "-i", "sine=frequency=60:duration=3", + "-f", "lavfi", "-i", "sine=frequency=1000:duration=3", + "-filter_complex", "[1:a]volume=0.3[l];[2:a]volume=0.1[h];[l][h]amix=inputs=2[a]", + "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-t", "3", + path.join(dir, "media", "fin.mp4"), + ], { encoding: "utf8" }); + if (r.status !== 0) throw new Error(`ffmpeg failed: ${r.stderr || r.status}`); + const timeline = [ + { type: "clip", id: "c01", video: "playvid", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "This is a complete sentence.", onscreen: { title: "24 Oct 2020" } }, + { type: "card", id: "k01", style: "chapter", seconds: 1.5, heading: "Before the finale" }, + { type: "video", id: "fin", src: "media/fin.mp4", from: 1, fileSeconds: 3, fit: "contain", audio: { bass: 6 }, title: "The finale" }, + ]; + const m = deckManifest(name, "The Video Entry Fixture", timeline); + m.render.fetchPad = 0; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify({ ...m, render: { ...m.render, lockedEdges: false } }, null, 2) + "\n"); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "playvid_0.00-9.00.mp4")); + // A draft take with its own timeline (the clip and the card): the CLI adds the finale to it, and only to it. + mkdirSync(path.join(dir, "takes", "walk"), { recursive: true }); + writeFileSync( + path.join(dir, "takes", "walk", "take.json"), + JSON.stringify( + { + id: "walk", group: "takes", order: 1, label: "Walk", kind: "different", summary: "the clip and the card", + preview: "preview.mp4", window: "full", style: null, draft: true, + patch: { timeline: [timeline[0], timeline[1]] }, + }, + null, + 2, + ) + "\n", + ); + copyFileSync(cachedWindow, path.join(dir, "takes", "walk", "preview.mp4")); + return { dir }; +} diff --git a/umtool/e2e/video-entry.spec.ts b/umtool/e2e/video-entry.spec.ts @@ -0,0 +1,106 @@ +import { test, expect, type Page } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import { copyFileSync, existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// A VIDEO entry (report-to-video/video-entry.mjs; umtool/docs/report-video.md, "A video entry"): a file of the +// project played FULL FRAME with its own sound, nothing of the deck over it. Play plays the fixture's cut, +// which ends on one: the item before darkens into it, the video's element plays on Play's clock, and while it +// is on screen the root says the chrome is off and the video covers the whole frame. And the CLI adds one to a +// take only (`timeline <p> --take <t> add-video`), the project's cut untouched. Fixture: +// e2e/fixtures/video-entry-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/video-entry-fixture"; +const DIR = path.join(FIXTURE, "reports", "video-entry-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const TAKE = path.join(DIR, "takes", "walk", "take.json"); + +const root = (page: Page) => page.locator("[data-play-cut]"); + +const umtool = (args: string[]) => + execFileSync("node", ["bin/umtool.mjs", ...args], { + cwd: path.join(HERE, ".."), + encoding: "utf8", + env: { ...process.env, REPORTS_DIR: FIXTURE, CHANNELS_DIR: path.join(FIXTURE, "channels"), UMTOOL_CACHE_DIR: path.join(FIXTURE, "cache"), UMTOOL_MEDIA_DIR: "" }, + }); + +test.beforeAll(() => { + for (const f of [MANIFEST, TAKE]) { + if (!existsSync(`${f}.pristine`)) copyFileSync(f, `${f}.pristine`); + copyFileSync(`${f}.pristine`, f); + } +}); + +test.beforeEach(() => { + test.setTimeout(120_000); +}); + +test("Play plays a cut that ends on a video entry: the stage darkens into it, then the file plays full frame, chrome off", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true })); + await expect(root(page)).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 }); + // The strip shows it as an item of its own, last. + const rows = page.locator("[data-play-row]"); + await expect(rows).toHaveCount(3); + expect(await rows.evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c01", "k01", "fin"]); + // Nothing of it before it is near. + await expect(page.locator("[data-play-video]")).toHaveCount(0); + await expect(root(page)).not.toHaveAttribute("data-play-chrome", "off"); + + // From the card: it plays on into the video. + await page.locator('[data-play-row="k01"]').click(); + await expect(root(page)).toHaveAttribute("data-play-item", "k01"); + await page.locator("[data-play-toggle]").click(); + // The card darkens into it (the whole stage, its chrome with it). + await expect(page.locator('[data-play-dip="k01"]')).toBeVisible({ timeout: 20_000 }); + await expect(root(page)).toHaveAttribute("data-play-item", "fin", { timeout: 20_000 }); + await expect(root(page)).toHaveAttribute("data-play-chrome", "off"); + const player = page.locator('[data-play-video="fin"]'); + await expect(player).toBeVisible(); + await expect(player).toHaveAttribute("data-play-video-fit", "contain"); + // It covers the whole frame: its box is the player's. + const pb = await page.locator("[data-play-player-pin]").boundingBox(); + const vb = await player.boundingBox(); + expect(pb && vb).toBeTruthy(); + expect(Math.abs((vb?.width ?? 0) - (pb?.width ?? 0))).toBeLessThan(2); + // Its element plays the file on Play's clock: its source second moves on from `from` (1 s). + const el = player.locator("video"); + await expect(el).toHaveAttribute("src", /\/api\/report\/file\?.*path=media%2Ffin\.mp4/); + await expect.poll(async () => el.evaluate((v: HTMLVideoElement) => v.currentTime), { timeout: 20_000 }).toBeGreaterThan(1.2); + await expect.poll(async () => el.evaluate((v: HTMLVideoElement) => v.muted), { timeout: 10_000 }).toBe(false); + // It ends on its last frame: the cut ends, the video stays on screen at its end. + await expect(root(page)).toHaveAttribute("data-play-state", "ended", { timeout: 20_000 }); + await expect(player).toBeVisible(); + expect(await el.evaluate((v: HTMLVideoElement) => v.currentTime)).toBeGreaterThan(2.5); + await page.screenshot({ path: test.info().outputPath("video-entry-end.png") }); +}); + +test("the CLI adds a video entry to a take only: its knobs, its file's length; the project's cut untouched", () => { + const before = readFileSync(MANIFEST, "utf8"); + const dry = JSON.parse(umtool(["timeline", PROJECT, "--take", "walk", "add-video", "media/fin.mp4", "--from", "1", "--bass", "6", "--dry-run", "--json"])); + expect(dry.ok).toBe(true); + expect(JSON.parse(readFileSync(TAKE, "utf8")).patch.timeline).toHaveLength(2); + const out = JSON.parse(umtool(["timeline", PROJECT, "--take", "walk", "add-video", "media/fin.mp4", "--from", "1", "--bass", "6", "--json"])); + expect(out.ok).toBe(true); + expect(out.inserted.at).toBe(2); + expect(out.inserted.entry).toMatchObject({ type: "video", src: "media/fin.mp4", from: 1, audio: { bass: 6 } }); + expect(out.inserted.entry.fileSeconds).toBeGreaterThan(2.9); + const take = JSON.parse(readFileSync(TAKE, "utf8")); + expect(take.patch.timeline.map((e: { id: string }) => e.id)).toEqual(["c01", "k01", out.inserted.id]); + expect(readFileSync(MANIFEST, "utf8")).toBe(before); + // A bad knob is refused in the build's words, nothing written. + let code = 0; + try { + umtool(["timeline", PROJECT, "--take", "walk", "add-video", "media/fin.mp4", "--fit", "stretch", "--json"]); + } catch (e) { + code = (e as { status?: number }).status ?? -1; + } + expect(code).not.toBe(0); + expect(JSON.parse(readFileSync(TAKE, "utf8")).patch.timeline).toHaveLength(3); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -40,6 +40,7 @@ import { verticalErrors } from "umtool-report-to-video/look"; import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs"; import { sideErrors } from "yt-dlp-transcript-common/lib/report/vertical.mjs"; import { validateRoom } from "umtool-report-to-video/room"; +import { applyVideoPatch, validateVideoEntries, validateVideoEntry } from "umtool-report-to-video/video-entry"; import { applySectionEnter } from "./sections.mjs"; import { citeUrlAt, parseClipSpec } from "./clipEditorModel.mjs"; import { addSectionIn, followSplitMarkers, moveBoundaryIn, moveToSectionIn, placeIn, reanchorMarkers, removeBoundaryIn, sectionModel, sectionWords, setSectionIn } from "./sectionEdit.mjs"; @@ -1901,6 +1902,8 @@ function structureErrors(manifest) { // The finale is one run of the last clips: moving a clip past it is refused. ...validateFinaleEntries(manifest), ...validateTeasers(manifest), + // A video entry (video-entry.mjs): a file of the project played full frame. + ...validateVideoEntries(manifest), ...validateNarration(manifest), ...validateDrafted(manifest), ...validatePublish(manifest), @@ -3753,6 +3756,30 @@ export async function flashForward(dir, clipId, spec, { token = null } = {}) { const TEASER_PATCH_KEYS = ["lines", "beat", "dip", "tail", "tailWait"]; /** + * SET a video entry's knobs (video-entry.mjs applyVideoPatch: from, to, fit, + * audio.bass, audio.gain, enter, holdLast, deck, title, note, src), checked as + * the build checks it; one undo point. + * + * @param {string} dir + * @param {string} id + * @param {Record<string, unknown>} patch + * @param {{ token?: string | null, at?: number | null }} [opts] + */ +export async function updateVideoEntry(dir, id, patch, { token = null, at = null } = {}) { + if (!patch || typeof patch !== "object" || !Object.keys(patch).length) throw new Error("nothing to change"); + return structural(dir, "video", token, (m) => { + const i = entryIndex(m.timeline, id, at); + const e = m.timeline[i]; + if (e.type !== "video") throw new Error(`${id} is a ${e.type ?? "non-video"} entry, not a video`); + const next = applyVideoPatch(e, patch); + const errors = validateVideoEntry(next, `timeline[${i}] (${id})`); + if (errors.length) throw new Error(errors.join("; ")); + m.timeline[i] = next; + return { id, at: i, entry: next }; + }); +} + +/** * Patch one teaser: its lines, beat, dip, tail and tail wait. A key given as * null (or "") is removed; a key not given is kept. Checked with the build's * validateTeaser (which checks the dip too) against the patched entry. diff --git a/umtool/lib/report/playVideo.mjs b/umtool/lib/report/playVideo.mjs @@ -0,0 +1,55 @@ +// A VIDEO entry in Play (report-to-video/video-entry.mjs; umtool/docs/knobs.md, +// "Play the cut"): what the stage shows at cut second t. Pure, so the +// arithmetic is unit-tested (playVideo.test.mjs) and PlayCut.tsx only applies it. +// +// - On a video item: its file at source second `src` (its `from` plus the +// seconds since its lead's black), fading up over `enter.in` after the lead; +// black before. The clips' sound is ducked to 0 (`duck`): the video's own +// element plays its sound. +// - On the item BEFORE a video that enters with a fade: the whole stage -- +// its picture and every overlay -- darkens to black over its last +// `enter.out` seconds (`dark`), its sound with it (`duck`), black at the +// seam Play cuts on (the video item's `from`). +// - Anything else: nothing (`null`), and the stage is what it always was. + +import { itemIndexAt } from "./playCut.mjs"; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const clamp01 = (v) => Math.max(0, Math.min(1, v)); +const round = (v) => Math.round(v * 1000) / 1000; + +/** + * @typedef {{ src: string, from: number, to: number, fit: "contain" | "cover", enter: { out: number, in: number } | null, + * lead: number, hold: number, seconds: number, bass: number, gain: number, noChrome: boolean }} VideoEntryPlay + */ + +/** + * @param {{ items: Array<{ id: string, start: number, from: number, to: number, end: number }> }} plan + * @param {Map<string, { videoEntry?: VideoEntryPlay }>} entries + * @param {number} t + * @returns {null | { id: string, video: VideoEntryPlay | null, src: number | null, opacity: number, dark: number, duck: number, playing: boolean }} + */ +export function videoStageAt(plan, entries, t) { + const items = plan?.items ?? []; + const i = itemIndexAt(plan, t); + const it = items[i]; + if (!it || !fin(t)) return null; + const ve = entries.get(it.id)?.videoEntry; + if (ve) { + const local = t - it.start; + const span = Math.max(0, ve.to - ve.from); + const into = local - ve.lead; + const src = round(ve.from + Math.min(span, Math.max(0, into))); + const opacity = into < 0 ? 0 : ve.enter && ve.enter.in > 0 ? clamp01(into / ve.enter.in) : 1; + return { id: it.id, video: ve, src, opacity: round(opacity), dark: 0, duck: 0, playing: into >= 0 && into < span }; + } + const next = items[i + 1]; + const nv = next ? entries.get(next.id)?.videoEntry : null; + if (nv?.enter && fin(next?.from)) { + const end = /** @type {number} */ (next.from); + const dark = clamp01((t - (end - nv.enter.out)) / nv.enter.out); + if (dark <= 0) return null; + return { id: it.id, video: null, src: null, opacity: 0, dark: round(dark), duck: round(1 - dark), playing: false }; + } + return null; +} diff --git a/umtool/lib/report/playVideo.test.mjs b/umtool/lib/report/playVideo.test.mjs @@ -0,0 +1,55 @@ +// A video entry in Play (playVideo.mjs): the stage's fade into it, its source second, the ducked sound. +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { videoStageAt } from "./playVideo.mjs"; + +const ve = { src: "media/v.mp4", from: 2, to: 6, fit: "contain", enter: { out: 0.5, in: 0.5 }, lead: 0.4, hold: 0, seconds: 4.4, bass: 6, gain: 0, noChrome: true }; +// A 3 s card, then the video (4.4 s, its first 0.4 s the dissolve's black); Play cuts at the overlap's midpoint. +const plan = { + items: [ + { id: "k01", start: 0, end: 3, from: 0, to: 2.8 }, + { id: "fin", start: 2.6, end: 7, from: 2.8, to: 7 }, + ], +}; +const entries = new Map([["k01", {}], ["fin", { videoEntry: ve }]]); + +test("the item before a video darkens over its last enter.out seconds, its sound with it; untouched before", () => { + assert.equal(videoStageAt(plan, entries, 1), null); + assert.equal(videoStageAt(plan, entries, 2.3), null); + const mid = videoStageAt(plan, entries, 2.55); + assert.equal(mid?.dark, 0.5); + assert.equal(mid?.duck, 0.5); + assert.equal(mid?.video, null); +}); + +test("on the video: black through its lead, then up over enter.in, on its own source clock; the clips' sound off", () => { + const black = videoStageAt(plan, entries, 2.9); + assert.equal(black?.opacity, 0); + assert.equal(black?.src, 2); + assert.equal(black?.duck, 0); + assert.equal(black?.playing, false); + const up = videoStageAt(plan, entries, 3.25); + assert.equal(up?.opacity, 0.5); + assert.equal(up?.src, 2.25); + assert.equal(up?.playing, true); + const on = videoStageAt(plan, entries, 5); + assert.equal(on?.opacity, 1); + assert.equal(on?.src, 4); + // Its end: the last frame, held (no fade out). + const end = videoStageAt(plan, entries, 7); + assert.equal(end?.opacity, 1); + assert.equal(end?.src, 6); + assert.equal(end?.playing, false); +}); + +test('enter "cut": no darkening before it, no fade up', () => { + const cut = new Map([["k01", {}], ["fin", { videoEntry: { ...ve, enter: null, lead: 0 } }]]); + assert.equal(videoStageAt(plan, cut, 2.75), null); + assert.equal(videoStageAt(plan, cut, 2.9)?.opacity, 1); +}); + +test("a cut without a video entry: nothing, anywhere", () => { + const none = new Map([["k01", {}], ["fin", {}]]); + for (const t of [0, 2.6, 2.9, 7]) assert.equal(videoStageAt(plan, none, t), null); +}); diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -25,6 +25,7 @@ import { sectionModel } from "./sectionEdit.mjs"; import { manifestToken } from "./manifest.mjs"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; +import { videoAudio, videoEnter, videoFit, videoHidesChrome, videoLead, videoSeconds, videoSpan } from "umtool-report-to-video/video-entry"; const fin = (v) => typeof v === "number" && Number.isFinite(v); const text = (v) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : ""); @@ -76,6 +77,40 @@ export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = nu } /** + * A VIDEO entry as Play plays it (video-entry.mjs): a file of the project, its + * span (`from`–`to` source seconds), how it fits the frame, its entrance (the + * item before fades to black over `enter.out`, it fades up over `enter.in` + * after its `lead`), its sound's bass and gain, and whether the chrome is off + * over it. Its file is served by /api/report/file (lib/report/projectFile.mjs). Its length on the + * clock is the segment's (videoSeconds, which the estimate's segments use). + * + * @param {Record<string, any>} e + * @param {number} D the cut's transition + */ +export function videoPlayEntry(e, D) { + const span = videoSpan(e); + return { + id: e.id, + type: "video", + heading: text(e.title) || String(e.src ?? "").split("/").pop() || e.id, + section: e.section ?? null, + // Not `video` (a clip's recording id): the file and how it plays. + videoEntry: { + src: String(e.src ?? ""), + from: span.from, + to: span.to, + fit: videoFit(e), + enter: videoEnter(e), + lead: videoLead(e, D), + hold: fin(e.holdLast) ? e.holdLast : 0, + seconds: videoSeconds(e, D), + ...videoAudio(e), + noChrome: videoHidesChrome(e), + }, + }; +} + +/** * WHAT PLAYS BY DEFAULT is the LATEST take (operator, 1 Nov 2026): with no * `take`, the newest working take (workingCut.mjs) -- the project's manifest * as it is now with that take's patch, so the look is the next draft's and @@ -132,6 +167,7 @@ export async function playView(project, { take = null, bare = false } = {}) { const entries = await Promise.all( timeline.map(async (e, i) => { if (e.type === "post") return postPlayEntry(e, render, planContext(timeline, i, render), mediaSceneOf(timeline, i, repeatGroups, render)); + if (e.type === "video") return videoPlayEntry(e, D); if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null }; const win = pickWindow(await windowsFor(project, e, cache), null); const dateKey = clipDateKey(e); diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -347,6 +347,33 @@ export async function insertTakeEntry(projectDir, id, afterId, spec, { token = n ); } +/** + * SET a video entry's knobs in a TAKE's timeline (video-entry.mjs + * applyVideoPatch), checked as the build checks it; an undo point of the take's. + */ +export async function updateTakeVideoEntry(projectDir, id, entryId, patch, { token = null, at = null, now = new Date() } = {}) { + const { applyVideoPatch, validateVideoEntry } = await import("umtool-report-to-video/video-entry"); + if (!patch || typeof patch !== "object" || !Object.keys(patch).length) throw new Error("nothing to change"); + return editTakeTimeline( + projectDir, + id, + "video", + token, + (m) => + applyStructural(m, (x) => { + const i = entryIndex(x.timeline, entryId, at); + const e = x.timeline[i]; + if (e.type !== "video") throw new Error(`${entryId} is a ${e.type ?? "non-video"} entry, not a video`); + const next = applyVideoPatch(e, patch); + const errors = validateVideoEntry(next, `timeline[${i}] (${entryId})`); + if (errors.length) throw new Error(errors.join("; ")); + x.timeline[i] = next; + return { id: entryId, at: i, entry: next }; + }), + { now }, + ); +} + /** A take's label: one line, at most this long. */ export const TAKE_LABEL_MAX = 200; diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -49,6 +49,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { mergePatch } from "umtool-report-to-video/montage-styles"; import { postItemSeconds } from "umtool-report-to-video/post-item"; +import { videoSeconds } from "umtool-report-to-video/video-entry"; import { cutSlurState } from "umtool-report-to-video/post-slurs"; import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings"; import { markKeepFrames } from "umtool-report-to-video/prune-frames"; @@ -246,6 +247,8 @@ export async function loadMontageStyles({ file = montageStylesFile() } = {}) { /** An entry's length by the manifest's own numbers: a clip's cut, a post item's rule (post-item.mjs), else `seconds`, else 4 s. */ export function estimatedSeconds(e) { if (e?.type === "post") return postItemSeconds(e); + // A video entry (video-entry.mjs): its span and its hold (a take's hard cuts: no lead). + if (e?.type === "video") return videoSeconds(e, 0); if (e?.type === "clip") { const a = Number(e.cutStart ?? e.start); const b = Number(e.cutEnd ?? e.end); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -88,6 +88,7 @@ import { undoStructural, updateClip, updateTeaser, + updateVideoEntry, upsertPost, } from "./manifest.mjs"; @@ -165,6 +166,12 @@ export const TIMELINE_USAGE = [ " umtool timeline <project> groups promote <gid> [--label L] the group opens a subsection: a level-2 marker at", " its first clip titled with its claim (--label when it is over 24); the render sees only this", " A clip moved out of its group's run leaves the group; moved alone into the middle of a run, it joins it", + " umtool timeline <project> [--take <t>] add-video <src> [--from S] [--to S] [--fit contain|cover] [--bass dB]", + " [--gain dB] [--enter cut|<out>[,<in>]] [--hold S] [--title T] [--id ID] [--after <id>|-] [--dry-run] [--json]", + " a VIDEO ENTRY: a file of the project (src, relative) played FULL FRAME with its sound, no chrome over it;", + " at the end unless --after (`-`: the start); --from/--to source seconds (no --to: the file's end)", + " umtool timeline <project> [--take <t>] set-video <id> <key>=<value>… from= to= fit= audio.bass= audio.gain=", + " enter=cut|<out>,<in> enter.out= enter.in= holdLast= deck=hidden|shown title= note= src= (`key=` clears)", " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo | insert <spec> --after <id>|-]", " a take's timeline (walk a take): written into the take's patch (takes/<id>/take.json),", " each write with an undo point of the take's own; the project's manifest is untouched", @@ -174,9 +181,9 @@ export const TIMELINE_USAGE = [ ].join("\n"); const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"]; -const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"]; +const VERBS = ["ls", "insert", "add-video", "set-video", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"]; const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"]; -const VALUED = new Set(["--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation"]); +const VALUED = new Set(["--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation", "--from", "--fit", "--bass", "--gain", "--enter", "--hold"]); /** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ const TAKE_VERBS = ["ls", "move", "remove", "undo", "insert"]; @@ -281,6 +288,8 @@ export function timelineRows(manifest) { media: Array.isArray(e.media) ? e.media.map((m) => m?.kind) : [], } : {}), + // A video entry (video-entry.mjs): its file and the source span it plays. + ...(e.type === "video" ? { src: String(e.src ?? ""), from: e.from ?? 0, to: e.to ?? e.fileSeconds ?? null } : {}), date: typeof e.date === "string" ? (e.type === "post" ? e.date.slice(0, 10) : e.date) : null, title: typeof title === "string" ? title : e.type === "post" ? `${String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim().slice(0, 60)}` : null, }; @@ -295,7 +304,9 @@ export function timelineLines(rows) { r.type === "clip" ? `${String(r.video ?? "?").padEnd(14)} ${fmt(r.start)}–${fmt(r.end)}${r.cutStart != null ? ` (cut ${fmt(r.cutStart)}–${fmt(r.cutEnd)})` : ""}` + (r.gaps?.length ? ` gaps ${r.gaps.map((g) => `−${fmt(g.from)}–${fmt(g.to)}`).join(" ")} (plays ${fmt(r.plays)}s)` : "") - : r.type === "post" + : r.type === "video" + ? `${String(r.src ?? "").padEnd(14)} ${fmt(r.from)}–${r.to == null ? "end" : fmt(r.to)}` + : r.type === "post" ? `${String(r.post ?? "").padEnd(14)} ${fmt(r.seconds)}s ${r.media?.length ? r.media.join("+") : "text"}` : "".padEnd(14); const label = [r.date, r.title].filter(Boolean).join(" "); @@ -501,6 +512,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } if (!VERBS.includes(verb)) throw new CliError(`unknown: timeline ${verb} — ${VERBS.join(", ")}`); const project = await projectOf(projectArg, root); + // A video entry (video-entry.mjs), into the cut or a take's timeline. + if (verb === "add-video" || verb === "set-video") return await videoVerb(project, verb, rest, flags, { out, json }); if (flags.has("--take")) return await takeTimeline(project, String(flags.get("--take")), verb, rest, flags, { out, json }); const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); @@ -910,6 +923,131 @@ async function takeTimeline(project, take, verb, rest, flags, { out, json }) { return 0; } +/** A number flag, or null when absent; a usage error when it is not one. */ +function numFlag(flags, name) { + if (!flags.has(name)) return null; + const v = flags.get(name); + const n = Number(v); + if (v === true || v === "" || !Number.isFinite(n)) throw new CliError(`${name} needs a number (got ${v === true ? "nothing" : v})`); + return n; +} + +/** A file's length in seconds (ffprobe), or null. */ +async function probeSeconds(file) { + const { execFile } = await import("node:child_process"); + return new Promise((resolve) => { + execFile(process.env.FFPROBE ?? "ffprobe", ["-v", "error", "-show_entries", "format=duration:stream=codec_type", "-of", "json", file], (e, stdout) => { + if (e) return resolve(null); + try { + const doc = JSON.parse(stdout); + const d = Number(doc.format?.duration); + resolve({ seconds: Number.isFinite(d) && d > 0 ? Math.round(d * 1000) / 1000 : null, hasVideo: (doc.streams ?? []).some((x) => x.codec_type === "video") }); + } catch { + resolve(null); + } + }); + }); +} + +/** + * `umtool timeline <p> [--take <t>] add-video <src> …` and `set-video <id> k=v…`: a VIDEO ENTRY + * (video-entry.mjs) put into the cut -- or the take's timeline only -- through the timeline's writers, + * checked as the build checks it. `--dry-run`: the entry and where it goes, nothing written. + * Exit 0 · 1 refused (no such file, take or entry; the build would not take it) · 2 usage. + */ +async function videoVerb(project, verb, rest, flags, { out, json }) { + const V = await import("umtool-report-to-video/video-entry"); + const take = flags.has("--take") ? String(flags.get("--take")) : null; + const dry = flags.has("--dry-run"); + const edit = take ? await import("./takeEdit.mjs") : null; + let timeline; + if (take) { + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + timeline = (await resolveTakeManifest(project.dir, take)).manifest.timeline ?? []; + } else { + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + timeline = manifest.timeline ?? []; + } + const where = take ? `take ${take} of ${project.id}` : project.id; + let result; + if (verb === "add-video") { + const src = rest[0]; + if (!src) throw new CliError("add-video needs <src>: a video file of the project, relative to its directory"); + const rel = src.replace(/^\.\//, ""); + const file = path.resolve(project.dir, rel); + const r = path.relative(project.dir, file); + if (path.isAbsolute(src) || r.startsWith("..")) throw new CliError(`${src}: a video entry plays a file INSIDE the project (relative to ${project.dir})`); + const probe = await probeSeconds(file); + if (!probe) throw new Error(`no video at ${file} (src: ${rel})`); + if (!probe.hasVideo) throw new Error(`${rel} has no picture -- a video entry plays a video`); + const patch = {}; + for (const [flag, key] of [["--from", "from"], ["--to", "to"], ["--hold", "holdLast"], ["--bass", "audio.bass"], ["--gain", "audio.gain"]]) { + const n = numFlag(flags, flag); + if (n !== null) patch[key] = n; + } + if (flags.has("--fit")) patch.fit = String(flags.get("--fit")); + if (flags.has("--enter")) patch.enter = String(flags.get("--enter")); + if (flags.has("--title")) patch.title = String(flags.get("--title")); + let entry; + try { + entry = V.applyVideoPatch({ type: "video", id: flags.has("--id") ? String(flags.get("--id")) : "video", src: rel }, patch); + } catch (e) { + throw new CliError(e instanceof Error ? e.message : String(e)); + } + if (probe.seconds) entry.fileSeconds = probe.seconds; + const errors = V.validateVideoEntry(entry, "add-video"); + if (errors.length) throw new Error(errors.join("; ")); + const afterArg = flags.has("--after") ? String(flags.get("--after")) : null; + const after = afterArg === null ? (timeline.length ? timeline[timeline.length - 1].id : null) : afterArg === "-" || afterArg === "" ? null : afterArg; + if (after && !timeline.some((e) => e?.id === after)) throw new Error(`no entry ${after} in ${where}`); + const at = after ? timeline.findIndex((e) => e?.id === after) + 1 : 0; + if (dry) { + const span = V.videoSpan(entry, probe.seconds); + if (json) out(JSON.stringify({ ok: true, op: verb, dryRun: true, ...(take ? { take } : {}), at, after, entry, span, seconds: V.videoSeconds(entry, 0, probe.seconds) }, null, 2)); + else out(`would add video ${entry.id} at ${at}${after ? ` (after ${after})` : " (the start)"} in ${where}: ${rel} ${span.from}–${span.to} s, ${V.videoFit(entry)}${entry.audio?.bass ? `, bass +${entry.audio.bass} dB` : ""}`); + return 0; + } + result = take + ? await edit.insertTakeEntry(project.dir, take, after, entry, { token: await edit.takeToken(project.dir, take) }) + : await withEditNotes(project, async () => insertEntry(project.dir, after, entry, { token: await manifestToken(project.dir) })); + } else { + const id = rest[0]; + if (!id) throw new CliError("set-video needs the video entry's id, then key=value…"); + const patch = {}; + for (const a of rest.slice(1)) { + const m = /^([a-zA-Z.]+)=(.*)$/s.exec(a); + if (!m) throw new CliError(`${a}: a setting is key=value (\`key=\` clears it)`); + if (!V.VIDEO_SET_KEYS.includes(m[1])) throw new CliError(`${m[1]} is not a video entry's setting (${V.VIDEO_SET_KEYS.join(", ")})`); + patch[m[1]] = m[2] === "" ? null : m[2]; + } + if (!Object.keys(patch).length) throw new CliError("set-video needs at least one key=value"); + const i = timeline.findIndex((e) => e?.id === id); + if (i < 0) throw new Error(`no entry ${id} in ${where}`); + if (timeline[i].type !== "video") throw new Error(`${id} is a ${timeline[i].type ?? "non-video"} entry, not a video`); + if (dry) { + const next = V.applyVideoPatch(timeline[i], patch); + const errors = V.validateVideoEntry(next, id); + if (errors.length) throw new Error(errors.join("; ")); + if (json) out(JSON.stringify({ ok: true, op: verb, dryRun: true, ...(take ? { take } : {}), at: i, entry: next }, null, 2)); + else out(`would set ${id} in ${where}: ${JSON.stringify(next)}`); + return 0; + } + result = take + ? await edit.updateTakeVideoEntry(project.dir, take, id, patch, { token: await edit.takeToken(project.dir, take) }) + : await withEditNotes(project, async () => updateVideoEntry(project.dir, id, patch, { token: await manifestToken(project.dir) })); + } + const r = result?.result ?? result; + if (json) { + out(JSON.stringify({ ok: true, op: verb, ...(take ? { take } : {}), [verb === "add-video" ? "inserted" : "updated"]: { id: r.id, at: r.at, entry: r.entry }, + ...(result?.revision ? { revision: result.revision.rel } : {}) }, null, 2)); + return 0; + } + out(`${verb === "add-video" ? "added video" : "set video"} ${r.id} at ${r.at} in ${where}`); + if (take && result?.revision) out(` undo point: takes/${take}/${result.revision.rel} (umtool timeline ${project.id} --take ${take} undo)`); + return 0; +} + /** `sections`, one line each: §, its marker, colour, label, its clips. */ /** * `umtool timeline <p> threads [--write [--conversation <id>]]`: the cut's conversations diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -148,7 +148,8 @@ import { resolveLocalSource, } from "./sources.mjs"; // A clip whose media is a file beside the manifest (`src`, `cues`). -import { clipLabel, createLocalMedia, hasLocalMedia, validateLocalMedia } from "./local-media.mjs"; +import { clipLabel, createLocalMedia, hasLocalMedia, resolveManifestPath, validateLocalMedia } from "./local-media.mjs"; +import { blackoutEnable, validateVideoEntries, videoBlackouts, videoFit, videoLoudnessTarget, videoLead, videoMeasureFilter, videoSeconds, videoSegmentGraph, videoSegmentKey, videoSpan } from "./video-entry.mjs"; import { createPostChannelResolver, resolvePostLinks } from "./post-links.mjs"; import { ensureWriteDir } from "../lib/report/storage.mjs"; // The deck (`render.chrome`): its geometry, validation and schedule are pure @@ -1163,7 +1164,7 @@ export function needsFetchMessage(missing) { // The timeline's vocabulary is OPEN; the build loop treats everything it has // no other branch for as a clip, and so does this. -const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro", "post"]); +const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro", "post", "video"]); const isClipEntry = (e) => !NON_CLIP_TYPES.has(e?.type); /** @@ -2587,7 +2588,7 @@ async function buildMontageWall({ M, entries, render, outDir, timeline, provenan // A post item's record (`.post.json`, its key: post-render.mjs) and its combo pass's (`.combo.json`, the badge-less // `.plain.mp4`) ride with its segment, so a take --from another reuses a post item whose key still matches (the plain one too: // without it a reused badged segment would be taken for a plain one and badged again). -export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".intro.json", ".quote.txt", ".attrib.txt", ".channel.txt", ".post.json", ".combo.json", ".plain.mp4"]); +export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".intro.json", ".quote.txt", ".attrib.txt", ".channel.txt", ".post.json", ".combo.json", ".plain.mp4", ".video.json"]); /** * Before an entry's segment is rebuilt: each of its files in `segDir` that is @@ -2915,6 +2916,63 @@ export async function buildTeaserSegment(entry, { manifestPath, render, outDir, // * It reserves the footer's rows but draws nothing in them. The marker's // position is a function of `section`, which a still does not have, and a // timeline strip whose marker vanishes for six seconds reads as a bug. +/** + * A video entry's segment (video-entry.mjs): the project file's span scaled + * to the WHOLE frame by its `fit`, nothing drawn on it, its sound with the + * bass boost, levelled toward the cut's loudness target (measured with the + * boost), its entrance's black lead (`videoLead`) and fade up, and its hold. + * Rebuilt only when its key (`<id>.video.json`) changes; every file written + * through a rename, so a take's hard-linked segment is never written through. + */ +async function buildVideoEntrySegment(entry, render, outDir, baseDir, D, timeline = []) { + const seg = path.join(outDir, "segments", `${entry.id}.mp4`); + const rec = path.join(outDir, "segments", `${entry.id}.video.json`); + const src = resolveManifestPath(baseDir, entry.src, { allowAbsolute: render.allowAbsoluteSrc === true }); + if (src.error) throw new Error(`${entry.id}: src ${src.error}`); + const st = await stat(src.file).catch(() => null); + if (!st?.isFile()) throw new Error(`${entry.id}: no video at ${src.file} (src: ${entry.src})`); + const media = await probeMedia(src.file); + if (!media.hasVideo) throw new Error(`${entry.id}: ${entry.src} has no picture -- a video entry plays a video`); + const { stdout: aOut } = await execFileP(FFPROBE, ["-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "csv=p=0", src.file]); + const hasAudio = aOut.trim().length > 0; + const span = videoSpan(entry, media.duration); + const lead = videoLead(entry, D); + const seconds = videoSeconds(entry, D, media.duration); + const { target: aim, basis } = videoLoudnessTarget(render, timeline, loudnessTargetOf(render)); + const target = hasAudio ? aim : null; + const key = videoSegmentKey({ entry, file: { size: st.size, mtimeMs: Math.round(st.mtimeMs), seconds: media.duration }, render, lead, target }); + const was = await readFile(rec, "utf8").then((t) => JSON.parse(t), () => null); + if (was?.key === key && (await exists(seg))) { + EMIT("note", { id: entry.id, message: `${entry.id}: video segment cached (${entry.src} ${span.from.toFixed(2)}–${span.to.toFixed(2)})` }); + return seg; + } + // Even loudness, as a clip's: the span measured THROUGH the bass boost, one gain toward the cut's level + // (videoLoudnessTarget: render.loudness, else the level its narration sits at) -- a boost makes it + // bassier, not louder; a limiter keeps the peaks under full scale. + const measure = async (af) => { + const { stderr } = await execFileP(FFMPEG, [ + "-nostdin", "-hide_banner", "-ss", span.from.toFixed(3), "-to", span.to.toFixed(3), "-i", src.file, + "-vn", "-af", `${af},ebur128`, "-f", "null", "-", + ], { maxBuffer: 1 << 26 }).catch((e) => ({ stderr: e.stderr ?? "" })); + return parseIntegratedLoudness(stderr); + }; + let level = null; + if (target != null) { + const measured = await measure(videoMeasureFilter(entry)); + level = { measured, gain: loudnessGain(measured, target), target, basis }; + } + const graph = videoSegmentGraph({ entry, render, seconds, lead, hasAudio, gainDb: level?.gain ?? null, span }); + const tmp = `${seg}.tmp-${process.pid}.mp4`; + await execFileP(FFMPEG, [ + "-nostdin", "-v", "error", "-y", "-i", src.file, + "-filter_complex", graph, "-map", "[v]", "-map", "[a]", + ...encodeArgs(render), "-t", String(seconds), tmp, + ], { maxBuffer: 1 << 26 }); + await rename(tmp, seg); + await replaceFile(rec, JSON.stringify({ version: 1, id: entry.id, key, src: entry.src, span, lead, seconds, fit: videoFit(entry), loudness: level }, null, 2) + "\n"); + return seg; +} + async function buildImageSegment(entry, render, outDir, chrome, provenance, baseDir, framing = null) { const seg = path.join(outDir, "segments", `${entry.id}.mp4`); const pal = render.palette; @@ -3625,7 +3683,9 @@ export function railFilterChain(rail, assets, times, render, inLabel, firstInput * the deadlock the rail's five chained loops hit cannot happen here. */ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts = {}) { - const { outLabel = "[hfout]", final = true } = opts; + const { outLabel = "[hfout]", final = true, blackouts = null, shift = 0 } = opts; + // The video entries' spans (video-entry.mjs videoBlackouts), cut seconds; "" with none. + const off = blackoutEnable(blackouts, shift); const inputs = []; const parts = []; let lab = inLabel; @@ -3680,7 +3740,7 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts parts.push(`${src}format=rgba[hfa${i}]`); src = `[hfa${i}]`; } - parts.push(`${lab}${src}overlay=x=${r.x}:y=${r.y}:format=yuv444:${posts ? "eof_action=pass" : "shortest=1"}${out}`); + parts.push(`${lab}${src}overlay=x=${r.x}:y=${r.y}:format=yuv444:${posts ? "eof_action=pass" : "shortest=1"}${off}${out}`); lab = out; }); if (final) parts.push(`${lab}format=yuv420p[vout]`); @@ -4351,7 +4411,8 @@ export async function cutJoins({ schedule = null, entries, segments, render }) { Math.round((base?.[i]?.hold ?? 0) * render.fps); const seconds = endFadeOf(render); let fade = null; - if (seconds > 0 && segments.length) { + // A cut that ends on a video entry ENDS on its final frame (video-entry.mjs): no end fade. + if (seconds > 0 && segments.length && entries[segments.length - 1]?.type !== "video") { const last = segments.length - 1; fade = { seconds, lastFrame: (await cutFrames(last)) - 1 }; } @@ -4849,6 +4910,7 @@ export function xfadeConcatArgs({ segments, durs, render, outPath, railPlan = nu ? chromeOverlayChain(render, chromeIn.regions, vlab, main.length + railInputs, { outLabel: chromeIn.outLabel, final: !rc, + blackouts: chromeIn.blackouts ?? null, }) : null; if (hf) parts.push(hf.chain); @@ -4961,8 +5023,9 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins } } const first0 = segs.length; - const hf = regions.length ? chromeOverlayChain(render, regions, "[vw]", first0, { final: true }) : null; - const hk = keyRegions.length ? chromeOverlayChain(render, keyRegions, "[vw]", first0, { final: true }) : null; + const bo = { blackouts: chrome?.blackouts ?? null, shift: a / fps }; + const hf = regions.length ? chromeOverlayChain(render, regions, "[vw]", first0, { final: true, ...bo }) : null; + const hk = keyRegions.length ? chromeOverlayChain(render, keyRegions, "[vw]", first0, { final: true, ...bo }) : null; let tail = "[vw]"; if (hf) { parts.push(hf.chain); @@ -5558,7 +5621,7 @@ async function applyRail(inPath, outPath, render, railPlan, preview, dips = null * function draws one. */ export function applyChromeArgs(inPath, outPath, render, chromePlan, preview = null, dips = null) { - const hf = chromeOverlayChain(render, chromePlan.regions, "[0:v]", 1, { final: true }); + const hf = chromeOverlayChain(render, chromePlan.regions, "[0:v]", 1, { final: true, blackouts: chromePlan.blackouts ?? null, shift: preview ? Number(preview.start) : 0 }); // The dips over the overlay: the whole frame, the panel with the footage. const dp = dipParts(hf.outLabel, dips, render.fps, { shift: preview ? Number(preview.start) : 0 }); return [ @@ -5636,7 +5699,7 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re const T = Number(dur).toFixed(3); parts.push(`${vlab}trim=start=${S}:duration=${T},setpts=PTS-STARTPTS[vw]`); parts.push(`${alab}atrim=start=${S}:duration=${T},asetpts=PTS-STARTPTS[aw]`); - const hf = chromeOverlayChain(render, chromePlan.regions, "[vw]", segs.length, { final: true }); + const hf = chromeOverlayChain(render, chromePlan.regions, "[vw]", segs.length, { final: true, blackouts: chromePlan.blackouts ?? null, shift: Number(at) }); parts.push(hf.chain); // The cut's dips (its whole joins and lengths), in the window's clock. const dp = dipParts(hf.outLabel, dipWindows(joins, durs, D, render.fps), render.fps, { shift: Number(at) }); @@ -5773,7 +5836,10 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro await logRebuild(outDir, { phase: "chrome", seconds: Number(((Date.now() - tAll) / 1000).toFixed(1)), workers: pool.budget, renders: CHROME_LAYERS, layers }); } - return { regions, outLabel: "[hfout]" }; + // Over a video entry the chrome is OFF (video-entry.mjs): each region's overlay leaves its span out. + // Only when the cut has one, so every other cut's graph is the one it was. + const blackouts = videoBlackouts(schedule); + return { regions, outLabel: "[hfout]", ...(blackouts.length ? { blackouts } : {}) }; } /** @@ -6387,7 +6453,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // manifest, deck or not: both are made where the cut is joined. { const errors = [ - ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), + ...validateCutEdits(whole), ...validateTeasers(whole), ...validateVideoEntries(whole), ...validateClaims(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole, { schedule: false }), ...validateTransitionStyle(whole), ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole), @@ -6518,8 +6584,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // A still has nothing to fetch and is already on disk, so this is a no-op // rather than an error: a bench that walks the timeline asking for each // entry's window should not have to know which kinds have one. - if (entry?.type === "image" || entry?.type === "teaser" || entry?.type === "post" || (entry?.type === "clip" && hasLocalMedia(entry))) { - const what = entry.type === "image" ? "an image" : entry.type === "teaser" ? "a teaser" : entry.type === "post" ? "a post item (its media is in the project)" : "a clip with its own `src`"; + if (entry?.type === "image" || entry?.type === "teaser" || entry?.type === "post" || entry?.type === "video" || (entry?.type === "clip" && hasLocalMedia(entry))) { + const what = entry.type === "image" ? "an image" : entry.type === "teaser" ? "a teaser" : entry.type === "video" ? "a video (a file of the project)" : entry.type === "post" ? "a post item (its media is in the project)" : "a clip with its own `src`"; EMIT("note", { message: `${fetchOnly} is ${what} entry — nothing to fetch` }); EMIT("done", { out: null, nothingToFetch: true }); return { out: null, failures: [] }; @@ -6738,6 +6804,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } // A post item (post-render.mjs) keeps a segment `--from` linked in when its key matches (its record, `.post.json`, // linked beside it) and writes every file of its own through a rename -- never through the link -- when it does not. + // A video entry (video-entry.mjs): keyed like a post item, every file written through a rename. + if (entry.type === "video") { + EMIT("card", { id: entry.id, i, n: entries.length }); + return buildVideoEntrySegment(entry, render, outDir, manifestDir, D, manifest.timeline); + } if (entry.type !== "teaser" && entry.type !== "clip" && entry.type !== "post") { await detachSegmentFiles(path.join(outDir, "segments"), entry.id); } diff --git a/umtool/report-to-video/clip-audio.mjs b/umtool/report-to-video/clip-audio.mjs @@ -63,7 +63,8 @@ export function validateClipAudio(audio, where = "audio") { export function validateClipAudioEntries(manifest) { const errors = []; (manifest?.timeline ?? []).forEach((e, i) => { - if (e?.audio === undefined) return; + // A video entry's `audio` (bass, gain) is its own: video-entry.mjs validates it. + if (e?.audio === undefined || e?.type === "video") return; const where = `timeline[${i}] (${e.id ?? "?"}).audio`; if (e.type && e.type !== "clip") { errors.push(`${where}: only a clip's sound has these settings`); return; } errors.push(...validateClipAudio(e.audio, where)); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -23,6 +23,7 @@ import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; import { attributionParts, deckSubtitle, deckSubtitleLines, formatDeckDate } from "./attribution.mjs"; import { postDeckText, postItemSeconds } from "./post-item.mjs"; +import { videoDip, videoEnter, videoHidesChrome, videoSeconds } from "./video-entry.mjs"; import { claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, tallyOf, tallyVerdicts, validateFactcheck, } from "./factcheck.mjs"; @@ -980,6 +981,8 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render)) return Math.max(1, gappedLength(from, to, renderGaps(entry, render))); } if (entry.type === "image") return Number(entry.seconds ?? 4); + // A video entry (video-entry.mjs): its entrance's black, its span, its hold. + if (entry.type === "video") return videoSeconds(entry, D); // A post item (post-item.mjs): its reading time and its attachments, or its `hold`. if (entry.type === "post") return postItemSeconds(entry, render); // The brand intro (intro.mjs) is exactly its `seconds` (introEntry fills the default). @@ -1025,6 +1028,8 @@ export function isMultiChannel(entries, provenance = {}) { export function hidesDeck(entry, deck) { // A teaser and the brand intro are full frame: never framed into the footage box. if (entry.type === "teaser" || entry.type === "intro") return true; + // A video entry is the whole frame, nothing over it -- unless it says `deck: "shown"`. + if (entry.type === "video") return videoHidesChrome(entry); return deck.overCards === "hide" && CARD_TYPES.includes(entry.type); } @@ -1285,6 +1290,9 @@ export function deckSchedule({ ...(marksOf(e, series).some((c) => c.at !== undefined) || claimClips.has(e.id) ? { sourceFrom: round(clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from) } : {}), + // Only on a video entry (video-entry.mjs): the chrome off over it, and how it is entered. + ...(e.type === "video" && videoHidesChrome(e) ? { noChrome: true } : {}), + ...(e.type === "video" && videoEnter(e) ? { enter: videoEnter(e) } : {}), // Only on a finale clip, likewise. ...(finIds.has(e.id) ? { finale: true } : {}), // And off the rail, when the finale says so (finale.pips: false). @@ -3053,6 +3061,8 @@ export function snapToFrames(seconds, fps = 30) { * black (`dipWindows`' `until`) all fall on the same frame. */ export function dipOf(entry, fps = 30) { + // A video entry's entrance is a dip with no black (video-entry.mjs videoDip). + if (entry?.type === "video") return videoDip(entry); if (entry?.type !== "teaser" || !isObj(entry.dip)) return null; const { fade, black } = entry.dip; if (!numIn(fade, ...DIP_LIMITS.fade) || !numIn(black, ...DIP_LIMITS.black)) return null; diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -76,6 +76,7 @@ import { existsSync } from "node:fs"; import path from "node:path"; +import { validateVideoEntries } from "./video-entry.mjs"; import { deckOn, deckQrUrl, estimateSchedule, postArchiveUrl, postNativeId, postQrUrl, resolveDeck, teaserLines, validateChrome, validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, deckClaimNotes, validateDeckClaims, @@ -298,7 +299,7 @@ function fxLintSchedule(whole) { export function validatorErrors(whole) { const errors = [ - ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateClipAudioEntries(whole), + ...validateCutEdits(whole), ...validateTeasers(whole), ...validateVideoEntries(whole), ...validateClaims(whole), ...validateClipAudioEntries(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), // The podcast's settings: its render refuses them, and `--lint` says so first. ...validatePodcast(whole), diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -18,6 +18,7 @@ }, "exports": { "./attribution": "./attribution.mjs", + "./video-entry": "./video-entry.mjs", "./site-links": "./site-links.mjs", "./brand": "./brand.mjs", "./brand-ids": "./brand-ids.mjs", diff --git a/umtool/report-to-video/video-entry.mjs b/umtool/report-to-video/video-entry.mjs @@ -0,0 +1,330 @@ +// video-entry.mjs — a `video` timeline entry: a file of the project played +// FULL FRAME, with its own sound, and nothing drawn over it. +// +// { "type": "video", "id": "fin-vid", +// "src": "posts-media/ObviousRises-x/2117366108705767779/2117366108705767779_1.mp4", +// "from": 32.26, // source seconds; default 0 +// "to": 46.32, // source seconds; absent = the file's end +// "fit": "contain", // "contain" (default: letter/pillarboxed on black) | "cover" (fills, cropped) +// "audio": { "bass": 8, "gain": 0 }, // dB: a low shelf boost (100 Hz), and a gain +// "enter": { "out": 0.5, "in": 0.5 }, // the join INTO it: the item before (its chrome too) fades to +// // black over its last `out` s, then this fades up over `in` s; +// // "cut" opts out (the cut's own transition) +// "holdLast": 0, // s on its last frame after `to`; default 0 +// "deck": "hidden", // default: NOTHING over it; "shown" keeps the chrome +// "fileSeconds": 46.32, // the file's probed length, written by the CLI (the estimate's `to`) +// "title": "…", "note": "…" } +// +// Where `image` is a still and a `clip` is a corpus window framed into the +// deck's box, this is a plain project video as the whole 1920x1080 frame: the +// deck, the header, the QR, the rail, the counters, the captions, every +// overlay layer are off over it (build-video lays every chrome region with an +// `enable` that leaves its span out -- `videoBlackouts`), and Play draws it +// the same way. As the LAST entry the cut ENDS on its final frame: no end +// fade (`render.endFade` is skipped), nothing after it. +// +// Its sound is levelled like a clip's: the bass boost first, the whole span +// measured with it (ebur128), one gain toward the cut's level +// (`videoLoudnessTarget`: `render.loudness`, else its narration's level); `audio.gain` after that levelling, as a +// clip's `audio.gain` is; a boost's peaks limited under −1 dBFS. Fades only where the join needs them: the fade up after +// the entrance's black, none at its end. +// +// A LEAF: no imports from build-video.mjs (it imports this), so umtool's +// writers and Play read the same rules. + +import { NARRATION_DEFAULTS } from "./narration.mjs"; +import { POST_NARRATION_DEFAULTS } from "./post-narration.mjs"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +export const VIDEO_FITS = Object.freeze(["contain", "cover"]); +export const VIDEO_DECKS = Object.freeze(["hidden", "shown"]); +export const VIDEO_AUDIO_LIMITS = Object.freeze({ + gain: Object.freeze({ min: -20, max: 20, unit: "dB" }), + bass: Object.freeze({ min: -12, max: 24, unit: "dB" }), +}); +export const VIDEO_ENTER_DEFAULT = Object.freeze({ out: 0.5, in: 0.5 }); +export const VIDEO_ENTER_LIMITS = Object.freeze({ out: Object.freeze([0.1, 4]), in: Object.freeze([0, 4]) }); +export const VIDEO_HOLD_MAX = 10; +/** The bass boost: a low shelf at this frequency and width (ffmpeg `bass`). */ +export const VIDEO_BASS = Object.freeze({ f: 100, w: 0.7 }); +/** Bumped when the segment's drawing or sound changes, so every key changes with it. */ +export const VIDEO_SEGMENT_V = 2; +/** The ceiling a boosted video's sound is limited to: −1 dBFS. */ +export const VIDEO_LIMIT = 0.891; + +/** The keys a video entry is SET by (umtool set / timeline add-video). */ +export const VIDEO_SET_KEYS = Object.freeze(["src", "from", "to", "fit", "audio.bass", "audio.gain", "enter", "enter.out", "enter.in", "holdLast", "deck", "title", "note"]); + +export const isVideoEntry = (e) => e?.type === "video"; + +/** + * Every reason a video entry cannot be built, as sentences naming `where`. + * Its `src` is checked as a path here (relative, inside the project); whether + * the file is there is the build's and the writer's (`validateVideoFiles`). + */ +export function validateVideoEntry(e, where = `timeline entry ${e?.id ?? "?"}`) { + if (!isVideoEntry(e)) return []; + const errors = []; + if (typeof e.src !== "string" || !e.src.trim()) errors.push(`${where}: a video entry needs \`src\`, a file of the project`); + else if (e.src.startsWith("/") || /^[a-z]+:\/\//i.test(e.src)) errors.push(`${where}.src must be a path relative to the project (got ${e.src})`); + else if (e.src.split(/[\\/]/).includes("..")) errors.push(`${where}.src climbs out of the project (${e.src})`); + if (e.from !== undefined && !(fin(e.from) && e.from >= 0)) errors.push(`${where}.from must be a number of seconds, 0 or more`); + if (e.to !== undefined && e.to !== null && !(fin(e.to) && e.to > 0)) errors.push(`${where}.to must be a number of seconds (absent: the file's end)`); + if (fin(e.to) && e.to - (fin(e.from) ? e.from : 0) < 0.2) errors.push(`${where}: to must be at least 0.2 s after from`); + if (e.fileSeconds !== undefined && !(fin(e.fileSeconds) && e.fileSeconds > 0)) errors.push(`${where}.fileSeconds must be the file's length in seconds`); + if (e.fit !== undefined && !VIDEO_FITS.includes(e.fit)) errors.push(`${where}.fit must be ${VIDEO_FITS.join(" or ")}`); + if (e.deck !== undefined && !VIDEO_DECKS.includes(e.deck)) errors.push(`${where}.deck must be ${VIDEO_DECKS.join(" or ")}`); + if (e.holdLast !== undefined && !(fin(e.holdLast) && e.holdLast >= 0 && e.holdLast <= VIDEO_HOLD_MAX)) errors.push(`${where}.holdLast must be from 0 to ${VIDEO_HOLD_MAX} seconds`); + if (e.audio !== undefined && e.audio !== null) { + if (!isObj(e.audio)) errors.push(`${where}.audio must be { bass, gain } in dB`); + else { + for (const k of Object.keys(e.audio)) if (!(k in VIDEO_AUDIO_LIMITS)) errors.push(`${where}.audio.${k} is not a video's audio setting (bass, gain)`); + for (const [k, { min, max, unit }] of Object.entries(VIDEO_AUDIO_LIMITS)) { + const v = e.audio[k]; + if (v !== undefined && !(fin(v) && v >= min && v <= max)) errors.push(`${where}.audio.${k} must be a number from ${min} to ${max} (${unit})`); + } + } + } + if (e.enter !== undefined && e.enter !== "cut") { + if (!isObj(e.enter)) errors.push(`${where}.enter must be "cut" or { out, in } in seconds`); + else { + for (const k of Object.keys(e.enter)) if (!(k in VIDEO_ENTER_LIMITS)) errors.push(`${where}.enter.${k} is not an entrance setting (out, in)`); + for (const [k, [lo, hi]] of Object.entries(VIDEO_ENTER_LIMITS)) { + const v = e.enter[k]; + if (v !== undefined && !(fin(v) && v >= lo && v <= hi)) errors.push(`${where}.enter.${k} must be from ${lo} to ${hi} seconds`); + } + } + } + for (const k of ["title", "note"]) if (e[k] !== undefined && typeof e[k] !== "string") errors.push(`${where}.${k} must be text`); + return errors; +} + +/** Every video entry's problems in a manifest's timeline (and nothing for a timeline without one). */ +export function validateVideoEntries(manifest) { + const errors = []; + (manifest?.timeline ?? []).forEach((e, i) => { + if (isVideoEntry(e)) errors.push(...validateVideoEntry(e, `timeline[${i}] (${e?.id ?? "?"})`)); + }); + return errors; +} + +/** Its fit: "contain" unless it says "cover". */ +export const videoFit = (e) => (e?.fit === "cover" ? "cover" : "contain"); + +/** Is the chrome drawn over it? Only with `deck: "shown"`. */ +export const videoHidesChrome = (e) => isVideoEntry(e) && e.deck !== "shown"; + +/** Its entrance, `{ out, in }` (the defaults filled), or null for `enter: "cut"`. */ +export function videoEnter(e) { + if (!isVideoEntry(e) || e.enter === "cut") return null; + const o = isObj(e.enter) ? e.enter : {}; + return { out: fin(o.out) ? o.out : VIDEO_ENTER_DEFAULT.out, in: fin(o.in) ? o.in : VIDEO_ENTER_DEFAULT.in }; +} + +/** Its audio knobs, `{ bass, gain }` in dB (0 when absent). */ +export function videoAudio(e) { + const a = isObj(e?.audio) ? e.audio : {}; + return { bass: fin(a.bass) ? a.bass : 0, gain: fin(a.gain) ? a.gain : 0 }; +} + +/** + * The source span it plays, `{ from, to }`: `to` absent is the file's end + * (`fileSeconds`, the probed length the build passes, else the entry's own + * `fileSeconds`). Clamped into the file when its length is known. + */ +export function videoSpan(e, fileSeconds = null) { + const len = fin(fileSeconds) ? fileSeconds : fin(e?.fileSeconds) ? e.fileSeconds : null; + const from = fin(e?.from) ? Math.max(0, e.from) : 0; + let to = fin(e?.to) ? e.to : len ?? from + 5; + if (len != null) to = Math.min(to, len); + return { from: Math.min(from, Math.max(0, to - 0.2)), to }; +} + +/** + * The dark start of its segment, in its own clock: the dissolve into it (`D`) + * when it enters with a fade -- the item before fades to black over that + * dissolve (a dip, as a teaser's), so the video's first frame plays after it, + * never under it. 0 for `enter: "cut"`. + */ +export const videoLead = (e, D = 0.5) => (videoEnter(e) ? Math.max(0, Number(D) || 0) : 0); + +/** + * Its segment's length: the lead, the span (`to − from`) and `holdLast`. The + * span is never shortened by the fades. + */ +export function videoSeconds(e, D = 0.5, fileSeconds = null) { + const { from, to } = videoSpan(e, fileSeconds); + const hold = fin(e?.holdLast) ? e.holdLast : 0; + return Math.round((videoLead(e, D) + (to - from) + hold) * 10000) / 10000; +} + +/** + * Its entrance as a dip on the segment before it (deck.mjs `dipOf`'s shape, + * `{ fade, black }`): the previous picture and every overlay fade to black + * over `out`, with no held black (the fade up is the video's own). + */ +export function videoDip(e) { + const en = videoEnter(e); + return en ? { fade: en.out, black: 0 } : null; +} + +/** + * The ffmpeg graph for its segment: picture `[0:v]` → `[v]`, sound `[0:a]` → + * `[a]` (or a silent bed when the file has none). Pure. `gainDb` is the + * loudness gain the build measured (null: none); `lead` its dark start. + */ +export function videoSegmentGraph({ entry, render, seconds, lead = 0, hasAudio = true, gainDb = null, span }) { + const { width: W, height: H, fps } = render; + const n = (v) => String(Math.round(Number(v) * 1e6) / 1e6); + const fit = videoFit(entry); + const en = videoEnter(entry); + const hold = fin(entry?.holdLast) ? entry.holdLast : 0; + const scale = fit === "cover" + ? [`scale=${W}:${H}:force_original_aspect_ratio=increase`, `crop=${W}:${H}`] + : [`scale=${W}:${H}:force_original_aspect_ratio=decrease`, `pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=black`]; + const v = [ + `[0:v]trim=start=${n(span.from)}:end=${n(span.to)},setpts=PTS-STARTPTS`, + `fps=${fps}`, + ...scale, + "setsar=1", + ...(lead > 0 ? [`tpad=start_duration=${n(lead)}:start_mode=add:color=black`] : []), + ...(hold > 0 ? [`tpad=stop_duration=${n(hold)}:stop_mode=clone`] : []), + ...(en && en.in > 0 ? [`fade=t=in:st=${n(lead)}:d=${n(en.in)}`] : []), + `trim=end=${n(seconds)}`, + "format=yuv420p[v]", + ].join(","); + const { bass, gain } = videoAudio(entry); + const ms = Math.round(lead * 1000); + const a = hasAudio + ? [ + `[0:a]atrim=start=${n(span.from)}:end=${n(span.to)},asetpts=PTS-STARTPTS`, + `aresample=${render.audioRate ?? 48000}`, + ...(bass ? [`bass=g=${n(bass)}:f=${VIDEO_BASS.f}:w=${VIDEO_BASS.w}`] : []), + ...(gainDb ? [`volume=${n(gainDb)}dB`] : []), + ...(gain ? [`volume=${n(gain)}dB`] : []), + // A boost's peaks under full scale (−1 dBFS): the encoder squashes what goes past it. + ...(bass > 0 || gain > 0 ? [`alimiter=limit=${VIDEO_LIMIT}:level=false`] : []), + ...(en && en.in > 0 ? [`afade=t=in:st=0:d=${n(en.in)}`] : []), + ...(ms > 0 ? [`adelay=${ms}:all=1`] : []), + `apad=whole_dur=${n(seconds)}`, + `atrim=end=${n(seconds)}[a]`, + ].join(",") + : `anullsrc=r=${render.audioRate ?? 48000}:cl=${(render.audioChannels ?? 2) === 1 ? "mono" : "stereo"},atrim=end=${n(seconds)}[a]`; + return `${v};${a}`; +} + +/** + * The loudness (LUFS) a video entry's sound is levelled to: the cut's target + * (`render.loudness`, `loudnessTarget` the caller resolved) when it has one; + * else the level the cut's own voice sits at -- its post items' narration + * (`render.postNarration.lufs`, default −21) when it has post items, a + * narrated card's (−17.7) otherwise -- so a hot meme does not jump out of the + * cut. `{ target, basis }`. + */ +export function videoLoudnessTarget(render, timeline = [], loudnessTarget = null) { + if (fin(loudnessTarget)) return { target: loudnessTarget, basis: "render.loudness" }; + if ((timeline ?? []).some((e) => e?.type === "post")) { + const l = render?.postNarration?.lufs; + return { target: fin(l) ? l : POST_NARRATION_DEFAULTS.lufs, basis: "render.postNarration.lufs" }; + } + return { target: NARRATION_DEFAULTS.lufs, basis: "narration" }; +} + +/** The audio chain the loudness is measured through: the bass boost, as the segment plays it. */ +export function videoMeasureFilter(entry) { + const { bass } = videoAudio(entry); + return bass ? `bass=g=${bass}:f=${VIDEO_BASS.f}:w=${VIDEO_BASS.w}` : "anull"; +} + +/** + * Its segment's KEY: what it is built from -- the file (its path, size and + * mtime), the span, the fit, the audio, the entrance, the hold, the lead (the + * cut's transition), the frame and the loudness target. The same key: the + * segment on disk is reused. + */ +export function videoSegmentKey({ entry, file, render, lead, target = null }) { + const { from, to } = videoSpan(entry, file.seconds); + return JSON.stringify({ + v: VIDEO_SEGMENT_V, + src: entry.src, size: file.size, mtime: file.mtimeMs, + from, to, fit: videoFit(entry), audio: videoAudio(entry), enter: videoEnter(entry), + holdLast: fin(entry.holdLast) ? entry.holdLast : 0, lead, + frame: [render.width, render.height, render.fps, render.audioRate, render.audioChannels, render.crf ?? 20, render.preset ?? "medium"], + target, + }); +} + +/** + * The cut seconds the chrome is OFF over, `[a, b]` pairs from the schedule's + * segments: each video entry that hides it, from the frame the dip into it + * has made black (the segment's start + the dissolve − a frame; mid-dissolve + * for `enter: "cut"`) to its end (mid-dissolve into the next, or the cut's + * end). Empty for a cut without one -- and then nothing changes. + * + * @param {{ segments: Array<{ type: string, start: number, end: number, noChrome?: boolean, dip?: object }>, total: number, fps?: number, transition?: number }} schedule + */ +export function videoBlackouts(schedule) { + const segs = schedule?.segments ?? []; + const D = Number(schedule?.transition ?? 0) || 0; + const fps = Number(schedule?.fps ?? 30) || 30; + const out = []; + segs.forEach((s, i) => { + if (s.type !== "video" || !s.noChrome) return; + const entered = i > 0 && s.enter ? s.start + D - 1 / fps : i > 0 ? s.start + D / 2 : 0; + const last = i === segs.length - 1; + const b = last ? Number(schedule.total ?? s.end) + 1 : s.end - D / 2; + out.push([Math.max(0, Math.round(entered * 1e4) / 1e4), Math.round(b * 1e4) / 1e4]); + }); + return out; +} + +/** An overlay's `enable` for blackouts in a stream whose clock starts `shift` s into the cut; "" with none. */ +export function blackoutEnable(blackouts, shift = 0) { + if (!blackouts?.length) return ""; + const n = (v) => String(Math.round(Number(v) * 1e6) / 1e6); + return `:enable='not(${blackouts.map(([a, b]) => `between(t,${n(a - shift)},${n(b - shift)})`).join("+")})'`; +} + +/** + * A video entry with `patch` applied (VIDEO_SET_KEYS; `audio.bass`, `enter.out` + * dotted; `enter: "cut"` or `"<out>,<in>"`; null or "" removes a key). A new + * object; the caller validates it (validateVideoEntry). Throws on a key it + * does not set. + */ +export function applyVideoPatch(entry, patch) { + const e = JSON.parse(JSON.stringify(entry)); + const num = (k, v) => { + const n = Number(v); + if (!Number.isFinite(n)) throw new Error(`${k} must be a number (got ${v})`); + return Math.round(n * 1000) / 1000; + }; + for (const [k, v] of Object.entries(patch ?? {})) { + if (!VIDEO_SET_KEYS.includes(k)) throw new Error(`${k} is not a video entry's setting (${VIDEO_SET_KEYS.join(", ")})`); + const clear = v === null || v === undefined || v === ""; + const [head, sub] = k.split("."); + if (sub) { + if (head === "enter" && (e.enter === "cut" || !isObj(e.enter))) e.enter = {}; + if (head === "audio" && !isObj(e.audio)) e.audio = {}; + if (clear) delete e[head][sub]; + else e[head][sub] = num(k, v); + if (!Object.keys(e[head]).length) delete e[head]; + continue; + } + if (clear) { + delete e[k]; + continue; + } + if (k === "from" || k === "to" || k === "holdLast") e[k] = num(k, v); + else if (k === "enter") { + if (v === "cut") e.enter = "cut"; + else if (isObj(v)) e.enter = v; + else { + const [o, i] = String(v).split(",").map((x) => x.trim()); + e.enter = { out: num("enter.out", o), ...(i !== undefined && i !== "" ? { in: num("enter.in", i) } : {}) }; + } + } else e[k] = String(v); + } + return e; +} diff --git a/umtool/report-to-video/video-entry.test.mjs b/umtool/report-to-video/video-entry.test.mjs @@ -0,0 +1,171 @@ +// A `video` timeline entry (video-entry.mjs): a file of the project played +// full frame with its own sound, no chrome over it. Pure parts here; the +// build is exercised on a real file at the end (skipped without ffmpeg). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + applyVideoPatch, blackoutEnable, validateVideoEntries, validateVideoEntry, videoBlackouts, videoDip, videoEnter, + videoHidesChrome, videoLead, videoLoudnessTarget, videoSeconds, videoSegmentGraph, videoSegmentKey, videoSpan, +} from "./video-entry.mjs"; +import { deckSchedule, dipOf, estimatedDuration, hidesDeck, resolveDeck } from "./deck.mjs"; +import { chromeOverlayChain, cutJoins } from "./build-video.mjs"; +import { validateClipAudioEntries } from "./clip-audio.mjs"; + +const FIN = { type: "video", id: "fin", src: "posts-media/x/1/1_1.mp4", from: 32.26, fileSeconds: 46.32, audio: { bass: 8 } }; + +test("a video entry validates; the vocabulary stays open", () => { + assert.deepEqual(validateVideoEntry(FIN), []); + assert.deepEqual(validateVideoEntry({ type: "video", id: "v", src: "a.mp4", to: 3, fit: "cover", enter: "cut", holdLast: 1, deck: "shown", audio: { gain: -3 } }), []); + const bad = validateVideoEntry({ type: "video", id: "v", src: "../x.mp4", from: -1, fit: "wide", audio: { bass: 40, treble: 1 }, enter: { out: 9 }, deck: "maybe", holdLast: 99 }); + for (const w of ["climbs out", ".from", ".fit", "audio.bass", "audio.treble", "enter.out", ".deck", ".holdLast"]) { + assert.ok(bad.some((e) => e.includes(w)), `${w} in ${bad.join(" | ")}`); + } + assert.ok(validateVideoEntry({ type: "video", id: "v" })[0].includes("needs `src`")); + assert.ok(validateVideoEntry({ type: "video", id: "v", src: "/abs.mp4" })[0].includes("relative")); + assert.ok(validateVideoEntry({ type: "video", id: "v", src: "a.mp4", from: 5, to: 5.1 })[0].includes("0.2 s")); + // Other types are none of its business, and a clip's `audio` rule leaves a video's alone. + assert.deepEqual(validateVideoEntries({ timeline: [{ type: "mystery", id: "m" }, { type: "card", id: "k" }, FIN] }), []); + assert.deepEqual(validateClipAudioEntries({ timeline: [FIN] }), []); +}); + +test("its span, lead and segment length: to − from (+ holdLast), never shortened by the fades", () => { + assert.deepEqual(videoSpan(FIN), { from: 32.26, to: 46.32 }); + assert.deepEqual(videoSpan({ ...FIN, to: 50 }, 46.32), { from: 32.26, to: 46.32 }); + assert.equal(videoLead(FIN, 0.4), 0.4); + assert.equal(videoLead({ ...FIN, enter: "cut" }, 0.4), 0); + assert.equal(videoSeconds(FIN, 0.4), 14.46); // 0.4 lead + 14.06 + assert.equal(videoSeconds({ ...FIN, enter: "cut" }, 0.4), 14.06); + assert.equal(videoSeconds({ ...FIN, holdLast: 1.5 }, 0), 15.56); + assert.equal(estimatedDuration(FIN, { transition: 0.4 }, 0.4), 14.46); + assert.deepEqual(videoEnter(FIN), { out: 0.5, in: 0.5 }); + assert.deepEqual(videoEnter({ ...FIN, enter: { out: 1 } }), { out: 1, in: 0.5 }); + assert.equal(videoEnter({ ...FIN, enter: "cut" }), null); + // The entrance is a dip on the item before: no held black (the fade up is its own). + assert.deepEqual(dipOf(FIN), { fade: 0.5, black: 0 }); + assert.deepEqual(videoDip({ ...FIN, enter: { out: 0.8, in: 0.2 } }), { fade: 0.8, black: 0 }); + assert.equal(dipOf({ ...FIN, enter: "cut" }), null); +}); + +test("no chrome over it by default; `deck: shown` keeps it", () => { + const deck = resolveDeck({}); + assert.equal(videoHidesChrome(FIN), true); + assert.equal(hidesDeck(FIN, deck), true); + assert.equal(hidesDeck({ ...FIN, deck: "shown" }, deck), false); +}); + +test("its graph: fit, the bass before the level, the fade up after the lead, no fade at the end", () => { + const render = { width: 1920, height: 1080, fps: 30, audioRate: 48000, audioChannels: 2 }; + const span = videoSpan(FIN); + const g = videoSegmentGraph({ entry: FIN, render, seconds: 14.46, lead: 0.4, gainDb: -2.5, span }); + assert.match(g, /trim=start=32\.26:end=46\.32/); + assert.match(g, /scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:\(ow-iw\)\/2:\(oh-ih\)\/2:color=black/); + assert.match(g, /tpad=start_duration=0\.4:start_mode=add:color=black/); + assert.match(g, /fade=t=in:st=0\.4:d=0\.5/); + assert.doesNotMatch(g, /fade=t=out/); + // Bass first, then the measured level. + assert.ok(g.indexOf("bass=g=8:f=100:w=0.7") < g.indexOf("volume=-2.5dB")); + assert.match(g, /adelay=400:all=1/); + // A boost's peaks limited, after the level; none for a plain video. + assert.ok(g.indexOf("alimiter=limit=0.891:level=false") > g.indexOf("volume=-2.5dB")); + assert.doesNotMatch(videoSegmentGraph({ entry: { ...FIN, audio: undefined }, render, seconds: 14.46, lead: 0.4, span }), /alimiter/); + const cover = videoSegmentGraph({ entry: { ...FIN, fit: "cover", enter: "cut" }, render, seconds: 14.06, lead: 0, span }); + assert.match(cover, /force_original_aspect_ratio=increase,crop=1920:1080/); + assert.doesNotMatch(cover, /fade=t=in|tpad|adelay/); + const silent = videoSegmentGraph({ entry: FIN, render, seconds: 14.46, lead: 0.4, hasAudio: false, span }); + assert.match(silent, /anullsrc=r=48000:cl=stereo,atrim=end=14\.46\[a\]/); +}); + +test("its key: src, span, fit, audio, entrance, hold, lead and the file", () => { + const render = { width: 1920, height: 1080, fps: 30 }; + const file = { size: 100, mtimeMs: 5, seconds: 46.32 }; + const k = videoSegmentKey({ entry: FIN, file, render, lead: 0.4 }); + assert.equal(k, videoSegmentKey({ entry: { ...FIN }, file, render, lead: 0.4 })); + for (const changed of [{ ...FIN, from: 30 }, { ...FIN, to: 40 }, { ...FIN, fit: "cover" }, { ...FIN, audio: { bass: 6 } }, { ...FIN, src: "b.mp4" }, { ...FIN, holdLast: 1 }, { ...FIN, enter: "cut" }]) { + assert.notEqual(videoSegmentKey({ entry: changed, file, render, lead: 0.4 }), k, JSON.stringify(changed)); + } + assert.notEqual(videoSegmentKey({ entry: FIN, file: { ...file, mtimeMs: 6 }, render, lead: 0.4 }), k); + assert.notEqual(videoSegmentKey({ entry: FIN, file, render, lead: 0 }), k); +}); + +test("the schedule carries it; the chrome is off from the black to the cut's end", () => { + const render = { width: 1920, height: 1080, fps: 30, transition: 0.4, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }; + const entries = [{ type: "card", id: "k01", seconds: 3, heading: "x" }, FIN]; + const doc = deckSchedule({ entries, durs: [3, 14.46], D: 0.4, render }); + const v = doc.segments[1]; + assert.equal(v.type, "video"); + assert.equal(v.hideDeck, true); + assert.equal(v.noChrome, true); + assert.deepEqual(v.enter, { out: 0.5, in: 0.5 }); + assert.equal(doc.segments[0].noChrome, undefined); + const bo = videoBlackouts(doc); + assert.equal(bo.length, 1); + // From the frame the dip made black (2.6 + 0.4 − 1/30) past the end. + assert.ok(Math.abs(bo[0][0] - (2.6 + 0.4 - 1 / 30)) < 1e-3, String(bo[0][0])); + assert.ok(bo[0][1] > doc.total); + // Shown: no blackout. A cut without one: none. + assert.deepEqual(videoBlackouts(deckSchedule({ entries: [entries[0], { ...FIN, deck: "shown" }], durs: [3, 14.46], D: 0.4, render })), []); + assert.deepEqual(videoBlackouts(deckSchedule({ entries: [entries[0]], durs: [3], D: 0.4, render })), []); +}); + +test("every overlay leaves the blackout out; without one the chain is the one it was", () => { + const render = { fps: 30 }; + const regions = [{ name: "deck", frames: "/f/deck", x: 0, y: 900 }, { name: "posts", frames: "/f/p", x: 10, y: 10, offset: 2 }]; + const plain = chromeOverlayChain(render, regions, "[v]", 3, {}); + const none = chromeOverlayChain(render, regions, "[v]", 3, { blackouts: [] }); + assert.equal(none.chain, plain.chain); + assert.doesNotMatch(plain.chain, /enable=/); + const off = chromeOverlayChain(render, regions, "[v]", 3, { blackouts: [[2.9667, 20]] }); + assert.equal((off.chain.match(/enable='not\(between\(t,2\.9667,20\)\)'/g) ?? []).length, 2); + // A chunk's clock starts `shift` seconds in. + assert.equal(blackoutEnable([[2.9667, 20]], 2), ":enable='not(between(t,0.9667,18))'"); + assert.equal(blackoutEnable([], 2), ""); +}); + +test("the cut ENDS on the video's final frame: no end fade when it is last; the dip into it on the item before", async () => { + const dir = mkdtempSync(path.join(os.tmpdir(), "video-entry-")); + const segs = ["a.mp4", "b.mp4"].map((n) => path.join(dir, n)); + let ffmpeg = true; + try { + for (const [i, s] of segs.entries()) execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `color=c=black:s=64x36:r=30:d=${i ? 2 : 1}`, "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-t", String(i ? 2 : 1), "-c:v", "libx264", "-c:a", "aac", s]); + } catch { + ffmpeg = false; + } + if (!ffmpeg) return; + const render = { fps: 30, endFade: 1, transition: 0.4 }; + const card = { type: "card", id: "k01", seconds: 1 }; + const withVideo = await cutJoins({ entries: [card, FIN], segments: segs, render }); + assert.ok(!withVideo?.[1]?.fade, "no end fade on the video"); + assert.deepEqual(withVideo[0].dip.seconds, 0.5); + const withCard = await cutJoins({ entries: [FIN, card], segments: segs, render }); + assert.ok(withCard?.[1]?.fade, "the end fade as ever when it is not last"); + const cutIn = await cutJoins({ entries: [card, { ...FIN, enter: "cut" }], segments: segs, render: { fps: 30, transition: 0.4 } }); + assert.equal(cutIn, null); +}); + +test("applyVideoPatch: dotted keys, enter forms, clearing, refusing a key it does not set", () => { + const e = applyVideoPatch(FIN, { "audio.bass": "6", "audio.gain": -2, enter: "0.8,0.3", to: "44", fit: "cover" }); + assert.deepEqual(e.audio, { bass: 6, gain: -2 }); + assert.deepEqual(e.enter, { out: 0.8, in: 0.3 }); + assert.equal(e.to, 44); + assert.equal(applyVideoPatch(e, { enter: "cut" }).enter, "cut"); + assert.equal(applyVideoPatch(e, { "audio.bass": null, "audio.gain": "" }).audio, undefined); + assert.equal(applyVideoPatch(e, { to: null }).to, undefined); + assert.throws(() => applyVideoPatch(e, { speed: 2 }), /not a video entry's setting/); + assert.throws(() => applyVideoPatch(e, { from: "x" }), /must be a number/); + // The original is untouched. + assert.deepEqual(FIN.audio, { bass: 8 }); +}); + +test("its level: the cut's target, else the level its narration sits at", () => { + assert.deepEqual(videoLoudnessTarget({}, [], -14), { target: -14, basis: "render.loudness" }); + assert.deepEqual(videoLoudnessTarget({}, [{ type: "post" }]), { target: -21, basis: "render.postNarration.lufs" }); + assert.deepEqual(videoLoudnessTarget({ postNarration: { lufs: -19 } }, [{ type: "post" }]), { target: -19, basis: "render.postNarration.lufs" }); + assert.deepEqual(videoLoudnessTarget({}, [{ type: "clip" }]), { target: -17.7, basis: "narration" }); +});