commit 29c18264a1eb90badd4e349054f805c5c6717d6c
parent e62b434936e22b5b1187147c093dd6d140875036
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 16:15:48 -0400
Merge lane/clip-blur: a clip's picture can be blurred (caption, strength, span) with an uncensored take; New clip from the clip editor and Add clip on the timeline
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# editor/CHANGELOG.md
Diffstat:
31 files changed, 1855 insertions(+), 62 deletions(-)
diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts
@@ -4,7 +4,7 @@
type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>;
type Render = Record<string, unknown> | null | undefined;
-export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide";
+export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur";
export const LOOK_KEYS: readonly LookKey[];
export const BAND_MAX: number;
export const TRANSITION_MAX: number;
@@ -19,6 +19,10 @@ export function slideOf(render: Render): Slide;
export function validateTransitionStyle(manifest: unknown): string[];
export function validateSlide(manifest: unknown): string[];
+export const RENDER_BLUR_VALUES: readonly ("on" | "off")[];
+export function renderBlurOn(render: Render): boolean;
+export function validateRenderBlur(manifest: unknown): string[];
+
export const ROOM: Readonly<{ minGap: number; maxS: number; fade: number; pad: number; detectDb: number; detectD: number }>;
export const ROOM_EDGES: readonly ("tail" | "head")[];
export const ROOM_BOUNDS: Readonly<{ minGap: readonly [number, number]; maxS: readonly [number, number] }>;
diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs
@@ -1,6 +1,6 @@
// THE LOOK'S RULES (release 38 lane E): the render keys a person sets for a
// cut with no deck -- `headerHeight`, `footerHeight`, `qr`, `transition`,
-// `transitionStyle`, `loudness`, `captions`, `room`, `slide` -- and the ONE set
+// `transitionStyle`, `loudness`, `captions`, `room`, `slide`, `blur` -- and the ONE set
// of checks every writer and reader of them runs:
//
// umtool's updateRender (lib/report/manifest.mjs: applyLookPatch, then lookErrors)
@@ -20,7 +20,7 @@ const q = (v) => JSON.stringify(v);
const round2 = (n) => Number(Number(n).toFixed(2));
/** The render keys the Look panel writes, in its order. */
-export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide"]);
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur"]);
/** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */
export const BAND_MAX = 240;
@@ -78,6 +78,26 @@ export function validateSlide(manifest) {
}
// ---------------------------------------------------------------------------
+// The blurred clips (`render.blur`) -- report-to-video/clip-blur.mjs blurs a
+// clip's picture where its `blur` asks; "off" renders every clip unblurred
+// and draws no caption: the uncensored variant, made as a take
+// (`umtool take <p> --id uncensored --set render.blur=off`).
+// ---------------------------------------------------------------------------
+
+/** `render.blur`: "on" (the default, absent) or "off". */
+export const RENDER_BLUR_VALUES = Object.freeze(["on", "off"]);
+
+/** Does this cut blur the clips that ask (`render.blur` absent or "on")? */
+export const renderBlurOn = (render) => render?.blur !== "off";
+
+/** `render.blur`: absent, "on" or "off". */
+export function validateRenderBlur(manifest) {
+ const v = manifest?.render?.blur;
+ if (v === undefined || v === null) return [];
+ return RENDER_BLUR_VALUES.includes(v) ? [] : [`render.blur must be "on" (blur the clips that ask) or "off" (the uncensored variant), not ${q(v)}`];
+}
+
+// ---------------------------------------------------------------------------
// Room at a clip's edges (`render.room`, a clip's `room`) -- report-to-video/
// room.mjs says what it does to the sound and the picture.
// ---------------------------------------------------------------------------
@@ -271,7 +291,8 @@ export function validateVertical(manifest) {
/** All of the look's keys: the build's validators and the lint call this. */
export function validateLook(manifest) {
// render.room and a clip's room (release 36 lane E) are part of the look.
- return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest)];
+ // render.blur (the uncensored variant's switch) is part of the look too.
+ return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest), ...validateRenderBlur(manifest)];
}
// ---------------------------------------------------------------------------
@@ -331,6 +352,12 @@ export function applyLookPatch(manifest, patch) {
if (typeof v !== "string" || !TRANSITION_STYLES.includes(v)) errors.push(`render.transitionStyle must be one of ${TRANSITION_STYLES.join(", ")}`);
else render.transitionStyle = v;
break;
+ case "blur":
+ // "on" is the default: written as no key at all.
+ if (v === "on") delete render.blur;
+ else if (v === "off") render.blur = "off";
+ else errors.push(`render.blur must be "on" (blur the clips that ask) or "off" (the uncensored variant)`);
+ break;
default:
// loudness, captions, room, slide: stored as given; the build's validators below say what is wrong.
render[k] = v;
diff --git a/common/lib/report/videoAssistOps.mjs b/common/lib/report/videoAssistOps.mjs
@@ -112,6 +112,8 @@ export function lookWords(key, value, render = {}) {
const edges = ["tail", "head"].filter((k) => r[k] === true);
return edges.length ? edges.join(" + ") : "off";
}
+ case "blur":
+ return value === "off" ? "uncensored (no clip blurred)" : "blurred where a clip asks";
case "slide": {
const s = { ...SLIDE_DEFAULTS, ...(isObj(value) ? value : {}) };
return `travel ${s2(s.travel)}, smear ${s2(s.blur)}, grain ${s2(s.grain)}`;
@@ -131,6 +133,7 @@ const LOOK_LABEL = Object.freeze({
captions: "speaker captions",
room: "room at the edges",
slide: "blur slide",
+ blur: "blurred clips",
});
const SLIDE_LABEL = Object.freeze({ travel: "slide travel", blur: "smear", grain: "grain" });
const ROOM_LABEL = Object.freeze({ tail: "room tail", head: "room head", maxS: "room tail up to", minGap: "room's silence gap" });
diff --git a/common/lib/report/videoAssistOps.test.ts b/common/lib/report/videoAssistOps.test.ts
@@ -26,7 +26,7 @@ test("the look's rules: one patch function — keys refused, null removes, qr on
assert.deepEqual(bad.errors, validateTransitionStyle({ render: { slide: { blur: 9 } } }));
assert.deepEqual(applyLookPatch(m, { loudness: { target: -40 } }).errors, validateLook({ render: { loudness: { target: -40 } } }));
assert.deepEqual(lookErrors(m), []);
- assert.equal(LOOK_KEYS.length, 9);
+ assert.equal(LOOK_KEYS.length, 10);
});
test("the request table: every request → the model's ops → the diff lines kept and the reasons refused", () => {
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
- **umtool's clip editor opens a clip from a whole saved recording as a short excerpt.** When the only file holding a clip was the whole recording (hours long), the editor used all of it as its view: a waveform of the whole stream with the clip a sliver in it, and a video seeking hours into a large file. It now cuts the clip and 45 seconds either side from the recording once, on the umtool machine, and works on that; the cut starts when the clip is opened and is kept for the next time. The rendered video still cuts from the whole recording.
+- **A report video can blur a clip's picture for sharing, keep an uncensored version beside it, and take a new clip from any span of a recording.** In umtool's clip editor each clip has a **Blur** box: **Blur picture** blurs that clip's footage when the video is built (the sound plays as recorded) and writes a caption on it, "Original footage uncensored, blurred here for TOS" by default and editable, with a strength and, with **From playhead** / **To playhead**, only part of the clip. The header, QR code, on-screen panel, captions and stamps are not blurred, and the live preview shows the blur as the build will draw it. The Build tab's Look panel has **Blurred clips: uncensored**, and a take made with `--set render.blur=off` renders the same cut unblurred, so a blurred cut for sharing and an uncensored take sit side by side. **New clip** in the clip editor (from a selection on the strip, which now reaches ± 180 s, or the span just after the clip) inserts a clip right after the current one, with its quote read from the transcript and **Blur picture** available on the form; the project page's timeline has the same as **Add clip**. A clip with nothing on disk to play offers **Fetch this clip's window**. From a terminal: `umtool set <project> <clip> blur.on=true blur.caption="…" blur.strength=8 blur.from=… blur.to=…` (`blur.on=` clears it) and `umtool look <project> blur=off`.
- **A recording saved from a live capture now plays in umtool's clip editor.** A stream recorded while it was on air has no length in its transcript's record, and umtool read a saved recording's length from there, so the whole recording counted as no window and every clip cut from it sat in the clip walk as not fetched. umtool now asks the saved file itself for its length when the record has none (once per file).
- **Rumble clip windows are cut from the whole recording, and a window whose picture runs off its sound is set aside.** A window fetched by seeking into Rumble's stream came out with the picture 1 to 4 seconds behind the sound 26 times out of 318, while a cut from a saved whole recording was exactly in sync. Fetch windows (`pnpm ops fetch-windows`, a site's **Fetch missing evidence**, umtool) now saves a Rumble video once, the way **Persist source video** does and on Rumble's download queue, then cuts every window of it from that copy: three clips of one video are one download, logged as "↧ <channel>/<id>: saving the whole recording (Rumble windows are cut from it), then cutting 3 window(s)". If that download fails, its windows fail with its message and nothing falls back to a seek. Which platforms work this way is `clips.wholeRecordingPlatforms` in settings.json (default `["rumble"]`), and `"wholeRecording": false` on a run seeks as before. Every window fetched by a seek, on any platform, is now checked with ffprobe for a picture or sound that starts late or a picture and sound of different lengths. A bad one is renamed `<from>-<to>.desynced.mp4`, never deleted, and fails with "the picture runs 3.2 s off the sound (a Rumble HLS seek); set aside as … — save the whole recording ("Persist source video") and fetch again to cut it from the saved video". A bad window already on disk is set aside when a fetch would have used it, and the same run fetches those seconds again. No reader (the video page, umtool, report videos) sees a set-aside window, and **Evict fetched windows** removes them by age like any window. **Check sync** on /storage and on a channel's Storage panel (`pnpm ops check-windows`, `{"slug"?, "video"?, "dryRun"?}`) checks the windows already on disk. Needs a restart of the editor.
- **umtool's clip editor keeps a voice's pitch at any speed, and goes up to 4×.** A selection, an edge, a transcript line or the auto-audition played at 1.5× or 2× used to rise in pitch with the speed (2× was an octave up), unlike the same video at 2× in a player: the bench plays a range from decoded audio, whose speed control is a tape-speed knob. At any speed but 1× the range is now time-stretched at its own pitch first (waveform-similarity overlap-add) and played at 1×, still starting and stopping on the exact sample; a clip's selection is stretched ahead while the editor is idle, so playing it does not wait. The speed list adds 1.75×, 2.5×, 3×, 3.5× and 4×. Needs a restart of umtool.
diff --git a/umtool/app/api/report/clip-editor/route.ts b/umtool/app/api/report/clip-editor/route.ts
@@ -13,7 +13,7 @@ export const dynamic = "force-dynamic";
// GET ?project=<id> the view: clips, token, speakers, unused proposals
// GET ?project=<id>&clip=<id>&from=<s>&to=<s> the strip for a span: turns, laughs, words | cues
// POST { project, op, token?, … } one operation (clipEditor.mjs runClipEditorOp):
-// trim | restore | split | merge | add | bring-in | ruling | role
+// trim | restore | split | merge | add | bring-in | ruling | role | … | audio | blur
// -> { op, result, carried, view }; 409 on a stale token (reload), 400 with
// the sentence on a refusal (the build's own, for a structural one)
const headers = { "cache-control": "no-store" };
diff --git a/umtool/app/api/report/cues/route.ts b/umtool/app/api/report/cues/route.ts
@@ -1,5 +1,5 @@
-import { resolveClip } from "@/lib/report/serve.mjs";
-import { cuesInWindow } from "@/lib/projects/report.mjs";
+import { resolveClip, resolveReport } from "@/lib/report/serve.mjs";
+import { cuesForSource, cuesInWindow } from "@/lib/projects/report.mjs";
export const dynamic = "force-dynamic";
@@ -7,6 +7,10 @@ export const dynamic = "force-dynamic";
// inferred from a waveform. Each carries whether it closes a sentence, computed
// with the same regex resolve-windows.mjs uses -- imported, not re-written, so
// the rail and the widener can never disagree about where a sentence ends.
+//
+// GET ?project&clip&from&to a clip's recording
+// GET ?project&video[&channel]&from&to a recording the cut does not carry yet (the
+// timeline's Add clip reads a new clip's quote here)
export async function GET(request: Request) {
const url = new URL(request.url);
const projectId = url.searchParams.get("project") ?? "";
@@ -17,6 +21,15 @@ export async function GET(request: Request) {
return Response.json({ error: "bad window" }, { status: 400 });
}
+ if (!clipId && url.searchParams.get("video")) {
+ const rr = await resolveReport(projectId);
+ if ("error" in rr) return Response.json({ error: rr.error }, { status: rr.status });
+ const channel = url.searchParams.get("channel") || null;
+ const got = await cuesForSource(rr.project.dir, { video: url.searchParams.get("video") ?? "", channel }, from, to);
+ if (!got) return Response.json({ error: "no cue file for this source" }, { status: 404 });
+ return Response.json(got, { headers: { "cache-control": "no-store" } });
+ }
+
const r = await resolveClip(projectId, clipId);
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
diff --git a/umtool/components/projects/TimelineEditor.tsx b/umtool/components/projects/TimelineEditor.tsx
@@ -5,6 +5,7 @@ import { createContext, useCallback, useContext, useEffect, useRef, useState } f
import AnchoredNotes from "@/components/notes/AnchoredNotes";
import { announceNotesChanged, useSharedNotes, wroteNotes } from "@/components/notes/NotesProvider";
import { buttonVariants } from "@/components/ui/button";
+import { newClipEntry, parseClipSpec, quoteFromCues } from "@/lib/report/clipEditorModel.mjs";
import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from "./timelineApi";
// Re-ordering the cut, on the project page.
@@ -12,9 +13,11 @@ import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from
// The rows stay the server's (each `<li data-entry data-at>` the page always
// drew); this list adds what moves them. Drag a row by its handle, or focus it
// and press alt+↑ / alt+↓; each row's menu duplicates it, removes it, or
-// inserts a clip after it (`<channel>/<video>@<start>-<end>`). Every one is a
-// structural write (POST /api/report/timeline): snapshotted first, so "Undo"
-// restores the cut as it was before the last burst of edits.
+// inserts a clip after it (`<channel>/<video>@<start>-<end>`). "Add clip" is the
+// same insert as a form: the spec, after which entry, an id, the quote (read
+// from the recording's cues as the spec is typed) and Blur picture. Every one
+// is a structural write (POST /api/report/timeline): snapshotted first, so
+// "Undo" restores the cut as it was before the last burst of edits.
type Ctx = {
project: string;
@@ -36,11 +39,17 @@ export function TimelineList({ project, count, children }: { project: string; co
const [error, setError] = useState<string | null>(null);
const [over, setOver] = useState<number | null>(null);
const dragging = useRef<{ id: string; at: number } | null>(null);
+ // The entries in order (Add clip's "after"), as the route last said.
+ const [entries, setEntries] = useState<{ id: string; type: string }[]>([]);
+ const [adding, setAdding] = useState(false);
const loadToken = useCallback(async () => {
const r = await fetch(`/api/report/timeline?project=${encodeURIComponent(project)}`, { cache: "no-store" });
const j = await r.json().catch(() => ({}));
- if (r.ok) tokenRef.current = typeof j.token === "string" ? j.token : null;
+ if (r.ok) {
+ tokenRef.current = typeof j.token === "string" ? j.token : null;
+ if (Array.isArray(j.timeline)) setEntries(j.timeline);
+ }
return tokenRef.current;
}, [project]);
useEffect(() => {
@@ -93,6 +102,9 @@ export function TimelineList({ project, count, children }: { project: string; co
<button type="button" data-testid="timeline-undo" disabled={busy} onClick={() => void run("undo", {})} className={buttonVariants({ size: "sm" })}>
Undo last edit
</button>
+ <button type="button" data-testid="timeline-add-clip" aria-expanded={adding} disabled={busy} onClick={() => setAdding((a) => !a)} className={buttonVariants({ size: "sm" })}>
+ Add clip
+ </button>
<span className="text-[var(--color-dim)]">
drag ⠿ or <kbd>alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> to move
</span>
@@ -103,6 +115,15 @@ export function TimelineList({ project, count, children }: { project: string; co
</span>
)}
</div>
+ {adding && (
+ <AddClipForm
+ project={project}
+ entries={entries}
+ busy={busy}
+ onCancel={() => setAdding(false)}
+ onAdd={(afterId, entry) => run("insert", { afterId, entry }).then((ok) => ok && setAdding(false))}
+ />
+ )}
<ul
className="space-y-1"
data-testid="timeline-list"
@@ -133,6 +154,128 @@ export function TimelineList({ project, count, children }: { project: string; co
);
}
+/**
+ * Add clip: `<channel>/<video>@<start>-<end>` after an entry (the last, unless
+ * another is picked), an optional id (blank: the route makes one), the quote
+ * -- read from the recording's cues while the spec is typed, until a person
+ * types one; " … " where the cues are not adjacent -- and Blur picture (the
+ * clip's `blur`, its default caption; change it in the clip editor).
+ */
+export function AddClipForm({
+ project,
+ entries,
+ busy,
+ onCancel,
+ onAdd,
+}: {
+ project: string;
+ entries: { id: string; type: string }[];
+ busy: boolean;
+ onCancel: () => void;
+ onAdd: (afterId: string | null, entry: Record<string, unknown>) => void;
+}) {
+ const [spec, setSpec] = useState("");
+ const [after, setAfter] = useState<string>(entries[entries.length - 1]?.id ?? "");
+ const [id, setId] = useState("");
+ const [quote, setQuote] = useState("");
+ const [typed, setTyped] = useState(false);
+ const [blur, setBlur] = useState(false);
+ const [cueNote, setCueNote] = useState<string | null>(null);
+ const parsed = parseClipSpec(spec);
+ const valid = !!parsed && parsed.end - parsed.start >= 0.5;
+ useEffect(() => {
+ if (!after && entries.length) setAfter(entries[entries.length - 1].id);
+ }, [entries, after]);
+ useEffect(() => {
+ if (typed || !parsed || !valid) return;
+ let live = true;
+ const t = setTimeout(() => {
+ const q = new URLSearchParams({ project, video: parsed.video, channel: parsed.channel, from: String(Math.max(0, parsed.start - 1)), to: String(parsed.end + 1) });
+ void fetch(`/api/report/cues?${q}`, { cache: "no-store" })
+ .then(async (r) => {
+ if (!live) return;
+ if (!r.ok) {
+ setCueNote("no transcript for this recording here: type the quote");
+ return;
+ }
+ const j = (await r.json()) as { cues?: { start: number; end: number; text: string }[] };
+ setCueNote(null);
+ setQuote(quoteFromCues(j.cues ?? [], parsed.start, parsed.end));
+ })
+ .catch(() => {});
+ }, 300);
+ return () => {
+ live = false;
+ clearTimeout(t);
+ };
+ // The spec's parts name it.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [project, spec, typed, valid]);
+ const submit = () => {
+ if (!parsed || !valid || busy) return;
+ onAdd(after || null, newClipEntry({ video: parsed.video, ownChannel: parsed.channel }, { start: parsed.start, end: parsed.end, id, quote, blur }));
+ };
+ const input = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]";
+ return (
+ <div data-testid="timeline-add-form" className="mb-2 space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[11px]">
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ autoFocus
+ data-testid="timeline-add-spec"
+ value={spec}
+ placeholder="<channel>/<video>@<start>-<end>"
+ onChange={(e) => setSpec(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") onCancel();
+ if (e.key === "Enter") submit();
+ }}
+ className={`w-72 ${input}`}
+ />
+ <label className="inline-flex items-center gap-1">
+ after
+ <select data-testid="timeline-add-after" value={after} onChange={(e) => setAfter(e.target.value)} className={input}>
+ <option value="">(the start)</option>
+ {entries.map((e, i) => (
+ <option key={`${e.id}:${i}`} value={e.id}>
+ {e.id} · {e.type}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="inline-flex items-center gap-1">
+ id
+ <input data-testid="timeline-add-id" value={id} maxLength={64} placeholder="(automatic)" onChange={(e) => setId(e.target.value)} className={`w-36 ${input}`} />
+ </label>
+ {spec && !valid && <span className="text-[var(--color-bad)]">a clip is <channel>/<video>@<start>-<end>, at least half a second</span>}
+ </div>
+ <textarea
+ data-testid="timeline-add-quote"
+ value={quote}
+ rows={2}
+ placeholder="the quote (read from the transcript when there is one)"
+ onChange={(e) => {
+ setTyped(true);
+ setQuote(e.target.value);
+ }}
+ className={`w-full ${input} font-sans`}
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="inline-flex items-center gap-1">
+ <input type="checkbox" data-testid="timeline-add-blur" checked={blur} onChange={(e) => setBlur(e.target.checked)} />
+ Blur picture
+ </label>
+ {cueNote && <span className="text-[var(--color-dim)]">{cueNote}</span>}
+ <button type="button" data-testid="timeline-add-submit" disabled={busy || !valid} onClick={submit} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Add
+ </button>
+ <button type="button" disabled={busy} onClick={onCancel} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}
+
/** Inside one row: the drag handle and the row's menu. */
export function RowControls({ id, at }: { id: string; at: number }) {
const ctx = useContext(TimelineCtx);
diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx
@@ -14,6 +14,9 @@ import AssistBox from "./AssistBox";
// /api/report/render (lib/report/manifest.mjs updateRender, the build's own
// checks). Nothing here calls a model. A deck cut keeps its own settings
// (the Media tab); a montage levels with render.montage.
+// The blurred clips (render.blur): "uncensored" renders every clip's picture
+// as recorded -- the other version of a cut whose clips ask for a blur, kept
+// as a take (`umtool take <p> --id uncensored --set render.blur=off`).
// Release 38 lane E: the blur slide's knobs (travel, smear, grain) and the
// room's numbers (how far the tail may run, the silence that ends it) are
// fields too, so every op the video assistant can propose is one here; the
@@ -30,6 +33,7 @@ type Look = {
captions?: { style: "speakers"; labels?: { host?: string | null; subject?: string | null } | null; size?: "m" | "l" } | null;
room?: { tail?: boolean; head?: boolean; minGap?: number; maxS?: number } | null;
slide?: { travel?: number; blur?: number; grain?: number } | null;
+ blur?: string;
};
type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; errors: string[]; token: string | null };
@@ -54,6 +58,7 @@ type Draft = {
travel: string;
smear: string;
grain: string;
+ blur: "on" | "off";
};
function draftOf(l: Look): Draft {
@@ -77,6 +82,7 @@ function draftOf(l: Look): Draft {
travel: String(l.slide?.travel ?? SLIDE_DEFAULTS.travel),
smear: String(l.slide?.blur ?? SLIDE_DEFAULTS.blur),
grain: String(l.slide?.grain ?? SLIDE_DEFAULTS.grain),
+ blur: l.blur === "off" ? "off" : "on",
};
}
@@ -122,6 +128,8 @@ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
(!on || ((was0?.maxS ?? ROOM.maxS) === maxS && (was0?.minGap ?? ROOM.minGap) === minGap));
if (!same) p.room = next;
}
+ // The blurred clips (render.blur): "on" is the default, written as no key.
+ if (d.blur !== (was.blur === "off" ? "off" : "on")) p.blur = d.blur === "off" ? "off" : null;
// The blur slide's knobs (release 38): only the ones off their defaults are written.
{
const cur = { travel: Number(d.travel), blur: Number(d.smear), grain: Number(d.grain) };
@@ -222,6 +230,12 @@ export default function LookPanel({ project }: { project: string }) {
))}
</Select>
</Field>
+ <Field label="Blurred clips" hint="a clip's Blur picture (clip editor)">
+ <Select data-look-blur="" value={draft.blur} disabled={busy} onChange={(e) => set({ blur: e.target.value as Draft["blur"] })}>
+ <option value="on">blurred (shareable)</option>
+ <option value="off">uncensored</option>
+ </Select>
+ </Field>
{!view.montage && (
<Field label="Loudness">
<span className="flex items-center gap-1.5">
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -8,13 +8,14 @@ import { useSharedNotes } from "@/components/notes/NotesProvider";
import { notesOn } from "@/components/notes/AnchoredNotes";
import { NoteThread } from "@/components/notes/NoteThread";
import type { CitedPlay } from "@/lib/clips/types";
-import { edgeClock, provenanceWords, quoteBetween, roleOf, snapCut, snapPoints } from "@/lib/report/clipEditorModel.mjs";
+import { edgeClock, newClipEntry, nextFreeId, provenanceWords, quoteBetween, roleOf, snapCut, snapPoints, spanQuote } from "@/lib/report/clipEditorModel.mjs";
import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Speaker, Turn } from "@/lib/report/clipEditorTypes";
import { cn } from "@/lib/utils";
import { ROOM, roomShade } from "umtool-report-to-video/room";
import { startTakeJob } from "../NewTakePanel";
+import { refusalOf, timelineOp } from "../timelineApi";
import AssistBox from "../report/AssistBox";
-import { AudioBox, MarksBox } from "./ClipKnobs";
+import { AudioBox, BlurBox, MarksBox } from "./ClipKnobs";
import LiveDeckPreview from "./LiveDeckPreview";
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional).
import type { ReplyProposal } from "@/lib/annotations/types";
@@ -33,7 +34,10 @@ import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy
// nearest word gap or silence
// the decisions Keep / Cut (montage-rulings.json, keyed by the moment),
// Split here, Merge with next, Restore the assistant's
-// version, Add a clip from the selection, Bring in a proposal
+// version, Add a clip from the selection, Bring in a proposal,
+// New clip (from the selection, or the span after this clip:
+// inserted AFTER it through the timeline route's `insert`,
+// its quote read from the words, Blur picture on it)
// the comments a note on the clip (notes.json, anchored to it), its thread
// and an agent's replies, resolve / reopen
// the short (release 36) a 9:16 box dragged on the player (the clip's
@@ -41,8 +45,10 @@ import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy
// a speaker's name for the captions in the Speakers list
// the knobs (video knobs) Marks on every clip -- each mark's verdict,
// second (Set at playhead, Shift+S), hold, on/off, count,
-// label; Add mark at playhead (Shift+M) -- and Audio: sync
-// nudge, gain, fades (./ClipKnobs.tsx)
+// label; Add mark at playhead (Shift+M) -- Audio: sync
+// nudge, gain, fades -- and Blur: the picture blurred at the
+// encode, its caption, strength, and a span at the playhead
+// (./ClipKnobs.tsx)
//
// Every write is one POST to /api/report/clip-editor; the answer is the whole
// view again, so the page never guesses what the server did. Edge edits are
@@ -50,7 +56,10 @@ import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy
// edit. Nothing here calls a model.
// ---------------------------------------------------------------------------
-const REACHES = [60, 20, 6] as const;
+// ± 180 s: far enough to select the span just past a long clip (New clip).
+const REACHES = [180, 60, 20, 6] as const;
+/** The strip's reach on a clip's first visit, and the player's (it looks for a file this far around the clip). */
+const REACH_DEFAULT = 60;
const NUDGES = [-2, -0.5, -0.1, 0.1, 0.5, 2] as const;
const COMMIT_MS = 450;
const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
@@ -87,7 +96,7 @@ export default function ClipEditor({
const [view, setView] = useState<EditorView>(initialView);
const [selected, setSelected] = useState(initialClip);
const [draft, setDraft] = useState<Cut | null>(null);
- const [reach, setReach] = useState<number>(REACHES[0]);
+ const [reach, setReach] = useState<number>(REACH_DEFAULT);
const [hood, setHood] = useState<Neighbourhood | null>(null);
const [playhead, setPlayhead] = useState<number | null>(null);
const [playing, setPlaying] = useState(false);
@@ -262,6 +271,44 @@ export default function ClipEditor({
if (id) choose(id);
});
};
+ // New clip (from the selection, or the span after this clip): the form, then
+ // the timeline route's `insert` after this clip -- snapshotted, checked by
+ // the build's own validators, an edit note on a generated cut -- and the
+ // editor on the new clip.
+ const [newClip, setNewClip] = useState<Cut | null>(null);
+ const openNewClip = () => {
+ if (selection) return setNewClip(selection);
+ const len = Math.max(5, clip.end - clip.start);
+ const a = clip.end;
+ const b = duration ? Math.min(duration, a + len) : a + len;
+ setNewClip(b - a >= 0.5 ? { cutStart: r2(a), cutEnd: r2(b) } : { cutStart: r2(Math.max(0, clip.start - len)), cutEnd: r2(clip.start) });
+ };
+ const insertClip = async (entry: Record<string, unknown>) => {
+ await flush();
+ setBusy(true);
+ try {
+ const res = await timelineOp(project, token.current, "insert", { afterId: clip.id, entry });
+ if (!res.ok) {
+ if (res.json.stale) await reload().catch(() => {});
+ setError(refusalOf(res));
+ return false;
+ }
+ await reload();
+ const id = typeof res.json.id === "string" ? res.json.id : null;
+ setNewClip(null);
+ setSelection(null);
+ if (id) {
+ choose(id);
+ setStatus(`New clip ${id} after ${clip.id}`);
+ }
+ return true;
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ };
const bringIn = (p: Proposal) => {
void flush()
.then(() => write({ op: "bring-in", proposal: p.id }, `Brought in ${p.id}`))
@@ -403,7 +450,7 @@ export default function ClipEditor({
const targets = useMemo(() => {
if (!clip.channel) return [];
const base = { channel: clip.channel, video: clip.video, project, clip: clip.id };
- const far = REACHES[0];
+ const far = REACH_DEFAULT;
const spans: [number, number][] = [
[Math.max(0, Math.floor(clip.start - far)), Math.ceil(duration ? Math.min(duration, clip.end + far) : clip.end + far)],
[clip.start, clip.end],
@@ -442,6 +489,11 @@ export default function ClipEditor({
{edgeClock(cut.cutStart)} – {edgeClock(cut.cutEnd)} · {(cut.cutEnd - cut.cutStart).toFixed(1)} s
</span>
{draft && <span className="micro" data-editor-unsaved="">unsaved</span>}
+ {clip.blur && (
+ <a href="#clip-blur" data-editor-blurred={view.blur?.rendered === false ? "off" : "on"} className={badgeVariants({ variant: "info", size: "sm" })} title="the player plays the source as it is; the render and the Live preview blur it">
+ {view.blur?.rendered === false ? "blur off in this cut" : "blurred in the render"}
+ </a>
+ )}
{clip.ruling && (
<span data-editor-ruling={clip.ruling} className={rulingBadge(clip.ruling)}>
{clip.ruling === "keep" ? "kept" : "cut"}
@@ -464,7 +516,7 @@ export default function ClipEditor({
)}
<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} />
- <LiveDeckPreview project={project} clip={clip} cut={cut} token={view.token} player={player} write={write} busy={busy} />
+ <LiveDeckPreview project={project} clip={clip} cut={cut} token={view.token} player={player} write={write} busy={busy} blurRendered={view.blur?.rendered ?? true} />
{/* ---- the strip --------------------------------------------------- */}
<div className="space-y-1">
@@ -599,6 +651,7 @@ export default function ClipEditor({
onGo={choose}
/>
<AudioBox clipId={clip.id} audio={clip.audio ?? null} busy={busy} write={write} canListen={playhead !== null} onListen={listen} />
+ <BlurBox clipId={clip.id} blur={clip.blur ?? null} defaults={view.blur} playhead={playhead} span={{ start: clip.start, end: clip.end }} busy={busy} write={(body, done) => flush().then(() => write(body, done))} />
{/* ---- the decisions ----------------------------------------------- */}
<div className="flex flex-wrap items-center gap-2" data-editor-actions="">
@@ -627,7 +680,24 @@ export default function ClipEditor({
Add a clip {edgeClock(selection.cutStart)}–{edgeClock(selection.cutEnd)}
</button>
)}
+ <button type="button" data-action="new-clip" disabled={busy} onClick={openNewClip} className={buttonVariants({ size: "md" })} title="a new clip from this recording, inserted after this one (drag on the strip to select its span first, or type it)">
+ {selection ? "New clip from selection…" : "New clip…"}
+ </button>
</div>
+ {newClip && (
+ <NewClipForm
+ key={`${clip.id}:${newClip.cutStart}-${newClip.cutEnd}`}
+ project={project}
+ clip={clip}
+ span={newClip}
+ ids={clips.map((c) => c.id)}
+ hood={hoodHere}
+ busy={busy}
+ blurCaption={view.blur?.caption ?? null}
+ onCancel={() => setNewClip(null)}
+ onInsert={insertClip}
+ />
+ )}
<div aria-live="polite" className="min-h-[1.2em] text-[12px]">
{error ? (
<span role="alert" data-editor-error="" className="text-reject-text">
@@ -799,6 +869,8 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
const cutRef = useRef(cut);
cutRef.current = cut;
const key = targets.map((t) => `${t.clip}|${t.from}|${t.to}`).join(",");
+ // Bumped when a fetch from the "nothing on disk" state finishes: look again.
+ const [attempt, setAttempt] = useState(0);
useEffect(() => {
let live = true;
@@ -823,7 +895,7 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
};
// `targets` is named by its key.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [key]);
+ }, [key, attempt]);
// Another clip on the same file: go to its cut, paused.
useEffect(() => {
@@ -877,7 +949,11 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
return (
<div data-editor-player="none" className="flex aspect-video w-full max-w-[720px] flex-col items-center justify-center gap-1 rounded-[3px] bg-panel-2 text-center text-[12px] text-muted">
<span>Nothing on disk plays this clip.</span>
- <span>Fetch its window from the Cut tab (Fetch windows), then come back.</span>
+ {targets[0] ? (
+ <FetchWindow project={targets[0].project} clipId={clipId} onDone={() => setAttempt((n) => n + 1)} />
+ ) : (
+ <span>Fetch its window from the Cut tab (Fetch windows), then come back.</span>
+ )}
</div>
);
const props = {
@@ -1535,3 +1611,157 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
</section>
);
}
+
+// ---------------------------------------------------------------------------
+// New clip: a span of this clip's recording, its id, its quote (read from the
+// words or the cues as the span changes, until a person types one), Blur
+// picture -- inserted after this clip (the timeline route's `insert`).
+// ---------------------------------------------------------------------------
+
+function NewClipForm({
+ project,
+ clip,
+ span,
+ ids,
+ hood,
+ busy,
+ blurCaption,
+ onCancel,
+ onInsert,
+}: {
+ project: string;
+ clip: EditorClip;
+ span: Cut;
+ ids: string[];
+ hood: Neighbourhood | null;
+ busy: boolean;
+ blurCaption: string | null;
+ onCancel: () => void;
+ onInsert: (entry: Record<string, unknown>) => Promise<boolean>;
+}) {
+ const [from, setFrom] = useState(String(span.cutStart));
+ const [to, setTo] = useState(String(span.cutEnd));
+ const [id, setId] = useState(() => nextFreeId(ids, clip.id));
+ const [quote, setQuote] = useState("");
+ const [typed, setTyped] = useState(false);
+ const [blur, setBlur] = useState(false);
+ const a = Number(from);
+ const b = Number(to);
+ const valid = Number.isFinite(a) && Number.isFinite(b) && a >= 0 && b - a >= 0.5;
+ // The quote: the strip's words when they cover the span, else the span's own.
+ useEffect(() => {
+ if (typed || !valid) return;
+ if (hood && hood.from <= a && hood.to >= b) {
+ setQuote(spanQuote({ words: hood.words, cues: hood.cues }, a, b));
+ return;
+ }
+ let live = true;
+ const t = setTimeout(() => {
+ const q = new URLSearchParams({ project, clip: clip.id, from: String(Math.max(0, Math.floor(a - 1))), to: String(Math.ceil(b + 1)) });
+ void fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((n: Neighbourhood | null) => {
+ if (live && n) setQuote(spanQuote({ words: n.words, cues: n.cues }, a, b));
+ })
+ .catch(() => {});
+ }, 250);
+ return () => {
+ live = false;
+ clearTimeout(t);
+ };
+ }, [project, clip.id, hood, a, b, valid, typed]);
+ const submit = () => {
+ if (!valid || busy) return;
+ void onInsert(newClipEntry(clip, { start: a, end: b, id, quote, blur }));
+ };
+ const field = "num w-[7em] rounded border border-seam-2 bg-ground px-1.5 py-0.5 font-mono text-[12px] text-text outline-none focus:border-signal";
+ return (
+ <section data-new-clip={clip.id} className="space-y-1.5 rounded-[3px] border border-seam bg-panel p-2 text-[12px] text-text-2">
+ <div className="flex flex-wrap items-baseline gap-2">
+ <h2 className="micro m-0">New clip after {clip.id}</h2>
+ <span className="text-muted">
+ {clip.video}
+ {typeof clip.section === "number" || typeof clip.section === "string" ? ` · section ${clip.section}` : ""}
+ {clip.onscreen?.title ? ` · “${clip.onscreen.title}”` : ""}
+ </span>
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <label className="inline-flex items-center gap-1.5">
+ <span className="micro">from</span>
+ <input data-new-clip-from="" type="number" step={0.1} min={0} value={from} disabled={busy} onChange={(e) => setFrom(e.target.value)} className={field} />
+ </label>
+ <label className="inline-flex items-center gap-1.5">
+ <span className="micro">to</span>
+ <input data-new-clip-to="" type="number" step={0.1} min={0} value={to} disabled={busy} onChange={(e) => setTo(e.target.value)} className={field} />
+ </label>
+ <span className="num font-mono text-[11.5px] text-muted">{valid ? `${edgeClock(a)}–${edgeClock(b)} · ${(b - a).toFixed(1)} s` : "at least half a second"}</span>
+ <label className="inline-flex items-center gap-1.5">
+ <span className="micro">id</span>
+ <input data-new-clip-id="" type="text" value={id} maxLength={64} disabled={busy} onChange={(e) => setId(e.target.value)} className={field.replace("w-[7em]", "w-[12em]")} />
+ </label>
+ </div>
+ <label className="flex items-start gap-1.5">
+ <span className="micro pt-1">quote</span>
+ <textarea
+ data-new-clip-quote=""
+ value={quote}
+ rows={2}
+ disabled={busy}
+ onChange={(e) => {
+ setTyped(true);
+ setQuote(e.target.value);
+ }}
+ placeholder="the words in the span (read from the transcript)"
+ className="min-w-0 flex-1 rounded border border-seam-2 bg-ground px-1.5 py-0.5 text-[12.5px] text-text outline-none focus:border-signal"
+ />
+ </label>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <label className="inline-flex items-center gap-1.5 text-text">
+ <input type="checkbox" data-new-clip-blur="" checked={blur} disabled={busy} onChange={(e) => setBlur(e.target.checked)} />
+ Blur picture
+ </label>
+ {blur && <span className="text-muted">“{blurCaption ?? "Original footage uncensored, blurred here for TOS"}” — change it in its Blur box</span>}
+ <button type="button" data-new-clip-insert="" disabled={busy || !valid} onClick={submit} className={buttonVariants({ variant: "go", size: "md" })}>
+ Insert after {clip.id}
+ </button>
+ <button type="button" data-new-clip-cancel="" disabled={busy} onClick={onCancel} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Cancel
+ </button>
+ </div>
+ </section>
+ );
+}
+
+/** Nothing on disk plays the clip: fetch its window (the bench's fetch, a job), then look again. */
+function FetchWindow({ project, clipId, onDone }: { project: string; clipId: string; onDone: () => void }) {
+ const [state, setState] = useState<{ running: boolean; msg: string | null }>({ running: false, msg: null });
+ const run = async () => {
+ setState({ running: true, msg: "fetching its window…" });
+ const r = await fetch("/api/report/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip: clipId, padBefore: 3, padAfter: 3 }) }).catch(() => null);
+ const j = r ? ((await r.json().catch(() => ({}))) as { error?: string; job?: { id: string }; cachedBefore?: number; cachedPad?: number }) : { error: "the fetch did not answer" };
+ if (r?.status === 409 && (j.cachedBefore !== undefined || j.cachedPad !== undefined)) {
+ setState({ running: false, msg: null });
+ return onDone();
+ }
+ if (!r?.ok || !j.job?.id) return setState({ running: false, msg: j.error ?? `HTTP ${r?.status ?? "?"}` });
+ for (;;) {
+ await new Promise((ok) => setTimeout(ok, 1000));
+ const p = await fetch(`/api/report/fetch?job=${encodeURIComponent(j.job.id)}`, { cache: "no-store" }).catch(() => null);
+ const pj = p?.ok ? ((await p.json()) as { job: { state: string; error: string | null } | null }) : null;
+ if (!pj?.job) return setState({ running: false, msg: "the fetch job is gone" });
+ if (pj.job.state === "running") continue;
+ if (pj.job.state !== "done") return setState({ running: false, msg: pj.job.error ?? `the fetch ${pj.job.state}` });
+ setState({ running: false, msg: null });
+ return onDone();
+ }
+ };
+ return (
+ <span className="flex flex-col items-center gap-1">
+ <button type="button" data-editor-fetch={clipId} disabled={state.running} onClick={() => void run()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {state.running ? "Fetching…" : "Fetch this clip's window"}
+ </button>
+ {state.msg && <span data-editor-fetch-msg="">{state.msg}</span>}
+ <span>or fetch every window from the Cut tab (Fetch windows)</span>
+ </span>
+ );
+}
diff --git a/umtool/components/projects/review/ClipKnobs.tsx b/umtool/components/projects/review/ClipKnobs.tsx
@@ -3,7 +3,7 @@
import { useEffect, useRef, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { edgeClock } from "@/lib/report/clipEditorModel.mjs";
-import type { ClipAudio, KnobDefaults, MarkVerdict, MarkView } from "@/lib/report/clipEditorTypes";
+import type { BlurDefaults, ClipAudio, ClipBlur, KnobDefaults, MarkVerdict, MarkView } from "@/lib/report/clipEditorTypes";
// THE CLIP'S KNOBS (video knobs, plans/video-knobs-ui.md), in the clip editor:
//
@@ -17,6 +17,10 @@ import type { ClipAudio, KnobDefaults, MarkVerdict, MarkView } from "@/lib/repor
// Audio the clip's sound at the encode: a sync nudge in ms (+ =
// later), gain in dB, fades in s; "listen" replays the 3 s
// around the playhead
+// Blur the clip's PICTURE blurred at the encode (report-to-video
+// clip-blur.mjs), its sound untouched: on/off, the caption
+// drawn on it, its strength, and "only from / to" at the
+// playhead (a partial span; Whole clip clears it)
//
// Every field shows the default it gets when its key is absent; Clear removes
// the key (the default again). Each change is one write through the clip
@@ -459,3 +463,124 @@ export function AudioBox({
</section>
);
}
+
+/**
+ * The clip's picture, blurred at the encode (clip-blur.mjs): for a clip whose
+ * footage a platform's graphic-content rules would refuse. The sound plays as
+ * it is; the caption is drawn on the blurred picture. The player above shows
+ * the source as it is (you are cutting it); the Live preview and the render
+ * show it blurred.
+ */
+export function BlurBox({
+ clipId,
+ blur,
+ defaults,
+ playhead,
+ span,
+ busy,
+ write,
+}: {
+ clipId: string;
+ blur: ClipBlur | null;
+ defaults: BlurDefaults | undefined;
+ playhead: number | null;
+ /** The clip's window (source seconds): a partial blur's from/to lie inside it. */
+ span: { start: number; end: number };
+ busy: boolean;
+ write: Write;
+}) {
+ const set = (patch: Record<string, unknown> | null, done: string) => void write({ op: "blur", clip: clipId, blur: patch }, done);
+ const fallback = defaults?.caption ?? "Original footage uncensored, blurred here for TOS";
+ const shown = blur?.caption ?? fallback;
+ const [caption, setCaption] = useState(shown);
+ useEffect(() => setCaption(shown), [shown, clipId]);
+ const saveCaption = () => {
+ const v = caption.trim();
+ if (v === shown) return;
+ set({ caption: v && v !== fallback ? v : null }, v && v !== fallback ? "Saved the blur's caption" : "The blur's caption is the default");
+ };
+ const inside = playhead !== null && playhead >= span.start - 0.02 && playhead <= span.end + 0.02;
+ const at = (edge: "from" | "to") => {
+ if (playhead === null || !inside) return;
+ set({ [edge]: r2(playhead) }, `Blurred ${edge === "from" ? "from" : "to"} ${edgeClock(playhead)}`);
+ };
+ const strength = defaults?.strength ?? { min: 2, max: 15, default: 5 };
+ const partial = blur && (blur.from !== undefined || blur.to !== undefined);
+ return (
+ <section id="clip-blur" data-blur-box={clipId} data-blur={JSON.stringify(blur ?? null)} className={box}>
+ <div className="flex flex-wrap items-baseline gap-2">
+ <label className="inline-flex items-center gap-1.5 text-text">
+ <input type="checkbox" data-blur-on="" checked={!!blur} disabled={busy} onChange={(e) => set(e.target.checked ? { on: true } : null, e.target.checked ? "The picture is blurred in the render" : "The picture plays as recorded")} />
+ <span className="micro">Blur picture</span>
+ </label>
+ <span className="text-muted">for footage a platform’s rules would refuse: the picture blurred, the sound as it is</span>
+ </div>
+ {blur && (
+ <>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <label className="inline-flex min-w-0 flex-1 items-center gap-1.5">
+ <span className="micro">caption</span>
+ <input
+ data-blur-caption=""
+ type="text"
+ value={caption}
+ maxLength={defaults?.captionMax ?? 120}
+ disabled={busy}
+ onChange={(e) => setCaption(e.target.value)}
+ onBlur={saveCaption}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") (e.target as HTMLInputElement).blur();
+ if (e.key === "Escape") {
+ setCaption(shown);
+ (e.target as HTMLInputElement).blur();
+ }
+ }}
+ className={`${input.replace("w-[6em]", "w-full")} min-w-[16em]`}
+ />
+ </label>
+ {blur.caption !== undefined && (
+ <button type="button" data-blur-caption-default="" disabled={busy} onMouseDown={(e) => e.preventDefault()} onClick={() => set({ caption: null }, "The blur's caption is the default")} className={buttonVariants({ variant: "quiet", size: "sm" })} title={fallback}>
+ Default
+ </button>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <KnobField
+ name="blur-strength"
+ label="strength"
+ unit={`% of the picture's height (${strength.min}–${strength.max})`}
+ step={0.5}
+ value={blur.strength}
+ placeholder={String(strength.default)}
+ busy={busy}
+ onSave={(v) => set({ strength: numOrNull(v) }, v ? `Blur strength ${v}` : "Blur strength as default")}
+ />
+ </div>
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5" data-blur-span={partial ? `${blur.from ?? ""}-${blur.to ?? ""}` : "whole"}>
+ <span className="micro">blurred</span>
+ <span className="num font-mono text-[11.5px] text-text">
+ {partial ? `${edgeClock(blur.from ?? span.start)} – ${edgeClock(blur.to ?? span.end)}` : "the whole clip"}
+ </span>
+ <button type="button" data-blur-from-playhead="" disabled={busy || !inside} onMouseDown={(e) => e.preventDefault()} onClick={() => at("from")} className={buttonVariants({ size: "sm" })} title="blur from the playhead on">
+ From playhead
+ </button>
+ <button type="button" data-blur-to-playhead="" disabled={busy || !inside} onMouseDown={(e) => e.preventDefault()} onClick={() => at("to")} className={buttonVariants({ size: "sm" })} title="blur up to the playhead">
+ To playhead
+ </button>
+ {partial && (
+ <button type="button" data-blur-whole="" disabled={busy} onMouseDown={(e) => e.preventDefault()} onClick={() => set({ from: null, to: null }, "The whole clip is blurred")} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Whole clip
+ </button>
+ )}
+ {playhead !== null && !inside && <span className="text-muted">the playhead is outside the clip’s window</span>}
+ </div>
+ <p className="m-0 text-muted" data-blur-note="">
+ {defaults && !defaults.rendered
+ ? "This cut renders uncensored (render.blur off, the Look panel): no clip is blurred in it. A take keeps the other version."
+ : "Blurred in the render and in the Live preview; the player above plays the source as it is."}
+ </p>
+ </>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/review/LiveDeckPreview.tsx b/umtool/components/projects/review/LiveDeckPreview.tsx
@@ -8,6 +8,7 @@ import type { EditorClip } from "@/lib/report/clipEditorTypes";
import { footageAt } from "@/lib/report/footage-move.mjs";
import { clipStamps, clockText, cutTimeAt, finaleUp, liveClock, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
import { tallyVerdicts } from "umtool-report-to-video/factcheck";
+import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH, blurCaptionLayout } from "umtool-report-to-video/clip-blur";
import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type DeckTexts, type Rect } from "../OnscreenSection";
// ---------------------------------------------------------------------------
@@ -30,7 +31,11 @@ import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDo
// The footage is the editor's own <video>, drawn into a canvas at the
// footage's box every frame (no second decode, never out of step), fitted and
// padded in the palette's ground as the build frames it, and carried along
-// the schedule's footage moves (the finale's grow, posts making room).
+// the schedule's footage moves (the finale's grow, posts making room). A clip
+// with a `blur` (clip-blur.mjs) is drawn through the canvas's own Gaussian
+// (`filter: blur()`, the same sigma: its strength as a % of the picture's
+// height) with its caption laid out by the build's own blurCaptionLayout,
+// over its span only -- unless the cut renders uncensored (render.blur off).
//
// Instant on an edit: a window, a claim, a mark or the words saved through the
// editor change the manifest's token, and the pages are composed again (a
@@ -76,6 +81,7 @@ export default function LiveDeckPreview({
player,
write,
busy,
+ blurRendered = true,
}: {
project: string;
clip: EditorClip;
@@ -84,6 +90,8 @@ export default function LiveDeckPreview({
player: React.RefObject<LivePlayer | null>;
write: Write;
busy: boolean;
+ /** Does the cut draw its clips' blur (render.blur not "off")? */
+ blurRendered?: boolean;
}) {
const [on, setOn] = useState(true);
useEffect(() => {
@@ -156,7 +164,11 @@ export default function LiveDeckPreview({
const bg = doc?.background ?? "#000";
const bgRef = useRef(bg);
bgRef.current = bg;
- const lastDraw = useRef<{ el: HTMLCanvasElement | null; media: HTMLMediaElement | null; t: number; bg: string; size: string }>({ el: null, media: null, t: NaN, bg: "", size: "" });
+ const lastDraw = useRef<{ el: HTMLCanvasElement | null; media: HTMLMediaElement | null; t: number; bg: string; size: string; blur: string }>({ el: null, media: null, t: NaN, bg: "", size: "", blur: "" });
+ // The clip's blur as the render draws it (null: none, or render.blur off).
+ 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;
// Every animation frame while on: the playhead's cut second, and the
// editor's picture drawn into the footage box when it moved.
@@ -181,8 +193,13 @@ export default function LiveDeckPreview({
if (!el) return;
const ld = lastDraw.current;
const video = m instanceof HTMLVideoElement && m.readyState >= 2 && m.videoWidth > 0 ? m : null;
- if (ld.el === el && ld.media === video && ld.t === (video?.currentTime ?? -1) && ld.bg === bgRef.current && ld.size === `${el.width}x${el.height}`) return;
- lastDraw.current = { el, media: video, t: video?.currentTime ?? -1, bg: bgRef.current, size: `${el.width}x${el.height}` };
+ 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}` : "";
+ 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";
const ctx = el.getContext("2d");
if (!ctx) return;
ctx.fillStyle = bgRef.current;
@@ -192,7 +209,34 @@ export default function LiveDeckPreview({
const k = Math.min(el.width / video.videoWidth, el.height / video.videoHeight);
const w = video.videoWidth * k;
const hh = video.videoHeight * k;
- ctx.drawImage(video, (el.width - w) / 2, (el.height - hh) / 2, w, hh);
+ const x = (el.width - w) / 2;
+ const y = (el.height - hh) / 2;
+ if (!blurNow) {
+ ctx.drawImage(video, x, y, w, hh);
+ return;
+ }
+ // The build's blur: gblur on the picture as it plays, sigma = strength % of its height.
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(x, y, w, hh);
+ ctx.clip();
+ ctx.filter = `blur(${((blurNow.strength / 100) * hh).toFixed(1)}px)`;
+ ctx.drawImage(video, x, y, w, hh);
+ ctx.restore();
+ // Its caption, laid out as the build lays it (top centre, one box a line).
+ const lay = blurCaptionLayout(blurNow.caption, w, hh);
+ ctx.font = `bold ${lay.fontSize}px "IBM Plex Mono", ui-monospace, monospace`;
+ ctx.textBaseline = "top";
+ lay.lines.forEach((line, i) => {
+ const tw = ctx.measureText(line).width;
+ const ty = y + lay.top + i * lay.lineHeight;
+ ctx.globalAlpha = 0.78;
+ ctx.fillStyle = bgRef.current;
+ ctx.fillRect(x + (w - tw) / 2 - lay.pad, ty - lay.pad, tw + 2 * lay.pad, lay.fontSize + 2 * lay.pad);
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = "#fff";
+ ctx.fillText(line, x + (w - tw) / 2, ty);
+ });
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -23,7 +23,7 @@ Inbox cannot disagree about what is wrong with one.
| `inbox [--all] [--json]` | the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx |
| `folders [--json]` · `kinds [--json]` | the tree, the registry |
| `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window |
-| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`; `key=` clears one ([knobs.md](knobs.md#marks)) |
+| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)); `key=` clears one ([knobs.md](knobs.md#marks)) |
| `look <project> key=value …` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys ([knobs.md](knobs.md)) |
| `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) |
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -24,6 +24,10 @@ that generates it ([notes.md](notes.md)).
| `audio.offset` — ms, + = the sound later (−2000…2000) | clip editor, **Audio**: **sync**, the ±10/±40 nudges, **listen** (the 3 s around the playhead) | `umtool set <p> <clip> audio.offset=-40` | `POST /api/report/clip-editor {op: "audio", clip, audio: {offset}}` |
| `audio.gain` — dB (−20…20) | Audio, **gain** | `audio.gain=-3` | same |
| `audio.fadeIn`, `audio.fadeOut` — seconds (0–5) | Audio, **fade in / fade out** | `audio.fadeIn=0.3` | same |
+| `blur.on` — `true`: the clip's PICTURE blurred at its encode, a caption drawn on it, the sound untouched (see [below](#a-clips-picture-blurred)) | clip editor, **Blur**: **Blur picture** | `umtool set <p> <clip> blur.on=true` (`blur.on=` clears every blur key) | `POST /api/report/clip-editor {op: "blur", clip, blur: {on, caption?, strength?, from?, to?} \| null}` |
+| `blur.caption` — the words on the blurred picture (≤ 120; default "Original footage uncensored, blurred here for TOS") | Blur, **caption** (prefilled with the default; **Default**) | `blur.caption="Blurred here for TOS"` | same |
+| `blur.strength` — the blur's radius, % of the picture's height as it plays (2–15; default 5) | Blur, **strength** | `blur.strength=8` | same |
+| `blur.from`, `blur.to` — source seconds inside the clip's window: blur only that span (either alone runs to the clip's edge; default the whole clip) | Blur, **From playhead** / **To playhead**, **Whole clip** | `blur.from=231.5 blur.to=262` | same |
| `layout` — `finale`: the deck's finale layout for this clip (`render.chrome.deck.finale`); `clip` is the default | — | `umtool set <p> <clip> layout=finale` | — |
`key=` (nothing after the `=`) clears a knob; in umtool, **Clear** beside a field (Audio: **Clear all**). A
@@ -32,6 +36,40 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that
clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the
claim's id and verdict and keeps its knobs while the id stays the same.
+## A clip's picture, blurred
+
+For footage a platform's graphic-content rules would refuse (the operator's case: a clip showing a dog having a
+seizure) that the cut still needs — its sound is the evidence. `blur` on the clip blurs its source picture at the
+segment encode (report-to-video `clip-blur.mjs`) and draws the caption on it, top centre, in the deck's face; the
+sound plays as recorded.
+
+```json
+{ "type": "clip", "id": "dog", "video": "BZCS-Azx_iE", "start": 228.36, "end": 298,
+ "blur": { "on": true, "caption": "Original footage uncensored, blurred here for TOS", "strength": 5, "from": 231.5, "to": 262 } }
+```
+
+- **Only the picture.** The blur is on the picture as it plays — scaled, not yet padded into the frame — so the
+ header, the footer, the QR, the rail, the deck (laid over the whole cut later), the speaker captions and the
+ stamps are as sharp as ever. A source with no picture (a poster plays) has nothing to blur.
+- **Strength** is the Gaussian's sigma as a % of the picture's height (5: ~54 px on a 1080-line picture, ~40 px in
+ the deck's footage box): nothing in the picture is recognisable at the master or any variant (each is a
+ downscale of the blurred master). The thumbnail's still, taken from a blurred second, is blurred too.
+- **Only part of a clip:** `from` / `to` (source seconds, inside the window; a window save that would leave them
+ outside is refused) — the blur and the caption over that span only.
+- **Refused:** an unknown key, `on` other than `true`, a caption over 120 characters or empty, a strength outside
+ 2–15, a span under 0.2 s or outside the window, a `blur` on anything but a clip, and a `blur` under
+ `render.montage` (a montage re-cuts its pictures).
+- **The uncensored variant:** `render.blur: "off"` (default `"on"`, absent) renders every clip as recorded and
+ draws no caption. Set it for the cut in the Build tab's **Look** (**Blurred clips**: blurred / uncensored),
+ `umtool look <p> blur=off`, or — to keep both — on a take: `umtool take <p> --id uncensored --label "Uncensored"
+ --set render.blur=off --full` beside a blurred `timeline` take ([report-video.md](report-video.md#making-takes)).
+- **The live preview** draws the blur and the caption over the footage as the render will (the canvas's own
+ Gaussian, the same sigma, the build's caption layout), over the span; the player above it plays the source as it
+ is, since that is what you are cutting. A cut with no deck has no live preview: **Render this clip** shows it.
+ A clip with `blur` says **blurred in the render** beside its id.
+- **`--chrome-only`** refuses segments blurred another way than the cut asks (render.blur switched, a span moved):
+ the blur is in the segment's picture, so it takes a normal build (`--skip-fetch` re-cuts from the cached windows).
+
## Marks
A clip may carry more than one MARK — each its own stamp and its own tally step, at its own second — e.g. a clip
@@ -80,6 +118,7 @@ that mentions the seizure in question and one before it. The Marks box is on eve
| `render.chrome.deck.markers[]` — `{after, label ≤ 24, color?, align?}`, at most 12; `align` `auto` `left` `right` `center` | On-screen, **markers**: add, the clip picker, label, colour, align, ↑ ↓, remove | `umtool look <p> deck.markers='[{"after":"c03","label":"Rescue","align":"right"}]'` | `PUT /api/report/chrome {project, token, markers}` |
| `render.chrome.deck.<key>` — any of the deck's own keys (`finale`, `pip`, …), as JSON; refused in the build's words when it does not know the key or the value | On-screen settings (the ones it has a field for) | `umtool look <p> deck.finale='{…}'` | — |
| `render.chrome.deck.markerLayout` — `stagger` or `truncate` when labels crowd (default: stagger only when a label would truncate) | markers, **layout** | `deck.markerLayout=truncate` | `PUT /api/report/chrome {project, token, markerLayout}` |
+| `render.blur` — `off`: every clip's picture as recorded, no caption (the uncensored variant); `on` (the default) blurs the clips that ask | Build, **Look**: **Blurred clips** | `umtool look <p> blur=off` · a take: `umtool take <p> --id uncensored --set render.blur=off` | `PUT /api/report/render {project, token, patch: {blur}}` |
| `render.variants` — the ladder **Make variants** encodes: `{name, height?, crf?, maxMiB?, preset?}` (at most 12; a `maxMiB` rung takes no crf, a height there caps it); `master` is the build itself | Deliver, **Variants and sync**: Edit, Save ladder, Use the default | `umtool look <p> variants='[{"name":"master"},{"name":"720p","height":720,"crf":23}]'` | `PUT /api/report/render {project, token, variants}` |
The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets
@@ -154,5 +193,5 @@ negative lag, needs a positive offset), then a build.
## Reading them back
-`umtool show <p>` prints a **knobs** block — each clip's claim knobs and audio (which clip stamps), the stamp's
+`umtool show <p>` prints a **knobs** block — each clip's claim knobs, audio and blur (which clip stamps), the stamp's
knobs and words, the markers and their layout, the ladder — and `umtool show <p> --json` carries it as `knobs`.
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -52,6 +52,7 @@ travel. umtool never reorders as a side effect of a window edit.
"verdict": "confirmed", // or "incorrect"; absent = nobody has looked yet
"assist": { "by": "assistant", … }, // the clip finder's provenance (see "Highlights"); never rendered
"chapter": "…", // chapter title; falls back to date + title
+ "blur": { "on": true }, // optional: its PICTURE blurred, a caption on it (knobs.md)
"section": 2, "sectionEnter": true,
"lock": true, "lockStart": true, "lockEnd": true }
```
@@ -838,6 +839,7 @@ Nothing on the page calls a model. The same, from a terminal ([cli.md](cli.md)):
```
umtool take <project> --id flash --label "Flash" --style flash-count --at 0 --dur 60
umtool take <project> --id crisp --label "Crisp" --set render.crf=34 --full
+umtool take <project> --id uncensored --label "Uncensored" --set render.blur=off --full
umtool takes make <project> --recipe takes/recipe.json # or --all-styles
umtool takes styles
umtool takes pick <project> flash [--anyway]
@@ -865,6 +867,11 @@ A take (`lib/report/takeMaker.mjs`):
fails leaves no take.json (a work dir the listing ignores), and a failed **Rebuild** leaves the
old take whole.
+**The uncensored variant.** A cut whose clips carry a `blur` ([knobs.md](knobs.md#a-clips-picture-blurred))
+renders them blurred; a take with `--set render.blur=off` (the New take form's patch:
+`{"render": {"blur": "off"}}`) renders the same cut with every picture as recorded and no caption.
+Keep the project's own cut (and its `timeline` take) blurred for sharing and the `uncensored` take beside it.
+
`--quick` (a recipe's or a take's `quick: true`) is that quick render. A take that exists is skipped unless forced (**make it again if it exists**, `--force`).
**Rebuild** on a card (`--rebuild`) makes it again from its own take.json against the project's
manifest as it is now. A recipe is `{ group, window, quick?, takes: [{ id, label, style?, patch?,
@@ -1211,12 +1218,14 @@ keep / cut and comments work the same. Nothing in it calls a model.
- **The player** loops the selected clip's cut, from what is on disk: a saved
video, a clip window, or audio (the cited clip's own lookup). Nothing on disk:
- fetch the windows from the Cut tab first.
-- **The strip** under it is the clip's neighbourhood, ± 60 s (± 20 s, ± 6 s to
- look closer): the speaker turns coloured host / subject (`reactions.json`),
+ **Fetch this clip's window** (the bench's fetch, a job; then it looks again),
+ or fetch every window from the Cut tab.
+- **The strip** under it is the clip's neighbourhood, ± 60 s (± 180 s to reach
+ further, ± 20 s, ± 6 s to look closer): the speaker turns coloured host / subject (`reactions.json`),
the laughs, a tick per word, the other clips (a click opens one), and the cut
with a handle at each edge to drag. A drag on the strip selects a span: **Add a
- clip** from it. A click puts the playhead there; so does a click on a word in
+ clip** from it (in time order among the recording's clips), or **New clip from
+ selection** (below). A click puts the playhead there; so does a click on a word in
the words under the strip (the project's word timings, else the cues; the
cut's words are lit).
- **The edges:** a number field each, nudges ±0.1 / ±0.5 / ±2 s, **at
@@ -1247,6 +1256,22 @@ keep / cut and comments work the same. Nothing in it calls a model.
person edited.
- **Render:** the picked take (or the one whole-cut take) made again, else the
Takes page.
+- **New clip** (from the selection, or — with none — the span just after this
+ clip, as long as it): a form with **from** / **to** (source seconds), the
+ **id** (`<this clip>-2`, `-3`, … until typed over), the **quote** (read from the
+ word timings, else the cues — `" … "` where two cues are not adjacent — until
+ typed over) and **Blur picture**. **Insert after** puts it right after this
+ clip through the timeline route's `insert` (`POST /api/report/timeline`: the
+ `auto-before-insert` snapshot, the build's checks, an `edit` note on a
+ generated cut, 409 on a stale token), with this clip's video and channel as
+ written, its `section`, its deck title (`onscreen.title`), `cite` the span's
+ first whole second and `citeUrl` this clip's with `t=` moved there (one with no
+ `t=` is kept as it is: it may cite a mirror). The editor then opens the new
+ clip; its window may need **Fetch this clip's window** first. The project
+ page's timeline has the same as **Add clip** (a `<channel>/<video>@<start>-<end>`
+ spec, after which entry, the quote from the recording's cues).
+- **Blur** (on every clip): the clip's picture blurred at the encode — see
+ [knobs.md](knobs.md#a-clips-picture-blurred).
Keys: space play / pause, `j` / `l` back / on 2 s, `i` / `o` in / out at the
playhead, `s` split, `m` merge, `k` keep, `x` cut, ← / → the previous / next
diff --git a/umtool/e2e/clip-blur.spec.ts b/umtool/e2e/clip-blur.spec.ts
@@ -0,0 +1,105 @@
+import { test, expect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// A clip's picture blurred (report-to-video clip-blur.mjs) and new clips from a
+// span of a recording:
+// - the clip editor's Blur box: Blur picture, the caption (prefilled with the
+// default), the strength, From playhead, Whole clip, off again
+// - New clip (from the span after the clip, its edges typed): inserted after
+// the clip through the timeline route, its quote read from the words, Blur
+// picture on it; the editor opens the new clip
+// - the project page's timeline: Add clip, its quote from the recording's
+// cues, after a chosen entry, Blur picture
+// Fixture: e2e/fixtures/clip-editor-fixture.mjs, as clip-blur-fixture
+// (r001 1.0-3.0, r002 4.0-6.0, r003 6.5-8.5 on vid1; vid1's cues 0-21 s).
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT = "reports/clip-blur-fixture";
+const DIR = path.join(HERE, "..", ".e2e-song", "reports", "clip-blur-fixture");
+
+type Entry = Record<string, unknown> & { id: string; type: string };
+const timeline = (): Entry[] => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")).timeline;
+const entry = (id: string) => timeline().find((e) => e.id === id) ?? null;
+const DEFAULT_CAPTION = "Original footage uncensored, blurred here for TOS";
+
+test("the Blur box: on, a caption, a strength, from the playhead, the whole clip, off", async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 900 });
+ await page.goto(urls.clipEditorHref(PROJECT, { clip: "r003", mode: "edit" }));
+ await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r003");
+ await expect(page.locator("[data-editor-player]")).not.toHaveAttribute("data-editor-player", "looking", { timeout: 15_000 });
+
+ const box = page.locator('[data-blur-box="r003"]');
+ await box.locator("[data-blur-on]").check();
+ await expect.poll(() => entry("r003")?.blur).toEqual({ on: true });
+ await expect(page.locator("[data-editor-blurred]")).toHaveAttribute("data-editor-blurred", "on");
+ await expect(box.locator("[data-blur-caption]")).toHaveValue(DEFAULT_CAPTION);
+
+ await box.locator("[data-blur-caption]").fill("Blurred here for TOS");
+ await box.locator("[data-blur-caption]").press("Enter");
+ await expect.poll(() => entry("r003")?.blur).toEqual({ on: true, caption: "Blurred here for TOS" });
+ await box.locator('[data-knob="blur-strength"]').fill("8");
+ await box.locator('[data-knob="blur-strength"]').press("Enter");
+ await expect.poll(() => (entry("r003")?.blur as { strength?: number } | undefined)?.strength).toBe(8);
+
+ // A word puts the playhead there; From playhead blurs from that second on.
+ await page.locator('[data-word-t="7.2"]').click();
+ await box.locator("[data-blur-from-playhead]").click();
+ await expect.poll(() => (entry("r003")?.blur as { from?: number } | undefined)?.from).toBe(7.2);
+ await expect(box.locator("[data-blur-span]")).toHaveAttribute("data-blur-span", "7.2-");
+ await box.locator("[data-blur-whole]").click();
+ await expect.poll(() => entry("r003")?.blur).toEqual({ on: true, caption: "Blurred here for TOS", strength: 8 });
+ // The default caption again is no caption key.
+ await box.locator("[data-blur-caption-default]").click();
+ await expect.poll(() => entry("r003")?.blur).toEqual({ on: true, strength: 8 });
+
+ await box.locator("[data-blur-on]").uncheck();
+ await expect.poll(() => entry("r003") && "blur" in entry("r003")!).toBe(false);
+ await expect(page.locator("[data-editor-blurred]")).toHaveCount(0);
+});
+
+test("New clip: the span after the clip, its quote from the words, Blur picture, inserted after it", async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 900 });
+ await page.goto(urls.clipEditorHref(PROJECT, { clip: "r003", mode: "edit" }));
+ await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r003");
+ await expect(page.locator("[data-editor-words]")).toBeVisible();
+
+ await page.locator('[data-action="new-clip"]').click();
+ const form = page.locator('[data-new-clip="r003"]');
+ // With no selection: the span just after the clip, as long as it (at least 5 s).
+ await expect(form.locator("[data-new-clip-from]")).toHaveValue("8.5");
+ await expect(form.locator("[data-new-clip-to]")).toHaveValue("13.5");
+ await expect(form.locator("[data-new-clip-id]")).toHaveValue("r003-2");
+ await form.locator("[data-new-clip-from]").fill("9.2");
+ await form.locator("[data-new-clip-to]").fill("11.8");
+ await expect(form.locator("[data-new-clip-quote]")).toHaveValue("Another whole sentence entirely.");
+ await form.locator("[data-new-clip-blur]").check();
+ await form.locator("[data-new-clip-insert]").click();
+
+ await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r003-2");
+ const ids = timeline().map((e) => e.id);
+ expect(ids.indexOf("r003-2")).toBe(ids.indexOf("r003") + 1);
+ expect(entry("r003-2")).toMatchObject({ type: "clip", video: "vid1", start: 9.2, end: 11.8, cite: 9, quote: "Another whole sentence entirely.", blur: { on: true } });
+ await expect(page.locator('[data-blur-box="r003-2"] [data-blur-on]')).toBeChecked();
+});
+
+test("the timeline's Add clip: a spec, its quote from the cues, after a chosen entry, Blur picture", async ({ page }) => {
+ test.setTimeout(90_000);
+ await page.goto(urls.section(PROJECT, "timeline"));
+ await expect(page.getByTestId("timeline-undo")).toBeEnabled();
+ await page.getByTestId("timeline-add-clip").click();
+ await page.getByTestId("timeline-add-spec").fill("testchan/vid1@12-15");
+ await expect(page.getByTestId("timeline-add-quote")).toHaveValue("A fourth one, done.");
+ await page.getByTestId("timeline-add-after").selectOption("r001");
+ await page.getByTestId("timeline-add-blur").check();
+ await page.getByTestId("timeline-add-submit").click();
+ await expect.poll(() => timeline().map((e) => e.id).indexOf("vid1-12")).toBe(timeline().map((e) => e.id).indexOf("r001") + 1);
+ expect(entry("vid1-12")).toEqual({ type: "clip", id: "vid1-12", channel: "testchan", video: "vid1", start: 12, end: 15, cite: 12, quote: "A fourth one, done.", blur: { on: true } });
+ await expect(page.getByTestId("timeline-add-form")).toHaveCount(0);
+});
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -1815,6 +1815,8 @@ makeClipDeckFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out",
makeMontageOpsFixture({ reports, channels: CHANNELS, manifest });
// Release 35 C2: the clip editor, an assistant's clips adjusted by hand (clip-editor.spec.ts).
makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// A clip's picture blurred, New clip from selection and the timeline's Add clip (clip-blur.spec.ts).
+makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "clip-blur-fixture", title: "The Clip Blur Fixture" });
// Release 36 lane C: the Look panel, a short's framing and Make a short (clip-look.spec.ts).
makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "clip-look-fixture", title: "The Clip Look Fixture" });
// P4b: the bench shell's own clips, and the Media tab's fields with their draft files.
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -1413,6 +1413,23 @@ export async function cuesInWindow(dir, clipId, from, to) {
const m = await readManifest(dir);
const e = clipsOf(m).find((x) => x.id === clipId);
if (!e) return null;
+ return cuesOfSource(dir, m, e, from, to);
+}
+
+/**
+ * The cues of a recording the cut does not carry yet -- `{ channel?, video }`
+ * (no channel: the cut's provenance channel) -- in [from, to]: what the
+ * timeline's Add clip reads a new clip's quote from. Null when no cue file.
+ */
+export async function cuesForSource(dir, source, from, to) {
+ const m = await readManifest(dir);
+ // Names that cross the wire, never paths: a video id and a channel slug.
+ const name = (v) => typeof v === "string" && /^[A-Za-z0-9._-]+$/.test(v) && v !== "." && v !== "..";
+ if (!m || !name(source?.video) || (source.channel !== undefined && source.channel !== null && !name(source.channel))) return null;
+ return cuesOfSource(dir, m, { video: source.video, ...(source.channel ? { channel: source.channel } : {}) }, from, to);
+}
+
+async function cuesOfSource(dir, m, e, from, to) {
const shadowExists = await hasShadowChannels(dir);
const file = cuePathFor(m, e, channelsDirFor(dir, m, { shadowExists }));
const doc = file ? await readCues(file) : null;
diff --git a/umtool/lib/report/blur.test.mjs b/umtool/lib/report/blur.test.mjs
@@ -0,0 +1,181 @@
+// A clip's picture blurred (report-to-video clip-blur.mjs), from umtool's side:
+// the writer (updateClip merges `blur` as it does `audio`; a default is not
+// written; a window save may not leave a partial blur's span outside), the
+// clip editor's `blur` op (token-guarded) and its view, a take's `--set
+// render.blur=off` (the uncensored variant), and New clip from selection --
+// the entry the timeline route's `insert` writes, its quote read from the
+// cues, its citation moved, a bad blur refused in the build's words.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { MANIFEST_NAME, StaleToken, StructureRefused, entryFromSpec, insertEntry, manifestToken, updateClip, updateRender } from "./manifest.mjs";
+import { clipEditorView, runClipEditorOp } from "./clipEditor.mjs";
+import { citeUrlAt, newClipEntry, nextFreeId, parseClipSpec, quoteFromCues, spanQuote } from "./clipEditorModel.mjs";
+import { patchFromSets } from "./takeMaker.mjs";
+import { mergePatch } from "umtool-report-to-video/montage-styles";
+import { BLUR_CAPTION_DEFAULT, clipBlurOf } from "umtool-report-to-video/clip-blur";
+import { validatorErrors } from "umtool-report-to-video/lint";
+
+const manifest = () => ({
+ schemaVersion: 1,
+ slug: "huck",
+ provenance: { channelSlug: "chan", siteOrigin: "https://example.test" },
+ render: { width: 640, height: 360, fps: 15 },
+ timeline: [
+ {
+ type: "clip", id: "eps-film-it", video: "BZCS-Azx_iE", start: 140.04, end: 228.35, cite: 140, section: 2,
+ citeUrl: "https://www.youtube.com/watch?v=BZCS-Azx_iE&t=140s", onscreen: { title: "He films it", subtitle: "a stream" }, quote: "q",
+ },
+ { type: "clip", id: "next", video: "BZCS-Azx_iE", start: 400, end: 410, section: 3 },
+ ],
+});
+
+async function project() {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-blur-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n");
+ return { id: "reports/huck", dir };
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+const entry = (m, id) => m.timeline.find((e) => e.id === id);
+
+test("updateClip blur: on, merged key by key, defaults not written, null clears; refused in the build's words", async () => {
+ const { dir } = await project();
+ try {
+ await updateClip(dir, "eps-film-it", { blur: { on: true } });
+ assert.deepEqual(entry(await read(dir), "eps-film-it").blur, { on: true });
+ await updateClip(dir, "eps-film-it", { blur: { caption: " Blurred for the platforms ", strength: "8", from: 150.004 } });
+ assert.deepEqual(entry(await read(dir), "eps-film-it").blur, { on: true, caption: "Blurred for the platforms", strength: 8, from: 150 });
+ // The default caption and strength are absent, not written.
+ await updateClip(dir, "eps-film-it", { blur: { caption: BLUR_CAPTION_DEFAULT, strength: 5, from: null } });
+ assert.deepEqual(entry(await read(dir), "eps-film-it").blur, { on: true });
+ await assert.rejects(updateClip(dir, "eps-film-it", { blur: { strength: 40 } }), /strength must be a number from 2 to 15/);
+ await assert.rejects(updateClip(dir, "eps-film-it", { blur: { to: 300 } }), /to 300 must lie inside the clip's window 140\.04–228\.35/);
+ await assert.rejects(updateClip(dir, "eps-film-it", { blur: { nope: 1 } }), /blur\.nope is not a blur setting/);
+ await assert.rejects(updateClip(dir, "next", { blur: { caption: "x" } }), /on must be true/, "a caption alone is not a blur");
+ // A window save may not leave a partial span outside.
+ await updateClip(dir, "eps-film-it", { blur: { from: 200, to: 220 } });
+ await assert.rejects(updateClip(dir, "eps-film-it", { end: 210 }), /to 220 must lie inside the clip's window/);
+ await updateClip(dir, "eps-film-it", { end: 225 });
+ // `on: false` (or null) and null clear it all.
+ await updateClip(dir, "eps-film-it", { blur: { on: false } });
+ assert.equal("blur" in entry(await read(dir), "eps-film-it"), false);
+ await updateClip(dir, "eps-film-it", { blur: { on: true } });
+ await updateClip(dir, "eps-film-it", { blur: null });
+ assert.equal("blur" in entry(await read(dir), "eps-film-it"), false);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("the clip editor's blur op: token-guarded, writes the key, the view carries it and what a new clip copies", async () => {
+ const p = await project();
+ try {
+ const view = await clipEditorView(p);
+ assert.deepEqual(view.blur, { caption: BLUR_CAPTION_DEFAULT, captionMax: 120, strength: { min: 2, max: 15, default: 5 }, rendered: true });
+ const c = view.clips.find((x) => x.id === "eps-film-it");
+ assert.equal(c.blur, null);
+ assert.equal(c.section, 2);
+ assert.equal(c.citeUrl, "https://www.youtube.com/watch?v=BZCS-Azx_iE&t=140s");
+ assert.equal(c.ownChannel, null);
+ await assert.rejects(runClipEditorOp(p, { op: "blur", clip: "eps-film-it", blur: { on: true }, token: "stale" }), StaleToken);
+ const out = await runClipEditorOp(p, { op: "blur", clip: "eps-film-it", blur: { on: true, caption: "Blurred here for TOS" }, token: view.token });
+ assert.deepEqual(entry(await read(p.dir), "eps-film-it").blur, { on: true, caption: "Blurred here for TOS" });
+ assert.deepEqual(out.view.clips.find((x) => x.id === "eps-film-it").blur, { on: true, caption: "Blurred here for TOS" });
+ await assert.rejects(runClipEditorOp(p, { op: "blur", clip: "eps-film-it", blur: "yes" }), /blur is \{ on: true/);
+ await runClipEditorOp(p, { op: "blur", clip: "eps-film-it", blur: null });
+ assert.equal("blur" in entry(await read(p.dir), "eps-film-it"), false);
+ // The uncensored variant in the Look: render.blur "off" (and "on" is no key at all).
+ await updateRender(p.dir, { blur: "off" });
+ assert.equal((await read(p.dir)).render.blur, "off");
+ assert.equal((await clipEditorView(p)).blur.rendered, false);
+ await updateRender(p.dir, { blur: "on" });
+ assert.equal("blur" in (await read(p.dir)).render, false);
+ await assert.rejects(updateRender(p.dir, { blur: "maybe" }), /render\.blur must be "on"/);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("a take's --set render.blur=off: the uncensored variant of the same cut", () => {
+ const m = manifest();
+ m.timeline[0].blur = { on: true };
+ const patch = patchFromSets(["render.blur=off"]);
+ assert.deepEqual(patch, { render: { blur: "off" } });
+ const take = mergePatch(m, patch);
+ assert.equal(take.render.blur, "off");
+ assert.deepEqual(validatorErrors(take).filter((e) => /blur/.test(e)), []);
+ assert.equal(clipBlurOf(take.timeline[0], take.render), null);
+ assert.notEqual(clipBlurOf(m.timeline[0], m.render), null, "the project's own cut stays blurred");
+});
+
+test("quoteFromCues: in order, a rolled-over cue said once, … where the cues are not adjacent", () => {
+ const cues = [
+ { start: 228, end: 231, text: "and then he" },
+ { start: 231, end: 233.5, text: "starts shaking" },
+ { start: 233.5, end: 235, text: "starts shaking" },
+ { start: 240, end: 242, text: "call the vet" },
+ { start: 300, end: 302, text: "out of span" },
+ ];
+ assert.equal(quoteFromCues(cues, 228.36, 298), "and then he starts shaking … call the vet");
+ assert.equal(quoteFromCues(cues, 228.36, 298, { gap: 10 }), "and then he starts shaking call the vet");
+ assert.equal(quoteFromCues([], 0, 10), "");
+ // The words win when there are any.
+ const words = [{ w: "only", start: 229, end: 229.5 }, { w: "words", start: 230, end: 230.5 }];
+ assert.equal(spanQuote({ words, cues }, 228.36, 298), "only words");
+ assert.equal(spanQuote({ words: [], cues }, 239, 243), "call the vet");
+});
+
+test("citeUrlAt, nextFreeId, parseClipSpec: the citation moved, an id the route would keep, the spec", () => {
+ assert.equal(citeUrlAt("https://www.youtube.com/watch?v=BZCS-Azx_iE&t=140s", 228.36), "https://www.youtube.com/watch?v=BZCS-Azx_iE&t=228s");
+ assert.equal(citeUrlAt("https://youtu.be/x?t=140", 228.9), "https://youtu.be/x?t=228");
+ assert.equal(citeUrlAt("https://rumble.com/v1.html#t=140", 228), "https://rumble.com/v1.html#t=228");
+ assert.equal(citeUrlAt("https://mirror.example/vod/1", 228), "https://mirror.example/vod/1", "no t= — kept, it may cite a mirror");
+ assert.equal(citeUrlAt("not a url", 5), "not a url");
+ assert.equal(nextFreeId(["eps-film-it", "next"], "eps-film-it"), "eps-film-it-2");
+ assert.equal(nextFreeId(["eps-film-it", "eps-film-it-2"], "eps-film-it"), "eps-film-it-3");
+ assert.equal(nextFreeId([], "new clip!"), "new-clip");
+ assert.deepEqual(parseClipSpec(" chan/BZCS-Azx_iE@228.36-298 "), { channel: "chan", video: "BZCS-Azx_iE", start: 228.36, end: 298 });
+ assert.equal(parseClipSpec("chan/vid"), null);
+ // The writer reads a spec by the same rule.
+ assert.deepEqual(entryFromSpec([], "chan/v1@3-6"), { type: "clip", id: "v1-3", channel: "chan", video: "v1", start: 3, end: 6 });
+});
+
+test("New clip from selection: the entry copies the recording, section, title and citation; inserted after the clip; a bad blur refused", async () => {
+ const p = await project();
+ try {
+ const view = await clipEditorView(p);
+ const like = view.clips.find((x) => x.id === "eps-film-it");
+ const e = newClipEntry(like, { start: 228.36, end: 298.004, id: "eps-film-it-2", quote: " and then he starts shaking ", blur: true });
+ assert.deepEqual(e, {
+ type: "clip", id: "eps-film-it-2", video: "BZCS-Azx_iE", start: 228.36, end: 298, cite: 228,
+ citeUrl: "https://www.youtube.com/watch?v=BZCS-Azx_iE&t=228s", section: 2, onscreen: { title: "He films it" },
+ quote: "and then he starts shaking", blur: { on: true },
+ });
+ // The default caption is written as none; a blank id is the route's to make.
+ assert.deepEqual(newClipEntry(like, { start: 1, end: 2, blur: { caption: BLUR_CAPTION_DEFAULT } }).blur, { on: true });
+ assert.equal("id" in newClipEntry(like, { start: 1, end: 2, id: " " }), false);
+ // An own channel is carried; the cut's provenance channel is not written.
+ assert.equal(newClipEntry({ ...like, ownChannel: "mirror" }, { start: 1, end: 2 }).channel, "mirror");
+
+ // The timeline route's insert (what the form posts): token-guarded, after the clip.
+ await assert.rejects(insertEntry(p.dir, "eps-film-it", e, { token: "stale" }), StaleToken);
+ const r = await insertEntry(p.dir, "eps-film-it", e, { token: await manifestToken(p.dir) });
+ assert.equal(r.id, "eps-film-it-2");
+ assert.equal(r.at, 1);
+ const m = await read(p.dir);
+ assert.deepEqual(m.timeline.map((x) => x.id), ["eps-film-it", "eps-film-it-2", "next"]);
+ assert.deepEqual(entry(m, "eps-film-it-2").blur, { on: true });
+ // The same id again: the route keeps the clip under a fresh one.
+ const again = await insertEntry(p.dir, "eps-film-it", e);
+ assert.equal(again.id, "eps-film-it-2-2");
+ // A blur the build would refuse is refused at the insert, in its words.
+ await assert.rejects(insertEntry(p.dir, "next", { ...e, id: "bad", blur: { on: true, strength: 99 } }), (err) => err instanceof StructureRefused && /strength must be a number from 2 to 15/.test(err.message));
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -48,6 +48,7 @@ import { readShorts } from "./shorts.mjs";
import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs";
import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { clipRoom } from "umtool-report-to-video/room";
+import { BLUR_CAPTION_DEFAULT, BLUR_CAPTION_MAX, BLUR_STRENGTH, renderBlurOn } from "umtool-report-to-video/clip-blur";
export { StaleToken, StructureRefused };
@@ -131,8 +132,16 @@ export async function clipEditorView(project) {
// with the entry that stamps it (plans/clip-marks.md).
...marksView(manifest, e),
audio: isObj(e.audio) ? e.audio : null,
+ // The clip's picture, blurred at the encode (clip-blur.mjs), as written.
+ blur: isObj(e.blur) ? e.blur : null,
// The deck's words for it as written (the live preview's fields): absent keys are automatic.
onscreen: isObj(e.onscreen) ? e.onscreen : null,
+ // What a new clip made from this one's recording copies (New clip from
+ // selection): its section, its citation link, and its channel AS
+ // WRITTEN (null: the cut's provenance channel).
+ section: e.section ?? null,
+ citeUrl: typeof e.citeUrl === "string" ? e.citeUrl : null,
+ ownChannel: typeof e.channel === "string" && e.channel ? e.channel : null,
};
});
const shorts = await readShorts(project.dir, manifest);
@@ -156,6 +165,9 @@ export async function clipEditorView(project) {
repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE },
shorts: Object.fromEntries(shorts.filter((x) => !x.gone).map((x) => [x.clip, { mtimeMs: x.mtimeMs, size: x.size, stale: x.stale }])),
room: roomViewOf(manifest.render),
+ // The blur's defaults and bounds (the Blur box's placeholders), and
+ // whether this cut draws it (render.blur "off": the uncensored variant).
+ blur: { caption: BLUR_CAPTION_DEFAULT, captionMax: BLUR_CAPTION_MAX, strength: BLUR_STRENGTH, rendered: renderBlurOn(manifest.render) },
knobs: { ...knobDefaultsOf(manifest.render), verdicts: markVerdictsOf(manifest) },
};
}
@@ -326,6 +338,9 @@ const num = (v, what) => {
* { clip, set: [mark, …] | null } all of them (manifest.mjs updateMarks)
* audio { clip, audio: { offset?, gain?, fadeIn?, fadeOut? } | null } the clip's sound
* (null on a key, or the whole: the default)
+ * blur { clip, blur: { on?, caption?, strength?, from?, to? } | null } the clip's
+ * picture blurred at the encode (null on a key: its
+ * default; null, or on: false, removes it)
* onscreen { clip, onscreen: { title?, subtitle? } | null } the deck's words for it
* (the live preview's fields; null: automatic)
* with `token` (the manifest's, from the view) on every manifest edit.
@@ -489,6 +504,15 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
structural = false;
break;
}
+ case "blur": {
+ // The clip's picture blurred (clip-blur.mjs): merged by updateClip, as
+ // `audio` is. A "trim" that leaves the cut where it is. Not structural.
+ const e = needClip();
+ if (body.blur !== null && !isObj(body.blur)) throw new OpError("blur is { on: true, caption?, strength?, from?, to? }, or null for none");
+ result = await updateClip(dir, e.id, { blur: body.blur }, { token, edit: "trim", now });
+ structural = false;
+ break;
+ }
case "onscreen": {
// The deck's title and subtitle for this clip (the live preview's
// fields), through the On-screen table's writer: a row replaces the
@@ -500,7 +524,7 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
break;
}
default:
- throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim, marks, audio or onscreen");
+ throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim, marks, audio, blur or onscreen");
}
let carried = null;
if (structural) {
diff --git a/umtool/lib/report/clipEditorModel.mjs b/umtool/lib/report/clipEditorModel.mjs
@@ -2,6 +2,7 @@
// server: snap points, a span's words, the proposals not in the cut, and a
// clip's provenance in words. No node imports -- a client component holds the
// same rules as the route.
+import { BLUR_CAPTION_DEFAULT } from "umtool-report-to-video/clip-blur";
/** @typedef {{ w?: string, word?: string, text?: string, start: number, end: number }} Word */
/** @typedef {{ start: number, end: number, text: string }} Cue */
@@ -146,3 +147,131 @@ export function edgeClock(s) {
const sec = (v % 60).toFixed(1).padStart(4, "0");
return h ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
}
+
+// ---------------------------------------------------------------------------
+// A NEW CLIP from a span of a recording (the clip editor's New clip from
+// selection, the timeline's Add clip): its quote, its citation, its id, and
+// the entry the timeline route's `insert` writes. Pure, so the page and a
+// test hold the same rule.
+// ---------------------------------------------------------------------------
+
+/**
+ * The cues spoken in [from, to] as one quote: in time order, a cue repeated
+ * word for word (a rolling caption) said once, and " … " where two cues are
+ * not adjacent (more than `gap` seconds of nothing between them) -- the words
+ * left out are marked, never run together.
+ * @param {Cue[] | null | undefined} cues
+ * @param {number} from
+ * @param {number} to
+ * @param {{ gap?: number }} [o]
+ */
+export function quoteFromCues(cues, from, to, { gap = 1 } = {}) {
+ const inSpan = (Array.isArray(cues) ? cues : [])
+ .filter((c) => c && fin(c.start) && fin(c.end) && c.end > from + 0.05 && c.start < to - 0.05)
+ .sort((a, b) => a.start - b.start);
+ let out = "";
+ let prev = null;
+ for (const c of inSpan) {
+ const text = String(c.text ?? "").replace(/\s+/g, " ").trim();
+ if (!text) continue;
+ if (prev && text === prev.text) {
+ prev = { text, end: Math.max(prev.end, c.end) };
+ continue;
+ }
+ out += prev ? (c.start - prev.end > gap ? " … " : " ") + text : text;
+ prev = { text, end: c.end };
+ }
+ return out;
+}
+
+/**
+ * A span's quote: from the word timings when there are any (quoteBetween), else the cues (quoteFromCues).
+ * @param {{ words?: Word[] | null, cues?: Cue[] | null }} o
+ * @param {number} from
+ * @param {number} to
+ */
+export function spanQuote({ words = null, cues = null }, from, to) {
+ return Array.isArray(words) && words.length ? quoteBetween({ words }, from, to) : quoteFromCues(cues, from, to);
+}
+
+/**
+ * A citation link moved to another second: its `t=` (query or fragment)
+ * replaced, in the form it had (`t=140s` stays seconds-with-an-s). A link
+ * with no `t=` is kept as it is -- it may cite a mirror on purpose.
+ * @param {string} url
+ * @param {number} sec
+ */
+export function citeUrlAt(url, sec) {
+ const s = Math.max(0, Math.floor(sec));
+ let u;
+ try {
+ u = new URL(url);
+ } catch {
+ return url;
+ }
+ if (u.searchParams.has("t")) {
+ const was = u.searchParams.get("t") ?? "";
+ u.searchParams.set("t", /^\d+s$/.test(was) ? `${s}s` : String(s));
+ return u.toString();
+ }
+ if (/(^#|&)t=/.test(u.hash)) {
+ u.hash = u.hash.replace(/(^#|&)t=[^&]*/, (_m, lead) => `${lead}t=${s}`);
+ return u.toString();
+ }
+ return url;
+}
+
+/** An id not yet among `ids`: `base`, else `base-2`, `base-3`, … (manifest.mjs freshEntryId's rule). */
+export function nextFreeId(ids, base) {
+ const clean = String(base).replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 56) || "entry";
+ const taken = new Set(ids);
+ if (!taken.has(clean)) return clean;
+ for (let n = 2; ; n += 1) if (!taken.has(`${clean}-${n}`)) return `${clean}-${n}`;
+}
+
+/** `<channel>/<video>@<start>-<end>`, in seconds: a clip spec (the timeline route's `insert`). */
+export const CLIP_SPEC_RE = /^([A-Za-z0-9._-]+)\/([^@\s/]+)@(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/;
+
+/** A clip spec parsed, or null when it is not one. */
+export function parseClipSpec(spec) {
+ const mm = String(spec ?? "").trim().match(CLIP_SPEC_RE);
+ if (!mm) return null;
+ return { channel: mm[1], video: mm[2], start: Number(mm[3]), end: Number(mm[4]) };
+}
+
+/**
+ * The entry a new clip is inserted as (POST /api/report/timeline
+ * `{op: "insert", afterId, entry}`): `from` the recording the clip `like` is
+ * on -- its video, its channel as written, its section, its deck title, its
+ * citation link moved to the new second -- over [start, end], cited at
+ * floor(start). `id` blank: the route gives it a fresh one. `blur`: true, or
+ * a caption, puts the picture's blur on it (clip-blur.mjs; the default
+ * caption is written as none).
+ *
+ * @param {{ video: string, ownChannel?: string | null, channel?: string | null, section?: unknown, citeUrl?: string | null, onscreen?: { title?: string } | null }} like
+ * @param {{ start: number, end: number, id?: string, quote?: string, blur?: boolean | { caption?: string } }} o
+ */
+export function newClipEntry(like, { start, end, id = "", quote = "", blur = false }) {
+ const a = r2(start);
+ const b = r2(end);
+ const cite = Math.floor(a);
+ const channel = like.ownChannel ?? null;
+ const title = typeof like.onscreen?.title === "string" && like.onscreen.title.trim() ? like.onscreen.title.trim() : null;
+ const q = String(quote ?? "").trim();
+ const given = blur && typeof blur === "object" && typeof blur.caption === "string" ? blur.caption.trim() : "";
+ const caption = given === BLUR_CAPTION_DEFAULT ? "" : given;
+ return {
+ type: "clip",
+ ...(String(id).trim() ? { id: String(id).trim() } : {}),
+ ...(channel ? { channel } : {}),
+ video: like.video,
+ start: a,
+ end: b,
+ cite,
+ ...(typeof like.citeUrl === "string" && like.citeUrl ? { citeUrl: citeUrlAt(like.citeUrl, cite) } : {}),
+ ...(like.section !== undefined && like.section !== null ? { section: like.section } : {}),
+ ...(title ? { onscreen: { title } } : {}),
+ ...(q ? { quote: q } : {}),
+ ...(blur ? { blur: { on: true, ...(caption ? { caption } : {}) } } : {}),
+ };
+}
diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts
@@ -38,8 +38,19 @@ export type EditorClip = {
audio?: ClipAudio | null;
/** The deck's words for the clip as written (absent keys are automatic): the live preview's fields. */
onscreen?: { title?: string; subtitle?: string } | null;
+ /** The clip's picture blurred at the encode (clip-blur.mjs), as written. */
+ blur?: ClipBlur | null;
+ /** What a new clip from this one's recording copies: its section, its citation link, its channel as written. */
+ section?: number | string | null;
+ citeUrl?: string | null;
+ ownChannel?: string | null;
};
+/** A clip's blur: on, the caption drawn on the blurred picture, its strength (% of the picture's height), a partial span (source seconds). */
+export type ClipBlur = { on: true; caption?: string; strength?: number; from?: number; to?: number };
+/** The blur's defaults and bounds, and whether this cut draws it (render.blur "off": the uncensored variant). */
+export type BlurDefaults = { caption: string; captionMax: number; strength: { min: number; max: number; default: number }; rendered: boolean };
+
/** A claim with its knobs (plans/video-knobs-plan.md): `at` is a source second. */
export type ClaimKnobs = { id: string; verdict: string; at?: number; hold?: number; stamp?: boolean; count?: number; label?: string };
/** A mark as the clip editor shows it: its knobs, and the clip that stamps it (the last carrying its id). */
@@ -75,6 +86,8 @@ export type EditorView = {
room?: { tail: boolean; head: boolean; minGap: number | null; maxS: number | null; join: number };
/** The claim knobs' defaults (video knobs). */
knobs?: KnobDefaults;
+ /** The blur's defaults and bounds (video knobs). */
+ blur?: BlurDefaults;
};
export type Turn = { start: number; end: number; speaker: number };
diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs
@@ -9,6 +9,8 @@
// marks=<json> mark.add=<verdict>[@<sec>] mark.remove=<id>
// mark.verdict=<verdict> (plans/clip-marks.md)
// audio.offset audio.gain audio.fadeIn audio.fadeOut
+// blur.on blur.caption blur.strength blur.from blur.to
+// (`blur.on=` clears the whole blur; report-to-video clip-blur.mjs)
// umtool look <project> key=value … factcheck.stamp.<k>, factcheck.verdicts.<V>.<k>,
// deck.markers=<json>, deck.markerLayout=…, variants=<json>,
// and the look's keys (transition=0.3, …)
@@ -38,8 +40,9 @@ import { variantsSteps } from "./driver.mjs";
import { outDirOf, variantsState } from "./variantsView.mjs";
export const AUDIO_KNOBS = Object.freeze(["offset", "gain", "fadeIn", "fadeOut"]);
+export const BLUR_KNOBS = Object.freeze(["on", "caption", "strength", "from", "to"]);
const MARK_KEYS = ["marks", "mark.add", "mark.remove", "mark.verdict"];
-const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), "layout"];
+const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout"];
export const SET_USAGE = [
"usage: umtool set <project> <clip> key=value … [--mark <id>] [--json]",
@@ -52,7 +55,12 @@ export const SET_USAGE = [
" mark.remove=<id>; mark.verdict=<verdict> (the first mark's, or --mark <id>'s; every clip carrying",
" the id); marks='[{\"id\":\"c1\",\"verdict\":\"CORROBORATED\",\"at\":190.2},…]' sets them all (`marks=` none).",
" audio.offset ms (-2000…2000, + = sound later),",
- " audio.gain dB (-20…20), audio.fadeIn / audio.fadeOut s (0–5). layout=finale|clip (the deck's finale",
+ " audio.gain dB (-20…20), audio.fadeIn / audio.fadeOut s (0–5).",
+ " blur.on=true blurs the clip's picture at the encode (the sound untouched; `blur.on=` clears the whole blur);",
+ " blur.caption=\"…\" (≤ 120 chars, drawn on the blurred picture; default \"Original footage uncensored, blurred",
+ " here for TOS\"); blur.strength 2–15 (% of the picture's height; default 5); blur.from / blur.to: source",
+ " seconds inside the clip's window, to blur only that span. render.blur=off (umtool look, or a take's",
+ " --set) renders every clip unblurred: the uncensored variant. layout=finale|clip (the deck's finale",
" layout for this clip; clip is the default). `key=` clears it (the default).",
].join("\n");
@@ -134,6 +142,8 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if (flags.has("--mark") && !mark) throw new CliError("--mark needs a mark id");
const claim = {};
const audio = {};
+ /** @type {Record<string, unknown>} */
+ const blur = {};
/** @type {Record<string, unknown>[]} the marks changes, in the order given */
const markChanges = [];
/** @type {Record<string, unknown>} */
@@ -149,9 +159,12 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
continue;
}
const [group, k] = key.split(".");
- (group === "claim" ? claim : audio)[k] = value;
+ if (group === "blur") blurAssign(blur, k, value);
+ else (group === "claim" ? claim : audio)[k] = value;
}
if (Object.keys(audio).length) entryPatch.audio = audio;
+ // `blur.on=` (or false): no blur at all, whatever else was given.
+ if (Object.keys(blur).length) entryPatch.blur = "on" in blur && (blur.on === null || blur.on === false) ? null : blur;
const results = {};
let notes = null;
for (const change of markChanges) {
@@ -174,6 +187,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
const token = await manifestToken(project.dir);
const { result, editNotes } = await withEditNotes(project, () => updateClip(project.dir, clipId, entryPatch, { token, edit: "trim" }));
if ("audio" in entryPatch) results.audio = result.entry.audio ?? null;
+ if ("blur" in entryPatch) results.blur = result.entry.blur ?? null;
if ("layout" in entryPatch) results.layout = result.entry.layout ?? "clip";
notes = editNotes ?? notes;
}
@@ -190,6 +204,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if (!results.stamps) out(` NOTE: ${results.claim.id} stamps on ${results.stampsOn} (the last clip carrying it) — these knobs are read there, not here`);
}
if ("audio" in results) out(`${clipId}: audio ${results.audio ? JSON.stringify(results.audio) : "as recorded"}`);
+ if ("blur" in results) out(`${clipId}: blur ${results.blur ? JSON.stringify(results.blur) : "none (the picture as recorded)"}`);
if ("layout" in results) out(`${clipId}: layout ${results.layout}`);
const n = noted(notes);
if (n) out(n);
@@ -203,6 +218,17 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
/**
+ * One `blur.*` assignment into the blur patch: a caption is text whatever it
+ * parses as (`blur.caption=2025` is the words "2025"); `blur.on=true` turns it
+ * on; the numbers as given (the writer refuses what the build would).
+ */
+export function blurAssign(blur, k, value) {
+ if (k === "caption" && value !== null) blur.caption = String(value);
+ else blur[k] = value;
+ return blur;
+}
+
+/**
* One `mark.*` / `marks` assignment as an updateMarks change: `mark.add=Episodes@190.2`
* (or a JSON object), `mark.remove=<id>`, `mark.verdict=<verdict>` (for --mark's
* id, else the clip's first mark), `marks=<json list>` (`marks=` none).
@@ -401,7 +427,8 @@ export function knobsOf(manifest) {
const first = all[0] ?? null;
const claim = first ? Object.fromEntries(CLAIM_KNOBS.filter((k) => first[k] !== undefined).map((k) => [k, first[k]])) : null;
const audio = isObj(e.audio) ? e.audio : null;
- if ((claim && Object.keys(claim).length) || audio || first || typeof e.layout === "string") {
+ const blur = isObj(e.blur) ? e.blur : null;
+ if ((claim && Object.keys(claim).length) || audio || blur || first || typeof e.layout === "string") {
clips.push({
id: e.id,
...(e.variant ? { variant: e.variant } : {}),
@@ -409,6 +436,7 @@ export function knobsOf(manifest) {
...(claim && Object.keys(claim).length ? { claim } : {}),
...(all.length > 1 ? { marks: all.map((m) => ({ ...m, stampsOn: stampingEntryId(manifest, m.id) })) } : {}),
...(audio ? { audio } : {}),
+ ...(blur ? { blur } : {}),
...(typeof e.layout === "string" ? { layout: e.layout } : {}),
});
}
@@ -425,6 +453,8 @@ export function knobsOf(manifest) {
markerLayout: deck?.markerLayout ?? null,
variants: variantsOf(manifest?.render),
variantsDefault: !Array.isArray(manifest?.render?.variants),
+ // render.blur "off": the uncensored variant (every clip's blur not drawn).
+ blurOff: manifest?.render?.blur === "off",
};
}
@@ -441,12 +471,14 @@ export function knobsLines(manifest) {
}
if (c.layout) bits.push(`layout ${c.layout}`);
if (c.audio) bits.push(`audio ${Object.entries(c.audio).map(([a, b]) => `${a}=${b}`).join(" ")}`);
+ if (c.blur) bits.push(`blur ${Object.entries(c.blur).filter(([a]) => a !== "on").map(([a, b]) => `${a}=${JSON.stringify(b)}`).join(" ") || "on"}${k.blurOff ? " (not drawn: render.blur off)" : ""}`);
lines.push(` ${String(c.id).padEnd(8)} ${bits.join(" · ")}`);
}
if (Object.keys(k.stamp).length) lines.push(` stamp ${Object.entries(k.stamp).map(([a, b]) => `${a}=${b}`).join(" ")}`);
if (Object.keys(k.stampLabels).length) lines.push(` stamp word ${Object.entries(k.stampLabels).map(([a, b]) => `${a}=${b}`).join(" ")}`);
if (k.markers.length) lines.push(` markers ${k.markers.map((m) => `${m.after}:"${m.label}"${m.align ? `(${m.align})` : ""}`).join(" ")}${k.markerLayout ? ` · layout ${k.markerLayout}` : ""}`);
lines.push(` variants ${k.variants.map((v) => v.name).join(", ")}${k.variantsDefault ? " (default)" : ""}`);
+ if (k.blurOff) lines.push(" blur off (render.blur: the uncensored variant — no clip is blurred)");
return lines;
}
diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs
@@ -128,3 +128,34 @@ test("umtool variants: refuses an unbuilt cut; makes the ladder (stub encoder) a
assert.deepEqual(s.made.items.map((i) => i.name), ["master", "1080p", "720p", "fit24"]);
assert.equal(s.sync.items[0].flagged, true);
});
+
+test("umtool set blur.*: on, caption (text whatever it parses as), strength, a span; blur.on= clears it all; render.blur=off by umtool look", async () => {
+ const dir = await project("blur");
+ const { lines, run } = runner(setCommand);
+ assert.equal(await run("blur", "c02", "blur.on=true", "blur.caption=Blurred here for TOS", "blur.strength=8", "blur.from=31.5", "blur.to=40"), 0, lines.join("\n"));
+ assert.deepEqual((await read(dir)).timeline[1].blur, { on: true, caption: "Blurred here for TOS", strength: 8, from: 31.5, to: 40 });
+ assert.match(lines.at(-1), /^c02: blur \{"on":true,"caption":"Blurred here for TOS"/);
+ assert.equal(await run("blur", "c02", "blur.caption=2025", "blur.from=", "blur.to="), 0);
+ assert.deepEqual((await read(dir)).timeline[1].blur, { on: true, caption: "2025", strength: 8 });
+ assert.equal(await run("blur", "c02", "blur.strength=40"), 1);
+ assert.match(lines.at(-1), /strength must be a number from 2 to 15/);
+ assert.equal(await run("blur", "c02", "blur.to=99"), 1);
+ assert.match(lines.at(-1), /must lie inside the clip's window 30–41/);
+ assert.equal(await run("blur", "c02", "blur.sigma=3"), 2);
+ assert.match(lines.at(-1), /not a clip knob/);
+ // what `umtool show` prints
+ const m = await read(dir);
+ assert.deepEqual(knobsOf(m).clips.find((c) => c.id === "c02").blur, { on: true, caption: "2025", strength: 8 });
+ assert.ok(knobsLines(m).some((l) => /c02\s.*blur caption="2025" strength=8/.test(l)), knobsLines(m).join("\n"));
+ // The uncensored variant: render.blur off, through the look's writer.
+ const look = runner(lookCommand);
+ assert.equal(await look.run("blur", "blur=off"), 0, look.lines.join("\n"));
+ assert.equal((await read(dir)).render.blur, "off");
+ assert.ok(knobsLines(await read(dir)).some((l) => /blur\s+off \(render\.blur/.test(l)));
+ assert.equal(await look.run("blur", "blur=on"), 0);
+ assert.equal("blur" in (await read(dir)).render, false);
+ // blur.on= clears the whole key.
+ assert.equal(await run("blur", "c02", "blur.on="), 0);
+ assert.equal("blur" in (await read(dir)).timeline[1], false);
+ assert.match(lines.at(-1), /c02: blur none/);
+});
diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs
@@ -46,7 +46,7 @@ const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NA
test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => {
const p = await project({ transition: 0.4, crf: 21 });
try {
- assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide"]);
+ assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur"]);
const token = await manifestToken(p.dir);
const r = await updateRender(p.dir, {
headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack",
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -37,9 +37,11 @@ import { verticalErrors } from "umtool-report-to-video/look";
import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
import { validateRoom } from "umtool-report-to-video/room";
import { applySectionEnter } from "./sections.mjs";
+import { parseClipSpec } from "./clipEditorModel.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
import { validateFinaleEntries } from "umtool-report-to-video/finale";
import { validateClipAudio } from "umtool-report-to-video/clip-audio";
+import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH, validateClipBlur, validateClipBlurEntries } from "umtool-report-to-video/clip-blur";
import {
CLAIM_KNOBS, CLAIM_MARKS_MAX, claimKnobsOf, claimKnobValue, freshMarkId, marksCopyOf, normalizeClaimKnobPatch, rawMarksOf, setMarks, stampingEntryId,
variantsProblems, verdictOfInput,
@@ -391,6 +393,44 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri
}
}
+ // ---- the clip's picture, blurred (video knobs) ---------------------------
+ //
+ // `blur: { on: true, caption?, strength?, from?, to? }` -- applied at the
+ // segment encode (report-to-video clip-blur.mjs, whose validateClipBlur is
+ // the check, against the window as patched). Merged into what the clip
+ // has, as `audio` is: a key set to null removes it; `blur: null` (or "",
+ // or `on` null/false) removes it all. A caption or strength at its default
+ // is removed (absent says it), and so are a caption's outer spaces.
+ if (patch.blur !== undefined) {
+ const v = patch.blur;
+ if (v === null || v === "" || (isObj(v) && (v.on === null || v.on === false || v.on === ""))) delete entry.blur;
+ else {
+ if (!isObj(v)) throw new Error("blur must be { on: true, caption?, strength?, from?, to? }, or null to clear it");
+ const next = { ...(isObj(entry.blur) ? entry.blur : {}) };
+ for (const [k, x] of Object.entries(v)) {
+ if (x === null || x === "") delete next[k];
+ else if (k === "on" && x === "true") next.on = true;
+ else if (["strength", "from", "to"].includes(k) && typeof x === "string") next[k] = Number(x);
+ else next[k] = x;
+ }
+ if (typeof next.caption === "string") next.caption = next.caption.trim();
+ if (next.caption === BLUR_CAPTION_DEFAULT || next.caption === "") delete next.caption;
+ if (typeof next.strength === "number") next.strength = Number(next.strength.toFixed(1));
+ if (next.strength === BLUR_STRENGTH.default) delete next.strength;
+ for (const k of ["from", "to"]) if (typeof next[k] === "number" && Number.isFinite(next[k])) next[k] = round2(next[k]);
+ const errors = validateClipBlur(next, "blur", entry);
+ if (errors.length) throw new Error(errors.join("; "));
+ // `on` first: the manifests are read by humans.
+ const { on, ...rest } = next;
+ entry.blur = { on, ...rest };
+ }
+ } else if ((patch.start !== undefined || patch.end !== undefined) && isObj(entry.blur)) {
+ // A window save that leaves a partial blur's span outside is refused, as
+ // a claim's `at` is: the span no longer says anything about the clip.
+ const errors = validateClipBlur(entry.blur, "blur", entry);
+ if (errors.length) throw new Error(errors.join("; "));
+ }
+
// ---- how the deck lays this entry out -----------------------------------
//
// `layout: "finale"` (the deck's finale layout, render.chrome.deck.finale);
@@ -1339,6 +1379,8 @@ function structureErrors(manifest) {
...validateDrafted(manifest),
...validatePublish(manifest),
...validateAssist(manifest),
+ // A clip inserted with a `blur` (the clip editor's New clip) is checked as the build checks it.
+ ...validateClipBlurEntries(manifest),
];
}
@@ -1433,8 +1475,8 @@ export async function duplicateEntry(dir, id, { token = null, at = null } = {})
});
}
-/** `<channel>/<video>@<start>-<end>`, in seconds. */
-const CLIP_SPEC_RE = /^([A-Za-z0-9._-]+)\/([^@\s/]+)@(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/;
+// `<channel>/<video>@<start>-<end>`, in seconds: clipEditorModel.mjs's
+// parseClipSpec, the rule the timeline's Add clip form reads a spec with too.
/**
* What `insertEntry` will put in the timeline, checked: a clip spec string
@@ -1446,10 +1488,9 @@ const CLIP_SPEC_RE = /^([A-Za-z0-9._-]+)\/([^@\s/]+)@(\d+(?:\.\d+)?)-(\d+(?:\.\d
*/
export function entryFromSpec(timeline, spec) {
if (typeof spec === "string") {
- const mm = spec.trim().match(CLIP_SPEC_RE);
- if (!mm) throw new Error("a clip is <channel>/<video>@<start>-<end> in seconds");
- const [, channel, video, s, e] = mm;
- return clipEntry(timeline, { type: "clip", channel, video, start: Number(s), end: Number(e) });
+ const c = parseClipSpec(spec);
+ if (!c) throw new Error("a clip is <channel>/<video>@<start>-<end> in seconds");
+ return clipEntry(timeline, { type: "clip", ...c });
}
if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new Error("an entry is an object, or a clip spec string");
const entry = JSON.parse(JSON.stringify(spec));
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -153,6 +153,7 @@ import {
import { fxOn, fxQuoteSpan, resolveFx, fxWhipJoins, fxWipeJoins, fxWordsOf, fxZoomJoins, validateFxEntries } from "./fx.mjs";
import { marksOf, stampsDrawn, validateClaims } from "./factcheck.mjs";
import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs";
+import { blurCaptionLayout, blurPictureFilters, blurProblems, blurRecordOf, blurSpan, clipBlurOf, fittedSize, validateClipBlurEntries } from "./clip-blur.mjs";
import { validateFinaleEntries } from "./finale.mjs";
import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs";
import { validateThreadEntries } from "./threads.mjs";
@@ -355,9 +356,13 @@ export function headerFilters(render, attribPath, channelPath = null) {
* Two runs, not one string, because a still lays itself out INTO the box (a
* row of panels, a crawl) and only needs the second half.
*
+ * `picture`: filters on the picture as it plays -- scaled, not yet padded --
+ * (a clip's blur, clip-blur.mjs), so the pad and everything laid over the
+ * frame later are untouched by them. None: the run as it always was.
+ *
* Pure, and exported, so the numbers can be tested without an encoder.
*/
-export function deckFraming(render, { feed = false } = {}) {
+export function deckFraming(render, { feed = false, picture = [] } = {}) {
const { W, H, footage: deckBox } = deckGeometry(render);
// The posts feed's footage box stands beside its column (feedGeometry);
// every footage segment of a feed cut is framed there, for the whole cut.
@@ -367,6 +372,7 @@ export function deckFraming(render, { feed = false } = {}) {
box: f,
fit: [
`scale=${f.width}:${f.height}:force_original_aspect_ratio=decrease`,
+ ...picture,
`pad=${f.width}:${f.height}:(ow-iw)/2:(oh-ih)/2:color=${bg}`,
],
place: [`pad=${W}:${H}:${f.x}:${f.y}:color=${bg}`, "setsar=1", `fps=${render.fps}`],
@@ -389,6 +395,29 @@ export function segmentFraming(render, feed = false) {
return { layout: feed ? "feed" : "deck", box: deckFraming(render, { feed }).box };
}
+/**
+ * A clip's picture with no deck: scaled into the picture area (`VW` × `VH`,
+ * left of any rail column), `picture`'s filters on it as it plays (a clip's
+ * blur), padded to the frame under the header band, the header drawn last.
+ * The footer, the bar, the QR and the brand's mark are overlaid after this,
+ * from inputs of their own. Pure, and exported so a test can read it.
+ */
+export function clipBaseFilters({ render, VW, VH, HH, hasHeader, attribPath, channelPath = null, picture = [] }) {
+ const pal = render.palette;
+ const { width, height } = render;
+ return [
+ `scale=${VW}:${VH}:force_original_aspect_ratio=decrease`,
+ ...picture,
+ `pad=${VW}:${VH}:(ow-iw)/2:(oh-ih)/2:color=${pal.bg}`,
+ // Widen back to the full frame, leaving the rail column (if any) as ground.
+ `pad=${width}:${VH}:0:0:color=${pal.bg}`,
+ `pad=${width}:${height}:0:${HH}:color=${pal.bg}`,
+ "setsar=1",
+ `fps=${render.fps}`,
+ ...(hasHeader ? headerFilters(render, attribPath, channelPath) : []),
+ ];
+}
+
/** Is this entry's segment framed into the footage box under the deck (rather than full frame)? */
export function framedUnderDeck(entry, render) {
if (entry.type === "clip" || entry.type === "image") return true;
@@ -1174,7 +1203,6 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// source cannot be had leaves this take's segment as it was.
await detachSegmentFiles(path.join(outDir, "segments"), entry.id);
const seg = path.join(outDir, "segments", `${entry.id}.mp4`);
- const pal = render.palette;
const { width, height } = render;
// EXTENT vs CUT.
@@ -1335,9 +1363,34 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
: audioPosterInput({ entry, meta, provenance, render, outDir, box, seconds: posterSeconds })
.then((input) => ({ input, parts: audioPosterParts({ posterIdx, box, render }) }));
+ // THE CLIP'S BLUR (clip-blur.mjs): its source picture blurred where it
+ // plays -- scaled, not yet padded into the frame -- and the caption drawn on
+ // it, so the pad, the header, the footer, the QR and everything laid over
+ // the cut later stay sharp. The sound is not touched. None (no `blur`, or
+ // render.blur "off"): every chain below is the one it always was.
+ const blur = clipBlurOf(entry, render);
+ if (blur && !media.hasVideo) EMIT("note", { message: `${entry.id}: no picture to blur in ${path.basename(raw)} — the poster plays as it is` });
+ const span = media.hasVideo ? blurSpan(blur, fetchStart + segA, segB - segA) : null;
+ if (blur) cutRecord.blur = blurRecordOf(blur);
+ /** The blur's filters for a picture fitted into `bw` × `bh` (empty: none). */
+ const blurPicture = async (bw, bh) => {
+ if (!span) return [];
+ const [sw, sh] = await probeDims(raw);
+ const { w, h } = fittedSize(sw, sh, bw, bh);
+ const layout = blurCaptionLayout(blur.caption, w, h);
+ const lineFiles = [];
+ for (const [k, line] of layout.lines.entries()) {
+ const file = path.join(outDir, "segments", `${entry.id}.blur-${k}.txt`);
+ await writeFile(file, line, "utf8");
+ lineFiles.push(file);
+ }
+ return blurPictureFilters({ blur, span, h, layout, lineFiles, render });
+ };
+
if (deckOn(render)) {
const fr = framing ?? segmentFraming(render);
const pst = await poster(fr.box, 1);
+ const picture = await blurPicture(fr.box.width, fr.box.height);
await execFileP(
FFMPEG,
[
@@ -1347,7 +1400,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
...(soundInput ?? []),
"-filter_complex", [
...levelParts(pst ? pst.parts : null, soundInput ? `[${pst ? 2 : 1}:a]` : "[0:a]"),
- `${pst ? "[pic]" : "[0:v]"}${deckFramingFilter(render, { feed: fr.layout === "feed" })}[v]`,
+ `${pst ? "[pic]" : "[0:v]"}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}[v]`,
].join(";"),
"-map", "[v]", "-map", audioMap,
...encodeArgs(render),
@@ -1407,16 +1460,10 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const shortPicture = dirs.short && media.hasVideo
? verticalFilters(entry.vertical?.crop ?? null, ...(await probeDims(raw)), { width, height, fps: render.fps })
: null;
- const base = shortPicture ? shortPicture.join(",") : [
- `scale=${VW}:${VH}:force_original_aspect_ratio=decrease`,
- `pad=${VW}:${VH}:(ow-iw)/2:(oh-ih)/2:color=${pal.bg}`,
- // Widen back to the full frame, leaving the rail column (if any) as ground.
- `pad=${width}:${VH}:0:0:color=${pal.bg}`,
- `pad=${width}:${height}:0:${HH}:color=${pal.bg}`,
- "setsar=1",
- `fps=${render.fps}`,
- ...(hasHeader ? headerFilters(render, attribPath, channelPath) : []),
- ].join(",");
+ // The blur on the picture alone (a short's is the whole frame: no header).
+ const base = shortPicture
+ ? [...shortPicture, ...(await blurPicture(width, height))].join(",")
+ : clipBaseFilters({ render, VW, VH, HH, hasHeader, attribPath, channelPath, picture: await blurPicture(VW, VH) }).join(",");
// A manifest with a RAIL draws the code in the rail's foot instead, as one
// more strip: bottom-right of the frame, bordered, one per clip. It used to
@@ -5350,7 +5397,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole),
...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole),
...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole), ...validateTransitionStyle(whole),
- ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateFinaleEntries(whole),
+ ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
@@ -5865,7 +5912,12 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
{
const present = entries.map((_, i) => i).filter((i) => !missing.includes(i));
const records = await Promise.all(present.map((i) => readCutRecord(segs[i])));
- const problems = framingProblems({ entries: present.map((i) => entries[i]), records, render, want: framing });
+ const problems = [
+ ...framingProblems({ entries: present.map((i) => entries[i]), records, render, want: framing }),
+ // 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 }),
+ ];
if (problems.length) throw new Error(`${what}: ${problems.join("; ")}`);
}
for (const i of missing) {
@@ -6165,9 +6217,15 @@ async function buildThumbnail(manifest, dirs, manifestDir) {
throw new Error(`no cached window of ${clip.video} holds ${at}s — fetch or build ${clip.id} first`);
}
still = path.join(work, "_thumb-frame.png");
+ // A clip blurred at that second (clip-blur.mjs) is blurred in its still
+ // too: the thumbnail is the first thing a platform's reviewer sees.
+ 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;
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`] : []),
"-frames:v", "1", still,
]);
}
diff --git a/umtool/report-to-video/clip-blur.mjs b/umtool/report-to-video/clip-blur.mjs
@@ -0,0 +1,252 @@
+// A clip's picture, blurred at its segment encode -- the per-clip `blur` knob
+// and the cut's `render.blur` switch.
+//
+// timeline entry: "blur": { "on": true, "caption": "…", "strength": 5, "from": 230.5, "to": 260 }
+// render: "blur": "off" (the uncensored variant; absent = "on")
+//
+// Why: a clip whose source picture shows something a platform's graphic-
+// content rules refuse (the operator's case, 2026-10-23: a dog having a
+// seizure) still has to be in the cut -- its SOUND is the evidence -- and the
+// cut still has to be shareable. So the source picture is blurred and a line
+// says so ("Original footage uncensored, blurred here for TOS"); the sound is
+// never touched. A take with `render.blur: "off"` renders the same cut
+// uncensored, beside it.
+//
+// ONLY THE SOURCE PICTURE. The blur is applied to the clip's picture after it
+// is scaled to the size it plays at and BEFORE it is padded into the frame:
+// the pad, the citation header, the footer, the QR, the rail, the deck (laid
+// over the whole concat later), the speaker captions (burned over the
+// finished frame) and the stamps are all drawn after it, so none of them is
+// blurred. The caption is drawn on the blurred picture itself, top centre, in
+// the deck's face (render.fontBold, as the montage's overlays are).
+//
+// `strength` is the Gaussian's sigma as a PERCENT of the picture's height as
+// it plays (2–15, default 5): 54 px on a 1080-line picture, ~40 px in the
+// deck's footage box. Measured on the picture after its scale, so the same
+// number blurs alike at any source resolution, and every variant made from
+// the master (720p, fit24) is a downscale of an already blurred picture.
+//
+// `from` / `to` (source seconds, inside the clip's window) blur only that span
+// -- either alone runs to the clip's edge -- and the caption shows over that
+// span only. Without them the whole clip is blurred.
+//
+// No imports from build-video.mjs: it imports this file, and so do the lint and
+// umtool's writers (updateClip validates through validateClipBlur). The
+// cut's switch (`render.blur`) is one of the look's keys: its rules are the
+// common look.mjs's, re-exported here.
+import { RENDER_BLUR_VALUES, renderBlurOn, validateRenderBlur } from "yt-dlp-transcript-common/lib/report/look.mjs";
+
+export { RENDER_BLUR_VALUES, renderBlurOn, validateRenderBlur };
+
+/** What a caption says when the clip sets none. */
+export const BLUR_CAPTION_DEFAULT = "Original footage uncensored, blurred here for TOS";
+export const BLUR_CAPTION_MAX = 120;
+/** sigma, as a percent of the picture's height. */
+export const BLUR_STRENGTH = Object.freeze({ min: 2, max: 15, default: 5 });
+/** The keys a clip's `blur` may carry. */
+export const CLIP_BLUR_KEYS = Object.freeze(["on", "caption", "strength", "from", "to"]);
+/** The shortest span a partial blur may cover (s). */
+export const BLUR_SPAN_MIN = 0.2;
+/** The window tolerance a stored 2 dp edge gets (the writer's and the build's). */
+const EPS = 0.02;
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const q = (v) => JSON.stringify(v);
+
+/**
+ * Every reason a clip's `blur` cannot be used, as sentences naming `where`
+ * (empty: it can). `undefined` / `null` is none. Unknown keys are refused.
+ * With `entry`, `from`/`to` are checked against its window too.
+ *
+ * @param {unknown} blur
+ * @param {string} [where]
+ * @param {{ start?: number, end?: number } | null} [entry]
+ * @returns {string[]}
+ */
+export function validateClipBlur(blur, where = "blur", entry = null) {
+ if (blur === undefined || blur === null) return [];
+ if (!isObj(blur)) return [`${where} must be { on: true, caption?, strength?, from?, to? }`];
+ const b = /** @type {Record<string, unknown>} */ (blur);
+ const errors = [];
+ for (const k of Object.keys(b)) {
+ if (!CLIP_BLUR_KEYS.includes(k)) errors.push(`${where}.${k} is not a blur setting (${CLIP_BLUR_KEYS.join(", ")})`);
+ }
+ if (b.on !== true) errors.push(`${where}.on must be true (remove the key to stop blurring this clip)`);
+ if (b.caption !== undefined && (typeof b.caption !== "string" || !b.caption.trim() || b.caption.length > BLUR_CAPTION_MAX)) {
+ errors.push(`${where}.caption must be a text of 1 to ${BLUR_CAPTION_MAX} characters (absent: "${BLUR_CAPTION_DEFAULT}")`);
+ }
+ if (b.strength !== undefined && (!num(b.strength) || b.strength < BLUR_STRENGTH.min || b.strength > BLUR_STRENGTH.max)) {
+ errors.push(`${where}.strength must be a number from ${BLUR_STRENGTH.min} to ${BLUR_STRENGTH.max} (the blur's radius, % of the picture's height; default ${BLUR_STRENGTH.default})`);
+ }
+ for (const k of ["from", "to"]) {
+ if (b[k] !== undefined && (!num(b[k]) || /** @type {number} */ (b[k]) < 0)) errors.push(`${where}.${k} must be a source second ≥ 0`);
+ }
+ if (num(b.from) && num(b.to) && /** @type {number} */ (b.to) - /** @type {number} */ (b.from) < BLUR_SPAN_MIN) {
+ errors.push(`${where}: from ${b.from} must be at least ${BLUR_SPAN_MIN} s before to ${b.to}`);
+ }
+ if (entry && num(entry.start) && num(entry.end)) {
+ const s = /** @type {number} */ (entry.start);
+ const e = /** @type {number} */ (entry.end);
+ for (const k of ["from", "to"]) {
+ const v = b[k];
+ if (num(v) && (/** @type {number} */ (v) < s - EPS || /** @type {number} */ (v) > e + EPS)) {
+ errors.push(`${where}.${k} ${v} must lie inside the clip's window ${s}–${e} — widen the window, or clear blur.${k}`);
+ }
+ }
+ }
+ return errors;
+}
+
+/**
+ * Every clip's `blur` in a manifest, checked (the build's, the lint's and the
+ * structural writers'). `render.blur` is the look's (validateLook).
+ */
+export function validateClipBlurEntries(manifest) {
+ const errors = [];
+ const montage = manifest?.render?.montage !== undefined && manifest?.render?.montage !== null;
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.blur === undefined) return;
+ const where = `timeline[${i}] (${e?.id ?? "?"}).blur`;
+ if (e?.type && e.type !== "clip") {
+ errors.push(`${where}: only a clip's picture can be blurred`);
+ return;
+ }
+ if (montage && e.blur !== null) errors.push(`${where}: a montage re-cuts its clips' pictures — blur does not combine with render.montage`);
+ errors.push(...validateClipBlur(e.blur, where, e));
+ });
+ return errors;
+}
+
+/**
+ * The blur this clip renders with, every default filled -- `{ strength,
+ * caption, from, to }` (from/to null: the clip's edge) -- or null: the clip
+ * has none, it is not valid, or the cut renders uncensored.
+ */
+export function clipBlurOf(entry, render) {
+ const b = isObj(entry?.blur) ? entry.blur : null;
+ if (!b || !renderBlurOn(render) || validateClipBlur(b).length) return null;
+ return {
+ strength: num(b.strength) ? b.strength : BLUR_STRENGTH.default,
+ caption: typeof b.caption === "string" && b.caption.trim() ? b.caption.trim() : BLUR_CAPTION_DEFAULT,
+ from: num(b.from) ? b.from : null,
+ to: num(b.to) ? b.to : null,
+ };
+}
+
+const f3 = (n) => String(Number(n.toFixed(3)));
+
+/**
+ * Where a blur lands in a segment that starts at source second `segStart` and
+ * runs `seconds`: `{ whole: true }` (all of it), `{ a, b }` (the segment's
+ * own seconds), or null (the span misses the segment entirely).
+ */
+export function blurSpan(blur, segStart, seconds) {
+ if (!blur) return null;
+ if (blur.from === null && blur.to === null) return { whole: true };
+ const a = Math.max(0, (blur.from ?? -Infinity) - segStart);
+ const b = Math.min(seconds, (blur.to ?? Infinity) - segStart);
+ if (!(b > a)) return null;
+ if (a <= 0 && b >= seconds) return { whole: true };
+ return { a, b };
+}
+
+/**
+ * The caption's size and lines for a picture `w` × `h` (as it plays): a font
+ * 4.2 % of the height (14–64 px), broken to what fits 84 % of the width, the
+ * top line 5 % down.
+ */
+export function blurCaptionLayout(caption, w, h) {
+ const fontSize = Math.max(14, Math.min(64, Math.round(Math.min(h * 0.042, w * 0.03))));
+ // Plex Mono's advance is 0.6 em.
+ const cols = Math.max(12, Math.floor((w * 0.84) / (fontSize * 0.6)));
+ const lines = [];
+ let line = "";
+ for (const word of String(caption).split(/\s+/).filter(Boolean)) {
+ if (line && (line + " " + word).length > cols) {
+ lines.push(line);
+ line = word;
+ } else line = line ? `${line} ${word}` : word;
+ }
+ if (line) lines.push(line);
+ return { fontSize, lines, lineHeight: Math.round(fontSize * 1.45), top: Math.round(h * 0.05), pad: Math.max(4, Math.round(fontSize * 0.35)) };
+}
+
+/**
+ * The filters that blur a picture `w` × `h` (as it plays, before it is padded
+ * into the frame) and draw the caption on it: gblur, then one drawtext per
+ * line (read from `lineFiles[k]`, which the caller writes -- textfile=, so
+ * nothing needs filter escaping), each with `enable` over a partial span.
+ * Empty when `span` is null. `h` is the picture's height as it plays.
+ *
+ * @param {{ blur: { strength: number }, span: { whole?: boolean, a?: number, b?: number } | null,
+ * h: number, layout: ReturnType<typeof blurCaptionLayout>, lineFiles: string[], render: any }} o
+ * @returns {string[]}
+ */
+export function blurPictureFilters({ blur, span, h, layout, lineFiles, render }) {
+ if (!blur || !span) return [];
+ const enable = span.whole ? "" : `:enable='between(t,${f3(span.a)},${f3(span.b)})'`;
+ const sigma = Math.max(1, Math.round((blur.strength / 100) * h * 10) / 10);
+ const pal = render?.palette ?? {};
+ const font = render?.fontBold ?? render?.fontRegular;
+ const out = [`gblur=sigma=${sigma}:steps=3${enable}`];
+ lineFiles.forEach((file, k) => {
+ out.push(
+ [
+ `drawtext=textfile='${file}'`,
+ ...(font ? [`fontfile='${font}'`] : []),
+ `fontsize=${layout.fontSize}`,
+ `fontcolor=${pal.fg ?? "white"}`,
+ "box=1",
+ `boxcolor=${pal.bg ?? "black"}@0.78`,
+ `boxborderw=${layout.pad}`,
+ "x=(w-text_w)/2",
+ `y=${layout.top + k * layout.lineHeight}`,
+ ].join(":") + enable,
+ );
+ });
+ return out;
+}
+
+/**
+ * The size a picture `sw` × `sh` plays at when fitted into `bw` × `bh` keeping
+ * its aspect (ffmpeg's force_original_aspect_ratio=decrease, to the pixel).
+ */
+export function fittedSize(sw, sh, bw, bh) {
+ if (!(sw > 0 && sh > 0)) return { w: bw, h: bh };
+ const k = Math.min(bw / sw, bh / sh);
+ return { w: Math.max(1, Math.round(sw * k)), h: Math.max(1, Math.round(sh * k)) };
+}
+
+/** What a segment's cut record says about its blur (null: none), so --chrome-only can tell. */
+export function blurRecordOf(blur) {
+ if (!blur) return null;
+ return { strength: blur.strength, caption: blur.caption, from: blur.from, to: blur.to };
+}
+
+/**
+ * Why segments on disk cannot be re-laid for this cut, as sentences: a
+ * segment blurred where the cut now wants it clear (render.blur turned off),
+ * or clear where it wants a blur. The picture is IN the segment, so only a
+ * rebuild changes it. A record with no `blur` was built without one.
+ *
+ * @param {{ entries: object[], records: Array<object|null>, render: object }} o
+ */
+export function blurProblems({ entries, records, render }) {
+ const wrong = [];
+ entries.forEach((e, i) => {
+ if (/** @type {any} */ (e)?.type !== "clip") return;
+ const want = clipBlurOf(e, render);
+ const got = /** @type {any} */ (records[i])?.blur ?? null;
+ if (!want && !got) return;
+ const same = (k) => (want?.[k] ?? null) === (got?.[k] ?? null);
+ if (want && got && same("strength") && same("caption") && same("from") && same("to")) return;
+ const how = (x) => (x ? "blurred" : "clear");
+ wrong.push(`${/** @type {any} */ (e).id} (${how(got)} on disk, ${how(want)}${want && got ? " another way" : ""} in this cut)`);
+ });
+ if (!wrong.length) return [];
+ return [
+ `${wrong.length} segment(s) carry another blur than this cut asks for: ${wrong.join(", ")}. ` +
+ "The blur is in the segment's picture -- run a normal build (with --skip-fetch it re-cuts from the cached windows), not --chrome-only.",
+ ];
+}
diff --git a/umtool/report-to-video/clip-blur.test.mjs b/umtool/report-to-video/clip-blur.test.mjs
@@ -0,0 +1,236 @@
+// A clip's picture blurred at its segment encode (clip-blur.mjs): the knob's
+// checks, the cut's switch (render.blur "off": the uncensored variant), the
+// filters it puts on the picture and ONLY the picture (the header, the pad and
+// everything laid over the frame later stay sharp), a manifest without it the
+// graph it always was, --chrome-only refusing segments blurred another way --
+// and one tiny real render: the picture's region smoothed, the header's not.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ BLUR_CAPTION_DEFAULT,
+ BLUR_STRENGTH,
+ blurCaptionLayout,
+ blurPictureFilters,
+ blurProblems,
+ blurRecordOf,
+ blurSpan,
+ clipBlurOf,
+ fittedSize,
+ validateClipBlur,
+ validateClipBlurEntries,
+} from "./clip-blur.mjs";
+import { clipBaseFilters, deckFraming, deckFramingFilter } from "./build-video.mjs";
+import { validatorErrors } from "./lint.mjs";
+import { validateLook } from "./look.mjs";
+import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs";
+
+const clip = (extra = {}) => ({ type: "clip", id: "dog", video: "v1", start: 228.36, end: 298, ...extra });
+const PAL = { bg: "#0b0d10", fg: "#e8eaed", muted: "#9aa0a6", accent: "#f5a623" };
+const RENDER = { width: 640, height: 360, fps: 30, palette: PAL, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE };
+
+test("validateClipBlur: the good shapes pass, every bad one is refused in a sentence naming the key", () => {
+ assert.deepEqual(validateClipBlur(undefined), []);
+ assert.deepEqual(validateClipBlur(null), []);
+ assert.deepEqual(validateClipBlur({ on: true }), []);
+ assert.deepEqual(validateClipBlur({ on: true, caption: "Blurred for TOS", strength: 8, from: 230, to: 260 }, "blur", clip()), []);
+ assert.deepEqual(validateClipBlur({ on: true, from: 240 }, "blur", clip()), [], "from alone runs to the clip's end");
+ const bad = (b, re, entry = null) => {
+ const errs = validateClipBlur(b, "blur", entry);
+ assert.ok(errs.some((e) => re.test(e)), `${JSON.stringify(b)} → ${JSON.stringify(errs)}`);
+ };
+ bad("yes", /must be \{ on: true/);
+ bad({}, /on must be true/);
+ bad({ on: false }, /on must be true/);
+ bad({ on: true, sigma: 3 }, /blur\.sigma is not a blur setting/);
+ bad({ on: true, caption: "" }, /caption must be a text of 1 to 120/);
+ bad({ on: true, caption: "x".repeat(121) }, /caption must be a text of 1 to 120/);
+ bad({ on: true, strength: 1 }, /strength must be a number from 2 to 15/);
+ bad({ on: true, strength: 16 }, /strength must be a number from 2 to 15/);
+ bad({ on: true, strength: "5" }, /strength must be a number/);
+ bad({ on: true, from: -1 }, /from must be a source second/);
+ bad({ on: true, from: 250, to: 250.1 }, /at least 0\.2 s before/);
+ bad({ on: true, from: 200 }, /from 200 must lie inside the clip's window 228\.36–298/, clip());
+ bad({ on: true, to: 300 }, /to 300 must lie inside the clip's window/, clip());
+});
+
+test("validateClipBlurEntries: only a clip, not under a montage; render.blur is the look's", () => {
+ const m = { render: {}, timeline: [clip({ blur: { on: true } }), { type: "card", id: "k", blur: { on: true } }] };
+ assert.deepEqual(validateClipBlurEntries(m), ["timeline[1] (k).blur: only a clip's picture can be blurred"]);
+ const mont = { render: { montage: { style: "x" } }, timeline: [clip({ blur: { on: true } })] };
+ assert.match(validateClipBlurEntries(mont)[0], /does not combine with render\.montage/);
+ assert.deepEqual(validateLook({ render: { blur: "off" } }), []);
+ assert.deepEqual(validateLook({ render: { blur: "on" } }), []);
+ assert.match(validateLook({ render: { blur: "no" } })[0], /render\.blur must be "on".*or "off"/);
+ // The lint (and the build: validatorErrors is its list) say the same.
+ const lint = validatorErrors({ render: { blur: false }, timeline: [clip({ blur: { on: true, strength: 99 } })] });
+ assert.ok(lint.some((e) => /render\.blur must be/.test(e)), JSON.stringify(lint));
+ assert.ok(lint.some((e) => /timeline\[0\] \(dog\)\.blur\.strength/.test(e)), JSON.stringify(lint));
+});
+
+test("clipBlurOf: the defaults filled; none without the key; render.blur off is none for every clip", () => {
+ assert.equal(clipBlurOf(clip(), {}), null);
+ assert.deepEqual(clipBlurOf(clip({ blur: { on: true } }), {}), { strength: BLUR_STRENGTH.default, caption: BLUR_CAPTION_DEFAULT, from: null, to: null });
+ assert.deepEqual(clipBlurOf(clip({ blur: { on: true, caption: " Blurred ", strength: 9, from: 240 } }), { blur: "on" }), { strength: 9, caption: "Blurred", from: 240, to: null });
+ assert.equal(clipBlurOf(clip({ blur: { on: true } }), { blur: "off" }), null, "the uncensored variant");
+ assert.equal(clipBlurOf(clip({ blur: { on: true, strength: 99 } }), {}), null, "an invalid blur is the validator's to refuse, never half-drawn");
+});
+
+test("blurSpan: whole, a span in the segment's own seconds, or none when it misses", () => {
+ const b = (from, to) => ({ strength: 5, caption: "c", from, to });
+ assert.equal(blurSpan(null, 100, 10), null);
+ assert.deepEqual(blurSpan(b(null, null), 100, 10), { whole: true });
+ assert.deepEqual(blurSpan(b(102, 105), 100, 10), { a: 2, b: 5 });
+ assert.deepEqual(blurSpan(b(102, null), 100, 10), { a: 2, b: 10 });
+ assert.deepEqual(blurSpan(b(null, 104.5), 100, 10), { a: 0, b: 4.5 });
+ assert.deepEqual(blurSpan(b(95, 120), 100, 10), { whole: true }, "covering the whole segment");
+ assert.equal(blurSpan(b(111, 115), 100, 10), null);
+});
+
+test("the filters: gblur scaled to the picture's height, one drawtext a caption line, enable over a partial span", () => {
+ const blur = { strength: 5, caption: BLUR_CAPTION_DEFAULT, from: null, to: null };
+ const layout = blurCaptionLayout(blur.caption, 1600, 900);
+ assert.equal(layout.fontSize, 38);
+ assert.ok(layout.lines.length >= 1 && layout.lines.every((l) => l.length <= Math.floor((1600 * 0.84) / (38 * 0.6))));
+ assert.equal(layout.lines.join(" "), BLUR_CAPTION_DEFAULT);
+ const files = layout.lines.map((_, k) => `/seg/dog.blur-${k}.txt`);
+ const whole = blurPictureFilters({ blur, span: { whole: true }, h: 900, layout, lineFiles: files, render: RENDER });
+ assert.equal(whole[0], "gblur=sigma=45:steps=3");
+ assert.equal(whole.length, 1 + layout.lines.length);
+ assert.match(whole[1], /^drawtext=textfile='\/seg\/dog\.blur-0\.txt':fontfile='[^']*IBMPlexMono-Bold\.ttf':fontsize=38:fontcolor=#e8eaed:box=1:boxcolor=#0b0d10@0\.78/);
+ assert.ok(!whole.some((f) => f.includes("enable")));
+ const part = blurPictureFilters({ blur, span: { a: 1.5, b: 4.25 }, h: 900, layout, lineFiles: files, render: RENDER });
+ assert.ok(part.every((f) => f.endsWith(":enable='between(t,1.5,4.25)'")), JSON.stringify(part));
+ assert.deepEqual(blurPictureFilters({ blur, span: null, h: 900, layout, lineFiles: files, render: RENDER }), []);
+ assert.deepEqual(fittedSize(1280, 720, 1600, 900), { w: 1600, h: 900 });
+ assert.deepEqual(fittedSize(720, 1280, 1600, 900), { w: 506, h: 900 });
+});
+
+test("only the picture: the blur sits between the scale and the pad; without it the chain is the bytes it was", () => {
+ const render = { ...RENDER, width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck" } };
+ // The deck: the picture into the footage box; the deck itself is laid over the concat later.
+ const plain = deckFramingFilter(render, {});
+ assert.equal(deckFramingFilter(render, { picture: [] }), plain, "no blur: the same string");
+ const { fit, place } = deckFraming(render);
+ assert.equal(plain, [...fit, ...place].join(","));
+ const blurred = deckFraming(render, { picture: ["gblur=sigma=40:steps=3"] });
+ assert.deepEqual(blurred.fit, [fit[0], "gblur=sigma=40:steps=3", fit[1]], "scaled, blurred, THEN padded");
+ assert.deepEqual(blurred.place, place);
+
+ // No deck: the header is drawn AFTER the blur, on the padded frame.
+ const args = { render: { ...RENDER, width: 640, height: 360 }, VW: 640, VH: 304, HH: 56, hasHeader: true, attribPath: "/seg/a.txt" };
+ const before = [
+ "scale=640:304:force_original_aspect_ratio=decrease",
+ `pad=640:304:(ow-iw)/2:(oh-ih)/2:color=${PAL.bg}`,
+ `pad=640:304:0:0:color=${PAL.bg}`,
+ `pad=640:360:0:56:color=${PAL.bg}`,
+ "setsar=1",
+ "fps=30",
+ ];
+ const base = clipBaseFilters(args);
+ assert.deepEqual(base.slice(0, 6), before, "without a blur: the chain as it always was");
+ assert.match(base[base.length - 1], /^drawtext=textfile='\/seg\/a\.txt'/);
+ const withBlur = clipBaseFilters({ ...args, picture: ["gblur=sigma=15:steps=3", "drawtext=textfile='/seg/dog.blur-0.txt'"] });
+ const g = withBlur.findIndex((f) => f.startsWith("gblur"));
+ const firstPad = withBlur.findIndex((f) => f.startsWith("pad="));
+ const header = withBlur.findIndex((f) => f.startsWith("drawtext=textfile='/seg/a.txt'"));
+ assert.equal(g, 1);
+ assert.ok(g < firstPad && firstPad < header, JSON.stringify(withBlur));
+ assert.equal(withBlur.filter((f) => f.startsWith("gblur")).length, 1);
+});
+
+test("--chrome-only: a segment blurred another way than the cut asks is refused by name", () => {
+ const e = clip({ blur: { on: true } });
+ const want = blurRecordOf(clipBlurOf(e, {}));
+ assert.deepEqual(blurProblems({ entries: [e], records: [{ blur: want }], render: {} }), []);
+ assert.deepEqual(blurProblems({ entries: [clip()], records: [{}], render: {} }), [], "neither: nothing to say");
+ assert.deepEqual(blurProblems({ entries: [clip()], records: [null], render: {} }), []);
+ assert.match(blurProblems({ entries: [e], records: [{ blur: want }], render: { blur: "off" } })[0], /dog \(blurred on disk, clear in this cut\)/);
+ assert.match(blurProblems({ entries: [e], records: [{}], render: {} })[0], /dog \(clear on disk, blurred in this cut\)/);
+ const moved = clip({ blur: { on: true, from: 240 } });
+ assert.match(blurProblems({ entries: [moved], records: [{ blur: want }], render: {} })[0], /blurred another way/);
+});
+
+// ---- one tiny real render --------------------------------------------------
+
+const have = spawnSync("ffmpeg", ["-version"]).status === 0;
+
+/** The gray frame `file` at `t` as raw bytes (w × h). */
+function grayFrame(file, w, h) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"], { maxBuffer: 1 << 24 });
+ assert.equal(r.status, 0, String(r.stderr));
+ assert.equal(r.stdout.length, w * h);
+ return r.stdout;
+}
+/**
+ * The detail in [x, y, w, h] of a gray frame `W` wide: the mean squared step
+ * between neighbouring pixels. A blur takes the edges out of a picture, so it
+ * drops by an order of magnitude; the large areas of colour stay.
+ */
+function detail(buf, W, [x, y, w, h]) {
+ let n = 0;
+ let sq = 0;
+ for (let j = y; j < y + h; j += 1) {
+ for (let i = x; i < x + w - 1; i += 1) {
+ const d = buf[j * W + i + 1] - buf[j * W + i];
+ const e = buf[(j + 1) * W + i] - buf[j * W + i];
+ sq += d * d + e * e;
+ n += 1;
+ }
+ }
+ return sq / n;
+}
+
+test("a tiny real render: the picture's region is smoothed, the header's is the same pixels", { skip: !have && "no ffmpeg" }, () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "clip-blur-"));
+ try {
+ const W = 320;
+ const H = 180;
+ const HH = 28;
+ const VH = H - HH;
+ const render = { ...RENDER, width: W, height: H, fps: 10 };
+ const attrib = path.join(dir, "attrib.txt");
+ writeFileSync(attrib, "Channel · a title · 2026-10-23");
+ const blur = clipBlurOf(clip({ blur: { on: true } }), render);
+ const fit = fittedSize(W * 2, VH * 2, W, VH);
+ const layout = blurCaptionLayout(blur.caption, fit.w, fit.h);
+ const lineFiles = layout.lines.map((line, k) => {
+ const f = path.join(dir, `blur-${k}.txt`);
+ writeFileSync(f, line);
+ return f;
+ });
+ const picture = blurPictureFilters({ blur, span: { whole: true }, h: fit.h, layout, lineFiles, render });
+ const encode = (chain, out) => {
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", `testsrc2=s=${W * 2}x${VH * 2}:r=10:d=0.3,format=yuv420p`,
+ // The segment's own output format (encodeArgs: -pix_fmt yuv420p), so both
+ // chains negotiate it from the source on, as a build's do.
+ "-vf", [...chain, "format=yuv420p"].join(","),
+ "-frames:v", "1", "-c:v", "png", out,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ return grayFrame(out, W, H);
+ };
+ const base = { render, VW: W, VH, HH, hasHeader: true, attribPath: attrib };
+ const sharp = encode(clipBaseFilters(base), path.join(dir, "sharp.png"));
+ const soft = encode(clipBaseFilters({ ...base, picture }), path.join(dir, "soft.png"));
+ // Below the caption, in the picture: the test pattern's edges are gone.
+ const region = [20, HH + Math.round(VH * 0.55), W - 40, Math.round(VH * 0.35)];
+ const ds = detail(sharp, W, region);
+ const db = detail(soft, W, region);
+ assert.ok(db < ds * 0.1, `the picture's detail ${db.toFixed(1)} should be a tenth of ${ds.toFixed(1)} or less`);
+ // The header band: drawn after the blur, byte for byte the same.
+ const header = sharp.subarray(0, W * HH);
+ assert.ok(header.some((v) => v !== header[0]), "the header has its words drawn");
+ assert.deepEqual(soft.subarray(0, W * HH), header);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -82,6 +82,7 @@ import {
} from "./deck.mjs";
import { validateClaims } from "./factcheck.mjs";
import { validateClipAudioEntries } from "./clip-audio.mjs";
+import { validateClipBlurEntries } from "./clip-blur.mjs";
import { validateFinaleEntries } from "./finale.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
@@ -288,6 +289,8 @@ export function validatorErrors(whole) {
...validateLook(whole),
// The deck finale: each entry's `layout` and the one run (finale.mjs).
...validateFinaleEntries(whole),
+ // A clip's blurred picture and the cut's render.blur (clip-blur.mjs).
+ ...validateClipBlurEntries(whole),
];
if (deckOn(whole.render)) {
errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`));
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -23,6 +23,7 @@
"./build-video": "./build-video.mjs",
"./check-availability": "./check-availability.mjs",
"./clip-audio": "./clip-audio.mjs",
+ "./clip-blur": "./clip-blur.mjs",
"./compose-chrome": "./compose-chrome.mjs",
"./cues": "./cues.mjs",
"./deck": "./deck.mjs",