Archilyzer · Source

archilyzer

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

commit 70bf0f44400b84d845c30075815e673117e37ae8
parent ab20ff53f622c5379e4b5c60afafbfd57548f8c9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 02:12:05 -0500

umtool: a band censor across a post item's attachment -- everything below (above, between) a line, or one side of an upright one, blurred, black or pixelated (operator: "censor across a line dividing the image e.g. censor everything neck down")

media[i].blur gains band ({below|above|between, left|right}, fractions of the
picture as shown) and style (blur|black|pixelate): the band is one more region
beside the boxes, the label at its corner. The render draws it (gblur, a
drawbox fill, a neighbour scale down and up), Play and the bench preview it
(a pixelated region drawn coarse on a canvas, live), and the bench's pad
draws the band's line(s) to drag. One knob, set-item media.<i>.censor=
below:0.38[:style][:strength] (off), and the long forms media.<i>.blur.band=
and .style=. It stays on in an uncensored cut, like the rest of the censor.

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

Diffstat:
Mumtool/components/projects/BlurBoxPad.tsx | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/components/projects/PostBench.tsx | 57++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/review/PostItemPlayer.tsx | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/docs/knobs.md | 1+
Mumtool/lib/report/postThread.test.mjs | 10++++++++++
Mumtool/lib/report/postsCli.mjs | 36++++++++++++++++++++++++++++++------
Mumtool/report-to-video/post-censor.mjs | 189++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/report-to-video/post-censor.test.mjs | 85++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
8 files changed, 491 insertions(+), 44 deletions(-)

diff --git a/umtool/components/projects/BlurBoxPad.tsx b/umtool/components/projects/BlurBoxPad.tsx @@ -1,14 +1,20 @@ "use client"; import { useEffect, useRef, useState } from "react"; +import { bandBox } from "umtool-report-to-video/post-censor"; // THE CENSOR BOXES, DRAWN (post-censor.mjs; knobs.md, "A post item"): the // attachment on a still frame -- a picture as it is, a video paused at the // bench's playhead (or its in point) -- shown as the cut shows it (its crop), // each box over it; drag to draw a new one, × to take one away. The boxes are // fractions of the picture as shown, which is what the render blurs. +// +// THE BAND (post-censor.mjs `band`): its line (two, between) drawn across the +// frame -- an upright one for left/right -- each dragged to where the censor +// starts; the region it censors tinted. A drag writes the knob (`onBand`). type Box = number[]; +export type Band = { below?: number; above?: number; between?: number[]; left?: number; right?: number }; type Props = { project: string; media: { src: string; kind: string; width?: number; height?: number; crop?: number[] }; @@ -17,13 +23,31 @@ type Props = { boxes: Box[]; onChange: (boxes: Box[]) => void; index: number; + /** The band (null: none), and its writer: each line dragged sets its edge. */ + band?: Band | null; + onBand?: (band: Band) => void; }; +/** A band's lines: `[{ edge, at, upright }]` (between: its two). */ +const linesOf = (band: Band | null | undefined) => { + if (!band) return [] as Array<{ edge: string; at: number; upright: boolean; k?: number }>; + const out: Array<{ edge: string; at: number; upright: boolean; k?: number }> = []; + if (typeof band.below === "number") out.push({ edge: "below", at: band.below, upright: false }); + else if (typeof band.above === "number") out.push({ edge: "above", at: band.above, upright: false }); + else if (Array.isArray(band.between)) band.between.forEach((at, k) => out.push({ edge: "between", at, upright: false, k })); + if (typeof band.left === "number") out.push({ edge: "left", at: band.left, upright: true }); + else if (typeof band.right === "number") out.push({ edge: "right", at: band.right, upright: true }); + return out; +}; +const r3 = (v: number) => Math.round(v * 1000) / 1000; + const r4 = (v: number) => Math.round(v * 10000) / 10000; const clamp = (v: number) => Math.min(1, Math.max(0, v)); -export default function BlurBoxPad({ project, media, at, boxes, onChange, index }: Props) { +export default function BlurBoxPad({ project, media, at, boxes, onChange, index, band = null, onBand }: Props) { const pad = useRef<HTMLDivElement | null>(null); + const [line, setLine] = useState<{ edge: string; k?: number } | null>(null); + const region = bandBox(band) as number[] | null; const video = useRef<HTMLVideoElement | null>(null); const [drag, setDrag] = useState<{ x: number; y: number; x2: number; y2: number } | null>(null); const crop = Array.isArray(media.crop) && media.crop.length === 4 ? media.crop : [0, 0, 1, 1]; @@ -59,16 +83,39 @@ export default function BlurBoxPad({ project, media, at, boxes, onChange, index data-post-bench-blur-pad={index} onPointerDown={(ev) => { if ((ev.target as HTMLElement).closest("button")) return; + // A band's line: dragged, not a box drawn. + const handle = (ev.target as HTMLElement).closest("[data-post-bench-band-line]") as HTMLElement | null; + if (handle && band && onBand) { + (ev.currentTarget as HTMLDivElement).setPointerCapture(ev.pointerId); + const k = handle.getAttribute("data-band-k"); + setLine({ edge: handle.getAttribute("data-post-bench-band-line") ?? "", ...(k ? { k: Number(k) } : {}) }); + return; + } (ev.currentTarget as HTMLDivElement).setPointerCapture(ev.pointerId); const p = where(ev); setDrag({ x: p.x, y: p.y, x2: p.x, y2: p.y }); }} onPointerMove={(ev) => { + if (line && band && onBand) { + const p = where(ev); + const upright = line.edge === "left" || line.edge === "right"; + const v = r3(Math.min(0.98, Math.max(0.02, upright ? p.x : p.y))); + if (line.edge === "between") { + const b = [...(band.between ?? [0.3, 0.6])]; + b[line.k ?? 0] = v; + onBand({ ...band, between: [Math.min(b[0], b[1]), Math.max(b[0], b[1])].map(r3) }); + } else onBand({ ...band, [line.edge]: v }); + return; + } if (!drag) return; const p = where(ev); setDrag({ ...drag, x2: p.x, y2: p.y }); }} onPointerUp={() => { + if (line) { + setLine(null); + return; + } if (!drag) return; const b = box(drag); setDrag(null); @@ -81,6 +128,29 @@ export default function BlurBoxPad({ project, media, at, boxes, onChange, index ) : ( <video ref={video} src={src} muted playsInline preload="auto" style={inner} /> )} + {region && ( + <div + data-post-bench-band-region={region.join(",")} + className="pointer-events-none absolute bg-sky-400/25 outline outline-1 outline-sky-300/70" + style={{ left: `${region[0] * 100}%`, top: `${region[1] * 100}%`, width: `${region[2] * 100}%`, height: `${region[3] * 100}%` }} + /> + )} + {linesOf(band).map((l) => ( + <div + key={`${l.edge}${l.k ?? ""}`} + data-post-bench-band-line={l.edge} + data-band-k={l.k === undefined ? undefined : String(l.k)} + data-band-at={String(l.at)} + title={`${l.edge} ${Math.round(l.at * 100)}% -- drag it`} + className={`absolute z-10 ${l.upright ? "top-0 h-full w-3 -translate-x-1/2 cursor-ew-resize" : "left-0 h-3 w-full -translate-y-1/2 cursor-ns-resize"}`} + style={l.upright ? { left: `${l.at * 100}%` } : { top: `${l.at * 100}%` }} + > + <div className={`absolute bg-sky-300 ${l.upright ? "left-1/2 top-0 h-full w-0.5 -translate-x-1/2" : "left-0 top-1/2 h-0.5 w-full -translate-y-1/2"}`} /> + <span className={`absolute rounded bg-sky-300 px-1 text-[10px] font-mono leading-tight text-black ${l.upright ? "left-1/2 top-1 -translate-x-1/2" : "right-1 top-1/2 -translate-y-1/2"}`}> + {Math.round(l.at * 100)}% + </span> + </div> + ))} {[...boxes, ...(drag ? [box(drag)] : [])].map((b, j) => ( <div key={j} @@ -103,7 +173,8 @@ export default function BlurBoxPad({ project, media, at, boxes, onChange, index ))} </div> <p className="m-0 text-[11.5px] text-text-2"> - drag on the frame to blur a region; no box blurs the whole frame{boxes.length ? ` · ${boxes.length} box${boxes.length === 1 ? "" : "es"}` : ""} + drag on the frame to censor a region; no box and no band censors the whole frame{boxes.length ? ` · ${boxes.length} box${boxes.length === 1 ? "" : "es"}` : ""} + {band ? " · drag the band's line" : ""} </p> </div> ); diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -10,7 +10,7 @@ import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; import PostThreadPanel from "./PostThreadPanel"; -import BlurBoxPad from "./BlurBoxPad"; +import BlurBoxPad, { type Band } from "./BlurBoxPad"; import PostNarrationPanel from "./PostNarrationPanel"; import PostComboPanel from "./PostComboPanel"; import ComboBadge, { type ComboInfo } from "./review/ComboBadge"; @@ -38,7 +38,7 @@ import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; // "paraphrased" label (its own text kept, shown beside) // --------------------------------------------------------------------------- -type Blur = { on: boolean; strength?: number; boxes?: number[][]; label?: string | false }; +type Blur = { on: boolean; strength?: number; boxes?: number[][]; label?: string | false; band?: Band; style?: "blur" | "black" | "pixelate" }; type Media = Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number; mute?: boolean; crop?: number[]; push?: boolean; words?: string; audio?: boolean; width?: number; height?: number; blur?: Blur }; type Ref = Record<string, unknown> & { author?: string; handle?: string; text?: string; paraphrase?: string }; type Entry = Record<string, unknown> & { id: string; media?: Media[]; hold?: number; mediaLayout?: string; redact?: boolean; quoted?: Ref; parents?: Ref[] }; @@ -51,6 +51,22 @@ const withParaphrase = (ref: Ref, paraphrase: string | undefined): Ref => { else out.paraphrase = paraphrase; return out; }; +/** A band's edge across: below, above, between, or none. */ +const bandAcross = (b: Band | undefined) => (typeof b?.below === "number" ? "below" : typeof b?.above === "number" ? "above" : Array.isArray(b?.between) ? "between" : "none"); +const bandEmpty = (b: Band) => (Object.keys(b).length ? b : undefined); +/** The band with its edge across set to `to` (none: dropped), the line where it was (or a third of the way down). */ +const withAcross = (b: Band | undefined, to: string): Band | undefined => { + const { below, above, between, ...rest } = b ?? {}; + const at = below ?? above ?? (between ? between[0] : 0.38); + if (to === "none") return bandEmpty(rest); + return { ...rest, ...(to === "between" ? { between: between ?? [Math.min(at, 0.6), Math.max(0.7, Math.min(0.95, at + 0.3))] } : { [to]: at }) }; +}; +/** The band with its upright edge set to `to` (all: dropped). */ +const withUpright = (b: Band | undefined, to: string): Band | undefined => { + const { left, right, ...rest } = b ?? {}; + if (to === "all") return bandEmpty(rest); + return { ...rest, [to]: left ?? right ?? 0.5 }; +}; const CROPS: Array<{ label: string; crop: number[] | null }> = [ { label: "none", crop: null }, { label: "centre 80%", crop: [0.1, 0.1, 0.8, 0.8] }, @@ -158,7 +174,7 @@ export default function PostBench({ push: m.push === true ? true : null, // The censoring blur (post-censor.mjs), every key as it stands (null: cleared). blur: m.blur - ? { on: m.blur.on === true, strength: m.blur.strength ?? null, boxes: m.blur.boxes?.length ? m.blur.boxes : null, label: m.blur.label === undefined ? null : m.blur.label } + ? { on: m.blur.on === true, strength: m.blur.strength ?? null, boxes: m.blur.boxes?.length ? m.blur.boxes : null, label: m.blur.label === undefined ? null : m.blur.label, band: m.blur.band ?? null, style: m.blur.style ?? null } : null, }, ]), @@ -542,6 +558,39 @@ export default function PostBench({ </button> )} </div> + <div className="flex flex-wrap items-center gap-2"> + style + <select + value={m.blur.style ?? "blur"} + onChange={(e) => setMedia(i, { blur: { ...m.blur!, style: e.target.value === "blur" ? undefined : (e.target.value as Blur["style"]) } })} + data-post-bench-censor-style={i} + > + <option value="blur">blurred</option> + <option value="black">black</option> + <option value="pixelate">pixelated</option> + </select> + band + <select + value={bandAcross(m.blur.band)} + onChange={(e) => setMedia(i, { blur: { ...m.blur!, band: withAcross(m.blur!.band, e.target.value) } })} + data-post-bench-censor-band={i} + > + <option value="none">none</option> + <option value="below">below a line</option> + <option value="above">above a line</option> + <option value="between">between two lines</option> + </select> + <select + value={typeof m.blur.band?.left === "number" ? "left" : typeof m.blur.band?.right === "number" ? "right" : "all"} + onChange={(e) => setMedia(i, { blur: { ...m.blur!, band: withUpright(m.blur!.band, e.target.value) } })} + data-post-bench-censor-side={i} + aria-label="the band's side" + > + <option value="all">the whole width</option> + <option value="left">left of a line</option> + <option value="right">right of a line</option> + </select> + </div> <BlurBoxPad project={project} media={m} @@ -549,6 +598,8 @@ export default function PostBench({ at={timed ? (srcNow ?? m.start ?? 0) : 0} boxes={m.blur.boxes ?? []} onChange={(boxes) => setMedia(i, { blur: { ...m.blur!, boxes: boxes.length ? boxes : undefined } })} + band={m.blur.band ?? null} + onBand={(band) => setMedia(i, { blur: { ...m.blur!, band } })} /> </> )} diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item"; import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration"; import { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow"; -import { blurCqw, blurOf } from "umtool-report-to-video/post-censor"; +import { blurCqw, blurOf, labelBoxOf, pixelGrid } from "umtool-report-to-video/post-censor"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom"; // --------------------------------------------------------------------------- @@ -183,6 +183,53 @@ function mixGraph(el: HTMLMediaElement, lowpassHz: number) { } } +type Censor = { strength: number; boxes: number[][]; band: number[] | null; label: string | null; style: "blur" | "black" | "pixelate" }; + +/** + * A PIXELATED region, live (post-censor.mjs `style: "pixelate"`): the element's + * pixels drawn coarse on a canvas over it -- each region (or the whole frame) + * read at the render's grid of blocks and scaled back up without smoothing -- + * redrawn every frame, so a playing video stays censored. + */ +function PixelLayer({ source, crop, censor }: { source: React.RefObject<HTMLVideoElement | HTMLImageElement | null>; crop: number[] | null; censor: Censor }) { + const canvas = useRef<HTMLCanvasElement | null>(null); + const key = JSON.stringify([crop, censor.boxes, censor.strength]); + useEffect(() => { + let raf = 0; + const tiny = document.createElement("canvas"); + const draw = () => { + const c = canvas.current; + const el = source.current; + raf = requestAnimationFrame(draw); + if (!c || !el) return; + const W = Math.max(1, Math.round(c.clientWidth)); + const H = Math.max(1, Math.round(c.clientHeight)); + if (c.width !== W || c.height !== H) [c.width, c.height] = [W, H]; + const sw = el instanceof HTMLVideoElement ? el.videoWidth : el.naturalWidth; + const sh = el instanceof HTMLVideoElement ? el.videoHeight : el.naturalHeight; + const ctx = c.getContext("2d"); + if (!ctx || !sw || !sh) return; + ctx.clearRect(0, 0, W, H); + const cr = crop ?? [0, 0, 1, 1]; + for (const r of censor.boxes.length ? censor.boxes : [[0, 0, 1, 1]]) { + const [nx, ny] = pixelGrid(censor.strength, r[2], r[3], W, H); + [tiny.width, tiny.height] = [nx, ny]; + const t = tiny.getContext("2d"); + if (!t) continue; + t.imageSmoothingEnabled = true; + // The region of the picture as shown (after its crop), in the source's pixels. + t.drawImage(el, (cr[0] + r[0] * cr[2]) * sw, (cr[1] + r[1] * cr[3]) * sh, r[2] * cr[2] * sw, r[3] * cr[3] * sh, 0, 0, nx, ny); + ctx.imageSmoothingEnabled = false; + ctx.drawImage(tiny, 0, 0, nx, ny, r[0] * W, r[1] * H, r[2] * W, r[3] * H); + } + }; + raf = requestAnimationFrame(draw); + return () => cancelAnimationFrame(raf); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key, source]); + return <canvas ref={canvas} data-post-pixelated="" className="pointer-events-none absolute inset-0 h-full w-full" />; +} + function MediaEl({ project, m, box, b, step, s, playing, inStep, mix = null, speed = 1, }: { @@ -200,6 +247,7 @@ function MediaEl({ speed?: number; }) { const ref = useRef<HTMLVideoElement | null>(null); + const img = useRef<HTMLImageElement | null>(null); // The muffle follows the clock: the gains set from the item's second, as the render's expressions are. const muffled = !!mix && mix.duck && step.sound; useEffect(() => { @@ -235,14 +283,19 @@ function MediaEl({ if (!run && !v.paused) v.pause(); }, [target, run, speed]); const progress = inStep ? Math.min(1, Math.max(0, (s - step.at) / Math.max(0.1, step.seconds))) : 0; - // CENSORED (post-censor.mjs): the whole frame blurred, or its boxes -- as the render blurs it. - const blur = blurOf(m) as { strength: number; boxes: number[][]; label: string | null } | null; - const blurCss = blur ? `blur(${blurCqw(blur.strength)}cqw)` : undefined; + // CENSORED (post-censor.mjs): the whole frame, or its regions (its boxes, its band) -- blurred, black or + // pixelated, as the render draws them. + const blur = blurOf(m) as Censor | null; + const blurCss = blur && blur.style === "blur" ? `blur(${blurCqw(blur.strength)}cqw)` : undefined; + const wholeBlur = blur && blur.style === "blur" && !blur.boxes.length ? blurCss : undefined; + const at = blur ? labelBoxOf(blur) : null; return ( <div data-post-media={m.i} data-post-media-kind={m.kind} - data-post-blurred={blur ? (blur.boxes.length ? "boxes" : "frame") : undefined} + data-post-blurred={blur ? (blur.boxes.length ? (blur.band ? "band" : "boxes") : "frame") : undefined} + data-post-censor-style={blur ? blur.style : undefined} + data-post-censor-band={blur?.band ? blur.band.join(",") : undefined} className="absolute overflow-hidden" style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height), containerType: blur ? "size" : undefined }} > @@ -257,18 +310,23 @@ function MediaEl({ playsInline loop={step.loop} muted={!(step.sound && run)} - style={{ ...inner, objectFit: "fill", filter: blur && !blur.boxes.length ? blurCss : undefined }} + style={{ ...inner, objectFit: "fill", filter: wholeBlur }} /> ) : ( // eslint-disable-next-line @next/next/no-img-element <img + ref={img} src={postFileUrl(project, String(m.src))} alt="" data-post-image={m.i} - style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center", filter: blur && !blur.boxes.length ? blurCss : undefined }} + style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center", filter: wholeBlur }} /> )} - {blur?.boxes.map((bx, j) => ( + {blur?.style === "pixelate" && <PixelLayer source={timed ? ref : img} crop={crop} censor={blur} />} + {blur?.style === "black" && (blur.boxes.length ? blur.boxes : [[0, 0, 1, 1]]).map((bx, j) => ( + <div key={j} data-post-blur-box={j} className="pointer-events-none absolute bg-black" style={{ left: `${bx[0] * 100}%`, top: `${bx[1] * 100}%`, width: `${bx[2] * 100}%`, height: `${bx[3] * 100}%` }} /> + ))} + {blur?.style === "blur" && blur.boxes.map((bx, j) => ( <div key={j} data-post-blur-box={j} @@ -276,8 +334,12 @@ function MediaEl({ style={{ left: `${bx[0] * 100}%`, top: `${bx[1] * 100}%`, width: `${bx[2] * 100}%`, height: `${bx[3] * 100}%`, backdropFilter: blurCss, WebkitBackdropFilter: blurCss }} /> ))} - {blur?.label && ( - <span data-post-blur-label="" className="pointer-events-none absolute left-[2%] top-[2%] rounded-[3px] bg-black/70 px-[1.2cqw] py-[0.4cqw] text-[2.4cqw] leading-none text-white"> + {blur?.label && at && ( + <span + data-post-blur-label="" + className="pointer-events-none absolute rounded-[3px] bg-black/70 px-[1.2cqw] py-[0.4cqw] text-[2.4cqw] leading-none text-white" + style={{ left: `calc(${at[0] * 100}% + 2cqw)`, top: `calc(${at[1] * 100}% + 2cqh)` }} + > {blur.label} </span> )} diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -653,6 +653,7 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused | `media[i].crop` — `[x, y, w, h]`, fractions of the picture: what of it is shown | post bench, **crop** (none, centre 80%, top half, bottom half) | `media.0.crop=0,0.1,1,0.8` (`=off`) | same | | `media[i].push` — an image's slow push-in (6% over its span) | post bench, **slow push-in** | `media.0.push=on` | same | | `media[i].blur` — the attachment CENSORED (`post-censor.mjs`): `{on, strength?: 1–10 (7), boxes?: [[x, y, w, h], …], label?: "…" \| false}`. The render blurs it for real (ffmpeg `gblur`, its sigma grown with the strength and the picture's width) -- the whole frame, or only its boxes (fractions of the picture as shown, after its crop, held still over the clip) -- and draws the label ("Censored"; `false`: none) at its corner. The file is never touched; `on: false` keeps the settings. A channel's `posts-markup.json` may censor it for every project (`censor`, below); the item's own `blur` wins | post bench, **censor it**, **strength**, **label** / **no label**, the boxes drawn on a still frame (drag; × removes; **Whole frame**); Play and the bench preview it | `media.0.blur=on` · `media.0.blur.strength=5` · `media.0.blur.label="Censored"` (`=off`: none) · `media.0.blur.boxes=0.2,0.3,0.4,0.4;…` (`=off`) · `media.0.blur=off` | same, `patch: {media: {"0": {blur: {on, strength, boxes, label}}}}` (merged; a null key cleared) | +| `media[i].blur.band` — a BAND censored across the attachment (operator, 4 Nov: "censor everything neck down"): `{below: f}` everything under a line `f` of the way down, `{above: f}`, `{between: [a, b]}`; with, or instead, `{left: f}` / `{right: f}` one side of an upright line (both: where they meet). Fractions of the picture as shown (after its crop). One more region beside the boxes (none of either: the whole frame); the label sits at its corner. `media[i].blur.style` — how every region is censored: `blur` (default; its strength), `black` (a solid fill), `pixelate` (blocks of 0.8% of the width per step of strength: 18 across at 7). A PRESENTATION choice: it stays on in the uncensored cut, like the rest of the censor | post bench, **censor it**: **style** (blurred / black / pixelated), **band** (none / below a line / above a line / between two lines) and its side (the whole width / left / right of a line); the band's line(s) drawn on the still frame, **dragged** to where it starts (its % beside it); Play and the bench preview it (a pixelated region drawn coarse on a canvas, live) | `media.0.censor=below:0.38` (the censor on, the band set; the strength and label kept) · `media.0.censor=below:0.38:pixelate:8` · `media.0.censor=between:0.2,0.6:black` · `media.0.censor=below:0.4:left:0.5` · `media.0.censor=off` (off, band and style cleared) · the long forms `media.0.blur.band=above:0.3` (`=off`) and `media.0.blur.style=black` (`=off`: blur) | same, `patch: {media: {"0": {blur: {on, band: {below}, style}}}}` (a null `band` or `style` cleared) | | `media[i].words` — a video's transcript (`{cues: [{start, end, text}]}` beside it), its words shown under it in Play and the render | post bench, **Transcribe its words (the editor)**: the editor's `transcribe` op on the file (a job on a local worker), set when it is done | `pnpm ops transcribe --json '{"path": "<project>/posts-media/…_1.mp4", "words": true, "out": "<project>/posts-media/…_1.words.json"}'`, then set `words` by the bench | `POST {op: "transcribe", id, media}` → `{jobId}` · `GET ?project&id&media&job=` | | | In umtool | From a terminal | Route | diff --git a/umtool/lib/report/postThread.test.mjs b/umtool/lib/report/postThread.test.mjs @@ -99,3 +99,13 @@ test("the cut's thread knobs (posts narrate --cut thread.*), and the import stor const got = (await manifest(p)).timeline[0].narration.takes[0].parts; assert.deepEqual(got.map((x) => [x.role, x.voice]), [["parent:0", "leo"], ["parent:0", "leo"], ["post", "zac"]]); }); + +test("set-item's censor knobs: a band in one knob, its edge, its style; off clears them", () => { + assert.deepEqual(postItemPatchOf(["media.0.censor=below:0.38:blur"]).media, { 0: { blur: { on: true, band: { below: 0.38 }, style: "blur" } } }); + assert.deepEqual(postItemPatchOf(["media.1.censor=between:0.2,0.6:pixelate:8"]).media, { 1: { blur: { on: true, band: { between: [0.2, 0.6] }, style: "pixelate", strength: 8 } } }); + assert.deepEqual(postItemPatchOf(["media.0.censor=off"]).media, { 0: { blur: { on: false, band: null, style: null } } }); + assert.deepEqual(postItemPatchOf(["media.0.blur.band=above:0.3:left:0.5", "media.0.blur.style=black"]).media, { 0: { blur: { band: { above: 0.3, left: 0.5 }, style: "black" } } }); + assert.deepEqual(postItemPatchOf(["media.0.blur.band=off", "media.0.blur.style=off"]).media, { 0: { blur: { band: null, style: null } } }); + assert.throws(() => postItemPatchOf(["media.0.censor=below"]), /takes a fraction/); + assert.throws(() => postItemPatchOf(["media.0.blur.style=below:0.3"]), /blur, black or pixelate/); +}); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -35,6 +35,7 @@ import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { PostsRefused, StaleToken, StructureRefused, addArchiveAvatars, manifestToken, setPostAvatar, updatePostItem, updatePostRedact, updatePosts, upsertPost } from "./manifest.mjs"; import { postWarnings } from "./postCards.mjs"; +import { censorSpecOf } from "umtool-report-to-video/post-censor"; // `umtool posts roles` (postThreadCli.mjs ROLES_USAGE): its lines, kept here so the usage is one block. const ROLES_LINES = [ @@ -79,7 +80,8 @@ export const POSTS_USAGE = [ " [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]", " [media.<i>.push=on|off] [media.<i>.trim=off] [quoted.paraphrase=\"…\"|off]", " [media.<i>.blur=on|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"|off]", - " [media.<i>.blur.boxes=x,y,w,h;…|off]", + " [media.<i>.blur.boxes=x,y,w,h;…|off] [media.<i>.blur.band=below:<f>|above:<f>|between:<a>,<b>[:left:<f>|:right:<f>]|off]", + " [media.<i>.blur.style=blur|black|pixelate|off] [media.<i>.censor=<edge>:<f>[:<style>][:<strength>]|off]", " [parent.<i>.paraphrase=\"…\"|off] [narration.rate=0.8–1.5|narration.<mix knob>=…] [--json]", " a post item's knobs (the post bench's writer, updatePostItem): its hold, its images' grid, the blur of other authors,", " an attachment's trim, sound, crop (fractions of its picture) and push-in; fit=read[:linger] (a narrated post: its", @@ -89,6 +91,9 @@ export const POSTS_USAGE = [ " media.<i>.blur=on: the attachment CENSORED in the render -- a real blur (strength 1-10, default 7) of the whole", " frame, or of its boxes (fractions of the picture as shown: x,y,w,h;…), labelled \"Censored\" (label=… or off);", " its file is never touched. Play and the bench preview it; the bench draws boxes on a paused frame.", + " media.<i>.censor=below:0.38[:blur|black|pixelate][:<strength>]: a BAND -- everything below a line across the picture", + " (above:<f>, between:<a>,<b>; :left:<f> / :right:<f> narrows it to one side of an upright line) censored in a style;", + " the blur on, the rest of its settings kept; off turns it off. Stays on in an uncensored cut (a presentation choice).", " thread.*: a THREAD READ (post-thread.mjs) -- a narrated item that reads the post it answers or quotes is drawn as", " the conversation, each post read shown in full and shrunk/dimmed as the next comes in: what each context post is", " on screen (auto: full when read, carried in when it is the item before, else context), the shrink, dim and their", @@ -658,18 +663,37 @@ export function postItemPatchOf(pairs) { } else if (k === "quoted.paraphrase") out.quoted = { paraphrase: paraphraseOf(raw) }; else if (/^parents?\.\d+\.paraphrase$/.test(k)) (out.parents ??= {})[k.split(".")[1]] = { paraphrase: paraphraseOf(raw) }; - else if (/^media\.\d+\.blur(\.(strength|label|boxes))?$/.test(k)) { - // The censoring blur (post-censor.mjs): on|off, its strength, its label (off: none), its boxes (x,y,w,h;…|off). - const [, i, , sub] = /^media\.(\d+)\.blur(\.(strength|label|boxes))?$/.exec(k) ?? []; + else if (/^media\.\d+\.blur(\.(strength|label|boxes|band|style))?$/.test(k)) { + // The censoring blur (post-censor.mjs): on|off, its strength, its label (off: none), its boxes (x,y,w,h;…|off), + // its band (below:0.38, between:0.2,0.6, left:0.5 … |off), its style (blur|black|pixelate|off: blur). + const [, i, , sub] = /^media\.(\d+)\.blur(\.(strength|label|boxes|band|style))?$/.exec(k) ?? []; const blur = (((out.media ??= {})[i] ??= {}).blur ??= {}); if (!sub) blur.on = onOff(v, k); else if (sub === "strength") blur.strength = OFF.has(v) || v === "" ? null : Number(raw); else if (sub === "label") blur.label = v === "off" ? false : raw.trim() === "" ? null : raw; - else blur.boxes = OFF.has(v) || v === "" ? null : raw.split(";").map((b) => b.split(",").map(Number)); + else if (sub === "band" || sub === "style") { + if (OFF.has(v) || v === "") blur[sub] = null; + else { + const c = censorSpecOf(raw); + if (c.error || (sub === "band" && !c.band) || (sub === "style" && !c.style) || Object.keys(c).length !== 1) throw new CliError(`${k}= takes ${sub === "band" ? "an edge and its place (below:0.38, above:0.2, between:0.2,0.6, left:0.5, right:0.5)" : "blur, black or pixelate"}${c.error ? ` -- ${c.error}` : ""}`); + blur[sub] = c[sub]; + } + } else blur.boxes = OFF.has(v) || v === "" ? null : raw.split(";").map((b) => b.split(",").map(Number)); if (typeof blur.strength === "number" && !Number.isFinite(blur.strength)) throw new CliError(`${k}= takes a number (1-10)`); + } else if (/^media\.\d+\.censor$/.test(k)) { + // A BAND CENSOR in one knob (post-censor.mjs censorSpecOf): the blur on, its band, its style, its strength -- + // `off`: the censor off and its band and style cleared. + const i = k.split(".")[1]; + const blur = (((out.media ??= {})[i] ??= {}).blur ??= {}); + if (OFF.has(v)) Object.assign(blur, { on: false, band: null, style: null }); + else { + const c = censorSpecOf(raw); + if (c.error) throw new CliError(`${k}=: ${c.error}`); + Object.assign(blur, { on: true, ...c }); + } } else { const m = /^media\.(\d+)\.(start|end|mute|crop|push|trim)$/.exec(k); - if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, follow=, follow.dim|ease=, thread=, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan=, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes]=, quoted.paraphrase=, parent.<i>.paraphrase=)`); + if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, follow=, follow.dim|ease=, thread=, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan=, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes|.band|.style]=, media.<i>.censor=, quoted.paraphrase=, parent.<i>.paraphrase=)`); const media = (out.media ??= {}); const one = (media[m[1]] ??= {}); if (m[2] === "start" || m[2] === "end") one[m[2]] = OFF.has(v) || v === "" ? null : Number(raw); diff --git a/umtool/report-to-video/post-censor.mjs b/umtool/report-to-video/post-censor.mjs @@ -3,7 +3,8 @@ // played BLURRED -- the whole frame, or only some regions of it -- with a // small label saying so. umtool/docs/knobs.md, "A post item". // -// media[i].blur = { on: true, strength?: 1–10 (7), boxes?: [[x, y, w, h], …], label?: "…" | false } +// media[i].blur = { on: true, strength?: 1–10 (7), boxes?: [[x, y, w, h], …], label?: "…" | false, +// band?: { below?|above?|between?: [a, b], left?|right? }, style?: "blur"|"black"|"pixelate" } // // `boxes` are fractions of the picture AS SHOWN (after its crop), held still // over the clip; none blurs the whole frame. `label` is the caption drawn on @@ -11,33 +12,118 @@ // one of its attachments for every project (posts-markup.json's `censor`, // post-redact.mjs); the item's own `blur` wins. // +// A BAND (operator, 4 Nov: "I'd also like to be able to censor across a line +// dividing the image e.g. censor everything neck down"): the region across the +// picture on one side of a line -- `below: 0.38` everything under 38% of its +// height, `above`, `between: [a, b]` -- and, optionally, on one side of an +// upright line (`left: 0.5` everything left of the middle, `right`); both: +// where they meet. It is one more region beside the boxes (none of either: +// the whole frame), and the label sits at its corner. `style` is how a region +// is censored: `blur` (the default, its `strength`), `black` (a solid fill) or +// `pixelate` (blocks, coarser with the strength). +// +// A PRESENTATION choice, like the rest of the censor: it stays ON in an +// uncensored cut (post-slurs.mjs toggles the slurs only). +// // NOTHING IS REWRITTEN: the attachment's file stays as it was captured. The // blur is a real one (ffmpeg gblur, sigma grown with the strength and the // picture's size), drawn where public output is made -- the render. Play and -// the post bench preview it (a CSS blur, the boxes as backdrop blurs). +// the post bench preview it (a CSS blur, the boxes as backdrop blurs; a black +// fill; the pixels drawn coarse on a canvas). // // PURE and dependency-free. -export const POST_BLUR_DEFAULTS = Object.freeze({ strength: 7, label: "Censored" }); +export const POST_BLUR_DEFAULTS = Object.freeze({ strength: 7, label: "Censored", style: "blur" }); export const POST_BLUR_BOXES_MAX = 8; +/** How a censored region is drawn. */ +export const POST_BLUR_STYLES = Object.freeze(["blur", "black", "pixelate"]); +/** A band's edges: one across (below, above, between) and, optionally, one upright (left, right). */ +export const POST_BAND_ACROSS = Object.freeze(["below", "above", "between"]); +export const POST_BAND_UPRIGHT = Object.freeze(["left", "right"]); +const BLUR_KEYS = ["on", "strength", "boxes", "label", "band", "style"]; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const r3 = (v) => Math.round(v * 1000) / 1000; +const r4 = (v) => Math.round(v * 10000) / 10000; /** Is attachment `m` blurred? */ export const blurOn = (m) => isObj(m?.blur) && m.blur.on === true; -/** Its blur with the defaults filled: `{ strength, boxes, label }` (label null: none), or null when it is not blurred. */ +/** + * THE BAND's BOX, pure: `[x, y, w, h]` as fractions of the picture as shown, + * or null when `band` names no edge (or the region is empty). `below: a` is + * y from a to the foot, `above: a` from the top to a, `between: [a, b]` a to + * b; `left: a` x from 0 to a, `right: a` from a to the right edge. + */ +export function bandBox(band) { + if (!isObj(band)) return null; + let y0 = 0, y1 = 1, x0 = 0, x1 = 1; + let any = false; + if (fin(band.below)) [y0, any] = [band.below, true]; + else if (fin(band.above)) [y1, any] = [band.above, true]; + else if (Array.isArray(band.between) && band.between.length === 2 && band.between.every(fin)) { + y0 = Math.min(...band.between); + y1 = Math.max(...band.between); + any = true; + } + if (fin(band.left)) [x1, any] = [band.left, true]; + else if (fin(band.right)) [x0, any] = [band.right, true]; + const c = (v) => Math.min(1, Math.max(0, v)); + [x0, x1, y0, y1] = [c(x0), c(x1), c(y0), c(y1)]; + if (!any || x1 - x0 < 0.01 || y1 - y0 < 0.01) return null; + return [r4(x0), r4(y0), r4(x1 - x0), r4(y1 - y0)]; +} + +/** Every reason a band is refused. */ +export function bandErrors(band, where) { + if (band === undefined) return []; + if (!isObj(band)) return [`${where} must be {below?|above?|between?, left?|right?} (fractions of the picture)`]; + const errors = []; + for (const k of Object.keys(band)) if (![...POST_BAND_ACROSS, ...POST_BAND_UPRIGHT].includes(k)) errors.push(`${where}.${k} is not a band edge (${[...POST_BAND_ACROSS, ...POST_BAND_UPRIGHT].join(", ")})`); + const across = POST_BAND_ACROSS.filter((k) => band[k] !== undefined); + const upright = POST_BAND_UPRIGHT.filter((k) => band[k] !== undefined); + if (across.length > 1) errors.push(`${where}: one of ${POST_BAND_ACROSS.join(", ")} (not ${across.join(" and ")})`); + if (upright.length > 1) errors.push(`${where}: one of left, right (not both)`); + if (!across.length && !upright.length) errors.push(`${where} names no edge (below, above, between, left or right)`); + const frac = (v) => fin(v) && v > 0 && v < 1; + for (const k of ["below", "above", "left", "right"]) if (band[k] !== undefined && !frac(band[k])) errors.push(`${where}.${k} must be a fraction of the picture, between 0 and 1 (0.38: 38% of the way ${k === "left" || k === "right" ? "across" : "down"})`); + if (band.between !== undefined) { + const b = band.between; + if (!(Array.isArray(b) && b.length === 2 && b.every(frac) && b[1] - b[0] >= 0.01)) errors.push(`${where}.between must be [a, b], fractions of the picture's height with a < b`); + } + if (!errors.length && !bandBox(band)) errors.push(`${where} leaves no picture to censor`); + return errors; +} + +/** + * Its blur with the defaults filled: `{ strength, boxes, band, label, style }` + * (label null: none; `band` the band's box, also the LAST of `boxes` -- the + * regions drawn; none of either: the whole frame), or null when it is not + * blurred. + */ export function blurOf(m) { if (!blurOn(m)) return null; const b = m.blur; + const band = bandBox(b.band); + const boxes = Array.isArray(b.boxes) ? b.boxes.filter((x) => Array.isArray(x) && x.length === 4) : []; return { strength: fin(b.strength) ? Math.min(10, Math.max(1, b.strength)) : POST_BLUR_DEFAULTS.strength, - boxes: Array.isArray(b.boxes) ? b.boxes.filter((x) => Array.isArray(x) && x.length === 4) : [], + boxes: band ? [...boxes, band] : boxes, + band, label: b.label === false ? null : typeof b.label === "string" && b.label.trim() ? b.label.trim() : POST_BLUR_DEFAULTS.label, + style: POST_BLUR_STYLES.includes(b.style) ? b.style : POST_BLUR_DEFAULTS.style, }; } +/** Where the label sits, as fractions of the picture: the band's corner, else the picture's. */ +export const labelBoxOf = (bl) => bl?.band ?? [0, 0, 1, 1]; + +/** A pixelated region's blocks `[across, down]`: a block is 0.8% of the picture's width per step of strength (at 7, 5.6%). */ +export function pixelGrid(strength, rw, rh, width, height) { + const block = Math.max(0.005, strength * 0.008); + return [Math.max(1, Math.round(rw / block)), Math.max(1, Math.round((rh * (height / Math.max(1, width))) / block))]; +} + /** The blur's sigma on a picture `width` px wide: 0.4% of the width per step of strength (at 7, ~2.8%). */ export const blurSigma = (strength, width) => Math.max(2, Math.round(width * strength * 0.004 * 10) / 10); /** The same as a share of the width, for a preview (CSS `cqw`). */ @@ -50,9 +136,9 @@ export const boxOk = (b) => /** Every reason `media[i].blur` is refused. */ export function blurErrors(blur, where) { if (blur === undefined) return []; - if (!isObj(blur)) return [`${where} must be {on, strength?, boxes?, label?}`]; + if (!isObj(blur)) return [`${where} must be {on, strength?, boxes?, label?, band?, style?}`]; const errors = []; - for (const k of Object.keys(blur)) if (!["on", "strength", "boxes", "label"].includes(k)) errors.push(`${where}.${k} is not a blur knob (on, strength, boxes, label)`); + for (const k of Object.keys(blur)) if (!BLUR_KEYS.includes(k)) errors.push(`${where}.${k} is not a blur knob (${BLUR_KEYS.join(", ")})`); if (typeof blur.on !== "boolean") errors.push(`${where}.on must be true or false`); if (blur.strength !== undefined && !(fin(blur.strength) && blur.strength >= 1 && blur.strength <= 10)) errors.push(`${where}.strength must be 1–10`); if (blur.boxes !== undefined) { @@ -60,6 +146,8 @@ export function blurErrors(blur, where) { else blur.boxes.forEach((b, j) => !boxOk(b) && errors.push(`${where}.boxes[${j}] must be [x, y, w, h] as fractions of the picture (each 0–1, inside it)`)); } if (blur.label !== undefined && blur.label !== false && !(typeof blur.label === "string" && blur.label.length <= 40)) errors.push(`${where}.label must be words (at most 40 characters) or false`); + errors.push(...bandErrors(blur.band, `${where}.band`)); + if (blur.style !== undefined && !POST_BLUR_STYLES.includes(blur.style)) errors.push(`${where}.style must be one of ${POST_BLUR_STYLES.join(", ")}`); return errors; } @@ -67,27 +155,46 @@ export function blurErrors(blur, where) { const dtText = (s) => String(s).replace(/\\/g, "\\\\").replace(/'/g, "\u2019").replace(/:/g, "\\:").replace(/%/g, "\\%"); /** - * The filters that blur attachment `m`, drawn `w` × `h` px: `[inLabel]` → - * `[outLabel]`. The whole frame, or each box: split, cropped, blurred and laid - * back over. A label is drawn by labelFilter, on the composed frame. + * The filters that censor attachment `m`, drawn `w` × `h` px: `[inLabel]` → + * `[outLabel]`. The whole frame, or each region (its boxes, its band) in its + * style: blurred (split, cropped, blurred and laid back over), black (a filled + * box) or pixelated (cropped, scaled down and back up without smoothing). A + * label is drawn by labelFilter, on the composed frame. */ export function blurFilters(inLabel, outLabel, m, { width, height }) { const b = blurOf(m); if (!b) return [`[${inLabel}]null[${outLabel}]`]; const sigma = blurSigma(b.strength, width); - if (!b.boxes.length) return [`[${inLabel}]gblur=sigma=${sigma}:steps=3[${outLabel}]`]; + const regions = b.boxes.length ? b.boxes : [[0, 0, 1, 1]]; + const px = (box) => { + const x = Math.round(box[0] * width); + const y = Math.round(box[1] * height); + return { x, y, w: Math.max(2, Math.min(width - x, Math.round(box[2] * width))), h: Math.max(2, Math.min(height - y, Math.round(box[3] * height))) }; + }; + if (b.style === "black") { + const fills = regions.map((box) => { + const r = px(box); + return `drawbox=x=${r.x}:y=${r.y}:w=${r.w}:h=${r.h}:color=black@1:t=fill`; + }); + return [`[${inLabel}]${fills.join(",")}[${outLabel}]`]; + } + const fx = (box, r) => { + if (b.style === "pixelate") { + const [nx, ny] = pixelGrid(b.strength, box[2], box[3], width, height); + return `scale=${nx}:${ny}:flags=neighbor,scale=${r.w}:${r.h}:flags=neighbor`; + } + return `gblur=sigma=${sigma}:steps=3`; + }; + if (!b.boxes.length) return [`[${inLabel}]${fx([0, 0, 1, 1], { w: width, h: height })}[${outLabel}]`]; const out = []; let cur = inLabel; b.boxes.forEach((box, j) => { - const x = Math.round(box[0] * width); - const y = Math.round(box[1] * height); - const w = Math.max(2, Math.min(width - x, Math.round(box[2] * width))); - const h = Math.max(2, Math.min(height - y, Math.round(box[3] * height))); + const r = px(box); const base = `${outLabel}_k${j}`; out.push(`[${cur}]split[${base}a][${base}b]`); - out.push(`[${base}b]crop=${w}:${h}:${x}:${y},gblur=sigma=${sigma}:steps=3[${base}c]`); + out.push(`[${base}b]crop=${r.w}:${r.h}:${r.x}:${r.y},${fx(box, r)}[${base}c]`); const next = j === b.boxes.length - 1 ? outLabel : `${base}o`; - out.push(`[${base}a][${base}c]overlay=x=${x}:y=${y}[${next}]`); + out.push(`[${base}a][${base}c]overlay=x=${r.x}:y=${r.y}[${next}]`); cur = next; }); return out; @@ -95,17 +202,21 @@ export function blurFilters(inLabel, outLabel, m, { width, height }) { /** * The label's drawtext on the frame `[inLabel]` → `[outLabel]`: the words at - * the attachment's top-left corner (its box `b` on the frame) while it is up, - * or null when it has none (or there is no face to draw it in). + * the censored region's top-left corner -- the band's, else the + * attachment's (its box `b` on the frame) -- while it is up, or null when it + * has none (or there is no face to draw it in). */ export function labelFilter(inLabel, outLabel, m, b, { from, to, fontfile, scale = 1 }) { const bl = blurOf(m); if (!bl?.label || !fontfile) return null; const size = Math.max(12, Math.round(26 * scale)); const pad = Math.round(size * 0.5); + const at = labelBoxOf(bl); + const x = Math.round(b.x + at[0] * b.width) + pad; + const y = Math.round(b.y + at[1] * b.height) + pad; return ( `[${inLabel}]drawtext=fontfile='${fontfile}':text='${dtText(bl.label)}':fontsize=${size}:fontcolor=white:box=1:boxcolor=black@0.7:boxborderw=${Math.round(size * 0.35)}:` + - `x=${b.x + pad}:y=${b.y + pad}:enable='between(t,${r3(from)},${r3(to)})'[${outLabel}]` + `x=${x}:y=${y}:enable='between(t,${r3(from)},${r3(to)})'[${outLabel}]` ); } @@ -142,3 +253,41 @@ export function censorEntry(entry, red) { }); return changed ? { ...entry, media } : entry; } + +/** + * A CENSOR in the knob's words (`umtool posts set-item … media.<i>.censor=`): + * colon-separated parts -- an edge and its place (`below:0.38`, `above:0.2`, + * `between:0.2,0.6`, `left:0.5`, `right:0.5`), a style (`blur`, `black`, + * `pixelate`) and a strength (1–10) -- as `{ band?, style?, strength? }`, or + * `{ error }`. `below:0.38:blur`, `below:0.4:left:0.5:pixelate:8`. + */ +export function censorSpecOf(text) { + const parts = String(text ?? "").trim().split(":").map((x) => x.trim()).filter(Boolean); + if (!parts.length) return { error: "a censor is <edge>:<fraction>[:<style>][:<strength>] (below:0.38:blur)" }; + const out = {}; + const band = {}; + for (let k = 0; k < parts.length; k += 1) { + const p = parts[k].toLowerCase(); + if ([...POST_BAND_ACROSS, ...POST_BAND_UPRIGHT].includes(p)) { + const v = parts[k + 1]; + k += 1; + if (v === undefined) return { error: `${p} takes a fraction of the picture (${p}:${p === "between" ? "0.2,0.6" : "0.38"})` }; + band[p] = p === "between" ? v.split(",").map(Number) : Number(v); + } else if (POST_BLUR_STYLES.includes(p)) out.style = p; + else if (/^\d+(\.\d+)?$/.test(p)) out.strength = Number(p); + else return { error: `${parts[k]}: not an edge (${[...POST_BAND_ACROSS, ...POST_BAND_UPRIGHT].join(", ")}), a style (${POST_BLUR_STYLES.join(", ")}) or a strength (1–10)` }; + } + if (Object.keys(band).length) out.band = band; + const errors = [...bandErrors(out.band, "the band"), ...(out.strength !== undefined && !(out.strength >= 1 && out.strength <= 10) ? ["the strength must be 1–10"] : [])]; + if (!out.band && !out.style && out.strength === undefined) errors.push("a censor names an edge, a style or a strength"); + return errors.length ? { error: errors.join("; ") } : out; +} + +/** A band in the knob's words (`below:0.38`, `between:0.2,0.6:left:0.5`), the inverse of censorSpecOf's band. */ +export function bandText(band) { + if (!isObj(band)) return ""; + const out = []; + for (const k of POST_BAND_ACROSS) if (band[k] !== undefined) out.push(`${k}:${Array.isArray(band[k]) ? band[k].join(",") : band[k]}`); + for (const k of POST_BAND_UPRIGHT) if (band[k] !== undefined) out.push(`${k}:${band[k]}`); + return out.join(":"); +} diff --git a/umtool/report-to-video/post-censor.test.mjs b/umtool/report-to-video/post-censor.test.mjs @@ -6,8 +6,10 @@ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { after, test } from "node:test"; -import { blurErrors, blurFilters, blurOf, blurSigma, censorEntry } from "./post-censor.mjs"; -import { postItemPlan, postLayout, validatePostItem } from "./post-item.mjs"; +import { bandBox, bandErrors, bandText, blurErrors, blurFilters, blurOf, blurSigma, censorEntry, censorSpecOf, labelFilter, pixelGrid } from "./post-censor.mjs"; +import { postItemPlan, postLayout, stepBoxes, validatePostItem } from "./post-item.mjs"; + +const stepBoxesOf = (e, layout) => stepBoxes(postItemPlan(e).steps[0], layout.slot)[0]; import { postSegmentArgs } from "./post-render.mjs"; import { validatePostsMarkup } from "./post-redact.mjs"; @@ -26,7 +28,7 @@ test("the knob: on, a strength 1-10, boxes of fractions, a label or false; valid const bad = blurErrors({ on: "yes", strength: 11, boxes: [[0.8, 0, 0.5, 0.5]], label: 3, extra: 1 }, "b"); assert.equal(bad.length, 5, bad.join("; ")); assert.ok(validatePostItem(entry({ on: true, strength: 0 })).some((e) => e.includes("media[0].blur.strength must be 1–10"))); - assert.deepEqual(blurOf({ blur: { on: true } }), { strength: 7, boxes: [], label: "Censored" }); + assert.deepEqual(blurOf({ blur: { on: true } }), { strength: 7, boxes: [], band: null, label: "Censored", style: "blur" }); assert.equal(blurOf({ blur: { on: false, strength: 3 } }), null, "off keeps its settings and blurs nothing"); }); @@ -58,6 +60,60 @@ test("a channel's markup censors an attachment in every project; the item's own assert.equal(validatePostsMarkup({ "1": { censor: [{ media: 9 }, { media: 0, blur: { strength: 30 } }] } }).length, 2); }); + +test("THE BAND's geometry: below, above, between, left and right, as a box of fractions; their meeting; nothing to censor refused", () => { + assert.deepEqual(bandBox({ below: 0.38 }), [0, 0.38, 1, 0.62]); + assert.deepEqual(bandBox({ above: 0.2 }), [0, 0, 1, 0.2]); + assert.deepEqual(bandBox({ between: [0.2, 0.6] }), [0, 0.2, 1, 0.4]); + assert.deepEqual(bandBox({ left: 0.5 }), [0, 0, 0.5, 1]); + assert.deepEqual(bandBox({ right: 0.75 }), [0.75, 0, 0.25, 1]); + assert.deepEqual(bandBox({ below: 0.4, left: 0.5 }), [0, 0.4, 0.5, 0.6], "both: where they meet (the bottom-left)"); + assert.equal(bandBox({}), null); + assert.equal(bandBox({ below: 0.999 }), null, "a sliver is no band"); + assert.deepEqual(bandErrors({ below: 0.38 }, "b"), []); + assert.equal(bandErrors({ below: 0.3, above: 0.6 }, "b").length, 1, "one edge across"); + assert.ok(bandErrors({ below: 1.2 }, "b").some((e) => e.includes("fraction of the picture"))); + assert.ok(bandErrors({ between: [0.6, 0.2] }, "b").some((e) => e.includes("a < b"))); + assert.ok(bandErrors({ top: 0.2 }, "b").some((e) => e.includes("not a band edge"))); + assert.ok(bandErrors({}, "b").some((e) => e.includes("names no edge"))); + // On the item: validated with it; the band is a region beside the boxes, the label at its corner. + assert.deepEqual(blurErrors({ on: true, strength: 9, band: { below: 0.38 }, style: "pixelate" }, "b"), []); + assert.ok(blurErrors({ on: true, style: "smudge" }, "b").some((e) => e.includes("style must be one of blur, black, pixelate"))); + assert.ok(validatePostItem(entry({ on: true, band: { below: 2 } })).some((e) => e.includes("media[0].blur.band.below"))); + const bl = blurOf({ blur: { on: true, strength: 9, boxes: [[0.1, 0.1, 0.2, 0.2]], band: { below: 0.38 } } }); + assert.deepEqual(bl, { strength: 9, boxes: [[0.1, 0.1, 0.2, 0.2], [0, 0.38, 1, 0.62]], band: [0, 0.38, 1, 0.62], label: "Censored", style: "blur" }); + assert.deepEqual(pixelGrid(7, 1, 1, 500, 280), [18, 10]); +}); + +test("the censor in the knob's words: an edge and its place, a style, a strength", () => { + assert.deepEqual(censorSpecOf("below:0.38:blur"), { band: { below: 0.38 }, style: "blur" }); + assert.deepEqual(censorSpecOf("between:0.2,0.6:black"), { band: { between: [0.2, 0.6] }, style: "black" }); + assert.deepEqual(censorSpecOf("below:0.4:left:0.5:pixelate:8"), { band: { below: 0.4, left: 0.5 }, style: "pixelate", strength: 8 }); + assert.deepEqual(censorSpecOf("pixelate"), { style: "pixelate" }); + assert.match(censorSpecOf("below").error, /takes a fraction/); + assert.match(censorSpecOf("below:0.3:smudge").error, /not an edge/); + assert.match(censorSpecOf("below:0.3:11").error, /strength must be 1–10/); + assert.equal(bandText({ between: [0.2, 0.6], left: 0.5 }), "between:0.2,0.6:left:0.5"); +}); + +test("the encode of a band: blurred, black or pixelated under the line, the label at the band's corner", () => { + const blurred = graphOf(entry({ on: true, strength: 9, band: { below: 0.5 } }), "/f/bold.ttf"); + assert.match(blurred, /\[m0_0r\]split\[m0_0_k0a\]\[m0_0_k0b\]/); + assert.equal((blurred.match(/gblur/g) ?? []).length, 1); + const black = graphOf(entry({ on: true, band: { below: 0.5 }, style: "black", label: false })); + assert.match(black, /drawbox=x=0:y=\d+:w=\d+:h=\d+:color=black@1:t=fill/); + assert.doesNotMatch(black, /gblur|split/); + const pix = graphOf(entry({ on: true, band: { above: 0.5 }, style: "pixelate" })); + assert.match(pix, /scale=\d+:\d+:flags=neighbor,scale=\d+:\d+:flags=neighbor/); + const whole = graphOf(entry({ on: true, style: "pixelate" })); + assert.match(whole, /\[m0_0r\]scale=\d+:\d+:flags=neighbor/); + // The label: at the band's top-left, not the attachment's. + const lf = labelFilter("a", "b", { blur: { on: true, band: { below: 0.5 } } }, { x: 100, y: 50, width: 400, height: 200 }, { from: 0, to: 3, fontfile: "/f.ttf" }); + assert.match(lf, /x=113:y=163:/); + const lf0 = labelFilter("a", "b", { blur: { on: true } }, { x: 100, y: 50, width: 400, height: 200 }, { from: 0, to: 3, fontfile: "/f.ttf" }); + assert.match(lf0, /x=113:y=63:/); +}); + const ROOT = mkdtempSync(path.join(tmpdir(), "post-censor-")); after(() => rmSync(ROOT, { recursive: true, force: true })); @@ -81,3 +137,26 @@ test("the encode runs: a blurred frame is smoother than the clean one (ffmpeg)", assert.ok(Number.isFinite(clean) && Number.isFinite(blurred), `${clean} ${blurred}`); assert.ok(blurred < clean * 0.6, `edges: clean ${clean}, blurred ${blurred}`); }); + +test("the encode runs: a band below the middle blurs the foot and leaves the head sharp (ffmpeg)", () => { + const src = path.join(ROOT, "vb.mp4"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=s=320x180:d=3:r=30", "-c:v", "libx264", "-pix_fmt", "yuv420p", src]); + const png = path.join(ROOT, "cardb.png"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=black:s=1440x810", "-frames:v", "1", png]); + const run = (blur, name) => { + const e = entry(blur); + const out = path.join(ROOT, `${name}.mp4`); + const layout = postLayout(e, box); + execFileSync("ffmpeg", postSegmentArgs({ entry: e, box, plan: postItemPlan(e), layout, cards: { read: png }, files: [src], render: { fps: 30 }, outPath: out, encode: ["-c:v", "libx264", "-preset", "ultrafast"] })); + return { out, b: stepBoxesOf(e, layout) }; + }; + const energy = ({ out, b }, half) => { + const y = half === "top" ? b.y : b.y + Math.floor(b.height / 2); + const r = spawnSync("ffmpeg", ["-v", "info", "-ss", "1", "-i", out, "-frames:v", "1", "-vf", `crop=${b.width}:${Math.floor(b.height / 2) - 4}:${b.x}:${y + 2},edgedetect,signalstats,metadata=print:key=lavfi.signalstats.YAVG`, "-f", "null", "-"], { encoding: "utf8" }); + return Number(/YAVG=([\d.]+)/.exec(`${r.stdout}${r.stderr}`)?.[1] ?? NaN); + }; + const clean = run(null, "clean-b"); + const band = run({ on: true, strength: 9, band: { below: 0.5 }, label: false }, "band-b"); + assert.ok(Math.abs(energy(band, "top") - energy(clean, "top")) < energy(clean, "top") * 0.15, "the head as sharp as the clean frame"); + assert.ok(energy(band, "bottom") < energy(clean, "bottom") * 0.5, `the foot blurred (${energy(band, "bottom")} vs ${energy(clean, "bottom")})`); +});