Archilyzer · Source

archilyzer

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

commit 76e10aedca5a8f77b6636659c607817f66bc22e5
parent f79e27bd85d98757d79d604fb8ddaec327e30ddf
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 16:13:14 -0500

umtool: Play plays a video entry -- full frame, its sound, the chrome off; the item before darkens into it; the strip shows it; e2e video-entry.spec.ts

playView gives it a videoEntry (src, span, fit, enter, lead, hold, seconds,
bass, gain, noChrome); VideoEntryPlayer plays the project file (served by
/api/report/file) on Play's clock over the whole stage (z above every overlay;
deck "shown": as the footage), black through its lead, fading up, ending on
its last frame; the clips' sound ducks with the darkening (engine.setDuck);
bass/gain through a Web Audio low shelf and gain. The spec plays a fixture
cut ending in one, and inserts one into a take with add-video.

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

Diffstat:
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/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/video-entry-fixture.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/video-entry.spec.ts | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/playVideo.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/playVideo.test.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playView.mjs | 36++++++++++++++++++++++++++++++++++++
11 files changed, 467 insertions(+), 2 deletions(-)

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/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/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);