Archilyzer · Source

archilyzer

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

commit 7b07fad716135f287e7fe27e8f93aaef8b2f070d
parent 8adc3bd117680e2a571ceda39e01ef92c8050cd8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 23:38:55 -0500

Hidden regions everywhere a clip's picture is drawn or cut, or a refusal by name

A hidden region is a privacy control: every path that draws or cuts a clip's picture
now hides the boxes, or refuses naming them -- none skips them quietly.

- --chrome-only / --chrome-preview refuse when a segment on disk hides other boxes than
  the cut asks for (censorProblems, beside blurProblems); an audio-only clip records
  censorNoPicture.
- A short of a RENDERED take gets the project's render.censor added (add-only:
  withProjectCensor) in every format; `umtool shorts --again` keeps the clip's boxes now
  and the record's snapshot both (mergeCensor in withOverrides); `--reframe` refuses a
  clip whose boxes changed since the take was rendered.
- A montage clip with boxes is refused (validateCensor, and the build); so is a basic cut.
- The YouTube thumbnail and every still (grabStill: umtool still, Play's Still, "Use this
  frame", promo --portrait-from) hide the boxes over their second (stillCensorArgs).
- umtool export as cut / with context hides them; --raw of a clip with boxes is refused
  unless --uncensored-raw (the route: uncensoredRaw), which says UNCENSORED.
- Play's canvas and the live preview draw them; Present carries them on each clip slide
  (`hidden`, the public payload too) and draws them over the picture, no toggle; the clip
  editor's player and the clip bench draw them outlined with a Peek toggle, off by default.
- knobs.md lists each path and whether it hides or refuses.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Meditor/CHANGELOG.md | 12++++++++++--
Mumtool/app/api/report/clip-export/route.ts | 4+++-
Mumtool/bin/umtool.mjs | 3++-
Mumtool/components/projects/ClipBench.tsx | 31++++++++++++++++++++++++++++++-
Mumtool/components/projects/present/PresentView.tsx | 7+++++++
Aumtool/components/projects/review/CensorOverlay.tsx | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/ClipEditor.tsx | 6++++--
Mumtool/components/projects/review/LiveDeckPreview.tsx | 10++++++++--
Mumtool/components/projects/review/PlayCut.tsx | 3+++
Mumtool/components/projects/review/footageCanvas.ts | 50++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/review/playEngine/engine.ts | 10++++++++--
Mumtool/docs/cli.md | 4++--
Mumtool/docs/knobs.md | 30++++++++++++++++++++++++------
Mumtool/e2e/clip-kit.spec.ts | 10++++++++++
Mumtool/lib/cli/groups.mjs | 9+++++----
Mumtool/lib/cli/verbs.mjs | 2+-
Mumtool/lib/report/benchData.ts | 3+++
Mumtool/lib/report/clipEditor.mjs | 5++++-
Mumtool/lib/report/clipEditorTypes.ts | 2++
Mumtool/lib/report/clipExport.mjs | 37++++++++++++++++++++++++++++++++-----
Mumtool/lib/report/clipExport.test.mjs | 45+++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/inspectorEdits.test.mjs | 29+++++++++++++++++++++++++++++
Mumtool/lib/report/playView.mjs | 3+++
Mumtool/lib/report/present.mjs | 3+++
Mumtool/lib/report/present.test.mjs | 21+++++++++++++++++++++
Mumtool/lib/report/shortsBatch.test.mjs | 33+++++++++++++++++++++++++++++++++
Mumtool/lib/report/stillGrab.mjs | 12+++++++++++-
Mumtool/lib/report/verticalCli.mjs | 34++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/basic.mjs | 8++++++++
Mumtool/report-to-video/basic.test.mjs | 10++++++++++
Mumtool/report-to-video/build-video.mjs | 18+++++++++++++++---
Mumtool/report-to-video/clip-censor.mjs | 43+++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/clip-censor.test.mjs | 88++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/vertical-plan.mjs | 31+++++++++++++++++++++++++++++--
34 files changed, 655 insertions(+), 43 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -7,8 +7,16 @@ **Hide regions**) blurs, blacks out or pixelates the same boxes on every clip of that recording. A box can be limited to a span of the clip. - A clip's own `censor` adds boxes for that clip; `censor=false` turns its recording's off. - - The boxes are applied to the source picture first, in every kind of build (a cut, a short, a desktop clip, Make a - short), and they stay on in the uncensored variant. + - The boxes are applied to the source picture first, and they stay on in the uncensored variant. + - Every path that draws or cuts a clip's picture either hides them or refuses by name. They are hidden in a cut, a + short, a desktop clip, Make a short, a short of an already-rendered take (the project's boxes are added), + `umtool shorts --again`, the YouTube thumbnail, stills, and `umtool export` as cut or with context. + - Play, the live preview and Present (its public payload too) draw them over the picture. The clip editor's player + and the clip bench draw them outlined, with a **Peek** toggle that is off by default. + - A montage, a basic cut, `--chrome-only` after the boxes changed and `--reframe` of a take rendered before them + are refused. So is `umtool export --raw`, unless `--uncensored-raw` asks for the recording as it is (and the + export says UNCENSORED). + - knobs.md, "Hidden regions", lists every path. - Without the keys the segments are unchanged. - **umtool: a short or a desktop clip can open on its payoff.** A clip's `coldOpen` (`{from, to}`, 1–4 s of its cut) plays first, then the short cuts hard to the clip's start. diff --git a/umtool/app/api/report/clip-export/route.ts b/umtool/app/api/report/clip-export/route.ts @@ -13,7 +13,8 @@ export const dynamic = "force-dynamic"; // (`context`), or a stretch as recorded (`raw`: the fetched window, or a // `span` -- the full exchange). // -// POST { project, clip, take?, kind?: "cut" | "context" | "raw", context?: N, span?: {from, to}, fetch?: true } +// POST { project, clip, take?, kind?: "cut" | "context" | "raw", context?: N, span?: {from, to}, fetch?: true, uncensoredRaw?: true } +// (`uncensoredRaw`: a raw export of a clip that hides regions is refused unless asked for as recorded, regions shown) // -> 202 { job } ONE umtool job on the app's runner (lib/jobs.ts: one at a // time, a log, Stop): `fetch: true` asks the editor first for what a // context or raw export needs that is not on disk (the bench's own @@ -69,6 +70,7 @@ export async function POST(request: Request) { span, fetch: need.held ? null : { padBefore: need.padBefore, padAfter: need.padAfter }, manifestPath, + uncensoredRaw: kind === "raw" && body.uncensoredRaw === true, }); const job = startJob(`export ${project.id}/${clip}`, steps, { project: project.id }); return Response.json({ ok: true, fetching: !need.held, job: jobView(job) }, { status: 202, headers }); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -789,6 +789,7 @@ async function cmdExportClip(p, clipId) { const from = val("--from"); const to = val("--to"); if (kind !== "raw" && (from !== undefined || to !== undefined)) die("--from/--to are a raw export's span: add --raw"); + if (has("--uncensored-raw") && kind !== "raw") die("--uncensored-raw goes with --raw (a cut or context export always hides its regions)"); if ((from === undefined) !== (to === undefined)) die("a raw span is --from S --to S, both"); const span = from !== undefined ? { from: Number(from), to: Number(to) } : null; const take = val("--take") ?? null; @@ -811,7 +812,7 @@ async function cmdExportClip(p, clipId) { try { r = await withRenderSlot( ["umtool", "export", p.id, clipId, kind], - () => exportClip(p, clipId, { take, kind, ...(context !== undefined ? { context: Number(context) } : {}), span }), + () => exportClip(p, clipId, { take, kind, ...(context !== undefined ? { context: Number(context) } : {}), span, uncensoredRaw: has("--uncensored-raw") }), { estimateMb: EXPORT_ESTIMATE_MB, say }, ); } catch (e) { diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -41,6 +41,7 @@ import { CutEdges } from "./bench/CutEdges"; import { sourceWindowMedia } from "./bench/benchMedia"; import { useBenchPlayer } from "./bench/useBenchPlayer"; import { usePeaks } from "./bench/usePeaks"; +import CensorOverlay, { type CensorRegion } from "./review/CensorOverlay"; import { DeckFrame, NeutralFrame, @@ -317,6 +318,8 @@ export type ClipBenchData = { siblings: Sibling[]; /** Is the cut built with the on-screen panel (`render.chrome`)? */ deckOn: boolean; + /** Every region the cut hides on this clip (clip-censor.mjs censorRegionsOf): drawn over the raw window. */ + hidden?: CensorRegion[]; /** The manifest's `generatedBy`: edits here are noted for the agent that runs it. */ generatedBy?: string | null; /** @@ -765,6 +768,9 @@ export default function ClipBench({ // The widest cached file is the one the bench draws from: it is how much room // there is to drag before anything has to be fetched. const cached = windows[0] ?? null; + // The raw window's picture and second, for its hidden regions (CensorOverlay). + const [benchAspect, setBenchAspect] = useState<number | null>(null); + const [benchAt, setBenchAt] = useState<number | null>(null); const fetchStart = cached?.from ?? 0; const cachedTo = cached?.to ?? 0; @@ -2932,7 +2938,30 @@ export default function ClipBench({ > {placeBar} <div className="flex md:contents"> - {cached ? ( + {cached && (data.hidden?.length ?? 0) > 0 ? ( + // With hidden regions the picture sits in a box of its own, the regions drawn over it (an editing + // surface: outlined, a Peek toggle off by default). Without, the <video> is the flex item as before. + <div + data-bench-censor="" + className={cn("relative aspect-video w-full lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]", inspector && "hidden")} + > + <video + ref={video} + data-testid="clip-video" + src={media.src ?? undefined} + className="absolute inset-0 h-full w-full rounded border border-[var(--color-line)] bg-black object-contain" + preload="metadata" + controls + onLoadedMetadata={(e) => { + const el = e.currentTarget; + if (el.videoWidth > 0 && el.videoHeight > 0) setBenchAspect(el.videoWidth / el.videoHeight); + }} + onTimeUpdate={(e) => setBenchAt((cached?.from ?? 0) + e.currentTarget.currentTime)} + onSeeked={(e) => setBenchAt((cached?.from ?? 0) + e.currentTarget.currentTime)} + /> + <CensorOverlay regions={data.hidden ?? []} at={benchAt} aspect={benchAspect} mode="edit" testId="bench-censor" /> + </div> + ) : cached ? ( <video ref={video} data-testid="clip-video" diff --git a/umtool/components/projects/present/PresentView.tsx b/umtool/components/projects/present/PresentView.tsx @@ -6,6 +6,7 @@ import PostItemPlayer, { postItemAssets, type CardView, type PostPlan, type Prog import ComboBadge, { type ComboInfo } from "../review/ComboBadge"; import { postPreload } from "../review/playEngine/postPreload"; import IntroCardPlayer, { type IntroPage } from "../review/IntroCardPlayer"; +import CensorOverlay, { type CensorRegion } from "../review/CensorOverlay"; import { aModalIsOpen } from "@/components/ui/modalOpen"; // --------------------------------------------------------------------------- @@ -51,6 +52,8 @@ type ClipSlide = SlideBase & { quote: string | null; qrUrl: string | null; blur: { strength: number; caption: string; from: number | null; to: number | null } | null; + /** Its hidden regions (clip-censor.mjs): drawn over the picture always -- no viewer toggle lifts them. */ + hidden?: CensorRegion[]; }; type TextSlide = SlideBase & { kind: "section" | "day" | "teaser" | "card"; lines?: string[]; tail?: string | null; seconds?: number | null; heading?: string; within?: string | null }; type VideoSlide = SlideBase & { kind: "video"; src: string; from: number; to: number; seconds: number }; @@ -479,6 +482,7 @@ function ClipView({ slide, project, take, playing, sound, censor, onDone }: { sl const video = useRef<HTMLVideoElement | null>(null); const [at, setAt] = useState<number | null>(null); const [done, setDone] = useState(false); + const [aspect, setAspect] = useState<number | null>(null); const media = slide.media; const src = media ? `/api/report/raw?${new URLSearchParams({ project, clip: slide.entry ?? slide.id, ...(take ? { take } : {}), file: media.name, ...(media.v ? { v: media.v } : {}) }).toString()}` @@ -533,6 +537,8 @@ function ClipView({ slide, project, take, playing, sound, censor, onDone }: { sl data-present-clip-video="" data-present-clip-blurred={blurNow ? "1" : "0"} onLoadedMetadata={(e) => { + const el = e.currentTarget; + if (el.videoWidth > 0 && el.videoHeight > 0) setAspect(el.videoWidth / el.videoHeight); if (media && slide.spans[0]) e.currentTarget.currentTime = Math.max(0, slide.spans[0].from - media.from); }} className="absolute inset-0 h-full w-full object-contain" @@ -543,6 +549,7 @@ function ClipView({ slide, project, take, playing, sound, censor, onDone }: { sl not fetched yet — its words below </div> )} + {src && (slide.hidden?.length ?? 0) > 0 && <CensorOverlay regions={slide.hidden ?? []} at={at} aspect={aspect} mode="cover" testId="present-clip-censor" />} {blurNow && slide.blur && ( <div className="pointer-events-none absolute inset-x-0 top-[5%] text-center text-[3.2cqh] font-semibold text-white drop-shadow">{slide.blur.caption}</div> )} diff --git a/umtool/components/projects/review/CensorOverlay.tsx b/umtool/components/projects/review/CensorOverlay.tsx @@ -0,0 +1,82 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; + +// HIDDEN REGIONS OVER A PLAYER (lane clip-kit, slice E; report-to-video clip-censor.mjs). Where a clip's raw window +// plays -- Present (its public page too), the clip editor, the bench -- the boxes its recording and the clip hide are +// drawn over the picture: the same boxes (fractions of the source picture), the same spans (source seconds), black +// where the build fills black, a heavy backdrop blur where it blurs or pixelates. `mode`: +// "cover" opaque, always (Present: a viewer, public or not, never sees the region) +// "edit" an editing surface: the fill and a dashed outline, and a Peek toggle (OFF by default) that drops the fill +// The picture's rect inside the player is measured (an element fitted with object-contain), so the boxes stand on +// the picture, not on its letterbox. + +export type CensorRegion = { box: number[]; style: "blur" | "black" | "pixelate"; strength: number; from: number | null; to: number | null }; + +/** The regions over source second `at` (all, when `at` is unknown: a still frame shows them all). */ +export const regionsAt = (regions: CensorRegion[], at: number | null) => + regions.filter((g) => at === null || ((g.from === null || at >= g.from - 1e-6) && (g.to === null || at <= g.to + 1e-6))); + +export default function CensorOverlay({ regions, at, aspect, mode = "cover", testId = "censor-overlay" }: { + regions: CensorRegion[]; + at: number | null; + /** The picture's width / height (its videoWidth / videoHeight); null until known (the whole box is used). */ + aspect: number | null; + mode?: "cover" | "edit"; + testId?: string; +}) { + const box = useRef<HTMLDivElement | null>(null); + const [size, setSize] = useState<{ w: number; h: number } | null>(null); + const [peek, setPeek] = useState(false); + useEffect(() => { + const el = box.current; + if (!el) return; + const ro = new ResizeObserver(() => setSize({ w: el.clientWidth, h: el.clientHeight })); + ro.observe(el); + setSize({ w: el.clientWidth, h: el.clientHeight }); + return () => ro.disconnect(); + }, []); + const now = regionsAt(regions, at); + // The picture's rect in the player (object-contain). + let pic = { x: 0, y: 0, w: size?.w ?? 0, h: size?.h ?? 0 }; + if (size && aspect && size.w > 0 && size.h > 0) { + const k = Math.min(size.w / aspect, size.h); + pic = { x: (size.w - k * aspect) / 2, y: (size.h - k) / 2, w: k * aspect, h: k }; + } + return ( + <div ref={box} data-testid={testId} data-censor-overlay={mode} data-censor-now={now.length} className="pointer-events-none absolute inset-0 overflow-hidden"> + {size && + now.map((g, i) => { + const fill = mode === "edit" && peek ? {} : g.style === "black" ? { background: "#000" } : { backdropFilter: `blur(${Math.max(8, Math.round(pic.w * g.strength * 0.004 * (g.style === "pixelate" ? 2 : 1)))}px)`, WebkitBackdropFilter: `blur(${Math.max(8, Math.round(pic.w * g.strength * 0.004))}px)`, background: "rgba(0,0,0,0.25)" }; + return ( + <div + key={i} + data-censor-region={i} + data-censor-style={g.style} + style={{ + position: "absolute", + left: pic.x + g.box[0] * pic.w, + top: pic.y + g.box[1] * pic.h, + width: g.box[2] * pic.w, + height: g.box[3] * pic.h, + ...fill, + ...(mode === "edit" ? { outline: "2px dashed rgba(255,80,80,0.9)", outlineOffset: -2 } : {}), + }} + /> + ); + })} + {mode === "edit" && regions.length > 0 && ( + <button + type="button" + data-censor-peek="" + aria-pressed={peek} + onClick={() => setPeek(!peek)} + className="pointer-events-auto absolute right-1 top-1 rounded-[3px] bg-black/70 px-1.5 py-0.5 text-[11px] text-white" + title="the hidden regions are drawn as the cut hides them; peek shows the picture under them here only" + > + {peek ? "Hide again" : "Peek"} + </button> + )} + </div> + ); +} diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -18,6 +18,7 @@ import { refusalOf, timelineOp } from "../timelineApi"; import AssistBox from "../report/AssistBox"; import { AudioBox, BlurBox, MarksBox } from "./ClipKnobs"; import LiveDeckPreview from "./LiveDeckPreview"; +import CensorOverlay, { type CensorRegion } from "./CensorOverlay"; // Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional). import type { ReplyProposal } from "@/lib/annotations/types"; import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest"; @@ -565,7 +566,7 @@ export default function ClipEditor({ </p> )} - <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} frame={framing ? { crop: clip.vertical?.crop ?? null, onChange: setCrop, busy } : null} /> + <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} frame={framing ? { crop: clip.vertical?.crop ?? null, onChange: setCrop, busy } : null} hidden={clip.hidden ?? []} at={playhead} /> <LiveDeckPreview project={project} clip={clip} cut={cut} token={view.token} player={player} write={write} busy={busy} blurRendered={view.blur?.rendered ?? true} /> {/* ---- the strip --------------------------------------------------- */} @@ -915,7 +916,7 @@ type Frame = { crop: number[] | null; onChange: (crop: number[] | null, aspect?: type Target = { channel: string; video: string; from: number; to: number; project: string; clip: string }; -const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void; frame?: Frame | null }>(function Player({ clipId, targets, cut, onTime, onPlaying, frame = null }, ref) { +const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void; frame?: Frame | null; hidden?: CensorRegion[]; at?: number | null }>(function Player({ clipId, targets, cut, onTime, onPlaying, frame = null, hidden = [], at = null }, ref) { const [found, setFound] = useState<{ play: CitedPlay; from: number } | null | undefined>(undefined); const [dims, setDims] = useState<{ w: number; h: number } | null>(null); const media = useRef<HTMLMediaElement | null>(null); @@ -1076,6 +1077,7 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut <div className="relative overflow-hidden rounded-[3px]"> <video {...props} playsInline className="aspect-video w-full rounded-[3px] bg-black" /> {frame && dims && <CropBox frame={frame} aspect={dims.w / dims.h} />} + {hidden.length > 0 && <CensorOverlay regions={hidden} at={at} aspect={dims ? dims.w / dims.h : null} mode="edit" testId="editor-censor" />} </div> )} {frame && (found.play.audio || !dims) && ( diff --git a/umtool/components/projects/review/LiveDeckPreview.tsx b/umtool/components/projects/review/LiveDeckPreview.tsx @@ -10,6 +10,7 @@ import { clipStamps, clockText, cutTimeAt, finaleUp, liveClock, stampAt, tallyAt import { tallyCellsFrom, VERDICTS } from "umtool-report-to-video/factcheck"; import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; import { drawFootage } from "./footageCanvas"; +import { regionsAt } from "./CensorOverlay"; import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type DeckTexts, type Rect } from "../OnscreenSection"; // --------------------------------------------------------------------------- @@ -172,6 +173,9 @@ export default function LiveDeckPreview({ const blur = clip.blur && blurRendered ? { strength: clip.blur.strength ?? BLUR_STRENGTH.default, caption: clip.blur.caption ?? BLUR_CAPTION_DEFAULT, from: clip.blur.from ?? null, to: clip.blur.to ?? null } : null; const blurRef = useRef(blur); blurRef.current = blur; + // Its hidden regions (clip-censor.mjs): drawn always -- the final look hides them whatever render.blur says. + const hiddenRef = useRef(clip.hidden ?? []); + hiddenRef.current = clip.hidden ?? []; // Every animation frame while on: the playhead's cut second, and the // editor's picture drawn into the footage box when it moved. @@ -198,12 +202,14 @@ export default function LiveDeckPreview({ const video = m instanceof HTMLVideoElement && m.readyState >= 2 && m.videoWidth > 0 ? m : null; const b = blurRef.current; const blurNow = b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity) ? b : null; - const blurKey = blurNow ? `${blurNow.strength}|${blurNow.caption}` : ""; + const hiddenNow = regionsAt(hiddenRef.current, src); + const blurKey = `${blurNow ? `${blurNow.strength}|${blurNow.caption}` : ""}|${hiddenNow.map((g) => g.box.join(",")).join(";")}`; if (ld.el === el && ld.media === video && ld.t === (video?.currentTime ?? -1) && ld.bg === bgRef.current && ld.size === `${el.width}x${el.height}` && ld.blur === blurKey) return; lastDraw.current = { el, media: video, t: video?.currentTime ?? -1, bg: bgRef.current, size: `${el.width}x${el.height}`, blur: blurKey }; // What the canvas draws, for a test to read: "on" while the blur covers the playhead. el.dataset.liveBlur = blurNow ? "on" : "off"; - drawFootage(el, video, bgRef.current, blurNow); + el.dataset.liveCensor = String(hiddenNow.length); + drawFootage(el, video, bgRef.current, blurNow, hiddenNow); }; raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf); diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -33,6 +33,7 @@ import type { ComboInfo } from "./ComboBadge"; import CopyShareLine from "../CopyShareLine"; import VersionVerdict from "./VersionVerdict"; import { StillButton } from "../inspector/StillInspector"; +import type { CensorRegion } from "./CensorOverlay"; // --------------------------------------------------------------------------- // THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The @@ -119,6 +120,8 @@ export type PlayEntry = { /** Seconds taken out of its middle (gaps.mjs): one item of jump cuts. */ gaps?: { from: number; to: number }[]; blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null; + /** Its hidden regions (clip-censor.mjs censorRegionsOf): drawn over the picture as the cut hides them. */ + censor?: CensorRegion[]; media?: (MediaRef & { from: number; to: number }) | null; /** Rejected by the walk -- a fact error or a cut reason -- and why (skipped unless "Show rejected clips"). */ rejected?: { reason: string; label: string; fact: boolean; why: string } | null; diff --git a/umtool/components/projects/review/footageCanvas.ts b/umtool/components/projects/review/footageCanvas.ts @@ -18,10 +18,12 @@ export type FootageBlur = { strength: number; caption: string } | null; * the Play view's engine), its size, how opaque (a dissolve draws the * incoming clip over the outgoing at its progress), and its blur. */ -export type FootageLayer = { source: CanvasImageSource; width: number; height: number; alpha: number; blur: FootageBlur }; +export type FootageLayer = { source: CanvasImageSource; width: number; height: number; alpha: number; blur: FootageBlur; censor?: FootageCensor[] }; +/** A hidden region (clip-censor.mjs) over the picture now: its box (fractions of the picture), its style, its strength. */ +export type FootageCensor = { box: number[]; style: "blur" | "black" | "pixelate"; strength: number }; -export function drawFootage(el: HTMLCanvasElement, video: HTMLVideoElement | null, bg: string, blur: FootageBlur) { - drawFootageLayers(el, video ? [{ source: video, width: video.videoWidth, height: video.videoHeight, alpha: 1, blur }] : [], bg); +export function drawFootage(el: HTMLCanvasElement, video: HTMLVideoElement | null, bg: string, blur: FootageBlur, censor: FootageCensor[] = []) { + drawFootageLayers(el, video ? [{ source: video, width: video.videoWidth, height: video.videoHeight, alpha: 1, blur, censor }] : [], bg); } /** The footage box's ground, then each layer in order, fitted, at its alpha, blurred as the build blurs it. */ @@ -41,12 +43,52 @@ export function drawFootageLayers(el: HTMLCanvasElement, layers: FootageLayer[], } function drawOne(ctx: CanvasRenderingContext2D, el: HTMLCanvasElement, layer: FootageLayer, bg: string) { - const { source, blur } = layer; const k = Math.min(el.width / layer.width, el.height / layer.height); const w = layer.width * k; const hh = layer.height * k; const x = (el.width - w) / 2; const y = (el.height - hh) / 2; + drawPicture(ctx, layer, x, y, w, hh, bg); + // Its hidden regions (clip-censor.mjs), over the picture as the cut hides them: black filled; blurred or + // pixelated from the picture under them. + for (const g of layer.censor ?? []) { + const rx = x + g.box[0] * w; + const ry = y + g.box[1] * hh; + const rw = g.box[2] * w; + const rh = g.box[3] * hh; + ctx.save(); + if (g.style === "black") { + ctx.fillStyle = "#000"; + ctx.fillRect(rx, ry, rw, rh); + } else { + ctx.beginPath(); + ctx.rect(rx, ry, rw, rh); + ctx.clip(); + if (g.style === "pixelate") { + // Scaled down to its blocks and back up, unsmoothed (post-censor.mjs pixelGrid's block: 0.8 % of the width a step). + const block = Math.max(2, w * g.strength * 0.008); + const nx = Math.max(1, Math.round(rw / block)); + const ny = Math.max(1, Math.round(rh / block)); + const tmp = document.createElement("canvas"); + tmp.width = nx; + tmp.height = ny; + const sx = (g.box[0] * layer.width); + const sy = (g.box[1] * layer.height); + tmp.getContext("2d")?.drawImage(layer.source, sx, sy, g.box[2] * layer.width, g.box[3] * layer.height, 0, 0, nx, ny); + ctx.imageSmoothingEnabled = false; + ctx.drawImage(tmp, rx, ry, rw, rh); + } else { + ctx.filter = `blur(${Math.max(4, w * g.strength * 0.004).toFixed(1)}px)`; + ctx.drawImage(layer.source, x, y, w, hh); + } + } + ctx.restore(); + } +} + +/** The picture itself, fitted, blurred as a clip's blur asks (its caption over it). */ +function drawPicture(ctx: CanvasRenderingContext2D, layer: FootageLayer, x: number, y: number, w: number, hh: number, bg: string) { + const { source, blur } = layer; if (!blur) { ctx.drawImage(source, x, y, w, hh); return; diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -3,6 +3,7 @@ import { inGap } from "umtool-report-to-video/gaps"; import { cutAtSource, itemIndexAt, pieceWants, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; import { EDGE_SLACK, audioSpans, decodesOf, scheduleFrom } from "@/lib/report/playSchedule.mjs"; import { drawFootageLayers, type FootageLayer } from "../footageCanvas"; +import { regionsAt, type CensorRegion } from "../CensorOverlay"; import { AudioBank, type ClipSound } from "./audioBank"; import { CodecPicture, codecsAvailable } from "./codecPicture"; import { ElementPicture } from "./elementPicture"; @@ -54,6 +55,8 @@ export type EngineEntry = { id: string; media?: (MediaRef & { from: number; to: number }) | null; blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null; + /** Its hidden regions (clip-censor.mjs): drawn over the picture, whatever render.blur says. */ + censor?: CensorRegion[]; }; export type EngineUi = { t: number; cur: number; playing: boolean; ended: boolean; waiting: boolean }; /** @@ -808,14 +811,17 @@ export class PlayEngine { const blur = b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity) ? { strength: b.strength ?? BLUR_STRENGTH.default, caption: b.caption ?? BLUR_CAPTION_DEFAULT } : null; - out.push({ source: l.source, width: l.w, height: l.h, alpha: l.alpha, blur }); + // Its hidden regions over this second (or, the second unknown, every one): drawn as the cut hides them. + const censor = regionsAt(e?.censor ?? [], src); + out.push({ source: l.source, width: l.w, height: l.h, alpha: l.alpha, blur, censor }); } // A frame not decoded yet (a seek, a join whose bytes are still coming): the last picture stays rather than a black flash. if (missing && !out.length && this.shown) return; - const key = `${items[this.cur]?.id}|${out.map((l) => `${l.alpha.toFixed(3)}:${l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp}:${l.blur ? 1 : 0}`).join(",")}|${this.bg}|${el.width}x${el.height}`; + const key = `${items[this.cur]?.id}|${out.map((l) => `${l.alpha.toFixed(3)}:${l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp}:${l.blur ? 1 : 0}:${l.censor?.length ?? 0}`).join(",")}|${this.bg}|${el.width}x${el.height}`; if (key === this.lastDraw && out.every((l) => !(l.source instanceof HTMLVideoElement) || l.source.paused)) return; this.lastDraw = key; el.dataset.playBlur = out.some((l) => l.blur) ? "on" : "off"; + el.dataset.playCensor = String(out.reduce((n, l) => n + (l.censor?.length ?? 0), 0)); el.dataset.playLayers = String(out.length); drawFootageLayers(el, out, this.bg); this.shown = out.length > 0; diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -65,7 +65,7 @@ Inbox cannot disagree about what is wrong with one. | `snapshot <project> [--label L]` | copy the manifest into `revisions/` | | `diff <project> <snapshot>` | added / removed / moved / window / retyped, by entry id | | `export <project> --format toc-bbcode\|toc-markdown\|description\|chapters [--variant V] [--first TITLE]` | the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00 | -| `export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson` | **one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip)) | +| `export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson` | **one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. A clip's hidden regions (`render.censor`, its `censor`) are hidden in a cut or context export; a raw export of a clip with boxes is refused unless `--uncensored-raw`, which shows them and says so. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip)) | | `check-sources [<project>…]` | **prints** the re-check chain; with no args, the never-checked and >30 d projects | | `notes …` | operator notes: list, read, reply, resolve ([notes.md](notes.md)) | | `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)) | @@ -227,7 +227,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `storage deliverables` | clips/ and share-*/ to the media root and back | none: moves deliverables between drives, then the switch: a terminal's, run when nothing builds | | `snapshot <project> [--label LABEL]` | copy the manifest into revisions/ | form · *project* | | `diff <project> <snapshot>` | what changed since a snapshot | form · *project* | -| `export <project> [<clip>] [--format toc-bbcode\|toc-markdown\|description\|chapters] [--variant VARIANT] [--first FIRST] [--context N] [--raw] [--from N] [--to N] [--fetch] [--take TAKE]` | the posting artifacts, or one clip clean into exports/ | form · queued · *project* | +| `export <project> [<clip>] [--format toc-bbcode\|toc-markdown\|description\|chapters] [--variant VARIANT] [--first FIRST] [--context N] [--raw] [--uncensored-raw] [--from N] [--to N] [--fetch] [--take TAKE]` | the posting artifacts, or one clip clean into exports/ | form · queued · *project* | | `check-sources [<projects>…]` | the re-check chain, printed | form · *corpus* | | `notes [<target>] [--all] [--resolved] [--all-status]` | the operator's notes, as markdown | form · *corpus* | | `notes reply <id> <text> [--resolve]` | answer a note | form · *corpus* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -515,13 +515,31 @@ A stream layout carries things a clip should not show: the chat overlay, a brows (lane clip-kit; `report-to-video/clip-censor.mjs`, with the post censor's styles and strengths). A box is a fraction of the SOURCE picture and may be limited to a span of the clip. -- **Where:** on the source picture FIRST -- before the clip's blur, its zooms and any framing -- in every path a clip - is cut in: a cut with or without the deck, a short, a desktop clip, Make a short. So a box is the same part of the - recording whatever frames it. A montage re-cuts its pictures and draws none. +- **Where it is drawn:** on the source picture FIRST -- before the clip's blur, its zooms and any framing -- so a box is + the same part of the recording whatever frames it. - **Privacy, not TOS:** it stays on in the uncensored variant (`render.blur: "off"`), as a post's censor does. No - caption is drawn. -- The cut record names what was hidden (`censor: [{box, style, strength?, from?, to?}]`). `--chrome-only` does not - re-cut segments: after changing a recording's boxes, build again. + caption is drawn. A hidden region is a privacy control, so every path that draws or cuts a clip's picture either + draws the boxes or REFUSES by name -- none skips them quietly: + +| Path | The boxes | +|---|---| +| a cut, with or without the deck (`umtool take`, build-video) | drawn into each clip's segment; the cut record names them (`censor: [{box, style, strength?, from?, to?}]`) | +| a short, a desktop clip, the take's own 16:9 look (`umtool vertical`, `umtool shorts`, Make a short) | drawn; a RENDERED take's frozen render gets the project's `render.censor` added (add-only: the take's boxes stay) | +| `umtool shorts --again` | the clip's boxes now AND the batch record's snapshot, both (a box added since is kept, none taken off) | +| the YouTube thumbnail (`thumbnail.clip`/`at`) | drawn on the grabbed frame, before its blur | +| a still (`umtool still`, Play's Still, "Use this frame", promo `--portrait-from`) | drawn on the PNG, the boxes over that second | +| `umtool export` as cut / `--context N` | drawn (the export says how many) | +| Play (the canvas), the live preview | drawn over the picture, the same boxes, spans and style | +| Present, its public payload too | drawn over the picture (`hidden` on each clip slide); no viewer toggle lifts them | +| the clip editor's player, the clip bench | drawn as an overlay, outlined, with **Peek** (off by default) to see under them there only | +| a montage (`render.montage`) | REFUSED by name (a montage re-cuts its pictures and draws no boxes yet) | +| a basic cut (`render.mode: "basic"`) | REFUSED by name, `render.blur: "off"` or not | +| `umtool export --raw` | REFUSED by name; `--uncensored-raw` (the app: `uncensoredRaw`) exports as recorded and says UNCENSORED | +| `--chrome-only` / `--chrome-preview` | REFUSED when a segment on disk hides other boxes than the cut asks for (a box added, changed or taken off since): build again | +| `umtool vertical --reframe` | REFUSED when a clip's boxes changed since the take was rendered (it cuts the take's finished picture) | + +Not drawn: the claim bench's and the candidates panel's windows (no clip yet -- a recording's boxes are not looked up +there), and the rendered segment previews (already cut with them). | Knob | Values (default) | What it does | |---|---|---| diff --git a/umtool/e2e/clip-kit.spec.ts b/umtool/e2e/clip-kit.spec.ts @@ -111,8 +111,18 @@ test("the clip editor: a clip's own QR corner, its end card off and back, the pr await page.locator("[data-censor-scope]").selectOption("clip"); await page.locator("[data-censor-add='r001']").click(); await expect.poll(() => clip("r001")?.censor ?? null).toEqual({ boxes: [[0.75, 0, 0.25, 1]], style: "black" }); + // The player draws it over the picture (an editing surface): filled black, outlined, Peek OFF until pressed. + const over = page.getByTestId("editor-censor"); + await expect(over).toHaveAttribute("data-censor-overlay", "edit"); + await expect(over.locator("[data-censor-region]")).toHaveCount(1); + await expect(over.locator("[data-censor-region]")).toHaveCSS("background-color", "rgb(0, 0, 0)"); + await expect(over.locator("[data-censor-peek]")).toHaveAttribute("aria-pressed", "false"); + await over.locator("[data-censor-peek]").click(); + await expect(over.locator("[data-censor-peek]")).toHaveAttribute("aria-pressed", "true"); + await expect(over.locator("[data-censor-region]")).not.toHaveCSS("background-color", "rgb(0, 0, 0)"); await page.locator("[data-censor-remove='c0']").click(); await expect.poll(() => clip("r001") && "censor" in clip("r001")).toBe(false); + await expect(over).toHaveCount(0); // The portrait: the player ready, the playhead moved (l: 2 s on), the frame there grabbed into shots/. await expect(page.locator("[data-editor-player]")).toHaveAttribute("data-editor-player", /^(?!looking|none)/, { timeout: 20_000 }); if (!render().promo) test.skip(true, "the look test sets the promo first"); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -488,16 +488,17 @@ export const GROUPS = [ cmd: "export", usage: [ " umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]", - " umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] one clip,", - " clean, into <project>/exports/: the cut's edges, its gaps out, its mute; --context N what the cut", - " plays ± N s; --raw the whole fetched window, or a span (the full exchange), as recorded; --fetch", + " umtool export <project> <clip> [--context N | --raw [--from S --to S] [--uncensored-raw]] [--fetch] [--take T] [--open]", + " one clip, clean, into <project>/exports/: the cut's edges, its gaps out, its mute; --context N what", + " the cut plays ± N s; --raw the whole fetched window, or a span (the full exchange), as recorded; its", + " hidden regions hidden (a raw export of a clip with boxes refused unless --uncensored-raw); --fetch", " asks the editor first for what that needs; in the heavy slot; --open shows it", ], docs: [ ["`export <project> --format toc-bbcode\\|toc-markdown\\|description\\|chapters [--variant V] [--first TITLE]`", "the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00"], ["`export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson`", - "**one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip))"], + "**one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. A clip's hidden regions (`render.censor`, its `censor`) are hidden in a cut or context export; a raw export of a clip with boxes is refused unless `--uncensored-raw`, which shows them and says so. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip))"], ], }, { diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -251,7 +251,7 @@ export const VERBS = Object.freeze([ form("diff", "project", "what changed since a snapshot", [project(), arg("snapshot", { help: "its path under revisions/" })]), form("export", "project", "the posting artifacts, or one clip clean into exports/", [ project(), clip({ required: false, help: "one clip (none: --format)" }), pick("--format", ["toc-bbcode", "toc-markdown", "description", "chapters"]), opt("--variant"), opt("--first"), - num("--context", { help: "± s, as recorded" }), bool("--raw", "the fetched window as recorded"), num("--from"), num("--to"), bool("--fetch", "ask the editor first for what is not on disk"), takeOpt(), + num("--context", { help: "± s, as recorded" }), bool("--raw", "the fetched window as recorded"), bool("--uncensored-raw", "a raw export of a clip that hides regions, shown as recorded"), num("--from"), num("--to"), bool("--fetch", "ask the editor first for what is not on disk"), takeOpt(), ], { ...Q, ...B(["clip"], { clip: "{id}" }) }), form("check-sources", "corpus", "the re-check chain, printed", [many("projects", { help: "one per line (none: the never-checked and > 30 d)" })]), diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -14,6 +14,7 @@ import { projectCache, segmentFor, windowVersion, windowsFor } from "@/lib/repor import { FETCH_MAX_WINDOW } from "@/lib/report/driver.mjs"; import { gapWalls } from "umtool-report-to-video/gaps"; import { deckOn } from "umtool-report-to-video/deck"; +import { censorRegionsOf } from "umtool-report-to-video/clip-censor"; import { pieceHrefOfProject } from "@/lib/pieces/article"; import { readWorkingCut } from "@/lib/report/workingCut.mjs"; import type { ProjectRef } from "@/lib/project-types"; @@ -164,6 +165,8 @@ export async function clipBenchData( // Whether the cut is built with the on-screen panel. Decides whether the // bench composes a preview of it; the fields are there either way. deckOn: deckOn(manifest.render ?? {}), + // Every region the cut hides on it (clip-censor.mjs): the bench draws them over the raw window. + hidden: censorRegionsOf(((manifest.timeline ?? []) as { id: string }[]).find((e) => e.id === clipId) ?? {}, manifest.render ?? {}, manifest.provenance ?? {}), generatedBy: typeof manifest.generatedBy === "string" ? manifest.generatedBy : null, view, // `v`: the version of each window's bytes, for the media URLs (serve.mjs, "A REPLACED FILE IS A NEW FILE"). diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -42,7 +42,7 @@ import { updateOnscreen, updateRender, } from "./manifest.mjs"; -import { namesClip } from "umtool-report-to-video/clip-censor"; +import { censorRegionsOf, namesClip } from "umtool-report-to-video/clip-censor"; import { withRecording } from "./censorCli.mjs"; import { CLAIM_KNOB_DEFAULTS, markVerdictsOf, rawMarksOf, stampingEntryId } from "./knobs.mjs"; import { resolveFactcheck } from "umtool-report-to-video/factcheck"; @@ -135,6 +135,9 @@ export async function clipEditorView(project) { kit: Object.fromEntries(CLIP_KIT_KEYS.filter((k) => e[k] !== undefined).map((k) => [k, e[k]])), // Its recording's hidden regions (render.censor naming its video), for the Hide regions list. recordingCensor: (Array.isArray(manifest.render?.censor) ? manifest.render.censor : []).filter((r) => namesClip(r, e, manifest.provenance ?? {})), + // Every region the cut hides on it (its own and its recording's, clip-censor.mjs): the player and the live + // preview draw them over the picture. + hidden: censorRegionsOf(e, manifest.render ?? {}, manifest.provenance ?? {}), // Room at its edges (release 36 lane E): the clip's own override as // written, and the edges it gets with the cut's render.room. room: e.room === false ? false : isObj(e.room) ? e.room : null, diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -33,6 +33,8 @@ export type EditorClip = { kit?: { qr?: false | { corner?: string; links?: string }; name?: string; promo?: false | { lead?: number; fade?: number; hold?: number }; zooms?: unknown[]; coldOpen?: { from: number; to: number }; censor?: false | CensorSet; [k: string]: unknown }; /** Its recording's hidden regions (render.censor naming its video). */ recordingCensor?: Array<CensorSet & { video: string; channel?: string }>; + /** Every region the cut hides on it (clip-censor.mjs censorRegionsOf): drawn over the player and the live preview. */ + hidden?: Array<{ box: number[]; style: "blur" | "black" | "pixelate"; strength: number; from: number | null; to: number | null }>; /** Room at its edges (release 36 lane E): the clip's own `room` as written (false: none), and the edges it gets. */ room?: false | { tail?: boolean; head?: boolean } | null; roomEdges?: { tail: boolean; head: boolean } | null; diff --git a/umtool/lib/report/clipExport.mjs b/umtool/lib/report/clipExport.mjs @@ -39,6 +39,7 @@ // // The pure half (names, the plan's ffmpeg arguments) is tested in // clipExport.test.mjs; `exportClip` runs it. +import { censorParts } from "umtool-report-to-video/clip-censor"; import { spawn } from "node:child_process"; import { mkdir, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; @@ -292,6 +293,9 @@ export const planSeconds = (plan) => gappedLength(plan.from, plan.to, plan.gaps) * @param {{ crf?: number, preset?: string, audioBitrate?: string }} [opts] * @returns {string[]} */ +/** The seconds an export plays (planSeconds, before it is declared below). */ +const kept0 = (plan) => gappedLength(plan.from, plan.to, plan.gaps); + export function exportArgs(plan, out, { crf = 18, preset = "medium", audioBitrate = "192k" } = {}) { const a = Math.max(0, plan.from - plan.fetchStart); const b = Math.max(a, plan.to - plan.fetchStart); @@ -308,6 +312,14 @@ export function exportArgs(plan, out, { crf = 18, preset = "medium", audioBitrat const local = plan.gaps.map((g) => ({ from: g.from - plan.from, to: g.to - plan.from })); const g = gapFilterParts({ gaps: local, seconds, vIn: plan.hasVideo === false ? null : "[0:v]", aIn: "[aclk]" }); parts.push(...g.parts); + // Hidden regions (report-to-video clip-censor.mjs): on the picture as the cut hides them, over their spans on this + // export's clock (its first frame is plan.from). + let vOut = g.v; + if (vOut && plan.censor?.regions?.length) { + const cp = censorParts(vOut.slice(1, -1), "vcen", plan.censor.regions, { width: plan.censor.width, height: plan.censor.height, from: plan.from, gaps: plan.gaps, seconds: kept0(plan) }); + parts.push(...cp); + vOut = "[vcen]"; + } const kept = planSeconds(plan); const af = []; if (plan.soundFrom != null) af.push(`afade=t=in:st=${n3(plan.soundFrom)}:d=${n3(MUTE_FADE)}`); @@ -317,7 +329,7 @@ export function exportArgs(plan, out, { crf = 18, preset = "medium", audioBitrat af.push(...clipAudioFilters(plan.kind === "cut" ? plan.audio : null, kept)); parts.push(`${g.a}${af.length ? af.join(",") : "anull"}[aout]`); args.push("-filter_complex", parts.join(";")); - if (g.v) args.push("-map", g.v === "[0:v]" ? "0:v:0" : g.v); + if (vOut) args.push("-map", vOut === "[0:v]" ? "0:v:0" : vOut); args.push("-map", "[aout]"); if (g.v) args.push("-c:v", "libx264", "-preset", preset, "-crf", String(crf), "-pix_fmt", "yuv420p"); args.push("-c:a", "aac", "-b:a", audioBitrate, "-movflags", "+faststart", "-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn"); @@ -420,7 +432,7 @@ async function heldWindow(project, entry, want, take = null) { * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "context" | "raw", name: string, rel: string, * abs: string, size: number, mtimeMs: number, seconds: number, summary: string, notes: string[], plan: ExportPlan }>} */ -export async function exportClip(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, ffmpeg, today } = {}) { +export async function exportClip(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, ffmpeg, today, uncensoredRaw = false } = {}) { if (!EXPORT_KINDS.includes(kind)) throw new ExportRefused(`an export is one of ${EXPORT_KINDS.join(", ")}`, 400); const ctx = kind === "context" ? contextSeconds(context) : EXPORT_CONTEXT.default; const sp = kind === "raw" ? spanOf(span) : null; @@ -460,6 +472,21 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", c ? { ...row, cutStart: row.pieced.cutStart, cutEnd: row.pieced.cutEnd, gaps: row.pieced.gaps } : row; const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source, media, row: planRow, kind, context: ctx, span: sp }); + // HIDDEN REGIONS (report-to-video clip-censor.mjs): a privacy control, so a cut or a context export hides them as + // the cut does; a raw export is "as recorded" and is REFUSED for a clip with boxes unless asked for uncensored, + // which it then says. + const { censorRegionsOf } = await import("umtool-report-to-video/clip-censor"); + const regions = media.hasVideo === false ? [] : censorRegionsOf(got.entry, got.render, got.provenance ?? {}); + if (regions.length && kind === "raw" && !uncensoredRaw) { + throw new ExportRefused(`${clipId} hides ${regions.length} region(s) of its picture (render.censor / its censor): a raw export is as recorded, and would show them -- export the cut or with --context (both hide them), or add --uncensored-raw to export the recording as it is`, 409); + } + if (regions.length && kind !== "raw") { + const { probeDims } = await import("umtool-report-to-video/build-video"); + const [width, height] = await probeDims(source.path); + plan.censor = { regions, width, height }; + plan.notes.push(`${regions.length} region(s) hidden (render.censor / its censor)`); + } + if (regions.length && kind === "raw") plan.notes.push(`UNCENSORED: ${regions.length} region(s) this clip hides are SHOWN (--uncensored-raw)`); if (!(planSeconds(plan) > 0.05)) throw new ExportRefused(`${clipId}: nothing to export (${planSummary(plan)})`, 422); const name = exportName(got.entry, { kind, context: ctx, span: sp, ...(today ? { today } : {}) }); const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR); @@ -498,16 +525,16 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", c * @param {{ id: string, dir: string }} project * @param {string} clipId * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null, - * fetch?: { padBefore: number, padAfter: number } | null, manifestPath?: string | null }} o + * fetch?: { padBefore: number, padAfter: number } | null, manifestPath?: string | null, uncensoredRaw?: boolean }} o */ -export async function exportSteps(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, fetch = null, manifestPath = null } = {}) { +export async function exportSteps(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, fetch = null, manifestPath = null, uncensoredRaw = false } = {}) { const { UMTOOL_DIR, editorFetchSteps, fetchSteps, localFetch } = await import("./driver.mjs"); const steps = []; if (fetch) { const pads = { padBefore: fetch.padBefore, padAfter: fetch.padAfter }; steps.push(...(localFetch() ? fetchSteps(project, clipId, pads, { manifestPath }) : editorFetchSteps(project, clipId, pads, { manifestPath }))); } - const kindArgs = kind === "context" ? ["--context", String(context)] : kind === "raw" ? ["--raw", ...(span ? ["--from", String(span.from), "--to", String(span.to)] : [])] : []; + const kindArgs = kind === "context" ? ["--context", String(context)] : kind === "raw" ? ["--raw", ...(span ? ["--from", String(span.from), "--to", String(span.to)] : []), ...(uncensoredRaw ? ["--uncensored-raw"] : [])] : []; steps.push({ cwd: UMTOOL_DIR, env: {}, diff --git a/umtool/lib/report/clipExport.test.mjs b/umtool/lib/report/clipExport.test.mjs @@ -225,6 +225,51 @@ test("export a clip: the kept seconds land in exports/ under the clip's name; ra await assert.rejects(exportClip(project, "nope"), /no clip nope/); }); +/** The mean luma of a box of the frame at `t` s (0–255). */ +function lumaAt(file, t, { x, y, w, h }) { + const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", `crop=${w}:${h}:${x}:${y},format=gray`, "-f", "rawvideo", "-"]); + assert.equal(r.status, 0, String(r.stderr)); + return r.stdout.reduce((n, v) => n + v, 0) / r.stdout.length; +} + +test("hidden regions: a cut and a context export hide them; a raw export is refused unless --uncensored-raw, which says so", { skip: !have && "needs ffmpeg" }, async () => { + const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-")); + roots.push(root); + mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); + const raw = path.join(root, "out", "clips-raw", "vid2_0.00-12.00.mp4"); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=white:s=320x180:r=30:d=12", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", + "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, + ]); + assert.equal(r.status, 0, String(r.stderr)); + writeFileSync(path.join(root, "video.manifest.json"), JSON.stringify({ + slug: "expc", title: "Export", + provenance: { channelSlug: "synth", channelsDir: CORPUS }, + render: { width: 320, height: 180, fps: 30, fetchPad: 1, transition: 0, censor: [{ video: "vid2", boxes: [[0.5, 0, 0.5, 1]], style: "black" }] }, + timeline: [{ type: "clip", id: "c1", channel: "synth", video: "vid2", start: 2, end: 9, date: "2026-08-12", quote: "Deal with it", gaps: [{ from: 4, to: 5.5 }] }], + })); + const project = { id: "expc", dir: root }; + const RIGHT = { x: 200, y: 20, w: 100, h: 140 }; + const LEFT = { x: 20, y: 20, w: 100, h: 140 }; + for (const o of [{ kind: "cut" }, { kind: "context", context: 1 }]) { + const x = await exportClip(project, "c1", o); + assert.match(x.notes.join(" "), /1 region\(s\) hidden/); + for (const t of [0.5, 4]) { + assert.ok(lumaAt(x.abs, t, RIGHT) < 30, `${o.kind}: hidden at ${t} s (${lumaAt(x.abs, t, RIGHT)})`); + assert.ok(lumaAt(x.abs, t, LEFT) > 220, `${o.kind}: the rest as recorded at ${t} s`); + } + } + await assert.rejects(exportClip(project, "c1", { kind: "raw" }), (e) => e.status === 409 && /c1 hides 1 region\(s\).*--uncensored-raw/.test(e.message)); + const un = await exportClip(project, "c1", { kind: "raw", uncensoredRaw: true }); + assert.match(un.notes.join(" "), /UNCENSORED: 1 region\(s\) this clip hides are SHOWN/); + assert.ok(lumaAt(un.abs, 1, RIGHT) > 220, "as recorded"); + // The job the app runs carries the flag only when asked. + const steps = await exportSteps(project, "c1", { kind: "raw", uncensoredRaw: true }); + assert.ok(steps.at(-1).argv.includes("--uncensored-raw")); + assert.ok(!(await exportSteps(project, "c1", { kind: "raw" })).at(-1).argv.includes("--uncensored-raw")); +}); + test("export a clip whose window is not on disk: refused, fetch it first", async () => { const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-")); roots.push(root); diff --git a/umtool/lib/report/inspectorEdits.test.mjs b/umtool/lib/report/inspectorEdits.test.mjs @@ -187,6 +187,35 @@ test("a still at second N: one frame of the fetched window into shots/, listed; await assert.rejects(grabStill(p, m, "nope", 1), /no clip nope/); }); +/** The mean luma of a box of a PNG (0–255). */ +function pngLuma(file, { x, y, w, h }) { + const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `crop=${w}:${h}:${x}:${y},format=gray`, "-f", "rawvideo", "-"]); + assert.equal(r.status, 0, String(r.stderr)); + return r.stdout.reduce((n, v) => n + v, 0) / r.stdout.length; +} + +test("a still of a clip that hides regions: the boxes over its second hidden in the PNG; outside their span, as recorded", { skip: !hasFfmpeg && "no ffmpeg" }, async () => { + const m0 = MANIFEST(); + m0.render.censor = [{ video: "vid1", boxes: [{ box: [0.5, 0, 0.5, 1], from: 1, to: 2 }], style: "black" }]; + const p = await project(m0); + await mkdir(path.join(p.dir, "out", "clips-raw"), { recursive: true }); + const win = path.join(p.dir, "out", "clips-raw", "vid1_0.00-9.00.mp4"); + const ff = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=white:size=160x90:rate=10:duration=9", "-pix_fmt", "yuv420p", win]); + assert.equal(ff.status, 0, String(ff.stderr)); + const m = await read(p.dir); + const RIGHT = { x: 100, y: 10, w: 50, h: 70 }; + const LEFT = { x: 10, y: 10, w: 50, h: 70 }; + const inside = await grabStill(p, m, "c01", 1.5); + assert.ok(pngLuma(inside.file, RIGHT) < 30, `hidden (${pngLuma(inside.file, RIGHT)})`); + assert.ok(pngLuma(inside.file, LEFT) > 220, "the rest as recorded"); + const outside = await grabStill(p, m, "c01", 2.5); + assert.ok(pngLuma(outside.file, RIGHT) > 220, "past its span: as recorded"); + // A clip's own box (no span: the whole clip), whatever the recording's. + m.timeline[0].censor = { boxes: [[0, 0, 0.5, 1]], style: "black" }; + const own = await grabStill(p, m, "c01", 2.5, { name: "still-own.png" }); + assert.ok(pngLuma(own.file, LEFT) < 30 && pngLuma(own.file, RIGHT) > 220, "its own box"); +}); + // ---- the CLI twins (inspectorCli.mjs; timelineCli.mjs teaser-insert; linksCli.mjs --embed-ids) ---- const cli = await import("./inspectorCli.mjs"); const { timelineCommand } = await import("./timelineCli.mjs"); diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -8,6 +8,7 @@ // // Nothing is fetched or cut here: a clip whose source window is not on disk // is listed with `media: null` and plays as a placeholder. +import { censorRegionsOf } from "umtool-report-to-video/clip-censor"; import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video"; import { deckOn, estimatedDuration, estimateSchedule, scheduleFrom, transitionOf } from "umtool-report-to-video/deck"; import { resolveFactcheck } from "umtool-report-to-video/factcheck"; @@ -233,6 +234,8 @@ export async function playViewWith(project, { take = null, bare = false, postFor // Seconds taken out of its middle (gaps.mjs): the plan plays it as one item of jump cuts. ...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}), blur: e.blur && typeof e.blur === "object" ? e.blur : null, + // Its hidden regions (report-to-video clip-censor.mjs): Play draws them over the picture as the cut hides them. + censor: censorRegionsOf(e, render, selected.provenance ?? {}), // Its SIDE POST (lane vertical, common lib/report/vertical.mjs): shown beside it over `from`-`to` (seconds // into the clip as it plays), never read -- Play lays its card (the post-item route's `side` page) over the clip. ...(e.side && typeof e.side === "object" && fin(e.side.from) && fin(e.side.to) ? { side: { from: e.side.from, to: e.side.to, place: typeof e.side.place === "string" ? e.side.place : null } } : {}), diff --git a/umtool/lib/report/present.mjs b/umtool/lib/report/present.mjs @@ -36,6 +36,7 @@ import { clockZoneOf } from "umtool-report-to-video/post-clock"; import { estimateSchedule } from "umtool-report-to-video/deck"; import { gapsOf, keptSpans } from "umtool-report-to-video/gaps"; import { clipBlurOf } from "umtool-report-to-video/clip-blur"; +import { censorRegionsOf } from "umtool-report-to-video/clip-censor"; import { playViewWith } from "./playView.mjs"; import { projectRedaction } from "./postRedaction.mjs"; import { sectionModel } from "./sectionEdit.mjs"; @@ -439,6 +440,8 @@ export function presentFrom({ view, manifest, red, canUncensor = true }) { quote: e.quote ?? null, qrUrl: words?.qrUrl ?? null, blur: clipBlurOf(src, render), + // Its hidden regions (clip-censor.mjs): drawn over the picture on every Present page, a public one too. + hidden: censorRegionsOf(src, render, manifest.provenance ?? {}), }); continue; } diff --git a/umtool/lib/report/present.test.mjs b/umtool/lib/report/present.test.mjs @@ -239,3 +239,24 @@ test("the intro (render.intro) is the first slide, before any divider, in the fi const none = await presentPayload(await project("intro-none", MIXED, MIXED_RENDER)); assert.ok(!none.slides.some((s) => s.kind === "intro")); }); + +test("hidden regions (clip-censor.mjs): a clip slide carries its own boxes and its recording's, on a public payload too; Play's entry carries them", async () => { + const own = { style: "black", boxes: [{ box: [0.1, 0.1, 0.2, 0.2], from: 1.5, to: 2.5 }] }; + const p = await project("hidden", [ + { type: "clip", id: "c01", video: "v1", start: 1, end: 3, lock: true, censor: own }, + { type: "clip", id: "c02", video: "v2", start: 1, end: 3, lock: true }, + ], { censor: [{ video: "v1", style: "blur", boxes: [[0.6, 0.6, 0.3, 0.3]] }] }); + for (const canUncensor of [true, false]) { + const pl = await presentPayload(p, { canUncensor }); + const c1 = pl.slides.find((s) => s.id === "c01"); + const c2 = pl.slides.find((s) => s.id === "c02"); + assert.equal(c1.hidden.length, 2, `the clip's box and its recording's (canUncensor ${canUncensor})`); + assert.deepEqual(c1.hidden.map((g) => g.style).sort(), ["black", "blur"]); + const black = c1.hidden.find((g) => g.style === "black"); + assert.deepEqual([black.from, black.to], [1.5, 2.5], "its span, source seconds"); + assert.deepEqual(c2.hidden, [], "another recording: none"); + } + const { playView } = await import("./playView.mjs"); + const view = await playView(p); + assert.equal(view.entries.find((e) => e.id === "c01").censor.length, 2, "Play draws the same boxes"); +}); diff --git a/umtool/lib/report/shortsBatch.test.mjs b/umtool/lib/report/shortsBatch.test.mjs @@ -249,3 +249,36 @@ test("the promo ends a short only on a whole clip, and a reel's outro is not add await rm(w.root, { recursive: true, force: true }); } }); + +test("hidden regions reach a short of a RENDERED take (its render frozen): the take's boxes and the project's, added; --again keeps a box added since; a reframe refuses one", async () => { + const w = await world(); + try { + const m = JSON.parse(await readFile(path.join(w.dir, "video.manifest.json"), "utf8")); + const TAKE_BOX = { video: "v", boxes: [[0, 0, 0.2, 0.2]], style: "black" }; + // The take as rendered: its own recording box, frozen in its manifest. + await writeFile(path.join(w.dir, "takes", "kit", "video.manifest.json"), JSON.stringify({ ...m, render: { ...m.render, censor: [TAKE_BOX] } })); + const dry = (o = {}) => buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true, ...o }, { reportsRoot: w.reportsRoot }).then((r) => r.dryRun.hidden); + assert.deepEqual(await dry(), { w01: 1 }, "the take's own"); + // A box on the recording set on the PROJECT since: added, in every format. + m.render.censor = [{ video: "v", boxes: [[0.75, 0, 0.25, 1]], style: "black" }]; + await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify(m)); + assert.deepEqual(await dry(), { w01: 2 }, "a short"); + assert.deepEqual(await dry({ desktop: true }), { w01: 2 }, "a desktop clip"); + assert.deepEqual(await dry({ landscape: true }), { w01: 2 }, "the take's own 16:9 look"); + // A reframe cuts the take's finished picture, which does not hide it: refused, by clip. + await assert.rejects(dry({ reframe: true }), /--reframe cuts take kit's finished picture, which does not hide the regions set since .* on w01 \(2 box\(es\)\)/); + + // A batch, then a box on the clip itself: --again builds with it (the record's snapshot and the clip now, both). + const o = sink(); + assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01", "--formats", "vertical"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: standIn([]) }), 0, o.errs.join("\n")); + const m2 = JSON.parse(await readFile(path.join(w.dir, "video.manifest.json"), "utf8")); + m2.timeline.find((e) => e.id === "w01").censor = { boxes: [[0.4, 0.4, 0.2, 0.2]], style: "blur" }; + await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify(m2)); + const calls = []; + assert.equal(await shortsCommand(["proj", "--take", "kit", "--again"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: standIn(calls) }), 0, o.errs.join("\n")); + assert.equal(calls.length, 1); + assert.deepEqual(await dry({ overrides: calls[0].overrides }), { w01: 3 }, "the take's, the project's recording box and the clip's own, added since the batch"); + } finally { + await rm(w.root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/stillGrab.mjs b/umtool/lib/report/stillGrab.mjs @@ -13,6 +13,7 @@ import { mkdir, readdir, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { FFMPEG_BIN, FFPROBE_BIN } from "umtool-report-to-video/build-video"; +import { censorRegionsOf, stillCensorArgs } from "umtool-report-to-video/clip-censor"; import { resolveInRoots } from "../paths.mjs"; import { clipsOf } from "../projects/report.mjs"; import { windowsFor } from "./serve.mjs"; @@ -102,7 +103,16 @@ export async function grabStill(project, manifest, clipId, at, { ffmpeg = FFMPEG // Two grabs of one second at once never share a temp file. const tmp = path.join(dir, `.${file}.part-${process.pid}-${Math.random().toString(36).slice(2, 10)}.png`); try { - await execFileP(ffmpeg, ["-v", "error", "-y", "-ss", src.offset.toFixed(3), "-i", src.file, "-frames:v", "1", "-an", tmp], { timeout: 60_000 }); + // Its hidden regions at that second (report-to-video clip-censor.mjs): hidden in the still, as in every cut. + const regions = censorRegionsOf(clip, manifest?.render ?? {}, manifest?.provenance ?? {}); + let cen = []; + if (regions.length) { + const { stdout } = await execFileP(FFPROBE_BIN, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", src.file]); + const [w, h] = String(stdout).trim().split(",").map(Number); + if (!(w > 0 && h > 0)) throw new StillRefused(`${clipId} hides regions of its picture, and its window's size could not be read: no still is grabbed`, 500); + cen = stillCensorArgs(regions, t, { width: w, height: h }); + } + await execFileP(ffmpeg, ["-v", "error", "-y", "-ss", src.offset.toFixed(3), "-i", src.file, ...cen, "-frames:v", "1", "-an", tmp], { timeout: 60_000 }); const st = await stat(tmp).catch(() => null); if (!st?.size) throw new StillRefused(`the window of ${clip.video} has no picture at ${t.toFixed(2)} s (an audio-only fetch?)`, 409); await rename(tmp, out); diff --git a/umtool/lib/report/verticalCli.mjs b/umtool/lib/report/verticalCli.mjs @@ -260,7 +260,11 @@ export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} if (!take) throw new CliError("--take <t>: the take whose items the short is cut from"); if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`); const takeDir = path.join(takesDirOf(dir), take); - const takeManifest0 = await takeManifestOf(dir, take); + const takeManifestFrozen = await takeManifestOf(dir, take); + const projectManifest0 = await readJson(path.join(dir, "video.manifest.json")); + // The PROJECT's recording boxes (render.censor) are added to a take's -- a rendered take's render is frozen, and a + // region hidden since must never show in a short of it. ADD-ONLY: the take's own boxes stay. + const takeManifest0 = withProjectCensor(takeManifestFrozen, projectManifest0?.render?.censor); // A rebuild from a batch's record (`o.look`, LOOK_SNAPSHOT_KEYS) lays the look it was built with over the take's. const takeManifest = isObj(o.look) ? { ...takeManifest0, render: { ...(takeManifest0.render ?? {}), ...o.look } } : takeManifest0; const projectManifest = await readJson(path.join(dir, "video.manifest.json")); @@ -325,8 +329,26 @@ export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} notes.push(`the channel promo ends the short: the reel's outro card is not added after it`); outro = null; } + // Every clip's hidden regions as this build draws them (the take's, the project's added: clip-censor.mjs). A reframe + // cuts the take's FINISHED picture, which hides only what the take was rendered with: a region hidden since is + // refused by name, never cut showing. + const C = await import("umtool-report-to-video/clip-censor"); + const baseId = (id) => String(id).replace(/~(?:\d+|co)$/, ""); + const frozenById = new Map((takeManifestFrozen.timeline ?? []).map((e) => [e?.id, e])); + const hidden = Object.fromEntries(plan.timeline.filter((e) => e?.type === "clip").map((e) => [e.id, C.censorRegionsOf(e, takeManifest.render ?? {}, takeManifest.provenance ?? {}).length])); + if (reframe) { + const since = plan.timeline.filter((e) => e?.type === "clip").filter((e) => { + const was = frozenById.get(baseId(e.id)); + const now = C.censorRecordOf(C.censorRegionsOf(e, takeManifest.render ?? {}, takeManifest.provenance ?? {})); + const then = was ? C.censorRecordOf(C.censorRegionsOf(was, takeManifestFrozen.render ?? {}, takeManifestFrozen.provenance ?? {})) : []; + return JSON.stringify(now) !== JSON.stringify(then); + }); + if (since.length) { + throw new CliError(`--reframe cuts take ${take}'s finished picture, which does not hide the regions set since it was rendered on ${since.map((e) => `${baseId(e.id)} (${hidden[e.id]} box(es))`).join(", ")}: render the take again, or build the short without --reframe`); + } + } if (o.dryRun) { - return { dryRun: { project: r.project.id, take, name, layout: tag, wouldWrite: outFile, intro: introSpec ? (introSpec === true ? "the take's render.intro, else the default" : introSpec) : null, outro: outro ? { title: outro.title, text: outro.text, image: outro.image, seconds: outro.seconds } : null, pieces: plan.pieces, items: plan.timeline.map((e) => ({ id: e.id, type: e.type, start: e.start, end: e.end })), promo: promoEnds, notes } }; + return { dryRun: { project: r.project.id, take, name, layout: tag, wouldWrite: outFile, hidden, intro: introSpec ? (introSpec === true ? "the take's render.intro, else the default" : introSpec) : null, outro: outro ? { title: outro.title, text: outro.text, image: outro.image, seconds: outro.seconds } : null, pieces: plan.pieces, items: plan.timeline.map((e) => ({ id: e.id, type: e.type, start: e.start, end: e.end })), promo: promoEnds, notes } }; } const started = Date.now(); // The project's fetched windows (and narration) are the take's too, as a made take's are (takeMaker.mjs @@ -429,6 +451,14 @@ export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} return { record }; } +/** A take's render with the project's recording boxes added (each once); the take as it is when there are none. */ +export function withProjectCensor(take, projectCensor) { + if (!Array.isArray(projectCensor) || !projectCensor.length) return take; + const have = Array.isArray(take?.render?.censor) ? take.render.censor : []; + const added = projectCensor.filter((r) => !have.some((x) => JSON.stringify(x) === JSON.stringify(r))); + return added.length ? { ...take, render: { ...(take.render ?? {}), censor: [...have, ...added] } } : take; +} + /** A take's manifest as rendered, else (a draft, never rendered) the project's with the take's patch laid on. */ export async function takeManifestOf(dir, take) { const rendered = await readJson(path.join(takesDirOf(dir), take, "video.manifest.json")); diff --git a/umtool/report-to-video/basic.mjs b/umtool/report-to-video/basic.mjs @@ -38,6 +38,7 @@ import path from "node:path"; import { promisify } from "node:util"; import { basicFadeOf, basicOn } from "yt-dlp-transcript-common/lib/report/look.mjs"; import { clipBlurOf } from "./clip-blur.mjs"; +import { censorRegionsOf } from "./clip-censor.mjs"; import { keptSpans, renderGaps } from "./gaps.mjs"; import { hasLocalMedia } from "./local-media.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; @@ -102,6 +103,13 @@ export function basicPlan(manifest, { only = null } = {}) { errors.push(`${e.id}: no span to play (start/end, cutStart/cutEnd)`); continue; } + // Its hidden regions (clip-censor.mjs): a basic cut draws none, and privacy is not switched off by a mode -- + // refused by name, whatever render.blur says. + const boxes = censorRegionsOf(e, render, manifest?.provenance ?? {}); + if (boxes.length) { + errors.push(`${e.id} hides ${boxes.length} region(s) of its picture (render.censor / its censor), and a basic cut draws none: render it as a deck cut, or take the boxes off only if the regions may show`); + continue; + } if (clipBlurOf(e, render)) { errors.push(`${e.id} asks for its picture blurred, and a basic cut draws no blur: render it as a deck cut, or say the basic cut is the uncensored one (umtool look <p> blur=off)`); continue; diff --git a/umtool/report-to-video/basic.test.mjs b/umtool/report-to-video/basic.test.mjs @@ -77,6 +77,16 @@ test("basicPlan: clips and their spans in order; the rest left out by name; a bl assert.deepEqual(basicPlan({ render: { basic: { fade: { video: 0.5 } } }, timeline: [] }).fade, { audio: 0.03, video: 0.5 }); }); +test("basicPlan: a clip that hides regions is refused by name -- its own box or its recording's, in the uncensored cut too", () => { + const clip = { type: "clip", id: "c1", video: "v", start: 1, end: 3 }; + const own = basicPlan({ render: {}, timeline: [{ ...clip, censor: { boxes: [[0, 0, 0.5, 0.5]] } }] }); + assert.match(own.errors[0], /c1 hides 1 region\(s\) of its picture .* a basic cut draws none/); + assert.deepEqual(own.items, []); + const rec = basicPlan({ render: { blur: "off", censor: [{ video: "v", boxes: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]] }] }, timeline: [clip] }); + assert.match(rec.errors[0], /c1 hides 2 region\(s\)/, "render.blur off does not lift a hidden region"); + assert.deepEqual(basicPlan({ render: { censor: [{ video: "another", boxes: [[0, 0, 0.5, 0.5]] }] }, timeline: [clip] }).errors, [], "another recording's: as before"); +}); + test("spanArgs: the file's seconds, fitted into the first window's shape, its fades and gain, the build's encode", () => { const shape = basicShape({ width: 1920, height: 1080, sar: "1:1", fps: "60/1" }); assert.deepEqual(shape, { W: 1920, H: 1080, fps: "60/1" }); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -242,7 +242,7 @@ import { promoBand, promoCardInput, promoFilterParts, promoOf, renderPromoCard, // ZOOM AT POINTS (lane clip-kit, slice F; clip-zoom.mjs): a per-clip build's pushes in on its picture. import { resolveZooms, validateZooms, zoomFilters } from "./clip-zoom.mjs"; // HIDDEN REGIONS (lane clip-kit, slice E; clip-censor.mjs): a recording's chat overlay, other accounts on screen. -import { censorParts, censorRecordOf, censorRegionsOf, validateCensor } from "./clip-censor.mjs"; +import { censorParts, censorProblems, censorRecordOf, censorRegionsOf, stillCensorArgs, validateCensor } from "./clip-censor.mjs"; // THE STACKED VERTICAL DECK (vertical-deck.mjs): a 9:16 cut that keeps its deck -- the picture at full width, the // captions under it, a clip's two crops, a post item's hero card -- and the modules it leaves out. import { ENLARGE_WARN, clipTwoCrop, leftOutWords, stackedCaptionGeo, stackedGeometry, stackedOn, twoCropEnlargement, twoCropGraph } from "./vertical-deck.mjs"; @@ -1817,6 +1817,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const censorRegions = media.hasVideo ? censorRegionsOf(entry, render, provenance) : []; const censorDims = censorRegions.length ? await probeDims(raw) : null; if (censorRegions.length) cutRecord.censor = censorRecordOf(censorRegions); + // No picture (a poster plays): nothing to hide, and the record says so (a chrome pass reads it). + else if (!media.hasVideo && censorRegionsOf(entry, render, provenance).length) cutRecord.censorNoPicture = true; /** The picture `vLabel` (a "[label]") with the regions hidden: the parts to run first, and the label after them. */ const censored = (vLabel) => { if (!censorRegions.length) return { parts: [], v: vLabel }; @@ -2151,7 +2153,11 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const mg = mont ? montageSegmentGraph({ mont, render, box: { w: VW, h: VH }, hasVideo: media.hasVideo, cutA, cutB, gainDb: level?.gain ?? null }) : null; // The gaps out first (none in a montage: segGaps is empty there). const g = gapped(ain); - // Hidden regions (clip-censor.mjs) on the picture first; a montage re-cuts its picture, and draws none. + // Hidden regions (clip-censor.mjs) on the picture first. A montage re-cuts its pictures from the source in its own + // graph: a montage clip with boxes is REFUSED, by name (never cut with the region showing). + if (mg && censorRegions.length) { + throw new Error(`${entry.id}: a montage clip cannot hide regions yet (${censorRegions.length} box(es) of its recording, render.censor or its own censor) -- take it out of the montage, or set its censor=false only if the region may show`); + } const cenPlain = mg || pst ? { parts: [], v: null } : censored(g.v); const pic = mg?.v ?? (pst ? "[pic]" : cenPlain.v); const lead = mg @@ -7645,6 +7651,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // A clip's blur is in its segment's picture (clip-blur.mjs): a cut // that asks for another (render.blur turned off) needs the segments again. ...blurProblems({ entries: present.map((i) => entries[i]), records, render }), + // Its hidden regions likewise (clip-censor.mjs): a box added since must never be laid over uncensored. + ...censorProblems({ entries: present.map((i) => entries[i]), records, render, provenance }), ]; if (problems.length) throw new Error(`${what}: ${problems.join("; ")}`); } @@ -7994,10 +8002,14 @@ async function buildThumbnail(manifest, dirs, manifestDir) { const blur = clipBlurOf(clip, render); const blurred = blur && (blur.from ?? -Infinity) <= at && at <= (blur.to ?? Infinity); const sigma = blurred ? Math.max(1, Math.round((blur.strength / 100) * (await probeDims(win.path))[1])) : 0; + // Its hidden regions at that second (clip-censor.mjs) are hidden in the still too, before any blur. + const regions = censorRegionsOf(clip, render, manifest.provenance ?? {}); + const dims = regions.length ? await probeDims(win.path) : null; + const cen = regions.length ? stillCensorArgs(regions, at, { width: dims[0], height: dims[1] }, blurred ? [`gblur=sigma=${sigma}:steps=3`] : []) : []; await execFileP(FFMPEG, [ "-nostdin", "-v", "error", "-y", "-ss", Math.max(0, at - win.from).toFixed(3), "-i", win.path, - ...(blurred ? ["-vf", `gblur=sigma=${sigma}:steps=3`] : []), + ...(cen.length ? cen : blurred ? ["-vf", `gblur=sigma=${sigma}:steps=3`] : []), "-frames:v", "1", still, ]); } diff --git a/umtool/report-to-video/clip-censor.mjs b/umtool/report-to-video/clip-censor.mjs @@ -83,6 +83,13 @@ export function renderCensorErrors(v, where = "render.censor") { /** Every reason a manifest's hidden regions cannot be drawn. */ export function validateCensor(manifest) { const errors = renderCensorErrors(manifest?.render?.censor); + // A montage re-cuts its pictures in its own graph, which draws no boxes: refused by name, never cut showing them. + if (isObj(manifest?.render?.montage)) { + for (const e of manifest?.timeline ?? []) { + const n = censorRegionsOf(e, manifest.render, manifest.provenance ?? {}).length; + if (n) errors.push(`timeline ${e.id}: a montage cannot hide regions yet (${n} box(es)): take render.montage off, or the boxes only if the regions may show`); + } + } for (const e of manifest?.timeline ?? []) { if (e?.censor === undefined) continue; if (e.type !== "clip") errors.push(`timeline ${e.id ?? "?"}: censor is a clip's`); @@ -162,3 +169,39 @@ export function censorParts(vIn, vOut, regions, { width, height, from = 0, gaps /** What a cut record says of the regions it hid (rounded). */ export const censorRecordOf = (regions) => regions.map((g) => ({ box: g.box, style: g.style, ...(g.style !== "black" ? { strength: g.strength } : {}), ...(g.from !== null ? { from: g.from } : {}), ...(g.to !== null ? { to: g.to } : {}) })); + +/** + * Why segments on disk cannot take this cut (`--chrome-only`, `--chrome-preview`): a clip whose recorded hidden + * regions are not the ones this cut asks for -- a box added, moved or taken off since it was cut. The regions are in + * the segment's picture, so a changed set needs the segment again: refused by name, never laid over uncensored. + * A clip with no picture (a poster plays) records that it had nothing to hide. + */ +export function censorProblems({ entries, records, render, provenance = {} }) { + const wrong = []; + entries.forEach((e, i) => { + if (e?.type !== "clip") return; + const want = censorRecordOf(censorRegionsOf(e, render, provenance)); + const rec = records[i] ?? null; + if (rec?.censorNoPicture === true) return; + const got = Array.isArray(rec?.censor) ? rec.censor : []; + if (JSON.stringify(want) === JSON.stringify(got)) return; + wrong.push(`${e.id} (${got.length} box(es) hidden on disk, ${want.length} asked for)`); + }); + if (!wrong.length) return []; + return [ + `${wrong.length} segment(s) hide other regions than this cut asks for: ${wrong.join(", ")}. ` + + "The hidden regions are in the segment's picture -- run a normal build (with --skip-fetch it re-cuts from the cached windows), not a chrome pass.", + ]; +} + +/** + * The regions a STILL of a clip at source second `at` hides (those over it), drawn on a frame `width`×`height`: + * ffmpeg args (`-filter_complex`, a graph from [0:v] to [cstill], `-map`) or none. `after` filters (a blur) follow. + */ +export function stillCensorArgs(regions, at, { width, height }, after = []) { + const over = (regions ?? []).filter((g) => (g.from === null || g.from <= at + 1e-6) && (g.to === null || at <= g.to + 1e-6)).map((g) => ({ ...g, from: null, to: null })); + if (!over.length && !after.length) return []; + const parts = over.length ? censorParts("0:v", after.length ? "cstill0" : "cstill", over, { width, height }) : []; + if (after.length) parts.push(`[${over.length ? "cstill0" : "0:v"}]${after.join(",")}[cstill]`); + return ["-filter_complex", parts.join(";"), "-map", "[cstill]"]; +} diff --git a/umtool/report-to-video/clip-censor.test.mjs b/umtool/report-to-video/clip-censor.test.mjs @@ -2,7 +2,12 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { censorParts, censorRegionsOf, clipCensorErrors, namesClip, renderCensorErrors, validateCensor } from "./clip-censor.mjs"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { censorParts, censorProblems, censorRecordOf, censorRegionsOf, clipCensorErrors, namesClip, renderCensorErrors, stillCensorArgs, validateCensor } from "./clip-censor.mjs"; +import { buildVideo, segmentFraming, setProgressMode } from "./build-video.mjs"; +import { mergeCensor, withOverrides } from "./vertical-plan.mjs"; import { parseBox, withRecording } from "../lib/report/censorCli.mjs"; const clip = (o = {}) => ({ type: "clip", id: "c1", channel: "chan", video: "rec1", start: 100, end: 160, ...o }); @@ -56,3 +61,84 @@ test("umtool censor's arguments: a box, a box over a span; a recording's set rep assert.deepEqual(withRecording(list, { video: "rec1" }, { video: "rec1", boxes: [[0, 0, 1, 0.1]] }).map((r) => [r.video, r.boxes.length]), [["rec2", 1], ["rec1", 1]]); assert.deepEqual(withRecording(list, { video: "rec1" }, null).map((r) => r.video), ["rec2"]); }); + +test("a chrome pass is refused when the hidden regions changed since the segments were cut (censorProblems)", () => { + const e = clip({ censor: { boxes: [[0.1, 0.1, 0.2, 0.2]], style: "black" } }); + const want = censorRecordOf(censorRegionsOf(e, {}, {})); + assert.deepEqual(censorProblems({ entries: [e], records: [{ censor: want }], render: {} }), [], "the same boxes: passes"); + const [msg] = censorProblems({ entries: [e], records: [{}], render: {} }); + assert.match(msg, /1 segment\(s\) hide other regions than this cut asks for: c1 \(0 box\(es\) hidden on disk, 1 asked for\)/); + assert.match(msg, /run a normal build/); + // A recording's box added since (render.censor) is a change too; one taken off as well. + assert.equal(censorProblems({ entries: [clip()], records: [{}], render: { censor: [CHAT] } }).length, 1); + assert.equal(censorProblems({ entries: [clip()], records: [{ censor: want }], render: {} }).length, 1); + // A clip with no picture (audio only) records that it hid nothing; legacy segments with no boxes asked pass. + assert.deepEqual(censorProblems({ entries: [e], records: [{ censorNoPicture: true }], render: {} }), []); + assert.deepEqual(censorProblems({ entries: [clip()], records: [null], render: {} }), []); +}); + +test("--chrome-only / --chrome-preview: built, a box added, refused before any chrome is rendered", async () => { + setProgressMode(() => {}); + const dir = mkdtempSync(path.join(tmpdir(), "censor-chrome-")); + const env = process.env.HYPERFRAMES_BIN; + try { + const mark = path.join(dir, "rendered"); + const stub = path.join(dir, "hf-stub.sh"); + writeFileSync(stub, `#!/bin/sh\ntouch '${mark}'\nexit 1\n`); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + const render = { width: 1920, height: 1080, fps: 30, transition: 0, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" }, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }; + const manifestPath = path.join(dir, "m.json"); + const c = { id: "c1", type: "clip", video: "a", start: 0, end: 10, date: "2024-09-05" }; + // The segment as a build left it: no boxes. + const segDir = path.join(dir, "out", "sourced", "segments"); + mkdirSync(segDir, { recursive: true }); + writeFileSync(path.join(segDir, "c1.mp4"), ""); + writeFileSync(path.join(segDir, "c1.cut.json"), JSON.stringify({ version: 1, framing: segmentFraming(render, false) })); + // Then a box on the clip, and one on its recording. + for (const m of [{ timeline: [{ ...c, censor: { boxes: [[0.75, 0, 0.25, 1]], style: "black" } }], render }, { timeline: [c], render: { ...render, censor: [{ video: "a", boxes: [[0, 0, 0.5, 0.5]] }] } }]) { + writeFileSync(manifestPath, JSON.stringify({ slug: "refuse", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, ...m })); + for (const opts of [{ chromeOnly: true }, { chromePreview: { at: 1, dur: 2 } }]) { + await assert.rejects(buildVideo({ manifestPath, opts }), /hide other regions than this cut asks for: c1/); + } + } + assert.equal((await import("node:fs")).existsSync(mark), false, "nothing rendered before the refusal"); + } finally { + if (env === undefined) delete process.env.HYPERFRAMES_BIN; + else process.env.HYPERFRAMES_BIN = env; + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("a montage cannot hide regions yet: refused by name, its own box or its recording's", () => { + const montage = { style: "punchy" }; + assert.match(validateCensor({ render: { montage }, timeline: [clip({ censor: { boxes: [[0, 0, 0.5, 0.5]] } })] }).join(), /timeline c1: a montage cannot hide regions yet \(1 box\(es\)\)/); + assert.match(validateCensor({ render: { montage, censor: [CHAT] }, timeline: [clip()] }).join(), /a montage cannot hide regions yet/); + assert.deepEqual(validateCensor({ render: { montage }, timeline: [clip()] }), [], "a montage with no boxes as before"); + assert.deepEqual(validateCensor({ render: { censor: [CHAT] }, timeline: [clip()] }), [], "boxes without a montage as before"); +}); + +test("a still's boxes (stillCensorArgs): those over its second, the whole box; none, no args; a blur after them", () => { + const regions = censorRegionsOf(clip({ censor: { boxes: [{ box: [0.5, 0, 0.5, 1], from: 120, to: 130 }], style: "black" } }), {}, {}); + assert.deepEqual(stillCensorArgs(regions, 110, { width: 1920, height: 1080 }), [], "outside its span: the still as it was"); + const args = stillCensorArgs(regions, 125, { width: 1920, height: 1080 }); + assert.equal(args[0], "-filter_complex"); + assert.match(args[1], /drawbox=x=960:y=0:w=960:h=1080/); + assert.deepEqual(args.slice(2), ["-map", "[cstill]"]); + const blurred = stillCensorArgs(regions, 125, { width: 1920, height: 1080 }, ["gblur=sigma=20"]); + assert.match(blurred[1], /\[cstill0\]gblur=sigma=20\[cstill\]$/); +}); + +test("a batch's snapshot never takes a box off (mergeCensor, withOverrides): the clip's now and the snapshot's, both", () => { + const A = [0, 0, 0.2, 0.2]; + const B = [0.5, 0.5, 0.2, 0.2]; + assert.deepEqual(mergeCensor({ boxes: [A], style: "black" }, null), { boxes: [A], style: "black" }); + assert.deepEqual(mergeCensor(undefined, { boxes: [B] }), { boxes: [B] }); + assert.deepEqual(mergeCensor({ boxes: [A], style: "black" }, { boxes: [B, A], style: "blur" }).boxes, [A, B], "a union, no box twice; the clip's style"); + assert.equal(mergeCensor({ boxes: [A] }, null).style, undefined); + assert.equal(mergeCensor(false, null), false, "a clip that opts out of its recording's boxes, as written"); + assert.equal(mergeCensor(undefined, null), undefined); + const tl = [{ type: "clip", id: "c1", video: "v", start: 0, end: 4, censor: { boxes: [A] } }]; + assert.deepEqual(withOverrides(tl, { c1: { censor: null, vertical: null } })[0].censor, { boxes: [A] }, "a box added after the batch is kept"); + assert.equal("censor" in withOverrides([{ ...tl[0], censor: undefined }], { c1: { censor: null } })[0], false); +}); diff --git a/umtool/report-to-video/vertical-plan.mjs b/umtool/report-to-video/vertical-plan.mjs @@ -43,12 +43,32 @@ export function beatsOf(doc) { */ export const PROJECT_KEYS = Object.freeze(["vertical", "side", "qr", "promo", "zooms", "coldOpen", "censor"]); -/** The project's per-clip framing (PROJECT_KEYS) laid over a take's entry. */ +/** + * A clip's hidden regions from two sources, ADD-ONLY (clip-censor.mjs: a privacy control): the boxes of both, never + * fewer than either had. A side that says none (absent, null) adds nothing; `false` (an opt-out) only stands when + * the other side has no boxes either. + */ +export function mergeCensor(a, b) { + const boxesOf = (v) => (isObj(v) && Array.isArray(v.boxes) ? v.boxes : []); + const all = [...boxesOf(a)]; + for (const x of boxesOf(b)) if (!all.some((y) => JSON.stringify(y) === JSON.stringify(x))) all.push(x); + if (all.length) return { ...(isObj(b) ? b : {}), ...(isObj(a) ? a : {}), boxes: all }; + if (a === false || b === false) return false; + return a ?? b ?? undefined; +} + +/** The project's per-clip framing (PROJECT_KEYS) laid over a take's entry; its hidden regions added to the take's. */ export function withProjectFraming(entry, projectById) { const own = projectById?.get?.(entry?.id); if (!own || entry?.type !== "clip") return entry; const out = { ...entry }; - for (const k of PROJECT_KEYS) if (own[k] !== undefined) out[k] = own[k]; + for (const k of PROJECT_KEYS) { + if (k === "censor") { + const m = mergeCensor(own.censor, entry.censor); + if (m === undefined) delete out.censor; + else out.censor = m; + } else if (own[k] !== undefined) out[k] = own[k]; + } return out; } @@ -64,6 +84,13 @@ export function withOverrides(timeline, overrides) { const out = { ...e }; for (const [k, v] of Object.entries(o)) { if (!PROJECT_KEYS.includes(k)) continue; + // Hidden regions: the snapshot's and the clip's boxes now, both (a box added since a batch was built is kept). + if (k === "censor") { + const m = mergeCensor(e.censor, v); + if (m === undefined) delete out.censor; + else out.censor = m; + continue; + } if (v === null) delete out[k]; else out[k] = v; }