commit fc98e21530d3f597db391341fe036c050ec3bf30
parent 10f5b2a4948f3d8b7aff1ba501c804fd4e1378b1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 14 Nov 2026 01:59:36 -0500
Merge lane/clip-kit-2: a clipping job is one command -- umtool shorts builds each clip of a take as a vertical short and a desktop clip into the project's own folder under stable names, and can build the same set again; a desktop clip is the picture full frame with a small source plate and captions lit word by word; a code may sit in any corner and link the citation, the moment in the source or the channel; a cut may end on a channel card that fades in over the clip's last seconds while its sound plays on, a still of the portrait, the name, the page and its code; a clip may open on a line of its own, push in on its picture at chosen seconds, and hide regions of a recording in every picture built, cut, exported or grabbed from it, with what is only overlaid on the operator's screen said to be so and a public page never given the unhidden file; without the new keys every build is as it was
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
82 files changed, 6220 insertions(+), 320 deletions(-)
diff --git a/common/lib/clips/assist.mjs b/common/lib/clips/assist.mjs
@@ -17,6 +17,7 @@
//
// Plain ESM with a .d.mts beside it.
import { textIn } from "./clips.mjs";
+import { seekPlatformOfUrl, seekRuleOf, seekValue } from "../platformSeek.mjs";
export const ASSIST_BY = Object.freeze(["assistant", "operator"]);
export const ASSIST_EDITS = Object.freeze(["trim", "split", "merge", "add", "restore"]);
@@ -95,23 +96,22 @@ export const cutOf = (e) => (num(e?.cutStart) && num(e?.cutEnd) ? { start: e.cut
* on no site links its source there): YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`,
* Rumble `start=<s>`, anything else `t=<s>` — added with `&` or `?`, an
* existing one of the same name replaced. Null for a URL that is not one.
+ * The rule per platform, and how sure it is (Kick's is NOT confirmed), is
+ * ../platformSeek.mjs; this writer writes every platform's parameter, sure or not.
* @param {string | null | undefined} url the recording's `webpage_url`
* @param {number} seconds
* @returns {string | null}
*/
export function watchUrlAt(url, seconds) {
if (typeof url !== "string" || !/^https?:\/\//i.test(url)) return null;
- let host;
try {
- host = new URL(url).hostname.toLowerCase().replace(/^(?:www|m)\./, "");
+ new URL(url);
} catch {
return null;
}
- const s = Math.max(0, Math.floor(Number(seconds) || 0));
- const youtube = host === "youtube.com" || host === "youtu.be" || host.endsWith(".youtube.com");
- const twitch = host === "twitch.tv" || host.endsWith(".twitch.tv");
- const key = host === "rumble.com" ? "start" : "t";
- const value = youtube ? `${s}s` : twitch ? `${Math.floor(s / 3600)}h${Math.floor((s % 3600) / 60)}m${s % 60}s` : String(s);
+ const rule = seekRuleOf(seekPlatformOfUrl(url));
+ const key = rule.key;
+ const value = seekValue(rule, seconds);
const hash = url.indexOf("#");
const base = hash >= 0 ? url.slice(0, hash) : url;
const frag = hash >= 0 ? url.slice(hash) : "";
diff --git a/common/lib/momentUrl.ts b/common/lib/momentUrl.ts
@@ -20,6 +20,7 @@
import { detectPlatform, type Platform } from "./platform";
import { parseWaybackUrl } from "./wayback";
+import { PLATFORM_SEEK, seekValue } from "./platformSeek.mjs";
export type MomentUrlInput = {
// Public origin of the archilyzer viewer that owns this video (a RemoteSource
@@ -35,18 +36,13 @@ export type MomentUrlInput = {
platform?: Platform | null;
};
-// Twitch watch/VOD URLs take an `XhYmZs` time token, not raw seconds.
-function twitchTime(totalSeconds: number): string {
- const s = Math.max(0, Math.floor(totalSeconds));
- const h = Math.floor(s / 3600);
- const m = Math.floor((s % 3600) / 60);
- return `${h}h${m}m${s % 60}s`;
-}
-
-// Best-effort deep link into a platform's own watch page at `seconds`. Mirrors
-// the per-platform time params the in-app players build. Platforms whose watch
-// page has no reliable start param (Rumble, Kick, archive.org, BitChute) get
-// the bare `webpageUrl`.
+// Best-effort deep link into a platform's own watch page at `seconds`. WHICH
+// parameter each platform takes, and how sure we are, is one table:
+// lib/platformSeek.mjs (PLATFORM_SEEK). This writer's policy is to write only a
+// `verified` one (YouTube, Twitch, Odysee); Rumble, Kick, archive.org, BitChute
+// and anything unknown get the bare `webpageUrl` rather than a seek that may be
+// ignored. (lib/clips/assist.mjs watchUrlAt reads the same table with the
+// opposite policy: it writes every platform's parameter.)
// Returns null only when there is no `webpageUrl` to work from.
export function platformMomentUrl(
webpageUrl: string | null | undefined,
@@ -66,24 +62,10 @@ export function platformMomentUrl(
} catch {
return webpageUrl;
}
- switch (plat) {
- case "youtube":
- u.searchParams.set("t", `${secs}s`);
- return u.toString();
- case "odysee":
- u.searchParams.set("t", String(secs));
- return u.toString();
- case "twitch":
- u.searchParams.set("t", twitchTime(secs));
- return u.toString();
- // Rumble / Kick / archive.org / BitChute / unknown: the watch page has no
- // dependable start param — return the plain webpage URL rather than an
- // invalid seek. (archive.org's and BitChute's own players take none we can
- // rely on; the archive's viewer plays the file itself and seeks it —
- // PlayerProvider.)
- default:
- return webpageUrl;
- }
+ const rule = plat && Object.prototype.hasOwnProperty.call(PLATFORM_SEEK, plat) ? PLATFORM_SEEK[plat as keyof typeof PLATFORM_SEEK] : null;
+ if (!rule?.verified) return webpageUrl;
+ u.searchParams.set(rule.key, seekValue(rule, secs));
+ return u.toString();
}
// The archilyzer viewer deep link, or null when `siteOrigin`/`slug` are missing
diff --git a/common/lib/platformSeek.d.mts b/common/lib/platformSeek.d.mts
@@ -0,0 +1,10 @@
+// Types for ./platformSeek.mjs (lane clip-kit): the per-platform seek rule and the VOD retention table.
+
+export type SeekRule = { key: string; form: "seconds" | "seconds-s" | "hms"; verified: boolean; why: string };
+
+export const PLATFORM_SEEK: Readonly<Record<"youtube" | "twitch" | "odysee" | "rumble" | "kick", SeekRule>>;
+export const UNKNOWN_SEEK: SeekRule;
+export const VOD_RETENTION_DAYS: Readonly<{ kick: number; twitch: number }>;
+export function seekPlatformOfUrl(url: string | null | undefined): "youtube" | "twitch" | "rumble" | "kick" | "odysee" | null;
+export function seekRuleOf(platform: string | null | undefined): SeekRule;
+export function seekValue(rule: SeekRule, seconds: number): string;
diff --git a/common/lib/platformSeek.mjs b/common/lib/platformSeek.mjs
@@ -0,0 +1,68 @@
+// THE PER-PLATFORM SEEK RULE, in one place (lane clip-kit): which query parameter a platform's own watch page takes
+// to start at a second, in what form, and how sure this repository is of it -- and how long a platform keeps a
+// stream's VOD. Two writers read it, each with its own policy, and neither changed what it writes:
+//
+// common/lib/momentUrl.ts platformMomentUrl the archive, the MCP and publishing: only a `verified` parameter is
+// written; any other platform gets its bare watch page.
+// common/lib/clips/assist.mjs watchUrlAt the clip finder's citeUrl, the share line, the link policy and umtool's
+// per-clip QR: every platform's parameter here, `t=<s>` for an unknown
+// host.
+//
+// They disagree on purpose where the rule is unsure: Rumble and Kick.
+// rumble `?start=<s>`: what the share line and the link policy have written since release 36. momentUrl.ts says
+// the watch page has "no dependable start param", so it does not write it.
+// kick NOT CONFIRMED. Nothing in this repository (code, docs or tests) shows that a kick.com VOD page honours
+// a time parameter. watchUrlAt writes `?t=<s>` as it does for any host it does not know; at worst the
+// page opens at its start. Kick also deletes free-tier VODs after about 30 days (VOD_RETENTION_DAYS).
+// Confirm one by hand, then set `verified: true` here and every writer follows.
+//
+// Plain ESM, no imports: the TS app code and the plain-node build tools read the same table.
+
+/**
+ * @typedef {{ key: string, form: "seconds" | "seconds-s" | "hms", verified: boolean, why: string }} SeekRule
+ */
+
+/** @type {Readonly<Record<string, SeekRule>>} */
+export const PLATFORM_SEEK = Object.freeze({
+ youtube: Object.freeze({ key: "t", form: "seconds-s", verified: true, why: "YouTube's watch page: t=<s>s" }),
+ twitch: Object.freeze({ key: "t", form: "hms", verified: true, why: "Twitch's VOD page: t=<h>h<m>m<s>s" }),
+ odysee: Object.freeze({ key: "t", form: "seconds", verified: true, why: "Odysee's page: t=<s>" }),
+ rumble: Object.freeze({ key: "start", form: "seconds", verified: false, why: "Rumble's page: start=<s>, written by the share line; momentUrl.ts finds no dependable start param" }),
+ kick: Object.freeze({ key: "t", form: "seconds", verified: false, why: "Kick's VOD page: no time parameter is confirmed in this repository; t=<s> is the generic guess" }),
+});
+
+/** A host this rule does not know: the generic guess (watchUrlAt writes it; momentUrl.ts does not). */
+export const UNKNOWN_SEEK = Object.freeze({ key: "t", form: "seconds", verified: false, why: "an unknown platform: t=<s> is a guess" });
+
+/**
+ * How long (days) a platform keeps a stream's VOD before it is deleted. Only platforms whose VODs expire; best-effort
+ * thresholds (common/lib/vodExpiry.ts explains each), not promises.
+ */
+export const VOD_RETENTION_DAYS = Object.freeze({ kick: 30, twitch: 14 });
+
+/** The platform a watch page's host belongs to, among the ones the rule knows; null for any other. */
+export function seekPlatformOfUrl(url) {
+ let host;
+ try {
+ host = new URL(String(url)).hostname.toLowerCase().replace(/^(?:www|m)\./, "");
+ } catch {
+ return null;
+ }
+ if (host === "youtube.com" || host === "youtu.be" || host.endsWith(".youtube.com")) return "youtube";
+ if (host === "twitch.tv" || host.endsWith(".twitch.tv")) return "twitch";
+ if (host === "rumble.com") return "rumble";
+ if (host === "kick.com" || host.endsWith(".kick.com")) return "kick";
+ if (host === "odysee.com") return "odysee";
+ return null;
+}
+
+/** A platform's rule (`platform` a Platform id), else the generic guess. */
+export const seekRuleOf = (platform) => (platform && Object.prototype.hasOwnProperty.call(PLATFORM_SEEK, platform) ? PLATFORM_SEEK[platform] : UNKNOWN_SEEK);
+
+/** A second written in a rule's form. */
+export function seekValue(rule, seconds) {
+ const s = Math.max(0, Math.floor(Number(seconds) || 0));
+ if (rule.form === "seconds-s") return `${s}s`;
+ if (rule.form === "hms") return `${Math.floor(s / 3600)}h${Math.floor((s % 3600) / 60)}m${s % 60}s`;
+ return String(s);
+}
diff --git a/common/lib/platformSeek.test.ts b/common/lib/platformSeek.test.ts
@@ -0,0 +1,38 @@
+// The per-platform seek rule (lane clip-kit): one table, two writers with their own policies, neither changed.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { PLATFORM_SEEK, VOD_RETENTION_DAYS, seekPlatformOfUrl, seekRuleOf, seekValue } from "./platformSeek.mjs";
+import { platformMomentUrl } from "./momentUrl";
+import { watchUrlAt } from "./clips/assist.mjs";
+import { VOD_RETENTION_DAYS as EXPIRY_DAYS } from "./vodExpiry";
+
+test("the table: each platform's parameter and form; Kick and Rumble not verified", () => {
+ assert.equal(seekValue(PLATFORM_SEEK.youtube, 3725.9), "3725s");
+ assert.equal(seekValue(PLATFORM_SEEK.twitch, 3725), "1h2m5s");
+ assert.equal(seekValue(PLATFORM_SEEK.kick, 10643.4), "10643");
+ assert.deepEqual(Object.entries(PLATFORM_SEEK).filter(([, r]) => !r.verified).map(([p]) => p), ["rumble", "kick"]);
+ assert.equal(seekPlatformOfUrl("https://www.kick.com/x/videos/u"), "kick");
+ assert.equal(seekPlatformOfUrl("https://youtu.be/abc"), "youtube");
+ assert.equal(seekPlatformOfUrl("https://example.org/v"), null);
+ assert.equal(seekRuleOf(null).key, "t");
+ assert.deepEqual(EXPIRY_DAYS, { ...VOD_RETENTION_DAYS }, "vodExpiry.ts reads the same numbers");
+});
+
+test("watchUrlAt writes every platform's parameter, as it always did", () => {
+ assert.equal(watchUrlAt("https://www.youtube.com/watch?v=abc&t=5s", 61), "https://www.youtube.com/watch?v=abc&t=61s");
+ assert.equal(watchUrlAt("https://www.twitch.tv/videos/1", 3725), "https://www.twitch.tv/videos/1?t=1h2m5s");
+ assert.equal(watchUrlAt("https://rumble.com/v2abc-title.html", 61), "https://rumble.com/v2abc-title.html?start=61");
+ assert.equal(watchUrlAt("https://kick.com/somechan/videos/u-u-i-d?t=1", 10643.7), "https://kick.com/somechan/videos/u-u-i-d?t=10643");
+ assert.equal(watchUrlAt("https://example.org/v#frag", 7), "https://example.org/v?t=7#frag");
+ assert.equal(watchUrlAt("not a url", 7), null);
+});
+
+test("platformMomentUrl writes only a verified parameter, as it always did", () => {
+ assert.equal(platformMomentUrl("https://www.youtube.com/watch?v=abc", "youtube", 61), "https://www.youtube.com/watch?v=abc&t=61s");
+ assert.equal(platformMomentUrl("https://www.twitch.tv/videos/1", "twitch", 3725), "https://www.twitch.tv/videos/1?t=1h2m5s");
+ assert.equal(platformMomentUrl("https://odysee.com/@c/v", "odysee", 9), "https://odysee.com/@c/v?t=9");
+ assert.equal(platformMomentUrl("https://rumble.com/v2abc.html", "rumble", 61), "https://rumble.com/v2abc.html");
+ assert.equal(platformMomentUrl("https://kick.com/somechan/videos/u", "kick", 61), "https://kick.com/somechan/videos/u");
+ assert.equal(platformMomentUrl("https://kick.com/somechan/videos/u", "kick", 0), "https://kick.com/somechan/videos/u");
+});
diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts
@@ -4,8 +4,10 @@
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" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic" | "tallWindows";
+export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic" | "tallWindows" | "desktop" | "promo" | "zooms" | "censor";
export const LOOK_KEYS: readonly LookKey[];
+export const QR_CORNERS: readonly ["br", "bl", "tr", "tl"];
+export const QR_LINK_VALUES: readonly ["cite", "moment", "channel"];
export const BAND_MAX: number;
export const TRANSITION_MAX: number;
export const TRANSITION_DEFAULT: number;
diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs
@@ -26,7 +26,10 @@ 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", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows"]);
+/** The corner code's corners and links (lane clip-kit; umtool report-to-video clip-kit.mjs draws them). */
+export const QR_CORNERS = Object.freeze(["br", "bl", "tr", "tl"]);
+export const QR_LINK_VALUES = Object.freeze(["cite", "moment", "channel"]);
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows", "desktop", "promo", "zooms", "censor"]);
/** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */
export const BAND_MAX = 240;
@@ -432,7 +435,22 @@ export function applyLookPatch(manifest, patch) {
if (v === false) render.qr = false;
else if (v === true) {
if (render.qr === false) delete render.qr;
- } else errors.push("render.qr must be true (on) or false (off)");
+ } else if (isObj(v)) {
+ // The clip kit (lane clip-kit): the code's corner and link, merged over its settings (a key null drops it).
+ const bad = Object.keys(v).filter((x) => !["corner", "links"].includes(x));
+ if (bad.length) errors.push(`render.qr.${bad[0]} is not set here: corner (br, bl, tr, tl) and links (cite, moment, channel) are`);
+ else if (v.corner != null && !QR_CORNERS.includes(/** @type {string} */ (v.corner))) errors.push(`render.qr.corner is one of ${QR_CORNERS.join(", ")}`);
+ else if (v.links != null && !QR_LINK_VALUES.includes(/** @type {string} */ (v.links))) errors.push(`render.qr.links is one of ${QR_LINK_VALUES.join(", ")}`);
+ else {
+ const next = { ...(isObj(render.qr) ? render.qr : {}) };
+ for (const [x, y] of Object.entries(v)) {
+ if (y === null) delete next[x];
+ else next[x] = y;
+ }
+ if (Object.keys(next).length) render.qr = next;
+ else delete render.qr;
+ }
+ } else errors.push("render.qr must be true (on), false (off) or {corner?, links?}");
break;
case "transition":
if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > TRANSITION_MAX) errors.push(`render.transition must be a number of seconds from 0 (a hard cut) to ${TRANSITION_MAX}`);
diff --git a/common/lib/report/vertical.d.mts b/common/lib/report/vertical.d.mts
@@ -17,6 +17,7 @@ export type VerticalKnobs = {
safe: { top: number; bottom: number; right: number };
loudness: number;
maxSeconds: number;
+ qr: false | true | { corner?: "tr" | "tl"; size?: number; links?: "cite" | "moment" | "channel" };
};
export const RENDER_FORMATS: readonly ("landscape" | "vertical")[];
export const VERTICAL_CLIP_LAYOUTS: readonly ClipLayout[];
@@ -46,3 +47,29 @@ export function validateClipSides(manifest: unknown): string[];
export function sidePostOf(entry: unknown, timeline?: unknown[]): Record<string, unknown> | null;
export function sideSpan(side: unknown, seconds: number): { from: number; to: number } | null;
export function validateVerticalFormat(manifest: unknown): string[];
+
+export const VERTICAL_QR_CORNERS: readonly ["tr", "tl"];
+export const VERTICAL_QR_KEYS: readonly string[];
+export const VERTICAL_QR_SIZE: Readonly<{ min: number; max: number; default: number }>;
+export const QR_LINKS: readonly ["cite", "moment", "channel"];
+export function verticalQrErrors(v: unknown, where?: string): string[];
+
+export type DesktopKnobs = {
+ tag: boolean;
+ hook: false | "title" | "section" | { text: string };
+ captions: { size: "m" | "l" | "xl"; lines: 1 | 2 };
+ safe: { top: number; bottom: number; right: number; left: number };
+ loudness: number;
+ maxSeconds: number;
+ qr: false | true | { corner?: "br" | "bl" | "tr" | "tl"; size?: number; links?: "cite" | "moment" | "channel" };
+};
+export const DESKTOP_WIDTH: number;
+export const DESKTOP_HEIGHT: number;
+export const DESKTOP_CAPTION_SIZES: readonly ["m", "l", "xl"];
+export const DESKTOP_QR_CORNERS: readonly ["br", "bl", "tr", "tl"];
+export const DESKTOP_QR_SIZE: Readonly<{ min: number; max: number; default: number }>;
+export const DESKTOP_SAFE_MAX: number;
+export const DESKTOP_DEFAULTS: Readonly<DesktopKnobs>;
+export const DESKTOP_KEYS: readonly string[];
+export function desktopKnobs(render: Render): DesktopKnobs;
+export function validateDesktopRender(manifest: { render?: Record<string, unknown> | null } | null | undefined): string[];
diff --git a/common/lib/report/vertical.mjs b/common/lib/report/vertical.mjs
@@ -74,6 +74,7 @@ export const VERTICAL_DEFAULTS = Object.freeze({
safe: Object.freeze({ top: 0.08, bottom: 0.2, right: 0.12 }),
loudness: -14,
maxSeconds: 60,
+ qr: false,
});
export const VERTICAL_KEYS = Object.freeze(Object.keys(VERTICAL_DEFAULTS));
export const VERTICAL_SAFE_MAX = Object.freeze({ top: 0.25, bottom: 0.35, right: 0.25 });
@@ -95,9 +96,32 @@ export function verticalKnobs(render) {
safe: { ...VERTICAL_DEFAULTS.safe, ...(isObj(v.safe) ? v.safe : {}) },
loudness: num(v.loudness) ? v.loudness : VERTICAL_DEFAULTS.loudness,
maxSeconds: num(v.maxSeconds) ? v.maxSeconds : VERTICAL_DEFAULTS.maxSeconds,
+ qr: v.qr === true || isObj(v.qr) ? v.qr : VERTICAL_DEFAULTS.qr,
};
}
+/** A short's code (lane clip-kit; umtool report-to-video clip-kit.mjs draws it): where it may stand, its keys. */
+export const VERTICAL_QR_CORNERS = Object.freeze(["tr", "tl"]);
+export const VERTICAL_QR_KEYS = Object.freeze(["corner", "size", "links"]);
+export const VERTICAL_QR_SIZE = Object.freeze({ min: 0.1, max: 0.3, default: 0.16 });
+export const QR_LINKS = Object.freeze(["cite", "moment", "channel"]);
+
+/** Each thing wrong with `render.vertical.qr` ([] when fine): false (the default), true, or {corner?, size?, links?}. */
+export function verticalQrErrors(v, where = "render.vertical.qr") {
+ if (v === undefined || v === null || v === false || v === true) return [];
+ if (!isObj(v)) return [`${where} is true, false or {${VERTICAL_QR_KEYS.join(", ")}}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!VERTICAL_QR_KEYS.includes(k)) errors.push(`${where}.${k} is not a key (${VERTICAL_QR_KEYS.join(", ")})`);
+ if (v.corner !== undefined && !VERTICAL_QR_CORNERS.includes(v.corner)) {
+ errors.push(`${where}.corner is ${VERTICAL_QR_CORNERS.join(" or ")} (a short's captions run along its foot), not ${q(v.corner)}`);
+ }
+ if (v.size !== undefined && !(num(v.size) && v.size >= VERTICAL_QR_SIZE.min && v.size <= VERTICAL_QR_SIZE.max)) {
+ errors.push(`${where}.size is ${VERTICAL_QR_SIZE.min}–${VERTICAL_QR_SIZE.max} of the frame's width`);
+ }
+ if (v.links !== undefined && !QR_LINKS.includes(v.links)) errors.push(`${where}.links is one of ${QR_LINKS.join(", ")}, not ${q(v.links)}`);
+ return errors;
+}
+
/** A clip's layout in a vertical cut: its own `vertical.layout`, else the cut's ("twocrop" is the stacked deck's: clipTwoCrop). */
export function clipLayoutOf(entry, render) {
const own = entry?.vertical?.layout;
@@ -155,6 +179,7 @@ export function validateVerticalRender(manifest) {
} else if (!VERTICAL_HOOKS.includes(v.hook)) errors.push(`render.vertical.hook must be false, ${VERTICAL_HOOKS.map(q).join(", ")} or {text}`);
}
if (v.tag !== undefined && typeof v.tag !== "boolean") errors.push("render.vertical.tag must be true or false");
+ errors.push(...verticalQrErrors(v.qr));
if (v.safe !== undefined) {
if (!isObj(v.safe)) errors.push("render.vertical.safe must be {top?, bottom?, right?}");
else {
@@ -220,4 +245,91 @@ export function sideSpan(side, seconds) {
}
/** All of the vertical format's checks. */
-export const validateVerticalFormat = (manifest) => [...validateVerticalRender(manifest), ...validateClipSides(manifest)];
+export const validateVerticalFormat = (manifest) => [...validateVerticalRender(manifest), ...validateDesktopRender(manifest), ...validateClipSides(manifest)];
+
+// ---------------------------------------------------------------------------
+// THE DESKTOP CLIP (lane clip-kit, slice C): a clip of a take built 16:9 by the same per-clip builder as a short
+// (`umtool vertical --desktop`, a batch's `desktop` format) -- for X, which autoplays muted: the picture full frame
+// (no letterbox, no header), ONE thin source line on a small plate over it, the words lit as they are said along its
+// foot, a code in a corner only when asked. Its knobs are `render.desktop`; absent, the defaults below (the
+// "minimal chrome" look). A cut never renders desktop by itself: only a per-clip build asks for it.
+//
+// render.desktop { tag?, hook?, captions?: {size?, lines?}, safe?: {top?, bottom?, right?, left?}, loudness?,
+// maxSeconds?, qr?: false | true | {corner?: "br"|"bl"|"tr"|"tl", size?, links?} }
+// ---------------------------------------------------------------------------
+
+export const DESKTOP_WIDTH = 1920;
+export const DESKTOP_HEIGHT = 1080;
+export const DESKTOP_CAPTION_SIZES = Object.freeze(["m", "l", "xl"]);
+export const DESKTOP_QR_CORNERS = Object.freeze(["br", "bl", "tr", "tl"]);
+export const DESKTOP_QR_SIZE = Object.freeze({ min: 0.05, max: 0.2, default: 0.09 });
+export const DESKTOP_SAFE_MAX = 0.25;
+export const DESKTOP_DEFAULTS = Object.freeze({
+ tag: true,
+ hook: false,
+ captions: Object.freeze({ size: "l", lines: 2 }),
+ safe: Object.freeze({ top: 0.04, bottom: 0.08, right: 0.03, left: 0.03 }),
+ loudness: -14,
+ maxSeconds: 140,
+ qr: false,
+});
+export const DESKTOP_KEYS = Object.freeze(Object.keys(DESKTOP_DEFAULTS));
+
+/** A desktop clip's knobs: `render.desktop` over the defaults. */
+export function desktopKnobs(render) {
+ const v = isObj(render?.desktop) ? render.desktop : {};
+ return {
+ tag: typeof v.tag === "boolean" ? v.tag : DESKTOP_DEFAULTS.tag,
+ hook: v.hook === undefined || v.hook === null ? DESKTOP_DEFAULTS.hook : v.hook,
+ captions: { ...DESKTOP_DEFAULTS.captions, ...(isObj(v.captions) ? v.captions : {}) },
+ safe: { ...DESKTOP_DEFAULTS.safe, ...(isObj(v.safe) ? v.safe : {}) },
+ loudness: num(v.loudness) ? v.loudness : DESKTOP_DEFAULTS.loudness,
+ maxSeconds: num(v.maxSeconds) ? v.maxSeconds : DESKTOP_DEFAULTS.maxSeconds,
+ qr: v.qr === true || isObj(v.qr) ? v.qr : DESKTOP_DEFAULTS.qr,
+ };
+}
+
+/** Each thing wrong with `render.desktop` ([] when fine, or absent). */
+export function validateDesktopRender(manifest) {
+ const v = manifest?.render?.desktop;
+ if (v === undefined || v === null) return [];
+ if (!isObj(v)) return [`render.desktop must be an object of the desktop knobs (${DESKTOP_KEYS.join(", ")})`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!DESKTOP_KEYS.includes(k)) errors.push(`render.desktop.${k} is not a desktop knob (${DESKTOP_KEYS.join(", ")})`);
+ if (v.tag !== undefined && typeof v.tag !== "boolean") errors.push("render.desktop.tag must be true or false");
+ if (v.hook !== undefined && v.hook !== false) {
+ if (isObj(v.hook)) {
+ const t = v.hook.text;
+ if (Object.keys(v.hook).some((k) => k !== "text") || typeof t !== "string" || !t.trim() || t.length > VERTICAL_HOOK_MAX) errors.push(`render.desktop.hook.text must be a line of 1–${VERTICAL_HOOK_MAX} characters`);
+ } else if (!VERTICAL_HOOKS.includes(v.hook)) errors.push(`render.desktop.hook must be false, ${VERTICAL_HOOKS.map(q).join(", ")} or {text}`);
+ }
+ if (v.captions !== undefined) {
+ if (!isObj(v.captions)) errors.push("render.desktop.captions must be {size?, lines?}");
+ else {
+ for (const k of Object.keys(v.captions)) if (k !== "size" && k !== "lines") errors.push(`render.desktop.captions.${k} is not a caption knob (size, lines)`);
+ if (v.captions.size !== undefined && !DESKTOP_CAPTION_SIZES.includes(v.captions.size)) errors.push(`render.desktop.captions.size must be one of ${DESKTOP_CAPTION_SIZES.join(", ")}`);
+ if (v.captions.lines !== undefined && v.captions.lines !== 1 && v.captions.lines !== 2) errors.push("render.desktop.captions.lines must be 1 or 2");
+ }
+ }
+ if (v.safe !== undefined) {
+ if (!isObj(v.safe)) errors.push("render.desktop.safe must be {top?, bottom?, right?, left?}");
+ else {
+ for (const [k, x] of Object.entries(v.safe)) {
+ if (!["top", "bottom", "right", "left"].includes(k)) errors.push(`render.desktop.safe.${k} is not an edge (top, bottom, right, left)`);
+ else if (!num(x) || x < 0 || x > DESKTOP_SAFE_MAX) errors.push(`render.desktop.safe.${k} must be a fraction of the frame from 0 to ${DESKTOP_SAFE_MAX}`);
+ }
+ }
+ }
+ if (v.loudness !== undefined && !(num(v.loudness) && v.loudness >= -30 && v.loudness <= -8)) errors.push("render.desktop.loudness must be a LUFS target from -30 to -8");
+ if (v.maxSeconds !== undefined && !(num(v.maxSeconds) && v.maxSeconds >= 5 && v.maxSeconds <= 600)) errors.push("render.desktop.maxSeconds must be 5 to 600 seconds");
+ if (v.qr !== undefined && v.qr !== true && v.qr !== false) {
+ if (!isObj(v.qr)) errors.push("render.desktop.qr is true, false or {corner?, size?, links?}");
+ else {
+ for (const k of Object.keys(v.qr)) if (!VERTICAL_QR_KEYS.includes(k)) errors.push(`render.desktop.qr.${k} is not a key (${VERTICAL_QR_KEYS.join(", ")})`);
+ if (v.qr.corner !== undefined && !DESKTOP_QR_CORNERS.includes(v.qr.corner)) errors.push(`render.desktop.qr.corner is one of ${DESKTOP_QR_CORNERS.join(", ")}`);
+ if (v.qr.size !== undefined && !(num(v.qr.size) && v.qr.size >= DESKTOP_QR_SIZE.min && v.qr.size <= DESKTOP_QR_SIZE.max)) errors.push(`render.desktop.qr.size is ${DESKTOP_QR_SIZE.min}–${DESKTOP_QR_SIZE.max} of the frame's width`);
+ if (v.qr.links !== undefined && !QR_LINKS.includes(v.qr.links)) errors.push(`render.desktop.qr.links is one of ${QR_LINKS.join(", ")}`);
+ }
+ }
+ return errors;
+}
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, 16);
+ assert.equal(LOOK_KEYS.length, 20);
});
test("render.mode and render.basic: deck is the default (no key), basic the footage alone; the fades checked", () => {
diff --git a/common/lib/vodExpiry.ts b/common/lib/vodExpiry.ts
@@ -1,5 +1,6 @@
import type { Platform } from "./platform";
import { daysSince } from "./format";
+import { VOD_RETENTION_DAYS as SEEK_RETENTION_DAYS } from "./platformSeek.mjs";
// Retention window (days) after which a platform's stream VODs are typically
// deleted, making playback impossible. Only platforms whose VODs expire appear
@@ -13,10 +14,8 @@ import { daysSince } from "./format";
// "Likely expired" wording + the tooltip acknowledge the uncertainty for
// partner (still up to 60d) and regular (already gone at 7d) accounts.
// Tune here if the retention policy changes.
-export const VOD_RETENTION_DAYS: Partial<Record<Platform, number>> = {
- kick: 30,
- twitch: 14,
-};
+// The numbers are lib/platformSeek.mjs's (one table: umtool's per-clip QR reads them too).
+export const VOD_RETENTION_DAYS: Partial<Record<Platform, number>> = { ...SEEK_RETENTION_DAYS };
const RETENTION_TOOLTIP: Partial<Record<Platform, string>> = {
kick: "Kick keeps VODs about 30 days after the stream, so this one has most likely been deleted. The transcript is still searchable here.",
diff --git a/common/package.json b/common/package.json
@@ -42,6 +42,7 @@
"./lib/atomicFile.mjs": "./lib/atomicFile.mjs",
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
+ "./lib/platformSeek.mjs": "./lib/platformSeek.mjs",
"./lib/projectsRoot.mjs": "./lib/projectsRoot.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
"./lib/recordingClock.mjs": "./lib/recordingClock.mjs",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,101 @@
# Changelog
## [Unreleased]
+- **umtool: parts of a recording's picture can be hidden on every clip of it.** This covers things like a stream
+ layout's chat overlay or a window showing other people's accounts.
+ - `render.censor` (`umtool censor <p> --video <id> --box x,y,w,h[@from-to]`, or the clip editor's
+ **Hide regions**) blurs, blacks out or pixelates the same boxes on every clip of that recording. A box can be
+ limited to a span of the clip.
+ - A clip's own `censor` adds boxes for that clip; `censor=false` turns its recording's off.
+ - The boxes are applied to the source picture first, and they stay on in the uncensored variant.
+ - Every path that draws or cuts a clip's picture either hides them or refuses by name. They are hidden in a cut, a
+ short, a desktop clip, Make a short, a short of an already-rendered take (the project's boxes are added),
+ `umtool shorts --again`, the YouTube thumbnail, stills, and `umtool export` as cut or with context.
+ - Players of a raw window overlay them on the operator's screen; they are not hidden in the file. These are Play,
+ the live preview, the operator's Present, the claim bench, the candidates panel and the article's cited clip.
+ The clip editor's player and the clip bench draw them outlined, with a **Peek** toggle that is off by default.
+ - A public Present payload never names the raw window of a clip with boxes. It plays the clip's built segment when
+ that segment hides exactly those boxes, and otherwise says the clip is not shown.
+ - A montage, a basic cut, `--chrome-only` after the boxes changed and `--reframe` of a take rendered before them
+ are refused. So is `umtool export --raw`, unless `--uncensored-raw` asks for the recording as it is (and the
+ export says UNCENSORED).
+ - knobs.md, "Hidden regions", lists every path.
+ - Without the keys the segments are unchanged.
+- **umtool: a short or a desktop clip can open on its payoff.** A clip's `coldOpen` (`{from, to}`, 1–4 s of its
+ cut) plays first, then the short cuts hard to the clip's start.
+ - The cold open has its own captions and sound, the hook band, no code and no card. The channel promo still ends
+ the clip.
+ - Set it with the clip editor's **Cold open from selection** or `umtool set <p> <clip> coldOpen.from=… coldOpen.to=…`.
+ - A cold open with a gap inside it or across its edges, or one that is the whole cut, is refused by the clip's name.
+ - Turn it off for a build with `--no-cold-open`.
+ - Reels, `--landscape` and the stacked deck play the clips as cut.
+- **umtool: a short or a desktop clip can zoom in at points.** A clip's `zooms`
+ (`[{at, scale|box, focus, hold, ramp}]`) push its picture in at those source seconds, eased in and out.
+ - The zoom works on the source picture before the layout. A short's crop stays put and the focus keeps its place
+ on screen.
+ - It is strict by default: a zoom past the source's own pixels is refused, naming the enlargement. With 1080 windows
+ a framed short has room up to ×1.78; a full short and a desktop clip have none.
+ - `render.zooms.soften` (up to 1.3) allows a soft zoom: the picture may play up to that many times the coarser of
+ its source's pixels and the layout's resting picture. The build says how much softer than its source it plays.
+ It is not a cap on the total past the source's pixels, which would leave a full short no zoom at all (knobs.md).
+ - The push is drawn on sub-pixel corners, so a slow ease never steps back. A zoom written outside the clip's cut
+ is refused.
+ - Controls: the clip editor's **Zoom here** (scale, focus, hold), the Look panel's **Zooms**, and
+ `umtool set <p> <clip> zooms=…`.
+- **umtool: a clip can end on the channel's card, for promoting the streamer it was clipped from.** `render.promo`
+ (`{name, url, qr?, portrait?, palette?, lead?, fade?, hold?, captions?}`) ends a short's, a desktop clip's or a
+ batch's last clip on a card.
+ - The card shows the portrait in a ring, the name stacked, the channel's page and a code to it. Nothing else unless
+ a `kicker` is given, and it does not move.
+ - The picture dissolves into it 4.5 s before the clip's end, over 0.7 s, while the clip's sound plays on. Then the
+ card holds 1.5 s in silence.
+ - The captions stay over the card in a band it keeps clear.
+ - The colours come from the cut's palette; `promo.palette` overrides them for the card alone. The fonts are the
+ repository's own.
+ - Set it in the Look panel's **Channel promo** (with **Draw the card**), or with `umtool look`.
+ - Take the portrait from a clip in the clip editor (**Use this frame as the promo portrait**) or with
+ `umtool promo <p> --portrait-from <clip>@<second>`; draw the cards with `umtool promo --draw`.
+ - One clip can opt out with `promo=false` or its **End card** select. For a whole build, `--no-promo` or
+ `--promo-lead`/`--promo-hold`.
+ - Without `render.promo` a build is unchanged.
+- **umtool: desktop clips, 16:9 with minimal chrome, for X.** `umtool vertical … --desktop`, or a batch's `desktop`
+ format (`umtool shorts … --formats vertical,desktop`), builds a take's clips at 1920x1080 with the builder shorts
+ use.
+ - The picture fills the frame, with no letterbox.
+ - One thin source line ("channel · date") sits on a small plate.
+ - Captions are lit word by word along the foot, because X autoplays muted.
+ - There is a code only when asked: `--qr on`, `--qr-corner br|bl|tr|tl`.
+ - The clip is brought to -14 LUFS. Over 140 s it gets a note.
+ - Set it in `render.desktop` or the Look panel's **Desktop clips**. A cut never renders desktop by itself.
+ - `--landscape` (the take's whole 16:9 look) is unchanged.
+- **umtool: a clip's QR can stand in any corner and link the source at the clip's second.**
+ - `render.qr.corner` is `br` (the default) or `bl`, `tr` or `tl`, so the code can stay off the streamer's camera box.
+ - `render.qr.links` is `cite` (the default), `moment` or `channel`. `moment` links the clip's own recording at the
+ second it starts playing; `channel` links the promo's page.
+ - A clip's own `qr` (`false`, or `{corner, links}`) speaks over the cut's.
+ - A short can carry a code too: `umtool vertical --qr on|--qr-corner tr|tl`, or `render.vertical.qr`. It sits at the
+ top of the safe area and links the moment by default.
+ - Where to set them: the Look panel (**QR corner**, **QR links**), the clip editor's Short panel (**QR on this
+ clip**), `umtool look` and `umtool set <p> <clip> qr.corner=tl`.
+ - Each platform's time parameter now lives in one table, `common/lib/platformSeek.mjs`. Both link writers read it,
+ and neither writes anything new. Kick's `t=` is marked unconfirmed.
+ - A moment code to a Kick or Twitch VOD gets a lint note naming the platform's VOD expiry.
+ - With none of the new keys, the code is drawn exactly as before.
+- **umtool: a batch of shorts in one command, `umtool shorts`.** `umtool shorts <p> --take <t> (--items a,b | --all)
+ --formats vertical,landscape` builds each clip in each format through the builder `umtool vertical` uses (the same
+ layouts and flags), into the project's `shorts-<take>/`, as `<name>.<format>.mp4`. Each file gets its record, and the
+ folder gets `batch.json`.
+ - A clip's name is its pinned `name`, else its title's slug, else its id. A clash gets `-<clip id>`, and a name once
+ given is kept.
+ - A file already there is kept unless `--replace`, which sets it aside first.
+ - `--again` builds the folder again from its record: each clip with the knobs and framing it was built with.
+ - A vertical over 180 s or a landscape over 140 s (X's 2:20) gets a note, never a refusal.
+ - A clip that fails is recorded and the rest go on. The command exits 1 at the end.
+ - It is a ⌘K form and runs as one queued job. `shorts-<take>` is a deliverable: `umtool storage deliverables` moves it
+ with `clips/`.
+ - `umtool vertical`'s form now offers `--landscape`.
+ - `umtool vertical` and `umtool shorts` now read the project's fetched windows for a draft take that was never
+ rendered, as a made take does. Before, such a take found no window unless the corpus had one.
- **umtool: the diet strip, the promise clock and the other layers are no longer drawn over a teaser, the brand
intro or a full-frame card.** The deck already slid away over them, but the measure extras, the side panels, the
chapters and the finale's pages stayed on screen over the teaser's card. Now they are left out over every item that
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -137,6 +137,14 @@ source tree).
(`DisplaySummary` records), documented in `common/lib/corpus.ts:35-36` and served by
`common/components/summariesCache.ts`. Nothing to do with AI summaries. Use **`digest`**.
+**The clip kit's names avoid four taken ones (lane clip-kit).** The channel promo a per-clip build ends on is
+`render.promo` (`report-to-video/promo-card.mjs`), never "end card": outro.mjs's END CARD is the stacked vertical
+deck's reel outro. A clip's payoff-first opening is `coldOpen`, never "hook": `render.vertical.hook` / `--hook` is the
+title band. The per-clip zoom is `zooms`, never `zoom` (`fx.zoom`: a screenshot pushed in on), `punch` (`fx.punch`: the
+words) or `punchIn` (`fx.punchIn`: the deck's snap). Hidden regions are `censor`, never `blur` (a clip's `blur`: the
+whole picture, a TOS caption). And `shorts/` is the clip editor's Make a short (every mp4 there read as a clip's);
+a batch of shorts is `shorts-<take>/`.
+
**"Workspace" means two things in umtool.** THE WORKSPACE (umtool redesign L7a,
`umtool/components/projects/workspace/`) is a report video's one screen at its own address
`/projects/<p>` (`workspaceHref`, `kinds.mjs` `opensWorkspace`): viewer, block strip, inspector.
diff --git a/umtool/app/api/report/candidates/route.ts b/umtool/app/api/report/candidates/route.ts
@@ -3,6 +3,7 @@ import { StaleToken, StructureRefused, manifestToken } from "@/lib/report/manife
import { CandidatesError, candidatesView, dismissCandidate, insertCandidate } from "@/lib/report/candidates.mjs";
import { projectCache, resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
+import { recordingRegionsOf } from "umtool-report-to-video/clip-censor";
export const dynamic = "force-dynamic";
@@ -11,7 +12,7 @@ export const dynamic = "force-dynamic";
// panel. Proposals come in from a terminal only (`umtool candidates <p>
// import|add`); this route is the operator's two presses.
//
-// GET ?project=<id> { …candidatesView, token, playable: { <id>: true } }
+// GET ?project=<id> { …candidatesView, token, playable: { <id>: true }, hidden: { <id>: its recording's regions } }
// (playable: a cached window holds the cited second, so Play plays it here)
// POST { project, op: "insert", id, section | group, token } through `timeline insert`'s writer
// → { ok, inserted, clip, window, token, editNotes, attributionError? } | 409 stale
@@ -32,7 +33,13 @@ export async function GET(request: Request) {
if (wins.some((w) => w.from <= c.t && w.to >= c.t + 2)) playable[c.id] = true;
}
}
- return Response.json({ ...view, token: await manifestToken(r.project.dir), playable }, { headers });
+ // Each candidate's recording's hidden regions (render.censor): overlaid where it plays, as on every raw window.
+ const hidden: Record<string, ReturnType<typeof recordingRegionsOf>> = {};
+ for (const c of view.candidates as { id: string; video: string; channel?: string }[]) {
+ const g = recordingRegionsOf(c.video, c.channel ?? null, r.manifest.render ?? {}, r.manifest.provenance ?? {});
+ if (g.length) hidden[c.id] = g;
+ }
+ return Response.json({ ...view, token: await manifestToken(r.project.dir), playable, hidden }, { headers });
}
export async function POST(request: Request) {
diff --git a/umtool/app/api/report/clip-export/route.ts b/umtool/app/api/report/clip-export/route.ts
@@ -13,7 +13,8 @@ export const dynamic = "force-dynamic";
// (`context`), or a stretch as recorded (`raw`: the fetched window, or a
// `span` -- the full exchange).
//
-// POST { project, clip, take?, kind?: "cut" | "context" | "raw", context?: N, span?: {from, to}, fetch?: true }
+// POST { project, clip, take?, kind?: "cut" | "context" | "raw", context?: N, span?: {from, to}, fetch?: true, uncensoredRaw?: true }
+// (`uncensoredRaw`: a raw export of a clip that hides regions is refused unless asked for as recorded, regions shown)
// -> 202 { job } ONE umtool job on the app's runner (lib/jobs.ts: one at a
// time, a log, Stop): `fetch: true` asks the editor first for what a
// context or raw export needs that is not on disk (the bench's own
@@ -69,6 +70,7 @@ export async function POST(request: Request) {
span,
fetch: need.held ? null : { padBefore: need.padBefore, padAfter: need.padAfter },
manifestPath,
+ uncensoredRaw: kind === "raw" && body.uncensoredRaw === true,
});
const job = startJob(`export ${project.id}/${clip}`, steps, { project: project.id });
return Response.json({ ok: true, fetching: !need.held, job: jobView(job) }, { status: 202, headers });
diff --git a/umtool/app/api/report/promo-card/route.ts b/umtool/app/api/report/promo-card/route.ts
@@ -0,0 +1,53 @@
+import { readFile } from "node:fs/promises";
+import { refuseCaller } from "@/lib/report/caller";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { drawPromoCards, setPromoPortrait } from "@/lib/report/promoCli.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE CHANNEL PROMO's card, drawn to look at, and its portrait from a clip (lane clip-kit, slice D;
+// report-to-video promo-card.mjs, lib/report/promoCli.mjs -- the same functions `umtool promo` runs).
+//
+// GET ?project=<id>&shape=v|h the card (PNG), 9:16 (v) or 16:9 (h), drawn from the look as saved
+// (kept by its key: drawn again only when the promo changes)
+// POST { project, op: "portrait", clip, at, box? } the frame of `clip` at source second `at` grabbed into shots/ and
+// made the card's portrait -> { promo } | 400 { error }
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return new Response(r.error, { status: r.status });
+ const shape = url.searchParams.get("shape") === "h" ? "h" : "v";
+ try {
+ const cards = await drawPromoCards(r.project);
+ const card = cards.find((c) => (shape === "v" ? c.height > c.width : c.width > c.height));
+ if (!card) return new Response("no card", { status: 500 });
+ return new Response(new Uint8Array(await readFile(card.file)), { headers: { "content-type": "image/png", ...noStore } });
+ } catch (e) {
+ return new Response(e instanceof Error ? e.message : String(e), { status: 400 });
+ }
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/promo-card");
+ if (refused) return refused;
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ if (body.op !== "portrait") return Response.json({ error: 'op is "portrait"' }, { status: 400 });
+ const at = Number(body.at);
+ const box = Array.isArray(body.box) && body.box.length === 4 && body.box.every((n) => typeof n === "number") ? (body.box as number[]) : null;
+ if (typeof body.clip !== "string" || !Number.isFinite(at)) return Response.json({ error: "clip and at (a source second) are needed" }, { status: 400 });
+ try {
+ const set = await setPromoPortrait(r.project, { clip: body.clip, at, box });
+ return Response.json({ promo: set.promo, still: set.still.rel }, { headers: noStore });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -789,6 +789,7 @@ async function cmdExportClip(p, clipId) {
const from = val("--from");
const to = val("--to");
if (kind !== "raw" && (from !== undefined || to !== undefined)) die("--from/--to are a raw export's span: add --raw");
+ if (has("--uncensored-raw") && kind !== "raw") die("--uncensored-raw goes with --raw (a cut or context export always hides its regions)");
if ((from === undefined) !== (to === undefined)) die("a raw span is --from S --to S, both");
const span = from !== undefined ? { from: Number(from), to: Number(to) } : null;
const take = val("--take") ?? null;
@@ -811,7 +812,7 @@ async function cmdExportClip(p, clipId) {
try {
r = await withRenderSlot(
["umtool", "export", p.id, clipId, kind],
- () => exportClip(p, clipId, { take, kind, ...(context !== undefined ? { context: Number(context) } : {}), span }),
+ () => exportClip(p, clipId, { take, kind, ...(context !== undefined ? { context: Number(context) } : {}), span, uncensoredRaw: has("--uncensored-raw") }),
{ estimateMb: EXPORT_ESTIMATE_MB, say },
);
} catch (e) {
@@ -954,6 +955,12 @@ const COMMANDS = {
trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))),
// A vertical short (1080x1920) of a take's items, natively or reframed: lib/report/verticalCli.mjs.
vertical: async () => process.exit(await (await import("../lib/report/verticalCli.mjs")).verticalCommand(argv.slice(argv.indexOf("vertical") + 1))),
+ // A batch of shorts: a take's clips in each format, into shorts-<take>/ (lane clip-kit): lib/report/shortsCli.mjs.
+ shorts: async () => process.exit(await (await import("../lib/report/shortsCli.mjs")).shortsCommand(argv.slice(argv.indexOf("shorts") + 1))),
+ // The channel promo's portrait from a clip, and its card drawn to look at (lane clip-kit): lib/report/promoCli.mjs.
+ // The regions hidden on every clip of one recording (lane clip-kit): lib/report/censorCli.mjs.
+ censor: async () => process.exit(await (await import("../lib/report/censorCli.mjs")).censorCommand(argv.slice(argv.indexOf("censor") + 1))),
+ promo: async () => process.exit(await (await import("../lib/report/promoCli.mjs")).promoCommand(argv.slice(argv.indexOf("promo") + 1))),
// Quick clip (lane output-modes): one moment to a basic-mode mp4 and its share line: lib/report/quickClip.mjs.
clip: async () => process.exit(await (await import("../lib/report/quickClip.mjs")).quickClipCommand(argv.slice(argv.indexOf("clip") + 1))),
// The inspector's twins (umtool redesign L6): provenance, title, a still at second N -- lib/report/inspectorCli.mjs.
diff --git a/umtool/components/clips/CitedClip.tsx b/umtool/components/clips/CitedClip.tsx
@@ -8,6 +8,7 @@ import { spanClock } from "@/lib/clips/words";
import { cn } from "@/lib/utils";
import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl";
import StoredUrlOption from "./StoredUrlOption";
+import CensorOverlay from "@/components/projects/review/CensorOverlay";
// ---------------------------------------------------------------------------
// THE CITED CLIP (release 32 R1): the seconds a citation names, played so a
@@ -105,6 +106,7 @@ const CitedClip = forwardRef<
const [fetching, setFetching] = useState<CitedFetchAnswer | { state: "asking" } | null>(null);
const [fromStored, setFromStored] = useState(false);
const [now, setNow] = useState(target.from);
+ const [picAspect, setPicAspect] = useState<number | null>(null);
const [playing, setPlaying] = useState(false);
const media = useRef<HTMLMediaElement | null>(null);
const spanning = useRef(false);
@@ -248,6 +250,8 @@ const CitedClip = forwardRef<
tabIndex: -1,
onLoadedMetadata: (e: React.SyntheticEvent<HTMLMediaElement>) => {
e.currentTarget.currentTime = play ? (card ? play.offset : Math.max(0, play.offset - (play.kind === "prepared" ? play.offset : 3))) : 0;
+ const el = e.currentTarget;
+ if (el instanceof HTMLVideoElement && el.videoWidth > 0 && el.videoHeight > 0) setPicAspect(el.videoWidth / el.videoHeight);
if (wantPlay.current) playSpanNow();
},
onTimeUpdate: (e: React.SyntheticEvent<HTMLMediaElement>) => {
@@ -291,13 +295,17 @@ const CitedClip = forwardRef<
<audio {...mediaProps} controls={!card} className={card ? "hidden" : "w-full"} />
</div>
) : (
- <video
- {...mediaProps}
- controls={!card}
- playsInline
- onClick={card ? () => api.playSpan() : undefined}
- className={cn("aspect-video w-full rounded-[3px] bg-black", card && "cursor-pointer")}
- />
+ <div className="relative">
+ <video
+ {...mediaProps}
+ controls={!card}
+ playsInline
+ onClick={card ? () => api.playSpan() : undefined}
+ className={cn("aspect-video w-full rounded-[3px] bg-black", card && "cursor-pointer")}
+ />
+ {/* The project's hidden regions on this recording (clip-censor.mjs): overlaid on the screen, outlined. */}
+ {(play.hidden?.length ?? 0) > 0 && <CensorOverlay regions={play.hidden ?? []} at={now} aspect={picAspect} mode="edit" testId="cited-censor" />}
+ </div>
)}
<div className="flex flex-wrap items-center gap-2">
{card ? (
diff --git a/umtool/components/projects/ClaimBench.tsx b/umtool/components/projects/ClaimBench.tsx
@@ -9,6 +9,7 @@ import { ReaderPane } from "@/components/ui/reader-pane";
import { citationText } from "@/lib/research/facets.mjs";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
import CopyCitation from "./bench/CopyCitation";
+import CensorOverlay, { type CensorRegion } from "./review/CensorOverlay";
import {
POPULATIONS,
SCOPES,
@@ -54,6 +55,8 @@ export type ClaimBenchData = {
source: { title: string | null; uploadDate: string | null; duration: number | null; webpageUrl: string | null } | null;
noCues: boolean;
windows: Array<{ name: string; from: number; to: number }>;
+ /** Its recording's hidden regions (render.censor): overlaid on the window, Peek off by default. */
+ hidden?: CensorRegion[];
gaps: string[];
fired: Array<{ rule: string; text: string }>;
prev: string | null;
@@ -183,6 +186,8 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
// is playable with no download at all -- which is most of them once a build
// has run, because the build already over-fetched around every clip.
const cached = data.windows[0] ?? null;
+ const [hiddenAt, setHiddenAt] = useState<number | null>(null);
+ const [hiddenAspect, setHiddenAspect] = useState<number | null>(null);
const roles = useMemo(() => parseRoles(roleText), [roleText]);
const rosterPreview = roles.ok ? rosterLine(roles.list) : null;
@@ -384,14 +389,23 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
<div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_360px]">
<div className="space-y-3">
{cached ? (
- <video
- ref={video}
- data-testid="claim-video"
- src={`/api/report/raw?project=${encodeURIComponent(data.project)}&claim=${encodeURIComponent(claim.id)}&file=${encodeURIComponent(cached.name)}`}
- className="aspect-video w-full rounded border border-[var(--color-line)] bg-black"
- preload="metadata"
- controls
- />
+ <div className="relative">
+ <video
+ ref={video}
+ data-testid="claim-video"
+ src={`/api/report/raw?project=${encodeURIComponent(data.project)}&claim=${encodeURIComponent(claim.id)}&file=${encodeURIComponent(cached.name)}`}
+ className="aspect-video w-full rounded border border-[var(--color-line)] bg-black"
+ preload="metadata"
+ controls
+ onLoadedMetadata={(e) => {
+ const el = e.currentTarget;
+ if (el.videoWidth > 0 && el.videoHeight > 0) setHiddenAspect(el.videoWidth / el.videoHeight);
+ }}
+ onTimeUpdate={(e) => setHiddenAt(cached.from + e.currentTarget.currentTime)}
+ onSeeked={(e) => setHiddenAt(cached.from + e.currentTarget.currentTime)}
+ />
+ {(data.hidden?.length ?? 0) > 0 && <CensorOverlay regions={data.hidden ?? []} at={hiddenAt} aspect={hiddenAspect} mode="edit" testId="claim-censor" />}
+ </div>
) : (
<div className="flex aspect-video w-full flex-col items-center justify-center gap-2 rounded border border-dashed border-[var(--color-line)] text-[12px] text-[var(--color-dim)]">
<div>no cached window covers this moment</div>
diff --git a/umtool/components/projects/ClaimBenchPage.tsx b/umtool/components/projects/ClaimBenchPage.tsx
@@ -5,6 +5,7 @@ import ClaimBench, { type ClaimBenchData } from "./ClaimBench";
import { manifestToken } from "@/lib/report/manifest.mjs";
import { readClaimDetail, readManifest } from "@/lib/projects/report.mjs";
import { ledgerTotals } from "umtool-report-to-video/ledger-totals";
+import { recordingRegionsOf } from "umtool-report-to-video/clip-censor";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import type { ProjectRef } from "@/lib/project-types";
@@ -74,6 +75,8 @@ export default async function ClaimBenchPage({
source: detail.source,
noCues: detail.noCues,
windows: detail.windows,
+ // Its recording's hidden regions (render.censor, clip-censor.mjs): overlaid on the window it plays.
+ hidden: recordingRegionsOf((detail.claim.video as string) ?? null, (detail.claim.channel as string) ?? null, manifest.render ?? {}, manifest.provenance ?? {}),
gaps: detail.gaps,
fired,
prev: i > 0 ? String(ledger[i - 1].id) : null,
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -41,6 +41,7 @@ import { CutEdges } from "./bench/CutEdges";
import { sourceWindowMedia } from "./bench/benchMedia";
import { useBenchPlayer } from "./bench/useBenchPlayer";
import { usePeaks } from "./bench/usePeaks";
+import CensorOverlay, { type CensorRegion } from "./review/CensorOverlay";
import {
DeckFrame,
NeutralFrame,
@@ -317,6 +318,8 @@ export type ClipBenchData = {
siblings: Sibling[];
/** Is the cut built with the on-screen panel (`render.chrome`)? */
deckOn: boolean;
+ /** Every region the cut hides on this clip (clip-censor.mjs censorRegionsOf): drawn over the raw window. */
+ hidden?: CensorRegion[];
/** The manifest's `generatedBy`: edits here are noted for the agent that runs it. */
generatedBy?: string | null;
/**
@@ -765,6 +768,9 @@ export default function ClipBench({
// The widest cached file is the one the bench draws from: it is how much room
// there is to drag before anything has to be fetched.
const cached = windows[0] ?? null;
+ // The raw window's picture and second, for its hidden regions (CensorOverlay).
+ const [benchAspect, setBenchAspect] = useState<number | null>(null);
+ const [benchAt, setBenchAt] = useState<number | null>(null);
const fetchStart = cached?.from ?? 0;
const cachedTo = cached?.to ?? 0;
@@ -2932,7 +2938,30 @@ export default function ClipBench({
>
{placeBar}
<div className="flex md:contents">
- {cached ? (
+ {cached && (data.hidden?.length ?? 0) > 0 ? (
+ // With hidden regions the picture sits in a box of its own, the regions drawn over it (an editing
+ // surface: outlined, a Peek toggle off by default). Without, the <video> is the flex item as before.
+ <div
+ data-bench-censor=""
+ className={cn("relative aspect-video w-full lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]", inspector && "hidden")}
+ >
+ <video
+ ref={video}
+ data-testid="clip-video"
+ src={media.src ?? undefined}
+ className="absolute inset-0 h-full w-full rounded border border-[var(--color-line)] bg-black object-contain"
+ preload="metadata"
+ controls
+ onLoadedMetadata={(e) => {
+ const el = e.currentTarget;
+ if (el.videoWidth > 0 && el.videoHeight > 0) setBenchAspect(el.videoWidth / el.videoHeight);
+ }}
+ onTimeUpdate={(e) => setBenchAt((cached?.from ?? 0) + e.currentTarget.currentTime)}
+ onSeeked={(e) => setBenchAt((cached?.from ?? 0) + e.currentTarget.currentTime)}
+ />
+ <CensorOverlay regions={data.hidden ?? []} at={benchAt} aspect={benchAspect} mode="edit" testId="bench-censor" />
+ </div>
+ ) : cached ? (
<video
ref={video}
data-testid="clip-video"
diff --git a/umtool/components/projects/present/PresentView.tsx b/umtool/components/projects/present/PresentView.tsx
@@ -6,6 +6,7 @@ import PostItemPlayer, { postItemAssets, type CardView, type PostPlan, type Prog
import ComboBadge, { type ComboInfo } from "../review/ComboBadge";
import { postPreload } from "../review/playEngine/postPreload";
import IntroCardPlayer, { type IntroPage } from "../review/IntroCardPlayer";
+import CensorOverlay, { type CensorRegion } from "../review/CensorOverlay";
import { aModalIsOpen } from "@/components/ui/modalOpen";
// ---------------------------------------------------------------------------
@@ -51,6 +52,13 @@ type ClipSlide = SlideBase & {
quote: string | null;
qrUrl: string | null;
blur: { strength: number; caption: string; from: number | null; to: number | null } | null;
+ /** Its hidden regions (clip-censor.mjs): overlaid on the raw window on the operator's page -- no toggle lifts them. */
+ hidden?: CensorRegion[];
+ /**
+ * A PUBLIC payload of a clip with hidden regions (no `media`: the raw window is never named): its built segment,
+ * which hides them in the file (`segment` its version), or null -- the slide says the clip is not shown.
+ */
+ censored?: { segment: number; seconds: number | null } | null;
};
type TextSlide = SlideBase & { kind: "section" | "day" | "teaser" | "card"; lines?: string[]; tail?: string | null; seconds?: number | null; heading?: string; within?: string | null };
type VideoSlide = SlideBase & { kind: "video"; src: string; from: number; to: number; seconds: number };
@@ -479,10 +487,16 @@ function ClipView({ slide, project, take, playing, sound, censor, onDone }: { sl
const video = useRef<HTMLVideoElement | null>(null);
const [at, setAt] = useState<number | null>(null);
const [done, setDone] = useState(false);
+ const [aspect, setAspect] = useState<number | null>(null);
const media = slide.media;
+ // A public page's clip with hidden regions plays its BUILT segment (the regions burned in), whole, or nothing.
+ const built = !media && slide.censored ? slide.censored : null;
+ const withheld = !media && slide.censored === null;
const src = media
? `/api/report/raw?${new URLSearchParams({ project, clip: slide.entry ?? slide.id, ...(take ? { take } : {}), file: media.name, ...(media.v ? { v: media.v } : {}) }).toString()}`
- : null;
+ : built
+ ? `/api/report/segment?${new URLSearchParams({ project, clip: slide.entry ?? slide.id, v: String(built.segment) }).toString()}`
+ : null;
// Where it is in its source, followed every frame; past a span's end, on to the next, past the last, done.
useEffect(() => {
const v = video.current;
@@ -513,12 +527,12 @@ function ClipView({ slide, project, take, playing, sound, censor, onDone }: { sl
else if (!v.paused) v.pause();
}, [playing, done]);
useEffect(() => {
- if (!media && slide.spans.length) {
+ if (!media && !built && slide.spans.length) {
// Not fetched: nothing plays, and the slide reads for its length.
const t = setTimeout(() => setDone(true), slide.seconds * 1000);
return () => clearTimeout(t);
}
- }, [media, slide.spans.length, slide.seconds]);
+ }, [media, built, slide.spans.length, slide.seconds]);
const blurNow = censor && slide.blur && at !== null && (slide.blur.from === null || at >= slide.blur.from) && (slide.blur.to === null || at < slide.blur.to);
return (
<div data-present-clip={slide.id} data-present-clip-at={at === null ? "" : at.toFixed(2)} data-present-clip-done={done ? "1" : "0"} className="absolute inset-0 flex flex-col bg-black" style={{ containerType: "size" }}>
@@ -532,17 +546,22 @@ function ClipView({ slide, project, take, playing, sound, censor, onDone }: { sl
muted={!sound}
data-present-clip-video=""
data-present-clip-blurred={blurNow ? "1" : "0"}
+ data-present-clip-built={built ? "1" : undefined}
+ onEnded={built ? () => setDone(true) : undefined}
onLoadedMetadata={(e) => {
+ const el = e.currentTarget;
+ if (el.videoWidth > 0 && el.videoHeight > 0) setAspect(el.videoWidth / el.videoHeight);
if (media && slide.spans[0]) e.currentTarget.currentTime = Math.max(0, slide.spans[0].from - media.from);
}}
className="absolute inset-0 h-full w-full object-contain"
style={{ filter: blurNow && slide.blur ? `blur(${slide.blur.strength}cqh)` : undefined }}
/>
) : (
- <div data-present-clip-missing="" className="absolute inset-0 flex items-center justify-center text-[2.4cqh] text-white/50">
- not fetched yet — its words below
+ <div data-present-clip-missing={withheld ? "withheld" : ""} className="absolute inset-0 flex items-center justify-center px-[4cqh] text-center text-[2.4cqh] text-white/50">
+ {withheld ? "this clip hides parts of its picture, and no build of it is here: it is not shown on this page — its words below" : "not fetched yet — its words below"}
</div>
)}
+ {media && src && (slide.hidden?.length ?? 0) > 0 && <CensorOverlay regions={slide.hidden ?? []} at={at} aspect={aspect} mode="cover" testId="present-clip-censor" />}
{blurNow && slide.blur && (
<div className="pointer-events-none absolute inset-x-0 top-[5%] text-center text-[3.2cqh] font-semibold text-white drop-shadow">{slide.blur.caption}</div>
)}
diff --git a/umtool/components/projects/report/CandidatesPanel.tsx b/umtool/components/projects/report/CandidatesPanel.tsx
@@ -6,6 +6,7 @@ import { badgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { MANIFEST_CHANGED, announceManifestChanged } from "../timelineApi";
+import CensorOverlay, { type CensorRegion } from "../review/CensorOverlay";
// ---------------------------------------------------------------------------
// THE CANDIDATES INBOX on the Cut tab (UI notes item 14). A sweep or an agent
@@ -53,6 +54,8 @@ type View = {
groups: { id: string; claim: string; section: number; ids: string[] }[];
token: string | null;
playable: Record<string, boolean>;
+ /** Each candidate's recording's hidden regions (render.censor): overlaid on its player. */
+ hidden?: Record<string, CensorRegion[]>;
};
const clock = (t: number) => {
@@ -63,9 +66,11 @@ const clock = (t: number) => {
};
/** The cited moment, played here from a cached window (seeked to its second). */
-function InlinePlayer({ project, c }: { project: string; c: Candidate }) {
+function InlinePlayer({ project, c, hidden = [] }: { project: string; c: Candidate; hidden?: CensorRegion[] }) {
const ref = useRef<HTMLVideoElement | null>(null);
const [from, setFrom] = useState<number | null>(null);
+ const [at, setAt] = useState<number | null>(null);
+ const [aspect, setAspect] = useState<number | null>(null);
const [err, setErr] = useState<string | null>(null);
const src = `/api/report/raw?project=${encodeURIComponent(project)}&candidate=${encodeURIComponent(c.id)}`;
useEffect(() => {
@@ -83,7 +88,7 @@ function InlinePlayer({ project, c }: { project: string; c: Candidate }) {
}, [src]);
if (err) return <span className="text-[11px] text-[var(--color-bad)]">could not play: {err}</span>;
if (from === null) return <span className="text-[11px] text-[var(--color-dim)]">opening…</span>;
- return (
+ const video = (
<video
ref={ref}
data-candidate-player={c.id}
@@ -91,12 +96,24 @@ function InlinePlayer({ project, c }: { project: string; c: Candidate }) {
controls
autoPlay
preload="auto"
- className="mt-1 w-full max-w-md rounded border border-[var(--color-line)]"
+ className={hidden.length ? "w-full rounded border border-[var(--color-line)]" : "mt-1 w-full max-w-md rounded border border-[var(--color-line)]"}
onLoadedMetadata={(e) => {
e.currentTarget.currentTime = Math.max(0, c.t - from);
+ const el = e.currentTarget;
+ if (el.videoWidth > 0 && el.videoHeight > 0) setAspect(el.videoWidth / el.videoHeight);
}}
+ onTimeUpdate={hidden.length ? (e) => setAt(from + e.currentTarget.currentTime) : undefined}
+ onSeeked={hidden.length ? (e) => setAt(from + e.currentTarget.currentTime) : undefined}
/>
);
+ if (!hidden.length) return video;
+ // Its recording's hidden regions, over the picture (outlined, Peek off by default).
+ return (
+ <div className="relative mt-1 w-full max-w-md">
+ {video}
+ <CensorOverlay regions={hidden} at={at} aspect={aspect} mode="edit" testId="candidate-censor" />
+ </div>
+ );
}
export default function CandidatesPanel({ project }: { project: string }) {
@@ -310,7 +327,7 @@ export default function CandidatesPanel({ project }: { project: string }) {
</button>
</div>
)}
- {playing === c.id && <InlinePlayer project={project} c={c} />}
+ {playing === c.id && <InlinePlayer project={project} c={c} hidden={view.hidden?.[c.id] ?? []} />}
</li>
);
})}
diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx
@@ -43,8 +43,14 @@ type Look = {
slide?: { travel?: number; blur?: number; grain?: number } | null;
blur?: string;
intro?: string | { style?: string; [k: string]: unknown } | null;
+ promo?: Promo | null;
+ zooms?: { soften?: number } | null;
+ desktop?: { tag?: boolean; qr?: boolean | { corner?: string; size?: number; links?: string }; captions?: { size?: string; lines?: number }; [k: string]: unknown } | null;
};
type Mode = "deck" | "basic";
+/** The channel promo (render.promo, report-to-video promo-card.mjs): the card a per-clip build ends on. */
+type Promo = { name?: string | string[]; url?: string; qr?: string | false; portrait?: { file: string; box?: number[] }; kicker?: string; palette?: Record<string, string>; lead?: number; fade?: number; hold?: number; captions?: boolean; [k: string]: unknown };
+const PROMO_DEFAULTS = { lead: 4.5, fade: 0.7, hold: 1.5 } as const;
type View = { look: Look; mode?: Mode; preset?: string | null; deck: boolean; montage: boolean; styles: string[]; introStyles?: string[]; errors: string[]; token: string | null };
/** The intro's style as written: a bare name or the object's `style`; "" for none. */
@@ -56,6 +62,8 @@ type Draft = {
header: boolean;
footer: boolean;
qr: boolean;
+ qrCorner: string;
+ qrLinks: string;
transition: string;
style: string;
loudness: "off" | "-16" | "custom";
@@ -74,14 +82,86 @@ type Draft = {
blur: "on" | "off";
intro: string;
mode: Mode;
+ deskTag: boolean;
+ deskQr: string;
+ deskSize: string;
+ promoOn: boolean;
+ promoName1: string;
+ promoName2: string;
+ promoUrl: string;
+ promoQr: boolean;
+ promoLead: string;
+ promoFade: string;
+ promoHold: string;
+ promoCaptions: boolean;
+ zoomSoft: string;
};
+/** A desktop clip's code as the panel shows it: off, or its corner (br when on with none). */
+const deskQrOf = (d: Look["desktop"]) => (!d?.qr ? "off" : typeof d.qr === "object" ? (d.qr.corner ?? "br") : "br");
+
+/** render.desktop as the draft would write it: only what is off its default; null for none. */
+function desktopNext(was: Look["desktop"], d: Draft): Look["desktop"] {
+ const { tag: _t, qr: _q, captions: _c, ...rest } = was ?? {};
+ const next: NonNullable<Look["desktop"]> = { ...rest };
+ if (!d.deskTag) next.tag = false;
+ if (d.deskQr !== "off") {
+ const old = was?.qr && typeof was.qr === "object" ? was.qr : {};
+ const { corner: _k, ...keep } = old;
+ next.qr = d.deskQr === "br" && !Object.keys(keep).length ? true : { ...keep, ...(d.deskQr !== "br" ? { corner: d.deskQr } : {}) };
+ }
+ const caps = { ...(was?.captions ?? {}) };
+ if (d.deskSize === "l") delete caps.size;
+ else caps.size = d.deskSize;
+ if (Object.keys(caps).length) next.captions = caps;
+ return Object.keys(next).length ? next : null;
+}
+
+/** The promo's fields as the panel edits them. */
+function promoDraftOf(p: Look["promo"]) {
+ const lines = Array.isArray(p?.name) ? p.name : typeof p?.name === "string" ? [p.name] : [];
+ return {
+ promoOn: !!p,
+ promoName1: lines[0] ?? "",
+ promoName2: lines[1] ?? "",
+ promoUrl: p?.url ?? "",
+ promoQr: p?.qr !== false,
+ promoLead: String(p?.lead ?? PROMO_DEFAULTS.lead),
+ promoFade: String(p?.fade ?? PROMO_DEFAULTS.fade),
+ promoHold: String(p?.hold ?? PROMO_DEFAULTS.hold),
+ promoCaptions: p?.captions !== false,
+ };
+}
+
+/** render.promo as the draft would write it (the portrait, colours and kicker kept as written); null: none. */
+function promoNext(was: Look["promo"], d: Draft): Look["promo"] {
+ if (!d.promoOn) return null;
+ const { name: _n, url: _u, qr: _q, lead: _l, fade: _f, hold: _h, captions: _c, ...keep } = was ?? {};
+ const n1 = d.promoName1.trim();
+ const n2 = d.promoName2.trim();
+ const next: Promo = { ...keep, name: n2 ? [n1, n2] : n1, url: d.promoUrl.trim() };
+ if (!d.promoQr) next.qr = false;
+ else if (typeof was?.qr === "string") next.qr = was.qr;
+ for (const [k, v] of [["lead", d.promoLead], ["fade", d.promoFade], ["hold", d.promoHold]] as const) {
+ const n = Number(v);
+ if (n !== PROMO_DEFAULTS[k]) next[k] = n;
+ }
+ if (!d.promoCaptions) next.captions = false;
+ return next;
+}
+
+/** One of render.qr's settings (the clip kit: corner, links), or its default. */
+const qrField = (qr: unknown, k: "corner" | "links", dflt: string) =>
+ qr && typeof qr === "object" && typeof (qr as Record<string, unknown>)[k] === "string" ? String((qr as Record<string, unknown>)[k]) : dflt;
+
function draftOf(l: Look, mode: Mode = "deck"): Draft {
const t = l.loudness?.target;
return {
header: l.headerHeight !== 0,
footer: l.footerHeight !== 0,
qr: l.qr !== false,
+ qrCorner: qrField(l.qr, "corner", "br"),
+ qrLinks: qrField(l.qr, "links", "cite"),
transition: String(l.transition ?? 0.5),
style: l.transitionStyle ?? "fade",
loudness: typeof t !== "number" ? "off" : t === -16 ? "-16" : "custom",
@@ -100,6 +180,11 @@ function draftOf(l: Look, mode: Mode = "deck"): Draft {
blur: l.blur === "off" ? "off" : "on",
intro: introStyleOf(l.intro),
mode,
+ deskTag: l.desktop?.tag !== false,
+ deskQr: deskQrOf(l.desktop),
+ deskSize: l.desktop?.captions?.size ?? "l",
+ ...promoDraftOf(l.promo),
+ zoomSoft: String(l.zooms?.soften ?? 1),
};
}
@@ -115,6 +200,10 @@ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
if (d.header !== (was.headerHeight !== 0)) p.headerHeight = d.header ? null : 0;
if (d.footer !== (was.footerHeight !== 0)) p.footerHeight = d.footer ? null : 0;
if (d.qr !== (was.qr !== false)) p.qr = d.qr;
+ // The code's corner and link (the clip kit): merged into render.qr, a default written as no key.
+ if (d.qr && (d.qrCorner !== qrField(was.qr, "corner", "br") || d.qrLinks !== qrField(was.qr, "links", "cite"))) {
+ p.qr = { corner: d.qrCorner === "br" ? null : d.qrCorner, links: d.qrLinks === "cite" ? null : d.qrLinks };
+ }
const tr = Number(d.transition);
if (tr !== (was.transition ?? 0.5)) p.transition = tr;
if (d.style !== (was.transitionStyle ?? "fade")) p.transitionStyle = d.style === "fade" ? null : d.style;
@@ -145,6 +234,18 @@ 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 channel promo (render.promo): the card a per-clip build ends on.
+ {
+ const next = promoNext(was.promo, d);
+ if (JSON.stringify(next ?? null) !== JSON.stringify(was.promo ?? null)) p.promo = next;
+ }
+ // The zooms' soft limit (render.zooms.soften, clip-zoom.mjs): 1 (strict) is no key.
+ if (Number(d.zoomSoft) !== (was.zooms?.soften ?? 1)) p.zooms = Number(d.zoomSoft) === 1 ? null : { soften: Number(d.zoomSoft) };
+ // The desktop clips (render.desktop, the clip kit): the source line, a code, the captions' size.
+ {
+ const next = desktopNext(was.desktop, d);
+ if (JSON.stringify(next ?? null) !== JSON.stringify(was.desktop ?? null)) p.desktop = next;
+ }
// The output mode (render.mode): the writer keeps "deck" as no key unless a look preset's must be beaten.
if (d.mode !== (view.mode ?? "deck")) p.mode = d.mode;
// The blurred clips (render.blur): "on" is the default, written as no key.
@@ -173,6 +274,8 @@ export default function LookPanel({ project }: { project: string }) {
const [status, setStatus] = useState<string | null>(null);
// Bumped when this panel writes the manifest, so the Ask box re-reads its token.
const [version, setVersion] = useState(0);
+ // The channel promo's card drawn (its two images asked for again with this number).
+ const [cardsAt, setCardsAt] = useState(0);
const load = useCallback(async () => {
const r = await fetch(`/api/report/render?project=${encodeURIComponent(project)}`, { cache: "no-store" });
@@ -268,6 +371,25 @@ export default function LookPanel({ project }: { project: string }) {
{check("header", "Header", "data-look-header")}
{check("footer", "Timeline footer", "data-look-footer")}
{check("qr", "QR code", "data-look-qr")}
+ {draft.qr && !view.deck && (
+ <>
+ <Field label="QR corner">
+ <Select data-look-qr-corner="" value={draft.qrCorner} disabled={busy} onChange={(e) => set({ qrCorner: e.target.value })}>
+ <option value="br">bottom right</option>
+ <option value="bl">bottom left</option>
+ <option value="tr">top right</option>
+ <option value="tl">top left</option>
+ </Select>
+ </Field>
+ <Field label="QR links" hint="moment: the source at the clip's second">
+ <Select data-look-qr-links="" value={draft.qrLinks} disabled={busy} onChange={(e) => set({ qrLinks: e.target.value })}>
+ <option value="cite">the clip's link</option>
+ <option value="moment">the source at the clip's second</option>
+ <option value="channel">the channel (the promo's page)</option>
+ </Select>
+ </Field>
+ </>
+ )}
</div>
<div className="mt-3 flex flex-wrap items-end gap-4">
<Field label="Between clips, s">
@@ -313,6 +435,85 @@ export default function LookPanel({ project }: { project: string }) {
</Field>
)}
</div>
+ <div className="mt-3 space-y-2" data-look-promo="">
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-2">
+ <span className="text-[12.5px] text-text-2" title="the card a short or a desktop clip ends on: umtool look <p> promo={…}">Channel promo</span>
+ {check("promoOn", "End clips on the channel's card", "data-look-promo-on")}
+ </div>
+ {draft.promoOn && (
+ <>
+ <div className="flex flex-wrap items-end gap-3">
+ <Field label="Name">
+ <Input data-look-promo-name1="" value={draft.promoName1} disabled={busy} onChange={(e) => set({ promoName1: e.target.value })} className="w-[12em]" />
+ </Field>
+ <Field label="Second line">
+ <Input data-look-promo-name2="" value={draft.promoName2} disabled={busy} onChange={(e) => set({ promoName2: e.target.value })} className="w-[12em]" />
+ </Field>
+ <Field label="Channel page">
+ <Input data-look-promo-url="" value={draft.promoUrl} disabled={busy} placeholder="https://kick.com/…" onChange={(e) => set({ promoUrl: e.target.value })} className="w-[18em]" />
+ </Field>
+ {check("promoQr", "QR to the page", "data-look-promo-qr")}
+ </div>
+ <div className="flex flex-wrap items-end gap-3">
+ <Field label="Comes up, s before the end">
+ <Input data-look-promo-lead="" type="number" min={1} max={10} step={0.1} value={draft.promoLead} disabled={busy} onChange={(e) => set({ promoLead: e.target.value })} className="w-[5.5em]" />
+ </Field>
+ <Field label="Fade, s">
+ <Input data-look-promo-fade="" type="number" min={0.2} max={2} step={0.1} value={draft.promoFade} disabled={busy} onChange={(e) => set({ promoFade: e.target.value })} className="w-[5.5em]" />
+ </Field>
+ <Field label="Held silent, s">
+ <Input data-look-promo-hold="" type="number" min={0} max={5} step={0.1} value={draft.promoHold} disabled={busy} onChange={(e) => set({ promoHold: e.target.value })} className="w-[5.5em]" />
+ </Field>
+ {check("promoCaptions", "Captions over the card", "data-look-promo-captions")}
+ </div>
+ <p className="m-0 text-[12px] text-muted" data-look-promo-portrait="">
+ {view.look.promo?.portrait?.file ? `Portrait: ${view.look.promo.portrait.file}` : "No portrait yet"} — set it from the clip editor’s Short panel (<i>Use this frame as the promo portrait</i>)
+ </p>
+ {view.look.promo && !dirty && (
+ <span className="flex flex-wrap items-start gap-2">
+ <button type="button" data-look-promo-draw="" disabled={busy} onClick={() => setCardsAt(Date.now())} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Draw the card
+ </button>
+ {cardsAt > 0 && (
+ <>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img data-look-promo-card="v" alt="the card, 9:16" src={`/api/report/promo-card?project=${encodeURIComponent(project)}&shape=v&n=${cardsAt}`} className="h-[220px] rounded-[3px] border border-seam-2" />
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img data-look-promo-card="h" alt="the card, 16:9" src={`/api/report/promo-card?project=${encodeURIComponent(project)}&shape=h&n=${cardsAt}`} className="h-[124px] rounded-[3px] border border-seam-2" />
+ </>
+ )}
+ </span>
+ )}
+ </>
+ )}
+ </div>
+ <div className="mt-3 flex flex-wrap items-end gap-x-5 gap-y-2" data-look-desktop="">
+ <span className="text-[12.5px] text-text-2" title="umtool vertical --desktop, umtool shorts --formats desktop: 16:9, the picture full frame">Desktop clips</span>
+ {check("deskTag", "Source line", "data-look-desktop-tag")}
+ <Field label="QR">
+ <Select data-look-desktop-qr="" value={draft.deskQr} disabled={busy} onChange={(e) => set({ deskQr: e.target.value })}>
+ <option value="off">none</option>
+ <option value="br">bottom right</option>
+ <option value="bl">bottom left</option>
+ <option value="tr">top right</option>
+ <option value="tl">top left</option>
+ </Select>
+ </Field>
+ <Field label="Zooms" hint="past the source's own pixels">
+ <Select data-look-zoom-soft="" value={draft.zoomSoft} disabled={busy} onChange={(e) => set({ zoomSoft: e.target.value })}>
+ <option value="1">never (sharp)</option>
+ <option value="1.15">up to ×1.15 soft</option>
+ <option value="1.3">up to ×1.3 soft</option>
+ </Select>
+ </Field>
+ <Field label="Captions">
+ <Select data-look-desktop-size="" value={draft.deskSize} disabled={busy} onChange={(e) => set({ deskSize: e.target.value })}>
+ <option value="m">medium</option>
+ <option value="l">large</option>
+ <option value="xl">extra large</option>
+ </Select>
+ </Field>
+ </div>
{!view.montage && (
<div className="mt-3 flex flex-wrap items-center gap-x-5 gap-y-2" data-look-room="">
<span className="text-[12.5px] text-text-2">Room at the clips’ edges</span>
diff --git a/umtool/components/projects/review/CensorOverlay.tsx b/umtool/components/projects/review/CensorOverlay.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+
+// HIDDEN REGIONS OVER A PLAYER (lane clip-kit, slice E; report-to-video clip-censor.mjs). Where a clip's raw window
+// plays -- Present (its public page too), the clip editor, the bench -- the boxes its recording and the clip hide are
+// drawn over the picture: the same boxes (fractions of the source picture), the same spans (source seconds), black
+// where the build fills black, a heavy backdrop blur where it blurs or pixelates. `mode`:
+// "cover" opaque, always (Present: a viewer, public or not, never sees the region)
+// "edit" an editing surface: the fill and a dashed outline, and a Peek toggle (OFF by default) that drops the fill
+// The picture's rect inside the player is measured (an element fitted with object-contain), so the boxes stand on
+// the picture, not on its letterbox.
+
+export type CensorRegion = { box: number[]; style: "blur" | "black" | "pixelate"; strength: number; from: number | null; to: number | null };
+
+/** The regions over source second `at` (all, when `at` is unknown: a still frame shows them all). */
+export const regionsAt = (regions: CensorRegion[], at: number | null) =>
+ regions.filter((g) => at === null || ((g.from === null || at >= g.from - 1e-6) && (g.to === null || at <= g.to + 1e-6)));
+
+export default function CensorOverlay({ regions, at, aspect, mode = "cover", testId = "censor-overlay" }: {
+ regions: CensorRegion[];
+ at: number | null;
+ /** The picture's width / height (its videoWidth / videoHeight); null until known (the whole box is used). */
+ aspect: number | null;
+ mode?: "cover" | "edit";
+ testId?: string;
+}) {
+ const box = useRef<HTMLDivElement | null>(null);
+ const [size, setSize] = useState<{ w: number; h: number } | null>(null);
+ const [peek, setPeek] = useState(false);
+ useEffect(() => {
+ const el = box.current;
+ if (!el) return;
+ const ro = new ResizeObserver(() => setSize({ w: el.clientWidth, h: el.clientHeight }));
+ ro.observe(el);
+ setSize({ w: el.clientWidth, h: el.clientHeight });
+ return () => ro.disconnect();
+ }, []);
+ const now = regionsAt(regions, at);
+ // The picture's rect in the player (object-contain).
+ let pic = { x: 0, y: 0, w: size?.w ?? 0, h: size?.h ?? 0 };
+ if (size && aspect && size.w > 0 && size.h > 0) {
+ const k = Math.min(size.w / aspect, size.h);
+ pic = { x: (size.w - k * aspect) / 2, y: (size.h - k) / 2, w: k * aspect, h: k };
+ }
+ return (
+ <div ref={box} data-testid={testId} data-censor-overlay={mode} data-censor-now={now.length} className="pointer-events-none absolute inset-0 overflow-hidden">
+ {size &&
+ now.map((g, i) => {
+ const fill = mode === "edit" && peek ? {} : g.style === "black" ? { background: "#000" } : { backdropFilter: `blur(${Math.max(8, Math.round(pic.w * g.strength * 0.004 * (g.style === "pixelate" ? 2 : 1)))}px)`, WebkitBackdropFilter: `blur(${Math.max(8, Math.round(pic.w * g.strength * 0.004))}px)`, background: "rgba(0,0,0,0.25)" };
+ return (
+ <div
+ key={i}
+ data-censor-region={i}
+ data-censor-style={g.style}
+ style={{
+ position: "absolute",
+ left: pic.x + g.box[0] * pic.w,
+ top: pic.y + g.box[1] * pic.h,
+ width: g.box[2] * pic.w,
+ height: g.box[3] * pic.h,
+ ...fill,
+ ...(mode === "edit" ? { outline: "2px dashed rgba(255,80,80,0.9)", outlineOffset: -2 } : {}),
+ }}
+ />
+ );
+ })}
+ {mode === "edit" && regions.length > 0 && (
+ <button
+ type="button"
+ data-censor-peek=""
+ aria-pressed={peek}
+ onClick={() => setPeek(!peek)}
+ className="pointer-events-auto absolute right-1 top-1 rounded-[3px] bg-black/70 px-1.5 py-0.5 text-[11px] text-white"
+ title="the hidden regions are drawn as the cut hides them; peek shows the picture under them here only"
+ >
+ {peek ? "Hide again" : "Peek"}
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -18,6 +18,7 @@ import { refusalOf, timelineOp } from "../timelineApi";
import AssistBox from "../report/AssistBox";
import { AudioBox, BlurBox, MarksBox } from "./ClipKnobs";
import LiveDeckPreview from "./LiveDeckPreview";
+import CensorOverlay, { type CensorRegion } from "./CensorOverlay";
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional).
import type { ReplyProposal } from "@/lib/annotations/types";
import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest";
@@ -565,7 +566,7 @@ export default function ClipEditor({
</p>
)}
- <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} frame={framing ? { crop: clip.vertical?.crop ?? null, onChange: setCrop, busy } : null} />
+ <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} frame={framing ? { crop: clip.vertical?.crop ?? null, onChange: setCrop, busy } : null} hidden={clip.hidden ?? []} at={playhead} />
<LiveDeckPreview project={project} clip={clip} cut={cut} token={view.token} player={player} write={write} busy={busy} blurRendered={view.blur?.rendered ?? true} />
{/* ---- the strip --------------------------------------------------- */}
@@ -890,7 +891,7 @@ export default function ClipEditor({
{view.reactionsError && <p className="m-0 text-[12px] text-reject-text">{view.reactionsError}</p>}
{view.rulingsError && <p className="m-0 text-[12px] text-reject-text">{view.rulingsError}</p>}
- <ShortMaker project={project} clipId={clip.id} short={view.shorts?.[clip.id] ?? null} framed={!!clip.vertical} framing={framing} onFraming={setFraming} onCentre={() => setCrop(null)} onMade={() => void reload().catch(() => {})} busy={busy} live={view.live?.status === "live"} />
+ <ShortMaker project={project} clipId={clip.id} short={view.shorts?.[clip.id] ?? null} framed={!!clip.vertical} framing={framing} onFraming={setFraming} onCentre={() => setCrop(null)} onMade={() => void reload().catch(() => {})} busy={busy} live={view.live?.status === "live"} kit={clip.kit ?? {}} onKit={(patch, done) => void write({ op: "kit", clip: clip.id, kit: patch }, done)} playhead={playhead} selection={selection} cut={cut} recordingCensor={clip.recordingCensor ?? []} onRecordingCensor={(censor, done) => void write({ op: "censor-recording", clip: clip.id, censor }, done)} />
<RenderTake project={project} render={render} takes={takes} takesHref={takesHref} />
</aside>
</div>
@@ -915,7 +916,7 @@ type Frame = { crop: number[] | null; onChange: (crop: number[] | null, aspect?:
type Target = { channel: string; video: string; from: number; to: number; project: string; clip: string };
-const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void; frame?: Frame | null }>(function Player({ clipId, targets, cut, onTime, onPlaying, frame = null }, ref) {
+const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void; frame?: Frame | null; hidden?: CensorRegion[]; at?: number | null }>(function Player({ clipId, targets, cut, onTime, onPlaying, frame = null, hidden = [], at = null }, ref) {
const [found, setFound] = useState<{ play: CitedPlay; from: number } | null | undefined>(undefined);
const [dims, setDims] = useState<{ w: number; h: number } | null>(null);
const media = useRef<HTMLMediaElement | null>(null);
@@ -1076,6 +1077,7 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
<div className="relative overflow-hidden rounded-[3px]">
<video {...props} playsInline className="aspect-video w-full rounded-[3px] bg-black" />
{frame && dims && <CropBox frame={frame} aspect={dims.w / dims.h} />}
+ {hidden.length > 0 && <CensorOverlay regions={hidden} at={at} aspect={dims ? dims.w / dims.h : null} mode="edit" testId="editor-censor" />}
</div>
)}
{frame && (found.play.audio || !dims) && (
@@ -1591,7 +1593,7 @@ function SpeakerLabel({ speaker, busy, onSave }: { speaker: Speaker; busy: boole
}
/** Make a short: the clip at 1080x1920 from its box, a job; the one there is set aside, never overwritten. */
-function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy, live = false }: {
+function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy, live = false, kit = {}, onKit, playhead = null, selection = null, cut = null, recordingCensor = [], onRecordingCensor }: {
project: string;
clipId: string;
short: { mtimeMs: number; size: number; stale: boolean } | null;
@@ -1604,6 +1606,17 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
// A live pre-clip project (plans/live-preclip.md): Share now cuts the window
// from the recording in progress first (/api/report/live-share).
live?: boolean;
+ // The clip kit (lane clip-kit): this clip's own keys as written, and their writer (op "kit").
+ kit?: NonNullable<EditorClip["kit"]>;
+ onKit?: (patch: Record<string, unknown>, done: string) => void;
+ // The player's source second: the channel promo's portrait is grabbed there.
+ playhead?: number | null;
+ // The strip's selection and the clip's cut: a cold open is a span of the cut (lane clip-kit, slice G).
+ selection?: { cutStart: number; cutEnd: number } | null;
+ cut?: { cutStart: number; cutEnd: number } | null;
+ // Hidden regions (lane clip-kit, slice E): the recording's, and their writer (op "censor-recording").
+ recordingCensor?: NonNullable<EditorClip["recordingCensor"]>;
+ onRecordingCensor?: (censor: Record<string, unknown> | null, done: string) => void;
}) {
const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null);
const [err, setErr] = useState<string | null>(null);
@@ -1639,6 +1652,17 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
else setJob({ id: j.job.id, state: j.job.state, error: j.job.error });
};
const running = job?.state === "running";
+ // The channel promo's portrait: this frame, grabbed into shots/ (/api/report/promo-card).
+ const [portrait, setPortrait] = useState<string | null>(null);
+ const usePortrait = async () => {
+ setErr(null);
+ setPortrait(null);
+ if (playhead === null) return;
+ const r = await fetch("/api/report/promo-card", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "portrait", clip: clipId, at: playhead }) });
+ const j = (await r.json().catch(() => ({}))) as { still?: string; error?: string };
+ if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`);
+ else setPortrait(j.still ?? null);
+ };
return (
<section data-short-maker={clipId} data-short-made={short ? "" : undefined} className="space-y-1.5">
<h2 className="micro m-0">Short</h2>
@@ -1669,6 +1693,56 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
</a>
)}
</div>
+ {onKit && (
+ <label className="flex items-center gap-1.5 text-[12px] text-text-2">
+ QR on this clip
+ <select
+ data-kit-qr={clipId}
+ value={kit.qr === false ? "none" : kit.qr && typeof kit.qr === "object" && kit.qr.corner ? kit.qr.corner : "cut"}
+ disabled={busy}
+ onChange={(e) => {
+ const v = e.target.value;
+ onKit({ qr: v === "cut" ? null : v === "none" ? false : { ...(kit.qr && typeof kit.qr === "object" ? kit.qr : {}), corner: v } }, v === "cut" ? "The cut's QR on this clip" : v === "none" ? "No QR on this clip" : "Saved the clip's QR corner");
+ }}
+ className="rounded-[3px] border border-seam-2 bg-transparent px-1 py-0.5 text-[12px] text-text"
+ >
+ <option value="cut">the cut’s</option>
+ <option value="none">none</option>
+ <option value="tr">top right</option>
+ <option value="tl">top left</option>
+ <option value="br">bottom right (16:9)</option>
+ <option value="bl">bottom left (16:9)</option>
+ </select>
+ </label>
+ )}
+ {onKit && (
+ <div className="flex flex-wrap items-center gap-1.5 text-[12px] text-text-2">
+ <label className="flex items-center gap-1.5">
+ End card
+ <select
+ data-kit-promo={clipId}
+ value={kit.promo === false ? "off" : "cut"}
+ disabled={busy}
+ onChange={(e) => onKit({ promo: e.target.value === "off" ? false : null }, e.target.value === "off" ? "This clip ends without the channel's card" : "This clip ends on the cut's channel card")}
+ className="rounded-[3px] border border-seam-2 bg-transparent px-1 py-0.5 text-[12px] text-text"
+ >
+ <option value="cut">the cut’s channel promo</option>
+ <option value="off">none</option>
+ </select>
+ </label>
+ <button type="button" data-promo-portrait={clipId} disabled={busy || playhead === null} onClick={() => void usePortrait()} className={buttonVariants({ variant: "quiet", size: "sm" })} title="the frame at the playhead, grabbed into shots/, becomes the card's portrait (render.promo.portrait)">
+ Use this frame as the promo portrait
+ </button>
+ {portrait && <span data-promo-portrait-set="">portrait: {portrait}</span>}
+ </div>
+ )}
+ {onKit && (
+ <ColdOpen clipId={clipId} coldOpen={kit.coldOpen && typeof kit.coldOpen === "object" ? (kit.coldOpen as { from: number; to: number }) : null} selection={selection} cut={cut} busy={busy} onKit={onKit} />
+ )}
+ {onKit && onRecordingCensor && (
+ <HideRegions clipId={clipId} own={kit.censor ?? null} recording={recordingCensor[0] ?? null} playhead={playhead} busy={busy} onKit={onKit} onRecording={onRecordingCensor} />
+ )}
+ {onKit && <ZoomList clipId={clipId} zooms={Array.isArray(kit.zooms) ? (kit.zooms as Zoom[]) : []} playhead={playhead} cut={cut} busy={busy} onKit={onKit} />}
{job && (
<p data-short-job={job.state} className="m-0 text-[12px] text-text-2">
{running ? "Rendering 1080×1920 in the heavy slot" : job.state === "done" ? "Made — on the Deliver tab's Shorts list" : `Failed${job.error ? `: ${job.error}` : ""}`}
@@ -1684,6 +1758,209 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
}
// ---------------------------------------------------------------------------
+// Zoom at points (lane clip-kit, report-to-video clip-zoom.mjs): a short's or a desktop clip's picture pushed in at
+// a source second, about a focus (percent of the picture), eased in and out. The build refuses one past the
+// source's pixels (or the cut's soft limit) by name.
+// ---------------------------------------------------------------------------
+
+/** A clip's cold open (report-to-video clip-kit.mjs coldOpenErrors): a span of its cut, 1-4 s, played first. */
+function ColdOpen({ clipId, coldOpen, selection, cut, busy, onKit }: { clipId: string; coldOpen: { from: number; to: number } | null; selection: { cutStart: number; cutEnd: number } | null; cut: { cutStart: number; cutEnd: number } | null; busy: boolean; onKit: (patch: Record<string, unknown>, done: string) => void }) {
+ const r2 = (n: number) => Math.round(n * 100) / 100;
+ const len = selection ? selection.cutEnd - selection.cutStart : 0;
+ const fits = !!selection && !!cut && len >= 1 && len <= 4 && selection.cutStart >= cut.cutStart - 0.02 && selection.cutEnd <= cut.cutEnd + 0.02;
+ return (
+ <div className="flex flex-wrap items-center gap-1.5 text-[12px] text-text-2" data-kit-cold-open={clipId}>
+ <span>Cold open</span>
+ <span data-cold-open-now="">{coldOpen ? `${coldOpen.from.toFixed(2)}–${coldOpen.to.toFixed(2)} s, played first` : "none"}</span>
+ <button
+ type="button"
+ data-cold-open-set={clipId}
+ disabled={busy || !fits}
+ onClick={() => selection && onKit({ coldOpen: { from: r2(selection.cutStart), to: r2(selection.cutEnd) } }, "The selection plays first")}
+ className={buttonVariants({ variant: "quiet", size: "sm" })}
+ title="select 1-4 s of the clip's cut on the strip: a short or a desktop clip plays it first, then cuts to the start"
+ >
+ Cold open from selection
+ </button>
+ {coldOpen && (
+ <button type="button" data-cold-open-clear={clipId} disabled={busy} onClick={() => onKit({ coldOpen: null }, "No cold open")} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Clear
+ </button>
+ )}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Hidden regions (lane clip-kit, report-to-video clip-censor.mjs): a box of the source picture (percent), hidden on
+// every clip of this recording (a chat overlay, a window with other accounts) or on this clip alone -- blurred, black
+// or pixelated, for the whole clip or from / to the playhead. Privacy: on in the uncensored variant too.
+// ---------------------------------------------------------------------------
+
+type CensorSetUi = NonNullable<EditorClip["recordingCensor"]>[number];
+const boxOf = (b: unknown): number[] | null => (Array.isArray(b) ? (b as number[]) : b && typeof b === "object" && Array.isArray((b as { box?: number[] }).box) ? (b as { box: number[] }).box : null);
+const pct = (n: number) => Math.round(n * 1000) / 10;
+
+function HideRegions({ clipId, own, recording, playhead, busy, onKit, onRecording }: {
+ clipId: string;
+ own: unknown;
+ recording: CensorSetUi | null;
+ playhead: number | null;
+ busy: boolean;
+ onKit: (patch: Record<string, unknown>, done: string) => void;
+ onRecording: (censor: Record<string, unknown> | null, done: string) => void;
+}) {
+ const [box, setBox] = useState(["70", "0", "30", "100"]);
+ const [scope, setScope] = useState<"recording" | "clip">("recording");
+ const [style, setStyle] = useState("blur");
+ const [from, setFrom] = useState<number | null>(null);
+ const [to, setTo] = useState<number | null>(null);
+ const ownSet = own && typeof own === "object" ? (own as { boxes?: unknown[]; style?: string }) : null;
+ const frac = box.map((v) => Number(v) / 100);
+ const ok = frac.every((n) => Number.isFinite(n) && n >= 0 && n <= 1) && frac[2] > 0.01 && frac[3] > 0.01 && frac[0] + frac[2] <= 1.0001 && frac[1] + frac[3] <= 1.0001;
+ const r3 = (n: number) => Math.round(n * 1000) / 1000;
+ const entry = (): number[] | { box: number[]; from?: number; to?: number } => {
+ const b = frac.map(r3);
+ return from !== null || to !== null ? { box: b, ...(from !== null ? { from } : {}), ...(to !== null ? { to } : {}) } : b;
+ };
+ const add = () => {
+ if (scope === "recording") onRecording({ boxes: [...(recording?.boxes ?? []), entry()], style: recording?.style ?? style }, "Hidden on every clip of this recording");
+ else onKit({ censor: { ...(ownSet ?? {}), boxes: [...(ownSet?.boxes ?? []), entry()], style: ownSet?.style ?? style } }, "Hidden on this clip");
+ };
+ const list = (boxes: unknown[], remove: (i: number) => void, tag: string) =>
+ boxes.map((b, i) => {
+ const bx = boxOf(b);
+ const span = b && typeof b === "object" && !Array.isArray(b) ? (b as { from?: number; to?: number }) : null;
+ return (
+ <li key={`${tag}${i}`} data-censor-row={`${tag}${i}`} className="flex items-center gap-1.5">
+ <span>
+ {tag === "r" ? "recording" : "this clip"}: {bx ? bx.map(pct).join(", ") : "?"} %{span ? ` (${span.from ?? "start"}–${span.to ?? "end"} s)` : ""}
+ </span>
+ <button type="button" data-censor-remove={`${tag}${i}`} disabled={busy} onClick={() => remove(i)} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label="remove this region">
+ ×
+ </button>
+ </li>
+ );
+ });
+ return (
+ <div className="space-y-1 text-[12px] text-text-2" data-kit-censor={clipId}>
+ <span>Hide regions</span>
+ <ul className="m-0 list-none space-y-0.5 p-0">
+ {list(recording?.boxes ?? [], (i) => {
+ const rest = (recording?.boxes ?? []).filter((_, j) => j !== i);
+ onRecording(rest.length ? { ...recording, boxes: rest, video: undefined, channel: undefined } : null, "Took the region off the recording");
+ }, "r")}
+ {list(ownSet?.boxes ?? [], (i) => {
+ const rest = (ownSet?.boxes ?? []).filter((_, j) => j !== i);
+ onKit({ censor: rest.length ? { ...ownSet, boxes: rest } : null }, "Took the region off this clip");
+ }, "c")}
+ </ul>
+ <div className="flex flex-wrap items-center gap-1">
+ {["x", "y", "w", "h"].map((k, i) => (
+ <input key={k} data-censor-box={k} type="number" min={0} max={100} step={1} value={box[i]} disabled={busy} aria-label={`${k}, % of the picture`} onChange={(e) => setBox(box.map((v, j) => (j === i ? e.target.value : v)))} className="w-[4em] rounded-[3px] border border-seam-2 bg-transparent px-1 text-text" />
+ ))}
+ %
+ <select data-censor-scope="" value={scope} disabled={busy} onChange={(e) => setScope(e.target.value as "recording" | "clip")} className="rounded-[3px] border border-seam-2 bg-transparent px-1 py-0.5 text-text">
+ <option value="recording">every clip of this recording</option>
+ <option value="clip">this clip</option>
+ </select>
+ <select data-censor-style="" value={style} disabled={busy} onChange={(e) => setStyle(e.target.value)} className="rounded-[3px] border border-seam-2 bg-transparent px-1 py-0.5 text-text">
+ <option value="blur">blurred</option>
+ <option value="black">black</option>
+ <option value="pixelate">pixelated</option>
+ </select>
+ <button type="button" data-censor-from="" disabled={busy || playhead === null} onClick={() => setFrom(playhead === null ? null : Math.round(playhead * 100) / 100)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ {from === null ? "From playhead" : `from ${from} s`}
+ </button>
+ <button type="button" data-censor-to="" disabled={busy || playhead === null} onClick={() => setTo(playhead === null ? null : Math.round(playhead * 100) / 100)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ {to === null ? "To playhead" : `to ${to} s`}
+ </button>
+ {(from !== null || to !== null) && (
+ <button type="button" data-censor-whole="" disabled={busy} onClick={() => { setFrom(null); setTo(null); }} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Whole clip
+ </button>
+ )}
+ <button type="button" data-censor-add={clipId} disabled={busy || !ok} onClick={add} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Hide it
+ </button>
+ </div>
+ </div>
+ );
+}
+
+type Zoom = { at: number; scale?: number; hold?: number; focus?: [number, number]; box?: number[]; ramp?: number };
+
+function ZoomList({ clipId, zooms, playhead, cut, busy, onKit }: { clipId: string; zooms: Zoom[]; playhead: number | null; cut: { cutStart: number; cutEnd: number } | null; busy: boolean; onKit: (patch: Record<string, unknown>, done: string) => void }) {
+ const write = (next: Zoom[], done: string) => onKit({ zooms: next.length ? [...next].sort((a, b) => a.at - b.at) : null }, done);
+ // A zoom at the playhead that fits the cut: in and out (0.4 s each way) and held up to 1.5 s, moved back when the
+ // playhead is too near the end (the build refuses one past the clip).
+ const fitted = (): Zoom | null => {
+ if (playhead === null) return null;
+ const end = cut?.cutEnd ?? Infinity;
+ const at = Math.max(cut?.cutStart ?? 0, Math.min(playhead, end - 1.1));
+ const hold = Math.min(1.5, Math.floor((end - at - 0.8) * 10) / 10);
+ return hold >= 0.3 ? { at: Math.round(at * 100) / 100, scale: 1.3, hold } : null;
+ };
+ const change = (i: number, z: Zoom) => write(zooms.map((x, j) => (j === i ? z : x)), "Saved the zoom");
+ return (
+ <div className="space-y-1" data-kit-zooms={clipId}>
+ <div className="flex flex-wrap items-center gap-1.5 text-[12px] text-text-2">
+ <span>Zooms</span>
+ <button
+ type="button"
+ data-zoom-add={clipId}
+ disabled={busy || !fitted()}
+ onClick={() => {
+ const z = fitted();
+ if (z) write([...zooms, z], "A zoom at the playhead");
+ }}
+ className={buttonVariants({ variant: "quiet", size: "sm" })}
+ title="push the picture in at the playhead (×1.3, held 1.5 s, about the picture's centre)"
+ >
+ Zoom here
+ </button>
+ </div>
+ {zooms.map((z, i) => (
+ <div key={`${z.at}-${i}`} data-zoom-row={i} className="flex flex-wrap items-center gap-1.5 text-[12px] text-text-2">
+ <span className="tabular-nums">{z.at.toFixed(2)} s</span>
+ {z.box ? (
+ <span>a box</span>
+ ) : (
+ <>
+ <select
+ data-zoom-scale={i}
+ value={String(z.scale ?? 1.3)}
+ disabled={busy}
+ onChange={(e) => change(i, { ...z, scale: Number(e.target.value) })}
+ className="rounded-[3px] border border-seam-2 bg-transparent px-1 py-0.5 text-[12px] text-text"
+ >
+ {["1.15", "1.3", "1.5", "1.8", "2"].map((v) => (
+ <option key={v} value={v}>
+ ×{v}
+ </option>
+ ))}
+ </select>
+ <label className="flex items-center gap-1">
+ focus
+ <input data-zoom-focus-x={i} type="number" min={0} max={100} step={5} value={Math.round((z.focus?.[0] ?? 0.5) * 100)} disabled={busy} onChange={(e) => change(i, { ...z, focus: [Number(e.target.value) / 100, z.focus?.[1] ?? 0.5] })} className="w-[4em] rounded-[3px] border border-seam-2 bg-transparent px-1 text-text" aria-label="focus, % across" />
+ <input data-zoom-focus-y={i} type="number" min={0} max={100} step={5} value={Math.round((z.focus?.[1] ?? 0.5) * 100)} disabled={busy} onChange={(e) => change(i, { ...z, focus: [z.focus?.[0] ?? 0.5, Number(e.target.value) / 100] })} className="w-[4em] rounded-[3px] border border-seam-2 bg-transparent px-1 text-text" aria-label="focus, % down" />%
+ </label>
+ </>
+ )}
+ <label className="flex items-center gap-1">
+ held
+ <input data-zoom-hold={i} type="number" min={0.3} max={10} step={0.1} value={z.hold ?? 1.5} disabled={busy} onChange={(e) => change(i, { ...z, hold: Number(e.target.value) })} className="w-[4em] rounded-[3px] border border-seam-2 bg-transparent px-1 text-text" />s
+ </label>
+ <button type="button" data-zoom-remove={i} disabled={busy} onClick={() => write(zooms.filter((_, j) => j !== i), "Took the zoom off")} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label="remove this zoom">
+ ×
+ </button>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
// 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`).
diff --git a/umtool/components/projects/review/LiveDeckPreview.tsx b/umtool/components/projects/review/LiveDeckPreview.tsx
@@ -10,6 +10,7 @@ import { clipStamps, clockText, cutTimeAt, finaleUp, liveClock, stampAt, tallyAt
import { tallyCellsFrom, VERDICTS } from "umtool-report-to-video/factcheck";
import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur";
import { drawFootage } from "./footageCanvas";
+import { regionsAt } from "./CensorOverlay";
import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type DeckTexts, type Rect } from "../OnscreenSection";
// ---------------------------------------------------------------------------
@@ -172,6 +173,9 @@ export default function LiveDeckPreview({
const blur = clip.blur && blurRendered ? { strength: clip.blur.strength ?? BLUR_STRENGTH.default, caption: clip.blur.caption ?? BLUR_CAPTION_DEFAULT, from: clip.blur.from ?? null, to: clip.blur.to ?? null } : null;
const blurRef = useRef(blur);
blurRef.current = blur;
+ // Its hidden regions (clip-censor.mjs): drawn always -- the final look hides them whatever render.blur says.
+ const hiddenRef = useRef(clip.hidden ?? []);
+ hiddenRef.current = clip.hidden ?? [];
// Every animation frame while on: the playhead's cut second, and the
// editor's picture drawn into the footage box when it moved.
@@ -198,12 +202,14 @@ export default function LiveDeckPreview({
const video = m instanceof HTMLVideoElement && m.readyState >= 2 && m.videoWidth > 0 ? m : null;
const b = blurRef.current;
const blurNow = b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity) ? b : null;
- const blurKey = blurNow ? `${blurNow.strength}|${blurNow.caption}` : "";
+ const hiddenNow = regionsAt(hiddenRef.current, src);
+ const blurKey = `${blurNow ? `${blurNow.strength}|${blurNow.caption}` : ""}|${hiddenNow.map((g) => g.box.join(",")).join(";")}`;
if (ld.el === el && ld.media === video && ld.t === (video?.currentTime ?? -1) && ld.bg === bgRef.current && ld.size === `${el.width}x${el.height}` && ld.blur === blurKey) return;
lastDraw.current = { el, media: video, t: video?.currentTime ?? -1, bg: bgRef.current, size: `${el.width}x${el.height}`, blur: blurKey };
// What the canvas draws, for a test to read: "on" while the blur covers the playhead.
el.dataset.liveBlur = blurNow ? "on" : "off";
- drawFootage(el, video, bgRef.current, blurNow);
+ el.dataset.liveCensor = String(hiddenNow.length);
+ drawFootage(el, video, bgRef.current, blurNow, hiddenNow);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -33,6 +33,7 @@ import type { ComboInfo } from "./ComboBadge";
import CopyShareLine from "../CopyShareLine";
import VersionVerdict from "./VersionVerdict";
import { StillButton } from "../inspector/StillInspector";
+import type { CensorRegion } from "./CensorOverlay";
// ---------------------------------------------------------------------------
// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
@@ -119,6 +120,8 @@ export type PlayEntry = {
/** Seconds taken out of its middle (gaps.mjs): one item of jump cuts. */
gaps?: { from: number; to: number }[];
blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null;
+ /** Its hidden regions (clip-censor.mjs censorRegionsOf): drawn over the picture as the cut hides them. */
+ censor?: CensorRegion[];
media?: (MediaRef & { from: number; to: number }) | null;
/** Rejected by the walk -- a fact error or a cut reason -- and why (skipped unless "Show rejected clips"). */
rejected?: { reason: string; label: string; fact: boolean; why: string } | null;
diff --git a/umtool/components/projects/review/footageCanvas.ts b/umtool/components/projects/review/footageCanvas.ts
@@ -18,10 +18,12 @@ export type FootageBlur = { strength: number; caption: string } | null;
* the Play view's engine), its size, how opaque (a dissolve draws the
* incoming clip over the outgoing at its progress), and its blur.
*/
-export type FootageLayer = { source: CanvasImageSource; width: number; height: number; alpha: number; blur: FootageBlur };
+export type FootageLayer = { source: CanvasImageSource; width: number; height: number; alpha: number; blur: FootageBlur; censor?: FootageCensor[] };
+/** A hidden region (clip-censor.mjs) over the picture now: its box (fractions of the picture), its style, its strength. */
+export type FootageCensor = { box: number[]; style: "blur" | "black" | "pixelate"; strength: number };
-export function drawFootage(el: HTMLCanvasElement, video: HTMLVideoElement | null, bg: string, blur: FootageBlur) {
- drawFootageLayers(el, video ? [{ source: video, width: video.videoWidth, height: video.videoHeight, alpha: 1, blur }] : [], bg);
+export function drawFootage(el: HTMLCanvasElement, video: HTMLVideoElement | null, bg: string, blur: FootageBlur, censor: FootageCensor[] = []) {
+ drawFootageLayers(el, video ? [{ source: video, width: video.videoWidth, height: video.videoHeight, alpha: 1, blur, censor }] : [], bg);
}
/** The footage box's ground, then each layer in order, fitted, at its alpha, blurred as the build blurs it. */
@@ -41,12 +43,52 @@ export function drawFootageLayers(el: HTMLCanvasElement, layers: FootageLayer[],
}
function drawOne(ctx: CanvasRenderingContext2D, el: HTMLCanvasElement, layer: FootageLayer, bg: string) {
- const { source, blur } = layer;
const k = Math.min(el.width / layer.width, el.height / layer.height);
const w = layer.width * k;
const hh = layer.height * k;
const x = (el.width - w) / 2;
const y = (el.height - hh) / 2;
+ drawPicture(ctx, layer, x, y, w, hh, bg);
+ // Its hidden regions (clip-censor.mjs), over the picture as the cut hides them: black filled; blurred or
+ // pixelated from the picture under them.
+ for (const g of layer.censor ?? []) {
+ const rx = x + g.box[0] * w;
+ const ry = y + g.box[1] * hh;
+ const rw = g.box[2] * w;
+ const rh = g.box[3] * hh;
+ ctx.save();
+ if (g.style === "black") {
+ ctx.fillStyle = "#000";
+ ctx.fillRect(rx, ry, rw, rh);
+ } else {
+ ctx.beginPath();
+ ctx.rect(rx, ry, rw, rh);
+ ctx.clip();
+ if (g.style === "pixelate") {
+ // Scaled down to its blocks and back up, unsmoothed (post-censor.mjs pixelGrid's block: 0.8 % of the width a step).
+ const block = Math.max(2, w * g.strength * 0.008);
+ const nx = Math.max(1, Math.round(rw / block));
+ const ny = Math.max(1, Math.round(rh / block));
+ const tmp = document.createElement("canvas");
+ tmp.width = nx;
+ tmp.height = ny;
+ const sx = (g.box[0] * layer.width);
+ const sy = (g.box[1] * layer.height);
+ tmp.getContext("2d")?.drawImage(layer.source, sx, sy, g.box[2] * layer.width, g.box[3] * layer.height, 0, 0, nx, ny);
+ ctx.imageSmoothingEnabled = false;
+ ctx.drawImage(tmp, rx, ry, rw, rh);
+ } else {
+ ctx.filter = `blur(${Math.max(4, w * g.strength * 0.004).toFixed(1)}px)`;
+ ctx.drawImage(layer.source, x, y, w, hh);
+ }
+ }
+ ctx.restore();
+ }
+}
+
+/** The picture itself, fitted, blurred as a clip's blur asks (its caption over it). */
+function drawPicture(ctx: CanvasRenderingContext2D, layer: FootageLayer, x: number, y: number, w: number, hh: number, bg: string) {
+ const { source, blur } = layer;
if (!blur) {
ctx.drawImage(source, x, y, w, hh);
return;
diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts
@@ -3,6 +3,7 @@ import { inGap } from "umtool-report-to-video/gaps";
import { cutAtSource, itemIndexAt, pieceWants, playPlan, sourceAt } from "@/lib/report/playCut.mjs";
import { EDGE_SLACK, audioSpans, decodesOf, scheduleFrom } from "@/lib/report/playSchedule.mjs";
import { drawFootageLayers, type FootageLayer } from "../footageCanvas";
+import { regionsAt, type CensorRegion } from "../CensorOverlay";
import { AudioBank, type ClipSound } from "./audioBank";
import { CodecPicture, codecsAvailable } from "./codecPicture";
import { ElementPicture } from "./elementPicture";
@@ -54,6 +55,8 @@ export type EngineEntry = {
id: string;
media?: (MediaRef & { from: number; to: number }) | null;
blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null;
+ /** Its hidden regions (clip-censor.mjs): drawn over the picture, whatever render.blur says. */
+ censor?: CensorRegion[];
};
export type EngineUi = { t: number; cur: number; playing: boolean; ended: boolean; waiting: boolean };
/**
@@ -808,14 +811,17 @@ export class PlayEngine {
const blur = b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity)
? { strength: b.strength ?? BLUR_STRENGTH.default, caption: b.caption ?? BLUR_CAPTION_DEFAULT }
: null;
- out.push({ source: l.source, width: l.w, height: l.h, alpha: l.alpha, blur });
+ // Its hidden regions over this second (or, the second unknown, every one): drawn as the cut hides them.
+ const censor = regionsAt(e?.censor ?? [], src);
+ out.push({ source: l.source, width: l.w, height: l.h, alpha: l.alpha, blur, censor });
}
// A frame not decoded yet (a seek, a join whose bytes are still coming): the last picture stays rather than a black flash.
if (missing && !out.length && this.shown) return;
- const key = `${items[this.cur]?.id}|${out.map((l) => `${l.alpha.toFixed(3)}:${l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp}:${l.blur ? 1 : 0}`).join(",")}|${this.bg}|${el.width}x${el.height}`;
+ const key = `${items[this.cur]?.id}|${out.map((l) => `${l.alpha.toFixed(3)}:${l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp}:${l.blur ? 1 : 0}:${l.censor?.length ?? 0}`).join(",")}|${this.bg}|${el.width}x${el.height}`;
if (key === this.lastDraw && out.every((l) => !(l.source instanceof HTMLVideoElement) || l.source.paused)) return;
this.lastDraw = key;
el.dataset.playBlur = out.some((l) => l.blur) ? "on" : "off";
+ el.dataset.playCensor = String(out.reduce((n, l) => n + (l.censor?.length ?? 0), 0));
el.dataset.playLayers = String(out.length);
drawFootageLayers(el, out, this.bg);
this.shown = out.length > 0;
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -65,7 +65,7 @@ Inbox cannot disagree about what is wrong with one.
| `snapshot <project> [--label L]` | copy the manifest into `revisions/` |
| `diff <project> <snapshot>` | added / removed / moved / window / retyped, by entry id |
| `export <project> --format toc-bbcode\|toc-markdown\|description\|chapters [--variant V] [--first TITLE]` | the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00 |
-| `export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson` | **one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip)) |
+| `export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson` | **one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. A clip's hidden regions (`render.censor`, its `censor`) are hidden in a cut or context export; a raw export of a clip with boxes is refused unless `--uncensored-raw`, which shows them and says so. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip)) |
| `check-sources [<project>…]` | **prints** the re-check chain; with no args, the never-checked and >30 d projects |
| `notes …` | operator notes: list, read, reply, resolve ([notes.md](notes.md)) |
| `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) |
@@ -227,7 +227,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `storage deliverables` | clips/ and share-*/ to the media root and back | none: moves deliverables between drives, then the switch: a terminal's, run when nothing builds |
| `snapshot <project> [--label LABEL]` | copy the manifest into revisions/ | form · *project* |
| `diff <project> <snapshot>` | what changed since a snapshot | form · *project* |
-| `export <project> [<clip>] [--format toc-bbcode\|toc-markdown\|description\|chapters] [--variant VARIANT] [--first FIRST] [--context N] [--raw] [--from N] [--to N] [--fetch] [--take TAKE]` | the posting artifacts, or one clip clean into exports/ | form · queued · *project* |
+| `export <project> [<clip>] [--format toc-bbcode\|toc-markdown\|description\|chapters] [--variant VARIANT] [--first FIRST] [--context N] [--raw] [--uncensored-raw] [--from N] [--to N] [--fetch] [--take TAKE]` | the posting artifacts, or one clip clean into exports/ | form · queued · *project* |
| `check-sources [<projects>…]` | the re-check chain, printed | form · *corpus* |
| `notes [<target>] [--all] [--resolved] [--all-status]` | the operator's notes, as markdown | form · *corpus* |
| `notes reply <id> <text> [--resolve]` | answer a note | form · *corpus* |
@@ -274,7 +274,10 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `pool prune [--max-gb N] [--dry-run]` | the render pool pruned to its cap | form · *corpus* |
| `pool verify [--sample N] [--all]` | the render pool's files checked | form · queued · *corpus* |
| `trailer <project> [--take TAKE] [--reel REEL] [--beats BEATS] [--beats-json JSON] [--intro] [--finale N] [--xfade N] [--no-snap] [--out OUT] [--dry-run] [--candidates] [--vertical] [--layout reframe]` | a trailer or beat reel cut from a take's master | form · queued · *project* |
-| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--reframe] [--dry-run] [--intro] [--no-intro] [--no-outro] [--deck stacked\|bare]` | a vertical short (1080x1920) of a take's items | form · queued · *project* |
+| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--reframe] [--landscape] [--desktop] [--dry-run] [--intro] [--no-intro] [--no-outro] [--deck stacked\|bare] [--qr on\|off] [--qr-corner tr\|tl\|br\|bl] [--promo] [--no-promo] [--promo-lead N] [--promo-fade N] [--promo-hold N] [--no-cold-open]` | a vertical short (1080x1920) of a take's items | form · queued · *project* |
+| `censor <project> [--video VIDEO] [--channel CHANNEL] [--box BOX…] [--style blur\|black\|pixelate] [--strength N] [--from N] [--to N] [--clear] [--list]` | the regions hidden on every clip of one recording (a chat overlay, other accounts) | form · *project* |
+| `promo <project> [--portrait-from PORTRAIT-FROM] [--box BOX] [--draw] [--take TAKE]` | the channel promo: its portrait from a clip at a second, its card drawn | form · *project* |
+| `shorts <project> --take TAKE [--items ITEMS] [--all] [--again] [--formats FORMATS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max-vertical N] [--max-landscape N] [--max-desktop N] [--deck stacked\|bare] [--qr on\|off] [--qr-corner tr\|tl\|br\|bl] [--no-promo] [--promo-lead N] [--promo-fade N] [--promo-hold N] [--no-cold-open] [--replace] [--dry-run]` | a batch of shorts: each clip of a take in each format, into shorts-<take>/ | form · queued · *project* |
| `trailer-beats <project> ls [--reel REEL]` | a reel's beats against its limit | form · *project* |
| `trailer-beats <project> add <clip> [<span>] [--at N] [--label LABEL] [--take TAKE] [--reel REEL]` | a clip beat | form · *project* |
| `trailer-beats <project> add-raw <at> <dur> [--at N] [--label LABEL] [--reel REEL]` | a beat of master seconds | form · *project* |
@@ -548,6 +551,18 @@ $U vertical emberparadox/mr-obvious --take mid-14 --reel short-die --reframe --j
- **The cut itself vertical**: `umtool look <p> format='"vertical"' vertical='{"clip":"framed","post":"card"}'` (or
the same keys in a take's patch) renders the whole timeline 9:16 -- `umtool take` as ever.
- `--landscape` builds the same items in the take's 16:9 look, to compare (a side post is a panel at the right).
+- **`--desktop`** builds the same items 16:9 with minimal chrome for X: the picture full frame, one thin source line,
+ the words lit along its foot, a code only with `--qr` ([knobs.md](knobs.md#desktop-clips-169-minimal-chrome)).
+- **The channel promo:** when the take sets `render.promo`, the short's last clip ends on the streamer's card -- the
+ picture dissolves into it over the clip's last seconds, its sound on under it and the captions over it, then it holds
+ in silence (`--no-promo`, `--promo-lead`, `--promo-hold`; [knobs.md](knobs.md#the-channel-promo-the-card-a-clip-ends-on)).
+- **Zooms:** a clip's `zooms` push its picture in at points, eased (`umtool set <p> <clip> zooms='[…]'`); refused past
+ the source's pixels unless the project allows a soft limit ([knobs.md](knobs.md#zoom-at-points-a-shorts-or-a-desktop-clips-picture-pushed-in)).
+- **A cold open:** a clip's `coldOpen` (1–4 s of its cut) plays first, then a hard cut to its start (`--no-cold-open`:
+ not; [knobs.md](knobs.md#a-cold-open-the-payoff-first)).
+- **A code on the short:** `--qr on` (or `--qr-corner tr|tl`) puts one at the top of the safe area, linking the source at
+ the second each clip plays from ([knobs.md](knobs.md#a-clips-qr-its-corner-and-its-link)).
+- **Many clips, both formats, one command:** `umtool shorts` ([below](#make-promo-clips-a-batch-of-shorts)).
- **The intro and the outro card.** `--intro` opens the short on the brand intro re-laid 9:16 -- the same style,
sound, timing and site swap, the drawing centred in the safe area -- from the take's `render.intro`, else
`boot-dark` with the mark on the chime; a reel whose `intro` is on opens on it too (its own intro when it has one;
@@ -556,6 +571,41 @@ $U vertical emberparadox/mr-obvious --take mid-14 --reel short-die --reframe --j
record names them (`intro`, `outro`).
- Hooks only ever say the cut's own words: a clip's title, its section's title (the deck's marker), or a line you give.
+## Make promo clips (a batch of shorts)
+
+The clipping job as one command: each listed clip of a take, in each format, through the same builder as
+`umtool vertical`, into the project's `shorts-<take>/`. One queued job, one log, one record.
+
+```sh
+U="node umtool/bin/umtool.mjs"
+$U shorts my-clips --take kit --items w01,w03,w05 --formats vertical,desktop --clip framed --hook title
+$U shorts my-clips --take kit --all --dry-run # the names and files it would write
+$U shorts my-clips --take kit --again # the folder's batch.json made again
+```
+
+- **Formats.** `vertical` is `umtool vertical`'s 9:16 short (its layouts and flags: `--clip`, `--hook`, `--captions`, …);
+ `desktop` the same clip 16:9 with minimal chrome (`umtool vertical --desktop`: the X clip); `landscape` the same clip
+ in the take's own 16:9 look (`umtool vertical --landscape`). A bottom `--qr-corner` is the desktop clips'; a short
+ keeps its code at the top right (said in its notes).
+- **Names.** `<name>.<format>.mp4`, each with its record (`.json`): the clip's `name` when it pins one, else its
+ title's slug, else its id. A name another clip of the folder holds gets `-<clip id>` (two clips of one cut often share
+ a title). Once a clip has a name in `batch.json` it keeps it, whatever its title becomes.
+- **A file there is kept** unless `--replace`, which sets the old one aside as `<name>.<format>.<stamp>.mp4` -- and
+ puts it back when the rebuild fails.
+- **Each format takes only the knobs it reads:** `landscape` (the take's own look) none of them (said in its notes); a
+ short keeps its code at the top when a bottom corner is asked for the desktop clips.
+- **`batch.json`** names each clip's files, lengths, notes and errors, the knobs it was last built with and its
+ **snapshot** (its own keys as read: framing, side post, code, promo, zooms, cold open) and the **look** it was built
+ with (the palette, `render.promo`, `render.qr`, the vertical and desktop knobs, …). `--again` builds every clip of
+ the folder again from those, so a later edit of the project or its look does not silently change a rebuild. A name
+ read back from `batch.json` is used only when it is a plain file name of the folder.
+- **Length.** A vertical over 180 s (`--max-vertical`, Shorts' 3 minutes) or a desktop or landscape clip over 140 s
+ (`--max-desktop`, `--max-landscape`, X's 2:20) is said so in the record: a note, never a refusal.
+- Each build runs in the heavy slot as `umtool vertical`'s does (another job may run between two clips). A clip that
+ fails is recorded with its error and the rest go on; the command exits 1 at the end.
+- Not `shorts/`: that folder is the clip editor's **Make a short**, whose every mp4 the Deliver tab reads as a clip's.
+ `shorts-<take>` is a deliverable, moved with `clips/` and `share-*` by `umtool storage deliverables`.
+
## `check` is the one to run before every build
```
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -379,6 +379,232 @@ project without the knob.
|---|---|---|---|
| taller windows | — | `umtool look <p> tallWindows=true` (`false` turns it off) | `PUT /api/report/render {patch: {tallWindows}}` |
+## Desktop clips (16:9, minimal chrome)
+
+A take's clips built 16:9 for X, by the builder a short uses (lane clip-kit; `vertical.mjs` `desktopGeometry`):
+`umtool vertical <p> --take <t> --items a --desktop`, or a batch's `desktop` format (`umtool shorts … --formats
+vertical,desktop`). X autoplays muted, so the words are on the picture:
+
+- **the picture full frame**: fitted, never cropped, no header or footer letterboxing it;
+- **one thin source line**: "channel · date" on a small plate over the picture, top left of the safe area;
+- **the captions** along the foot, at most two lines, each word lit as it is said (the short's captions, laid 16:9);
+- **a code** only when asked, in a corner of the safe area (the source at the clip's second by default; [A clip's
+ QR](#a-clips-qr-its-corner-and-its-link)); a code at a bottom corner narrows the captions on both sides, so they keep
+ centred and clear of it; one at the top left moves the source line beside it;
+- brought to -14 LUFS; over 140 s (X's 2:20) said so in a note, never refused.
+
+`--landscape` is another thing: the take's whole 16:9 look (its header, its corner code, its deck), to compare.
+
+| Knob (`render.desktop`) | Values (default) | What it does |
+|---|---|---|
+| `tag` | `true` · `false` (`true`) | the source line |
+| `hook` | `false` · `"title"` · `"section"` · `{text}` (`false`) | a line under the source line, of the cut's own copy |
+| `captions` | `{size: "m"\|"l"\|"xl", lines: 1\|2}` (`l`, 2) | the captions' size (3.4 % of the width at `l`) and lines |
+| `safe` | `{top, bottom, right, left}` fractions (0.04, 0.08, 0.03, 0.03) | where text keeps inside (X's own controls sit at the foot) |
+| `qr` | `false` · `true` · `{corner: br\|bl\|tr\|tl, size: 0.05–0.2, links}` (`false`) | a code; `true` is bottom right at 9 % of the width |
+| `loudness` | LUFS -30 … -8 (-14) | the clip brought to it |
+| `maxSeconds` | 5 … 600 (140) | over it, a note |
+
+| | In umtool | From a terminal |
+|---|---|---|
+| the desktop look | Build, **Look**: **Desktop clips** (Source line, QR, Captions) | `umtool look <p> desktop='{"qr":{"corner":"bl"},"captions":{"size":"xl"}}'` (`desktop=` the defaults) |
+| one clip, 16:9 | — | `umtool vertical <p> --take <t> --items a --desktop [--qr on] [--qr-corner bl] [--captions xl]` |
+| each clip, every format | the ⌘K form **shorts** | `umtool shorts <p> --take <t> --all --formats vertical,desktop` |
+
+## The channel promo (the card a clip ends on)
+
+A clip built alone -- a short, a desktop clip, each clip of a batch -- can end on a card promoting the streamer it was
+clipped from (lane clip-kit; `report-to-video/promo-card.mjs`). It is data, not a drawing: the project says who and
+where, one template draws it 9:16 and 16:9.
+
+- **The card is only** the portrait in a ring, the name stacked (its second line in the accent), the channel's page
+ (its host in the platform's colour: Kick's green, Twitch's purple, …) and a code to it. A small line over the name
+ (`kicker`) only when the project gives one. A still: no push, no zoom, no slam, no sting.
+- **The timing:** the card starts `lead` seconds (4.5) before the clip's end and fades in over `fade` (0.7), the clip's
+ own sound playing on under it; then it holds `hold` (1.5) seconds in silence. A lead longer than the clip less a
+ second is held to that, and said.
+- **The captions stay over the card**, moved into a band it keeps clear (in 9:16 above the bottom 20 %, the card's
+ content in the upper safe area; in 16:9 along the foot): X autoplays muted, and the last words are the ones a muted
+ viewer would lose. The source line and the hook fade out as the card comes up. `captions: false` ends the captions
+ where the card starts, and gives the card the whole safe area.
+- **The colours** are the cut's palette (`bg` the ground, `fg` the ink, `amber` -- else `accent` -- the ring and the
+ name's second line); `promo.palette` (`ground`, `ink`, `accent`, `link`, `plate`, each `#rrggbb`) changes them for the
+ card alone, so a streamer's own colours can be set per project without touching the template.
+- **The faces** are the repository's (Archivo for the name, IBM Plex Sans for the rest), so a fresh clone or the
+ container draws the same card. The card is drawn by a browser (as a post card is), once per key, into the build's
+ `cards/`.
+- Only a build whose LAST piece is a whole clip ends on it (a short ending on a post item, or on a clip cut short of
+ its end, ends without it, said); a reel's outro card is then not added after it (one ending, said). The stacked
+ vertical deck's end card is another thing; a take's 16:9 look (`--landscape`) draws none.
+- **The code** stands on a WHITE plate (whatever the palette; `palette.plate` changes it) with a quiet zone of four
+ modules, as the QR standard asks.
+
+| Knob | Values (default) | What it does |
+|---|---|---|
+| `render.promo.name` | a line, or two `["…", "…"]` (≤ 24 characters each) | the streamer's name, stacked |
+| `render.promo.url` | an http(s) link | the channel's page, shown as host + path |
+| `render.promo.qr` | a link · `false` (the url) | the code's link, or no code |
+| `render.promo.portrait` | `{file, box?}` (none) | a picture of the project's (`umtool promo --portrait-from`), the circle cut from `box` (fractions; default its centre) |
+| `render.promo.kicker` | a line ≤ 40 (none) | a small line over the name |
+| `render.promo.palette` | `{ground, ink, accent, link, plate}` | the card's own colours over the cut's |
+| `render.promo.lead`, `.fade`, `.hold` | 1–10 (4.5), 0.2–2 (0.7, inside the lead), 0–5 (1.5) seconds | when it comes up, how long it fades in, how long it holds |
+| `render.promo.captions` | `true` · `false` (`true`) | the captions over the card |
+| a clip's `promo` | `false` · `{lead?, fade?, hold?}` | this clip ends without the card, or with its own timing |
+
+| | In umtool | From a terminal |
+|---|---|---|
+| the promo | Build, **Look**: **Channel promo** (name, second line, channel page, QR, the timing, **Captions over the card**); **Draw the card** shows both | `umtool look <p> promo='{"name":["…","…"],"url":"https://kick.com/…"}'` (`promo=` none) |
+| its portrait | the clip editor's **Short**: **Use this frame as the promo portrait** (the frame at the playhead) | `umtool promo <p> --portrait-from <clip>@<second> [--box x,y,w,h]` |
+| the card, to look at | **Draw the card** | `umtool promo <p> --draw [--take <t>]` (into `out/promo/`) |
+| one clip | the clip editor's **Short**: **End card** (the cut's / none) | `umtool set <p> <clip> promo=false` · `promo.hold=2` · `promo=` |
+| a short or a batch | the ⌘K forms **vertical**, **shorts** | `umtool vertical … [--no-promo] [--promo-lead 4.5] [--promo-fade 0.7] [--promo-hold 1.5]` · `umtool shorts … [--no-promo]` |
+
+## Zoom at points (a short's or a desktop clip's picture pushed in)
+
+A clip built alone -- a short, a desktop clip, a batch's -- can push in on part of its picture for a moment, eased in
+and out (lane clip-kit; `report-to-video/clip-zoom.mjs`). The push is in SOURCE space, before the layout: a short's
+9:16 crop (`vertical.crop`) stays the same box, the focus keeps its place on screen and the picture grows around it.
+The captions, the source line, the code and the promo card never zoom. A whole cut's punch-ins are the deck's
+`fx.punchIn` (Effects), not these.
+
+**Sharp by default.** A layout already shows its source at some enlargement, its REST: a 1080 window fitted into a
+framed short's 1080x608 box 0.56×, cut 9:16 to fill 1080x1920 1.78×, a desktop clip 1.0× (from 720 windows 1.5× each
+of those). A zoom multiplies it: the picture plays at rest × scale its source's pixels. The REFERENCE is the coarser
+of the source's own pixels and the layout's resting picture, max(1, rest); a strict cut never plays past it, so a zoom
+that would is refused, by name, with the enlargement it would play at. With 1080 windows (`render.tallWindows`) a
+framed short has room up to ×1.78 (720 windows: ×1.19); a full short and a desktop clip have none.
+
+**Soft: `render.zooms.soften`** (1–1.3) lets a zoom play up to that many times the reference: rest × scale ≤ soften ×
+max(1, rest), and the build says how much softer than its source each such zoom plays. For a framed short (rest
+under 1) that caps the TOTAL enlargement past the source's pixels at `soften` (×1.3: a scale up to 2.31 from 1080
+windows); for a full 9:16 short or a desktop clip from 720 windows -- already past the source's pixels at rest -- it
+lets the picture go `soften` times softer than it already plays (×1.3: scale 1.3, a full short from 1080 windows at
+2.31× its pixels). It is deliberately NOT a cap on the total past the source's pixels in every layout: capped at 1.3,
+a full short (1.78× at rest) and a desktop clip from 720 windows (1.5×) could not zoom at all.
+
+**Smooth.** The push is drawn by ffmpeg's `perspective` on sub-pixel corners (cubic), only over the push -- not
+`zoompan`, which rounds its crop to whole pixels each frame, so a slow ease stepped back and forth.
+
+**Written against the cut.** The clip editor and `umtool set` refuse a zoom outside the clip's cut (`cutStart`–
+`cutEnd`); a build checks only the window, and a cut tightened since leaves the zoom out, said.
+
+| Knob | Values (default) | What it does |
+|---|---|---|
+| a clip's `zooms` | `[{at, hold?, scale?, focus?, box?, ramp?}]`, 1–8, none overlapping | `at` the source second the push starts; `hold` 0.3–10 s at full zoom (1.5); `scale` 1.05–3 (1.3) and `focus` `[x, y]` (fractions of the picture; its centre), or `box` `[x, y, w, h]`, the part of the picture to fill the frame with; `ramp` 0.2–1 s each way (0.4, smoothstep) |
+| `render.zooms.soften` | 1–1.3 (absent: 1, strict) | how many times the reference, max(1, rest), a zoom may play its source at |
+
+| | In umtool | From a terminal |
+|---|---|---|
+| a zoom | the clip editor's **Short**: **Zoom here** (at the playhead), its scale, focus (%) and hold; × takes it off | `umtool set <p> <clip> zooms='[{"at":231.4,"scale":1.3,"focus":[0.7,0.35]}]'` (`zooms=` none) |
+| the soft limit | Build, **Look**: **Zooms** (never / up to ×1.15 / up to ×1.3 soft) | `umtool look <p> zooms='{"soften":1.3}'` (`zooms=` strict) |
+
+The cut record names each zoom drawn (`zooms: [{at, scale, focus, hold, ramp, enlargement}]`, `at` on the segment's
+clock).
+
+## A cold open (the payoff first)
+
+A short or a desktop clip can open on a moment of its clip -- the payoff line -- and then cut to the clip's start
+(lane clip-kit; `report-to-video/vertical-plan.mjs` `coldOpenEntry`). A clip's `coldOpen: {from, to}` (source seconds
+of its cut, 1–4 s; 1.5–3 s reads best, said otherwise) is cut out as an entry of its own, played first with a hard cut
+into the clip. Refused when written (and at a build), naming the clip: one outside the cut, one that is the whole
+cut, and one with a gap (a jump cut taken out) inside it or across its edges -- never a cold open silently shorter.
+It plays:
+
+- its own words captioned and its own sound (each piece's edges faded a few hundredths of a second, as any short's);
+- the hook band over it; no code (the clip's code shows from the clip on) and no card (the channel promo is the
+ clip's end, unaffected); its zooms only those wholly inside its span;
+- counted in the short's length note.
+
+Only a per-clip build plays it: a reel's beats, `--landscape` (the take's look), `--reframe` and the stacked deck's
+cut play the clips as cut. A whole cut's flash-forward (`umtool timeline … flash-forward`) is the cut's own copy of a
+span; this is the short's.
+
+| | In umtool | From a terminal |
+|---|---|---|
+| a clip's cold open | the clip editor's **Short**: select 1–4 s of the cut on the strip, **Cold open from selection**; **Clear** | `umtool set <p> <clip> coldOpen.from=… coldOpen.to=…` (`coldOpen=` none) |
+| without them | the ⌘K forms' **--no-cold-open** | `umtool vertical … --no-cold-open` · `umtool shorts … --no-cold-open` |
+
+## Hidden regions (a chat overlay, other accounts on screen)
+
+A stream layout carries things a clip should not show: the chat overlay, a browser window with other people's accounts.
+`render.censor` hides the same boxes on every clip cut from ONE recording; a clip's own `censor` adds boxes to it
+(lane clip-kit; `report-to-video/clip-censor.mjs`, with the post censor's styles and strengths). A box is a fraction of
+the SOURCE picture and may be limited to a span of the clip.
+
+- **Where it is drawn:** on the source picture FIRST -- before the clip's blur, its zooms and any framing -- so a box is
+ the same part of the recording whatever frames it.
+- **Privacy, not TOS:** it stays on in the uncensored variant (`render.blur: "off"`), as a post's censor does. No
+ caption is drawn. A hidden region is a privacy control, so every path that draws or cuts a clip's picture either
+ hides the boxes or REFUSES by name -- none skips them quietly. Only the builds, the exports and the stills hide them
+ IN THE FILE; every player of a raw window overlays them on the operator's screen, which hides nothing from someone
+ who saves the window -- so a public payload never names a raw window of a clip that has them:
+
+| Path | The boxes |
+|---|---|
+| **hidden in the file** | |
+| a cut, with or without the deck (`umtool take`, build-video) | drawn into each clip's segment; the cut record names them (`censor: [{box, style, strength?, from?, to?}]`) |
+| a short, a desktop clip, the take's own 16:9 look (`umtool vertical`, `umtool shorts`, Make a short) | drawn; a RENDERED take's frozen render gets the project's `render.censor` added (add-only: the take's boxes stay) |
+| `umtool shorts --again` | the clip's boxes now AND the batch record's snapshot, both (a box added since is kept, none taken off) |
+| the YouTube thumbnail (`thumbnail.clip`/`at`) | drawn on the grabbed frame, before its blur |
+| a still (`umtool still`, Play's Still, "Use this frame", promo `--portrait-from`) | drawn on the PNG, the boxes over that second |
+| `umtool export` as cut / `--context N` | drawn (the export says how many) |
+| **overlaid on the operator's screen, not hidden in the file** | |
+| Play (the canvas), the live deck preview | drawn over the raw window: the same boxes, spans and style |
+| Present (the operator's) | drawn over the raw window (`hidden` on each clip slide); no toggle lifts them |
+| the clip editor's player, the clip bench | outlined and filled, with **Peek** (off by default) to see under them there only |
+| the claim bench, the candidates panel, a cited clip (the article player) | the RECORDING's boxes (`render.censor` matched on its video; a cited project clip's own too), outlined, Peek off |
+| **public** | |
+| Present's public payload (`public=1`, `umtool present --public`) | a clip with boxes carries NO raw window (`media: null`): it plays its BUILT segment (`/api/report/segment`, when that segment's record hides exactly its boxes: `censored.segment`), else the slide says the clip is not shown (`censored: null`). A page outside umtool cannot reach `/api/report/*` at all, so a public export must carry the segment itself |
+| **refused** | |
+| a montage (`render.montage`) | REFUSED by name (a montage re-cuts its pictures and draws no boxes yet) |
+| a basic cut (`render.mode: "basic"`) | REFUSED by name, `render.blur: "off"` or not |
+| `umtool export --raw` | REFUSED by name; `--uncensored-raw` (the app: `uncensoredRaw`) exports as recorded and says UNCENSORED |
+| `--chrome-only` / `--chrome-preview` | REFUSED when a segment on disk hides other boxes than the cut asks for (a box added, changed or taken off since): build again |
+| `umtool vertical --reframe` | REFUSED when a clip's boxes changed since the take was rendered (it cuts the take's finished picture) |
+
+The rendered segment previews (the bench's) play the built segment, which hides them in the file.
+
+| Knob | Values (default) | What it does |
+|---|---|---|
+| `render.censor` | `[{video, channel?, boxes, style?, strength?, from?, to?}]`, ≤ 16 | the boxes hidden on every clip of that recording (`channel`: only that channel's; absent: any) |
+| a clip's `censor` | `false` · `{boxes, style?, strength?, from?, to?}` | its own boxes, added; `false`: none, not even its recording's |
+| `boxes` | 1–8 of `[x, y, w, h]` or `{box: [x, y, w, h], from?, to?}` | fractions of the source picture; a box's own `from`/`to` (source seconds) limit it to that span |
+| `style`, `strength` | `blur` · `black` · `pixelate` (`blur`); 1–10 (7) | how it is hidden |
+| `from`, `to` | source seconds | every box of the entry only over that span |
+
+| | In umtool | From a terminal |
+|---|---|---|
+| a recording's | the clip editor's **Short**: **Hide regions** -- the box (x, y, w, h in %), **every clip of this recording**, the style, **From playhead** / **To playhead**, **Hide it**; × takes one off | `umtool censor <p> --video <id> [--channel <slug>] --box x,y,w,h[@from-to] [--box …] [--style black]` · `--clear` · `--list` |
+| one clip's | the same, **this clip** | `umtool set <p> <clip> censor.boxes='[[0.75,0,0.25,1]]' censor.style=pixelate` · `censor=false` · `censor=` |
+
+## A clip's QR: its corner and its link
+
+The corner code a cut with no deck draws on each clip (`render.qr`), and the code a short draws (`render.vertical.qr`),
+can stand in another corner and link another page (lane clip-kit; `report-to-video/clip-kit.mjs`). With none of these
+keys the code is where it always was (bottom right) with the link it always had (the clip's `citeUrl`, else its moment
+on the archive).
+
+| Knob | Values (default) | What it does |
+|---|---|---|
+| `render.qr.corner` | `br` · `bl` · `tr` · `tl` (`br`) | where the code stands: off the streamer's own camera box |
+| `render.qr.links` | `cite` · `moment` · `channel` (`cite`) | `cite` the clip's link as it always was; `moment` the SOURCE at the second the clip starts playing; `channel` the channel promo's page (`render.promo.url`) |
+| a clip's `qr` | `false` · `{corner?, links?}` | no code on this clip, or its own corner and link over the cut's (a short keeps `tr`/`tl`) |
+
+**A moment link** is the clip's own recording at the second it plays from (the build's snapped start): its `citeUrl`
+retimed when the citeUrl names this recording (it carries the clip's video id); with no citeUrl, the record's
+`webpage_url` at that second; a citeUrl naming another recording (a mirror cited on purpose) as written. The time
+parameter per platform is one table, `common/lib/platformSeek.mjs`: YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`, Odysee
+`t=<s>`, Rumble `start=<s>`, and **Kick `t=<s>`, which is not confirmed** — nothing in the repository shows a kick.com
+VOD page honours it (at worst it opens at the start). A moment code to a Kick or Twitch VOD is a lint NOTE: those VODs
+are deleted after about 30 / 14 days (`VOD_RETENTION_DAYS`), and the code stops opening then; `links: "channel"`
+lasts. The build records a code that is not `cite` in the clip's cut record (`qr: {url, corner}`).
+
+| | In umtool | From a terminal |
+|---|---|---|
+| the cut's corner and link | Build, **Look**: **QR corner**, **QR links** (with **QR code** on) | `umtool look <p> qr='{"corner":"tl","links":"moment"}'` (`null` for a key: its default) |
+| one clip's | the clip editor's **Short**: **QR on this clip** (the cut's / none / a corner) | `umtool set <p> <clip> qr.corner=tl` · `qr.links=moment` · `qr=false` · `qr=` (the cut's) |
+| a short's code | — | `umtool vertical <p> … --qr on` · `--qr-corner tl` · `umtool look <p> vertical='{"qr":true}'` |
+
## Basic output (the footage alone)
`render.mode: "basic"` renders the cut as its footage and nothing else (`report-to-video/basic.mjs`): each clip's
@@ -2170,6 +2396,7 @@ byte what it was.
| `render.vertical.safe` | `{top, bottom, right}` fractions (0.08, 0.2, 0.12) | kept clear of every caption, tag, card and post (the platforms' buttons) |
| `render.vertical.loudness` | LUFS -30 … -8 (-14) | each clip levelled to it in its segment; the short brought to it at the end |
| `render.vertical.maxSeconds` | 5 … 600 (60) | a short over it is said so (a note, never a refusal) |
+| `render.vertical.qr` | `false` · `true` · `{corner: "tr"\|"tl", size: 0.1–0.3, links}` (`false`) | a code at the top of the safe area (`tr` at the right, `tl` under the tag; a full layout's hook band moves below it), linking the source at the second the clip plays from (`links` `moment`, the default here) — [A clip's QR](#a-clips-qr-its-corner-and-its-link) |
| a clip's `vertical` | `{crop: [x, y, w, h], aspect?, layout?, crops?}` | its 9:16 box on the source (else centred) and its own layout over the cut's; `layout: "twocrop"` with `crops: [[x, y, w, h], [x, y, w, h]]` (fractions of the source, the top one first) is the stacked deck's two-crop reframe |
| a clip's `side` | `{item \| post, from, to, place?}` | a post shown BESIDE the clip while it plays: not read, the clip's sound on. `item` a post item of the cut, `post` its fields; `from`/`to` seconds into the clip; `place` `split`/`overlay` (vertical) or `right`/`left` (16:9: a panel over that side of the picture, sliding in) |
@@ -2184,6 +2411,7 @@ byte what it was.
| the brand intro 9:16 first (centred in the safe area); the reel's outro card 9:16 last | `umtool vertical <p> --take <t> --reel <r> --intro` (a reel with `intro` on: by itself; `--no-intro`) · the reel's `outro` on: by itself (`--no-outro`) |
| R, recomposed from the master | `umtool vertical <p> --take <t> --reel <r> --reframe` (each item's footage box, card and attachment, the deck's date line; nothing cut again) |
| the same items 16:9, to compare | `umtool vertical <p> --take <t> --reel <r> --landscape` |
+| each clip of a take in each format, into `shorts-<take>/` (a batch, its record, stable names) | `umtool shorts <p> --take <t> (--items a,b \| --all \| --again) [--formats vertical,desktop,landscape] [the vertical flags]` ([cli.md](cli.md#make-promo-clips-a-batch-of-shorts)) |
A clip's `vertical` and `side` are read from the PROJECT's manifest over the take's (they are set after the take was
made). The side card is drawn by the post card's own page with the cut's redaction and the authors' pictures; its
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -3638,6 +3638,12 @@ clip in the editor to frame it.
From a terminal: `node umtool/report-to-video/build-video.mjs
<project>/video.manifest.json --short <clipId>`.
+**Make a short is one of two per-clip paths.** It is the project's one clip, full-bleed, with speaker captions,
+into `shorts/`. `umtool vertical` (a take's items, in a layout: framed, quote, a hook, word-lit captions, a code,
+the channel promo) and its batch `umtool shorts` (each clip of a take, 9:16 and 16:9 desktop, into
+`shorts-<take>/`; [cli.md](cli.md#make-promo-clips-a-batch-of-shorts)) are the other, one builder. Make a short is
+unchanged by it; a batch never writes into `shorts/`.
+
## The brand intro (`render.intro`)
A cut can open with a short Archilyzer sting, after the Game Boy Advance boot
diff --git a/umtool/e2e/clip-kit.spec.ts b/umtool/e2e/clip-kit.spec.ts
@@ -0,0 +1,173 @@
+import { test, expect } from "@playwright/test";
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The clip kit (lane clip-kit): the Look panel's QR corner and link, its Desktop clips and its Channel promo (saved,
+// read back, the card drawn); the clip editor's own QR, End card and promo portrait; and the batch of shorts --
+// `umtool shorts`, run as ⌘K runs it (POST /api/cli, a queued step) -- each clip in both formats into shorts-kit/,
+// each ending on the channel's card. Fixture: e2e/fixtures/clip-editor-fixture.mjs as reports/clip-kit-fixture,
+// with a draft take `kit`.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/clip-kit-fixture";
+const DIR = path.join(FIXTURE, "reports", "clip-kit-fixture");
+const json = (name: string) => {
+ try {
+ return JSON.parse(readFileSync(path.join(DIR, name), "utf8"));
+ } catch {
+ return null;
+ }
+};
+const render = () => json("video.manifest.json")?.render ?? {};
+const clip = (id: string) => (json("video.manifest.json")?.timeline ?? []).find((e: { id: string }) => e.id === id) ?? null;
+const probe = (file: string) =>
+ execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:format=duration", "-of", "json", file], { encoding: "utf8" });
+
+test("the look: the QR's corner and link, desktop clips and the channel promo saved and read back; the card drawn", async ({ page }) => {
+ test.setTimeout(180_000);
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.section(PROJECT, "build"));
+ await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", "");
+ // The QR: on (the fixture's default), in the top left, linking the source at each clip's second.
+ await page.locator("[data-look-qr-corner]").selectOption("tl");
+ await page.locator("[data-look-qr-links]").selectOption("moment");
+ // Desktop clips: a code at the bottom left, the captions extra large.
+ await page.locator("[data-look-desktop-qr]").selectOption("bl");
+ await page.locator("[data-look-desktop-size]").selectOption("xl");
+ // The channel promo.
+ await page.locator("[data-look-promo-on]").check();
+ await page.locator("[data-look-promo-name1]").fill("Fixture");
+ await page.locator("[data-look-promo-name2]").fill("Channel");
+ await page.locator("[data-look-promo-url]").fill("https://kick.com/fixture");
+ await page.locator("[data-look-promo-lead]").fill("1");
+ await page.locator("[data-look-promo-fade]").fill("0.3");
+ await page.locator("[data-look-promo-hold]").fill("1");
+ await page.locator("[data-look-save]").click();
+ await expect(page.locator("[data-look-status]")).toHaveText("Saved — the next render uses it");
+ const r = render();
+ expect(r.qr).toEqual({ corner: "tl", links: "moment" });
+ expect(r.desktop).toEqual({ qr: { corner: "bl" }, captions: { size: "xl" } });
+ expect(r.promo).toEqual({ name: ["Fixture", "Channel"], url: "https://kick.com/fixture", lead: 1, fade: 0.3, hold: 1 });
+ await page.reload();
+ await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", "");
+ await expect(page.locator("[data-look-qr-corner]")).toHaveValue("tl");
+ await expect(page.locator("[data-look-qr-links]")).toHaveValue("moment");
+ await expect(page.locator("[data-look-desktop-qr]")).toHaveValue("bl");
+ await expect(page.locator("[data-look-desktop-size]")).toHaveValue("xl");
+ await expect(page.locator("[data-look-promo-on]")).toBeChecked();
+ await expect(page.locator("[data-look-promo-url]")).toHaveValue("https://kick.com/fixture");
+ await expect(page.locator("[data-look-promo-portrait]")).toContainText("No portrait yet");
+ // The card, drawn 9:16 and 16:9 by the build's own page.
+ await page.locator("[data-look-promo-draw]").click();
+ for (const shape of ["v", "h"]) {
+ const img = page.locator(`[data-look-promo-card='${shape}']`);
+ await expect.poll(async () => img.evaluate((e) => (e as HTMLImageElement).naturalWidth), { timeout: 60_000 }).toBe(shape === "v" ? 1080 : 1920);
+ }
+});
+
+test("the clip editor: a clip's own QR corner, its end card off and back, the promo's portrait from the playhead", async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 900 });
+ await page.goto(urls.clipEditorHref(PROJECT, { clip: "r001" }));
+ await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r001");
+ await page.locator("[data-kit-qr='r001']").selectOption("tr");
+ await expect.poll(() => clip("r001")?.qr ?? null).toEqual({ corner: "tr" });
+ await page.locator("[data-kit-qr='r001']").selectOption("none");
+ await expect.poll(() => clip("r001")?.qr).toBe(false);
+ await page.locator("[data-kit-qr='r001']").selectOption("cut");
+ await expect.poll(() => clip("r001") && "qr" in clip("r001")).toBe(false);
+ await page.locator("[data-kit-promo='r001']").selectOption("off");
+ await expect.poll(() => clip("r001")?.promo).toBe(false);
+ await page.locator("[data-kit-promo='r001']").selectOption("cut");
+ await expect.poll(() => clip("r001") && "promo" in clip("r001")).toBe(false);
+ // A zoom at the playhead (slice F): added, its scale changed, taken off.
+ await expect(page.locator("[data-editor-player]")).toHaveAttribute("data-editor-player", /^(?!looking|none)/, { timeout: 20_000 });
+ await page.locator("body").press("l");
+ await expect(page.locator("[data-zoom-add='r001']")).toBeEnabled();
+ await page.locator("[data-zoom-add='r001']").click();
+ await expect.poll(() => clip("r001")?.zooms?.length ?? 0).toBe(1);
+ // The playhead is near the cut's end (1-3 s): the zoom is moved back and held as long as fits.
+ expect(clip("r001").zooms[0]).toMatchObject({ at: 1.9, scale: 1.3, hold: 0.3 });
+ await page.locator("[data-zoom-scale='0']").selectOption("1.5");
+ await expect.poll(() => clip("r001")?.zooms?.[0]?.scale).toBe(1.5);
+ await page.locator("[data-zoom-remove='0']").click();
+ await expect.poll(() => clip("r001") && "zooms" in clip("r001")).toBe(false);
+ // Hidden regions (slice E): a box on every clip of this recording, taken off again; one on this clip alone.
+ await page.locator("[data-censor-box='x']").fill("75");
+ await page.locator("[data-censor-box='y']").fill("0");
+ await page.locator("[data-censor-box='w']").fill("25");
+ await page.locator("[data-censor-box='h']").fill("100");
+ await page.locator("[data-censor-style]").selectOption("black");
+ await page.locator("[data-censor-add='r001']").click();
+ await expect.poll(() => render().censor ?? null).toEqual([{ video: "vid1", boxes: [[0.75, 0, 0.25, 1]], style: "black" }]);
+ await page.locator("[data-censor-remove='r0']").click();
+ await expect.poll(() => render().censor ?? null).toBe(null);
+ await page.locator("[data-censor-scope]").selectOption("clip");
+ await page.locator("[data-censor-add='r001']").click();
+ await expect.poll(() => clip("r001")?.censor ?? null).toEqual({ boxes: [[0.75, 0, 0.25, 1]], style: "black" });
+ // The player draws it over the picture (an editing surface): filled black, outlined, Peek OFF until pressed.
+ const over = page.getByTestId("editor-censor");
+ await expect(over).toHaveAttribute("data-censor-overlay", "edit");
+ await expect(over.locator("[data-censor-region]")).toHaveCount(1);
+ await expect(over.locator("[data-censor-region]")).toHaveCSS("background-color", "rgb(0, 0, 0)");
+ await expect(over.locator("[data-censor-peek]")).toHaveAttribute("aria-pressed", "false");
+ await over.locator("[data-censor-peek]").click();
+ await expect(over.locator("[data-censor-peek]")).toHaveAttribute("aria-pressed", "true");
+ await expect(over.locator("[data-censor-region]")).not.toHaveCSS("background-color", "rgb(0, 0, 0)");
+ await page.locator("[data-censor-remove='c0']").click();
+ await expect.poll(() => clip("r001") && "censor" in clip("r001")).toBe(false);
+ await expect(over).toHaveCount(0);
+ // The portrait: the player ready, the playhead moved (l: 2 s on), the frame there grabbed into shots/.
+ await expect(page.locator("[data-editor-player]")).toHaveAttribute("data-editor-player", /^(?!looking|none)/, { timeout: 20_000 });
+ if (!render().promo) test.skip(true, "the look test sets the promo first");
+ await page.locator("body").press("l");
+ await expect(page.locator("[data-promo-portrait='r001']")).toBeEnabled();
+ await page.locator("[data-promo-portrait='r001']").click();
+ await expect(page.locator("[data-promo-portrait-set]")).toContainText("shots/still-r001-");
+ const portrait = render().promo?.portrait;
+ expect(portrait?.file).toMatch(/^shots\/still-r001-.*\.png$/);
+ expect(portrait?.from?.clip).toBe("r001");
+ expect(existsSync(path.join(DIR, portrait.file))).toBe(true);
+});
+
+test("umtool shorts, as ⌘K runs it: each clip in both formats into shorts-kit/, named, recorded, ending on the card", async ({ page }) => {
+ test.setTimeout(420_000);
+ await page.goto(urls.homeHref());
+ const origin = new URL(page.url()).origin;
+ if (!render().promo) test.skip(true, "the look test sets the promo first");
+ const r = await page.request.post("/api/cli", { data: { verb: "shorts", values: { project: PROJECT, "--take": "kit", "--items": "r001,r002", "--formats": "vertical,desktop", "--hook": "title" } }, headers: { origin } });
+ expect(r.status()).toBe(202);
+ const { queued, line } = (await r.json()) as { queued: { qid: string }; line: string };
+ expect(line).toBe(`node umtool/bin/umtool.mjs shorts ${PROJECT} --take kit --items r001,r002 --formats vertical,desktop --hook title`);
+ const stepOf = async () => (await (await page.request.get(`/api/cli?qid=${queued.qid}`)).json()) as { step: { state: string }; log: unknown };
+ await expect.poll(async () => ["queued", "running"].includes((await stepOf()).step.state), { timeout: 400_000, intervals: [2000] }).toBe(false);
+ const step = await stepOf();
+ expect(step.step.state, Array.isArray(step.log) ? step.log.slice(-20).join("\n") : String(step.log)).toBe("done");
+ const folder = path.join(DIR, "shorts-kit");
+ const batch = JSON.parse(readFileSync(path.join(folder, "batch.json"), "utf8"));
+ expect(batch.kind).toBe("shorts-batch");
+ expect(batch.clips.map((c: { id: string; name: string }) => [c.id, c.name])).toEqual([["r001", "r001"], ["r002", "r002"]]);
+ for (const c of batch.clips) {
+ expect(c.errors).toEqual({});
+ for (const [fmt, size] of [["vertical", [1080, 1920]], ["desktop", [1920, 1080]]] as const) {
+ const file = path.join(folder, c.files[fmt]);
+ const p = JSON.parse(probe(file));
+ expect([p.streams[0].width, p.streams[0].height]).toEqual(size);
+ // The clip (about 2 s) and the card's silent second.
+ expect(Number(p.format.duration)).toBeGreaterThan(2.5);
+ const rec = JSON.parse(readFileSync(file.replace(/\.mp4$/, ".json"), "utf8"));
+ expect(rec.layout).toBe(fmt === "vertical" ? "vertical" : "desktop");
+ }
+ }
+ // The card was drawn into the build's cards; the segment's record names it.
+ const seg = JSON.parse(readFileSync(path.join(DIR, "takes", "kit", "out", "vertical-shorts-vertical", "segments", "r002.cut.json"), "utf8"));
+ expect(seg.promo).toMatchObject({ lead: 1, fade: 0.3, hold: 1, captions: true });
+ // Not the clip editor's shorts/: its list has none of these.
+ expect(existsSync(path.join(DIR, "shorts", "r001.vertical.mp4"))).toBe(false);
+});
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -1912,6 +1912,13 @@ makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out"
makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "add-clip-fixture", title: "The Add Clip 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" });
+// Lane clip-kit: the batch of shorts, the QR's corner and link, desktop clips, the channel promo (clip-kit.spec.ts):
+// the same cut, its own copy, with a draft take `kit` the batch is cut from.
+{
+ const { dir } = makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "clip-kit-fixture", title: "The Clip Kit Fixture" });
+ mkdirSync(path.join(dir, "takes", "kit"), { recursive: true });
+ writeFileSync(path.join(dir, "takes", "kit", "take.json"), JSON.stringify({ id: "kit", group: "takes", order: 1, label: "Clips", kind: "reference", preview: "preview.mp4", window: "full", style: null, patch: null, draft: true }, null, 2) + "\n");
+}
// P4b: the bench shell's own clips, and the Media tab's fields with their draft files.
makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Walk a take: a draft take of sub-windows, walked on the bench (take-walk.spec.ts).
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -488,16 +488,17 @@ export const GROUPS = [
cmd: "export",
usage: [
" umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]",
- " umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] one clip,",
- " clean, into <project>/exports/: the cut's edges, its gaps out, its mute; --context N what the cut",
- " plays ± N s; --raw the whole fetched window, or a span (the full exchange), as recorded; --fetch",
+ " umtool export <project> <clip> [--context N | --raw [--from S --to S] [--uncensored-raw]] [--fetch] [--take T] [--open]",
+ " one clip, clean, into <project>/exports/: the cut's edges, its gaps out, its mute; --context N what",
+ " the cut plays ± N s; --raw the whole fetched window, or a span (the full exchange), as recorded; its",
+ " hidden regions hidden (a raw export of a clip with boxes refused unless --uncensored-raw); --fetch",
" asks the editor first for what that needs; in the heavy slot; --open shows it",
],
docs: [
["`export <project> --format toc-bbcode\\|toc-markdown\\|description\\|chapters [--variant V] [--first TITLE]`",
"the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00"],
["`export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson`",
- "**one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip))"],
+ "**one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. A clip's hidden regions (`render.censor`, its `censor`) are hidden in a cut or context export; a raw export of a clip with boxes is refused unless `--uncensored-raw`, which shows them and says so. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip))"],
],
},
{
@@ -693,7 +694,7 @@ export const GROUPS = [
usage: [
" umtool vertical <project> --take <t> (--reel R | --beats F | --items a,b) [--clip full|framed|quote]",
" [--post card|stack|media] [--side split|overlay] [--hook title|section|<copy>] [--deck stacked|bare]",
- " [--reframe] [--json]",
+ " [--reframe | --landscape] [--json]",
" a vertical short (1080x1920, -14 LUFS) of the take's items: each clip cut again in its layout,",
" each post drawn in a portrait box; --reframe recomposes the finished 16:9 master instead",
],
@@ -701,6 +702,37 @@ export const GROUPS = [
],
},
{
+ cmd: "censor",
+ usage: [
+ " umtool censor <project> --video <id> [--channel <slug>] --box x,y,w,h[@from-to] [--box …] [--style blur|black|pixelate]",
+ " [--strength 1-10] [--from s] [--to s] | --clear | --list the same parts of the picture hidden on",
+ " every clip of one recording (render.censor: a chat overlay, a window with other accounts)",
+ ],
+ docs: [
+ ],
+ },
+ {
+ cmd: "promo",
+ usage: [
+ " umtool promo <project> [--portrait-from <clip>@<second>] [--box x,y,w,h] [--draw] [--take <t>] [--json]",
+ " the channel promo (render.promo, set with `umtool look <p> promo=…`): its portrait grabbed",
+ " from a clip at a second into shots/, its card drawn 9:16 and 16:9 into out/promo/",
+ ],
+ docs: [
+ ],
+ },
+ {
+ cmd: "shorts",
+ usage: [
+ " umtool shorts <project> --take <t> (--items a,b | --all | --again) [--formats vertical,landscape]",
+ " [the vertical flags] [--max-vertical 180] [--max-landscape 140] [--replace] [--dry-run] [--json]",
+ " a batch of shorts: each clip in each format through `umtool vertical`'s builder, into the",
+ " project's shorts-<take>/ as <name>.<format>.mp4 (the title's slug) with batch.json",
+ ],
+ docs: [
+ ],
+ },
+ {
cmd: "trailer-beats",
usage: [
" umtool trailer-beats <project> [ls] | add <clip> [<from>-<to>] [--at N] [--label L] | add-raw <at> <dur> | set <n> <from>-<to>",
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -251,7 +251,7 @@ export const VERBS = Object.freeze([
form("diff", "project", "what changed since a snapshot", [project(), arg("snapshot", { help: "its path under revisions/" })]),
form("export", "project", "the posting artifacts, or one clip clean into exports/", [
project(), clip({ required: false, help: "one clip (none: --format)" }), pick("--format", ["toc-bbcode", "toc-markdown", "description", "chapters"]), opt("--variant"), opt("--first"),
- num("--context", { help: "± s, as recorded" }), bool("--raw", "the fetched window as recorded"), num("--from"), num("--to"), bool("--fetch", "ask the editor first for what is not on disk"), takeOpt(),
+ num("--context", { help: "± s, as recorded" }), bool("--raw", "the fetched window as recorded"), bool("--uncensored-raw", "a raw export of a clip that hides regions, shown as recorded"), num("--from"), num("--to"), bool("--fetch", "ask the editor first for what is not on disk"), takeOpt(),
], { ...Q, ...B(["clip"], { clip: "{id}" }) }),
form("check-sources", "corpus", "the re-check chain, printed", [many("projects", { help: "one per line (none: the never-checked and > 30 d)" })]),
@@ -322,8 +322,31 @@ export const VERBS = Object.freeze([
form("vertical", "project", "a vertical short (1080x1920) of a take's items", [
project(), takeOpt({ required: true, help: "the take" }), reel(), file("--beats", { help: "a beats file of the project" }), opt("--items", { help: "id,id" }), pick("--clip", ["full", "framed", "quote"]), pick("--post", ["card", "stack", "media"]),
pick("--side", ["split", "overlay"]), opt("--hook", { help: "title | section | a line of the cut's own copy" }), pick("--captions", ["l", "xl"]), pick("--lines", ["1", "2"]), num("--loudness"), num("--max"),
- name("--name"), bool("--reframe", "recompose the finished 16:9 master"), dry(), bool("--intro"), bool("--no-intro"), bool("--no-outro"),
- pick("--deck", ["stacked", "bare"]),
+ name("--name"), bool("--reframe", "recompose the finished 16:9 master"), bool("--landscape", "the same items in the take's 16:9 look"), bool("--desktop", "the same items 16:9, minimal chrome (render.desktop)"), dry(), bool("--intro"), bool("--no-intro"), bool("--no-outro"),
+ pick("--deck", ["stacked", "bare"]), pick("--qr", ["on", "off"]), pick("--qr-corner", ["tr", "tl", "br", "bl"], { help: "br and bl: a desktop clip's" }),
+ bool("--promo", "end on the take's channel promo (render.promo)"), bool("--no-promo", "end without it"),
+ num("--promo-lead", { help: "s before the end the card comes up (4.5)" }), num("--promo-fade", { help: "s (0.7)" }), num("--promo-hold", { help: "s of silence on the card (1.5)" }),
+ bool("--no-cold-open", "play the clips as cut, without their cold opens"),
+ ], Q),
+ form("censor", "project", "the regions hidden on every clip of one recording (a chat overlay, other accounts)", [
+ project(), opt("--video", { help: "the recording's id" }), opt("--channel", { help: "its channel (default: any)" }),
+ many("--box", { item: "string", help: "x,y,w,h or x,y,w,h@from-to, one per line" }), pick("--style", ["blur", "black", "pixelate"]),
+ num("--strength", { help: "1-10 (7)" }), num("--from", { help: "s" }), num("--to", { help: "s" }), bool("--clear", "this recording's regions removed"), bool("--list", "every recording's"),
+ ]),
+ form("promo", "project", "the channel promo: its portrait from a clip at a second, its card drawn", [
+ project(), opt("--portrait-from", { help: "<clip>@<source second>" }), opt("--box", { help: "x,y,w,h: the circle's part of the frame" }),
+ bool("--draw", "draw the card 9:16 and 16:9 into out/promo/"), takeOpt({ help: "draw it in this take's look" }),
+ ]),
+ form("shorts", "project", "a batch of shorts: each clip of a take in each format, into shorts-<take>/", [
+ project(), takeOpt({ required: true, help: "the take" }), opt("--items", { help: "id,id" }), bool("--all", "every clip of the take"),
+ bool("--again", "the folder's batch.json made again"), opt("--formats", { help: "vertical,desktop,landscape (default vertical)" }),
+ pick("--clip", ["full", "framed", "quote"]), pick("--post", ["card", "stack", "media"]), pick("--side", ["split", "overlay"]),
+ opt("--hook", { help: "title | section | a line of the cut's own copy" }), pick("--captions", ["l", "xl"]), pick("--lines", ["1", "2"]), num("--loudness"),
+ num("--max-vertical", { help: "s (180): over it, a note" }), num("--max-landscape", { help: "s (140): over it, a note" }), num("--max-desktop", { help: "s (140): over it, a note" }),
+ pick("--deck", ["stacked", "bare"]), pick("--qr", ["on", "off"]), pick("--qr-corner", ["tr", "tl", "br", "bl"], { help: "br and bl: the desktop clips'; a short keeps tr" }),
+ bool("--no-promo", "no channel promo at the end"), num("--promo-lead", { help: "s (4.5)" }), num("--promo-fade", { help: "s (0.7)" }), num("--promo-hold", { help: "s (1.5)" }),
+ bool("--no-cold-open", "play the clips as cut, without their cold opens"),
+ bool("--replace", "set a file there aside and make it again"), dry(),
], Q),
// ---- the trailer's beats ----
diff --git a/umtool/lib/clips/cited.test.ts b/umtool/lib/clips/cited.test.ts
@@ -6,14 +6,17 @@
// Run with: pnpm --filter umtool exec tsx --test lib/clips/cited.test.ts
import { before, test } from "node:test";
import assert from "node:assert/strict";
-import { mkdtemp } from "node:fs/promises";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
let lib: typeof import("./cited");
+let ROOT = "";
before(async () => {
- process.env.CHANNELS_DIR = path.join(await mkdtemp(path.join(os.tmpdir(), "umtool-cited-")), "channels");
+ ROOT = await mkdtemp(path.join(os.tmpdir(), "umtool-cited-"));
+ process.env.CHANNELS_DIR = path.join(ROOT, "channels");
+ process.env.REPORTS_DIR = path.join(ROOT, "reports");
lib = await import("./cited");
});
@@ -81,3 +84,19 @@ test("Cut from the stored media URL rides on the fetch as fetch_clip's storedUrl
await lib.fetchCitedClip({ target, reason: "review" }, plain.deps);
assert.equal("storedUrl" in (plain.calls[0].body ?? {}), false);
});
+
+test("a cited span of a project carries the regions it hides on that recording: its clip's, else the recording's", async () => {
+ const dir = path.join(ROOT, "reports", "hide");
+ await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true });
+ await writeFile(path.join(dir, "out", "clips-raw", "vid1_0.00-10.00.mp4"), "a window");
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: "hide", title: "Hide",
+ provenance: { channelSlug: "chan", channelsDir: path.join(ROOT, "channels") },
+ render: { fps: 30, censor: [{ video: "vid1", boxes: [[0.75, 0, 0.25, 1]], style: "black" }] },
+ timeline: [{ type: "clip", id: "c1", channel: "chan", video: "vid1", start: 2, end: 6, censor: { boxes: [[0, 0, 0.2, 0.2]] } }],
+ }));
+ const play = await lib.findCitedPlay({ channel: "chan", video: "vid1", from: 2, to: 6, project: "hide", clip: "c1" });
+ assert.ok(play, "the project's window plays");
+ assert.equal(play.kind, "window");
+ assert.equal(play.hidden?.length, 2, "the recording's box and the clip's own");
+});
diff --git a/umtool/lib/clips/cited.ts b/umtool/lib/clips/cited.ts
@@ -8,7 +8,7 @@ import { resolveEvidenceSource } from "yt-dlp-transcript-common/lib/evidenceClip
import { CHANNELS_DIR } from "@/lib/paths";
import { answerOf } from "@/lib/research/fetch";
import { SourceError } from "@/lib/research/sources";
-import { projectCache, resolveClip, windowVersion, windowsFor } from "@/lib/report/serve.mjs";
+import { projectCache, resolveClip, resolveReport, windowVersion, windowsFor } from "@/lib/report/serve.mjs";
import { corpusMediaUrl } from "@/lib/articles/article";
import type { CitedFetchAnswer, CitedPlay, CitedTarget } from "./types";
import { fetchFailureSentence } from "./words";
@@ -80,9 +80,22 @@ async function projectPlay(t: CitedTarget): Promise<CitedPlay | null> {
};
}
-/** What plays the span now, or null (nothing on disk: offer Fetch clip). */
+/** What plays the span now, or null (nothing on disk: offer Fetch clip). A project's hidden regions ride along. */
export async function findCitedPlay(t: CitedTarget): Promise<CitedPlay | null> {
- return (await projectPlay(t)) ?? (await corpusPlay(t));
+ const play = (await projectPlay(t)) ?? (await corpusPlay(t));
+ if (!play || play.audio || !t.project) return play;
+ const hidden = await citedHidden(t);
+ return hidden.length ? { ...play, hidden } : play;
+}
+
+/** The regions a project hides on the cited recording: its clip's (render.censor's and its own), else the recording's. */
+async function citedHidden(t: CitedTarget) {
+ const { censorRegionsOf, recordingRegionsOf } = await import("umtool-report-to-video/clip-censor");
+ const r = t.clip ? await resolveClip(t.project as string, t.clip).catch(() => null) : null;
+ if (r && !("error" in r)) return censorRegionsOf(r.clip, r.manifest.render ?? {}, r.manifest.provenance ?? {});
+ const rep = await resolveReport(t.project as string).catch(() => null);
+ if (!rep || "error" in rep) return [];
+ return recordingRegionsOf(t.video, t.channel, rep.manifest.render ?? {}, rep.manifest.provenance ?? {});
}
/** Parse a target from a query string or a JSON body; throws a 400 in words. */
diff --git a/umtool/lib/clips/types.ts b/umtool/lib/clips/types.ts
@@ -9,6 +9,11 @@ export type CitedPlay = {
offset: number;
audio: boolean;
label: string;
+ /**
+ * The regions the project hides on this recording (clip-censor.mjs: the clip's own and render.censor's, or the
+ * recording's alone where no clip is named), on the SOURCE clock: the player overlays them. Absent: none.
+ */
+ hidden?: Array<{ box: number[]; style: "blur" | "black" | "pixelate"; strength: number; from: number | null; to: number | null }>;
};
/**
diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts
@@ -14,6 +14,7 @@ import { projectCache, segmentFor, windowVersion, windowsFor } from "@/lib/repor
import { FETCH_MAX_WINDOW } from "@/lib/report/driver.mjs";
import { gapWalls } from "umtool-report-to-video/gaps";
import { deckOn } from "umtool-report-to-video/deck";
+import { censorRegionsOf } from "umtool-report-to-video/clip-censor";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import { readWorkingCut } from "@/lib/report/workingCut.mjs";
import type { ProjectRef } from "@/lib/project-types";
@@ -164,6 +165,8 @@ export async function clipBenchData(
// Whether the cut is built with the on-screen panel. Decides whether the
// bench composes a preview of it; the fields are there either way.
deckOn: deckOn(manifest.render ?? {}),
+ // Every region the cut hides on it (clip-censor.mjs): the bench draws them over the raw window.
+ hidden: censorRegionsOf(((manifest.timeline ?? []) as { id: string }[]).find((e) => e.id === clipId) ?? {}, manifest.render ?? {}, manifest.provenance ?? {}),
generatedBy: typeof manifest.generatedBy === "string" ? manifest.generatedBy : null,
view,
// `v`: the version of each window's bytes, for the media URLs (serve.mjs, "A REPLACED FILE IS A NEW FILE").
diff --git a/umtool/lib/report/censorCli.mjs b/umtool/lib/report/censorCli.mjs
@@ -0,0 +1,104 @@
+// `umtool censor` (lane clip-kit, slice E): the boxes hidden on every clip cut from ONE recording -- a stream layout's
+// chat overlay, a browser window showing other people's accounts -- written into `render.censor` (report-to-video
+// clip-censor.mjs) through the look's writer. A clip's own boxes are `umtool set <p> <clip> censor.boxes=…`.
+//
+// umtool censor <project> --video <id> [--channel <slug>] --box x,y,w,h[@from-to] [--box …]
+// [--style blur|black|pixelate] [--strength 1-10] [--from s] [--to s] [--json]
+// umtool censor <project> --video <id> [--channel <slug>] --clear
+// umtool censor <project> --list
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { kindMakesTakes } from "../projects/kinds.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { manifestToken, updateRender } from "./manifest.mjs";
+
+export const CENSOR_USAGE = [
+ "usage: umtool censor <project> --video <id> [--channel <slug>] --box x,y,w,h[@from-to] [--box …]",
+ " [--style blur|black|pixelate] [--strength 1-10] [--from s] [--to s] [--json]",
+ " umtool censor <project> --video <id> [--channel <slug>] --clear",
+ " umtool censor <project> --list",
+ "",
+ "Hides the same parts of the picture on every clip cut from one recording (render.censor): fractions of the",
+ "source picture, each box for the whole clip or, with @from-to (source seconds), that span. Blurred (default),",
+ "black or pixelated; on in the uncensored variant too (privacy, not TOS). Given again for the same recording, the",
+ "boxes replace its boxes. A clip's own: `umtool set <p> <clip> censor.boxes='[[x,y,w,h]]'` (`censor=false` none).",
+].join("\n");
+
+class CliError extends Error {}
+
+/** `x,y,w,h` or `x,y,w,h@from-to`, read. */
+export function parseBox(text) {
+ const m = /^([0-9.]+),([0-9.]+),([0-9.]+),([0-9.]+)(?:@([0-9.]+)-([0-9.]+))?$/.exec(String(text ?? "").trim());
+ if (!m) throw new CliError(`--box ${text}: x,y,w,h (fractions of the picture), or x,y,w,h@from-to (source seconds)`);
+ const box = m.slice(1, 5).map(Number);
+ return m[5] !== undefined ? { box, from: Number(m[5]), to: Number(m[6]) } : box;
+}
+
+/** render.censor with one recording's boxes set (`entry`) or removed (null). */
+export function withRecording(list, { video, channel = null }, entry) {
+ const same = (r) => r?.video === video && (r.channel ?? null) === channel;
+ const rest = (Array.isArray(list) ? list : []).filter((r) => !same(r));
+ return entry ? [...rest, entry] : rest;
+}
+
+/**
+ * `umtool censor …`
+ * @param {string[]} args
+ * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void }} [o]
+ */
+export async function censorCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) {
+ try {
+ const flags = { "--box": [] };
+ const pos = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (["--video", "--channel", "--style", "--strength", "--from", "--to", "--box"].includes(a)) {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ if (a === "--box") flags["--box"].push(args[++i]);
+ else flags[a] = args[++i];
+ } else if (["--clear", "--list", "--json", "--help"].includes(a)) flags[a] = true;
+ else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`);
+ else pos.push(a);
+ }
+ if (flags["--help"] || !pos.length) {
+ log(CENSOR_USAGE);
+ return flags["--help"] ? 0 : 2;
+ }
+ const r = await resolveProject(pos[0], reportsRoot);
+ if (r.ambiguous) throw new CliError(`"${pos[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${pos[0]}"`);
+ if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`);
+ const manifest = await readManifest(r.project.dir);
+ const now = Array.isArray(manifest?.render?.censor) ? manifest.render.censor : [];
+ if (flags["--list"]) {
+ log(flags["--json"] ? JSON.stringify(now, null, 2) : now.length ? now.map((e) => `${e.channel ? `${e.channel}/` : ""}${e.video}: ${e.boxes.length} box(es), ${e.style ?? "blur"}`).join("\n") : "no recording's regions are hidden (render.censor)");
+ return 0;
+ }
+ const video = typeof flags["--video"] === "string" ? flags["--video"].trim() : "";
+ if (!video) throw new CliError("--video <id>: the recording whose clips hide the boxes");
+ const channel = typeof flags["--channel"] === "string" ? flags["--channel"].trim() : null;
+ let entry = null;
+ if (!flags["--clear"]) {
+ if (!flags["--box"].length) throw new CliError("--box x,y,w,h (one or more), or --clear");
+ const num = (k) => (flags[k] !== undefined ? Number(flags[k]) : undefined);
+ entry = {
+ video, ...(channel ? { channel } : {}), boxes: flags["--box"].map(parseBox),
+ ...(flags["--style"] ? { style: flags["--style"] } : {}),
+ ...(num("--strength") !== undefined ? { strength: num("--strength") } : {}),
+ ...(num("--from") !== undefined ? { from: num("--from") } : {}),
+ ...(num("--to") !== undefined ? { to: num("--to") } : {}),
+ };
+ }
+ const next = withRecording(now, { video, channel }, entry);
+ const w = await updateRender(r.project.dir, { censor: next.length ? next : null }, { token: await manifestToken(r.project.dir) });
+ const written = w.look.censor ?? [];
+ if (flags["--json"]) log(JSON.stringify(written, null, 2));
+ else log(entry ? `${channel ? `${channel}/` : ""}${video}: ${entry.boxes.length} box(es) hidden on every clip of it (${entry.style ?? "blur"})` : `${video}: no regions hidden`);
+ return 0;
+ } catch (e) {
+ if (e instanceof CliError || e?.name === "RenderRefused") {
+ err(`umtool censor: ${e instanceof Error ? e.message : e}`);
+ return 2;
+ }
+ throw e;
+ }
+}
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -40,7 +40,10 @@ import {
updateMarks,
updateClip,
updateOnscreen,
+ updateRender,
} from "./manifest.mjs";
+import { censorRegionsOf, namesClip } from "umtool-report-to-video/clip-censor";
+import { withRecording } from "./censorCli.mjs";
import { CLAIM_KNOB_DEFAULTS, markVerdictsOf, rawMarksOf, stampingEntryId } from "./knobs.mjs";
import { resolveFactcheck } from "umtool-report-to-video/factcheck";
import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs";
@@ -51,6 +54,7 @@ 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";
+import { CLIP_KIT_KEYS } from "umtool-report-to-video/clip-kit";
export { StaleToken, StructureRefused };
@@ -94,7 +98,7 @@ export async function readWords(dir, reactions = null) {
* @typedef {{ id: string, channel: string | null, video: string, start: number, end: number,
* cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null,
* assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean,
- * vertical: { crop: number[], aspect?: number } | null,
+ * vertical: { crop: number[], aspect?: number } | null, kit: Record<string, unknown>,
* room: false | { tail?: boolean, head?: boolean } | null, roomEdges: { tail: boolean, head: boolean } | null,
* gaps?: Array<{ from: number, to: number }> }} EditorClip
*/
@@ -127,6 +131,13 @@ export async function clipEditorView(project) {
montage: isObj(e.montage),
// A short's framing (release 36): fractions of the source picture.
vertical: isObj(e.vertical) && Array.isArray(e.vertical.crop) ? { crop: e.vertical.crop, ...(fin(e.vertical.aspect) ? { aspect: e.vertical.aspect } : {}) } : null,
+ // The clip kit (lane clip-kit): its own code and name for a per-clip build, as written.
+ kit: Object.fromEntries(CLIP_KIT_KEYS.filter((k) => e[k] !== undefined).map((k) => [k, e[k]])),
+ // Its recording's hidden regions (render.censor naming its video), for the Hide regions list.
+ recordingCensor: (Array.isArray(manifest.render?.censor) ? manifest.render.censor : []).filter((r) => namesClip(r, e, manifest.provenance ?? {})),
+ // Every region the cut hides on it (its own and its recording's, clip-censor.mjs): the player and the live
+ // preview draw them over the picture.
+ hidden: censorRegionsOf(e, manifest.render ?? {}, manifest.provenance ?? {}),
// Room at its edges (release 36 lane E): the clip's own override as
// written, and the edges it gets with the cut's render.room.
room: e.room === false ? false : isObj(e.room) ? e.room : null,
@@ -563,6 +574,30 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
structural = false;
break;
}
+ case "kit": {
+ // The clip kit (lane clip-kit, clip-kit.mjs): its keys merged as `umtool set` merges them (a key null clears
+ // it), through the same writer. A "trim" that leaves the cut where it is; not structural.
+ const e = needClip();
+ if (!isObj(body.kit) || !Object.keys(body.kit).length) throw new OpError(`kit is {${CLIP_KIT_KEYS.join("?, ")}?}: the keys to set`);
+ const bad = Object.keys(body.kit).filter((k) => !CLIP_KIT_KEYS.includes(k.split(".")[0]));
+ if (bad.length) throw new OpError(`kit: ${bad.join(", ")} is not a clip kit key (${CLIP_KIT_KEYS.join(", ")})`);
+ result = await updateClip(dir, e.id, body.kit, { token, edit: "trim", now });
+ structural = false;
+ break;
+ }
+ case "censor-recording": {
+ // The regions hidden on every clip of THIS clip's recording (render.censor; clip-censor.mjs), through the
+ // look's writer and its checks: `censor` {boxes, style?, strength?} sets them, null removes them.
+ const e = needClip();
+ if (body.censor !== null && !isObj(body.censor)) throw new OpError("censor is {boxes, style?, strength?}, or null for none");
+ const m = await readManifest(dir);
+ const key = { video: e.video, channel: null };
+ const next = withRecording(m?.render?.censor, key, body.censor ? { video: e.video, ...body.censor } : null);
+ const w = await updateRender(dir, { censor: next.length ? next : null }, { token });
+ result = { censor: w.look.censor ?? null };
+ structural = false;
+ break;
+ }
case "room": {
const e = needClip();
if (body.room !== null && body.room !== false && !isObj(body.room)) throw new OpError("room is false, {tail?, head?}, or null for the cut's");
@@ -618,7 +653,7 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
break;
}
default:
- throw new OpError("op must be trim, restore, split, merge, flash-forward, add, bring-in, ruling, role, label, vertical, room, claim, marks, audio, blur or onscreen");
+ throw new OpError("op must be trim, restore, split, merge, flash-forward, add, bring-in, ruling, role, label, vertical, kit, censor-recording, room, claim, marks, audio, blur or onscreen");
}
let carried = null;
if (structural) {
diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts
@@ -29,6 +29,12 @@ export type EditorClip = {
gaps?: { from: number; to: number }[];
/** A short's framing (release 36): `crop` = [x, y, w, h], fractions of the source picture. */
vertical: { crop: number[]; aspect?: number } | null;
+ /** The clip kit (lane clip-kit): its own code (`qr`: false or {corner?, links?}) and batch `name`, as written. */
+ kit?: { qr?: false | { corner?: string; links?: string }; name?: string; promo?: false | { lead?: number; fade?: number; hold?: number }; zooms?: unknown[]; coldOpen?: { from: number; to: number }; censor?: false | CensorSet; [k: string]: unknown };
+ /** Its recording's hidden regions (render.censor naming its video). */
+ recordingCensor?: Array<CensorSet & { video: string; channel?: string }>;
+ /** Every region the cut hides on it (clip-censor.mjs censorRegionsOf): drawn over the player and the live preview. */
+ hidden?: Array<{ box: number[]; style: "blur" | "black" | "pixelate"; strength: number; from: number | null; to: number | null }>;
/** Room at its edges (release 36 lane E): the clip's own `room` as written (false: none), and the edges it gets. */
room?: false | { tail?: boolean; head?: boolean } | null;
roomEdges?: { tail: boolean; head: boolean } | null;
@@ -122,3 +128,7 @@ export type Neighbourhood = {
/** The take "Render a take" makes again (the clip deck's rule), or null: the Takes page chooses. */
export type RenderTarget = { take: string; label: string; builtAt: string | null; why: "latest" | "picked" | "whole cut" } | null;
+
+/** Hidden regions (report-to-video clip-censor.mjs): boxes as fractions of the source picture, each maybe over a span. */
+export type CensorBox = number[] | { box: number[]; from?: number; to?: number };
+export type CensorSet = { boxes: CensorBox[]; style?: "blur" | "black" | "pixelate"; strength?: number; from?: number; to?: number };
diff --git a/umtool/lib/report/clipExport.mjs b/umtool/lib/report/clipExport.mjs
@@ -39,6 +39,7 @@
//
// The pure half (names, the plan's ffmpeg arguments) is tested in
// clipExport.test.mjs; `exportClip` runs it.
+import { censorParts } from "umtool-report-to-video/clip-censor";
import { spawn } from "node:child_process";
import { mkdir, rename, rm, stat } from "node:fs/promises";
import path from "node:path";
@@ -292,6 +293,9 @@ export const planSeconds = (plan) => gappedLength(plan.from, plan.to, plan.gaps)
* @param {{ crf?: number, preset?: string, audioBitrate?: string }} [opts]
* @returns {string[]}
*/
+/** The seconds an export plays (planSeconds, before it is declared below). */
+const kept0 = (plan) => gappedLength(plan.from, plan.to, plan.gaps);
+
export function exportArgs(plan, out, { crf = 18, preset = "medium", audioBitrate = "192k" } = {}) {
const a = Math.max(0, plan.from - plan.fetchStart);
const b = Math.max(a, plan.to - plan.fetchStart);
@@ -308,6 +312,14 @@ export function exportArgs(plan, out, { crf = 18, preset = "medium", audioBitrat
const local = plan.gaps.map((g) => ({ from: g.from - plan.from, to: g.to - plan.from }));
const g = gapFilterParts({ gaps: local, seconds, vIn: plan.hasVideo === false ? null : "[0:v]", aIn: "[aclk]" });
parts.push(...g.parts);
+ // Hidden regions (report-to-video clip-censor.mjs): on the picture as the cut hides them, over their spans on this
+ // export's clock (its first frame is plan.from).
+ let vOut = g.v;
+ if (vOut && plan.censor?.regions?.length) {
+ const cp = censorParts(vOut.slice(1, -1), "vcen", plan.censor.regions, { width: plan.censor.width, height: plan.censor.height, from: plan.from, gaps: plan.gaps, seconds: kept0(plan) });
+ parts.push(...cp);
+ vOut = "[vcen]";
+ }
const kept = planSeconds(plan);
const af = [];
if (plan.soundFrom != null) af.push(`afade=t=in:st=${n3(plan.soundFrom)}:d=${n3(MUTE_FADE)}`);
@@ -317,7 +329,7 @@ export function exportArgs(plan, out, { crf = 18, preset = "medium", audioBitrat
af.push(...clipAudioFilters(plan.kind === "cut" ? plan.audio : null, kept));
parts.push(`${g.a}${af.length ? af.join(",") : "anull"}[aout]`);
args.push("-filter_complex", parts.join(";"));
- if (g.v) args.push("-map", g.v === "[0:v]" ? "0:v:0" : g.v);
+ if (vOut) args.push("-map", vOut === "[0:v]" ? "0:v:0" : vOut);
args.push("-map", "[aout]");
if (g.v) args.push("-c:v", "libx264", "-preset", preset, "-crf", String(crf), "-pix_fmt", "yuv420p");
args.push("-c:a", "aac", "-b:a", audioBitrate, "-movflags", "+faststart", "-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn");
@@ -420,7 +432,7 @@ async function heldWindow(project, entry, want, take = null) {
* @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "context" | "raw", name: string, rel: string,
* abs: string, size: number, mtimeMs: number, seconds: number, summary: string, notes: string[], plan: ExportPlan }>}
*/
-export async function exportClip(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, ffmpeg, today } = {}) {
+export async function exportClip(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, ffmpeg, today, uncensoredRaw = false } = {}) {
if (!EXPORT_KINDS.includes(kind)) throw new ExportRefused(`an export is one of ${EXPORT_KINDS.join(", ")}`, 400);
const ctx = kind === "context" ? contextSeconds(context) : EXPORT_CONTEXT.default;
const sp = kind === "raw" ? spanOf(span) : null;
@@ -460,6 +472,21 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", c
? { ...row, cutStart: row.pieced.cutStart, cutEnd: row.pieced.cutEnd, gaps: row.pieced.gaps }
: row;
const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source, media, row: planRow, kind, context: ctx, span: sp });
+ // HIDDEN REGIONS (report-to-video clip-censor.mjs): a privacy control, so a cut or a context export hides them as
+ // the cut does; a raw export is "as recorded" and is REFUSED for a clip with boxes unless asked for uncensored,
+ // which it then says.
+ const { censorRegionsOf } = await import("umtool-report-to-video/clip-censor");
+ const regions = media.hasVideo === false ? [] : censorRegionsOf(got.entry, got.render, got.provenance ?? {});
+ if (regions.length && kind === "raw" && !uncensoredRaw) {
+ throw new ExportRefused(`${clipId} hides ${regions.length} region(s) of its picture (render.censor / its censor): a raw export is as recorded, and would show them -- export the cut or with --context (both hide them), or add --uncensored-raw to export the recording as it is`, 409);
+ }
+ if (regions.length && kind !== "raw") {
+ const { probeDims } = await import("umtool-report-to-video/build-video");
+ const [width, height] = await probeDims(source.path);
+ plan.censor = { regions, width, height };
+ plan.notes.push(`${regions.length} region(s) hidden (render.censor / its censor)`);
+ }
+ if (regions.length && kind === "raw") plan.notes.push(`UNCENSORED: ${regions.length} region(s) this clip hides are SHOWN (--uncensored-raw)`);
if (!(planSeconds(plan) > 0.05)) throw new ExportRefused(`${clipId}: nothing to export (${planSummary(plan)})`, 422);
const name = exportName(got.entry, { kind, context: ctx, span: sp, ...(today ? { today } : {}) });
const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR);
@@ -498,16 +525,16 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", c
* @param {{ id: string, dir: string }} project
* @param {string} clipId
* @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null,
- * fetch?: { padBefore: number, padAfter: number } | null, manifestPath?: string | null }} o
+ * fetch?: { padBefore: number, padAfter: number } | null, manifestPath?: string | null, uncensoredRaw?: boolean }} o
*/
-export async function exportSteps(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, fetch = null, manifestPath = null } = {}) {
+export async function exportSteps(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, fetch = null, manifestPath = null, uncensoredRaw = false } = {}) {
const { UMTOOL_DIR, editorFetchSteps, fetchSteps, localFetch } = await import("./driver.mjs");
const steps = [];
if (fetch) {
const pads = { padBefore: fetch.padBefore, padAfter: fetch.padAfter };
steps.push(...(localFetch() ? fetchSteps(project, clipId, pads, { manifestPath }) : editorFetchSteps(project, clipId, pads, { manifestPath })));
}
- const kindArgs = kind === "context" ? ["--context", String(context)] : kind === "raw" ? ["--raw", ...(span ? ["--from", String(span.from), "--to", String(span.to)] : [])] : [];
+ const kindArgs = kind === "context" ? ["--context", String(context)] : kind === "raw" ? ["--raw", ...(span ? ["--from", String(span.from), "--to", String(span.to)] : []), ...(uncensoredRaw ? ["--uncensored-raw"] : [])] : [];
steps.push({
cwd: UMTOOL_DIR,
env: {},
diff --git a/umtool/lib/report/clipExport.test.mjs b/umtool/lib/report/clipExport.test.mjs
@@ -225,6 +225,51 @@ test("export a clip: the kept seconds land in exports/ under the clip's name; ra
await assert.rejects(exportClip(project, "nope"), /no clip nope/);
});
+/** The mean luma of a box of the frame at `t` s (0–255). */
+function lumaAt(file, t, { x, y, w, h }) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", `crop=${w}:${h}:${x}:${y},format=gray`, "-f", "rawvideo", "-"]);
+ assert.equal(r.status, 0, String(r.stderr));
+ return r.stdout.reduce((n, v) => n + v, 0) / r.stdout.length;
+}
+
+test("hidden regions: a cut and a context export hide them; a raw export is refused unless --uncensored-raw, which says so", { skip: !have && "needs ffmpeg" }, async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-"));
+ roots.push(root);
+ mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true });
+ const raw = path.join(root, "out", "clips-raw", "vid2_0.00-12.00.mp4");
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=white:s=320x180:r=30:d=12",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12",
+ "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ writeFileSync(path.join(root, "video.manifest.json"), JSON.stringify({
+ slug: "expc", title: "Export",
+ provenance: { channelSlug: "synth", channelsDir: CORPUS },
+ render: { width: 320, height: 180, fps: 30, fetchPad: 1, transition: 0, censor: [{ video: "vid2", boxes: [[0.5, 0, 0.5, 1]], style: "black" }] },
+ timeline: [{ type: "clip", id: "c1", channel: "synth", video: "vid2", start: 2, end: 9, date: "2026-08-12", quote: "Deal with it", gaps: [{ from: 4, to: 5.5 }] }],
+ }));
+ const project = { id: "expc", dir: root };
+ const RIGHT = { x: 200, y: 20, w: 100, h: 140 };
+ const LEFT = { x: 20, y: 20, w: 100, h: 140 };
+ for (const o of [{ kind: "cut" }, { kind: "context", context: 1 }]) {
+ const x = await exportClip(project, "c1", o);
+ assert.match(x.notes.join(" "), /1 region\(s\) hidden/);
+ for (const t of [0.5, 4]) {
+ assert.ok(lumaAt(x.abs, t, RIGHT) < 30, `${o.kind}: hidden at ${t} s (${lumaAt(x.abs, t, RIGHT)})`);
+ assert.ok(lumaAt(x.abs, t, LEFT) > 220, `${o.kind}: the rest as recorded at ${t} s`);
+ }
+ }
+ await assert.rejects(exportClip(project, "c1", { kind: "raw" }), (e) => e.status === 409 && /c1 hides 1 region\(s\).*--uncensored-raw/.test(e.message));
+ const un = await exportClip(project, "c1", { kind: "raw", uncensoredRaw: true });
+ assert.match(un.notes.join(" "), /UNCENSORED: 1 region\(s\) this clip hides are SHOWN/);
+ assert.ok(lumaAt(un.abs, 1, RIGHT) > 220, "as recorded");
+ // The job the app runs carries the flag only when asked.
+ const steps = await exportSteps(project, "c1", { kind: "raw", uncensoredRaw: true });
+ assert.ok(steps.at(-1).argv.includes("--uncensored-raw"));
+ assert.ok(!(await exportSteps(project, "c1", { kind: "raw" })).at(-1).argv.includes("--uncensored-raw"));
+});
+
test("export a clip whose window is not on disk: refused, fetch it first", async () => {
const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-"));
roots.push(root);
diff --git a/umtool/lib/report/clipKit.test.mjs b/umtool/lib/report/clipKit.test.mjs
@@ -0,0 +1,145 @@
+// The clip kit's keys written (lane clip-kit): `umtool set`'s and the clip editor's writer (manifest.mjs updateClip)
+// takes a clip's `qr` (whole or one field) and its batch `name`, refuses what the build would, and clears with null.
+import assert from "node:assert/strict";
+import { mkdir, 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, updateClip } from "./manifest.mjs";
+
+const manifest = () => ({
+ schemaVersion: 1,
+ slug: "kit",
+ provenance: { channelSlug: "chan", siteOrigin: "" },
+ render: { width: 640, height: 360, fps: 15 },
+ timeline: [{ type: "clip", id: "w01", video: "01a1d292-6d30", start: 10, end: 20, citeUrl: "https://kick.com/somechan/videos/01a1d292-6d30" }],
+});
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")).timeline[0];
+
+test("updateClip: a clip's qr (whole or one field) and name; refused in the build's words; null clears", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-kit-"));
+ try {
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n");
+ await updateClip(dir, "w01", { "qr.corner": "tl" });
+ assert.deepEqual((await read(dir)).qr, { corner: "tl" });
+ await updateClip(dir, "w01", { "qr.links": "moment" });
+ assert.deepEqual((await read(dir)).qr, { corner: "tl", links: "moment" });
+ await updateClip(dir, "w01", { "qr.corner": null });
+ assert.deepEqual((await read(dir)).qr, { links: "moment" });
+ await updateClip(dir, "w01", { qr: false });
+ assert.equal((await read(dir)).qr, false);
+ await updateClip(dir, "w01", { qr: null });
+ assert.equal("qr" in (await read(dir)), false);
+ await updateClip(dir, "w01", { name: " toms-toast " });
+ assert.equal((await read(dir)).name, "toms-toast");
+ await assert.rejects(updateClip(dir, "w01", { "qr.corner": "middle" }), /w01\.qr\.corner is one of br, bl, tr, tl/);
+ await assert.rejects(updateClip(dir, "w01", { name: "x".repeat(61) }), /name is a file name of 1 to 60/);
+ // A refused write leaves the file as it was.
+ assert.deepEqual(await read(dir), { ...manifest().timeline[0], name: "toms-toast" });
+ await updateClip(dir, "w01", { name: "" });
+ assert.equal("name" in (await read(dir)), false);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+import { updateRender } from "./manifest.mjs";
+
+test("the channel promo written: the look's (checked by the build's rules) and a clip's own (false, or its timing)", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-promo-"));
+ try {
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n");
+ // A code linking the channel needs the channel's page first.
+ await assert.rejects(updateRender(dir, { qr: { links: "channel" } }), /set render\.promo\.url/);
+ const r = await updateRender(dir, { promo: { name: ["Synth", "Live"], url: "https://kick.com/somechan" } });
+ assert.deepEqual(r.look.promo, { name: ["Synth", "Live"], url: "https://kick.com/somechan" });
+ await assert.rejects(updateRender(dir, { promo: { name: "Synth", url: "kick.com" } }), /render\.promo\.url is the channel's page/);
+ await updateClip(dir, "w01", { promo: false });
+ assert.equal((await read(dir)).promo, false);
+ await updateClip(dir, "w01", { "promo.hold": 2 });
+ assert.deepEqual((await read(dir)).promo, { hold: 2 });
+ await assert.rejects(updateClip(dir, "w01", { "promo.hold": 9 }), /w01\.promo\.hold is 0–5 seconds/);
+ await updateClip(dir, "w01", { promo: null });
+ assert.equal("promo" in (await read(dir)), false);
+ // The render's promo removed: none again.
+ await updateRender(dir, { promo: null });
+ assert.equal(JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")).render.promo, undefined);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a clip's zooms written: whole, checked against its window and each other; [] or null clears", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-zooms-"));
+ try {
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n");
+ await updateClip(dir, "w01", { zooms: [{ at: 12, scale: 1.5, focus: [0.7, 0.3] }] });
+ assert.deepEqual((await read(dir)).zooms, [{ at: 12, scale: 1.5, focus: [0.7, 0.3] }]);
+ await assert.rejects(updateClip(dir, "w01", { zooms: [{ at: 19 }] }), /w01\.zooms\[0\] \(19–21\.3 s\) runs outside the clip's window \(10–20\)/);
+ await assert.rejects(updateClip(dir, "w01", { zooms: [{ at: 11 }, { at: 12 }] }), /starts before the one at 11 s is out again/);
+ await updateClip(dir, "w01", { zooms: [] });
+ assert.equal("zooms" in (await read(dir)), false);
+ // Written, a zoom is checked against the CUT: one inside the window the cut does not play is refused.
+ const m = manifest();
+ Object.assign(m.timeline[0], { cutStart: 12, cutEnd: 17 });
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n");
+ await assert.rejects(updateClip(dir, "w01", { zooms: [{ at: 16 }] }), /w01\.zooms\[0\] \(16–18\.3 s\) runs outside the clip's cut \(12–17\)/);
+ await assert.rejects(updateClip(dir, "w01", { zooms: [{ at: 11 }] }), /runs outside the clip's cut \(12–17\)/);
+ await updateClip(dir, "w01", { zooms: [{ at: 12.5 }] });
+ await assert.rejects(updateRender(dir, { zooms: { soften: 2 } }), /soften is 1–1\.3/);
+ assert.deepEqual((await updateRender(dir, { zooms: { soften: 1.3 } })).look.zooms, { soften: 1.3 });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a clip's cold open written: both fields in one patch, inside its cut, 1-4 s; null clears", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-coldopen-"));
+ try {
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n");
+ await updateClip(dir, "w01", { "coldOpen.from": 17, "coldOpen.to": 19.5 });
+ assert.deepEqual((await read(dir)).coldOpen, { from: 17, to: 19.5 });
+ await assert.rejects(updateClip(dir, "w01", { "coldOpen.to": 25 }), /w01\.coldOpen is 8 s: a cold open is 1–4 s/);
+ await assert.rejects(updateClip(dir, "w01", { coldOpen: { from: 19, to: 21 } }), /outside the clip's cut \(10–20\)/);
+ // Across a gap, or the whole cut: refused at write time, naming the clip and the gap.
+ const m = manifest();
+ Object.assign(m.timeline[0], { cutStart: 12, cutEnd: 15, gaps: [{ from: 13.5, to: 14 }] });
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n");
+ await assert.rejects(updateClip(dir, "w01", { coldOpen: { from: 13, to: 14.5 } }), /w01\.coldOpen \(13–14\.5\) runs across w01's gap 13\.5–14 s/);
+ await assert.rejects(updateClip(dir, "w01", { coldOpen: { from: 12, to: 15 } }), /w01\.coldOpen \(12–15\) is the whole cut/);
+ await assert.doesNotReject(updateClip(dir, "w01", { coldOpen: { from: 12, to: 13.4 } }));
+ await updateClip(dir, "w01", { coldOpen: null });
+ assert.equal("coldOpen" in (await read(dir)), false);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+import { censorCommand } from "./censorCli.mjs";
+
+test("hidden regions written: a clip's own (dotted fields), a recording's through umtool censor; refused in the build's words", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "umtool-censor-"));
+ const dir = path.join(root, "reports", "proj");
+ try {
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n");
+ await updateClip(dir, "w01", { "censor.boxes": [[0, 0, 0.2, 0.2]], "censor.style": "black" });
+ assert.deepEqual((await read(dir)).censor, { boxes: [[0, 0, 0.2, 0.2]], style: "black" });
+ await assert.rejects(updateClip(dir, "w01", { "censor.style": "smudge" }), /censor\.style is one of blur, black, pixelate/);
+ await updateClip(dir, "w01", { censor: false });
+ assert.equal((await read(dir)).censor, false);
+ const out = [];
+ const code = await censorCommand(["proj", "--video", "01a1d292-6d30", "--box", "0.75,0,0.25,1", "--box", "0,0.6,0.3,0.4@12-14", "--style", "pixelate"], { reportsRoot: path.join(root, "reports"), log: (s) => out.push(s), err: (s) => out.push(s) });
+ assert.equal(code, 0, out.join("\n"));
+ const m = JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+ assert.deepEqual(m.render.censor, [{ video: "01a1d292-6d30", boxes: [[0.75, 0, 0.25, 1], { box: [0, 0.6, 0.3, 0.4], from: 12, to: 14 }], style: "pixelate" }]);
+ const bad = [];
+ assert.equal(await censorCommand(["proj", "--video", "x", "--box", "0.9,0,0.3,1"], { reportsRoot: path.join(root, "reports"), log: () => {}, err: (s) => bad.push(s) }), 2);
+ assert.match(bad.join(), /boxes\[0\] is \[x, y, w, h\]/);
+ assert.equal(await censorCommand(["proj", "--video", "01a1d292-6d30", "--clear"], { reportsRoot: path.join(root, "reports"), log: () => {}, err: () => {} }), 0);
+ assert.equal(JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")).render.censor, undefined);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/deliverables.test.mjs b/umtool/lib/report/deliverables.test.mjs
@@ -99,7 +99,9 @@ test("updateStorage writes the switch, keeps the rest, and does not rewrite a no
test("deliverable names: clips and share-*, never a leftover, a file or another directory", async () => {
assert.ok(isDeliverableName("clips") && isDeliverableName("share-first") && isDeliverableName("share-batch-2026.10.01"));
- for (const no of ["out", "share-", "shares", "clips.moved-20261001T000000Z", "share-x.incoming", "../clips", "share-a/b"]) {
+ // A take's batch of shorts (lane clip-kit): shorts-<take>, never the clip editor's own shorts/.
+ assert.ok(isDeliverableName("shorts-kit") && isDeliverableName("shorts-x-2"));
+ for (const no of ["out", "share-", "shares", "clips.moved-20261001T000000Z", "share-x.incoming", "../clips", "share-a/b", "shorts", "shorts-", "shorts-a/b", "shorts-kit.incoming"]) {
assert.equal(isDeliverableName(no), false, no);
}
const w = await world();
diff --git a/umtool/lib/report/inspectorEdits.test.mjs b/umtool/lib/report/inspectorEdits.test.mjs
@@ -187,6 +187,35 @@ test("a still at second N: one frame of the fetched window into shots/, listed;
await assert.rejects(grabStill(p, m, "nope", 1), /no clip nope/);
});
+/** The mean luma of a box of a PNG (0–255). */
+function pngLuma(file, { x, y, w, h }) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `crop=${w}:${h}:${x}:${y},format=gray`, "-f", "rawvideo", "-"]);
+ assert.equal(r.status, 0, String(r.stderr));
+ return r.stdout.reduce((n, v) => n + v, 0) / r.stdout.length;
+}
+
+test("a still of a clip that hides regions: the boxes over its second hidden in the PNG; outside their span, as recorded", { skip: !hasFfmpeg && "no ffmpeg" }, async () => {
+ const m0 = MANIFEST();
+ m0.render.censor = [{ video: "vid1", boxes: [{ box: [0.5, 0, 0.5, 1], from: 1, to: 2 }], style: "black" }];
+ const p = await project(m0);
+ await mkdir(path.join(p.dir, "out", "clips-raw"), { recursive: true });
+ const win = path.join(p.dir, "out", "clips-raw", "vid1_0.00-9.00.mp4");
+ const ff = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=white:size=160x90:rate=10:duration=9", "-pix_fmt", "yuv420p", win]);
+ assert.equal(ff.status, 0, String(ff.stderr));
+ const m = await read(p.dir);
+ const RIGHT = { x: 100, y: 10, w: 50, h: 70 };
+ const LEFT = { x: 10, y: 10, w: 50, h: 70 };
+ const inside = await grabStill(p, m, "c01", 1.5);
+ assert.ok(pngLuma(inside.file, RIGHT) < 30, `hidden (${pngLuma(inside.file, RIGHT)})`);
+ assert.ok(pngLuma(inside.file, LEFT) > 220, "the rest as recorded");
+ const outside = await grabStill(p, m, "c01", 2.5);
+ assert.ok(pngLuma(outside.file, RIGHT) > 220, "past its span: as recorded");
+ // A clip's own box (no span: the whole clip), whatever the recording's.
+ m.timeline[0].censor = { boxes: [[0, 0, 0.5, 1]], style: "black" };
+ const own = await grabStill(p, m, "c01", 2.5, { name: "still-own.png" });
+ assert.ok(pngLuma(own.file, LEFT) < 30 && pngLuma(own.file, RIGHT) > 220, "its own box");
+});
+
// ---- the CLI twins (inspectorCli.mjs; timelineCli.mjs teaser-insert; linksCli.mjs --embed-ids) ----
const cli = await import("./inspectorCli.mjs");
const { timelineCommand } = await import("./timelineCli.mjs");
diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs
@@ -57,11 +57,15 @@ const FX_KEYS = ["fx", ...FX_ENTRY_FIELDS.map((k) => `fx.${k}`)];
const GAP_KEYS = ["gaps", "gap.add", "gap.remove"];
export const VERTICAL_SET_KEYS = Object.freeze(["vertical", "vertical.crop", "vertical.layout", "vertical.aspect", "vertical.crops"]);
export const SIDE_SET_KEYS = Object.freeze(["side", "side.item", "side.post", "side.from", "side.to", "side.place"]);
+/** The clip kit (lane clip-kit; report-to-video clip-kit.mjs): a clip's code in a per-clip build, its batch file name. */
+export const KIT_SET_KEYS = Object.freeze(["qr", "qr.corner", "qr.links", "name", "promo", "promo.lead", "promo.fade", "promo.hold", "zooms", "coldOpen", "coldOpen.from", "coldOpen.to", "censor", "censor.boxes", "censor.style", "censor.strength", "censor.from", "censor.to"]);
const SET_KEYS = [
"claim", ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS,
...FX_KEYS, ...GAP_KEYS, "chat", "hideModules", "shelfNote", "chapter",
// The vertical format (lane vertical): the clip's 9:16 crop and layout, and its side post.
...VERTICAL_SET_KEYS, ...SIDE_SET_KEYS,
+ // The clip kit (lane clip-kit): its code and its name in a batch of shorts.
+ ...KIT_SET_KEYS,
];
export const SET_USAGE = [
@@ -115,6 +119,18 @@ export const SET_USAGE = [
" side.item=<post item id> | side.post='{\"author\",\"handle\",\"date\",\"text\",…}' -- a post shown BESIDE the",
" clip while it plays, never read, the clip's sound running; side.from / side.to seconds into the clip;",
" side.place=split|overlay (vertical) | right|left (16:9). `side=` removes it (docs/knobs.md \"Vertical\").",
+ " qr=false: no code on this clip; qr.corner=br|bl|tr|tl (a short: tr|tl) and qr.links=cite|moment|channel over",
+ " the cut's (render.qr, render.vertical.qr); `qr=` the cut's again. name=<file name>: its files in a batch of",
+ " shorts (umtool shorts) are called that, not its title's slug; `name=` the title's again.",
+ " promo=false: a per-clip build of this clip ends without the channel promo (render.promo); promo.lead /",
+ " promo.fade / promo.hold (seconds) its own timing over the cut's; `promo=` the cut's again.",
+ " zooms='[{\"at\":231.4,\"scale\":1.3,\"focus\":[0.7,0.35],\"hold\":1.5}]' pushes a short's or a desktop clip's",
+ " picture in at those source seconds (or \"box\":[x,y,w,h] to fill the frame with); `zooms=` none.",
+ " coldOpen.from=… coldOpen.to=… (source seconds of its cut, 1-4 s): a short or a desktop clip plays that payoff",
+ " first, then cuts to the clip's start; `coldOpen=` none.",
+ " censor.boxes='[[x,y,w,h]]' hides those parts of its picture (fractions of the source; a box may be",
+ " {\"box\":[…],\"from\":s,\"to\":s}); censor.style=blur|black|pixelate, censor.strength=1-10, censor.from/to;",
+ " censor=false: none, not even its recording's (`umtool censor` sets a recording's); `censor=` its recording's.",
" gap.add=12.3-15.1 cuts those source seconds out of the clip's middle (one segment of jump cuts; inside",
" the cut, ≥ 0.2 s, 0.5 s kept between); gap.remove=<sec> the gap holding it; gaps=12.3-15.1,20-20.6 (or",
" a JSON list of {from,to}) the whole list, `gaps=` none. The same as `umtool window --gap/--gap-remove/--gaps`.",
@@ -244,6 +260,11 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
entryPatch[key] = key === "side.item" && value !== null ? String(value) : value;
continue;
}
+ if (KIT_SET_KEYS.includes(key)) {
+ // A name is words whatever it parses as; the rest as given (clip-kit.mjs checks them in the writer).
+ entryPatch[key] = key === "name" && value !== null ? String(value) : value;
+ continue;
+ }
if (key === "shelfNote") {
// A note on the shelf over this entry's span (deck.mjs parseShelfNote checks it); words whatever they parse as.
entryPatch.shelfNote = value === null || value === undefined ? null : String(value);
@@ -350,6 +371,12 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if ("chat" in entryPatch) results.chat = result.entry.chat ?? null;
if (VERTICAL_SET_KEYS.some((k) => k in entryPatch)) results.vertical = result.entry.vertical ?? null;
if (SIDE_SET_KEYS.some((k) => k in entryPatch)) results.side = result.entry.side ?? null;
+ if (["qr", "qr.corner", "qr.links"].some((k) => k in entryPatch)) results.qr = result.entry.qr ?? null;
+ if ("name" in entryPatch) results.name = result.entry.name ?? null;
+ if (["promo", "promo.lead", "promo.fade", "promo.hold"].some((k) => k in entryPatch)) results.promo = result.entry.promo ?? null;
+ if ("zooms" in entryPatch) results.zooms = result.entry.zooms ?? null;
+ if (Object.keys(entryPatch).some((k) => k === "censor" || k.startsWith("censor."))) results.censor = result.entry.censor ?? null;
+ if (["coldOpen", "coldOpen.from", "coldOpen.to"].some((k) => k in entryPatch)) results.coldOpen = result.entry.coldOpen ?? null;
if (FX_KEYS.some((k) => k in entryPatch)) results.fx = result.entry.fx ?? null;
if ("gaps" in entryPatch || "gapAdd" in entryPatch || "gapRemove" in entryPatch) {
results.gaps = result.entry.gaps ?? [];
@@ -387,6 +414,12 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if ("fx" in results) out(`${clipId}: fx ${results.fx ? JSON.stringify(results.fx) : "none"}`);
if ("vertical" in results) out(`${clipId}: vertical ${results.vertical ? JSON.stringify(results.vertical) : "the cut's (the centred crop)"}`);
if ("side" in results) out(`${clipId}: side ${results.side ? JSON.stringify({ ...results.side, ...(results.side.post ? { post: `@${results.side.post.handle ?? results.side.post.author}` } : {}) }) : "none"}`);
+ if ("qr" in results) out(`${clipId}: qr ${results.qr === false ? "none on this clip" : results.qr ? JSON.stringify(results.qr) : "the cut's"}`);
+ if ("censor" in results) out(`${clipId}: censor ${results.censor === false ? "none (not even its recording's)" : results.censor ? JSON.stringify(results.censor) : "its recording's (render.censor)"}`);
+ if ("coldOpen" in results) out(`${clipId}: cold open ${results.coldOpen ? `${results.coldOpen.from}–${results.coldOpen.to} s, played first` : "none"}`);
+ if ("zooms" in results) out(`${clipId}: zooms ${results.zooms ? results.zooms.map((z) => `${z.at} s ×${z.scale ?? (z.box ? "box" : 1.3)}`).join(", ") : "none"}`);
+ if ("promo" in results) out(`${clipId}: promo ${results.promo === false ? "none (it ends without the card)" : results.promo ? JSON.stringify(results.promo) : "the cut's"}`);
+ if ("name" in results) out(`${clipId}: name ${results.name ? JSON.stringify(results.name) : "its title's slug"}`);
if ("gaps" in results) out(`${clipId}: ${results.gaps.length ? `gaps ${results.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "no gaps (the cut plays whole)"}`);
if (results.review) {
const r = results.review;
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", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows"]);
+ assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows", "desktop", "promo", "zooms", "censor"]);
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
@@ -38,6 +38,12 @@ import {
import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { verticalErrors } from "umtool-report-to-video/look";
+import { CLIP_KIT_KEYS, clipKitErrors, validateClipKit } from "umtool-report-to-video/clip-kit";
+import { validatePromo } from "umtool-report-to-video/promo-card";
+import { renderZoomsErrors } from "umtool-report-to-video/clip-zoom";
+import { renderCensorErrors } from "umtool-report-to-video/clip-censor";
+/** The kit keys a clip patch sets (clip-kit.mjs), whole or one dotted field. */
+const CLIP_KIT_PATCH_KEYS = CLIP_KIT_KEYS;
import { LOOK_KEYS, applyLookPatch, basicOn, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
import { sideErrors } from "yt-dlp-transcript-common/lib/report/vertical.mjs";
import { validateRoom } from "umtool-report-to-video/room";
@@ -849,6 +855,28 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n
if (errors.length) throw new Error(errors.join("; "));
}
+ // ---- the clip kit (lane clip-kit; report-to-video clip-kit.mjs) ----------
+ //
+ // A clip's own code for a per-clip build (`qr`: false, or {corner?, links?}, whole or one field) and its pinned
+ // file name in a batch of shorts (`name`). null / "" removes one. Checked by the build's own rules.
+ for (const key of CLIP_KIT_PATCH_KEYS) {
+ const whole = patch[key];
+ const fields = Object.keys(patch).filter((k) => k.startsWith(`${key}.`));
+ if (whole === undefined && !fields.length) continue;
+ let next = whole !== undefined ? (whole === null || whole === "" ? null : whole) : isObj(entry[key]) ? { ...entry[key] } : {};
+ for (const k of fields) {
+ const f = k.slice(key.length + 1);
+ const v = patch[k];
+ if (next === null || !isObj(next)) next = {};
+ if (v === null || v === "") delete next[f];
+ else next[f] = v;
+ }
+ if (next === null || (isObj(next) && !Object.keys(next).length) || (Array.isArray(next) && !next.length)) delete entry[key];
+ else entry[key] = typeof next === "string" ? next.trim() : next;
+ const errors = clipKitErrors(entry, clipId, { writer: true });
+ if (errors.length) throw new Error(errors.join("; "));
+ }
+
// ---- the walk's verdict -------------------------------------------------
//
// Whether somebody has LOOKED at this clip, and what they said: confirmed,
@@ -1886,6 +1914,12 @@ export async function updateRender(dir, patch, { token = null } = {}) {
if (token !== null && current !== token) throw new StaleToken(token, current);
const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
const { render, errors } = applyLookPatch(manifest, patch);
+ // The channel promo (report-to-video promo-card.mjs) and the clip kit's QR: the build's own rules.
+ if ("promo" in patch || "qr" in patch) errors.push(...validatePromo({ render }), ...validateClipKit({ render, timeline: manifest.timeline ?? [] }));
+ // The zooms' soft limit (report-to-video clip-zoom.mjs).
+ if ("zooms" in patch) errors.push(...renderZoomsErrors(render.zooms));
+ // The recordings' hidden regions (report-to-video clip-censor.mjs).
+ if ("censor" in patch) errors.push(...renderCensorErrors(render.censor));
if (errors.length) throw new RenderRefused(errors);
manifest.render = render;
const nextToken = await writeManifestAtomic(dir, manifest);
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -8,6 +8,7 @@
//
// Nothing is fetched or cut here: a clip whose source window is not on disk
// is listed with `media: null` and plays as a placeholder.
+import { censorRegionsOf } from "umtool-report-to-video/clip-censor";
import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video";
import { deckOn, estimatedDuration, estimateSchedule, scheduleFrom, transitionOf } from "umtool-report-to-video/deck";
import { resolveFactcheck } from "umtool-report-to-video/factcheck";
@@ -233,6 +234,8 @@ export async function playViewWith(project, { take = null, bare = false, postFor
// Seconds taken out of its middle (gaps.mjs): the plan plays it as one item of jump cuts.
...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}),
blur: e.blur && typeof e.blur === "object" ? e.blur : null,
+ // Its hidden regions (report-to-video clip-censor.mjs): Play draws them over the picture as the cut hides them.
+ censor: censorRegionsOf(e, render, selected.provenance ?? {}),
// Its SIDE POST (lane vertical, common lib/report/vertical.mjs): shown beside it over `from`-`to` (seconds
// into the clip as it plays), never read -- Play lays its card (the post-item route's `side` page) over the clip.
...(e.side && typeof e.side === "object" && fin(e.side.from) && fin(e.side.to) ? { side: { from: e.side.from, to: e.side.to, place: typeof e.side.place === "string" ? e.side.place : null } } : {}),
diff --git a/umtool/lib/report/present.mjs b/umtool/lib/report/present.mjs
@@ -36,6 +36,7 @@ import { clockZoneOf } from "umtool-report-to-video/post-clock";
import { estimateSchedule } from "umtool-report-to-video/deck";
import { gapsOf, keptSpans } from "umtool-report-to-video/gaps";
import { clipBlurOf } from "umtool-report-to-video/clip-blur";
+import { censorRecordOf, censorRegionsOf } from "umtool-report-to-video/clip-censor";
import { playViewWith } from "./playView.mjs";
import { projectRedaction } from "./postRedaction.mjs";
import { sectionModel } from "./sectionEdit.mjs";
@@ -315,9 +316,14 @@ function postSlideId(e) {
* THE PAYLOAD, pure (the tests' door): Play's view of the cut, the cut itself, the project's redaction and the
* deck's estimated schedule -> the presentation.
*
- * @param {{ view: Record<string, any>, manifest: Record<string, any>, red: any, canUncensor?: boolean }} o
+ * A clip that hides regions of its picture (clip-censor.mjs) carries NO raw window on a payload that cannot uncensor:
+ * its `media` is null, and `censored` names its BUILT segment when one hides exactly its regions (`censoredSegments`,
+ * read by presentPayload: `{v, seconds}` by entry id), else null -- the slide says the clip is not shown. The
+ * operator's payload keeps the window, the regions overlaid on the operator's screen.
+ *
+ * @param {{ view: Record<string, any>, manifest: Record<string, any>, red: any, canUncensor?: boolean, censoredSegments?: Map<string, { v: number, seconds: number | null }> }} o
*/
-export function presentFrom({ view, manifest, red, canUncensor = true }) {
+export function presentFrom({ view, manifest, red, canUncensor = true, censoredSegments = new Map() }) {
const render = manifest.render ?? {};
const timeline = (Array.isArray(manifest.timeline) ? manifest.timeline : []).filter((e) => e && typeof e.id === "string");
const zone = clockZoneOf(render);
@@ -421,6 +427,10 @@ export function presentFrom({ view, manifest, red, canUncensor = true }) {
const to = fin(e.cutEnd) ? e.cutEnd : e.end;
const spans = keptSpans(from, to, gapsOf(e));
const day = dayOfKey(e.dateKey);
+ // Its hidden regions (clip-censor.mjs). A public payload never names the raw window of a clip that has them.
+ const hidden = censorRegionsOf(src, render, manifest.provenance ?? {});
+ const withheld = !canUncensor && hidden.length > 0;
+ const seg = withheld ? (censoredSegments.get(e.id) ?? null) : null;
slides.push({
id: unique(e.id),
kind: "clip",
@@ -431,7 +441,8 @@ export function presentFrom({ view, manifest, red, canUncensor = true }) {
dateLabel: dayLabel(day),
video: e.video,
channel: e.channel ?? null,
- media: e.media ?? null,
+ media: withheld ? null : (e.media ?? null),
+ ...(withheld ? { censored: seg ? { segment: seg.v, seconds: seg.seconds } : null } : {}),
spans,
seconds: Math.round(spans.reduce((n, s) => n + (s.to - s.from), 0) * 1000) / 1000,
title: words?.title || text(e.heading),
@@ -439,6 +450,8 @@ export function presentFrom({ view, manifest, red, canUncensor = true }) {
quote: e.quote ?? null,
qrUrl: words?.qrUrl ?? null,
blur: clipBlurOf(src, render),
+ // The operator's page overlays them on the raw window (on the screen, not in the file).
+ hidden,
});
continue;
}
@@ -515,5 +528,31 @@ export async function presentPayload(project, { take = null, bare = false, canUn
if ("error" in r) return r;
const { anonymiseManifest } = await import("umtool-report-to-video/post-anon");
const manifest = anonymity ? anonymiseManifest(r.manifest, anonymity.doc, { set: anonymity.set }) : r.manifest;
- return presentFrom({ view: r.view, manifest, red, canUncensor });
+ return presentFrom({ view: r.view, manifest, red, canUncensor, censoredSegments: canUncensor ? new Map() : await censoredSegmentsOf(project, manifest) });
+}
+
+/**
+ * The BUILT segments (/api/report/segment: the project's out/, its cut record beside it) that hide exactly the
+ * regions a clip asks for now, by entry id -- what a public Present plays instead of the raw window. A segment cut
+ * with other boxes (or none) is not used.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} manifest
+ */
+export async function censoredSegmentsOf(project, manifest) {
+ const { segmentFor } = await import("./serve.mjs");
+ const { readFile } = await import("node:fs/promises");
+ const out = new Map();
+ for (const e of manifest.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ const want = censorRecordOf(censorRegionsOf(e, manifest.render ?? {}, manifest.provenance ?? {}));
+ if (!want.length) continue;
+ const seg = await segmentFor(project, e.id).catch(() => null);
+ if (!seg) continue;
+ const rec = await readFile(/* turbopackIgnore: true */ seg.abs.replace(/\.mp4$/, ".cut.json"), "utf8").then(JSON.parse, () => null);
+ if (JSON.stringify(rec?.censor ?? []) !== JSON.stringify(want)) continue;
+ const seconds = typeof rec?.start === "number" && typeof rec?.end === "number" ? Math.round((rec.end - rec.start) * 1000) / 1000 : null;
+ out.set(e.id, { v: seg.mtimeMs, seconds });
+ }
+ return out;
}
diff --git a/umtool/lib/report/present.test.mjs b/umtool/lib/report/present.test.mjs
@@ -14,6 +14,8 @@ const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-present-"));
after(() => rm(ROOT, { recursive: true, force: true }));
// Never the real corpus: the play view looks for cached windows and markup under the channels dir.
process.env.CHANNELS_DIR = path.join(ROOT, "channels");
+// The projects are under it: the built-segment lookup (serve.mjs segmentFor) reads only inside the read roots.
+process.env.REPORTS_DIR = path.join(ROOT, "reports");
process.env.UMTOOL_PRINTS_CACHE = path.join(ROOT, "prints");
const { presentPayload, presentFrom, censorData, publicPostEntry, dayIn, dayLabel, isPostReel, PRESENT_DEFAULTS } = await import("./present.mjs");
@@ -239,3 +241,59 @@ test("the intro (render.intro) is the first slide, before any divider, in the fi
const none = await presentPayload(await project("intro-none", MIXED, MIXED_RENDER));
assert.ok(!none.slides.some((s) => s.kind === "intro"));
});
+
+test("hidden regions (clip-censor.mjs): a clip slide carries its own boxes and its recording's, on a public payload too; Play's entry carries them", async () => {
+ const own = { style: "black", boxes: [{ box: [0.1, 0.1, 0.2, 0.2], from: 1.5, to: 2.5 }] };
+ const p = await project("hidden", [
+ { type: "clip", id: "c01", video: "v1", start: 1, end: 3, lock: true, censor: own },
+ { type: "clip", id: "c02", video: "v2", start: 1, end: 3, lock: true },
+ ], { censor: [{ video: "v1", style: "blur", boxes: [[0.6, 0.6, 0.3, 0.3]] }] });
+ for (const canUncensor of [true, false]) {
+ const pl = await presentPayload(p, { canUncensor });
+ const c1 = pl.slides.find((s) => s.id === "c01");
+ const c2 = pl.slides.find((s) => s.id === "c02");
+ assert.equal(c1.hidden.length, 2, `the clip's box and its recording's (canUncensor ${canUncensor})`);
+ assert.deepEqual(c1.hidden.map((g) => g.style).sort(), ["black", "blur"]);
+ const black = c1.hidden.find((g) => g.style === "black");
+ assert.deepEqual([black.from, black.to], [1.5, 2.5], "its span, source seconds");
+ assert.deepEqual(c2.hidden, [], "another recording: none");
+ }
+ const { playView } = await import("./playView.mjs");
+ const view = await playView(p);
+ assert.equal(view.entries.find((e) => e.id === "c01").censor.length, 2, "Play draws the same boxes");
+});
+
+test("a PUBLIC payload never names the raw window of a clip that hides regions: its built segment when it hides exactly them, else none; the operator's keeps the window", async () => {
+ const own = { style: "black", boxes: [[0.1, 0.1, 0.2, 0.2]] };
+ const timeline = [
+ { type: "clip", id: "c01", video: "v1", start: 1, end: 3, lock: true, censor: own },
+ { type: "clip", id: "c02", video: "v2", start: 1, end: 3, lock: true },
+ ];
+ const p = await project("withheld", timeline);
+ await mkdir(path.join(p.dir, "out", "clips-raw"), { recursive: true });
+ await writeFile(path.join(p.dir, "out", "clips-raw", "v1_0.00-6.00.mp4"), "raw window one");
+ await writeFile(path.join(p.dir, "out", "clips-raw", "v2_0.00-6.00.mp4"), "raw window two");
+ const op = await presentPayload(p);
+ assert.equal(op.slides.find((s) => s.id === "c01").media?.name, "v1_0.00-6.00.mp4", "the operator's page plays the window, overlaid");
+ const pub = await presentPayload(p, { canUncensor: false });
+ const json = JSON.stringify(pub);
+ assert.ok(!json.includes("v1_0.00-6.00"), "no path to the raw window anywhere in the public payload");
+ const c1 = pub.slides.find((s) => s.id === "c01");
+ assert.equal(c1.media, null);
+ assert.equal(c1.censored, null, "no build here: the slide says it is not shown");
+ // The same clip without regions: unchanged.
+ assert.deepEqual(pub.slides.find((s) => s.id === "c02"), (await presentPayload(p, { canUncensor: false })).slides.find((s) => s.id === "c02"));
+ assert.equal(pub.slides.find((s) => s.id === "c02").media?.name, "v2_0.00-6.00.mp4");
+ assert.equal("censored" in pub.slides.find((s) => s.id === "c02"), false);
+ // A built segment that hides exactly its regions: played instead; one cut with other boxes is not.
+ const segs = path.join(p.dir, "out", "segments");
+ await mkdir(segs, { recursive: true });
+ await writeFile(path.join(segs, "c01.mp4"), "built");
+ await writeFile(path.join(segs, "c01.cut.json"), JSON.stringify({ version: 1, id: "c01", start: 1, end: 3, censor: [] }));
+ assert.equal((await presentPayload(p, { canUncensor: false })).slides.find((s) => s.id === "c01").censored, null, "a segment cut without the boxes");
+ await writeFile(path.join(segs, "c01.cut.json"), JSON.stringify({ version: 1, id: "c01", start: 1, end: 3, censor: [{ box: [0.1, 0.1, 0.2, 0.2], style: "black" }] }));
+ const built = (await presentPayload(p, { canUncensor: false })).slides.find((s) => s.id === "c01");
+ assert.equal(typeof built.censored.segment, "number");
+ assert.equal(built.censored.seconds, 2);
+ assert.equal(built.media, null);
+});
diff --git a/umtool/lib/report/promoCli.mjs b/umtool/lib/report/promoCli.mjs
@@ -0,0 +1,143 @@
+// `umtool promo` (lane clip-kit, slice D): the channel promo's two jobs that are not a key to type -- its portrait,
+// grabbed from a clip at a second (lib/report/stillGrab.mjs, into shots/), and the card drawn in both sizes to look
+// at before a render (report-to-video promo-card.mjs). The promo itself is look data: `umtool look <p> promo='{…}'`.
+//
+// umtool promo <project> [--portrait-from <clip>@<second>] [--box x,y,w,h] [--draw] [--take <t>] [--json]
+//
+// Plain ESM: the CLI runs it under bare node; the app's route (/api/report/promo-card) calls the same functions.
+import path from "node:path";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { kindMakesTakes } from "../projects/kinds.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { manifestToken, updateRender } from "./manifest.mjs";
+import { StillRefused, grabStill } from "./stillGrab.mjs";
+import { ensureWriteDir } from "./storage.mjs";
+
+export const PROMO_USAGE = [
+ "usage: umtool promo <project> [--portrait-from <clip>@<second>] [--box x,y,w,h] [--draw] [--take <t>] [--json]",
+ "",
+ "The channel promo (render.promo: the streamer's name, page, code and portrait; set with `umtool look <p>",
+ "promo='{\"name\":[\"…\",\"…\"],\"url\":\"https://…\"}'`). --portrait-from grabs the frame of a clip at a source second",
+ "into shots/ and makes it the card's portrait (--box: the part the circle is cut from, fractions of the frame).",
+ "--draw draws the card 9:16 and 16:9 into out/promo/ (the take's look with --take) and prints where.",
+].join("\n");
+
+class CliError extends Error {}
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** `<clip>@<second>`, read. */
+export function parsePortraitFrom(text) {
+ const m = /^([A-Za-z0-9][A-Za-z0-9._~-]*)@(\d+(?:\.\d+)?)$/.exec(String(text ?? "").trim());
+ if (!m) throw new CliError(`--portrait-from ${text}: <clip>@<source second> (e.g. w01@10650.2)`);
+ return { clip: m[1], at: Number(m[2]) };
+}
+
+/** `x,y,w,h` (fractions), read. */
+export function parseBox(text) {
+ const b = String(text ?? "").split(",").map((s) => Number(s.trim()));
+ if (b.length !== 4 || !b.every((n) => Number.isFinite(n) && n >= 0 && n <= 1) || b[2] <= 0 || b[3] <= 0 || b[0] + b[2] > 1.001 || b[1] + b[3] > 1.001) {
+ throw new CliError(`--box ${text}: x,y,w,h as fractions of the frame, inside it`);
+ }
+ return b;
+}
+
+/**
+ * The portrait grabbed and written into render.promo (the promo must be set: it is the streamer's, not a guess).
+ * Returns the promo as written.
+ *
+ * @param {{ dir: string, id: string }} project
+ * @param {{ clip: string, at: number, box?: number[] | null }} o
+ */
+export async function setPromoPortrait(project, { clip, at, box = null }) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ const promo = manifest.render?.promo;
+ if (!isObj(promo)) throw new CliError(`${project.id} sets no channel promo yet: umtool look ${project.id} promo='{"name":"…","url":"https://…"}' first`);
+ let still;
+ try {
+ // The tallest window that holds the second, when the project fetches taller ones (render.tallWindows).
+ still = await grabStill(project, manifest, clip, at, { preferTall: manifest.render?.tallWindows === true });
+ } catch (e) {
+ if (e instanceof StillRefused) throw new CliError(e.message);
+ throw e;
+ }
+ const next = { ...promo, portrait: { file: still.rel, ...(box ? { box } : {}), from: { clip, at: still.at } } };
+ const r = await updateRender(project.dir, { promo: next }, { token: await manifestToken(project.dir) });
+ return { promo: r.look.promo, still };
+}
+
+/**
+ * Both cards drawn (9:16 and 16:9) from the project's look, or a take's: `[{width, height, file, key, cached}]`.
+ *
+ * @param {{ dir: string, id: string }} project
+ * @param {{ take?: string | null }} [o]
+ */
+export async function drawPromoCards(project, { take = null } = {}) {
+ let manifest = await readManifest(project.dir);
+ if (take) manifest = (await (await import("./takeManifest.mjs")).resolveTakeManifest(project.dir, take)).manifest;
+ const promo = manifest?.render?.promo;
+ if (!isObj(promo)) throw new CliError(`${project.id}${take ? ` (take ${take})` : ""} sets no channel promo (render.promo)`);
+ const { promoErrors, renderPromoCard } = await import("umtool-report-to-video/promo-card");
+ const errors = promoErrors(promo);
+ if (errors.length) throw new CliError(errors.join("; "));
+ // Through ensureWriteDir: a tiered project's out/ stays the link to the media root.
+ const dir = await ensureWriteDir(path.join(/* turbopackIgnore: true */ project.dir, "out", "promo"));
+ const out = [];
+ for (const [width, height] of [[1080, 1920], [1920, 1080]]) {
+ const r = await renderPromoCard({ promo: { ...promo, captions: promo.captions !== false }, render: manifest.render, width, height, dir, manifestDir: project.dir });
+ out.push({ width, height, file: r.file, key: r.key, cached: r.cached });
+ }
+ return out;
+}
+
+/**
+ * `umtool promo …`
+ * @param {string[]} args
+ * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void }} [o]
+ */
+export async function promoCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) {
+ try {
+ const flags = {};
+ const pos = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (["--portrait-from", "--box", "--take"].includes(a)) {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ flags[a] = args[++i];
+ } else if (["--draw", "--json", "--help"].includes(a)) flags[a] = true;
+ else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`);
+ else pos.push(a);
+ }
+ if (flags["--help"] || !pos.length) {
+ log(PROMO_USAGE);
+ return flags["--help"] ? 0 : 2;
+ }
+ const r = await resolveProject(pos[0], reportsRoot);
+ if (r.ambiguous) throw new CliError(`"${pos[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${pos[0]}"`);
+ if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`);
+ if (!flags["--portrait-from"] && !flags["--draw"]) throw new CliError("--portrait-from <clip>@<second> and/or --draw: what to do");
+ if (flags["--box"] && !flags["--portrait-from"]) throw new CliError("--box goes with --portrait-from");
+ const result = {};
+ if (flags["--portrait-from"]) {
+ const { clip, at } = parsePortraitFrom(flags["--portrait-from"]);
+ const box = flags["--box"] ? parseBox(flags["--box"]) : null;
+ const set = await setPromoPortrait(r.project, { clip, at, box });
+ result.portrait = set.promo.portrait;
+ if (!flags["--json"]) log(`portrait: ${set.still.rel} (${clip} at ${set.still.at} s)${box ? ` cut from [${box.join(", ")}]` : ""}`);
+ }
+ if (flags["--draw"]) {
+ const take = typeof flags["--take"] === "string" ? flags["--take"] : null;
+ result.cards = await drawPromoCards(r.project, { take });
+ if (!flags["--json"]) for (const c of result.cards) log(`${c.width}x${c.height}: ${c.file}${c.cached ? " (drawn before)" : ""}`);
+ }
+ if (flags["--json"]) log(JSON.stringify(result, null, 2));
+ return 0;
+ } catch (e) {
+ if (e instanceof CliError || e?.name === "RenderRefused") {
+ err(`umtool promo: ${e instanceof Error ? e.message : e}`);
+ return 2;
+ }
+ throw e;
+ }
+}
diff --git a/umtool/lib/report/shortsBatch.mjs b/umtool/lib/report/shortsBatch.mjs
@@ -0,0 +1,188 @@
+// A BATCH OF SHORTS (lane clip-kit, slice A): the clipping job as one command. `umtool shorts <project> --take <t>
+// (--items a,b | --all) --formats vertical,landscape` builds every listed clip in every format through the ONE
+// builder behind `umtool vertical` (lib/report/verticalCli.mjs buildShort), into one folder of the project,
+// `shorts-<take>/` -- a deliverable (storage.mjs isDeliverableName), never `shorts/`, which the clip editor's Make a
+// short owns and whose every mp4 the Deliver tab reads as `<clipId>.mp4`.
+//
+// shorts-<take>/<name>.<format>.mp4 each with its record (<name>.<format>.json, the vertical-short record)
+// shorts-<take>/batch.json the batch: what was asked, each clip's name, files, notes and snapshot
+//
+// NAMES are stable: a clip's `name` when it pins one, else its title's slug, else its id. A name another clip of the
+// folder already holds gets `-<clipId>` (two clips of one cut often share a title). Once a clip has a name in the
+// folder's batch.json it keeps it on every later run, whatever its title becomes or whatever else the batch holds.
+//
+// THE SNAPSHOT: each clip's PROJECT keys (vertical-plan.mjs PROJECT_KEYS -- set after the take was made, read over
+// it) as the batch read them. `--again` rebuilds from the record: the same items, formats and knobs, each clip
+// framed by its snapshot, so a later edit of the project does not silently change a rebuild.
+//
+// PURE: no fs. The command is lib/report/shortsCli.mjs.
+
+/** The formats a batch builds, each the builder's options and its length note's cap (s; a note, never a refusal). */
+export const BATCH_FORMATS = Object.freeze({
+ vertical: Object.freeze({ landscape: false, desktop: false, maxSeconds: 180 }),
+ // 16:9 with minimal chrome (slice C, vertical.mjs desktopGeometry): the X clip.
+ desktop: Object.freeze({ landscape: false, desktop: true, maxSeconds: 140 }),
+ landscape: Object.freeze({ landscape: true, desktop: false, maxSeconds: 140 }),
+});
+
+/**
+ * The knobs one format is built with: a short keeps its code at the top (tr, unless tl) -- a bottom corner asked for
+ * the desktop clips is the short's default corner. Returns `{knobs, note}`.
+ */
+export function knobsForFormat(knobs, format) {
+ // The take's own 16:9 look reads none of the per-clip builder's knobs (its look is the take's): none handed on.
+ if (format === "landscape") {
+ const asked = Object.keys(knobs ?? {}).filter((k) => !["maxSeconds"].includes(k));
+ return { knobs: {}, note: asked.length ? `the take's own 16:9 look: ${asked.join(", ")} ${asked.length > 1 ? "are" : "is"} not its (left out)` : null };
+ }
+ const qr = knobs?.qr;
+ if (format === "vertical" && qr && typeof qr === "object" && !["tr", "tl"].includes(qr.corner)) {
+ return { knobs: { ...knobs, qr: true }, note: `its code at the top right (a short's captions run along its foot; ${qr.corner} is a desktop clip's corner)` };
+ }
+ return { knobs: { ...(knobs ?? {}) }, note: null };
+}
+export const FORMAT_NAMES = Object.freeze(Object.keys(BATCH_FORMATS));
+
+/** The folder a take's batch lands in. */
+export const BATCH_PREFIX = "shorts-";
+export const batchDirName = (take) => `${BATCH_PREFIX}${take}`;
+export const BATCH_FILE = "batch.json";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** A title as a file name: lower case, letters and digits, words joined by "-" (apostrophes dropped), ≤ 60. */
+export function slugOf(text) {
+ const s = String(text ?? "")
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .toLowerCase()
+ .replace(/['’‘`]/g, "")
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+ return s.slice(0, 60).replace(/-+$/, "");
+}
+
+/** A clip's own name, a pinned `name` or its title's slug or its id: what its files are called before a tiebreak. */
+export function baseNameOf(entry) {
+ const pinned = typeof entry?.name === "string" ? slugOf(entry.name) : "";
+ if (pinned) return pinned;
+ const title = typeof entry?.title === "string" ? slugOf(entry.title) : "";
+ return title || slugOf(entry?.id) || "clip";
+}
+
+/**
+ * Each clip's name in the folder: `prior` ({<clip id>: name}, the folder's batch.json) kept as it is; a new clip its
+ * base name, or `<base>-<id>` when another clip holds that already. In the order given; returns {<clip id>: name}.
+ *
+ * @param {Array<{ id: string, name?: string, title?: string }>} entries
+ * @param {Record<string, string>} [prior]
+ */
+export function assignNames(entries, prior = {}) {
+ const names = { ...(isObj(prior) ? prior : {}) };
+ const taken = new Map(Object.entries(names).map(([id, n]) => [n, id]));
+ for (const e of entries) {
+ if (typeof names[e.id] === "string") continue;
+ const base = baseNameOf(e);
+ let n = base;
+ if (taken.has(n) && taken.get(n) !== e.id) n = `${base}-${slugOf(e.id) || "clip"}`;
+ for (let k = 2; taken.has(n) && taken.get(n) !== e.id; k += 1) n = `${base}-${slugOf(e.id)}-${k}`;
+ names[e.id] = n;
+ taken.set(n, e.id);
+ }
+ return names;
+}
+
+/** A name read back from a record: a file name of the folder, nothing else (no separator, no dot path). */
+export const safeName = (n) => typeof n === "string" && /^[a-z0-9][a-z0-9-]{0,80}$/.test(n);
+
+/** `--formats a,b` read: known names, each once, in the order given. Throws naming an unknown one. */
+export function parseFormats(text) {
+ const list = String(text ?? "vertical").split(",").map((s) => s.trim()).filter(Boolean);
+ const bad = list.filter((f) => !FORMAT_NAMES.includes(f));
+ if (bad.length) throw new Error(`--formats ${bad.join(", ")}: not a format (${FORMAT_NAMES.join(", ")})`);
+ if (!list.length) throw new Error(`--formats: one or more of ${FORMAT_NAMES.join(", ")}`);
+ return [...new Set(list)];
+}
+
+/** The keys of a clip a batch snapshots (vertical-plan.mjs PROJECT_KEYS): each set one, null for one it lacks. */
+export function snapshotOf(entry, keys) {
+ /** @type {Record<string, unknown>} */
+ const out = {};
+ for (const k of keys) out[k] = entry?.[k] === undefined ? null : entry[k];
+ return out;
+}
+
+/** A file set aside before it is made again: `<name>.<format>.<stamp>.mp4`. */
+export function asideName(file, now = new Date()) {
+ const p = (n) => String(n).padStart(2, "0");
+ const stamp = `${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`;
+ return file.replace(/\.mp4$/, `.${stamp}.mp4`);
+}
+
+/**
+ * What `--again` builds from a record: each clip of it, in its order, with the formats it has a file (or an error)
+ * in, the knobs it was last built with and its snapshot. `[{id, formats, knobs, snapshot}]`.
+ */
+export function againOf(record) {
+ if (!isObj(record) || record.kind !== "shorts-batch" || !Array.isArray(record.clips)) throw new Error("not a batch record (batch.json, kind shorts-batch)");
+ return record.clips
+ .filter((c) => isObj(c) && typeof c.id === "string")
+ .map((c) => ({
+ id: c.id,
+ formats: FORMAT_NAMES.filter((f) => (isObj(c.files) && c.files[f]) || (isObj(c.errors) && c.errors[f])),
+ knobs: isObj(c.knobs) ? c.knobs : {},
+ snapshot: isObj(c.snapshot) ? c.snapshot : null,
+ look: isObj(c.look) ? c.look : null,
+ }))
+ .filter((c) => c.formats.length);
+}
+
+/**
+ * A clip's row after one format's build: `prior` (its row, or null) with this run's name and title, and the format's
+ * file, length and notes -- or its error, the file dropped when it is no longer there (`exists`). The knobs and the
+ * snapshot are the last SUCCESSFUL build's. Pure.
+ *
+ * @param {Record<string, any> | null} prior
+ * @param {{ id: string, name: string, title: string | null, format: string, knobs: Record<string, any>, snapshot: Record<string, any>,
+ * file?: string, seconds?: number | null, notes?: string[], error?: string, exists?: boolean, look?: Record<string, any> | null }} r
+ */
+export function rowAfter(prior, r) {
+ const row = { id: r.id, name: r.name, title: r.title, knobs: {}, snapshot: null, files: {}, seconds: {}, notes: {}, errors: {}, ...(isObj(prior) ? prior : {}) };
+ row.name = r.name;
+ row.title = r.title;
+ row.files = { ...row.files };
+ row.seconds = { ...row.seconds };
+ row.notes = isObj(row.notes) ? { ...row.notes } : {};
+ row.errors = { ...row.errors };
+ if (r.error) {
+ row.errors[r.format] = r.error;
+ if (!r.exists) {
+ delete row.files[r.format];
+ delete row.seconds[r.format];
+ delete row.notes[r.format];
+ }
+ return row;
+ }
+ delete row.errors[r.format];
+ row.files[r.format] = r.file;
+ row.seconds[r.format] = r.seconds ?? null;
+ row.notes[r.format] = r.notes ?? [];
+ row.knobs = r.knobs;
+ row.snapshot = r.snapshot;
+ // The look it was built with (verticalCli.mjs LOOK_SNAPSHOT_KEYS): what `--again` builds from.
+ if (isObj(r.look)) row.look = r.look;
+ return row;
+}
+
+/** The clips a batch builds: `items` (each must be a clip of the take), else with `all` every clip of the take. */
+export function batchItems(timeline, { items = null, all = false } = {}) {
+ const clips = (timeline ?? []).filter((e) => e?.type === "clip" && typeof e.id === "string");
+ if (items?.length) {
+ const byId = new Map(clips.map((e) => [e.id, e]));
+ const missing = items.filter((id) => !byId.has(id));
+ if (missing.length) throw new Error(`${missing.join(", ")}: not ${missing.length > 1 ? "clips" : "a clip"} of the take`);
+ return [...new Set(items)].map((id) => byId.get(id));
+ }
+ if (all) return clips;
+ throw new Error("--items <id>,… or --all: which clips");
+}
diff --git a/umtool/lib/report/shortsBatch.test.mjs b/umtool/lib/report/shortsBatch.test.mjs
@@ -0,0 +1,332 @@
+// A batch of shorts (lane clip-kit, slice A): names, formats, the snapshot, and `umtool shorts` driving the one
+// builder (a stand-in here: nothing is rendered) into shorts-<take>/ with its batch.json.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+import { againOf, asideName, assignNames, baseNameOf, batchItems, parseFormats, rowAfter, slugOf, snapshotOf } from "./shortsBatch.mjs";
+import { shortsCommand } from "./shortsCli.mjs";
+import { PROJECT_KEYS, planVerticalCut, withOverrides } from "umtool-report-to-video/vertical-plan";
+
+test("a title's slug: lower case, apostrophes dropped, words joined", () => {
+ assert.equal(slugOf("A clip about Tom's toast"), "a-clip-about-toms-toast");
+ assert.equal(slugOf(" Rye or sourdough?! "), "rye-or-sourdough");
+ assert.equal(slugOf("Café — déjà vu"), "cafe-deja-vu");
+ assert.equal(slugOf("x".repeat(80)).length, 60);
+ assert.equal(baseNameOf({ id: "w01", title: "A great break", name: "Pinned Name" }), "pinned-name");
+ assert.equal(baseNameOf({ id: "w01" }), "w01");
+});
+
+test("names: two clips sharing a title, the second gets -<id>; a name once given is kept", () => {
+ const clips = [
+ { id: "m01", title: "A clip about Tom's toast" },
+ { id: "w01", title: "A clip about Tom's toast" },
+ { id: "w05", title: "Rye loaf" },
+ ];
+ assert.deepEqual(assignNames(clips), {
+ m01: "a-clip-about-toms-toast",
+ w01: "a-clip-about-toms-toast-w01",
+ w05: "rye-loaf",
+ });
+ // A later run that holds only w01 keeps its name; a retitled clip keeps its name too.
+ const prior = { w01: "a-clip-about-toms-toast-w01", w05: "rye-loaf" };
+ assert.deepEqual(assignNames([{ id: "w01", title: "x" }, { id: "w05", title: "Retitled" }], prior), prior);
+ // A new clip whose slug a prior clip holds takes the tiebreak.
+ assert.equal(assignNames([{ id: "m05", title: "Rye loaf" }], prior).m05, "rye-loaf-m05");
+});
+
+test("formats, items and the record's again", () => {
+ assert.deepEqual(parseFormats("vertical,landscape,vertical"), ["vertical", "landscape"]);
+ assert.deepEqual(parseFormats(undefined), ["vertical"]);
+ assert.throws(() => parseFormats("square"), /square: not a format/);
+ const tl = [{ type: "clip", id: "a" }, { type: "post", id: "p" }, { type: "clip", id: "b" }];
+ assert.deepEqual(batchItems(tl, { all: true }).map((e) => e.id), ["a", "b"]);
+ assert.deepEqual(batchItems(tl, { items: ["b", "a", "b"] }).map((e) => e.id), ["b", "a"]);
+ assert.throws(() => batchItems(tl, { items: ["p"] }), /p: not a clip of the take/);
+ assert.throws(() => batchItems(tl, {}), /--items <id>,… or --all/);
+ const again = againOf({ kind: "shorts-batch", clips: [
+ { id: "a", knobs: { clip: "framed" }, snapshot: { vertical: null, side: null }, files: { landscape: "a.landscape.mp4" }, errors: { vertical: "failed" } },
+ { id: "b", files: {}, errors: {} },
+ ] });
+ assert.deepEqual(again, [{ id: "a", formats: ["vertical", "landscape"], knobs: { clip: "framed" }, snapshot: { vertical: null, side: null }, look: null }]);
+ // A row: a success records the file, the knobs and the snapshot; a failure keeps a file still there, drops one gone.
+ const ok = rowAfter(null, { id: "a", name: "n", title: "T", format: "vertical", knobs: { clip: "framed" }, snapshot: { vertical: null, side: null }, file: "n.vertical.mp4", seconds: 9, notes: ["x"] });
+ assert.deepEqual(ok, { id: "a", name: "n", title: "T", knobs: { clip: "framed" }, snapshot: { vertical: null, side: null }, files: { vertical: "n.vertical.mp4" }, seconds: { vertical: 9 }, notes: { vertical: ["x"] }, errors: {} });
+ const refused = rowAfter(ok, { id: "a", name: "n", title: "T", format: "vertical", knobs: {}, snapshot: {}, error: "is there", exists: true });
+ assert.deepEqual([refused.files, refused.errors, refused.knobs], [{ vertical: "n.vertical.mp4" }, { vertical: "is there" }, { clip: "framed" }]);
+ assert.deepEqual(rowAfter(ok, { id: "a", name: "n", title: "T", format: "vertical", knobs: {}, snapshot: {}, error: "crashed", exists: false }).files, {});
+ assert.throws(() => againOf({ kind: "vertical-short" }), /not a batch record/);
+ assert.match(asideName("/x/a.vertical.mp4", new Date(2026, 10, 13, 9, 5, 7)), /\/x\/a\.vertical\.20261113-090507\.mp4$/);
+});
+
+test("the snapshot: the project keys a clip has, null for one it lacks; laid over the project's entries", () => {
+ const e = { type: "clip", id: "a", vertical: { crop: [0.6, 0, 0.3164, 1] } };
+ assert.deepEqual(snapshotOf(e, PROJECT_KEYS), { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null, qr: null, promo: null, zooms: null, coldOpen: null, censor: null });
+ const project = [{ type: "clip", id: "a", vertical: { crop: [0.1, 0, 0.3164, 1] }, side: { item: "p", from: 0, to: 3 } }];
+ const laid = withOverrides(project, { a: { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null, title: "ignored" } });
+ assert.deepEqual(laid[0], { type: "clip", id: "a", vertical: { crop: [0.6, 0, 0.3164, 1] } });
+ // The plan reads the snapshot's framing over the take's own entry.
+ const plan = planVerticalCut({ timeline: [{ type: "clip", id: "a", start: 1, end: 5 }], items: ["a"], project: laid });
+ assert.deepEqual(plan.timeline[0].vertical, { crop: [0.6, 0, 0.3164, 1] });
+ // No snapshot: the entries as they are (byte for byte the plan it always made).
+ assert.equal(withOverrides(project, null), project);
+});
+
+async function world() {
+ const root = await mkdtemp(path.join(tmpdir(), "shortsbatch-"));
+ const reportsRoot = path.join(root, "reports");
+ const dir = path.join(reportsRoot, "proj");
+ await mkdir(path.join(dir, "takes", "kit"), { recursive: true });
+ const timeline = [
+ { type: "clip", id: "m01", video: "v", start: 1, end: 5, title: "Tom's toast" },
+ { type: "clip", id: "w01", video: "v", start: 0, end: 8, title: "Tom's toast", vertical: { crop: [0.6, 0, 0.3164, 1] } },
+ ];
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "cut", title: "Cut", render: { fps: 30 }, timeline }));
+ await writeFile(path.join(dir, "takes", "kit", "take.json"), JSON.stringify({ id: "kit", group: "takes", order: 1, label: "kit", kind: "reference", preview: "preview.mp4", patch: null, draft: true, window: "full", style: null }));
+ return { root, reportsRoot, dir };
+}
+
+/** A builder that writes a file where it is asked and records what it was asked. */
+function standIn(calls, { fail = () => false } = {}) {
+ return async (o) => {
+ calls.push(o);
+ if (fail(o)) throw new Error(`stand-in refused ${o.items[0]}`);
+ await mkdir(path.dirname(o.out), { recursive: true });
+ await writeFile(o.out, `mp4 of ${o.items[0]}`);
+ return { record: { seconds: 150, notes: o.knobs.maxSeconds < 150 ? [`this short runs 150.0 s, over its ${o.knobs.maxSeconds} s`] : [], out: o.out } };
+ };
+}
+
+const sink = () => {
+ const logs = [];
+ const errs = [];
+ return { logs, errs, log: (s) => logs.push(s), err: (s) => errs.push(s) };
+};
+
+test("umtool shorts: each clip in each format into shorts-<take>/, named, recorded; a file there kept unless --replace", async () => {
+ const w = await world();
+ try {
+ const calls = [];
+ const o = sink();
+ const code = await shortsCommand(["proj", "--take", "kit", "--all", "--formats", "vertical,landscape", "--clip", "framed", "--hook", "title"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: standIn(calls) });
+ assert.equal(code, 0, o.errs.join("\n"));
+ const folder = path.join(w.dir, "shorts-kit");
+ const files = (await readdir(folder)).sort();
+ assert.deepEqual(files, ["batch.json", "toms-toast-w01.landscape.mp4", "toms-toast-w01.vertical.mp4", "toms-toast.landscape.mp4", "toms-toast.vertical.mp4"]);
+ // The builder was asked one clip at a time, with the flags' knobs and each format's cap.
+ // The take's own 16:9 look takes none of the per-clip builder's knobs (each format only the knobs it reads).
+ assert.deepEqual(calls.map((c) => [c.items[0], c.landscape, c.knobs.maxSeconds, c.knobs.clip]), [["m01", false, 180, "framed"], ["m01", true, 140, undefined], ["w01", false, 180, "framed"], ["w01", true, 140, undefined]]);
+ assert.deepEqual(calls[2].overrides, { w01: { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null, qr: null, promo: null, zooms: null, coldOpen: null, censor: null } });
+ const rec = JSON.parse(await readFile(path.join(folder, "batch.json"), "utf8"));
+ assert.equal(rec.kind, "shorts-batch");
+ assert.deepEqual(rec.last.argv, ["shorts", "proj", "--take", "kit", "--items", "m01,w01", "--formats", "vertical,landscape"]);
+ assert.deepEqual(rec.clips.map((c) => [c.id, c.name, c.files.vertical, c.knobs.clip]), [["m01", "toms-toast", "toms-toast.vertical.mp4", "framed"], ["w01", "toms-toast-w01", "toms-toast-w01.vertical.mp4", "framed"]]);
+ assert.deepEqual(rec.clips[0].notes, { vertical: [], landscape: ["the take's own 16:9 look: clip, hook are not its (left out)", "this short runs 150.0 s, over its 140 s"] });
+
+ // Again without --replace: refused per file, recorded, exit 1; the files are untouched.
+ const o2 = sink();
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01"], { reportsRoot: w.reportsRoot, log: o2.log, err: o2.err, build: standIn([]) }), 1);
+ assert.match(o2.errs.join("\n"), /toms-toast-w01\.vertical\.mp4 is there — --replace/);
+ const rec2 = JSON.parse(await readFile(path.join(folder, "batch.json"), "utf8"));
+ assert.deepEqual(rec2.clips.map((c) => c.id), ["m01", "w01"], "a clip of the folder this run did not build keeps its row");
+ assert.equal(rec2.clips[1].knobs.clip, "framed", "a refused run keeps the knobs the file was made with");
+ assert.equal(rec2.clips[1].files.landscape, "toms-toast-w01.landscape.mp4");
+
+ // --again: the record's clips, formats and knobs, framed by its snapshot, the old files set aside.
+ await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "cut", render: { fps: 30 }, timeline: [{ type: "clip", id: "m01", video: "v", start: 1, end: 5, title: "Renamed" }, { type: "clip", id: "w01", video: "v", start: 0, end: 8, vertical: { crop: [0, 0, 0.3164, 1] } }] }));
+ const calls3 = [];
+ const o3 = sink();
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--again"], { reportsRoot: w.reportsRoot, log: o3.log, err: o3.err, build: standIn(calls3) }), 0, o3.errs.join("\n"));
+ assert.deepEqual(calls3.map((c) => [c.items[0], c.landscape, c.knobs.clip]), [["m01", false, "framed"], ["m01", true, undefined], ["w01", false, "framed"], ["w01", true, undefined]]);
+ assert.deepEqual(calls3[2].overrides.w01.vertical, { crop: [0.6, 0, 0.3164, 1] }, "the snapshot, not the project's new crop");
+ const after = await readdir(folder);
+ assert.ok(after.includes("toms-toast.vertical.mp4"), "the name kept though the title changed");
+ assert.equal(after.filter((f) => /\.\d{8}-\d{6}\.mp4$/.test(f)).length, 4, "each old file set aside");
+ } finally {
+ await rm(w.root, { recursive: true, force: true });
+ }
+});
+
+test("umtool shorts: a failing clip is recorded and the rest go on; --dry-run writes nothing; refusals say why", async () => {
+ const w = await world();
+ try {
+ const o = sink();
+ const code = await shortsCommand(["proj", "--take", "kit", "--all"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: standIn([], { fail: (x) => x.items[0] === "m01" }) });
+ assert.equal(code, 1);
+ const rec = JSON.parse(await readFile(path.join(w.dir, "shorts-kit", "batch.json"), "utf8"));
+ assert.match(rec.clips[0].errors.vertical, /stand-in refused m01/);
+ assert.deepEqual(rec.clips[0].files, {});
+ assert.deepEqual(rec.clips[1].files, { vertical: "toms-toast-w01.vertical.mp4" });
+
+ await rm(path.join(w.dir, "shorts-kit"), { recursive: true });
+ const d = sink();
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01", "--formats", "landscape", "--dry-run", "--json"], { reportsRoot: w.reportsRoot, log: d.log, err: d.err, build: standIn([]) }), 0);
+ assert.deepEqual(JSON.parse(d.logs.join("\n")).clips[0].files, { landscape: "toms-toast.landscape.mp4" }, "alone in a new folder, w01 takes its plain name");
+ assert.equal(existsSync(path.join(w.dir, "shorts-kit")), false);
+
+ const say = async (args, re) => {
+ const x = sink();
+ assert.equal(await shortsCommand(args, { reportsRoot: w.reportsRoot, log: x.log, err: x.err, build: standIn([]) }), 2, args.join(" "));
+ assert.match(x.errs.join("\n"), re);
+ };
+ await say(["proj", "--all"], /--take <t>/);
+ await say(["proj", "--take", "kit"], /--items <id>,… or --all/);
+ await say(["proj", "--take", "kit", "--items", "nope"], /nope: not a clip of the take/);
+ await say(["proj", "--take", "kit", "--all", "--formats", "square"], /square: not a format/);
+ await say(["proj", "--take", "kit", "--again"], /batch\.json is not there/);
+ await say(["proj", "--take", "kit", "--all", "--max-vertical", "2"], /--max-vertical is 5 to 600/);
+ } finally {
+ await rm(w.root, { recursive: true, force: true });
+ }
+});
+
+test("umtool shorts: --again builds from the look it recorded; a failed rebuild puts the old file back; a hand-edited name is not trusted", async () => {
+ const w = await world();
+ try {
+ const look = { palette: { bg: "#101010" }, promo: { name: "Example Channel", url: "https://example.org/c" } };
+ const withLook = (calls, o2 = {}) => async (o) => {
+ calls.push(o);
+ if (o2.fail) throw new Error("the build failed");
+ await mkdir(path.dirname(o.out), { recursive: true });
+ await writeFile(o.out, `mp4 of ${o.items[0]} ${calls.length}`);
+ return { record: { seconds: 9, notes: [], out: o.out, look } };
+ };
+ const o = sink();
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01", "--formats", "vertical,landscape", "--qr-corner", "br"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: withLook([]) }), 0, o.errs.join("\n"));
+ const folder = path.join(w.dir, "shorts-kit");
+ const rec = JSON.parse(await readFile(path.join(folder, "batch.json"), "utf8"));
+ assert.deepEqual(rec.clips[0].look, look);
+ assert.match(rec.clips[0].notes.vertical[0], /code at the top right/);
+ // --again: the recorded look handed to the builder.
+ const calls = [];
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--again"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: withLook(calls) }), 0);
+ assert.deepEqual(calls.map((c) => c.look), [look, look]);
+ // A rebuild that fails: the file it replaced is back, its contents as they were.
+ const file = path.join(folder, "toms-toast.vertical.mp4");
+ const before = await readFile(file, "utf8");
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01", "--replace"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: withLook([], { fail: true }) }), 1);
+ assert.equal(await readFile(file, "utf8"), before);
+ // A name in the record that is not a plain file name of the folder is not used.
+ const hacked = JSON.parse(await readFile(path.join(folder, "batch.json"), "utf8"));
+ hacked.clips[0].name = "../../escape";
+ await writeFile(path.join(folder, "batch.json"), JSON.stringify(hacked));
+ const d = sink();
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01", "--dry-run", "--json"], { reportsRoot: w.reportsRoot, log: d.log, err: d.err, build: withLook([]) }), 0);
+ assert.deepEqual(JSON.parse(d.logs.join("\n")).clips[0].files, { vertical: "toms-toast.vertical.mp4" });
+ } finally {
+ await rm(w.root, { recursive: true, force: true });
+ }
+});
+
+import { buildShort } from "./verticalCli.mjs";
+import { linkSharedOut } from "./takeMaker.mjs";
+import { lstat, readlink } from "node:fs/promises";
+
+test("the promo ends a short only on a whole clip, and a reel's outro is not added after it; a take's empty clips-raw becomes the link", async () => {
+ const w = await world();
+ try {
+ const m = JSON.parse(await readFile(path.join(w.dir, "video.manifest.json"), "utf8"));
+ m.render.promo = { name: "Example Channel", url: "https://example.org/c" };
+ m.timeline.push({ type: "post", id: "p1", post: "x/1", platform: "x", author: "A", handle: "a", date: "2026-01-01T00:00:00Z", text: "a post" });
+ await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify(m));
+ const ends = await buildShort({ project: "proj", take: "kit", items: ["m01", "w01"], dryRun: true }, { reportsRoot: w.reportsRoot });
+ assert.equal(ends.dryRun.promo, true);
+ const post = await buildShort({ project: "proj", take: "kit", items: ["w01", "p1"], dryRun: true }, { reportsRoot: w.reportsRoot });
+ assert.equal(post.dryRun.promo, false);
+ assert.match(post.dryRun.notes.join(), /ends on p1, a post: no channel promo/);
+ // An empty real out/clips-raw (a failed build's) is replaced by the link to the project's.
+ await mkdir(path.join(w.dir, "out", "clips-raw"), { recursive: true });
+ await writeFile(path.join(w.dir, "out", "clips-raw", "v_0.00-9.00.mp4"), "x");
+ const takeOut = path.join(w.dir, "takes", "kit", "out");
+ await mkdir(path.join(takeOut, "clips-raw"), { recursive: true });
+ await linkSharedOut(w.dir, takeOut);
+ assert.ok((await lstat(path.join(takeOut, "clips-raw"))).isSymbolicLink());
+ assert.equal(await readlink(path.join(takeOut, "clips-raw")), path.join(w.dir, "out", "clips-raw"));
+ } finally {
+ await rm(w.root, { recursive: true, force: true });
+ }
+});
+
+test("hidden regions reach a short of a RENDERED take (its render frozen): the take's boxes and the project's, added; --again keeps a box added since; a reframe refuses one", async () => {
+ const w = await world();
+ try {
+ const m = JSON.parse(await readFile(path.join(w.dir, "video.manifest.json"), "utf8"));
+ const TAKE_BOX = { video: "v", boxes: [[0, 0, 0.2, 0.2]], style: "black" };
+ // The take as rendered: its own recording box, frozen in its manifest.
+ await writeFile(path.join(w.dir, "takes", "kit", "video.manifest.json"), JSON.stringify({ ...m, render: { ...m.render, censor: [TAKE_BOX] } }));
+ const dry = (o = {}) => buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true, ...o }, { reportsRoot: w.reportsRoot }).then((r) => r.dryRun.hidden);
+ assert.deepEqual(await dry(), { w01: 1 }, "the take's own");
+ // A box on the recording set on the PROJECT since: added, in every format.
+ m.render.censor = [{ video: "v", boxes: [[0.75, 0, 0.25, 1]], style: "black" }];
+ await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify(m));
+ assert.deepEqual(await dry(), { w01: 2 }, "a short");
+ assert.deepEqual(await dry({ desktop: true }), { w01: 2 }, "a desktop clip");
+ assert.deepEqual(await dry({ landscape: true }), { w01: 2 }, "the take's own 16:9 look");
+ // A reframe cuts the take's finished picture, which does not hide it: refused, by clip.
+ await assert.rejects(dry({ reframe: true }), /--reframe cuts take kit's finished picture, which does not hide the regions set since .* on w01 \(2 box\(es\)\)/);
+
+ // A batch, then a box on the clip itself: --again builds with it (the record's snapshot and the clip now, both).
+ const o = sink();
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01", "--formats", "vertical"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: standIn([]) }), 0, o.errs.join("\n"));
+ const m2 = JSON.parse(await readFile(path.join(w.dir, "video.manifest.json"), "utf8"));
+ m2.timeline.find((e) => e.id === "w01").censor = { boxes: [[0.4, 0.4, 0.2, 0.2]], style: "blur" };
+ await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify(m2));
+ const calls = [];
+ assert.equal(await shortsCommand(["proj", "--take", "kit", "--again"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: standIn(calls) }), 0, o.errs.join("\n"));
+ assert.equal(calls.length, 1);
+ assert.deepEqual(await dry({ overrides: calls[0].overrides }), { w01: 3 }, "the take's, the project's recording box and the clip's own, added since the batch");
+ } finally {
+ await rm(w.root, { recursive: true, force: true });
+ }
+});
+
+test("a record's look keeps its fonts by name (the pipeline's) or relative to the project, never this checkout's path; --again resolves them", async () => {
+ const { lookSnapshotOf, lookFromSnapshot } = await import("./verticalCli.mjs");
+ const { MONO_FONT_FILE, MONO_BOLD_FONT_FILE } = await import("umtool-report-to-video/brand");
+ const dir = "/somewhere/reports/proj";
+ const look = lookSnapshotOf({ fontRegular: MONO_FONT_FILE, fontBold: `${dir}/fonts/Own-Bold.ttf`, palette: { bg: "#000000" }, width: 1920 }, { projectDir: dir });
+ assert.deepEqual(look, { fontRegular: "IBMPlexMono-Regular.ttf", fontBold: "fonts/Own-Bold.ttf", palette: { bg: "#000000" } });
+ assert.ok(!JSON.stringify(look).includes(path.dirname(MONO_FONT_FILE)), "no absolute path of this checkout");
+ assert.deepEqual(lookFromSnapshot(look, { projectDir: dir }), { fontRegular: MONO_FONT_FILE, fontBold: `${dir}/fonts/Own-Bold.ttf`, palette: { bg: "#000000" } });
+ assert.equal(lookFromSnapshot({ fontBold: "IBMPlexMono-Bold.ttf" }, { projectDir: dir }).fontBold, MONO_BOLD_FONT_FILE);
+ // A font elsewhere on the machine stays as written (there is no name to give it).
+ assert.equal(lookSnapshotOf({ fontRegular: "/usr/share/fonts/X.ttf" }, { projectDir: dir }).fontRegular, "/usr/share/fonts/X.ttf");
+});
+
+test("a short or a desktop clip of a take with a cold-open teaser and an analysis ending: the clip alone is planned, as without them (per-clip builds have no deck, so no full-frame blackout)", async () => {
+ const w = await world();
+ try {
+ const m = JSON.parse(await readFile(path.join(w.dir, "video.manifest.json"), "utf8"));
+ const plain = await buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true }, { reportsRoot: w.reportsRoot });
+ const plainDesk = await buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true, desktop: true }, { reportsRoot: w.reportsRoot });
+ m.render.chrome = { engine: "hyperframes", layout: "deck", deck: {} };
+ m.timeline = [
+ { type: "teaser", id: "t-open", seconds: 4, lines: ["Coming up"], dip: true },
+ ...m.timeline,
+ { type: "analysis", id: "a-end", seconds: 7, kind: "ending" },
+ ];
+ await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify(m));
+ const withThem = await buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true }, { reportsRoot: w.reportsRoot });
+ const desk = await buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true, desktop: true }, { reportsRoot: w.reportsRoot });
+ assert.deepEqual(withThem.dryRun.items, plain.dryRun.items);
+ assert.deepEqual(withThem.dryRun.pieces, plain.dryRun.pieces);
+ assert.deepEqual(desk.dryRun.items, plainDesk.dryRun.items);
+ assert.deepEqual(withThem.dryRun.items.map((i) => i.type), ["clip"]);
+ } finally {
+ await rm(w.root, { recursive: true, force: true });
+ }
+});
+
+test("the per-clip renders drop the deck (a desktop clip, a bare short): no chrome, so no full-frame blackout; the stacked deck keeps it, over the planned clips alone", async () => {
+ const { desktopRender, verticalRender } = await import("umtool-report-to-video/vertical");
+ const { fullFrameItems } = await import("umtool-report-to-video/full-frame");
+ const render = { width: 1920, height: 1080, fps: 30, chrome: { engine: "hyperframes", layout: "deck", deck: {} } };
+ assert.equal(desktopRender(render).chrome, undefined);
+ assert.equal(verticalRender({ ...render, format: "vertical", vertical: { deck: "bare" } }).chrome, undefined, "a bare short");
+ assert.deepEqual(verticalRender({ ...render, format: "vertical" }).chrome, render.chrome, "the stacked deck keeps it");
+ // Its schedule is the planned clips': no teaser, intro or analysis item among them, so no full-frame item.
+ assert.deepEqual(fullFrameItems({ segments: [{ id: "w01", type: "clip", start: 0, end: 8, duration: 8 }], total: 8, fps: 30, transition: 0.5 }), []);
+});
diff --git a/umtool/lib/report/shortsCli.mjs b/umtool/lib/report/shortsCli.mjs
@@ -0,0 +1,231 @@
+// `umtool shorts` (lane clip-kit, slice A): every listed clip of a take, in every listed format, into the project's
+// `shorts-<take>/`, through the ONE builder behind `umtool vertical` (verticalCli.mjs buildShort). The rules -- the
+// names, the formats, the snapshot -- are lib/report/shortsBatch.mjs's.
+//
+// umtool shorts <project> --take <t> (--items a,b | --all | --again) [--formats vertical,landscape]
+// [--clip full|framed|quote] [--hook title|section|"<copy>"] [--captions l|xl] [--lines 1|2]
+// [--loudness -14] [--max-vertical 180] [--max-landscape 140] [--deck stacked|bare]
+// [--replace] [--dry-run] [--json]
+//
+// One command, one record: each build takes the heavy slot as `umtool vertical` does (another job may run between
+// two clips); a clip that fails is recorded with its error, the rest go on, and the command exits 1 at the end.
+import { existsSync } from "node:fs";
+import { readFile, rename } from "node:fs/promises";
+import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
+import path from "node:path";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { kindMakesTakes } from "../projects/kinds.mjs";
+import { deliverableDir } from "./storage.mjs";
+import { BATCH_FILE, BATCH_FORMATS, FORMAT_NAMES, againOf, asideName, assignNames, batchDirName, batchItems, knobsForFormat, parseFormats, rowAfter, safeName, snapshotOf } from "./shortsBatch.mjs";
+import { CliError, buildShort, isRefusal, knobsOfFlags, promoOptionsOf, takeManifestOf } from "./verticalCli.mjs";
+
+export const SHORTS_USAGE = [
+ "usage: umtool shorts <project> --take <t> (--items <id>,<id>… | --all | --again) [--formats vertical,desktop,landscape]",
+ " [--clip full|framed|quote] [--post card|stack|media] [--side split|overlay]",
+ " [--hook title|section|\"<a line of the cut's own copy>\"] [--captions l|xl] [--lines 1|2]",
+ " [--loudness -14] [--max-vertical 180] [--max-desktop 140] [--max-landscape 140]",
+ " [--deck stacked|bare] [--qr on|off] [--qr-corner tr|tl|br|bl] [--no-promo]",
+ " [--promo-lead 4.5] [--promo-fade 0.7] [--promo-hold 1.5] [--no-cold-open] [--replace] [--dry-run] [--json]",
+ "",
+ "A batch of shorts: each clip (--items, or --all of the take's) in each format -- vertical (1080x1920, the",
+ "`umtool vertical` layouts and flags), desktop (1920x1080, minimal chrome: `umtool vertical --desktop`) and",
+ "landscape (the take's own 16:9 look) -- into the project's",
+ "shorts-<take>/ as <name>.<format>.mp4, each with its record, and batch.json. A clip's name is its own `name`, else",
+ "its title's slug, else its id; one another clip holds already gets -<clip id>; once given, it is kept. A file",
+ "there is not replaced unless --replace (the old one set aside as <name>.<format>.<stamp>.mp4). --again builds the",
+ "folder's batch.json again: its clips, formats and knobs, each clip framed as the record saw it. Over its length",
+ "(--max-vertical 180 s, --max-desktop and --max-landscape 140 s) a short is said so: a note, never a refusal. Each build runs in the",
+ "heavy slot, as `umtool vertical`'s does; a clip that fails is recorded and the rest go on (exit 1 at the end).",
+ "When the take sets a channel promo (render.promo), each vertical and desktop clip ends on its card (--no-promo: not).",
+].join("\n");
+
+const VALUED = new Set(["--take", "--items", "--formats", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max-vertical", "--max-landscape", "--max-desktop", "--deck", "--qr", "--qr-corner", "--promo-lead", "--promo-fade", "--promo-hold"]);
+const BOOL = new Set(["--all", "--again", "--replace", "--dry-run", "--json", "--help", "--no-promo", "--no-cold-open"]);
+
+function parse(args) {
+ /** @type {Record<string, string>} */
+ const flags = {};
+ const positional = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a.startsWith("--")) {
+ if (VALUED.has(a)) {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ flags[a] = args[++i];
+ } else if (BOOL.has(a)) flags[a] = "";
+ else throw new CliError(`unknown flag ${a}`);
+ } else positional.push(a);
+ }
+ return { flags, positional, has: (n) => n in flags };
+}
+
+const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** Write a file through a rename (a reader never sees half of it). */
+const writeJson = (file, doc) => writeFileAtomic(file, JSON.stringify(doc, null, 2) + "\n", "utf8");
+
+/**
+ * `umtool shorts …`
+ * @param {string[]} args everything after `shorts`
+ * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, build?: typeof buildShort }} [opts]
+ * `build` the builder (tests stand one in).
+ * @returns {Promise<number>}
+ */
+export async function shortsCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, build = buildShort } = {}) {
+ try {
+ const p = parse(args);
+ if (p.has("--help") || !p.positional.length) {
+ log(SHORTS_USAGE);
+ return p.has("--help") ? 0 : 2;
+ }
+ const json = p.has("--json");
+ const say = json ? err : log;
+ const take = p.flags["--take"] ?? null;
+ if (!take) throw new CliError("--take <t>: the take whose clips the shorts are cut from");
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`);
+ const r = await resolveProject(p.positional[0], reportsRoot);
+ if (r.ambiguous) throw new CliError(`"${p.positional[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${p.positional[0]}"`);
+ if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`);
+ const dir = r.project.dir;
+ const folder = path.join(dir, batchDirName(take));
+ const prior = await readJson(path.join(folder, BATCH_FILE));
+
+ // What is asked: the flags, or (--again) the folder's record -- each clip with its own formats, knobs and snapshot.
+ /** @type {Array<{ id: string, formats: string[], knobs: Record<string, any>, snapshot: Record<string, any> | null }> | null} */
+ let again = null;
+ const replace = p.has("--replace") || p.has("--again");
+ if (p.has("--again")) {
+ if (!prior) throw new CliError(`--again: ${batchDirName(take)}/${BATCH_FILE} is not there — make the batch first`);
+ try {
+ again = againOf(prior);
+ } catch (e) {
+ throw new CliError(`--again: ${e instanceof Error ? e.message : e}`);
+ }
+ if (!again.length) throw new CliError(`--again: ${batchDirName(take)}/${BATCH_FILE} names no clip with a file`);
+ }
+ let formats;
+ try {
+ formats = parseFormats(p.flags["--formats"] ?? "vertical");
+ } catch (e) {
+ throw new CliError(e instanceof Error ? e.message : String(e));
+ }
+ // The channel promo's flags ride in the knobs a row records (`promo`: false, or its timing).
+ const po = promoOptionsOf(p.flags);
+ const knobs = { ...knobsOfFlags(p.flags), ...(po.promo === false ? { promo: false } : po.promoKnobs ? { promo: po.promoKnobs } : {}), ...(p.has("--no-cold-open") ? { coldOpen: false } : {}) };
+ const takeManifest = await takeManifestOf(dir, take);
+ let entries;
+ try {
+ entries = batchItems(takeManifest.timeline ?? [], { items: again ? again.map((c) => c.id) : p.has("--items") ? p.flags["--items"].split(",").map((s) => s.trim()).filter(Boolean) : null, all: p.has("--all") });
+ } catch (e) {
+ throw new CliError(e instanceof Error ? e.message : String(e));
+ }
+ const projectManifest = await readJson(path.join(dir, "video.manifest.json"));
+ const projectById = new Map((projectManifest?.timeline ?? []).filter((e) => typeof e?.id === "string").map((e) => [e.id, e]));
+ const priorRows = new Map((Array.isArray(prior?.clips) ? prior.clips : []).filter((c) => isObj(c) && typeof c.id === "string").map((c) => [c.id, c]));
+ // A name read back is kept only when it is a plain file name of this folder (a record edited by hand is not trusted).
+ const priorNames = Object.fromEntries([...priorRows.values()].filter((c) => safeName(c.name)).map((c) => [c.id, c.name]));
+ // A clip's name reads its PROJECT entry (a pinned `name`, a title set after the take), over the take's.
+ const names = assignNames(entries.map((e) => ({ ...e, ...(projectById.get(e.id) ?? {}) })), priorNames);
+ const caps = {
+ vertical: p.flags["--max-vertical"] !== undefined ? Number(p.flags["--max-vertical"]) : BATCH_FORMATS.vertical.maxSeconds,
+ landscape: p.flags["--max-landscape"] !== undefined ? Number(p.flags["--max-landscape"]) : BATCH_FORMATS.landscape.maxSeconds,
+ desktop: p.flags["--max-desktop"] !== undefined ? Number(p.flags["--max-desktop"]) : BATCH_FORMATS.desktop.maxSeconds,
+ };
+ for (const [f, n] of Object.entries(caps)) if (!(Number.isFinite(n) && n >= 5 && n <= 600)) throw new CliError(`--max-${f} is 5 to 600 seconds`);
+
+ const { PROJECT_KEYS } = await import("umtool-report-to-video/vertical-plan");
+ const againById = new Map((again ?? []).map((c) => [c.id, c]));
+ const plan = entries.map((e) => {
+ const ag = againById.get(e.id) ?? null;
+ const fs = ag ? ag.formats : formats;
+ return {
+ id: e.id, name: names[e.id], title: projectById.get(e.id)?.title ?? e.title ?? null,
+ knobs: ag ? ag.knobs : knobs,
+ snapshot: ag?.snapshot ?? snapshotOf(projectById.get(e.id) ?? e, PROJECT_KEYS),
+ look: ag?.look ?? null,
+ files: Object.fromEntries(fs.map((f) => [f, `${names[e.id]}.${f}.mp4`])),
+ };
+ });
+ if (p.has("--dry-run")) {
+ const out = { project: r.project.id, take, folder, clips: plan.map((c) => ({ id: c.id, name: c.name, title: c.title, knobs: c.knobs, files: c.files, exists: Object.values(c.files).filter((f) => existsSync(path.join(folder, f))) })) };
+ log(json ? JSON.stringify(out, null, 2) : [`would write into ${folder}`, ...out.clips.map((c) => ` ${c.id} ${Object.values(c.files).join(" ")}${c.exists.length ? ` (there: ${c.exists.join(", ")}${replace ? ", set aside" : " — --replace to make again"})` : ""}`)].join("\n"));
+ return 0;
+ }
+ const outDir = await deliverableDir(dir, batchDirName(take));
+ const started = Date.now();
+ const record = {
+ version: 1, kind: "shorts-batch", project: r.project.id, take,
+ // The last run: what it was asked. Each clip's row says what IT was last built with.
+ last: { argv: ["shorts", r.project.id, "--take", take, ...(again ? ["--again"] : ["--items", entries.map((e) => e.id).join(","), "--formats", formats.join(",")])], caps, madeAt: new Date().toISOString(), buildSeconds: 0 },
+ clips: /** @type {any[]} */ ([...priorRows.values()]),
+ };
+ const put = (row) => {
+ const i = record.clips.findIndex((x) => x.id === row.id);
+ if (i >= 0) record.clips[i] = row;
+ else record.clips.push(row);
+ };
+ let failed = 0;
+ for (const c of plan) {
+ for (const f of Object.keys(c.files)) {
+ const file = path.join(outDir, c.files[f]);
+ const base = { id: c.id, name: c.name, title: c.title, format: f, knobs: c.knobs, snapshot: c.snapshot };
+ let row;
+ let aside = null;
+ try {
+ if (existsSync(file)) {
+ if (!replace) throw new CliError(`${c.files[f]} is there — --replace to make it again (the old one set aside)`);
+ aside = asideName(file);
+ await rename(file, aside);
+ await rename(file.replace(/\.mp4$/, ".json"), aside.replace(/\.mp4$/, ".json")).catch(() => {});
+ }
+ say(`shorts: ${c.id} (${c.name}) ${f} …`);
+ const { promo: promoKnob, coldOpen: coldKnob, ...rest } = c.knobs ?? {};
+ const fk = knobsForFormat(rest, f);
+ const done = await build(
+ {
+ project: r.project.id, take, items: [c.id], knobs: { ...fk.knobs, maxSeconds: caps[f] }, name: "shorts", out: file, landscape: BATCH_FORMATS[f].landscape, desktop: BATCH_FORMATS[f].desktop, overrides: { [c.id]: c.snapshot },
+ ...(promoKnob === false ? { promo: false } : promoKnob && typeof promoKnob === "object" ? { promoKnobs: promoKnob } : {}),
+ ...(coldKnob === false ? { coldOpen: false } : {}),
+ ...(c.look ? { look: c.look } : {}),
+ },
+ { reportsRoot, say },
+ );
+ const rec = "record" in done ? done.record : null;
+ row = rowAfter(record.clips.find((x) => x.id === c.id) ?? null, { ...base, file: c.files[f], seconds: rec?.seconds ?? null, notes: [...(fk.note ? [fk.note] : []), ...(rec?.notes ?? [])], look: rec?.look ?? null });
+ } catch (e) {
+ if (!(e instanceof Error)) throw e;
+ // A rebuild that failed puts the old file back where it was (and its record).
+ if (aside && !existsSync(file) && existsSync(aside)) {
+ await rename(aside, file).catch(() => {});
+ await rename(aside.replace(/\.mp4$/, ".json"), file.replace(/\.mp4$/, ".json")).catch(() => {});
+ }
+ failed += 1;
+ err(`shorts: ${c.id} ${f}: ${e.message}`);
+ row = rowAfter(record.clips.find((x) => x.id === c.id) ?? null, { ...base, error: e.message, exists: existsSync(file) });
+ }
+ put(row);
+ record.last.buildSeconds = Math.round((Date.now() - started) / 1000);
+ await writeJson(path.join(outDir, BATCH_FILE), record);
+ }
+ }
+ if (json) log(JSON.stringify(record, null, 2));
+ else {
+ for (const c of record.clips.filter((x) => entries.some((e) => e.id === x.id))) {
+ for (const [f, ns] of Object.entries(c.notes ?? {})) for (const n of ns) log(`note: ${c.id} ${f}: ${n}`);
+ log(`${c.id} ${Object.values(c.files).join(" ") || "(nothing made)"}`);
+ }
+ log(`wrote ${path.join(outDir, BATCH_FILE)}${failed ? ` — ${failed} failed` : ""}`);
+ }
+ return failed ? 1 : 0;
+ } catch (e) {
+ if (isRefusal(e)) {
+ err(`umtool shorts: ${e.message}`);
+ return 2;
+ }
+ throw e;
+ }
+}
+
+export { FORMAT_NAMES };
diff --git a/umtool/lib/report/stillGrab.mjs b/umtool/lib/report/stillGrab.mjs
@@ -12,7 +12,8 @@ import { execFile } from "node:child_process";
import { mkdir, readdir, rename, rm, stat } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
-import { FFMPEG_BIN } from "umtool-report-to-video/build-video";
+import { FFMPEG_BIN, FFPROBE_BIN } from "umtool-report-to-video/build-video";
+import { censorRegionsOf, stillCensorArgs } from "umtool-report-to-video/clip-censor";
import { resolveInRoots } from "../paths.mjs";
import { clipsOf } from "../projects/report.mjs";
import { windowsFor } from "./serve.mjs";
@@ -43,8 +44,9 @@ export const stillNameOf = (clip, seconds) => `still-${String(clip).replace(/[^A
* @param {Record<string, any>} clip
* @param {number} at
*/
-export async function stillSourceOf(project, clip, at) {
+export async function stillSourceOf(project, clip, at, { preferTall = false, ffprobe = null } = {}) {
const windows = await windowsFor(project, clip);
+ const found = [];
for (const w of windows) {
if (w.piecesOf) continue;
const src = w.excerptOf ? { path: w.excerptOf.path, from: w.excerptOf.from } : { path: w.path, from: w.from };
@@ -53,9 +55,26 @@ export async function stillSourceOf(project, clip, at) {
const abs = resolveInRoots(src.path);
if (!abs) continue;
if (!(await stat(abs).catch(() => null))?.isFile()) continue;
- return { file: abs, offset: Math.max(0, at - src.from) };
+ const hit = { file: abs, offset: Math.max(0, at - src.from) };
+ if (!preferTall) return hit;
+ found.push(hit);
}
- return null;
+ if (!found.length) return null;
+ // The tallest picture of those that hold the second (a project fetching taller windows: render.tallWindows).
+ const heightOf = async (f) => {
+ const { stdout } = await execFileP(ffprobe ?? FFPROBE_BIN, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=height", "-of", "csv=p=0", f]).catch(() => ({ stdout: "0" }));
+ return Number(String(stdout).trim()) || 0;
+ };
+ let best = found[0];
+ let bestH = await heightOf(best.file);
+ for (const f of found.slice(1)) {
+ const h = await heightOf(f.file);
+ if (h > bestH) {
+ best = f;
+ bestH = h;
+ }
+ }
+ return best;
}
/**
@@ -69,12 +88,12 @@ export async function stillSourceOf(project, clip, at) {
* @param {number} at a source second
* @param {{ ffmpeg?: string, name?: string | null }} [opts]
*/
-export async function grabStill(project, manifest, clipId, at, { ffmpeg = FFMPEG_BIN, name = null } = {}) {
+export async function grabStill(project, manifest, clipId, at, { ffmpeg = FFMPEG_BIN, name = null, preferTall = false } = {}) {
const clip = clipsOf(manifest).find((e) => e.id === clipId);
if (!clip) throw new StillRefused(`no clip ${clipId} in ${project.id}`, 404);
const t = Number(at);
if (!Number.isFinite(t) || t < 0) throw new StillRefused("at is a source second, 0 or more");
- const src = await stillSourceOf(project, clip, t);
+ const src = await stillSourceOf(project, clip, t, { preferTall });
if (!src) throw new StillRefused(`no fetched window of ${clip.video} holds ${t.toFixed(2)} s -- fetch ${clipId} first (umtool fetch ${project.id} --clips ${clipId})`, 409);
const file = name ?? stillNameOf(clipId, t);
if (!/^[A-Za-z0-9_.-]{1,120}\.png$/.test(file)) throw new StillRefused(`a still's name is letters, digits, . _ - and .png (got ${file})`);
@@ -84,7 +103,16 @@ export async function grabStill(project, manifest, clipId, at, { ffmpeg = FFMPEG
// Two grabs of one second at once never share a temp file.
const tmp = path.join(dir, `.${file}.part-${process.pid}-${Math.random().toString(36).slice(2, 10)}.png`);
try {
- await execFileP(ffmpeg, ["-v", "error", "-y", "-ss", src.offset.toFixed(3), "-i", src.file, "-frames:v", "1", "-an", tmp], { timeout: 60_000 });
+ // Its hidden regions at that second (report-to-video clip-censor.mjs): hidden in the still, as in every cut.
+ const regions = censorRegionsOf(clip, manifest?.render ?? {}, manifest?.provenance ?? {});
+ let cen = [];
+ if (regions.length) {
+ const { stdout } = await execFileP(FFPROBE_BIN, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", src.file]);
+ const [w, h] = String(stdout).trim().split(",").map(Number);
+ if (!(w > 0 && h > 0)) throw new StillRefused(`${clipId} hides regions of its picture, and its window's size could not be read: no still is grabbed`, 500);
+ cen = stillCensorArgs(regions, t, { width: w, height: h });
+ }
+ await execFileP(ffmpeg, ["-v", "error", "-y", "-ss", src.offset.toFixed(3), "-i", src.file, ...cen, "-frames:v", "1", "-an", tmp], { timeout: 60_000 });
const st = await stat(tmp).catch(() => null);
if (!st?.size) throw new StillRefused(`the window of ${clip.video} has no picture at ${t.toFixed(2)} s (an audio-only fetch?)`, 409);
await rename(tmp, out);
diff --git a/umtool/lib/report/storage.mjs b/umtool/lib/report/storage.mjs
@@ -608,6 +608,8 @@ export const DELIVERABLES_MODES = ["local", "media"];
const CLIPS = "clips";
/** A share batch's directory prefix (lib/report/deliver.mjs's SHARE_PREFIX). */
const SHARE = "share-";
+/** A take's batch of shorts (lib/report/shortsBatch.mjs's BATCH_PREFIX): `shorts-<take>`. */
+const SHORTS = "shorts-";
/** What a cut move leaves beside a deliverable: `<name>.moved-<stamp>` or `<name>.incoming`. */
const LEFTOVER = /^(.+)\.(moved-[^/]*|incoming)$/;
@@ -616,7 +618,7 @@ const LEFTOVER = /^(.+)\.(moved-[^/]*|incoming)$/;
export const isDeliverableName = (name) =>
typeof name === "string" &&
!LEFTOVER.test(name) &&
- (name === CLIPS || (name.startsWith(SHARE) && name.length > SHARE.length && !/[\/\\\0]/.test(name)));
+ (name === CLIPS || ([SHARE, SHORTS].some((x) => name.startsWith(x) && name.length > x.length) && !/[\/\\\0]/.test(name)));
/**
* `storage.deliverables` of a parsed manifest.
@@ -692,7 +694,7 @@ export async function deliverableDir(projectDir, name, opts = {}) {
}
/**
- * Every deliverable a project has, by name: `clips` and each `share-*` that is
+ * Every deliverable a project has, by name: `clips` and each `share-*` (and `shorts-*`) that is
* a directory or a link -- and the name of any whose cut move left only a
* leftover (`clips.moved-<ts>` with no `clips`), so a move finishes it.
* `clips` first, then the batches by name.
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -44,7 +44,7 @@
// pages import the parts they show (the styles, the staleness check).
import { resolvePresetLayers } from "umtool-report-to-video/presets";
import { createHash } from "node:crypto";
-import { link, lstat, mkdir, readFile, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
+import { link, lstat, mkdir, readFile, readdir, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { mergePatch } from "umtool-report-to-video/montage-styles";
@@ -504,7 +504,12 @@ export async function linkSharedOut(projectDir, takeOut) {
const src = path.join(projectDir, "out", name);
const dst = path.join(takeOut, name);
if (!(await stat(src).then((s) => s.isDirectory(), () => false))) continue;
- if (await exists(dst)) continue;
+ if (await exists(dst)) {
+ // An EMPTY real directory (a build that failed before its first fetch made it) holds nothing: the link replaces it.
+ const empty = await lstat(dst).then((st) => st.isDirectory() && !st.isSymbolicLink(), () => false) && (await readdir(dst).catch(() => [null])).length === 0;
+ if (!empty) continue;
+ await rmdir(dst);
+ }
await symlink(src, dst);
linked.push(name);
}
diff --git a/umtool/lib/report/verticalCli.mjs b/umtool/lib/report/verticalCli.mjs
@@ -22,13 +22,47 @@ import { takesDirOf } from "./takes.mjs";
import { readTrailerBeats, reelFileOf } from "./trailerBeats.mjs";
import { resolveOutro } from "umtool-report-to-video/outro";
import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs";
+import { ensureWriteDir } from "./storage.mjs";
+
+/**
+ * The look keys a short is built from that a batch's record keeps (lib/report/shortsBatch.mjs `--again`): what the
+ * render draws a per-clip build with, as the take resolved them then.
+ */
+export const LOOK_SNAPSHOT_KEYS = Object.freeze(["palette", "fontRegular", "fontBold", "fps", "captions", "loudness", "qr", "vertical", "desktop", "promo", "zooms", "tallWindows", "maxHeightSource", "blur", "transition", "transitionStyle", "headerHeight", "footerHeight"]);
+const FONT_KEYS = ["fontRegular", "fontBold"];
+const PIPELINE_FONTS = path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "fonts");
+/**
+ * The snapshot of `render`'s look. Its fonts are kept BY NAME (one of the pipeline's fonts/: its file name) or
+ * relative to the project (`projectDir`), never as an absolute path of this checkout -- a record outlives a move.
+ */
+export function lookSnapshotOf(render, { projectDir = null } = {}) {
+ const out = Object.fromEntries(LOOK_SNAPSHOT_KEYS.filter((k) => render?.[k] !== undefined).map((k) => [k, render[k]]));
+ for (const k of FONT_KEYS) {
+ const v = out[k];
+ if (typeof v !== "string" || !path.isAbsolute(v)) continue;
+ if (path.dirname(v) === PIPELINE_FONTS) out[k] = path.basename(v);
+ else if (projectDir && !path.relative(projectDir, v).startsWith("..")) out[k] = path.relative(projectDir, v);
+ }
+ return out;
+}
+/** A recorded look made usable again: a font by name is the pipeline's, a relative one the project's. */
+export function lookFromSnapshot(look, { projectDir }) {
+ const out = { ...look };
+ for (const k of FONT_KEYS) {
+ const v = out[k];
+ if (typeof v !== "string" || path.isAbsolute(v)) continue;
+ out[k] = !v.includes("/") && existsSync(path.join(/* turbopackIgnore: true */ PIPELINE_FONTS, v)) ? path.join(/* turbopackIgnore: true */ PIPELINE_FONTS, v) : path.join(/* turbopackIgnore: true */ projectDir, v);
+ }
+ return out;
+}
export const VERTICAL_USAGE = [
"usage: umtool vertical <project> --take <t> (--reel <r> | --beats FILE | --items <id>,<id>…)",
" [--clip full|framed|quote] [--post card|stack|media] [--side split|overlay]",
" [--hook title|section|\"<a line of the cut's own copy>\"] [--captions l|xl] [--lines 1|2]",
- " [--loudness -14] [--max 60] [--name N] [--out FILE] [--reframe] [--dry-run] [--json]",
- " [--intro | --no-intro] [--no-outro] [--deck stacked|bare]",
+ " [--loudness -14] [--max 60] [--name N] [--out FILE] [--reframe | --landscape | --desktop] [--dry-run] [--json]",
+ " [--intro | --no-intro] [--no-outro] [--deck stacked|bare] [--qr on|off] [--qr-corner tr|tl]",
+ " [--promo | --no-promo] [--promo-lead 4.5] [--promo-fade 0.7] [--promo-hold 1.5] [--no-cold-open]",
"",
"A vertical short (1080x1920, the take's fps) of a take's items: a reel's beats (promo/<r>-beats.json, as",
"`umtool trailer --reel` reads them), a beats file, or whole items. Built natively: each clip cut again in",
@@ -42,6 +76,9 @@ export const VERTICAL_USAGE = [
"60 s (--max) is said so. A clip's vertical crop and layout and its side post are read from the PROJECT's",
"manifest over the take's. The hook only ever says the cut's own words: a clip's title, its section's title,",
"or a line you give it from the cut's copy.",
+ "--landscape builds the same items in the take's own 16:9 look instead (its header, QR and deck), to compare.",
+ "--desktop builds them 16:9 with minimal chrome (render.desktop): the picture full frame, one thin source line on a",
+ "plate, the words lit along its foot, a code in a corner only with --qr (--qr-corner br|bl|tr|tl); -14 LUFS.",
"--reframe recomposes the take's finished 16:9 master instead (each item's region -- the footage, the post's",
"card and attachment, the deck's date line -- laid out 9:16): nothing is cut again, any finished take.",
"Writes takes/<t>/out/<slug>.<name>.<layout>.vertical.mp4 (--out: that file) and a .json beside it. The build",
@@ -53,14 +90,21 @@ export const VERTICAL_USAGE = [
"--deck stacked (the default for a cut with a deck: render.vertical.deck) keeps the deck in 9:16 -- the rail",
"under the top band, the picture at full width, the captions under it, the instruments in two columns, the",
"source line and its QR above the bottom band; --deck bare is the vertical with no deck, as it first shipped.",
+ "--qr on (or --qr-corner tr|tl) puts a code at the top of the safe area linking the source at the second each",
+ "clip plays from (render.vertical.qr; a clip's own `qr` speaks over it); off by default.",
+ "The channel promo (render.promo: the streamer's portrait, name, page and its code) ends the short's last clip when",
+ "the take sets one: the picture dissolves into the card over the clip's last --promo-lead seconds (its sound on",
+ "under it, the captions over it), then the card holds --promo-hold seconds in silence; --no-promo ends without it.",
+ "A clip with a cold open (its `coldOpen`: a span of its cut, 1-4 s) plays it first, then cuts to its start;",
+ "--no-cold-open plays the clips as cut.",
].join("\n");
-class CliError extends Error {}
+export class CliError extends Error {}
-const VALUED = new Set(["--take", "--reel", "--beats", "--items", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max", "--name", "--out", "--deck"]);
-const BOOL = new Set(["--reframe", "--landscape", "--dry-run", "--json", "--help", "--intro", "--no-intro", "--no-outro"]);
+const VALUED = new Set(["--take", "--reel", "--beats", "--items", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max", "--name", "--out", "--deck", "--qr", "--qr-corner", "--promo-lead", "--promo-hold", "--promo-fade"]);
+const BOOL = new Set(["--reframe", "--landscape", "--desktop", "--promo", "--no-promo", "--no-cold-open", "--dry-run", "--json", "--help", "--intro", "--no-intro", "--no-outro"]);
-function parse(args) {
+export function parse(args) {
/** @type {Record<string, string>} */
const flags = {};
const positional = [];
@@ -93,12 +137,37 @@ export function knobsOfFlags(flags) {
}
if (flags["--loudness"] !== undefined) k.loudness = Number(flags["--loudness"]);
if (flags["--max"] !== undefined) k.maxSeconds = Number(flags["--max"]);
+ // The short's code (clip-kit.mjs): --qr on|off, --qr-corner tr|tl (a corner alone turns it on).
+ if (flags["--qr"] !== undefined || flags["--qr-corner"] !== undefined) {
+ const on = flags["--qr"] === undefined ? true : ["on", "true"].includes(flags["--qr"]) ? true : ["off", "false"].includes(flags["--qr"]) ? false : flags["--qr"];
+ k.qr = on === true && flags["--qr-corner"] !== undefined ? { corner: flags["--qr-corner"] } : on;
+ }
return k;
}
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
/**
+ * The desktop knobs (render.desktop's shape) the flags ask for: their captions, hook, loudness, length and code. A
+ * caption size or corner only a short has is left to the desktop's own default.
+ */
+export function desktopKnobsOf(knobs = {}) {
+ /** @type {Record<string, any>} */
+ const d = {};
+ if (knobs.hook !== undefined) d.hook = knobs.hook;
+ if (isObj(knobs.captions)) {
+ const c = {};
+ if (["m", "l", "xl"].includes(knobs.captions.size)) c.size = knobs.captions.size;
+ if (knobs.captions.lines !== undefined) c.lines = knobs.captions.lines;
+ if (Object.keys(c).length) d.captions = c;
+ }
+ if (knobs.loudness !== undefined) d.loudness = knobs.loudness;
+ if (knobs.maxSeconds !== undefined) d.maxSeconds = knobs.maxSeconds;
+ if (knobs.qr !== undefined) d.qr = knobs.qr;
+ return d;
+}
+
+/**
* A short's 9:16 end card (outro.mjs) -- the archive's link as a QR and the short's sources, each clip's date, channel
* and time from the stacked deck's schedule -- or null: a short that keeps no deck (`--deck bare`, a cut without one)
* ends on the outro card it always did.
@@ -134,14 +203,304 @@ function run(argv, { cwd, log }) {
}
/**
+ * The channel promo the flags ask for (promo-card.mjs): `promo` false (--no-promo) or true (--promo: the cut's, refused
+ * when it sets none), and its timing over the cut's (--promo-lead, --promo-fade, --promo-hold).
+ */
+export function promoOptionsOf(flags) {
+ /** @type {{ promo?: boolean, promoKnobs?: Record<string, number> }} */
+ const o = {};
+ if ("--no-promo" in flags) o.promo = false;
+ else if ("--promo" in flags) o.promo = true;
+ const k = {};
+ for (const [f, key] of [["--promo-lead", "lead"], ["--promo-fade", "fade"], ["--promo-hold", "hold"]]) if (flags[f] !== undefined) k[key] = Number(flags[f]);
+ if (Object.keys(k).length) o.promoKnobs = k;
+ return o;
+}
+
+/** The options `umtool vertical`'s flags ask for (buildShort's), read from its parsed flags. */
+export function shortOptionsOf(p) {
+ return {
+ project: p.positional[0],
+ take: p.flags["--take"] ?? null,
+ reel: p.flags["--reel"] ?? null,
+ beats: p.has("--beats") ? p.flags["--beats"] : null,
+ items: p.has("--items") ? p.flags["--items"].split(",").map((s) => s.trim()).filter(Boolean) : null,
+ knobs: knobsOfFlags(p.flags),
+ name: p.flags["--name"] ?? null,
+ out: p.flags["--out"] ?? null,
+ reframe: p.has("--reframe"),
+ landscape: p.has("--landscape"),
+ desktop: p.has("--desktop"),
+ ...promoOptionsOf(p.flags),
+ ...(p.has("--no-cold-open") ? { coldOpen: false } : {}),
+ dryRun: p.has("--dry-run"),
+ intro: p.has("--intro"),
+ noIntro: p.has("--no-intro"),
+ noOutro: p.has("--no-outro"),
+ };
+}
+
+/**
+ * ONE SHORT, BUILT (the builder behind `umtool vertical` and `umtool shorts`): a take's items -- a reel's beats, a
+ * beats file or a list of items -- natively in a 9:16 layout, recomposed from the master (`reframe`), or in the
+ * take's 16:9 look (`landscape`). Writes the mp4 and its record beside it and returns the record; `dryRun` returns
+ * what it would do instead. Throws a CliError (or the plan's VerticalPlanError) for a refusal.
+ *
+ * `overrides` (`{<clip id>: {<key>: value}}`, a batch's snapshot): laid over the PROJECT's own entries before the
+ * plan reads them, so a rebuild from a record frames each clip as it was then.
+ *
+ * @param {{ project: string, take?: string | null, reel?: string | null, beats?: string | null, items?: string[] | null,
+ * knobs?: Record<string, any>, name?: string | null, out?: string | null, reframe?: boolean, landscape?: boolean,
+ * dryRun?: boolean, intro?: boolean, noIntro?: boolean, noOutro?: boolean, overrides?: Record<string, Record<string, any>> | null,
+ * desktop?: boolean, promo?: boolean, promoKnobs?: Record<string, number>, coldOpen?: boolean, look?: Record<string, any> | null }} o
+ * @param {{ reportsRoot?: string, say?: (s: string) => void }} [ctx]
+ * @returns {Promise<{ dryRun: Record<string, any> } | { record: Record<string, any> }>}
+ */
+export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} } = {}) {
+ const V = await import("umtool-report-to-video/vertical");
+ const P = await import("umtool-report-to-video/vertical-plan");
+ const r = await resolveProject(o.project, reportsRoot);
+ if (r.ambiguous) throw new CliError(`"${o.project}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${o.project}"`);
+ if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`);
+ const dir = r.project.dir;
+ const reel = o.reel ?? null;
+ let take = o.take ?? null;
+ let beats = null;
+ /** The reel's settings (its intro, outro and crossfade), when the short is a reel. */
+ let reelSettings = /** @type {Record<string, any>} */ ({});
+ if (reel) {
+ const doc = await readTrailerBeats(dir, { reel });
+ if (!doc.exists) throw new CliError(`no reel ${reel}: ${reelFileOf(reel)} is not there`);
+ beats = P.beatsOf(doc.beats);
+ reelSettings = doc.settings ?? {};
+ take ??= doc.settings?.take ?? null;
+ } else if (o.beats) {
+ const doc = await readJson(path.resolve(o.beats));
+ if (!doc) throw new CliError(`--beats ${o.beats}: not a JSON file`);
+ beats = P.beatsOf(doc);
+ }
+ const items = o.items?.length ? o.items : null;
+ if (!beats && !items) throw new CliError("--reel <r>, --beats FILE or --items <id>,…: what the short is made of");
+ if (!take) throw new CliError("--take <t>: the take whose items the short is cut from");
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`);
+ const takeDir = path.join(takesDirOf(dir), take);
+ const takeManifestFrozen = await takeManifestOf(dir, take);
+ const projectManifest0 = await readJson(path.join(dir, "video.manifest.json"));
+ // The PROJECT's recording boxes (render.censor) are added to a take's -- a rendered take's render is frozen, and a
+ // region hidden since must never show in a short of it. ADD-ONLY: the take's own boxes stay.
+ const takeManifest0 = withProjectCensor(takeManifestFrozen, projectManifest0?.render?.censor);
+ // A rebuild from a batch's record (`o.look`, LOOK_SNAPSHOT_KEYS) lays the look it was built with over the take's.
+ const takeManifest = isObj(o.look) ? { ...takeManifest0, render: { ...(takeManifest0.render ?? {}), ...lookFromSnapshot(o.look, { projectDir: dir }) } } : takeManifest0;
+ const projectManifest = await readJson(path.join(dir, "video.manifest.json"));
+ const outDir = path.join(takeDir, "out");
+ const sourced = path.join(outDir, "sourced");
+ const schedule = await readJson(path.join(sourced, "schedule.json"));
+ const knobs = o.knobs ?? {};
+ // A desktop build reads its own knobs (render.desktop: a corner a short does not have is one it does).
+ const errors = o.desktop || o.landscape ? [] : V.validateVerticalRender({ render: { format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } } });
+ if (errors.length) throw new CliError(errors.join("; "));
+ const name = P.shortName({ reel, name: o.name ?? null });
+ const reframe = !!o.reframe;
+ // `landscape`: the same items in the take's own 16:9 look (a side post as a panel), for comparison.
+ const landscape = !!o.landscape;
+ // `desktop` (lane clip-kit): the same clips 16:9 with minimal chrome, by this builder (vertical.mjs desktopGeometry).
+ const desktop = !!o.desktop;
+ if ([landscape, reframe, desktop].filter(Boolean).length > 1) throw new CliError("one of --landscape, --desktop and --reframe");
+ const dknobs = desktop ? desktopKnobsOf(knobs) : null;
+ if (desktop) {
+ const derr = V.validateDesktopRender({ render: { desktop: { ...(takeManifest.render?.desktop ?? {}), ...dknobs } } });
+ if (derr.length) throw new CliError(derr.join("; "));
+ }
+ const tag = landscape ? "landscape" : desktop ? "desktop" : P.layoutTag(knobs, { reframe });
+ // The channel promo (promo-card.mjs): a per-clip build's; --promo asks for the cut's (none set: refused).
+ if ((o.promo === true || o.promoKnobs) && !takeManifest.render?.promo) {
+ throw new CliError(`--promo: the take sets no channel promo -- umtool look ${r.project.id} promo='{"name":"…","url":"https://…"}' (or a take's patch)`);
+ }
+ const promoArgs0 = o.promo === false ? ["--no-promo"] : o.promoKnobs ? ["--promo-knobs", JSON.stringify(o.promoKnobs)] : [];
+ const slug = takeManifest.slug ?? r.project.id.split("/").pop();
+ const outFile = o.out ? path.resolve(o.out) : path.join(outDir, `${slug}.${name}.${tag}${landscape || desktop ? "" : ".vertical"}.mp4`);
+ const cuts = new Map();
+ for (const e of takeManifest.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ const c = await readJson(path.join(sourced, "segments", `${e.id}.cut.json`));
+ if (c) cuts.set(e.id, c);
+ }
+ // The brand intro (9:16) and the reel's outro card (outro.mjs), added after the short is made.
+ const introSpec = o.noIntro ? null : isObj(reelSettings.intro) ? reelSettings.intro : (o.intro || reelSettings.intro === true) ? true : null;
+ let outro = null;
+ const ro = o.noOutro ? null : resolveOutro(reelSettings.outro, { reelTitle: reelSettings.title ?? null, projectTitle: projectManifest?.title ?? null });
+ if (ro) {
+ if (!ro.title) throw new CliError(`the reel ${reel}'s outro has no title: give it one (\`umtool trailer-beats ${r.project.id} --reel ${reel} outro '{"title":"…"}'\`)`);
+ const imageFile = ro.image ? path.join(dir, ro.image) : null;
+ if (imageFile && !existsSync(imageFile)) throw new CliError(`the reel ${reel}'s outro image ${ro.image} is not a file of ${r.project.id}`);
+ outro = { ...ro, imageFile };
+ }
+ const project = P.withOverrides(projectManifest?.timeline ?? [], o.overrides ?? null);
+ // A clip's cold open (vertical-plan.mjs coldOpenEntry) plays in a short or a desktop clip of the bare builder: not
+ // in the take's 16:9 look, a reframe or the stacked deck (each cut from a finished or crossfaded cut).
+ const stacked = !desktop && !landscape && !reframe && V.stackedDeckWanted({ ...(takeManifest.render ?? {}), format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } });
+ const coldOpens = o.coldOpen !== false && !landscape && !reframe && !stacked;
+ const plan = P.planVerticalCut({ timeline: takeManifest.timeline ?? [], beats, items, schedule, cuts, project, coldOpens });
+ // The channel promo ends the short only when its last piece is a whole clip (promo-card.mjs): then a reel's outro
+ // card is not added after it (one ending, said).
+ const notes = [];
+ const lastPiece = plan.pieces.at(-1);
+ const lastEntry = lastPiece ? plan.timeline.find((e) => e.id === lastPiece.id) : null;
+ const promoEnds = !landscape && !reframe && !stacked && o.promo !== false && !!takeManifest.render?.promo && lastEntry?.type === "clip" && lastEntry.promo !== false && lastPiece.to === null && !lastPiece.from;
+ const promoArgs2 = !landscape && !reframe && !stacked && o.promo !== false && takeManifest.render?.promo && !promoEnds ? ["--no-promo"] : [];
+ if (!promoEnds && promoArgs2.length && lastEntry) notes.push(`the short ends on ${lastEntry.id}${lastEntry.type === "clip" ? " cut short of its end" : `, a ${lastEntry.type}`}: no channel promo (it ends a whole clip)`);
+ if (promoEnds && outro) {
+ notes.push(`the channel promo ends the short: the reel's outro card is not added after it`);
+ outro = null;
+ }
+ // Every clip's hidden regions as this build draws them (the take's, the project's added: clip-censor.mjs). A reframe
+ // cuts the take's FINISHED picture, which hides only what the take was rendered with: a region hidden since is
+ // refused by name, never cut showing.
+ const C = await import("umtool-report-to-video/clip-censor");
+ const baseId = (id) => String(id).replace(/~(?:\d+|co)$/, "");
+ const frozenById = new Map((takeManifestFrozen.timeline ?? []).map((e) => [e?.id, e]));
+ const hidden = Object.fromEntries(plan.timeline.filter((e) => e?.type === "clip").map((e) => [e.id, C.censorRegionsOf(e, takeManifest.render ?? {}, takeManifest.provenance ?? {}).length]));
+ if (reframe) {
+ const since = plan.timeline.filter((e) => e?.type === "clip").filter((e) => {
+ const was = frozenById.get(baseId(e.id));
+ const now = C.censorRecordOf(C.censorRegionsOf(e, takeManifest.render ?? {}, takeManifest.provenance ?? {}));
+ const then = was ? C.censorRecordOf(C.censorRegionsOf(was, takeManifestFrozen.render ?? {}, takeManifestFrozen.provenance ?? {})) : [];
+ return JSON.stringify(now) !== JSON.stringify(then);
+ });
+ if (since.length) {
+ throw new CliError(`--reframe cuts take ${take}'s finished picture, which does not hide the regions set since it was rendered on ${since.map((e) => `${baseId(e.id)} (${hidden[e.id]} box(es))`).join(", ")}: render the take again, or build the short without --reframe`);
+ }
+ }
+ if (o.dryRun) {
+ return { dryRun: { project: r.project.id, take, name, layout: tag, wouldWrite: outFile, hidden, intro: introSpec ? (introSpec === true ? "the take's render.intro, else the default" : introSpec) : null, outro: outro ? { title: outro.title, text: outro.text, image: outro.image, seconds: outro.seconds } : null, pieces: plan.pieces, items: plan.timeline.map((e) => ({ id: e.id, type: e.type, start: e.start, end: e.end })), promo: promoEnds, notes } };
+ }
+ const started = Date.now();
+ // The project's fetched windows (and narration) are the take's too, as a made take's are (takeMaker.mjs
+ // linkSharedOut): a draft take that was never rendered has no out/clips-raw of its own to cut from.
+ if (!reframe) {
+ // Through ensureWriteDir: a tiered project's out/ is a link to the media root, never replaced by a directory.
+ const { linkSharedOut } = await import("./takeMaker.mjs");
+ await linkSharedOut(dir, await ensureWriteDir(outDir));
+ if (landscape) await linkSharedOut(dir, await ensureWriteDir(path.join(takeDir, `out-landscape-${name}`)));
+ }
+ let made;
+ if (reframe) {
+ const RF = await import("umtool-report-to-video/reframe");
+ made = await RF.reframeTake({ takeDir, outDir, slug, beats, items, plan, render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, outFile, log: say });
+ } else if (landscape) {
+ const renderPath = path.join(dir, `.vertical-${take}-${name}.render.json`);
+ await writeFile(renderPath, JSON.stringify({ ...takeManifest, render: P.renderForPart(takeManifest.render, plan.timeline), timeline: plan.timeline }, null, 2) + "\n", "utf8");
+ const own = path.join(takeDir, `out-landscape-${name}`);
+ const argv = [process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", own, "--skip-fetch", "--no-chapters"];
+ say(`vertical --landscape: building ${plan.timeline.length} item(s) 16:9 in the heavy slot …`);
+ const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true }));
+ if (code !== 0) throw new CliError(`the landscape build exited ${code}`);
+ const RF = await import("umtool-report-to-video/reframe");
+ await mkdir(path.dirname(outFile), { recursive: true });
+ await writeFile(outFile, await readFile(path.join(own, `${slug}.mp4`)));
+ made = { seconds: await RF.probeSeconds(outFile), loudness: null };
+ } else if (desktop) {
+ // The desktop build (build-video --desktop): the take's render, the planned items, the desktop knobs over its own.
+ const renderPath = path.join(dir, `.desktop-${take}-${name}.render.json`);
+ await writeFile(renderPath, JSON.stringify({ ...takeManifest, render: P.renderForPart(takeManifest.render, plan.timeline), timeline: plan.timeline }, null, 2) + "\n", "utf8");
+ const work = `desktop-${name}`;
+ const built = path.join(outDir, `${slug}.${name}.desktop-build.mp4`);
+ const sections = V.sectionTitlesOf(takeManifest);
+ const argv = [
+ process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", outDir,
+ "--skip-fetch", "--no-chapters", "--desktop", "--desktop-knobs", JSON.stringify(dknobs), "--vertical-work", work, "--vertical-out", built, ...(promoArgs2.length ? promoArgs2 : promoArgs0),
+ "--vertical-sections", JSON.stringify(Object.fromEntries(plan.timeline.map((e) => [e.id, sections.get(e.id.replace(/~(?:\d+|co)$/, "")) ?? null]))),
+ ];
+ say(`vertical --desktop: building ${plan.timeline.length} item(s) 16:9 in the heavy slot …`);
+ const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true }));
+ if (code !== 0) throw new CliError(`the desktop build exited ${code}`);
+ const RF = await import("umtool-report-to-video/reframe");
+ const dk = V.desktopKnobs({ desktop: { ...(takeManifest.render?.desktop ?? {}), ...dknobs } });
+ made = await RF.assembleShort({
+ pieces: plan.pieces, segmentsDir: path.join(outDir, work, "segments"), built, outFile, schedule: null,
+ render: { ...takeManifest.render, vertical: { loudness: dk.loudness } }, log: say,
+ });
+ } else {
+ // The build's manifest: the take's render, the planned items; beside the project's manifest, so its files resolve.
+ const renderPath = path.join(dir, `.vertical-${take}-${name}.render.json`);
+ const doc = { ...takeManifest, timeline: plan.timeline };
+ await writeFile(renderPath, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ const work = `vertical-${name}-${tag}`;
+ const sections = V.sectionTitlesOf(takeManifest);
+ const built = path.join(outDir, `${slug}.${name}.${tag}.vertical-build.mp4`);
+ const argv = [
+ process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", outDir,
+ "--skip-fetch", "--no-chapters", "--vertical", "--vertical-knobs", JSON.stringify(knobs), "--vertical-work", work, "--vertical-out", built, ...(promoArgs2.length ? promoArgs2 : promoArgs0),
+ // The hook "section" names a clip's section in the WHOLE take (each planned entry under its source's id).
+ "--vertical-sections", JSON.stringify(Object.fromEntries(plan.timeline.map((e) => [e.id, sections.get(e.id.replace(/~(?:\d+|co)$/, "")) ?? null]))),
+ ];
+ say(`vertical: building ${plan.timeline.length} item(s) 9:16 in the heavy slot …`);
+ const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true }));
+ if (code !== 0) throw new CliError(`the vertical build exited ${code}`);
+ const RF = await import("umtool-report-to-video/reframe");
+ made = await RF.assembleShort({
+ pieces: plan.pieces, segmentsDir: path.join(outDir, work, "segments"), built, outFile,
+ // A stacked vertical deck's pieces are cut from the built cut (its deck laid over it), at the build's places.
+ schedule: V.stackedDeckWanted({ ...(takeManifest.render ?? {}), format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } })
+ ? await readJson(path.join(outDir, work, "schedule.json"))
+ : null,
+ render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, log: say,
+ });
+ }
+ // The intro before and the card after, in one pass, in the heavy slot (the intro is a HyperFrames render, cached).
+ let wrapped = { intro: null, outro: null };
+ if ((introSpec || outro) && !landscape && !desktop) {
+ const { wrapShort } = await import("umtool-report-to-video/reel-intro");
+ const RF = await import("umtool-report-to-video/reframe");
+ const slot = await heavySlot();
+ // The 9:16 end card (outro.mjs) -- the stacked deck's only: a bare short's outro is the card it always was.
+ const endCard = await endCardOf({
+ render: takeManifest.render ?? {}, knobs, provenance: takeManifest.provenance ?? {}, timeline: plan.timeline,
+ schedule: reframe || landscape ? null : await readJson(path.join(outDir, `vertical-${name}-${tag}`, "schedule.json")),
+ });
+ wrapped = await slot(["umtool", "vertical", r.project.id, "--take", take, ...(reel ? ["--reel", reel] : []), "(intro/outro)"], () => wrapShort({
+ file: outFile, takeDir, render: takeManifest.render ?? {}, manifest: takeManifest, introSpec, outro,
+ xfade: typeof reelSettings.xfade === "number" ? reelSettings.xfade : 0.3, log: say, endCard,
+ }));
+ made = { ...made, seconds: await RF.probeSeconds(outFile) };
+ }
+ const record = {
+ version: 1, kind: "vertical-short", project: r.project.id, take, name, layout: tag, reframe,
+ knobs, ...(o.promo === false ? { promo: false } : o.promoKnobs ? { promo: o.promoKnobs } : {}), ...(o.coldOpen === false ? { coldOpen: false } : {}), pieces: plan.pieces, ...(wrapped.intro ? { intro: wrapped.intro } : {}), ...(wrapped.outro ? { outro: wrapped.outro } : {}), seconds: made.seconds, loudness: made.loudness ?? null,
+ look: lookSnapshotOf(takeManifest.render, { projectDir: dir }),
+ notes: [...notes, ...V.verticalNotes({ format: "vertical", vertical: desktop ? { maxSeconds: V.desktopKnobs({ desktop: { ...(takeManifest.render?.desktop ?? {}), ...dknobs } }).maxSeconds } : knobs }, made.seconds)], out: outFile,
+ madeAt: new Date().toISOString(), buildSeconds: Math.round((Date.now() - started) / 1000),
+ };
+ await writeFile(outFile.replace(/\.mp4$/, ".json"), JSON.stringify(record, null, 2) + "\n", "utf8");
+ return { record };
+}
+
+/** A take's render with the project's recording boxes added (each once); the take as it is when there are none. */
+export function withProjectCensor(take, projectCensor) {
+ if (!Array.isArray(projectCensor) || !projectCensor.length) return take;
+ const have = Array.isArray(take?.render?.censor) ? take.render.censor : [];
+ const added = projectCensor.filter((r) => !have.some((x) => JSON.stringify(x) === JSON.stringify(r)));
+ return added.length ? { ...take, render: { ...(take.render ?? {}), censor: [...have, ...added] } } : take;
+}
+
+/** A take's manifest as rendered, else (a draft, never rendered) the project's with the take's patch laid on. */
+export async function takeManifestOf(dir, take) {
+ const rendered = await readJson(path.join(takesDirOf(dir), take, "video.manifest.json"));
+ if (rendered) return rendered;
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ return resolveTakeManifest(dir, take).then((x) => x.manifest, (e) => {
+ throw new CliError(`take ${take}: ${e instanceof Error ? e.message : e}`);
+ });
+}
+
+/**
* `umtool vertical …`
* @param {string[]} args everything after `vertical`
* @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void }} [opts]
* @returns {Promise<number>}
*/
export async function verticalCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) {
- const V = await import("umtool-report-to-video/vertical");
- const P = await import("umtool-report-to-video/vertical-plan");
try {
const p = parse(args);
if (p.has("--help") || !p.positional.length) {
@@ -150,153 +509,21 @@ export async function verticalCommand(args, { reportsRoot = REPORTS_ROOT, log =
}
const json = p.has("--json");
const say = json ? err : log;
- const r = await resolveProject(p.positional[0], reportsRoot);
- if (r.ambiguous) throw new CliError(`"${p.positional[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
- if (!r.project) throw new CliError(`no project matches "${p.positional[0]}"`);
- if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`);
- const dir = r.project.dir;
- const reel = p.flags["--reel"] ?? null;
- let take = p.flags["--take"] ?? null;
- let beats = null;
- /** The reel's settings (its intro, outro and crossfade), when the short is a reel. */
- let reelSettings = /** @type {Record<string, any>} */ ({});
- if (reel) {
- const doc = await readTrailerBeats(dir, { reel });
- if (!doc.exists) throw new CliError(`no reel ${reel}: ${reelFileOf(reel)} is not there`);
- beats = P.beatsOf(doc.beats);
- reelSettings = doc.settings ?? {};
- take ??= doc.settings?.take ?? null;
- } else if (p.has("--beats")) {
- const doc = await readJson(path.resolve(p.flags["--beats"]));
- if (!doc) throw new CliError(`--beats ${p.flags["--beats"]}: not a JSON file`);
- beats = P.beatsOf(doc);
- }
- const items = p.has("--items") ? p.flags["--items"].split(",").map((s) => s.trim()).filter(Boolean) : null;
- if (!beats && !items) throw new CliError("--reel <r>, --beats FILE or --items <id>,…: what the short is made of");
- if (!take) throw new CliError("--take <t>: the take whose items the short is cut from");
- if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`);
- const takeDir = path.join(takesDirOf(dir), take);
- // The take's manifest as rendered, else (a draft, never rendered) the project's with the take's patch laid on.
- let takeManifest = await readJson(path.join(takeDir, "video.manifest.json"));
- if (!takeManifest) {
- const { resolveTakeManifest } = await import("./takeManifest.mjs");
- takeManifest = await resolveTakeManifest(dir, take).then((x) => x.manifest, (e) => {
- throw new CliError(`take ${take}: ${e instanceof Error ? e.message : e}`);
- });
- }
- const projectManifest = await readJson(path.join(dir, "video.manifest.json"));
- const outDir = path.join(takeDir, "out");
- const sourced = path.join(outDir, "sourced");
- const schedule = await readJson(path.join(sourced, "schedule.json"));
- const knobs = knobsOfFlags(p.flags);
- const errors = V.validateVerticalRender({ render: { format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } } });
- if (errors.length) throw new CliError(errors.join("; "));
- const name = P.shortName({ reel, name: p.flags["--name"] ?? null });
- const reframe = p.has("--reframe");
- // `--landscape`: the same items in the take's own 16:9 look (a side post as a panel), for comparison.
- const landscape = p.has("--landscape");
- if (landscape && reframe) throw new CliError("--landscape or --reframe, not both");
- const tag = landscape ? "landscape" : P.layoutTag(knobs, { reframe });
- const slug = takeManifest.slug ?? r.project.id.split("/").pop();
- const outFile = p.flags["--out"] ? path.resolve(p.flags["--out"]) : path.join(outDir, `${slug}.${name}.${tag}${landscape ? "" : ".vertical"}.mp4`);
- const cuts = new Map();
- for (const e of takeManifest.timeline ?? []) {
- if (e?.type !== "clip") continue;
- const c = await readJson(path.join(sourced, "segments", `${e.id}.cut.json`));
- if (c) cuts.set(e.id, c);
- }
- // The brand intro (9:16) and the reel's outro card (outro.mjs), added after the short is made.
- const introSpec = p.has("--no-intro") ? null : isObj(reelSettings.intro) ? reelSettings.intro : (p.has("--intro") || reelSettings.intro === true) ? true : null;
- let outro = null;
- const o = p.has("--no-outro") ? null : resolveOutro(reelSettings.outro, { reelTitle: reelSettings.title ?? null, projectTitle: projectManifest?.title ?? null });
- if (o) {
- if (!o.title) throw new CliError(`the reel ${reel}'s outro has no title: give it one (\`umtool trailer-beats ${r.project.id} --reel ${reel} outro '{"title":"…"}'\`)`);
- const imageFile = o.image ? path.join(dir, o.image) : null;
- if (imageFile && !existsSync(imageFile)) throw new CliError(`the reel ${reel}'s outro image ${o.image} is not a file of ${r.project.id}`);
- outro = { ...o, imageFile };
- }
- const plan = P.planVerticalCut({ timeline: takeManifest.timeline ?? [], beats, items, schedule, cuts, project: projectManifest?.timeline ?? [] });
- if (p.has("--dry-run")) {
- const out = { project: r.project.id, take, name, layout: tag, wouldWrite: outFile, intro: introSpec ? (introSpec === true ? "the take's render.intro, else the default" : introSpec) : null, outro: outro ? { title: outro.title, text: outro.text, image: outro.image, seconds: outro.seconds } : null, pieces: plan.pieces, items: plan.timeline.map((e) => ({ id: e.id, type: e.type, start: e.start, end: e.end })) };
- log(json ? JSON.stringify(out, null, 2) : [`would write ${outFile}`, ...(introSpec ? [" (intro, 9:16)"] : []), ...plan.pieces.map((x) => ` ${x.id}${x.to === null ? "" : ` ${x.from}–${x.to}`}`), ...(outro ? [` (outro card "${outro.title}", ${outro.seconds} s)`] : [])].join("\n"));
+ const done = await buildShort(shortOptionsOf(p), { reportsRoot, say });
+ if ("dryRun" in done) {
+ const out = done.dryRun;
+ log(json ? JSON.stringify(out, null, 2) : [`would write ${out.wouldWrite}`, ...(out.intro ? [" (intro, 9:16)"] : []), ...out.pieces.map((x) => ` ${x.id}${x.to === null ? "" : ` ${x.from}–${x.to}`}`), ...(out.outro ? [` (outro card "${out.outro.title}", ${out.outro.seconds} s)`] : [])].join("\n"));
return 0;
}
- const started = Date.now();
- let made;
- if (reframe) {
- const RF = await import("umtool-report-to-video/reframe");
- made = await RF.reframeTake({ takeDir, outDir, slug, beats, items, plan, render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, outFile, log: say });
- } else if (landscape) {
- const renderPath = path.join(dir, `.vertical-${take}-${name}.render.json`);
- await writeFile(renderPath, JSON.stringify({ ...takeManifest, render: P.renderForPart(takeManifest.render, plan.timeline), timeline: plan.timeline }, null, 2) + "\n", "utf8");
- const own = path.join(takeDir, `out-landscape-${name}`);
- const argv = [process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", own, "--skip-fetch", "--no-chapters"];
- say(`vertical --landscape: building ${plan.timeline.length} item(s) 16:9 in the heavy slot …`);
- const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true }));
- if (code !== 0) throw new CliError(`the landscape build exited ${code}`);
- const RF = await import("umtool-report-to-video/reframe");
- await mkdir(path.dirname(outFile), { recursive: true });
- await writeFile(outFile, await readFile(path.join(own, `${slug}.mp4`)));
- made = { seconds: await RF.probeSeconds(outFile), loudness: null };
- } else {
- // The build's manifest: the take's render, the planned items; beside the project's manifest, so its files resolve.
- const renderPath = path.join(dir, `.vertical-${take}-${name}.render.json`);
- const doc = { ...takeManifest, timeline: plan.timeline };
- await writeFile(renderPath, JSON.stringify(doc, null, 2) + "\n", "utf8");
- const work = `vertical-${name}-${tag}`;
- const sections = V.sectionTitlesOf(takeManifest);
- const built = path.join(outDir, `${slug}.${name}.${tag}.vertical-build.mp4`);
- const argv = [
- process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", outDir,
- "--skip-fetch", "--no-chapters", "--vertical", "--vertical-knobs", JSON.stringify(knobs), "--vertical-work", work, "--vertical-out", built,
- // The hook "section" names a clip's section in the WHOLE take (each planned entry under its source's id).
- "--vertical-sections", JSON.stringify(Object.fromEntries(plan.timeline.map((e) => [e.id, sections.get(e.id.replace(/~\d+$/, "")) ?? null]))),
- ];
- say(`vertical: building ${plan.timeline.length} item(s) 9:16 in the heavy slot …`);
- const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true }));
- if (code !== 0) throw new CliError(`the vertical build exited ${code}`);
- const RF = await import("umtool-report-to-video/reframe");
- made = await RF.assembleShort({
- pieces: plan.pieces, segmentsDir: path.join(outDir, work, "segments"), built, outFile,
- // A stacked vertical deck's pieces are cut from the built cut (its deck laid over it), at the build's places.
- schedule: V.stackedDeckWanted({ ...(takeManifest.render ?? {}), format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } })
- ? await readJson(path.join(outDir, work, "schedule.json"))
- : null,
- render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, log: say,
- });
- }
- // The intro before and the card after, in one pass, in the heavy slot (the intro is a HyperFrames render, cached).
- let wrapped = { intro: null, outro: null };
- if ((introSpec || outro) && !landscape) {
- const { wrapShort } = await import("umtool-report-to-video/reel-intro");
- const RF = await import("umtool-report-to-video/reframe");
- const slot = await heavySlot();
- // The 9:16 end card (outro.mjs) -- the stacked deck's only: a bare short's outro is the card it always was.
- const endCard = await endCardOf({
- render: takeManifest.render ?? {}, knobs, provenance: takeManifest.provenance ?? {}, timeline: plan.timeline,
- schedule: reframe || landscape ? null : await readJson(path.join(outDir, `vertical-${name}-${tag}`, "schedule.json")),
- });
- wrapped = await slot(["umtool", "vertical", r.project.id, "--take", take, ...(reel ? ["--reel", reel] : []), "(intro/outro)"], () => wrapShort({
- file: outFile, takeDir, render: takeManifest.render ?? {}, manifest: takeManifest, introSpec, outro,
- xfade: typeof reelSettings.xfade === "number" ? reelSettings.xfade : 0.3, log: say, endCard,
- }));
- made = { ...made, seconds: await RF.probeSeconds(outFile) };
- }
- const record = {
- version: 1, kind: "vertical-short", project: r.project.id, take, name, layout: tag, reframe,
- knobs, pieces: plan.pieces, ...(wrapped.intro ? { intro: wrapped.intro } : {}), ...(wrapped.outro ? { outro: wrapped.outro } : {}), seconds: made.seconds, loudness: made.loudness ?? null,
- notes: V.verticalNotes({ format: "vertical", vertical: knobs }, made.seconds), out: outFile,
- madeAt: new Date().toISOString(), buildSeconds: Math.round((Date.now() - started) / 1000),
- };
- await writeFile(outFile.replace(/\.mp4$/, ".json"), JSON.stringify(record, null, 2) + "\n", "utf8");
+ const record = done.record;
if (json) log(JSON.stringify(record, null, 2));
else {
for (const n of record.notes) log(`note: ${n}`);
- log(`wrote ${outFile} (${made.seconds.toFixed(1)} s, 1080x1920)`);
+ log(`wrote ${record.out} (${record.seconds.toFixed(1)} s, ${record.layout === "landscape" || record.layout === "desktop" ? "1920x1080" : "1080x1920"})`);
}
return 0;
} catch (e) {
- if (e instanceof CliError || e?.name === "VerticalPlanError") {
+ if (isRefusal(e)) {
err(`umtool vertical: ${e.message}`);
return 2;
}
@@ -304,3 +531,5 @@ export async function verticalCommand(args, { reportsRoot = REPORTS_ROOT, log =
}
}
+/** A refusal (said, exit 2) rather than a crash. */
+export const isRefusal = (e) => e instanceof CliError || e?.name === "VerticalPlanError";
diff --git a/umtool/report-to-video/basic.mjs b/umtool/report-to-video/basic.mjs
@@ -38,6 +38,7 @@ import path from "node:path";
import { promisify } from "node:util";
import { basicFadeOf, basicOn } from "yt-dlp-transcript-common/lib/report/look.mjs";
import { clipBlurOf } from "./clip-blur.mjs";
+import { censorRegionsOf } from "./clip-censor.mjs";
import { keptSpans, renderGaps } from "./gaps.mjs";
import { hasLocalMedia } from "./local-media.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
@@ -102,6 +103,13 @@ export function basicPlan(manifest, { only = null } = {}) {
errors.push(`${e.id}: no span to play (start/end, cutStart/cutEnd)`);
continue;
}
+ // Its hidden regions (clip-censor.mjs): a basic cut draws none, and privacy is not switched off by a mode --
+ // refused by name, whatever render.blur says.
+ const boxes = censorRegionsOf(e, render, manifest?.provenance ?? {});
+ if (boxes.length) {
+ errors.push(`${e.id} hides ${boxes.length} region(s) of its picture (render.censor / its censor), and a basic cut draws none: render it as a deck cut, or take the boxes off only if the regions may show`);
+ continue;
+ }
if (clipBlurOf(e, render)) {
errors.push(`${e.id} asks for its picture blurred, and a basic cut draws no blur: render it as a deck cut, or say the basic cut is the uncensored one (umtool look <p> blur=off)`);
continue;
diff --git a/umtool/report-to-video/basic.test.mjs b/umtool/report-to-video/basic.test.mjs
@@ -77,6 +77,16 @@ test("basicPlan: clips and their spans in order; the rest left out by name; a bl
assert.deepEqual(basicPlan({ render: { basic: { fade: { video: 0.5 } } }, timeline: [] }).fade, { audio: 0.03, video: 0.5 });
});
+test("basicPlan: a clip that hides regions is refused by name -- its own box or its recording's, in the uncensored cut too", () => {
+ const clip = { type: "clip", id: "c1", video: "v", start: 1, end: 3 };
+ const own = basicPlan({ render: {}, timeline: [{ ...clip, censor: { boxes: [[0, 0, 0.5, 0.5]] } }] });
+ assert.match(own.errors[0], /c1 hides 1 region\(s\) of its picture .* a basic cut draws none/);
+ assert.deepEqual(own.items, []);
+ const rec = basicPlan({ render: { blur: "off", censor: [{ video: "v", boxes: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]] }] }, timeline: [clip] });
+ assert.match(rec.errors[0], /c1 hides 2 region\(s\)/, "render.blur off does not lift a hidden region");
+ assert.deepEqual(basicPlan({ render: { censor: [{ video: "another", boxes: [[0, 0, 0.5, 0.5]] }] }, timeline: [clip] }).errors, [], "another recording's: as before");
+});
+
test("spanArgs: the file's seconds, fitted into the first window's shape, its fades and gain, the build's encode", () => {
const shape = basicShape({ width: 1920, height: 1080, sar: "1:1", fps: "60/1" });
assert.deepEqual(shape, { W: 1920, H: 1080, fps: "60/1" });
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -232,9 +232,18 @@ import { buildPostSegment } from "./post-render.mjs";
import {
clipGeometry, clipVerticalLayout, landscapeSideGeometry, landscapeSideOverlay, sidePostOf, sideSpan, sourceTagText,
sectionTitlesOf, validateVerticalRender, verticalAss, verticalClipGraph, verticalHookOf, verticalNotes, verticalOn,
- verticalPostBox, verticalPostEntry, verticalRender,
+ verticalPostBox, verticalPostEntry, verticalRender, safeArea,
+ desktopGeometry, desktopHookOf, desktopKnobs, desktopRender, desktopSafeArea, validateDesktopRender, pictureRegion,
} from "./vertical.mjs";
import { renderSideCard, sideFitFilter } from "./side-card.mjs";
+// THE CLIP KIT (lane clip-kit): a per-clip build's code -- its corner, its link (clip-kit.mjs).
+import { clipQrUrl, cornerOverlayXY, cornerQrOf, desktopQrBox, desktopQrOf, validateClipKit, verticalQrBox, verticalQrOf } from "./clip-kit.mjs";
+// THE CHANNEL PROMO (lane clip-kit, slice D): the card a per-clip build ends on (promo-card.mjs).
+import { promoBand, promoCardInput, promoFilterParts, promoOf, renderPromoCard, validatePromo } from "./promo-card.mjs";
+// ZOOM AT POINTS (lane clip-kit, slice F; clip-zoom.mjs): a per-clip build's pushes in on its picture.
+import { resolveZooms, validateZooms, zoomFilters } from "./clip-zoom.mjs";
+// HIDDEN REGIONS (lane clip-kit, slice E; clip-censor.mjs): a recording's chat overlay, other accounts on screen.
+import { censorParts, censorProblems, censorRecordOf, censorRegionsOf, stillCensorArgs, validateCensor } from "./clip-censor.mjs";
// THE STACKED VERTICAL DECK (vertical-deck.mjs): a 9:16 cut that keeps its deck -- the picture at full width, the
// captions under it, a clip's two crops, a post item's hero card -- and the modules it leaves out.
import { ENLARGE_WARN, clipTwoCrop, leftOutWords, stackedCaptionGeo, stackedGeometry, stackedOn, twoCropEnlargement, twoCropGraph } from "./vertical-deck.mjs";
@@ -1804,6 +1813,20 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
return blurPictureFilters({ blur, span, h, layout, lineFiles, render });
};
+ // HIDDEN REGIONS (clip-censor.mjs): its recording's boxes (render.censor) and its own, on the SOURCE picture first --
+ // before its blur, its zooms and any framing -- over their spans. None: every graph below is the one it always was.
+ const censorRegions = media.hasVideo ? censorRegionsOf(entry, render, provenance) : [];
+ const censorDims = censorRegions.length ? await probeDims(raw) : null;
+ if (censorRegions.length) cutRecord.censor = censorRecordOf(censorRegions);
+ // No picture (a poster plays): nothing to hide, and the record says so (a chrome pass reads it).
+ else if (!media.hasVideo && censorRegionsOf(entry, render, provenance).length) cutRecord.censorNoPicture = true;
+ /** The picture `vLabel` (a "[label]") with the regions hidden: the parts to run first, and the label after them. */
+ const censored = (vLabel) => {
+ if (!censorRegions.length) return { parts: [], v: vLabel };
+ const parts = censorParts(vLabel.slice(1, -1), "vcen", censorRegions, { width: censorDims[0], height: censorDims[1], from: cutRecord.start, gaps: cutRecord.gaps ?? [], seconds: segSeconds });
+ return { parts, v: "[vcen]" };
+ };
+
// THE SIDE POST (side-card.mjs): the post a clip carries beside it, up over its `from`-`to`, never read.
const sidePost = dirs.sides ? sidePostOf(entry, dirs.sides.timeline) : null;
const sideUp = sidePost ? sideSpan(entry.side, segSeconds) : null;
@@ -1821,8 +1844,12 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// carries a side post -- its captions lit word by word, its tag and hook, as one ASS file. A source with no
// picture keeps the plain path's poster.
if (dirs.vertical && !dirs.vertical.stacked && media.hasVideo) {
- const layout = clipVerticalLayout(entry, render);
- const geo = clipGeometry(layout, render, width, height);
+ const isDesktop = dirs.vertical.desktop === true;
+ const layout = isDesktop ? "desktop" : clipVerticalLayout(entry, render);
+ // A desktop clip's code first: its corner narrows the captions (vertical.mjs desktopGeometry).
+ const dqr = isDesktop ? desktopQrOf(entry, render) : null;
+ const dqrBox = dqr ? desktopQrBox(dqr, { W: width, safe: desktopSafeArea(render, width, height) }) : null;
+ const geo = isDesktop ? desktopGeometry(render, width, height, { qr: dqrBox }) : clipGeometry(layout, render, width, height);
const [sw, sh] = await probeDims(raw);
const inputs = cutArgs(raw, segA, segB);
let next = 1;
@@ -1838,16 +1865,65 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
side = { idx: next, ...sideUp };
next += 1;
}
+ // The short's code (clip-kit.mjs, render.vertical.qr): the source at the second it plays from, at the top of the
+ // safe area -- off unless the cut or the command asks. Its PNG the input after the rest.
+ const vqr = isDesktop ? dqr : verticalQrOf(entry, render);
+ const qrPng = vqr ? await qrForEntry(entry, provenance, render, outDir, { links: vqr.links, at: cutRecord.start, webpageUrl: meta.webpageUrl ?? null }) : null;
+ const qrBox = !qrPng ? null : isDesktop ? dqrBox : verticalQrBox(vqr, { W: width, safe: safeArea(render, width, height), tag: geo.tag });
+ let qrIdx = null;
+ if (qrBox) {
+ inputs.push("-i", qrPng.png);
+ qrIdx = next;
+ next += 1;
+ }
const g = gapped(ain);
+ // Its zooms (clip-zoom.mjs): in source space, after the blur, before the layout cuts it; refused past their
+ // limit by name, said when softer than the source.
+ let zoom = [];
+ if (Array.isArray(entry.zooms) && entry.zooms.length) {
+ const { region, rest } = pictureRegion(geo, sw, sh, entry.vertical?.crop ?? null);
+ const z = resolveZooms(entry, { from: cutRecord.start, gaps: cutRecord.gaps ?? [], srcW: sw, srcH: sh, region, rest, soften: render.zooms?.soften ?? 1, seconds: segSeconds });
+ if (z.errors.length) throw new Error(`zooms: ${z.errors.join("; ")}`);
+ for (const message of z.notes) EMIT("note", { message });
+ zoom = zoomFilters(z.zooms, { srcW: sw, srcH: sh, fps: render.fps });
+ if (z.zooms.length) cutRecord.zooms = z.zooms.map((x) => ({ at: Number(x.at.toFixed(3)), scale: Number(x.scale.toFixed(3)), focus: x.focus.map((n) => Number(n.toFixed(4))), hold: x.hold, ramp: x.ramp, enlargement: Number((rest * x.scale).toFixed(3)) }));
+ }
const graph = verticalClipGraph({
- geo, srcW: sw, srcH: sh, crop: entry.vertical?.crop ?? null, blur: await blurPicture(sw, sh), side, fps: render.fps, W: width, H: height,
+ geo, srcW: sw, srcH: sh, crop: entry.vertical?.crop ?? null, blur: [...(await blurPicture(sw, sh)), ...zoom], side, fps: render.fps, W: width, H: height,
});
const tag = sourceTagText({ channel: channelName(entry, meta, provenance), date: entry.date ?? uploadDateToIso(meta.uploadDate) });
+ // The promo's timing for the captions (the card itself is drawn below): from when, over how long, into which band.
+ const promoSpec = dirs.vertical.promoFor === entry.id ? promoOf(entry, render, segSeconds) : null;
+ const promoNow = promoSpec ? { from: Math.max(0, segSeconds - promoSpec.lead), fade: promoSpec.fade, captions: promoSpec.captions, band: promoBand({ width, height, captions: promoSpec.captions }).band } : null;
+ // A code at the top of a full layout pushes its hook band down below it (a desktop clip's is laid out already).
+ const capGeo = !isDesktop && qrBox && geo.hook?.top !== undefined ? { ...geo, hook: { ...geo.hook, top: Math.max(geo.hook.top, qrBox.y + qrBox.size + Math.round(height * 0.012)) } } : geo;
const cap = await segmentCaptions({
entry, provenance, look: dirs.look, render, outDir, from: cutRecord.start, seconds: segSeconds, bottom: 0, gaps: cutRecord.gaps ?? [],
- vertical: { geo, tag, hook: verticalHookOf(entry, render, dirs.vertical.sections), side: sideUp },
+ vertical: {
+ geo: capGeo, tag, side: sideUp,
+ hook: isDesktop ? desktopHookOf(entry, render, dirs.vertical.sections) : verticalHookOf(entry, render, dirs.vertical.sections),
+ ...(isDesktop ? { knobs: desktopKnobs(render) } : {}),
+ ...(promoNow ? { promo: promoNow } : {}),
+ },
});
- cutRecord.vertical = { layout, crop: entry.vertical?.crop ?? null, width, height, ...(cap ? { captions: cap.lines } : {}) };
+ cutRecord.vertical = { layout, crop: entry.vertical?.crop ?? null, width, height, ...(cap ? { captions: cap.lines } : {}), ...(qrBox ? { qr: { url: qrPng.url, corner: vqr.corner, ...qrBox } } : {}) };
+ const qrParts = qrBox
+ ? [`[${qrIdx}:v]scale=${qrBox.size}:${qrBox.size}:flags=neighbor,setsar=1[vqr]`, `[vp0][vqr]overlay=x=${qrBox.x}:y=${qrBox.y}:format=auto[vp]`]
+ : [];
+ // THE CHANNEL PROMO (promo-card.mjs): the last clip of a per-clip build ends on the card -- faded in over the
+ // clip's last seconds, its sound on under it, then held in silence; the captions go on over it, in its band.
+ const promo = promoSpec;
+ let promoPart = null;
+ if (promo) {
+ if (promo.note) EMIT("note", { message: `${entry.id}: ${promo.note}` });
+ const card = await renderPromoCard({ promo, render, width, height, dir: path.join(outDir, "cards"), manifestDir: dirs.vertical.manifestDir });
+ EMIT("log", { message: `${entry.id}: the promo card ${card.cached ? "(drawn before)" : "drawn"} -- ${path.basename(card.file)}` });
+ inputs.push(...promoCardInput({ file: card.file, lead: promo.lead, hold: promo.hold, fps: render.fps }));
+ const cardIdx = next;
+ next += 1;
+ promoPart = promoFilterParts({ vIn: "[vp]", aIn: audioMap.startsWith("[") ? audioMap : `[${audioMap}]`, cardIdx, seconds: segSeconds, lead: promo.lead, fade: promo.fade, hold: promo.hold, fps: render.fps });
+ cutRecord.promo = { key: card.key, card: path.basename(card.file), lead: promo.lead, fade: promo.fade, hold: promo.hold, captions: promo.captions };
+ }
await encodeClipSegment({
seg, outDir, render, opts, id: entry.id, record: cutRecord,
argv: [
@@ -1856,10 +1932,13 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
"-filter_complex", [
...g.parts,
...levelParts(null, g.a),
- `${g.v}${graph}[vp]`,
- cap ? `[vp]${cap.filter}[v]` : "[vp]null[v]",
+ ...censored(g.v).parts,
+ `${censored(g.v).v}${graph}${qrBox ? "[vp0]" : "[vp]"}`,
+ ...qrParts,
+ ...(promoPart ? promoPart.parts : []),
+ cap ? `${promoPart ? promoPart.v : "[vp]"}${cap.filter}[v]` : `${promoPart ? promoPart.v : "[vp]"}null[v]`,
].join(";"),
- "-map", "[v]", "-map", audioMap,
+ "-map", "[v]", "-map", promoPart ? promoPart.a : audioMap,
...encodeArgs(render),
seg,
],
@@ -1901,7 +1980,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
"-filter_complex", [
...g.parts,
...levelParts(null, g.a),
- `${g.v}${graph}[vp]`,
+ ...censored(g.v).parts,
+ `${censored(g.v).v}${graph}[vp]`,
cap ? `[vp]${cap.filter}[v]` : "[vp]null[v]",
].join(";"),
"-map", "[v]", "-map", audioMap,
@@ -1921,7 +2001,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const sideGeo = sideUp ? landscapeSideGeometry({ x: fr.box.x, y: fr.box.y, w: fr.box.width, h: fr.box.height }, entry.side.place) : null;
const sideInput = sideGeo ? await sideCard(sideGeo.w, sideGeo.h) : [];
const sideIdx = 1 + (pst ? 1 : 0) + (soundInput ? 1 : 0);
- const framed = `${pst ? "[pic]" : g.v}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}`;
+ const cen = pst ? { parts: [], v: "[pic]" } : censored(g.v);
+ const framed = `${cen.v}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}`;
// The stacked vertical deck's captions (vertical-deck.mjs): under the picture, each word lit, over the frame.
const vcap = dirs.vertical?.stacked && dirs.look
? await segmentCaptions({
@@ -1943,6 +2024,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
"-filter_complex", [
...g.parts,
...levelParts(pst ? pst.parts : null, g.a),
+ ...cen.parts,
...(sideGeo
? [`${framed}[vb]`, `[${sideIdx}:v]${sideFitFilter(sideGeo.w, sideGeo.h)}[vsc]`, ...(capped(`[vb][vsc]${landscapeSideOverlay(sideGeo, sideUp, render.width)}`) ?? [`[vb][vsc]${landscapeSideOverlay(sideGeo, sideUp, render.width)}[v]`])]
: capped(framed) ?? [`${framed}[v]`]),
@@ -2012,8 +2094,13 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// float over the bottom-right of the picture — the one part of the frame this
// cut promises never to draw on. Manifests with no rail keep the old overlay,
// byte for byte.
- const qr =
- render.qr === false || render.rail ? null : await qrForEntry(entry, provenance, render, outDir);
+ // The clip kit (clip-kit.mjs): the code's corner and its link -- the clip's `qr` over render.qr's; `br` and the
+ // citeUrl (as it always was) when neither says.
+ const cornerQr = render.rail ? null : cornerQrOf(entry, render);
+ const qr = cornerQr
+ ? await qrForEntry(entry, provenance, render, outDir, { links: cornerQr.links, at: cutRecord.start, webpageUrl: meta.webpageUrl ?? null })
+ : null;
+ if (qr && cornerQr.links !== "cite") cutRecord.qr = { url: qr.url, corner: cornerQr.corner };
const qrM = render.qr?.margin ?? 28;
// Bound the bar strip SHORTER than the clip. An overlay secondary that outruns
@@ -2067,10 +2154,16 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const mg = mont ? montageSegmentGraph({ mont, render, box: { w: VW, h: VH }, hasVideo: media.hasVideo, cutA, cutB, gainDb: level?.gain ?? null }) : null;
// The gaps out first (none in a montage: segGaps is empty there).
const g = gapped(ain);
- const pic = mg?.v ?? (pst ? "[pic]" : g.v);
+ // Hidden regions (clip-censor.mjs) on the picture first. A montage re-cuts its pictures from the source in its own
+ // graph: a montage clip with boxes is REFUSED, by name (never cut with the region showing).
+ if (mg && censorRegions.length) {
+ throw new Error(`${entry.id}: a montage clip cannot hide regions yet (${censorRegions.length} box(es) of its recording, render.censor or its own censor) -- take it out of the montage, or set its censor=false only if the region may show`);
+ }
+ const cenPlain = mg || pst ? { parts: [], v: null } : censored(g.v);
+ const pic = mg?.v ?? (pst ? "[pic]" : cenPlain.v);
const lead = mg
? [...(pst ? [`[0:a]asplit=2[mpa][mpw]`, ...pst.parts.map((p) => p.replaceAll("[0:a]", "[mpw]"))] : []), ...mg.parts]
- : [...g.parts, ...levelParts(pst ? pst.parts : null, g.a)];
+ : [...g.parts, ...levelParts(pst ? pst.parts : null, g.a), ...cenPlain.parts];
const parts = hasFooter
? [
@@ -2091,7 +2184,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// Sit above the footer when there is one, so the code never straddles the chrome.
parts.push(
qr
- ? `[${q}][${qrIdx}:v]overlay=x=${VW}-w-${qrM}:y=H-h-${FH + qrM}[v]`
+ ? `[${q}][${qrIdx}:v]overlay=${cornerOverlayXY(cornerQr.corner, { VW, FH, HH, m: qrM })}[v]`
: `[${q}]null[v]`,
);
// A montage's cut style and its counter, over the finished frame.
@@ -2212,7 +2305,7 @@ async function segmentCaptions({ entry, provenance, look, render, outDir, from,
if (vertical) {
const file = path.join(outDir, "segments", `${entry.id}.vertical.ass`);
const words = src.words.map(rel);
- await replaceFile(file, verticalAss({ geo: vertical.geo, render, words, seconds, tag: vertical.tag, hook: vertical.hook, side: vertical.side, W: render.width, H: render.height }));
+ await replaceFile(file, verticalAss({ geo: vertical.geo, render, words, seconds, tag: vertical.tag, hook: vertical.hook, side: vertical.side, W: render.width, H: render.height, ...(vertical.knobs ? { knobs: vertical.knobs } : {}), ...(vertical.promo ? { promo: vertical.promo } : {}) }));
return { filter: assFilter(file, FONTS_DIR), lines: words.length, wordsFrom: src.wordsFrom };
}
const size = render.captions?.size ?? "m";
@@ -2742,14 +2835,15 @@ export async function readCutRecord(seg) {
// Two rules learned the hard way: it must be FULLY OPAQUE (a translucent QR will
// not scan) and it must keep its quiet zone (the white border is part of the
// symbol, not decoration).
-async function qrForEntry(entry, provenance, render, outDir) {
+async function qrForEntry(entry, provenance, render, outDir, { links = "cite", at = null, webpageUrl = null } = {}) {
// A `src` clip's file has no page on the archive: only its own citeUrl.
if (hasLocalMedia(entry) && !entry.citeUrl) return null;
const q = render.qr ?? {};
// A mirror's LOCAL slug is not the id the site serves, and a clip taken from a
// copy whose archived transcript is broken should point at the copy that reads —
// so an explicit per-clip citeUrl always wins over the derived one.
- const url = entry.citeUrl ?? archiveMomentUrl(entry, provenance, entry.start);
+ // `links` (clip-kit.mjs): "moment" the source at the second it plays from, "channel" the promo's page.
+ const url = clipQrUrl(entry, provenance, { links, at, webpageUrl, channelUrl: render.promo?.url ?? null });
const png = path.join(outDir, "qr", `${entry.id}.png`);
await execFileP(QRENCODE, [
"-o", png,
@@ -3377,6 +3471,8 @@ async function buildImageSegment(entry, render, outDir, chrome, provenance, base
? null
: await qrForEntry(entry, provenance, render, outDir);
const qrM = render.qr?.margin ?? 28;
+ // A still's code stands in the cut's corner (render.qr.corner, clip-kit.mjs): bottom right when it names none.
+ const stillCorner = cornerQrOf(entry, render)?.corner ?? "br";
const secs = dur.toFixed(3);
// Inputs: one per picture, then the silence, then the code.
@@ -3393,7 +3489,7 @@ async function buildImageSegment(entry, render, outDir, chrome, provenance, base
}
parts.push(
qr
- ? `[${q}][${qrIdx}:v]overlay=x=${VW}-w-${qrM}:y=H-h-${FH + qrM}[v]`
+ ? `[${q}][${qrIdx}:v]overlay=${cornerOverlayXY(stillCorner, { VW, FH, HH, m: qrM })}[v]`
: `[${q}]null[v]`,
);
@@ -6814,7 +6910,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const basic = basicOn(manifest.render);
if (basic) {
const asked = [
- [opts.short, "--short"], [opts.vertical || verticalOn(manifest.render), "--vertical (render.format vertical)"], [opts.joinPreview, "--join-preview"],
+ [opts.short, "--short"], [opts.vertical || verticalOn(manifest.render), "--vertical (render.format vertical)"], [opts.desktop, "--desktop"], [opts.joinPreview, "--join-preview"],
[opts.chromeOnly, "--chrome-only"], [opts.chromePreview, "--chrome-preview"], [opts.clipPreview, "--clip-preview"], [opts.railOnly, "--rail-only / --preview"],
[opts.thumbnailOnly, "--thumbnail"], [opts.chaptersOnly, "--chapters-only"],
].filter(([on]) => on).map(([, flag]) => flag);
@@ -6842,6 +6938,19 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const landscape = manifest.timeline.filter((e) => e?.type === "analysis").map((e) => e.id);
if (landscape.length) throw new Error(`vertical: ${landscape.join(", ")} ${landscape.length > 1 ? "are analysis items" : "is an analysis item"}, which has no vertical form -- take it out of the vertical cut`);
}
+ // A DESKTOP build (lane clip-kit): a take's clips 16:9 with minimal chrome, by the per-clip builder a short uses.
+ const desktop = !!opts.desktop;
+ if (desktop) {
+ if (opts.short || vertical) throw new Error("--desktop builds the clips 16:9: not with --short or --vertical");
+ const knobs = opts.desktopKnobs && typeof opts.desktopKnobs === "object" ? opts.desktopKnobs : null;
+ const asked = { ...(manifest.render ?? {}), ...(knobs ? { desktop: { ...(manifest.render?.desktop ?? {}), ...knobs } } : {}) };
+ const errors = validateDesktopRender({ render: asked });
+ if (errors.length) throw new Error(`desktop: ${errors.join("; ")}`);
+ manifest.render = { ...desktopRender(asked), desktop: asked.desktop ?? {} };
+ manifest.timeline = (manifest.timeline ?? []).filter((e) => !isIntro(e));
+ const analysis = manifest.timeline.filter((e) => e?.type === "analysis").map((e) => e.id);
+ if (analysis.length) throw new Error(`desktop: ${analysis.join(", ")} is an analysis item, which a desktop clip build does not draw -- take it out`);
+ }
// A join preview (release 38, join-preview.mjs): the first few joins of
// the cut, each clip shortened to a few seconds at the join, in the cut's look.
if (opts.joinPreview) {
@@ -6867,7 +6976,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole),
...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole, { schedule: false }), ...validateTransitionStyle(whole),
...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole),
- ...validateGapEntries(whole), ...measureSettingsProblems(whole), ...validateAnalysisEntries(whole),
+ ...validateGapEntries(whole), ...measureSettingsProblems(whole), ...validateAnalysisEntries(whole), ...validateClipKit(whole), ...validatePromo(whole), ...validateZooms(whole), ...validateCensor(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
@@ -6940,6 +7049,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
dirs.dir = path.join(outRoot, opts.verticalWork ?? "vertical");
dirs.final = opts.verticalOut ? path.resolve(opts.verticalOut) : path.join(outRoot, `${manifest.slug}.vertical.mp4`);
}
+ // A desktop build likewise (the same flags name its work dir and its file).
+ if (desktop) {
+ dirs.dir = path.join(outRoot, opts.verticalWork ?? "desktop");
+ dirs.final = opts.verticalOut ? path.resolve(opts.verticalOut) : path.join(outRoot, `${manifest.slug}.desktop.mp4`);
+ }
// A join preview's too: its own work dir and file, the cut's out/ untouched.
if (opts.joinPreview) {
dirs.dir = path.join(outRoot, "join-preview-work");
@@ -6985,6 +7099,25 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// A vertical cut's hooks may name a clip's section: the deck's markers, read from the cut as written.
// A short of a take's items (umtool vertical) passes the WHOLE take's sections: its own timeline is a part of it.
if (vertical) dirs.vertical = { on: true, sections: opts.verticalSections ? new Map(Object.entries(opts.verticalSections)) : sectionTitlesOf(whole), stacked: stackedOn(render) };
+ // A desktop clip is drawn by the same per-clip branch, in its own geometry (vertical.mjs desktopGeometry).
+ if (desktop) dirs.vertical = { on: true, desktop: true, sections: opts.verticalSections ? new Map(Object.entries(opts.verticalSections)) : sectionTitlesOf(whole), stacked: false };
+ // THE CHANNEL PROMO (promo-card.mjs): a per-clip build (not the stacked deck) ends its LAST clip on the card, when
+ // the cut sets one (render.promo) and that clip does not say `promo: false`; `--no-promo` none, `--promo-knobs`
+ // its timing over the cut's.
+ if (opts.noPromo) delete render.promo;
+ else if (opts.promoKnobs && typeof opts.promoKnobs === "object") {
+ if (!render.promo) throw new Error("--promo-knobs: the cut sets no channel promo (render.promo: umtool look <p> promo='{\"name\":…,\"url\":…}')");
+ render.promo = { ...render.promo, ...opts.promoKnobs };
+ const errors = validatePromo({ render });
+ if (errors.length) throw new Error(`promo: ${errors.join("; ")}`);
+ }
+ if (dirs.vertical && !dirs.vertical.stacked && render.promo) {
+ // The card ends the build: only when its LAST entry is a clip (a post item last would put the card mid-short).
+ const last = (manifest.timeline ?? []).at(-1);
+ dirs.vertical.promoFor = last?.type === "clip" ? last.id : null;
+ if (last && last.type !== "clip") EMIT("note", { message: `the build ends on ${last.id}, a ${last.type ?? "non-clip"}: the channel promo ends a clip, so it is left out` });
+ dirs.vertical.manifestDir = manifestDir;
+ }
// A project's out/ first, through ensureOutDir: with UMTOOL_MEDIA_DIR set it
// is a link to the media root, and the recursive mkdirs below would
@@ -7524,6 +7657,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// A clip's blur is in its segment's picture (clip-blur.mjs): a cut
// that asks for another (render.blur turned off) needs the segments again.
...blurProblems({ entries: present.map((i) => entries[i]), records, render }),
+ // Its hidden regions likewise (clip-censor.mjs): a box added since must never be laid over uncensored.
+ ...censorProblems({ entries: present.map((i) => entries[i]), records, render, provenance }),
];
if (problems.length) throw new Error(`${what}: ${problems.join("; ")}`);
}
@@ -7873,10 +8008,14 @@ async function buildThumbnail(manifest, dirs, manifestDir) {
const blur = clipBlurOf(clip, render);
const blurred = blur && (blur.from ?? -Infinity) <= at && at <= (blur.to ?? Infinity);
const sigma = blurred ? Math.max(1, Math.round((blur.strength / 100) * (await probeDims(win.path))[1])) : 0;
+ // Its hidden regions at that second (clip-censor.mjs) are hidden in the still too, before any blur.
+ const regions = censorRegionsOf(clip, render, manifest.provenance ?? {});
+ const dims = regions.length ? await probeDims(win.path) : null;
+ const cen = regions.length ? stillCensorArgs(regions, at, { width: dims[0], height: dims[1] }, blurred ? [`gblur=sigma=${sigma}:steps=3`] : []) : [];
await execFileP(FFMPEG, [
"-nostdin", "-v", "error", "-y",
"-ss", Math.max(0, at - win.from).toFixed(3), "-i", win.path,
- ...(blurred ? ["-vf", `gblur=sigma=${sigma}:steps=3`] : []),
+ ...(cen.length ? cen : blurred ? ["-vf", `gblur=sigma=${sigma}:steps=3`] : []),
"-frames:v", "1", still,
]);
}
@@ -8035,6 +8174,8 @@ async function main() {
" [--only <id>] [--fetch-only <id>] [--short <id>] (a vertical short of one clip: <project>/shorts/<id>.mp4)\n" +
" [--join-preview [--join-from <id>]] (the first few joins, a few seconds each side: out/join-preview.mp4)\n" +
" [--vertical [--vertical-knobs <json>] [--vertical-work <dir>] [--vertical-out <file>]] (the cut 9:16: out/<slug>.vertical.mp4)\n" +
+ " [--desktop [--desktop-knobs <json>] [--vertical-work <dir>] [--vertical-out <file>]] (the clips 16:9, minimal chrome: out/<slug>.desktop.mp4)\n" +
+ " [--no-promo | --promo-knobs <json>] (a per-clip build's channel promo: none, or its timing)\n" +
" [--pad <s>] [--pad-before <s>] [--pad-after <s>] [--skip-fetch] [--no-network] [--audio-fallback] [--no-xfade] [--no-chapters] [--chapters-only]\n" +
" [--progress ndjson] [--continue-on-error] [--no-reuse] [--no-segment-cache]\n" +
" [--no-rail] [--rail-only] [--preview <start> <dur>]\n" +
@@ -8096,6 +8237,14 @@ async function main() {
verticalWork: flag("--vertical-work") ?? null,
verticalOut: flag("--vertical-out") ?? null,
verticalSections: flag("--vertical-sections") ? JSON.parse(flag("--vertical-sections")) : null,
+ // A DESKTOP build of the cut's clips (lane clip-kit; vertical.mjs desktopRender): 1920x1080, the picture full frame,
+ // a thin source line, words lit along its foot -- its knobs over the cut's render.desktop; the vertical's work
+ // dir and file flags name its own.
+ desktop: argv.includes("--desktop"),
+ desktopKnobs: flag("--desktop-knobs") ? JSON.parse(flag("--desktop-knobs")) : null,
+ // The channel promo (promo-card.mjs) of a per-clip build: off, or its timing over the cut's render.promo.
+ noPromo: argv.includes("--no-promo"),
+ promoKnobs: flag("--promo-knobs") ? JSON.parse(flag("--promo-knobs")) : null,
};
try {
Object.assign(opts, chromeFlags(argv));
diff --git a/umtool/report-to-video/clip-censor.mjs b/umtool/report-to-video/clip-censor.mjs
@@ -0,0 +1,214 @@
+// HIDDEN REGIONS of a clip's picture (lane clip-kit, slice E): a stream layout's chat overlay, a browser window showing
+// other people's accounts -- the same boxes on every clip cut from ONE recording, or on one clip, each for the whole
+// clip or a span of it. Privacy, not TOS: they stay on in the uncensored variant (`render.blur: "off"`), as a post
+// attachment's censor does (post-censor.mjs, whose styles, strengths and box rules these are).
+//
+// render.censor [{ video, channel?, boxes, style?, strength?, from?, to? }] per recording (≤ 16)
+// video the recording's id; `channel` its channel (default: any channel's recording of that id)
+// clip.censor false (none, not even the recording's) | { boxes, style?, strength?, from?, to? } added to them
+// boxes [[x, y, w, h] | { box: [x, y, w, h], from?, to? }] 1 to 8, fractions of the SOURCE picture;
+// a box's own from/to (source seconds) limit it to that span
+// style "blur" (default) | "black" | "pixelate"; strength 1–10 (7)
+// from, to source seconds: every box of the entry only over that span
+//
+// WHERE: on the source picture, FIRST -- before a clip's blur, its zooms and any layout -- in every path a clip is cut
+// in (a cut with or without the deck, a short, a desktop clip, Make a short), so a box is the same part of the
+// recording whatever frames it. Nothing else is touched: the sound, the captions, the header, the deck.
+//
+// PURE: no fs, no ffmpeg run.
+import { blurSigma, boxOk, pixelGrid } from "./post-censor.mjs";
+import { offsetIn } from "./gaps.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+
+export const CENSOR_STYLES = Object.freeze(["blur", "black", "pixelate"]);
+export const CENSOR_DEFAULTS = Object.freeze({ style: "blur", strength: 7 });
+export const CENSOR_BOXES_MAX = 8;
+export const CENSOR_RECORDINGS_MAX = 16;
+const ENTRY_KEYS = ["boxes", "style", "strength", "from", "to"];
+
+function spanErrors(o, where) {
+ const errors = [];
+ for (const k of ["from", "to"]) if (o[k] !== undefined && !(num(o[k]) && o[k] >= 0)) errors.push(`${where}.${k} is a source second`);
+ if (num(o.from) && num(o.to) && o.to - o.from < 0.2) errors.push(`${where}: its span ${o.from}–${o.to} is under 0.2 s`);
+ return errors;
+}
+
+/** Each thing wrong with one censor entry's boxes, style, strength and span. */
+function entryErrors(v, where) {
+ const errors = [];
+ if (!Array.isArray(v.boxes) || !v.boxes.length || v.boxes.length > CENSOR_BOXES_MAX) errors.push(`${where}.boxes is a list of 1 to ${CENSOR_BOXES_MAX} boxes: [x, y, w, h] or {box, from?, to?}`);
+ else v.boxes.forEach((b, j) => {
+ const w = `${where}.boxes[${j}]`;
+ if (Array.isArray(b)) {
+ if (!boxOk(b)) errors.push(`${w} is [x, y, w, h], fractions of the picture inside it`);
+ } else if (isObj(b)) {
+ for (const k of Object.keys(b)) if (!["box", "from", "to"].includes(k)) errors.push(`${w}.${k} is not a key (box, from, to)`);
+ if (!boxOk(b.box)) errors.push(`${w}.box is [x, y, w, h], fractions of the picture inside it`);
+ errors.push(...spanErrors(b, w));
+ } else errors.push(`${w} is [x, y, w, h] or {box, from?, to?}`);
+ });
+ if (v.style !== undefined && !CENSOR_STYLES.includes(v.style)) errors.push(`${where}.style is one of ${CENSOR_STYLES.join(", ")}`);
+ if (v.strength !== undefined && !(num(v.strength) && v.strength >= 1 && v.strength <= 10)) errors.push(`${where}.strength is 1–10`);
+ errors.push(...spanErrors(v, where));
+ return errors;
+}
+
+/** Each thing wrong with a clip's `censor` ([] when fine, or absent). */
+export function clipCensorErrors(v, where = "clip.censor") {
+ if (v === undefined || v === false) return [];
+ if (!isObj(v)) return [`${where} is false (none, not even the recording's) or {boxes, style?, strength?, from?, to?}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!ENTRY_KEYS.includes(k)) errors.push(`${where}.${k} is not a key (${ENTRY_KEYS.join(", ")})`);
+ return [...errors, ...entryErrors(v, where)];
+}
+
+/** Each thing wrong with `render.censor` ([] when fine, or absent). */
+export function renderCensorErrors(v, where = "render.censor") {
+ if (v === undefined || v === null) return [];
+ if (!Array.isArray(v) || v.length > CENSOR_RECORDINGS_MAX) return [`${where} is a list of at most ${CENSOR_RECORDINGS_MAX} recordings' boxes [{video, channel?, boxes, …}]`];
+ const errors = [];
+ v.forEach((e, i) => {
+ const w = `${where}[${i}]`;
+ if (!isObj(e)) return errors.push(`${w} is {video, channel?, boxes, style?, strength?, from?, to?}`);
+ for (const k of Object.keys(e)) if (![...ENTRY_KEYS, "video", "channel"].includes(k)) errors.push(`${w}.${k} is not a key (video, channel, ${ENTRY_KEYS.join(", ")})`);
+ if (typeof e.video !== "string" || !e.video.trim()) errors.push(`${w}.video is the recording's id`);
+ if (e.channel !== undefined && (typeof e.channel !== "string" || !e.channel.trim())) errors.push(`${w}.channel is a channel's slug`);
+ errors.push(...entryErrors(e, w));
+ });
+ return errors;
+}
+
+/** Every reason a manifest's hidden regions cannot be drawn. */
+export function validateCensor(manifest) {
+ const errors = renderCensorErrors(manifest?.render?.censor);
+ // A montage re-cuts its pictures in its own graph, which draws no boxes: refused by name, never cut showing them.
+ if (isObj(manifest?.render?.montage)) {
+ for (const e of manifest?.timeline ?? []) {
+ const n = censorRegionsOf(e, manifest.render, manifest.provenance ?? {}).length;
+ if (n) errors.push(`timeline ${e.id}: a montage cannot hide regions yet (${n} box(es)): take render.montage off, or the boxes only if the regions may show`);
+ }
+ }
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.censor === undefined) continue;
+ if (e.type !== "clip") errors.push(`timeline ${e.id ?? "?"}: censor is a clip's`);
+ else errors.push(...clipCensorErrors(e.censor, `timeline ${e.id}.censor`));
+ }
+ return errors;
+}
+
+/** Does a recording entry of `render.censor` name this clip's recording? */
+export function namesClip(rec, entry, provenance = {}) {
+ if (rec?.video !== entry?.video) return false;
+ if (rec.channel === undefined) return true;
+ return rec.channel === (entry.channel ?? provenance?.channelSlug ?? null);
+}
+
+/**
+ * The regions a clip's picture hides (PURE): its recording's (render.censor) and its own, each `{box, style,
+ * strength, from, to}` (`from`/`to` source seconds or null: the whole clip). None when the clip says `censor: false`.
+ */
+export function censorRegionsOf(entry, render, provenance = {}) {
+ if (entry?.type !== "clip" || entry.censor === false) return [];
+ const sets = [
+ ...(Array.isArray(render?.censor) ? render.censor.filter((r) => isObj(r) && namesClip(r, entry, provenance)) : []),
+ ...(isObj(entry.censor) ? [entry.censor] : []),
+ ];
+ const out = [];
+ for (const s of sets) {
+ const style = CENSOR_STYLES.includes(s.style) ? s.style : CENSOR_DEFAULTS.style;
+ const strength = num(s.strength) ? s.strength : CENSOR_DEFAULTS.strength;
+ for (const b of Array.isArray(s.boxes) ? s.boxes : []) {
+ const box = Array.isArray(b) ? b : b?.box;
+ if (!boxOk(box)) continue;
+ const from = num(b?.from) ? b.from : num(s.from) ? s.from : null;
+ const to = num(b?.to) ? b.to : num(s.to) ? s.to : null;
+ out.push({ box, style, strength, from, to });
+ }
+ }
+ return out;
+}
+
+/**
+ * The regions `render.censor` hides on a RECORDING (its video, and channel when known), for a player of it where no
+ * clip exists yet (the claim bench, a candidate, a cited span): its recording's boxes, none of a clip's own.
+ */
+export const recordingRegionsOf = (video, channel, render, provenance = {}) =>
+ typeof video === "string" && video ? censorRegionsOf({ type: "clip", id: "~recording", video, ...(typeof channel === "string" && channel ? { channel } : {}) }, render, provenance) : [];
+
+const f3 = (n) => Number(n).toFixed(3);
+
+/**
+ * The filtergraph parts that hide `regions` on a picture of `width`×`height` px (`[vIn]` → `[vOut]`, labels without
+ * brackets): each box blurred or pixelated (split, cropped, laid back over) or filled black, over its span on the
+ * segment's clock (`from` the source second the segment starts at, `gaps` the cut's). Empty when there are none:
+ * the graph is the one it always was.
+ */
+export function censorParts(vIn, vOut, regions, { width, height, from = 0, gaps = [], seconds = Infinity }) {
+ if (!regions?.length) return [];
+ const parts = [];
+ let cur = vIn;
+ regions.forEach((g, j) => {
+ const x = Math.round(g.box[0] * width);
+ const y = Math.round(g.box[1] * height);
+ const w = Math.max(2, 2 * Math.round(Math.min(width - x, g.box[2] * width) / 2));
+ const h = Math.max(2, 2 * Math.round(Math.min(height - y, g.box[3] * height) / 2));
+ const a = g.from === null ? null : Math.max(0, offsetIn(g.from, from, gaps));
+ const b = g.to === null ? null : Math.min(seconds, offsetIn(g.to, from, gaps));
+ const enable = a === null && b === null ? "" : `:enable='between(t,${f3(a ?? 0)},${f3(b ?? 1e6)})'`;
+ const next = j === regions.length - 1 ? vOut : `${vOut}_c${j}`;
+ if (g.style === "black") {
+ parts.push(`[${cur}]drawbox=x=${x}:y=${y}:w=${w}:h=${h}:color=black@1:t=fill${enable}[${next}]`);
+ } else {
+ const fx = g.style === "pixelate"
+ ? (() => {
+ const [nx, ny] = pixelGrid(g.strength, g.box[2], g.box[3], width, height);
+ return `scale=${nx}:${ny}:flags=neighbor,scale=${w}:${h}:flags=neighbor`;
+ })()
+ : `gblur=sigma=${blurSigma(g.strength, width)}:steps=3`;
+ parts.push(`[${cur}]split[${vOut}_s${j}a][${vOut}_s${j}b]`, `[${vOut}_s${j}b]crop=${w}:${h}:${x}:${y},${fx}[${vOut}_s${j}c]`, `[${vOut}_s${j}a][${vOut}_s${j}c]overlay=x=${x}:y=${y}${enable}[${next}]`);
+ }
+ cur = next;
+ });
+ return parts;
+}
+
+/** What a cut record says of the regions it hid (rounded). */
+export const censorRecordOf = (regions) => regions.map((g) => ({ box: g.box, style: g.style, ...(g.style !== "black" ? { strength: g.strength } : {}), ...(g.from !== null ? { from: g.from } : {}), ...(g.to !== null ? { to: g.to } : {}) }));
+
+/**
+ * Why segments on disk cannot take this cut (`--chrome-only`, `--chrome-preview`): a clip whose recorded hidden
+ * regions are not the ones this cut asks for -- a box added, moved or taken off since it was cut. The regions are in
+ * the segment's picture, so a changed set needs the segment again: refused by name, never laid over uncensored.
+ * A clip with no picture (a poster plays) records that it had nothing to hide.
+ */
+export function censorProblems({ entries, records, render, provenance = {} }) {
+ const wrong = [];
+ entries.forEach((e, i) => {
+ if (e?.type !== "clip") return;
+ const want = censorRecordOf(censorRegionsOf(e, render, provenance));
+ const rec = records[i] ?? null;
+ if (rec?.censorNoPicture === true) return;
+ const got = Array.isArray(rec?.censor) ? rec.censor : [];
+ if (JSON.stringify(want) === JSON.stringify(got)) return;
+ wrong.push(`${e.id} (${got.length} box(es) hidden on disk, ${want.length} asked for)`);
+ });
+ if (!wrong.length) return [];
+ return [
+ `${wrong.length} segment(s) hide other regions than this cut asks for: ${wrong.join(", ")}. ` +
+ "The hidden regions are in the segment's picture -- run a normal build (with --skip-fetch it re-cuts from the cached windows), not a chrome pass.",
+ ];
+}
+
+/**
+ * The regions a STILL of a clip at source second `at` hides (those over it), drawn on a frame `width`×`height`:
+ * ffmpeg args (`-filter_complex`, a graph from [0:v] to [cstill], `-map`) or none. `after` filters (a blur) follow.
+ */
+export function stillCensorArgs(regions, at, { width, height }, after = []) {
+ const over = (regions ?? []).filter((g) => (g.from === null || g.from <= at + 1e-6) && (g.to === null || at <= g.to + 1e-6)).map((g) => ({ ...g, from: null, to: null }));
+ if (!over.length && !after.length) return [];
+ const parts = over.length ? censorParts("0:v", after.length ? "cstill0" : "cstill", over, { width, height }) : [];
+ if (after.length) parts.push(`[${over.length ? "cstill0" : "0:v"}]${after.join(",")}[cstill]`);
+ return ["-filter_complex", parts.join(";"), "-map", "[cstill]"];
+}
diff --git a/umtool/report-to-video/clip-censor.test.mjs b/umtool/report-to-video/clip-censor.test.mjs
@@ -0,0 +1,152 @@
+// Hidden regions (lane clip-kit, slice E): the rules, a recording's boxes on every clip of it, a clip's own, the graph.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { recordingRegionsOf, censorParts, censorProblems, censorRecordOf, censorRegionsOf, clipCensorErrors, namesClip, renderCensorErrors, stillCensorArgs, validateCensor } from "./clip-censor.mjs";
+import { buildVideo, segmentFraming, setProgressMode } from "./build-video.mjs";
+import { mergeCensor, withOverrides } from "./vertical-plan.mjs";
+import { parseBox, withRecording } from "../lib/report/censorCli.mjs";
+
+const clip = (o = {}) => ({ type: "clip", id: "c1", channel: "chan", video: "rec1", start: 100, end: 160, ...o });
+const CHAT = { video: "rec1", boxes: [[0.75, 0, 0.25, 1]], style: "pixelate" };
+const TAB = { video: "rec1", channel: "chan", boxes: [{ box: [0, 0.6, 0.3, 0.4], from: 120, to: 130 }] };
+
+test("the rules: boxes of the picture (1 to 8), a box's own span, a style and a strength; per recording, its video", () => {
+ assert.deepEqual(renderCensorErrors([CHAT, TAB]), []);
+ assert.deepEqual(clipCensorErrors({ boxes: [[0.1, 0.1, 0.2, 0.2]], style: "black", from: 101, to: 110 }), []);
+ assert.deepEqual(clipCensorErrors(false), []);
+ const no = (v, re, f = clipCensorErrors) => assert.match(f(v).join("\n"), re, JSON.stringify(v));
+ no({ boxes: [] }, /a list of 1 to 8 boxes/);
+ no({ boxes: [[0.9, 0, 0.3, 1]] }, /boxes\[0\] is \[x, y, w, h\]/);
+ no({ boxes: [{ box: [0, 0, 0.5, 0.5], from: 5, to: 5.1 }] }, /under 0\.2 s/);
+ no({ boxes: [[0, 0, 0.5, 0.5]], style: "smudge" }, /style is one of blur, black, pixelate/);
+ no({ boxes: [[0, 0, 0.5, 0.5]], strength: 20 }, /strength is 1–10/);
+ no("yes", /is false \(none, not even the recording's\)/);
+ no([{ boxes: [[0, 0, 0.5, 0.5]] }], /video is the recording's id/, renderCensorErrors);
+ no([{ ...CHAT, hidden: true }], /hidden is not a key/, renderCensorErrors);
+ assert.match(validateCensor({ render: {}, timeline: [{ type: "post", id: "p", censor: false }] }).join(), /censor is a clip's/);
+});
+
+test("a clip's regions: its recording's (any channel, or the one named) and its own; `censor: false` none at all", () => {
+ assert.ok(namesClip(CHAT, clip()) && namesClip(TAB, clip()) && !namesClip(TAB, clip({ channel: "other" })) && !namesClip(CHAT, clip({ video: "rec2" })));
+ const r = censorRegionsOf(clip({ censor: { boxes: [[0.1, 0.1, 0.1, 0.1]], style: "black" } }), { censor: [CHAT, TAB] });
+ assert.deepEqual(r.map((g) => [g.style, g.from, g.to]), [["pixelate", null, null], ["blur", 120, 130], ["black", null, null]]);
+ assert.deepEqual(censorRegionsOf(clip({ censor: false }), { censor: [CHAT] }), []);
+ assert.deepEqual(censorRegionsOf(clip({ video: "rec2" }), { censor: [CHAT] }), []);
+ // The channel from the provenance when the clip names none.
+ assert.equal(censorRegionsOf({ type: "clip", video: "rec1" }, { censor: [TAB] }, { channelSlug: "chan" }).length, 1);
+});
+
+test("the graph: blurred and pixelated regions split, cut and laid back; black filled; a span on the segment's clock; none: nothing", () => {
+ assert.deepEqual(censorParts("0:v", "vcen", [], { width: 1920, height: 1080 }), []);
+ const regions = censorRegionsOf(clip({ censor: { boxes: [[0, 0, 0.1, 0.1]], style: "black" } }), { censor: [CHAT, TAB] });
+ const parts = censorParts("0:v", "vcen", regions, { width: 1920, height: 1080, from: 110, gaps: [{ from: 115, to: 117 }], seconds: 40 });
+ assert.equal(parts[0], "[0:v]split[vcen_s0a][vcen_s0b]");
+ assert.match(parts[1], /^\[vcen_s0b\]crop=480:1080:1440:0,scale=\d+:\d+:flags=neighbor,scale=480:1080:flags=neighbor\[vcen_s0c\]$/);
+ assert.equal(parts[2], "[vcen_s0a][vcen_s0c]overlay=x=1440:y=0[vcen_c0]");
+ assert.match(parts[4], /gblur=sigma=/);
+ // 120–130 source s, from 110 with 2 s of gap before: 8–18 on the segment's clock.
+ assert.equal(parts[5], "[vcen_s1a][vcen_s1c]overlay=x=0:y=648:enable='between(t,8.000,18.000)'[vcen_c1]");
+ assert.equal(parts[6], "[vcen_c1]drawbox=x=0:y=0:w=192:h=108:color=black@1:t=fill[vcen]");
+});
+
+test("umtool censor's arguments: a box, a box over a span; a recording's set replaced, removed", () => {
+ assert.deepEqual(parseBox("0.75,0,0.25,1"), [0.75, 0, 0.25, 1]);
+ assert.deepEqual(parseBox("0,0.6,0.3,0.4@120-130"), { box: [0, 0.6, 0.3, 0.4], from: 120, to: 130 });
+ assert.throws(() => parseBox("a,b"), /x,y,w,h/);
+ const list = [CHAT, { video: "rec2", boxes: [[0, 0, 0.5, 0.5]] }];
+ assert.deepEqual(withRecording(list, { video: "rec1" }, { video: "rec1", boxes: [[0, 0, 1, 0.1]] }).map((r) => [r.video, r.boxes.length]), [["rec2", 1], ["rec1", 1]]);
+ assert.deepEqual(withRecording(list, { video: "rec1" }, null).map((r) => r.video), ["rec2"]);
+});
+
+test("a chrome pass is refused when the hidden regions changed since the segments were cut (censorProblems)", () => {
+ const e = clip({ censor: { boxes: [[0.1, 0.1, 0.2, 0.2]], style: "black" } });
+ const want = censorRecordOf(censorRegionsOf(e, {}, {}));
+ assert.deepEqual(censorProblems({ entries: [e], records: [{ censor: want }], render: {} }), [], "the same boxes: passes");
+ const [msg] = censorProblems({ entries: [e], records: [{}], render: {} });
+ assert.match(msg, /1 segment\(s\) hide other regions than this cut asks for: c1 \(0 box\(es\) hidden on disk, 1 asked for\)/);
+ assert.match(msg, /run a normal build/);
+ // A recording's box added since (render.censor) is a change too; one taken off as well.
+ assert.equal(censorProblems({ entries: [clip()], records: [{}], render: { censor: [CHAT] } }).length, 1);
+ assert.equal(censorProblems({ entries: [clip()], records: [{ censor: want }], render: {} }).length, 1);
+ // A clip with no picture (audio only) records that it hid nothing; legacy segments with no boxes asked pass.
+ assert.deepEqual(censorProblems({ entries: [e], records: [{ censorNoPicture: true }], render: {} }), []);
+ assert.deepEqual(censorProblems({ entries: [clip()], records: [null], render: {} }), []);
+});
+
+test("--chrome-only / --chrome-preview: built, a box added, refused before any chrome is rendered", async () => {
+ setProgressMode(() => {});
+ const dir = mkdtempSync(path.join(tmpdir(), "censor-chrome-"));
+ const env = process.env.HYPERFRAMES_BIN;
+ try {
+ const mark = path.join(dir, "rendered");
+ const stub = path.join(dir, "hf-stub.sh");
+ writeFileSync(stub, `#!/bin/sh\ntouch '${mark}'\nexit 1\n`);
+ chmodSync(stub, 0o755);
+ process.env.HYPERFRAMES_BIN = stub;
+ const render = { width: 1920, height: 1080, fps: 30, transition: 0, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" }, chrome: { engine: "hyperframes", layout: "deck", deck: {} } };
+ const manifestPath = path.join(dir, "m.json");
+ const c = { id: "c1", type: "clip", video: "a", start: 0, end: 10, date: "2024-09-05" };
+ // The segment as a build left it: no boxes.
+ const segDir = path.join(dir, "out", "sourced", "segments");
+ mkdirSync(segDir, { recursive: true });
+ writeFileSync(path.join(segDir, "c1.mp4"), "");
+ writeFileSync(path.join(segDir, "c1.cut.json"), JSON.stringify({ version: 1, framing: segmentFraming(render, false) }));
+ // Then a box on the clip, and one on its recording.
+ for (const m of [{ timeline: [{ ...c, censor: { boxes: [[0.75, 0, 0.25, 1]], style: "black" } }], render }, { timeline: [c], render: { ...render, censor: [{ video: "a", boxes: [[0, 0, 0.5, 0.5]] }] } }]) {
+ writeFileSync(manifestPath, JSON.stringify({ slug: "refuse", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, ...m }));
+ for (const opts of [{ chromeOnly: true }, { chromePreview: { at: 1, dur: 2 } }]) {
+ await assert.rejects(buildVideo({ manifestPath, opts }), /hide other regions than this cut asks for: c1/);
+ }
+ }
+ assert.equal((await import("node:fs")).existsSync(mark), false, "nothing rendered before the refusal");
+ } finally {
+ if (env === undefined) delete process.env.HYPERFRAMES_BIN;
+ else process.env.HYPERFRAMES_BIN = env;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("a montage cannot hide regions yet: refused by name, its own box or its recording's", () => {
+ const montage = { style: "punchy" };
+ assert.match(validateCensor({ render: { montage }, timeline: [clip({ censor: { boxes: [[0, 0, 0.5, 0.5]] } })] }).join(), /timeline c1: a montage cannot hide regions yet \(1 box\(es\)\)/);
+ assert.match(validateCensor({ render: { montage, censor: [CHAT] }, timeline: [clip()] }).join(), /a montage cannot hide regions yet/);
+ assert.deepEqual(validateCensor({ render: { montage }, timeline: [clip()] }), [], "a montage with no boxes as before");
+ assert.deepEqual(validateCensor({ render: { censor: [CHAT] }, timeline: [clip()] }), [], "boxes without a montage as before");
+});
+
+test("a still's boxes (stillCensorArgs): those over its second, the whole box; none, no args; a blur after them", () => {
+ const regions = censorRegionsOf(clip({ censor: { boxes: [{ box: [0.5, 0, 0.5, 1], from: 120, to: 130 }], style: "black" } }), {}, {});
+ assert.deepEqual(stillCensorArgs(regions, 110, { width: 1920, height: 1080 }), [], "outside its span: the still as it was");
+ const args = stillCensorArgs(regions, 125, { width: 1920, height: 1080 });
+ assert.equal(args[0], "-filter_complex");
+ assert.match(args[1], /drawbox=x=960:y=0:w=960:h=1080/);
+ assert.deepEqual(args.slice(2), ["-map", "[cstill]"]);
+ const blurred = stillCensorArgs(regions, 125, { width: 1920, height: 1080 }, ["gblur=sigma=20"]);
+ assert.match(blurred[1], /\[cstill0\]gblur=sigma=20\[cstill\]$/);
+});
+
+test("a batch's snapshot never takes a box off (mergeCensor, withOverrides): the clip's now and the snapshot's, both", () => {
+ const A = [0, 0, 0.2, 0.2];
+ const B = [0.5, 0.5, 0.2, 0.2];
+ assert.deepEqual(mergeCensor({ boxes: [A], style: "black" }, null), { boxes: [A], style: "black" });
+ assert.deepEqual(mergeCensor(undefined, { boxes: [B] }), { boxes: [B] });
+ assert.deepEqual(mergeCensor({ boxes: [A], style: "black" }, { boxes: [B, A], style: "blur" }).boxes, [A, B], "a union, no box twice; the clip's style");
+ assert.equal(mergeCensor({ boxes: [A] }, null).style, undefined);
+ assert.equal(mergeCensor(false, null), false, "a clip that opts out of its recording's boxes, as written");
+ assert.equal(mergeCensor(undefined, null), undefined);
+ const tl = [{ type: "clip", id: "c1", video: "v", start: 0, end: 4, censor: { boxes: [A] } }];
+ assert.deepEqual(withOverrides(tl, { c1: { censor: null, vertical: null } })[0].censor, { boxes: [A] }, "a box added after the batch is kept");
+ assert.equal("censor" in withOverrides([{ ...tl[0], censor: undefined }], { c1: { censor: null } })[0], false);
+});
+
+test("a recording's regions where no clip exists yet (recordingRegionsOf): render.censor matched on its video and channel", () => {
+ const render = { censor: [CHAT, TAB, { video: "other", boxes: [[0, 0, 0.5, 0.5]] }] };
+ assert.equal(recordingRegionsOf("rec1", "chan", render, {}).length, 2);
+ assert.equal(recordingRegionsOf("rec1", "elsewhere", render, {}).length, 1, "TAB names its channel");
+ assert.deepEqual(recordingRegionsOf("rec2", null, render, {}), []);
+ assert.deepEqual(recordingRegionsOf(null, null, render, {}), []);
+});
diff --git a/umtool/report-to-video/clip-kit-render.test.mjs b/umtool/report-to-video/clip-kit-render.test.mjs
@@ -0,0 +1,326 @@
+// The clip kit, rendered for real (lane clip-kit): a desktop clip (slice C) and a short's code (slice B) on a
+// synthetic window -- the frame's size, the code where it is said to stand, the source line's plate -- and, with
+// none of the kit's keys, a short built exactly as before.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+// The corpus the build reads metadata and cues from: set before build-video (cues.mjs) is loaded.
+const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-kit-corpus-"));
+process.env.CHANNELS_DIR = CORPUS;
+
+const { buildVideo, setProgressMode } = await import("./build-video.mjs");
+const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs");
+const { desktopQrBox, verticalQrBox } = await import("./clip-kit.mjs");
+const { clipGeometry, desktopSafeArea, safeArea } = await import("./vertical.mjs");
+
+// Every module this file reads, loaded before the first test is declared: a test declared after a top-level await
+// can start after the root's after-hook has removed the corpus (node:test ends the root once its queue is empty).
+const { probeDuration } = await import("./build-video.mjs");
+const { promoBand } = await import("./promo-card.mjs");
+const havePw = await import("@playwright/test").then((m) => !!(m.chromium ?? m.default?.chromium), () => false);
+
+test.after(() => rm(CORPUS, { recursive: true, force: true }));
+
+const have = ["ffmpeg", "ffprobe", "qrencode"].every((b) => spawnSync(b, b === "qrencode" ? ["--version"] : ["-version"]).status === 0);
+const FPS = 30;
+const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" };
+const RENDER = {
+ width: 1920, height: 1080, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0,
+ headerHeight: 0, footerHeight: 0, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE,
+ fetchPad: 0, snapWindow: 0.05, silenceMinDur: 0.1,
+};
+const CHANNEL = "synth";
+const VIDEO = "vid-0123456789";
+{
+ const dir = path.join(CORPUS, CHANNEL, "data", VIDEO);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(CORPUS, CHANNEL, "config.json"), JSON.stringify({ name: "Synth" }));
+ writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: VIDEO, title: "Synthetic", duration: 6, uploadDate: "20240102", cues: [{ start: 0.2, end: 5.8, text: "a line said over the clip" }] }));
+ writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: VIDEO, title: "Synthetic", duration: 6, webpage_url: `https://kick.com/synth/videos/${VIDEO}` }));
+}
+
+/** A project: one clip, 1–4 s of a 6 s grey 1920x1080 window with a tone. */
+async function project({ clip = {}, render = {} } = {}) {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-kit-"));
+ mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true });
+ const raw = path.join(root, "out", "clips-raw", `${VIDEO}_0.00-6.00.mp4`);
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=1920x1080:r=${FPS}:d=6`,
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=6",
+ "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "kit", title: "Kit",
+ provenance: { channelSlug: CHANNEL, channelsDir: CORPUS, siteOrigin: "" },
+ render: { ...RENDER, ...render },
+ timeline: [{ type: "clip", id: "c1", channel: CHANNEL, video: VIDEO, start: 1, end: 4, cite: 1, quote: "q", citeUrl: `https://kick.com/synth/videos/${VIDEO}`, ...clip }],
+ }));
+ return { root, manifestPath };
+}
+
+const quiet = () => setProgressMode(() => {});
+/** The picture's size. */
+function dims(file) {
+ const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]);
+ return String(r.stdout).trim();
+}
+/** The luma's min and max over a box of a frame `t` s in: a code is black and white, the grey ground is neither. */
+function range(file, box, t = 1) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", `crop=${box.w}:${box.h}:${box.x}:${box.y},signalstats,metadata=print:file=-`, "-f", "null", "-"], { maxBuffer: 1 << 24 });
+ const out = String(r.stdout);
+ const get = (k) => Number((new RegExp(`lavfi\\.signalstats\\.${k}=([0-9.]+)`).exec(out) ?? [])[1]);
+ return { min: get("YMIN"), max: get("YMAX") };
+}
+const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0];
+
+test("a desktop clip: 1920x1080, the picture full frame, the code in its corner, the source line on its plate", { skip: !have && "needs ffmpeg and qrencode" }, async () => {
+ quiet();
+ const p = await project();
+ try {
+ const out = path.join(p.root, "out", "kit.desktop.mp4");
+ await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, desktop: true, desktopKnobs: { qr: { corner: "br" } }, verticalOut: out } });
+ assert.equal(dims(out), "1920,1080");
+ const seg = path.join(p.root, "out", "desktop", "segments", "c1.mp4");
+ const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8"));
+ assert.equal(rec.vertical.layout, "desktop");
+ assert.equal(rec.vertical.qr.url, `https://kick.com/synth/videos/${VIDEO}?t=1`, "the source at the clip's second");
+ const box = desktopQrBox({ corner: "br", size: 0.09 }, { W: 1920, safe: desktopSafeArea({}, 1920, 1080) });
+ assert.deepEqual([rec.vertical.qr.x, rec.vertical.qr.y, rec.vertical.qr.size], [box.x, box.y, box.size]);
+ const inQr = range(seg, { x: box.x + 8, y: box.y + 8, w: box.size - 16, h: box.size - 16 });
+ assert.ok(inQr.min < 40 && inQr.max > 215, `the code is drawn there (${JSON.stringify(inQr)})`);
+ // The opposite corner: the grey picture alone (no letterbox, nothing drawn).
+ const bare = range(seg, { x: 60, y: 1080 - box.size - 90, w: box.size, h: box.size });
+ assert.ok(bare.min > 100 && bare.max < 150, `the picture full frame there (${JSON.stringify(bare)})`);
+ // The source line: its plate darkens the top left of the safe area.
+ const s = desktopSafeArea({}, 1920, 1080);
+ const plate = range(seg, { x: s.x0 + 4, y: s.y0 + 4, w: 40, h: 16 });
+ assert.ok(plate.min < 110, `the source line's plate (${JSON.stringify(plate)})`);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("a short's code: at the top right of the safe area; none unless asked, the short as it was", { skip: !have && "needs ffmpeg and qrencode" }, async () => {
+ quiet();
+ const ps = [await project(), await project({ render: { vertical: { qr: false } } }), await project()];
+ try {
+ const outs = ps.map((p) => path.join(p.root, "out", "kit.vertical.mp4"));
+ await buildVideo({ manifestPath: ps[0].manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: outs[0] } });
+ await buildVideo({ manifestPath: ps[1].manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: outs[1] } });
+ await buildVideo({ manifestPath: ps[2].manifestPath, opts: { noNetwork: true, vertical: true, verticalKnobs: { qr: true }, verticalOut: outs[2] } });
+ const segs = ps.map((p) => path.join(p.root, "out", "vertical", "segments", "c1.mp4"));
+ // No code asked (absent, or false): the same segment, its record naming none.
+ assert.equal(md5(segs[0]), md5(segs[1]));
+ const rec0 = JSON.parse(await readFile(segs[0].replace(/\.mp4$/, ".cut.json"), "utf8"));
+ assert.equal(rec0.vertical.qr, undefined);
+ assert.equal(dims(outs[2]), "1080,1920");
+ const rec = JSON.parse(await readFile(segs[2].replace(/\.mp4$/, ".cut.json"), "utf8"));
+ const geo = clipGeometry("full", { format: "vertical" }, 1080, 1920);
+ const box = verticalQrBox({ corner: "tr", size: 0.16 }, { W: 1080, safe: safeArea({ format: "vertical" }, 1080, 1920), tag: geo.tag });
+ assert.deepEqual([rec.vertical.qr.x, rec.vertical.qr.y, rec.vertical.qr.corner], [box.x, box.y, "tr"]);
+ const inQr = range(segs[2], { x: box.x + 8, y: box.y + 8, w: box.size - 16, h: box.size - 16 });
+ assert.ok(inQr.min < 40 && inQr.max > 215, `the code is drawn there (${JSON.stringify(inQr)})`);
+ const without = range(segs[0], { x: box.x + 8, y: box.y + 8, w: box.size - 16, h: box.size - 16 });
+ assert.ok(without.max < 200, `no code without one asked (${JSON.stringify(without)})`);
+ } finally {
+ for (const p of ps) await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+// ---- slice D: the channel promo -------------------------------------------------------------------------------------
+
+/** The picture's mean luma at `t` s. */
+function yavg(file, t) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", "signalstats,metadata=print:file=-", "-f", "null", "-"], { maxBuffer: 1 << 24 });
+ return Number((/lavfi\.signalstats\.YAVG=([0-9.]+)/.exec(String(r.stdout)) ?? [])[1]);
+}
+/** The RMS of a file's sound over [a, b] (s), mono 8 kHz. */
+function rms(file, a, b) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 26 });
+ const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, Math.floor(r.stdout.length / 2));
+ let sum = 0;
+ let n = 0;
+ for (let i = Math.floor(a * 8000); i < Math.min(pcm.length, Math.floor(b * 8000)); i += 1) {
+ sum += pcm[i] * pcm[i];
+ n += 1;
+ }
+ return n ? Math.sqrt(sum / n) : 0;
+}
+
+const PROMO = { name: ["Example Channel", "Live"], url: "https://kick.com/synth", portrait: { file: "shots/face.png" }, lead: 2, fade: 0.5, hold: 1 };
+async function promoProject(o = {}) {
+ const p = await project({ render: { promo: PROMO }, ...o });
+ mkdirSync(path.join(p.root, "shots"), { recursive: true });
+ const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=400x400:d=1", "-frames:v", "1", path.join(p.root, "shots", "face.png")]);
+ assert.equal(r.status, 0, String(r.stderr));
+ return p;
+}
+
+test("the promo: the clip dissolves into the card over its last seconds, its sound under it, then the card held in silence", { skip: (!have || !havePw) && "needs ffmpeg, qrencode and Playwright's chromium" }, async () => {
+ quiet();
+ for (const fmt of ["vertical", "desktop"]) {
+ const p = await promoProject();
+ try {
+ const out = path.join(p.root, "out", `kit.${fmt}.mp4`);
+ await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, [fmt]: true, verticalOut: out } });
+ const seg = path.join(p.root, "out", fmt, "segments", "c1.mp4");
+ const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8"));
+ assert.deepEqual([rec.promo.lead, rec.promo.fade, rec.promo.hold, rec.promo.captions], [2, 0.5, 1, true], fmt);
+ const S = 3; // the clip: 1–4 s
+ const d = await probeDuration(seg, FPS);
+ assert.ok(Math.abs(d - (S + 1)) <= 2 / FPS, `${fmt}: the segment is the clip and the hold (${d})`);
+ assert.ok(yavg(seg, S - 2 - 0.4) > 100, `${fmt}: the clip before the card`);
+ assert.ok(yavg(seg, S - 2 + 0.5 + 0.4) < 70, `${fmt}: the card up while the clip still plays`);
+ assert.ok(yavg(seg, S + 0.6) < 70, `${fmt}: the card held`);
+ assert.ok(rms(seg, S - 1.5, S - 0.3) > 800, `${fmt}: the clip's sound under the card`);
+ assert.ok(rms(seg, S + 0.1, S + 0.95) < 20, `${fmt}: silence on the card`);
+ // The captions over the card stand in its band.
+ const ass = await readFile(seg.replace(/\.mp4$/, ".vertical.ass"), "utf8");
+ const [W, H] = fmt === "vertical" ? [1080, 1920] : [1920, 1080];
+ const band = promoBand({ width: W, height: H }).band;
+ assert.match(ass, new RegExp(`\\\\pos\\(\\d+,${band.y1}\\)`), `${fmt}: a caption in the card's band`);
+ assert.equal(dims(out), fmt === "vertical" ? "1080,1920" : "1920,1080");
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+ }
+});
+
+test("the promo: a clip's `promo: false` ends without it, exactly as a cut that sets none", { skip: (!have || !havePw) && "needs ffmpeg, qrencode and Playwright's chromium" }, async () => {
+ quiet();
+ const ps = [await project(), await promoProject({ clip: { promo: false } })];
+ try {
+ for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: path.join(p.root, "out", "kit.vertical.mp4") } });
+ const segs = ps.map((p) => path.join(p.root, "out", "vertical", "segments", "c1.mp4"));
+ assert.equal(md5(segs[0]), md5(segs[1]));
+ assert.equal(JSON.parse(await readFile(segs[1].replace(/\.mp4$/, ".cut.json"), "utf8")).promo, undefined);
+ } finally {
+ for (const p of ps) await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+// ---- slice F: zoom at points ----------------------------------------------------------------------------------------
+/** The mean luma of a box of a frame `t` s in. */
+function boxAvg(file, box, t) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", `crop=${box.w}:${box.h}:${box.x}:${box.y},signalstats,metadata=print:file=-`, "-f", "null", "-"], { maxBuffer: 1 << 24 });
+ return Number((/lavfi\.signalstats\.YAVG=([0-9.]+)/.exec(String(r.stdout)) ?? [])[1]);
+}
+
+test("a zoom: the framed short's picture pushed in on its focus for its span, eased back out; refused past the sharp limit", { skip: !have && "needs ffmpeg and qrencode" }, async () => {
+ quiet();
+ // A window whose left half is white and right half black: pushed in on its left edge, the picture is mostly white.
+ const p = await project({ render: { vertical: { clip: "framed" } }, clip: { zooms: [{ at: 1.5, scale: 1.75, focus: [0, 0.5], hold: 1, ramp: 0.3 }] } });
+ const raw = path.join(p.root, "out", "clips-raw", `${VIDEO}_0.00-6.00.mp4`);
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=black:s=1920x1080:r=${FPS}:d=6`, "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=6",
+ "-filter_complex", "[0:v]drawbox=x=0:y=0:w=960:h=1080:c=white:t=fill[v]", "-map", "[v]", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ try {
+ await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: path.join(p.root, "out", "kit.vertical.mp4") } });
+ const seg = path.join(p.root, "out", "vertical", "segments", "c1.mp4");
+ const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8"));
+ assert.deepEqual([rec.zooms[0].at, rec.zooms[0].scale, rec.zooms[0].focus], [0.5, 1.75, [0, 0.5]]);
+ const v = clipGeometry("framed", { format: "vertical" }, 1080, 1920).video;
+ const box = { x: 0, y: v.y + 40, w: 1080, h: v.h - 80 };
+ const before = boxAvg(seg, box, 0.2);
+ const pushed = boxAvg(seg, box, 1.3);
+ const after = boxAvg(seg, box, 2.6);
+ assert.ok(before > 100 && before < 150, `half white before (${before})`);
+ assert.ok(pushed > 180, `pushed in on the white (${pushed})`);
+ assert.ok(Math.abs(after - before) < 12, `back out after (${after} vs ${before})`);
+ // Past the sharp limit (a 1080 window in a full 9:16 crop is already past its pixels): refused, by name.
+ const m = JSON.parse(await readFile(p.manifestPath, "utf8"));
+ m.render.vertical = { clip: "full" };
+ await writeFile(p.manifestPath, JSON.stringify(m));
+ await assert.rejects(buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: path.join(p.root, "out", "kit2.vertical.mp4") } }), /zooms: c1: the zoom at 1\.5 s \(×1\.75\) plays its source at .* the limit here is ×1/);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+// ---- the corner code in every entry type a cut with no deck draws (review B1) ---------------------------------------
+test("a cut with no deck, the QR on and off: a clip, a still with a citeUrl, a title card and a video entry all build; the codes where they always were", { skip: !have && "needs ffmpeg and qrencode" }, async () => {
+ quiet();
+ for (const qr of [{ scale: 4 }, false, { corner: "tl" }]) {
+ const p = await project({ render: { width: 640, height: 360, headerHeight: 0, qr } });
+ try {
+ mkdirSync(path.join(p.root, "stills"), { recursive: true });
+ const still = path.join(p.root, "stills", "one.png");
+ const vid = path.join(p.root, "stills", "v.mp4");
+ assert.equal(spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=640x360:d=1", "-frames:v", "1", still]).status, 0);
+ assert.equal(spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=640x360:r=${FPS}:d=2`, "-f", "lavfi", "-i", "sine=frequency=330:sample_rate=48000:duration=2", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", vid]).status, 0);
+ const m = JSON.parse(await readFile(p.manifestPath, "utf8"));
+ m.timeline.push(
+ { type: "image", id: "i1", src: "stills/one.png", seconds: 1.5, citeUrl: "https://example.test/still/1" },
+ { type: "card", id: "k1", style: "title", heading: "A heading", seconds: 2 },
+ { type: "video", id: "v1", src: "stills/v.mp4" },
+ );
+ await writeFile(p.manifestPath, JSON.stringify(m));
+ const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ assert.ok(r.out, `built (qr ${JSON.stringify(qr)})`);
+ const segs = path.join(p.root, "out", "sourced", "segments");
+ if (qr === false) continue;
+ // The still's code: bottom right (as it always was), or the cut's corner.
+ const size = 64;
+ const at = qr.corner === "tl" ? { x: 28 + 4, y: 28 + 4 } : { x: 640 - 28 - size + 8, y: 360 - 28 - size + 8 };
+ const box = { ...at, w: 24, h: 24 };
+ const inStill = range(path.join(segs, "i1.mp4"), box, 0.5);
+ assert.ok(inStill.max > 215 || inStill.min < 40, `the still's code is drawn at its corner (qr ${JSON.stringify(qr)}: ${JSON.stringify(inStill)})`);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+ }
+});
+
+// ---- slice E: hidden regions ----------------------------------------------------------------------------------------
+test("hidden regions: a recording's box on every clip of it, in a cut and in a short; a box over a span; on in the uncensored cut; another recording's changes nothing", { skip: !have && "needs ffmpeg and qrencode" }, async () => {
+ quiet();
+ // The window is a grey picture with WHITE in its right quarter (a stand-in chat overlay); the box blacks it out.
+ const white = async (p) => {
+ const raw = path.join(p.root, "out", "clips-raw", `${VIDEO}_0.00-6.00.mp4`);
+ const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=1920x1080:r=${FPS}:d=6`, "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=6",
+ "-filter_complex", "[0:v]drawbox=x=1440:y=0:w=480:h=1080:c=white:t=fill[v]", "-map", "[v]", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw]);
+ assert.equal(r.status, 0, String(r.stderr));
+ };
+ const CHAT = { video: VIDEO, boxes: [[0.75, 0, 0.25, 1]], style: "black" };
+ const ps = [
+ await project({ render: { qr: false, censor: [CHAT], blur: "off" } }),
+ await project({ render: { qr: false, censor: [{ ...CHAT, boxes: [{ box: [0.75, 0, 0.25, 1], from: 2.5, to: 4 }] }] } }),
+ await project({ render: { qr: false } }),
+ await project({ render: { qr: false, censor: [{ ...CHAT, video: "another-recording" }] } }),
+ ];
+ try {
+ for (const p of ps) await white(p);
+ for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ const seg = (p) => path.join(p.root, "out", "sourced", "segments", "c1.mp4");
+ const right = { x: 1500, y: 300, w: 300, h: 300 };
+ // The whole clip, in the uncensored variant too: black where the overlay was.
+ assert.ok(boxAvg(seg(ps[0]), right, 1) < 40, `hidden (${boxAvg(seg(ps[0]), right, 1)})`);
+ assert.deepEqual(JSON.parse(await readFile(seg(ps[0]).replace(/\.mp4$/, ".cut.json"), "utf8")).censor, [{ box: [0.75, 0, 0.25, 1], style: "black" }]);
+ // Over its span only (source 2.5–4 s, the clip from 1 s): shown at 0.5 s, hidden at 2 s.
+ assert.ok(boxAvg(seg(ps[1]), right, 0.5) > 200 && boxAvg(seg(ps[1]), right, 2) < 40, "over its span");
+ // Another recording's boxes change nothing: the segment as with none.
+ assert.equal(md5(seg(ps[3])), md5(seg(ps[2])));
+ assert.equal(JSON.parse(await readFile(seg(ps[2]).replace(/\.mp4$/, ".cut.json"), "utf8")).censor, undefined);
+ // A short of the same clip: the box is the same part of the recording (hidden under its framed layout too).
+ const m = JSON.parse(await readFile(ps[0].manifestPath, "utf8"));
+ m.render.vertical = { clip: "framed" };
+ await writeFile(ps[0].manifestPath, JSON.stringify(m));
+ await buildVideo({ manifestPath: ps[0].manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: path.join(ps[0].root, "out", "kit.vertical.mp4") } });
+ const v = clipGeometry("framed", { format: "vertical" }, 1080, 1920).video;
+ const vseg = path.join(ps[0].root, "out", "vertical", "segments", "c1.mp4");
+ assert.ok(boxAvg(vseg, { x: 860, y: v.y + 100, w: 180, h: 200 }, 1) < 40, "hidden in the short's picture");
+ } finally {
+ for (const p of ps) await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/clip-kit.mjs b/umtool/report-to-video/clip-kit.mjs
@@ -0,0 +1,241 @@
+// THE CLIP KIT's rules (lane clip-kit): the keys a clip carries for a per-clip build (a short, a desktop clip, a
+// batch), checked here once -- the writer (lib/report/manifest.mjs updateClip), `umtool set`, the lint and the build
+// all call these. This file holds the QR's (slice B); each later slice adds its keys.
+//
+// render.qr false | { scale?, quiet?, ecc?, margin?, corner?, links? } the corner code of a cut with no deck
+// corner "br" (the default: where it always was) | "bl" | "tr" | "tl"
+// links "cite" (the default: the clip's citeUrl, else its moment on the archive -- as it always was)
+// | "moment" (the SOURCE at the second the clip starts playing: platformSeek.mjs's rule)
+// | "channel" (the promo's channel page, render.promo.url)
+// render.vertical.qr false (the default) | true | { corner?: "tr" | "tl", size?, links? } a code on a 9:16 short
+// (its links default "moment": the operator asked for "a QR to the channel at the timestamp")
+// clip.qr false (no code on this clip) | { corner?, links? } over the cut's
+//
+// A MOMENT link is the clip's own recording at the second it plays from (the build's snapped start):
+// - its citeUrl, when that names this recording (it carries the clip's video id), retimed with watchUrlAt;
+// - else, with no citeUrl, the record's webpage_url at the second;
+// - else (a citeUrl that names another recording: a mirror the cut cites on purpose) the citeUrl as written.
+// Kick's time parameter is not confirmed (common/lib/platformSeek.mjs): watchUrlAt writes `?t=<s>` there, and the
+// lint notes that a Kick (or Twitch) VOD is deleted after its retention, so the code stops opening.
+//
+// PURE: no fs, no ffmpeg.
+import { watchUrlAt } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { VOD_RETENTION_DAYS, seekPlatformOfUrl } from "yt-dlp-transcript-common/lib/platformSeek.mjs";
+import { DESKTOP_QR_CORNERS, DESKTOP_QR_SIZE, QR_LINKS, VERTICAL_QR_CORNERS, VERTICAL_QR_KEYS, VERTICAL_QR_SIZE, desktopKnobs, verticalQrErrors } from "yt-dlp-transcript-common/lib/report/vertical.mjs";
+import { archiveMomentUrl } from "./site-links.mjs";
+import { clipPromoErrors } from "./promo-card.mjs";
+import { zoomsErrors } from "./clip-zoom.mjs";
+import { clipCensorErrors } from "./clip-censor.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const q = (v) => JSON.stringify(v);
+
+export const QR_CORNERS = Object.freeze(["br", "bl", "tr", "tl"]);
+/** The keys of `render.qr` (the first four the corner code always read). */
+export const QR_KEYS = Object.freeze(["scale", "quiet", "ecc", "margin", "corner", "links"]);
+export { QR_LINKS, VERTICAL_QR_CORNERS, VERTICAL_QR_KEYS, VERTICAL_QR_SIZE, verticalQrErrors };
+
+/** The keys a clip may carry for the kit (vertical-plan.mjs reads them from the project over a take's). */
+export const CLIP_KIT_KEYS = Object.freeze(["qr", "name", "promo", "zooms", "coldOpen", "censor"]);
+
+/** A cold open's length (s): refused outside the hard bounds, noted outside the soft ones (what reads best). */
+export const COLD_OPEN = Object.freeze({ min: 1, max: 4, softMin: 1.5, softMax: 3 });
+/** A clip's pinned file name in a batch (shortsBatch.mjs): at most this many characters. */
+export const CLIP_NAME_MAX = 60;
+
+/** Each thing wrong with `render.qr`'s new keys ([] when fine). The older keys are as unchecked as they were. */
+export function qrSettingsErrors(qr, where = "render.qr") {
+ if (qr === undefined || qr === null || qr === false || qr === true) return [];
+ if (!isObj(qr)) return [`${where} is false or {${QR_KEYS.join(", ")}}`];
+ const errors = [];
+ if (qr.corner !== undefined && !QR_CORNERS.includes(qr.corner)) errors.push(`${where}.corner is one of ${QR_CORNERS.join(", ")}, not ${q(qr.corner)}`);
+ if (qr.links !== undefined && !QR_LINKS.includes(qr.links)) errors.push(`${where}.links is one of ${QR_LINKS.join(", ")}, not ${q(qr.links)}`);
+ return errors;
+}
+
+/** Each thing wrong with a clip's kit keys ([] when fine), named `<where>.<key>`. */
+export function clipKitErrors(entry, where = "clip", { writer = false } = {}) {
+ const errors = [];
+ if (!isObj(entry)) return errors;
+ if (entry.qr !== undefined && entry.qr !== false) {
+ if (!isObj(entry.qr)) errors.push(`${where}.qr is false (no code on this clip) or {corner?, links?}`);
+ else {
+ for (const k of Object.keys(entry.qr)) if (!["corner", "links"].includes(k)) errors.push(`${where}.qr.${k} is not a key (corner, links)`);
+ errors.push(...qrSettingsErrors({ corner: entry.qr.corner, links: entry.qr.links }, `${where}.qr`));
+ }
+ }
+ if (entry.name !== undefined && !(typeof entry.name === "string" && entry.name.trim() && entry.name.length <= CLIP_NAME_MAX)) {
+ errors.push(`${where}.name is a file name of 1 to ${CLIP_NAME_MAX} characters`);
+ }
+ // Its channel promo (promo-card.mjs): false, or its own timing.
+ errors.push(...clipPromoErrors(entry.promo, `${where}.promo`));
+ // Its zooms (clip-zoom.mjs): against its cut when written (a zoom the cut does not play is refused), against its
+ // window at a build (a cut tightened since leaves one out, said).
+ errors.push(...zoomsErrors(entry.zooms, `${where}.zooms`, entry, { cut: writer }));
+ // Its cold open: a span of its own cut, played first.
+ errors.push(...coldOpenErrors(entry.coldOpen, `${where}.coldOpen`, entry));
+ // Its hidden regions (clip-censor.mjs).
+ errors.push(...clipCensorErrors(entry.censor, `${where}.censor`));
+ if ((entry.qr !== undefined || entry.name !== undefined || entry.promo !== undefined || entry.zooms !== undefined || entry.coldOpen !== undefined || entry.censor !== undefined) && entry.type !== undefined && entry.type !== "clip") {
+ errors.push(`${where}: qr, name, promo, zooms, coldOpen and censor are a clip's`);
+ }
+ return errors;
+}
+
+/**
+ * Each thing wrong with a clip's `coldOpen` ([] when fine, or absent): `{from, to}`, source seconds inside the clip's
+ * cut (its cutStart–cutEnd, else its window), 1–4 s long -- the payoff a short or a desktop clip plays FIRST, then
+ * cuts to the clip's start.
+ */
+export function coldOpenErrors(v, where = "clip.coldOpen", entry = null) {
+ if (v === undefined) return [];
+ if (!isObj(v)) return [`${where} is {from, to}: source seconds of the clip's cut, played first`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!["from", "to"].includes(k)) errors.push(`${where}.${k} is not a key (from, to)`);
+ const num = (n) => typeof n === "number" && Number.isFinite(n);
+ if (!num(v.from) || !num(v.to) || v.to <= v.from) return [...errors, `${where} is {from, to}, from before to (source seconds)`];
+ const len = v.to - v.from;
+ if (len < COLD_OPEN.min - 1e-6 || len > COLD_OPEN.max + 1e-6) errors.push(`${where} is ${Math.round(len * 100) / 100} s: a cold open is ${COLD_OPEN.min}–${COLD_OPEN.max} s`);
+ const a = num(entry?.cutStart) ? entry.cutStart : entry?.start;
+ const b = num(entry?.cutEnd) ? entry.cutEnd : entry?.end;
+ if (num(a) && num(b) && (v.from < a - 0.02 || v.to > b + 0.02)) errors.push(`${where} (${v.from}–${v.to}) is outside the clip's cut (${a}–${b})`);
+ else if (num(a) && num(b) && v.from <= a + 0.02 && v.to >= b - 0.02) errors.push(`${where} (${v.from}–${v.to}) is the whole cut: a cold open plays a part of it first`);
+ // A gap (a jump cut taken out of the clip) inside or across it: refused, never a cold open silently shorter.
+ const clip = where.replace(/\.coldOpen$/, "").replace(/^timeline /, "");
+ for (const g of Array.isArray(entry?.gaps) ? entry.gaps : []) {
+ if (!num(g?.from) || !num(g?.to)) continue;
+ if (g.from < v.to - 0.02 && g.to > v.from + 0.02) {
+ errors.push(`${where} (${v.from}–${v.to}) runs across ${clip}'s gap ${g.from}–${g.to} s (a jump cut taken out): move it off the gap, or take the gap out`);
+ }
+ }
+ return errors;
+}
+
+/** A NOTE for a cold open outside what reads best (1.5–3 s), or null. */
+export function coldOpenNote(entry, where) {
+ const v = entry?.coldOpen;
+ if (!isObj(v) || typeof v.from !== "number" || typeof v.to !== "number") return null;
+ const len = v.to - v.from;
+ return len < COLD_OPEN.softMin || len > COLD_OPEN.softMax ? `${where}: its cold open is ${Math.round(len * 100) / 100} s; ${COLD_OPEN.softMin}–${COLD_OPEN.softMax} s reads best` : null;
+}
+
+/** Every clip's kit errors in a manifest, and the render's QR settings' ([] when fine). */
+export function validateClipKit(manifest) {
+ // render.vertical.qr is checked with the vertical knobs (common vertical.mjs validateVerticalRender).
+ const errors = [...qrSettingsErrors(manifest?.render?.qr)];
+ for (const e of manifest?.timeline ?? []) errors.push(...clipKitErrors(e, `timeline ${e?.id ?? "?"}`));
+ const wantsChannel = [manifest?.render?.qr?.links, isObj(manifest?.render?.vertical?.qr) ? manifest.render.vertical.qr.links : null, ...(manifest?.timeline ?? []).map((e) => (isObj(e?.qr) ? e.qr.links : null))].includes("channel");
+ if (wantsChannel && !(typeof manifest?.render?.promo?.url === "string" && /^https?:\/\//.test(manifest.render.promo.url))) {
+ errors.push("a QR's links is \"channel\", which is the channel promo's page: set render.promo.url (an https link)");
+ }
+ return errors;
+}
+
+/** Does `url` name the recording `video` (its id is in it)? */
+export const namesRecording = (url, video) => typeof url === "string" && typeof video === "string" && video.length >= 4 && url.includes(video);
+
+/**
+ * The source at a second: the clip's citeUrl retimed when it names this recording, else the record's page at it,
+ * else the citeUrl as written (a mirror cited on purpose), else null.
+ *
+ * @param {{ citeUrl?: string, video?: string }} entry
+ * @param {number} at the source second the clip starts playing from
+ * @param {string | null} [webpageUrl] its record's webpage_url
+ */
+export function momentLinkOf(entry, at, webpageUrl = null) {
+ const cite = typeof entry?.citeUrl === "string" && entry.citeUrl ? entry.citeUrl : null;
+ if (cite && namesRecording(cite, entry.video)) return watchUrlAt(cite, at) ?? cite;
+ if (!cite && webpageUrl) return watchUrlAt(webpageUrl, at);
+ return cite;
+}
+
+/**
+ * The code's settings a clip draws with: off (null) for `render.qr: false` or `clip.qr: false`, else
+ * `{corner, links}` -- the clip's over the cut's, the defaults (`br`, `cite`) under both.
+ */
+export function cornerQrOf(entry, render) {
+ if (render?.qr === false || entry?.qr === false) return null;
+ const cut = isObj(render?.qr) ? render.qr : {};
+ const own = isObj(entry?.qr) ? entry.qr : {};
+ return { corner: own.corner ?? cut.corner ?? "br", links: own.links ?? cut.links ?? "cite" };
+}
+
+/** A 9:16 short's code: null when off (the default), else `{corner, size, links}`. A clip's `qr` speaks over it. */
+export function verticalQrOf(entry, render) {
+ const v = render?.vertical?.qr;
+ if (!v || entry?.qr === false) return null;
+ const cut = isObj(v) ? v : {};
+ const own = isObj(entry?.qr) ? entry.qr : {};
+ const corner = own.corner && VERTICAL_QR_CORNERS.includes(own.corner) ? own.corner : cut.corner ?? "tr";
+ return { corner, size: cut.size ?? VERTICAL_QR_SIZE.default, links: own.links ?? cut.links ?? "moment" };
+}
+
+/** A desktop clip's code (render.desktop.qr): null when off (the default), else `{corner, size, links}`; a clip's `qr` speaks over it. */
+export function desktopQrOf(entry, render) {
+ const v = desktopKnobs(render).qr;
+ if (!v || entry?.qr === false) return null;
+ const cut = isObj(v) ? v : {};
+ const own = isObj(entry?.qr) ? entry.qr : {};
+ const corner = DESKTOP_QR_CORNERS.includes(own.corner) ? own.corner : cut.corner ?? "br";
+ return { corner, size: cut.size ?? DESKTOP_QR_SIZE.default, links: own.links ?? cut.links ?? "moment" };
+}
+
+/** Where a desktop clip's code stands, px: in its corner of the safe area (`safe` vertical.mjs desktopSafeArea's). */
+export function desktopQrBox(qr, { W, safe }) {
+ const size = Math.max(2, 2 * Math.round((W * qr.size) / 2));
+ const x = qr.corner === "bl" || qr.corner === "tl" ? safe.x0 : safe.x1 - size;
+ const y = qr.corner === "tl" || qr.corner === "tr" ? safe.y0 : safe.y1 - size;
+ return { x, y, size };
+}
+
+/**
+ * The link a clip's code carries. `links` "cite" is the corner code's link as it always was (the citeUrl, else the
+ * clip's moment on the archive); "moment" the source at `at` (momentLinkOf), falling back to that; "channel" the
+ * promo's page. Null: no link to draw (a `src` clip with no citeUrl).
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} provenance
+ * @param {{ links?: string, at?: number | null, webpageUrl?: string | null, channelUrl?: string | null, local?: boolean }} [o]
+ * `local`: the clip plays a file of its own (`src`).
+ */
+export function clipQrUrl(entry, provenance, { links = "cite", at = null, webpageUrl = null, channelUrl = null, local = false } = {}) {
+ if (local && !entry.citeUrl) return null;
+ const cite = () => entry.citeUrl ?? archiveMomentUrl(entry, provenance, entry.start);
+ if (links === "channel" && channelUrl) return channelUrl;
+ if (links === "moment") return momentLinkOf(entry, Number.isFinite(at) ? at : entry.cutStart ?? entry.start, webpageUrl) ?? cite();
+ return cite();
+}
+
+/**
+ * The overlay that places the corner code (ffmpeg `overlay` x/y): `br` is the one the build always drew,
+ * byte for byte. `VW` the picture's width, `FH` the footer's height, `HH` the header's, `m` the margin.
+ */
+export function cornerOverlayXY(corner, { VW, FH = 0, HH = 0, m = 28 }) {
+ const x = corner === "bl" || corner === "tl" ? `${m}` : `${VW}-w-${m}`;
+ const y = corner === "tr" || corner === "tl" ? `${HH + m}` : `H-h-${FH + m}`;
+ return `x=${x}:y=${y}`;
+}
+
+/**
+ * Where a 9:16 short's code stands, px: under the top band, at the safe area's right (`tr`) or left (`tl`) edge; a
+ * code at the left stands under the source tag. `safe` is vertical.mjs safeArea's; `tag` its geometry's tag.
+ */
+export function verticalQrBox(qr, { W, safe, tag = null }) {
+ const size = Math.max(2, 2 * Math.round((W * qr.size) / 2));
+ const top = safe.y0 + Math.round(W * 0.02);
+ const y = qr.corner === "tl" && tag ? Math.max(top, tag.y + Math.round(tag.size * 1.9)) : top;
+ const x = qr.corner === "tl" ? safe.x0 : safe.x1 - size;
+ return { x, y, size };
+}
+
+/**
+ * A NOTE (never a refusal) for a code that links a stream's VOD on a platform that deletes them: the code stops
+ * opening after the retention (platformSeek.mjs VOD_RETENTION_DAYS). Null for any other link.
+ */
+export function expiringLinkNote(url, where) {
+ const p = seekPlatformOfUrl(url);
+ const days = p ? VOD_RETENTION_DAYS[p] : undefined;
+ if (!days || !/\/videos?\//.test(String(url))) return null;
+ const name = p === "kick" ? "Kick" : "Twitch";
+ return `${where}: its QR links a ${name} VOD (${url}); ${name} deletes VODs about ${days} days after the stream, so the code will stop opening then — link the channel instead (qr links "channel") if it must last`;
+}
diff --git a/umtool/report-to-video/clip-kit.test.mjs b/umtool/report-to-video/clip-kit.test.mjs
@@ -0,0 +1,184 @@
+// The clip kit's QR (lane clip-kit, slice B): the corner, the link at the clip's second, a short's code, the notes --
+// and, with none of the new keys, the corner code exactly as it always was.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ clipKitErrors, clipQrUrl, cornerOverlayXY, cornerQrOf, expiringLinkNote, momentLinkOf, namesRecording, qrSettingsErrors,
+ validateClipKit, verticalQrBox, verticalQrOf,
+} from "./clip-kit.mjs";
+import { archiveMomentUrl } from "./site-links.mjs";
+import { qrsOf, lintManifest } from "./lint.mjs";
+import { safeArea, clipGeometry, validateVerticalRender, verticalKnobs } from "./vertical.mjs";
+
+const KICK = "https://kick.com/somechan/videos/01a1d292-6d30-7092-867d-d46a2db2f3e8";
+const clip = (o = {}) => ({ type: "clip", id: "w01", video: "01a1d292-6d30-7092-867d-d46a2db2f3e8", start: 10643.6, end: 10764, ...o });
+
+test("no new keys: the corner code is where it always was, with the link it always had", () => {
+ // The overlay the build drew before the kit, byte for byte.
+ const VW = 1920, FH = 0, qrM = 28;
+ assert.equal(cornerOverlayXY("br", { VW, FH, HH: 56, m: qrM }), `x=${VW}-w-${qrM}:y=H-h-${FH + qrM}`);
+ assert.equal(cornerOverlayXY("br", { VW: 1600, FH: 40, m: 20 }), "x=1600-w-20:y=H-h-60");
+ assert.deepEqual(cornerQrOf(clip(), {}), { corner: "br", links: "cite" });
+ const prov = { siteOrigin: "https://archive.example", channelSlug: "chan" };
+ const e = clip({ channel: "chan" });
+ assert.equal(clipQrUrl(e, prov), archiveMomentUrl(e, prov, e.start));
+ assert.equal(clipQrUrl(clip({ citeUrl: KICK }), prov), KICK);
+ assert.equal(clipQrUrl(clip({ citeUrl: null, src: "a.mp4" }), prov, { local: true }), null);
+ // The lint's corner codes: the same links as before.
+ const m = { render: { width: 1920, height: 1080 }, provenance: prov, timeline: [e, clip({ id: "w02", citeUrl: KICK })] };
+ assert.deepEqual(qrsOf(m).map((q) => [q.url, "links" in q]), [[archiveMomentUrl(e, prov, e.start), false], [KICK, false]]);
+ assert.deepEqual(validateClipKit(m), []);
+ // A short asks for no code: none (the vertical knobs' default).
+ assert.equal(verticalKnobs({ format: "vertical" }).qr, false);
+ assert.equal(verticalQrOf(clip(), { format: "vertical" }), null);
+});
+
+test("the corners, a clip's own over the cut's, off for one clip", () => {
+ assert.equal(cornerOverlayXY("tl", { VW: 1920, HH: 56, m: 28 }), "x=28:y=84");
+ assert.equal(cornerOverlayXY("tr", { VW: 1920, HH: 0, m: 28 }), "x=1920-w-28:y=28");
+ assert.equal(cornerOverlayXY("bl", { VW: 1920, FH: 0, m: 28 }), "x=28:y=H-h-28");
+ assert.deepEqual(cornerQrOf(clip({ qr: { corner: "tl" } }), { qr: { corner: "bl", links: "moment" } }), { corner: "tl", links: "moment" });
+ assert.equal(cornerQrOf(clip({ qr: false }), {}), null);
+ assert.equal(cornerQrOf(clip(), { qr: false }), null);
+});
+
+test("a moment link: this recording's citeUrl retimed; a mirror kept; else the record's page; the channel", () => {
+ // The citeUrl names this recording (its id is in it): retimed to the second the clip plays from.
+ assert.equal(momentLinkOf(clip({ citeUrl: KICK }), 10643.9), `${KICK}?t=10643`);
+ assert.equal(momentLinkOf(clip({ citeUrl: `${KICK}?t=10600` }), 10643.9), `${KICK}?t=10643`);
+ // A mirror (another recording): as written.
+ assert.equal(momentLinkOf(clip({ citeUrl: "https://www.youtube.com/watch?v=mirror1&t=5s" }), 99), "https://www.youtube.com/watch?v=mirror1&t=5s");
+ // No citeUrl: the record's page at the second.
+ assert.equal(momentLinkOf(clip(), 61.2, "https://www.youtube.com/watch?v=abc"), "https://www.youtube.com/watch?v=abc&t=61s");
+ assert.equal(momentLinkOf(clip(), 61.2, null), null);
+ assert.ok(namesRecording(KICK, "01a1d292-6d30-7092-867d-d46a2db2f3e8"));
+ assert.equal(namesRecording(KICK, "abc"), false, "an id too short to tell is not taken as a match");
+ const prov = { siteOrigin: "https://archive.example", channelSlug: "chan" };
+ assert.equal(clipQrUrl(clip({ citeUrl: KICK }), prov, { links: "moment", at: 10650 }), `${KICK}?t=10650`);
+ // No moment to link: the cite as before.
+ assert.equal(clipQrUrl(clip({ channel: "chan" }), prov, { links: "moment", at: 5 }), archiveMomentUrl(clip({ channel: "chan" }), prov, 10643.6));
+ assert.equal(clipQrUrl(clip({ citeUrl: KICK }), prov, { links: "channel", channelUrl: "https://kick.com/somechan" }), "https://kick.com/somechan");
+});
+
+test("the rules refuse what cannot be drawn, by name", () => {
+ assert.deepEqual(qrSettingsErrors({ scale: 4, corner: "tl", links: "moment" }), []);
+ assert.match(qrSettingsErrors({ corner: "middle" }).join(), /render\.qr\.corner is one of br, bl, tr, tl/);
+ assert.match(qrSettingsErrors({ links: "site" }).join(), /render\.qr\.links is one of cite, moment, channel/);
+ assert.match(clipKitErrors({ type: "clip", qr: { corner: "tl", size: 2 } }, "w01").join(), /w01\.qr\.size is not a key/);
+ assert.match(clipKitErrors({ type: "clip", qr: "yes" }, "w01").join(), /w01\.qr is false/);
+ assert.match(clipKitErrors({ type: "clip", name: "x".repeat(61) }, "w01").join(), /w01\.name is a file name of 1 to 60/);
+ assert.match(clipKitErrors({ type: "post", qr: false }, "p1").join(), /qr, name, promo, zooms, coldOpen and censor are a clip's/);
+ assert.match(validateClipKit({ render: { qr: { links: "channel" } }, timeline: [] }).join(), /set render\.promo\.url/);
+ assert.deepEqual(validateClipKit({ render: { qr: { links: "channel" }, promo: { url: "https://kick.com/somechan" } }, timeline: [] }), []);
+ // A short's code: at the top only (its captions run along the foot), a size in bounds.
+ assert.deepEqual(validateVerticalRender({ render: { vertical: { qr: { corner: "tl", size: 0.2, links: "moment" } } } }), []);
+ assert.match(validateVerticalRender({ render: { vertical: { qr: { corner: "br" } } } }).join(), /corner is tr or tl/);
+ assert.match(validateVerticalRender({ render: { vertical: { qr: { size: 0.5 } } } }).join(), /size is 0\.1–0\.3/);
+});
+
+test("a short's code: on, the moment by default, at the top of the safe area, never over the tag", () => {
+ const render = { format: "vertical", vertical: { qr: true } };
+ assert.deepEqual(verticalQrOf(clip(), render), { corner: "tr", size: 0.16, links: "moment" });
+ assert.deepEqual(verticalQrOf(clip({ qr: { corner: "tl", links: "cite" } }), render), { corner: "tl", size: 0.16, links: "cite" });
+ assert.equal(verticalQrOf(clip({ qr: false }), render), null);
+ // A clip's bottom corner is the landscape code's: a short keeps its own corner.
+ assert.equal(verticalQrOf(clip({ qr: { corner: "br" } }), render).corner, "tr");
+ const W = 1080, H = 1920;
+ const safe = safeArea(render, W, H);
+ for (const layout of ["full", "framed", "quote", "split"]) {
+ const geo = clipGeometry(layout, render, W, H);
+ for (const corner of ["tr", "tl"]) {
+ const b = verticalQrBox({ corner, size: 0.16 }, { W, safe, tag: geo.tag });
+ assert.ok(b.x >= safe.x0 && b.x + b.size <= safe.x1 && b.y >= safe.y0 && b.y + b.size <= safe.y1, `${layout} ${corner} inside the safe area`);
+ if (corner === "tl" && geo.tag) assert.ok(b.y >= geo.tag.y + geo.tag.size, `${layout}: under the tag`);
+ }
+ }
+});
+
+test("a moment code to a Kick or Twitch VOD is a NOTE naming the expiry; a channel page or YouTube is not", () => {
+ assert.match(expiringLinkNote(`${KICK}?t=10643`, "w01"), /w01: its QR links a Kick VOD .* about 30 days/);
+ assert.match(expiringLinkNote("https://www.twitch.tv/videos/123?t=1h0m0s", "w01"), /Twitch deletes VODs about 14 days/);
+ assert.equal(expiringLinkNote("https://kick.com/somechan", "w01"), null);
+ assert.equal(expiringLinkNote("https://www.youtube.com/watch?v=abc&t=5s", "w01"), null);
+ // In the lint: a warning for a moment code, none for the same link cited as it always was.
+ const base = { render: { width: 1920, height: 1080 }, provenance: { siteOrigin: "https://archive.example" } };
+ const moment = lintManifest({ ...base, render: { ...base.render, qr: { links: "moment" } }, timeline: [clip({ citeUrl: KICK })] }, { validators: false });
+ assert.ok(moment.warnings.some((w) => /Kick deletes VODs/.test(w)), moment.warnings.join("\n"));
+ assert.equal(moment.errors.length, 0, moment.errors.join("\n"));
+ // A citeUrl that is itself a Kick VOD is noted too (review); an archive link is not.
+ const cite = lintManifest({ ...base, timeline: [clip({ citeUrl: KICK })] }, { validators: false });
+ assert.ok(cite.warnings.some((w) => /Kick deletes VODs/.test(w)), cite.warnings.join("\n"));
+ const archive = lintManifest({ ...base, provenance: { siteOrigin: "https://archive.example", channelSlug: "chan" }, timeline: [clip({ channel: "chan" })] }, { validators: false });
+ assert.ok(!archive.warnings.some((w) => /deletes VODs/.test(w)));
+ // A stacked-deck 9:16 cut draws no vertical code: none is listed.
+ const stacked = { ...base, render: { width: 1080, height: 1920, format: "vertical", vertical: { qr: true, deck: "stacked" }, chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { show: false } } } }, timeline: [clip({ citeUrl: KICK })] };
+ assert.ok(!qrsOf(stacked).some((q) => /\(its QR\)/.test(q.where)));
+ // A short's code is measured and noted too.
+ const short = lintManifest({ ...base, render: { width: 1080, height: 1920, format: "vertical", qr: false, vertical: { qr: true } }, timeline: [clip({ citeUrl: KICK })] }, { validators: false });
+ assert.ok(short.warnings.some((w) => /timeline w01 \(its QR\): its QR links a Kick VOD/.test(w)), short.warnings.join("\n"));
+});
+
+// ---- slice C: the desktop clip --------------------------------------------------------------------------------------
+import { desktopGeometry, desktopRender, desktopSafeArea, verticalAss } from "./vertical.mjs";
+import { DESKTOP_DEFAULTS, desktopKnobs, validateDesktopRender } from "yt-dlp-transcript-common/lib/report/vertical.mjs";
+import { desktopQrBox, desktopQrOf } from "./clip-kit.mjs";
+import { knobsForFormat } from "../lib/report/shortsBatch.mjs";
+import { desktopKnobsOf } from "../lib/report/verticalCli.mjs";
+
+test("desktop: the knobs' defaults are minimal chrome; the rules refuse by name", () => {
+ assert.deepEqual(desktopKnobs({}), { ...DESKTOP_DEFAULTS, captions: { ...DESKTOP_DEFAULTS.captions }, safe: { ...DESKTOP_DEFAULTS.safe } });
+ assert.equal(desktopKnobs({}).qr, false);
+ assert.equal(desktopKnobs({}).maxSeconds, 140, "X's 2:20");
+ assert.deepEqual(validateDesktopRender({ render: { desktop: { qr: { corner: "bl", size: 0.1, links: "moment" }, captions: { size: "m", lines: 1 }, hook: "title" } } }), []);
+ assert.match(validateDesktopRender({ render: { desktop: { qr: { corner: "middle" } } } }).join(), /render\.desktop\.qr\.corner is one of br, bl, tr, tl/);
+ assert.match(validateDesktopRender({ render: { desktop: { wide: true } } }).join(), /render\.desktop\.wide is not a desktop knob/);
+ assert.match(validateDesktopRender({ render: { desktop: { safe: { top: 0.5 } } } }).join(), /safe\.top must be a fraction/);
+ assert.deepEqual(validateDesktopRender({ render: {} }), []);
+ // The render: 1920x1080, nothing over the picture but what the clip draws, the desktop's loudness; marked a desktop build.
+ const r = desktopRender({ width: 1280, height: 720, headerHeight: 56, qr: { corner: "tl" }, chrome: { deck: {} }, intro: "boot", desktop: { loudness: -16 } });
+ assert.deepEqual([r.width, r.height, r.headerHeight, r.footerHeight, r.qr, r.chrome, r.intro, r.desktopBuild], [1920, 1080, 0, 0, false, undefined, undefined, true]);
+ assert.deepEqual(r.loudness, { target: -16 });
+});
+
+test("desktop: every text inside the safe area; a bottom code narrows the captions both sides; a top-left code moves the source line", () => {
+ const W = 1920, H = 1080;
+ const a = desktopSafeArea({}, W, H);
+ const g = desktopGeometry({}, W, H);
+ assert.deepEqual(g.video, { x: 0, y: 0, w: W, h: H, aspect: W / H, fill: "fit" }, "the picture full frame, never cropped");
+ assert.ok(g.tag.x >= a.x0 && g.tag.y >= a.y0);
+ assert.equal(g.captions.marginV, H - a.y1);
+ assert.equal(g.captions.marginL, a.x0);
+ const qr = desktopQrBox({ corner: "br", size: 0.09 }, { W, safe: a });
+ assert.ok(qr.x + qr.size <= a.x1 && qr.y + qr.size <= a.y1 && qr.x >= a.x0);
+ const gq = desktopGeometry({}, W, H, { qr });
+ assert.equal(gq.captions.marginL - g.captions.marginL, gq.captions.marginR - g.captions.marginR, "centred");
+ assert.ok(W - gq.captions.marginR <= qr.x, "the captions end before the code");
+ const tl = desktopQrBox({ corner: "tl", size: 0.09 }, { W, safe: a });
+ assert.ok(desktopGeometry({}, W, H, { qr: tl }).tag.x >= tl.x + tl.size, "the source line beside the code");
+ // A clip's own corner over the cut's; the moment by default; off unless asked.
+ assert.equal(desktopQrOf({ type: "clip" }, {}), null);
+ assert.deepEqual(desktopQrOf({ type: "clip", qr: { corner: "tl" } }, { desktop: { qr: true } }), { corner: "tl", size: 0.09, links: "moment" });
+ assert.equal(desktopQrOf({ type: "clip", qr: false }, { desktop: { qr: true } }), null);
+});
+
+test("desktop: the ASS reads the desktop's lines and tag; the vertical's are unchanged without knobs", () => {
+ const words = [{ text: "one", start: 0.1, end: 0.4 }, { text: "two", start: 0.5, end: 0.8 }];
+ const g = desktopGeometry({}, 1920, 1080);
+ const doc = verticalAss({ geo: g, render: {}, words, seconds: 2, tag: "Synth · 2 Jan 2024", W: 1920, H: 1080, knobs: desktopKnobs({ desktop: { tag: false } }) });
+ assert.match(doc, /PlayResX: 1920\nPlayResY: 1080/);
+ assert.ok(!/,tag,,0,0,0,,Synth/.test(doc), "the desktop's tag: false is read");
+ assert.match(verticalAss({ geo: g, render: {}, words, seconds: 2, tag: "Synth", W: 1920, H: 1080, knobs: desktopKnobs({}) }), /,tag,,0,0,0,,Synth/);
+ // Without knobs: the vertical's, exactly the document it always wrote.
+ const vg = clipGeometry("full", {}, 1080, 1920);
+ assert.equal(verticalAss({ geo: vg, render: {}, words, seconds: 2, tag: "Synth" }), verticalAss({ geo: vg, render: {}, words, seconds: 2, tag: "Synth", knobs: null }));
+});
+
+test("desktop: the flags' knobs; a batch keeps a short's code at the top", () => {
+ assert.deepEqual(desktopKnobsOf({ clip: "framed", hook: "title", captions: { size: "xl", lines: 1 }, loudness: -16, maxSeconds: 140, qr: { corner: "bl" } }), { hook: "title", captions: { size: "xl", lines: 1 }, loudness: -16, maxSeconds: 140, qr: { corner: "bl" } });
+ assert.deepEqual(knobsForFormat({ qr: { corner: "bl" } }, "desktop"), { knobs: { qr: { corner: "bl" } }, note: null });
+ const v = knobsForFormat({ qr: { corner: "bl" }, clip: "framed" }, "vertical");
+ assert.deepEqual(v.knobs, { qr: true, clip: "framed" });
+ assert.match(v.note, /top right/);
+ assert.deepEqual(knobsForFormat({ qr: { corner: "tl" } }, "vertical").knobs, { qr: { corner: "tl" } });
+});
diff --git a/umtool/report-to-video/clip-zoom.mjs b/umtool/report-to-video/clip-zoom.mjs
@@ -0,0 +1,199 @@
+// ZOOM AT POINTS in a per-clip build (lane clip-kit, slice F): a clip of a short or a desktop clip pushes in on a
+// part of its picture for a moment, eased in and out -- the operator: "we may want to zoom in at points".
+//
+// clip.zooms [{ at, hold?, scale?, focus?: [x, y], box?: [x, y, w, h], ramp? }] 1 to 8, none overlapping
+// at the source second the push starts (inside the clip's window; gap-aware)
+// hold seconds held at full zoom (0.3–10; 1.5)
+// scale how far in (1.05–3; 1.3) -- or `box`, the part of the SOURCE picture to fill the frame with
+// focus the point that stays where it is on screen, fractions of the source picture ([0.5, 0.5]; a box's
+// centre)
+// ramp the ease in, and out again (0.2–1 s; 0.4; smoothstep)
+// render.zooms { soften?: 1–1.3 } how much softer than the layout's resting picture a zoom may play (absent: 1)
+//
+// IN SOURCE SPACE, BEFORE THE LAYOUT. The picture is pushed in about `focus` and the layout then cuts it as it always
+// does: a short's 9:16 crop (`vertical.crop`) is the same box, the focus keeps its place on screen and the picture
+// grows around it; a desktop clip's full frame likewise. Captions, the source line, the code and the promo card are
+// drawn after it and never zoom.
+//
+// SHARP. A layout already shows its source at some enlargement, `rest` (a 1080 window fitted into the 1080x608 box
+// of a framed short: 0.56; cropped 9:16 to fill 1080x1920: 1.78; a desktop clip: 1.0; from a 720 window 1.5× that).
+// A zoom multiplies it: the picture plays at rest × scale its source's pixels. THE REFERENCE is the coarser of the
+// source's own pixels and the layout's resting picture, max(1, rest): a zoom may play its source at no more than
+// that -- the sharp limit is the scale that reaches it, max(1, 1 / rest), so where the layout already enlarges (a
+// full 9:16 crop, a desktop clip from a 720 window) a strict cut cannot zoom. Past it is refused, by name -- unless
+// the project allows a SOFT zoom, `render.zooms.soften` (1–1.3): the picture may then play up to `soften` times the
+// reference (rest × scale ≤ soften × max(1, rest)), and the build says how much softer than its source it plays.
+// NOT a cap on the total enlargement past the source's pixels: a full 9:16 crop already plays its 1080 source at
+// 1.78×, and capping that total at 1.3 would leave a full short (and a desktop clip from 720 windows) no zoom at all.
+//
+// PURE: no fs, no ffmpeg run. The build (build-video.mjs) draws it with ffmpeg's perspective (zoomFilters).
+import { offsetIn } from "./gaps.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+
+export const ZOOM_KEYS = Object.freeze(["at", "hold", "scale", "focus", "box", "ramp"]);
+export const ZOOM_LIMITS = Object.freeze({
+ hold: Object.freeze({ min: 0.3, max: 10, default: 1.5 }),
+ scale: Object.freeze({ min: 1.05, max: 3, default: 1.3 }),
+ ramp: Object.freeze({ min: 0.2, max: 1, default: 0.4 }),
+});
+export const ZOOMS_MAX = 8;
+/** `render.zooms.soften`: how far past the reference, max(1, rest), a zoom may play its source (1: strict). */
+export const ZOOM_SOFT = Object.freeze({ min: 1, max: 1.3, default: 1 });
+
+/** A zoom's span on a clock: from `at`, eased in over `ramp`, held, eased out over `ramp`. */
+export const zoomEnd = (z) => z.at + 2 * (z.ramp ?? ZOOM_LIMITS.ramp.default) + (z.hold ?? ZOOM_LIMITS.hold.default);
+
+/**
+ * Each thing wrong with a clip's `zooms` ([] when fine, or absent). `entry` its window (start, end), when known;
+ * `cut` (the writer): against its cut (cutStart–cutEnd, else its window), a zoom it does not play refused.
+ */
+export function zoomsErrors(zooms, where = "clip.zooms", entry = null, { cut = false } = {}) {
+ if (zooms === undefined) return [];
+ if (!Array.isArray(zooms) || !zooms.length || zooms.length > ZOOMS_MAX) return [`${where} is a list of 1 to ${ZOOMS_MAX} zooms [{at, hold?, scale?, focus?, box?, ramp?}]`];
+ const errors = [];
+ zooms.forEach((z, i) => {
+ const w = `${where}[${i}]`;
+ if (!isObj(z)) return errors.push(`${w} is {at, hold?, scale?, focus?, box?, ramp?}`);
+ for (const k of Object.keys(z)) if (!ZOOM_KEYS.includes(k)) errors.push(`${w}.${k} is not a key (${ZOOM_KEYS.join(", ")})`);
+ if (!num(z.at) || z.at < 0) errors.push(`${w}.at is a source second`);
+ else if (entry && num(entry.start) && num(entry.end)) {
+ const a = cut && num(entry.cutStart) ? entry.cutStart : entry.start;
+ const b = cut && num(entry.cutEnd) ? entry.cutEnd : entry.end;
+ const span = cut && (num(entry.cutStart) || num(entry.cutEnd)) ? "cut" : "window";
+ if (z.at < a - 0.02 || zoomEnd(z) > b + 0.02) errors.push(`${w} (${z.at}–${Math.round(zoomEnd(z) * 100) / 100} s) runs outside the clip's ${span} (${a}–${b})`);
+ }
+ for (const [k, b] of Object.entries(ZOOM_LIMITS)) if (z[k] !== undefined && !(num(z[k]) && z[k] >= b.min && z[k] <= b.max)) errors.push(`${w}.${k} is ${b.min}–${b.max}`);
+ if (z.focus !== undefined && !(Array.isArray(z.focus) && z.focus.length === 2 && z.focus.every((n) => num(n) && n >= 0 && n <= 1))) errors.push(`${w}.focus is [x, y], fractions of the picture`);
+ if (z.box !== undefined) {
+ const b = z.box;
+ if (!(Array.isArray(b) && b.length === 4 && b.every(num) && b[2] > 0.02 && b[3] > 0.02 && b[0] >= 0 && b[1] >= 0 && b[0] + b[2] <= 1.001 && b[1] + b[3] <= 1.001)) errors.push(`${w}.box is [x, y, w, h], fractions of the picture inside it`);
+ if (z.scale !== undefined || z.focus !== undefined) errors.push(`${w}: a box says its own scale and focus -- give box, or scale and focus`);
+ }
+ });
+ const ok = zooms.filter((z) => isObj(z) && num(z.at)).sort((a, b) => a.at - b.at);
+ for (let i = 1; i < ok.length; i += 1) {
+ if (ok[i].at < zoomEnd(ok[i - 1]) - 1e-6) errors.push(`${where}: the zoom at ${ok[i].at} s starts before the one at ${ok[i - 1].at} s is out again (${Math.round(zoomEnd(ok[i - 1]) * 100) / 100} s)`);
+ }
+ return errors;
+}
+
+/** Each thing wrong with `render.zooms` ([] when fine, or absent). */
+export function renderZoomsErrors(v, where = "render.zooms") {
+ if (v === undefined || v === null) return [];
+ if (!isObj(v)) return [`${where} is {soften}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (k !== "soften") errors.push(`${where}.${k} is not a key (soften)`);
+ if (v.soften !== undefined && !(num(v.soften) && v.soften >= ZOOM_SOFT.min && v.soften <= ZOOM_SOFT.max)) {
+ errors.push(`${where}.soften is ${ZOOM_SOFT.min}–${ZOOM_SOFT.max}: how much softer than the layout's resting picture (or the source's own pixels, if sharper) a zoom may play (1: never)`);
+ }
+ return errors;
+}
+
+/** Every reason a manifest's zooms cannot be drawn. */
+export function validateZooms(manifest) {
+ const errors = renderZoomsErrors(manifest?.render?.zooms);
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.zooms === undefined) continue;
+ if (e.type !== "clip") errors.push(`timeline ${e.id ?? "?"}: zooms are a clip's`);
+ else errors.push(...zoomsErrors(e.zooms, `timeline ${e.id}.zooms`, e));
+ }
+ return errors;
+}
+
+/**
+ * The enlargement a layout shows its source at, before any zoom: the frame's pixels over the source's for the part
+ * of the source it shows. `region` that part ({w, h}, px of the source); `box` the frame's box it fills ({w, h}).
+ * A fitted picture is the smaller ratio.
+ */
+export const restEnlargement = (region, box) => Math.min(box.w / region.w, box.h / region.h);
+
+/** The sharp limit: the zoom at which the picture reaches its source's own pixels (never under 1). */
+export const sharpLimit = (rest) => Math.max(1, 1 / rest);
+
+/**
+ * Each zoom resolved for a segment (PURE): its clock in the segment's seconds (`from` the source second it starts at,
+ * `gaps` the cut's), its scale (a box's derived from the region the layout shows) and focus, and how sharp it plays.
+ * `region` px of the source the layout shows ({x, y, w, h}); `rest` its enlargement; `soften` the soft limit.
+ * Returns `{zooms, errors, notes}`: a zoom past its limit is an error naming it, one past the sharp limit (soft,
+ * allowed) a note.
+ */
+export function resolveZooms(entry, { from, gaps = [], srcW, srcH, region, rest, soften = 1, seconds = Infinity, id = entry?.id ?? "clip" }) {
+ const zooms = [];
+ const errors = [];
+ const notes = [];
+ const sharp = sharpLimit(rest);
+ const ceiling = sharp * Math.max(1, Math.min(ZOOM_SOFT.max, soften));
+ const round = (n) => Math.round(n * 100) / 100;
+ for (const z of Array.isArray(entry?.zooms) ? entry.zooms : []) {
+ const ramp = z.ramp ?? ZOOM_LIMITS.ramp.default;
+ const hold = z.hold ?? ZOOM_LIMITS.hold.default;
+ let scale = z.scale ?? ZOOM_LIMITS.scale.default;
+ let focus = Array.isArray(z.focus) ? z.focus : null;
+ if (Array.isArray(z.box)) {
+ const [bx, by, bw, bh] = z.box;
+ scale = Math.min(region.w / (bw * srcW), region.h / (bh * srcH));
+ focus = [bx + bw / 2, by + bh / 2];
+ }
+ focus ??= [(region.x + region.w / 2) / srcW, (region.y + region.h / 2) / srcH];
+ const at = offsetIn(z.at, from, gaps);
+ const what = `${id}: the zoom at ${z.at} s (×${round(scale)})`;
+ // A push outside what this segment plays (a cut tighter than its window, a reel's part): not drawn, said.
+ if (at < -0.05 || at + 2 * ramp + hold > seconds + 0.05) {
+ notes.push(`${what} is outside what plays here (${round(from)} s on, ${round(seconds)} s) -- left out`);
+ continue;
+ }
+ if (scale <= 1.001) {
+ notes.push(`${what} shows no more than the layout already does -- left out`);
+ continue;
+ }
+ if (scale > ceiling + 1e-6) {
+ const ways = ["a smaller zoom", "a sharper source (render.tallWindows)", ...(soften < ZOOM_SOFT.max ? [`a soft limit (umtool look <p> zooms='{"soften":${ZOOM_SOFT.max}}')`] : [])];
+ errors.push(`${what} plays its source at ${round(rest * scale)}× its pixels; the limit here is ×${round(ceiling)} (${soften > 1 ? `render.zooms.soften ${soften} times ` : ""}the sharp ×${round(sharp)}) -- ${ways.join(", ")}`);
+ continue;
+ }
+ if (rest * scale > 1.001) notes.push(`${what} plays softer than its source: ${round(rest * scale)}× its pixels`);
+ zooms.push({ at: Math.max(0, at), ramp, hold, scale, focus });
+ }
+ return { zooms, errors, notes };
+}
+
+const f = (n) => Number(n).toFixed(4);
+
+/** The eased zoom of one push at `t` (an ffmpeg expression): 0 outside it, smoothstep up, held, smoothstep down. */
+function pushExpr(z, t) {
+ const a = z.at;
+ const b = a + z.ramp;
+ const c = b + z.hold;
+ const d = c + z.ramp;
+ const up = `((${t}-${f(a)})/${f(z.ramp)})`;
+ const down = `((${f(d)}-${t})/${f(z.ramp)})`;
+ const ease = (u) => `(${u}*${u}*(3-2*${u}))`;
+ return `if(between(${t},${f(a)},${f(d)}),${f(z.scale - 1)}*if(lt(${t},${f(b)}),${ease(up)},if(lt(${t},${f(c)}),1,${ease(down)})),0)`;
+}
+
+/**
+ * The zoom as ONE ffmpeg filter chain on the source picture (PURE): its frames at `fps`, then the part of the picture
+ * the zoom shows mapped onto the whole frame by `perspective` -- its corners in SUB-PIXEL source coordinates,
+ * interpolated (cubic), re-evaluated each frame on the frame count -- and only over the pushes (`enable`): between
+ * them the frame passes untouched. Not zoompan, which rounds its crop's x, y and size to whole pixels each frame, so
+ * a slow ease steps back and forth (a wobble). The focus stays where it is on screen: the shown part starts at
+ * focus × (1 − 1/zoom) of the picture. Empty when there are no zooms.
+ */
+export function zoomFilters(zooms, { srcW, srcH, fps }) {
+ if (!zooms?.length) return [];
+ // perspective's `in` counts frames from 1 (enable's `n` from 0): frame n is at (in − 1) / fps.
+ const t = `((in-1)/${fps})`;
+ const Z = `(1+${zooms.map((z) => pushExpr(z, t)).join("+")})`;
+ // The focus of the push under way (a nested choice by span); outside every push the filter is off.
+ const pick = (k) => zooms.reduceRight((acc, z) => `if(between(${t},${f(z.at)},${f(zoomEnd(z))}),${f(z.focus[k])},${acc})`, "0.5");
+ const x = `${pick(0)}*W*(1-1/${Z})`;
+ const y = `${pick(1)}*H*(1-1/${Z})`;
+ const r = `${x}+W/${Z}`;
+ const b = `${y}+H/${Z}`;
+ const on = zooms.map((z) => `between(n/${fps},${f(z.at)},${f(zoomEnd(z))})`).join("+");
+ void srcW;
+ void srcH;
+ return [`fps=${fps}`, `perspective=x0='${x}':y0='${y}':x1='${r}':y1='${y}':x2='${x}':y2='${b}':x3='${r}':y3='${b}':interpolation=cubic:sense=source:eval=frame:enable='${on}'`];
+}
diff --git a/umtool/report-to-video/clip-zoom.test.mjs b/umtool/report-to-video/clip-zoom.test.mjs
@@ -0,0 +1,146 @@
+// Zoom at points (lane clip-kit, slice F): the rules, the sharp and the soft limits, the eased expression.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+
+import { renderZoomsErrors, resolveZooms, restEnlargement, sharpLimit, validateZooms, zoomEnd, zoomFilters, zoomsErrors } from "./clip-zoom.mjs";
+import { clipGeometry, desktopGeometry, pictureRegion } from "./vertical.mjs";
+
+const clip = (zooms, o = {}) => ({ type: "clip", id: "c1", start: 10, end: 40, zooms, ...o });
+
+test("the rules: a list of 1 to 8, inside the window, none overlapping; a box or a scale and focus", () => {
+ assert.deepEqual(zoomsErrors([{ at: 12 }, { at: 20, scale: 1.5, focus: [0.7, 0.3], hold: 2, ramp: 0.3 }, { at: 30, box: [0.5, 0, 0.3, 0.4] }], "z", clip()), []);
+ const no = (z, re) => assert.match(zoomsErrors(z, "z", clip()).join("\n"), re, JSON.stringify(z));
+ no([], /a list of 1 to 8/);
+ no(Array.from({ length: 9 }, (_, i) => ({ at: 11 + i * 3 })), /a list of 1 to 8/);
+ no([{ at: 39.5 }], /runs outside the clip's window/);
+ // The writer checks the cut; a build the window (a cut tightened since leaves it out, said).
+ const cut = clip(undefined, { cutStart: 15, cutEnd: 30 });
+ assert.match(zoomsErrors([{ at: 29 }], "z", cut, { cut: true }).join(), /z\[0\] \(29–31\.3 s\) runs outside the clip's cut \(15–30\)/);
+ assert.match(zoomsErrors([{ at: 12 }], "z", cut, { cut: true }).join(), /runs outside the clip's cut/);
+ assert.deepEqual(zoomsErrors([{ at: 29 }], "z", cut), [], "a build: inside its window");
+ no([{ at: 12, scale: 5 }], /scale is 1\.05–3/);
+ no([{ at: 12, focus: [2, 0] }], /focus is \[x, y\]/);
+ no([{ at: 12, box: [0.9, 0, 0.3, 0.3] }], /box is \[x, y, w, h\]/);
+ no([{ at: 12, box: [0.1, 0, 0.3, 0.3], scale: 2 }], /a box says its own scale/);
+ no([{ at: 12 }, { at: 13 }], /starts before the one at 12 s is out again \(14\.3 s\)/);
+ no([{ at: 12, wobble: 1 }], /wobble is not a key/);
+ assert.equal(zoomEnd({ at: 12 }), 14.3);
+ assert.deepEqual(renderZoomsErrors({ soften: 1.3 }), []);
+ assert.match(renderZoomsErrors({ soften: 2 }).join(), /soften is 1–1\.3/);
+ assert.match(validateZooms({ render: {}, timeline: [{ type: "post", id: "p", zooms: [{ at: 1 }] }] }).join(), /zooms are a clip's/);
+});
+
+test("sharp: a layout's rest enlargement, the sharp limit -- a framed short has room, a desktop clip and a full short none", () => {
+ const W = 1080, H = 1920;
+ const framed = pictureRegion(clipGeometry("framed", {}, W, H), 1920, 1080);
+ assert.equal(Math.round(framed.rest * 1000) / 1000, 0.563);
+ assert.equal(Math.round(sharpLimit(framed.rest) * 100) / 100, 1.78);
+ const full = pictureRegion(clipGeometry("full", {}, W, H), 1920, 1080);
+ assert.ok(full.rest > 1.7 && sharpLimit(full.rest) === 1, "a full short is already past its pixels");
+ const desk = pictureRegion(desktopGeometry({}, 1920, 1080), 1920, 1080);
+ assert.equal(desk.rest, 1);
+ // 720 windows: a framed short's room is 1.18.
+ assert.equal(Math.round(sharpLimit(pictureRegion(clipGeometry("framed", {}, W, H), 1280, 720).rest) * 100) / 100, 1.19);
+ assert.equal(restEnlargement({ w: 100, h: 100 }, { w: 200, h: 150 }), 1.5);
+});
+
+test("resolved: refused past the limit by name; a soft limit lets it through with a note; a box's scale and focus", () => {
+ const desk = pictureRegion(desktopGeometry({}, 1920, 1080), 1920, 1080);
+ const base = { from: 10, srcW: 1920, srcH: 1080, region: desk.region, rest: desk.rest, seconds: 30 };
+ const strict = resolveZooms(clip([{ at: 12, scale: 1.2 }]), base);
+ assert.equal(strict.zooms.length, 0);
+ assert.match(strict.errors[0], /c1: the zoom at 12 s \(×1\.2\) plays its source at 1\.2× its pixels; the limit here is ×1 .*soft limit/);
+ const soft = resolveZooms(clip([{ at: 12, scale: 1.2 }]), { ...base, soften: 1.3 });
+ assert.deepEqual(soft.errors, []);
+ assert.match(soft.notes[0], /plays softer than its source: 1\.2× its pixels/);
+ assert.equal(soft.zooms[0].at, 2, "on the segment's clock");
+ assert.match(resolveZooms(clip([{ at: 12, scale: 1.4 }]), { ...base, soften: 1.3 }).errors[0], /limit here is ×1\.3 .*sharper source \(render\.tallWindows\)$/);
+ // soften is NOT a cap on the total past the source's pixels: the reference is the coarser of those and the layout's
+ // resting picture. A full 9:16 crop of a 1080 window already plays at 1.78×: soften 1.3 lets it go 1.3 times that.
+ const full = pictureRegion(clipGeometry("full", {}, 1080, 1920), 1920, 1080);
+ assert.ok(full.rest > 1.7, `a full crop rests at ${full.rest}`);
+ assert.match(resolveZooms(clip([{ at: 12, scale: 1.2 }]), { ...base, region: full.region, rest: full.rest }).errors[0], /the limit here is ×1 /, "strict: no zoom");
+ const fsoft = resolveZooms(clip([{ at: 12, scale: 1.3 }]), { ...base, region: full.region, rest: full.rest, soften: 1.3 });
+ assert.deepEqual(fsoft.errors, []);
+ assert.match(fsoft.notes[0], /plays softer than its source: 2\.3\d?× its pixels/);
+ assert.match(resolveZooms(clip([{ at: 12, scale: 1.35 }]), { ...base, region: full.region, rest: full.rest, soften: 1.3 }).errors[0], /limit here is ×1\.3 /);
+ // A framed short (rests at 0.56): soften 1.3 lets the picture play 1.3× its source's pixels -- scale up to 2.31.
+ const fr0 = pictureRegion(clipGeometry("framed", {}, 1080, 1920), 1920, 1080);
+ assert.deepEqual(resolveZooms(clip([{ at: 12, scale: 2.3 }]), { ...base, region: fr0.region, rest: fr0.rest, soften: 1.3 }).errors, []);
+ assert.equal(resolveZooms(clip([{ at: 12, scale: 2.4 }]), { ...base, region: fr0.region, rest: fr0.rest, soften: 1.3 }).errors.length, 1);
+ // A framed short: 1.5 is sharp, no note.
+ const fr = pictureRegion(clipGeometry("framed", {}, 1080, 1920), 1920, 1080);
+ const sharp = resolveZooms(clip([{ at: 12, scale: 1.5 }]), { ...base, region: fr.region, rest: fr.rest });
+ assert.deepEqual([sharp.errors, sharp.notes, sharp.zooms[0].focus], [[], [], [0.5, 0.5]]);
+ // A box: its centre the focus, the scale that fills the region with it.
+ const box = resolveZooms(clip([{ at: 12, box: [0.4, 0.4, 0.6, 0.6] }]), { ...base, region: fr.region, rest: fr.rest });
+ assert.deepEqual([Math.round(box.zooms[0].scale * 1000) / 1000, box.zooms[0].focus.map((n) => Math.round(n * 100) / 100)], [1.667, [0.7, 0.7]]);
+ // A box too small for the source's pixels: refused like any zoom past its limit.
+ assert.match(resolveZooms(clip([{ at: 12, box: [0.5, 0.5, 0.5, 0.5] }]), { ...base, region: fr.region, rest: fr.rest }).errors[0], /×2\) plays its source at 1\.13× its pixels/);
+ // Outside what plays (the cut later than the window): left out, said.
+ const out = resolveZooms(clip([{ at: 12 }]), { ...base, from: 13, region: fr.region, rest: fr.rest });
+ assert.deepEqual([out.zooms.length, /outside what plays/.test(out.notes[0])], [0, true]);
+});
+
+test("the filter: frames at the cut's rate, a sub-pixel perspective eased by smoothstep about each push's focus, on only over the pushes; none without zooms", () => {
+ assert.deepEqual(zoomFilters([], { srcW: 1920, srcH: 1080, fps: 30 }), []);
+ const [fps, zp] = zoomFilters([{ at: 2, ramp: 0.4, hold: 1.5, scale: 1.5, focus: [0.75, 0.3] }], { srcW: 1920, srcH: 1080, fps: 30 });
+ assert.equal(fps, "fps=30");
+ assert.match(zp, /^perspective=x0='if\(between\(\(\(in-1\)\/30\),2\.0000,4\.3000\),0\.7500,0\.5\)\*W\*\(1-1\/\(1\+if\(between\(\(\(in-1\)\/30\),2\.0000,4\.3000\),0\.5000\*if\(lt\(\(\(in-1\)\/30\),2\.4000\),/);
+ assert.match(zp, /\*\(3-2\*/, "smoothstep");
+ assert.match(zp, /:interpolation=cubic:sense=source:eval=frame:enable='between\(n\/30,2\.0000,4\.3000\)'$/);
+ assert.doesNotMatch(zp, /zoompan/, "zoompan rounds its crop to whole pixels: a slow ease wobbles");
+});
+
+const haveFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;
+test("a slow push (1 s eases, 2 s held: 4 s) moves the picture monotonically -- no back-step in its offset; untouched outside it", { skip: !haveFfmpeg && "needs ffmpeg" }, () => {
+ // A black picture with a white right quarter: the edge's place on screen, to a fraction of a pixel, every frame.
+ const W = 640;
+ const H = 360;
+ const FPS = 30;
+ const z = { at: 0.5, ramp: 1, hold: 2, scale: 1.06, focus: [0.5, 0.5] };
+ const chain = zoomFilters([z], { srcW: W, srcH: H, fps: FPS }).join(",");
+ const r = spawnSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", `color=c=black:s=${W}x${H}:r=${FPS}:d=5,drawbox=x=480:y=0:w=160:h=${H}:c=white:t=fill,format=yuv420p`, "-vf", chain, "-f", "rawvideo", "-pix_fmt", "gray", "-"], { maxBuffer: 64 << 20 });
+ assert.equal(r.status, 0, String(r.stderr));
+ const n = r.stdout.length / (W * H);
+ assert.equal(n, 5 * FPS);
+ const edge = [];
+ for (let i = 0; i < n; i += 1) {
+ let sum = 0;
+ for (let y = 150; y < 210; y += 1) for (let x = 0; x < W; x += 1) sum += r.stdout[i * W * H + y * W + x];
+ edge.push(W - sum / 255 / 60);
+ }
+ const t = (i) => i / FPS;
+ const steps = [];
+ for (let i = 1; i < n; i += 1) {
+ const d = edge[i] - edge[i - 1];
+ if (t(i) > z.at && t(i) <= z.at + z.ramp && d < -0.02) steps.push(`in at ${t(i).toFixed(2)} s: ${d.toFixed(2)} px`);
+ if (t(i) > z.at + z.ramp + z.hold && t(i) <= zoomEnd(z) && d > 0.02) steps.push(`out at ${t(i).toFixed(2)} s: +${d.toFixed(2)} px`);
+ }
+ assert.deepEqual(steps, [], "a back-step in the ease");
+ // On time, frame by frame: the edge where the eased zoom puts it at that frame's second -- 160·(Z − 1) px past 480
+ // (focus in the middle). One frame early or late is off by tenths of a pixel in the ramps.
+ const ease = (u) => u * u * (3 - 2 * u);
+ const want = (s) => {
+ if (s < z.at || s > zoomEnd(z)) return 480;
+ const u = s < z.at + z.ramp ? ease((s - z.at) / z.ramp) : s < z.at + z.ramp + z.hold ? 1 : ease((zoomEnd(z) - s) / z.ramp);
+ return 480 + 160 * (z.scale - 1) * u;
+ };
+ const off = edge.map((e, i) => Math.abs(e - want(t(i))));
+ assert.ok(Math.max(...off) < 0.06, `frame ${off.indexOf(Math.max(...off))} is ${Math.max(...off).toFixed(3)} px off its second`);
+ // The first pushed frame (at 0.5 s, the ease at 0) is still the source; the next has moved; the last eased frame
+ // (one before 4.5 s) is a hair out, the one at 4.5 s back home.
+ const first = Math.round(z.at * FPS);
+ const last = Math.round(zoomEnd(z) * FPS);
+ assert.ok(Math.abs(edge[first] - 480) < 0.01, `the first pushed frame ${edge[first]}`);
+ assert.ok(edge[first + 1] - 480 > 0.015, `the second pushed frame ${edge[first + 1]}`);
+ assert.ok(edge[last - 1] - 480 > 0.015, `the last eased frame ${edge[last - 1]}`);
+ assert.ok(Math.abs(edge[last] - 480) < 0.01, `the push over ${edge[last]}`);
+ // Pushed in about the centre: the edge at 480 lands at (480 − 0.5·640·(1 − 1/1.06))·1.06 = 489.6 while held.
+ const held = edge[Math.round((z.at + z.ramp + 1) * FPS)];
+ assert.ok(Math.abs(held - 489.6) < 0.3, `held at ${held}`);
+ // Outside the push the frame is the source's, untouched.
+ assert.equal(edge[3], 480);
+ assert.equal(edge[n - 3], 480);
+});
diff --git a/umtool/report-to-video/cold-open.test.mjs b/umtool/report-to-video/cold-open.test.mjs
@@ -0,0 +1,81 @@
+// A clip's cold open (lane clip-kit, slice G): the rules, the plan (its span first, a hard cut into the clip), and the
+// join -- cut from the segments, never the build's crossfade.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+import { coldOpenErrors, coldOpenNote } from "./clip-kit.mjs";
+import { coldOpenEntry, piecesWhole, planVerticalCut } from "./vertical-plan.mjs";
+import { assembleShort, probeSeconds } from "./reframe.mjs";
+
+const clip = (o = {}) => ({ type: "clip", id: "w01", video: "v", start: 10, end: 40, cutStart: 12, cutEnd: 38, title: "T", ...o });
+
+test("the rules: {from, to} inside the clip's cut, 1 to 4 s; a note outside 1.5 to 3 s", () => {
+ assert.deepEqual(coldOpenErrors({ from: 35, to: 37.5 }, "c", clip()), []);
+ const no = (v, re) => assert.match(coldOpenErrors(v, "c", clip()).join("\n"), re, JSON.stringify(v));
+ no({ from: 35 }, /\{from, to\}, from before to/);
+ no({ from: 35, to: 35.5 }, /0\.5 s: a cold open is 1–4 s/);
+ no({ from: 30, to: 36 }, /6 s: a cold open is 1–4 s/);
+ no({ from: 38, to: 40 }, /outside the clip's cut \(12–38\)/);
+ no({ from: 35, to: 37, play: true }, /play is not a key/);
+ // A gap inside it or across either edge: refused by the clip's name and the gap, never shortened.
+ const gapped = clip({ gaps: [{ from: 36, to: 36.5 }] });
+ for (const v of [{ from: 35, to: 37.5 }, { from: 36.2, to: 38 }, { from: 34, to: 36.3 }]) {
+ assert.match(coldOpenErrors(v, "timeline w01.coldOpen", gapped).join(), /timeline w01\.coldOpen .* runs across w01's gap 36–36\.5 s/, JSON.stringify(v));
+ }
+ assert.deepEqual(coldOpenErrors({ from: 34, to: 36 }, "w01.coldOpen", gapped), [], "up to the gap");
+ assert.doesNotMatch(coldOpenErrors({ from: 35, to: 37.5 }, "timeline w01.coldOpen", gapped).join(), /~co/);
+ // The whole cut is not a cold open.
+ assert.match(coldOpenErrors({ from: 12, to: 15 }, "c", clip({ cutEnd: 15 })).join(), /is the whole cut/);
+ assert.equal(coldOpenNote(clip({ coldOpen: { from: 35, to: 37.5 } }), "w01"), null);
+ assert.match(coldOpenNote(clip({ coldOpen: { from: 34, to: 37.8 } }), "w01"), /3\.8 s; 1\.5–3 s reads best/);
+});
+
+test("the plan: the span first as <id>~co (no card, no code, its own zooms), then the clip; both joined hard", () => {
+ const e = clip({ coldOpen: { from: 35, to: 37.5 }, qr: { corner: "tl" }, promo: { hold: 2 }, zooms: [{ at: 20 }, { at: 35.2, hold: 0.5, ramp: 0.3 }] });
+ const co = coldOpenEntry(e);
+ assert.equal(co.id, "w01~co");
+ assert.deepEqual([co.start, co.end, co.cutStart, co.promo, co.qr, co.coldOpen], [35, 37.5, undefined, false, false, undefined]);
+ assert.deepEqual(co.zooms, [{ at: 35.2, hold: 0.5, ramp: 0.3 }], "only the zooms inside its span");
+ const plan = planVerticalCut({ timeline: [e, clip({ id: "w02" })], items: ["w01", "w02"] });
+ assert.deepEqual(plan.timeline.map((x) => x.id), ["w01~co", "w01", "w02"]);
+ assert.deepEqual(plan.pieces, [{ id: "w01~co", from: 0, to: null, hard: true }, { id: "w01", from: 0, to: null, hard: true }, { id: "w02", from: 0, to: null }]);
+ assert.equal(piecesWhole(plan.pieces), false);
+ // Not asked (--no-cold-open, a landscape or a reframe): the plan it always made.
+ const off = planVerticalCut({ timeline: [e], items: ["w01"], coldOpens: false });
+ assert.deepEqual(off.pieces, [{ id: "w01", from: 0, to: null }]);
+ assert.equal(piecesWhole(off.pieces), true);
+ assert.equal(coldOpenEntry(clip()), null);
+});
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
+
+test("the hard join: the pieces cut from their segments end to end -- the cold open, then the clip, no crossfade", { skip: !have && "needs ffmpeg" }, async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-coldopen-"));
+ try {
+ const seg = (name, colour, d) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `color=c=${colour}:s=320x568:r=30:d=${d}`, "-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:duration=${d}`, "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(root, name)]);
+ assert.equal(r.status, 0, String(r.stderr));
+ };
+ seg("w01~co.mp4", "white", 2);
+ seg("w01.mp4", "black", 3);
+ // The build's own joined file (a 0.4 s crossfade): never what a hard join plays.
+ seg("built.mp4", "gray", 4.6);
+ const out = path.join(root, "short.mp4");
+ const r = await assembleShort({
+ pieces: [{ id: "w01~co", from: 0, to: null, hard: true }, { id: "w01", from: 0, to: null, hard: true }],
+ segmentsDir: root, built: path.join(root, "built.mp4"), outFile: out, render: { fps: 30, vertical: { loudness: -14 } },
+ });
+ assert.ok(Math.abs(r.seconds - 5) < 0.1, `the two pieces end to end (${r.seconds})`);
+ const y = (t) => Number((/YAVG=([0-9.]+)/.exec(String(spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", out, "-frames:v", "1", "-vf", "signalstats,metadata=print:file=-", "-f", "null", "-"]).stdout)) ?? [])[1]);
+ assert.ok(y(0.5) > 200, "the cold open first");
+ assert.ok(y(3) < 40, "then the clip");
+ assert.ok(Math.abs((await probeSeconds(out)) - r.seconds) < 0.01);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -123,6 +123,10 @@ import { ENLARGE_WARN, STACKED_QR_SHARE, STACKED_QR_SMALL_SHARE, clipTwoCrop, st
import { roomWindowWarnings } from "./room.mjs";
import { qrUrlFor } from "./render-cards.mjs";
import { archiveMomentUrl } from "./site-links.mjs";
+import { clipQrUrl, coldOpenNote, cornerQrOf, desktopQrOf, expiringLinkNote, validateClipKit, verticalQrOf } from "./clip-kit.mjs";
+import { validatePromo } from "./promo-card.mjs";
+import { validateZooms } from "./clip-zoom.mjs";
+import { validateCensor } from "./clip-censor.mjs";
import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs";
import { validatePodcast } from "./build-podcast.mjs";
import { draftsReviewFromNarration, draftsReviewProblems, readDraftsReview } from "./drafts-review.mjs";
@@ -219,6 +223,24 @@ export function qrsOf(manifest, { only = null, metaOf = null } = {}) {
}
return out;
}
+ // A 9:16 short's code (clip-kit.mjs, render.vertical.qr): each clip's, at the top of the safe area.
+ if (verticalOn(render) && !stackedOn(render)) {
+ for (const e of timeline) {
+ const vq = e.type === "clip" ? verticalQrOf(e, render) : null;
+ if (!vq || (e.src != null && !e.citeUrl)) continue;
+ const url = clipQrUrl(e, provenance, { links: vq.links, at: e.cutStart ?? e.start, channelUrl: render.promo?.url ?? null, webpageUrl: metaOf?.(e)?.webpageUrl ?? null });
+ if (url) out.push({ where: `timeline ${e.id} (its QR)`, id: e.id, source: "entry", url, links: vq.links, px: Math.round((Number(render.width) || 1080) * vq.size) });
+ }
+ }
+ // A desktop clip's code (vertical.mjs desktopRender; render.desktop.qr), in its corner.
+ if (render.desktopBuild === true) {
+ for (const e of timeline) {
+ const dq = e.type === "clip" ? desktopQrOf(e, render) : null;
+ if (!dq || (e.src != null && !e.citeUrl)) continue;
+ const url = clipQrUrl(e, provenance, { links: dq.links, at: e.cutStart ?? e.start, channelUrl: render.promo?.url ?? null, webpageUrl: metaOf?.(e)?.webpageUrl ?? null });
+ if (url) out.push({ where: `timeline ${e.id} (its QR)`, id: e.id, source: "entry", url, links: dq.links, px: Math.round((Number(render.width) || 1920) * dq.size) });
+ }
+ }
if (render.qr === false) return out;
if (render.rail) {
// The rail's foot: a tile per entry (a card's is the sweep's link), the
@@ -235,13 +257,18 @@ export function qrsOf(manifest, { only = null, metaOf = null } = {}) {
const scale = Number(render.qr?.scale ?? 4);
for (const e of timeline) {
let url = null;
+ let links = "cite";
if (e.type === "clip") {
if (e.src != null && !e.citeUrl) continue;
- url = e.citeUrl ?? archiveMomentUrl(e, provenance, e.start);
+ // The clip kit (clip-kit.mjs): a clip's `qr: false` draws none; `links` "moment" / "channel" another link.
+ const cq = cornerQrOf(e, render);
+ if (!cq) continue;
+ links = cq.links;
+ url = clipQrUrl(e, provenance, { links, at: e.cutStart ?? e.start, channelUrl: render.promo?.url ?? null, webpageUrl: metaOf?.(e)?.webpageUrl ?? null });
} else if (e.type === "image" && e.citeUrl) {
url = e.citeUrl;
}
- if (url) out.push({ where: `timeline ${e.id} (its corner QR)`, id: e.id, source: "entry", url, px: null, perModule: scale });
+ if (url) out.push({ where: `timeline ${e.id} (its corner QR)`, id: e.id, source: "entry", url, px: null, perModule: scale, ...(links !== "cite" ? { links } : {}) });
}
return out;
}
@@ -338,6 +365,8 @@ export function validatorErrors(whole) {
...validateStatsEntries(whole),
// A clip's `chat` and render.chrome.chat (chat.mjs).
...validateChatEntries(whole),
+ // The clip kit: a clip's `qr` and `name`, render.qr's corner and links (clip-kit.mjs); the channel promo (promo-card.mjs).
+ ...validateClipKit(whole), ...validatePromo(whole), ...validateZooms(whole), ...validateCensor(whole),
// Release 33: render.montage, its keys and what it does not combine with.
...validateMontage(whole),
// Release 35: a clip's `assist` (the clip finder's provenance; the render ignores it).
@@ -480,6 +509,19 @@ export function lintManifest(manifest, {
// An analysis item: a bound pace row, a number typed into words, its audio heard twice (analysis-plan.mjs).
warnings.push(...analysisWarnings(manifest, { only }));
+ // A cold open outside what reads best (clip-kit.mjs): a note.
+ for (const e of manifest.timeline ?? []) {
+ if (only && e?.id !== only) continue;
+ const n = coldOpenNote(e, `timeline ${e?.id}`);
+ if (n) warnings.push(n);
+ }
+ // The channel promo's portrait (promo-card.mjs): a picture of the project's, there.
+ {
+ const pf = whole?.render?.promo?.portrait?.file;
+ if (typeof pf === "string" && manifestDir && !path.isAbsolute(pf) && !exists(path.resolve(manifestDir, pf))) {
+ errors.push(`render.promo.portrait: "${pf}" names no file of the project (umtool promo <p> --portrait-from <clip>@<second> grabs one)`);
+ }
+ }
for (const { where, src } of imageSrcsOf(manifest, { only })) {
if (path.isAbsolute(src) || src.startsWith("~")) {
errors.push(`${where}: the image "${src}" must be a path relative to the manifest (it is checked in beside its pictures)`);
@@ -516,6 +558,13 @@ export function lintManifest(manifest, {
const what =
`${q.where}: ${per.toFixed(2)} px per module at 720p ` +
`(${q.px === null ? `scale ${q.perModule}` : `${q.px} px`} on a ${height}p frame, a version-${version} code, ${modules} modules)`;
+ // A code that links a stream's VOD at its second, on a platform that deletes VODs: a note (clip-kit.mjs).
+ // A code whose link is a Kick or Twitch VOD -- the moment, or a citeUrl that is one -- stops opening once the VOD
+ // is deleted: a note (clip-kit.mjs expiringLinkNote).
+ if (q.source === "entry") {
+ const n = expiringLinkNote(q.url, q.where);
+ if (n) warnings.push(n);
+ }
if (per < MIN_QR_PX_PER_MODULE_720P) {
errors.push(`${what} — too small to scan; make it larger or the link shorter (at least ${MIN_QR_PX_PER_MODULE_720P})`);
} else if (per < WARN_QR_PX_PER_MODULE_720P) {
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -29,6 +29,10 @@
"./vertical": "./vertical.mjs",
"./vertical-deck": "./vertical-deck.mjs",
"./vertical-plan": "./vertical-plan.mjs",
+ "./clip-kit": "./clip-kit.mjs",
+ "./promo-card": "./promo-card.mjs",
+ "./clip-zoom": "./clip-zoom.mjs",
+ "./clip-censor": "./clip-censor.mjs",
"./reframe": "./reframe.mjs",
"./side-card": "./side-card.mjs",
"./check-availability": "./check-availability.mjs",
diff --git a/umtool/report-to-video/promo-card.mjs b/umtool/report-to-video/promo-card.mjs
@@ -0,0 +1,427 @@
+// THE CHANNEL PROMO (lane clip-kit, slice D): the card a per-clip build ends on, promoting the streamer it was
+// clipped from. DATA, not a drawing: the project says who and where (`render.promo`), one template draws it in 9:16
+// and 16:9, and the clip's last seconds dissolve into it.
+//
+// render.promo { name: "Some Streamer" | ["Some", "Streamer"], one or two lines (≤ 24 characters each)
+// url: "https://kick.com/…", the channel's page, shown host + path
+// qr?: "https://…" | false, the code's link (default: url); false: none
+// portrait?: { file: "shots/….png", box?: [x, y, w, h] }, a picture of the project's, the circle cut
+// from `box` (fractions; default its centre)
+// kicker?: "…", a small line over the name (default: none)
+// palette?: { ground?, ink?, accent?, link?, plate? }, the card's colours over the cut's (#rrggbb)
+// lead?: 4.5, fade?: 0.7, hold?: 1.5, seconds (below)
+// captions?: true } the captions stay over the card
+// clip.promo false (this clip ends without it) | { lead?, fade?, hold? } over the cut's
+//
+// THE TIMING (the operator's accepted card, 13 Nov): the card starts `lead` seconds before the clip's end and fades in
+// over `fade`, the clip's own sound playing on under it; then it holds `hold` seconds in silence. A still: no push,
+// no zoom ("the promo screen is wiggling a bit"), no slam, no sting.
+//
+// THE CARD IS ONLY portrait, name, url and code (the operator: "drop the 'clipped from the stream of' text and 'live on
+// kick' to really keep it minimal"). A kicker is drawn only when the project gives one.
+//
+// THE CAPTIONS stay over the card for the seconds the clip still plays under it -- X autoplays muted, and the last
+// words are the ones a muted viewer would lose -- moved into a band the card keeps clear (promoBand).
+//
+// THE COLOURS are the cut's palette (`render.palette`: bg → ground, fg → ink, amber (else accent) → the ring and the
+// name's second line), `promo.palette` over them for the card alone; the url's host in its platform's colour (Kick's
+// green, …) unless `palette.link` says. The faces are the repository's own (Archivo, IBM Plex Sans; fonts/).
+//
+// The card is drawn by a browser (Playwright's chromium, as a post card is) from promoCardHtml, once per key, into the
+// build's cards dir. PURE above renderPromoCard.
+import { execFile } from "node:child_process";
+import { createHash, randomBytes } from "node:crypto";
+import { access, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import { promisify } from "node:util";
+
+import { FONTS_DIR } from "./brand.mjs";
+
+const execFileP = promisify(execFile);
+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);
+
+export const PROMO_KEYS = Object.freeze(["name", "url", "qr", "portrait", "kicker", "palette", "lead", "fade", "hold", "captions"]);
+export const PROMO_CLIP_KEYS = Object.freeze(["lead", "fade", "hold"]);
+export const PROMO_PALETTE_KEYS = Object.freeze(["ground", "ink", "accent", "link", "plate"]);
+export const PROMO_TIMING = Object.freeze({
+ lead: Object.freeze({ min: 1, max: 10, default: 4.5 }),
+ fade: Object.freeze({ min: 0.2, max: 2, default: 0.7 }),
+ hold: Object.freeze({ min: 0, max: 5, default: 1.5 }),
+});
+export const PROMO_NAME_LINE_MAX = 24;
+export const PROMO_KICKER_MAX = 40;
+/** The clip's sound fades out over its last this-many seconds, before the card's silence. */
+export const PROMO_SOUND_OUT = 0.15;
+/** The code's quiet zone, in modules (the QR standard's four). */
+export const PROMO_QR_QUIET = 4;
+/** A platform's own colour, for the url's host (the operator's card: Kick's green). */
+export const PROMO_LINK_COLOURS = Object.freeze({ "kick.com": "#53fc18", "twitch.tv": "#a970ff", "youtube.com": "#ff4e45", "rumble.com": "#85c742" });
+const IMAGE = /\.(png|jpe?g|webp)$/i;
+const HEX = /^#[0-9a-fA-F]{6}$/;
+
+/** A promo's name as its lines. */
+export function nameLines(name) {
+ if (Array.isArray(name)) return name.map((s) => String(s).trim()).filter(Boolean);
+ const s = String(name ?? "").trim();
+ if (!s) return [];
+ if (s.length <= PROMO_NAME_LINE_MAX / 2 || !s.includes(" ")) return [s];
+ // Two lines, broken at the space nearest the middle.
+ const mid = s.length / 2;
+ let best = -1;
+ for (let i = s.indexOf(" "); i >= 0; i = s.indexOf(" ", i + 1)) if (best < 0 || Math.abs(i - mid) < Math.abs(best - mid)) best = i;
+ return [s.slice(0, best), s.slice(best + 1)];
+}
+
+/** Each thing wrong with `render.promo` ([] when fine, or absent). */
+export function promoErrors(v, where = "render.promo") {
+ if (v === undefined || v === null) return [];
+ if (!isObj(v)) return [`${where} is {name, url, qr?, portrait?, kicker?, palette?, lead?, fade?, hold?, captions?}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!PROMO_KEYS.includes(k)) errors.push(`${where}.${k} is not a key (${PROMO_KEYS.join(", ")})`);
+ const lines = nameLines(v.name);
+ if (!(typeof v.name === "string" || (Array.isArray(v.name) && v.name.every((s) => typeof s === "string"))) || !lines.length || lines.length > 2 || lines.some((l) => l.length > PROMO_NAME_LINE_MAX)) {
+ errors.push(`${where}.name is the channel's name: one or two lines of at most ${PROMO_NAME_LINE_MAX} characters`);
+ }
+ const https = (u) => typeof u === "string" && /^https?:\/\/[^\s]+$/.test(u);
+ if (!https(v.url)) errors.push(`${where}.url is the channel's page, an http(s) link`);
+ if (v.qr !== undefined && v.qr !== false && !https(v.qr)) errors.push(`${where}.qr is a link (http(s)) or false (no code); absent: the url`);
+ if (v.portrait !== undefined) {
+ const p = v.portrait;
+ if (!isObj(p) || typeof p.file !== "string" || !p.file.trim() || path.isAbsolute(p.file) || p.file.split(/[\\/]/).includes("..") || !IMAGE.test(p.file)) {
+ errors.push(`${where}.portrait is {file, box?}: a .png, .jpg or .webp of the project's, by its path in it (e.g. shots/still-w01-10650_20s.png)`);
+ } else {
+ for (const k of Object.keys(p)) if (!["file", "box", "from"].includes(k)) errors.push(`${where}.portrait.${k} is not a key (file, box, from)`);
+ if (p.box !== undefined && !(Array.isArray(p.box) && p.box.length === 4 && p.box.every(num) && p.box[2] > 0 && p.box[3] > 0 && p.box[0] >= 0 && p.box[1] >= 0 && p.box[0] + p.box[2] <= 1.001 && p.box[1] + p.box[3] <= 1.001)) {
+ errors.push(`${where}.portrait.box is [x, y, w, h], fractions of the picture inside it`);
+ }
+ }
+ }
+ if (v.kicker !== undefined && !(typeof v.kicker === "string" && v.kicker.trim() && v.kicker.length <= PROMO_KICKER_MAX)) errors.push(`${where}.kicker is a line of 1 to ${PROMO_KICKER_MAX} characters`);
+ if (v.palette !== undefined) {
+ if (!isObj(v.palette)) errors.push(`${where}.palette is {${PROMO_PALETTE_KEYS.join(", ")}}, each #rrggbb`);
+ else for (const [k, c] of Object.entries(v.palette)) {
+ if (!PROMO_PALETTE_KEYS.includes(k)) errors.push(`${where}.palette.${k} is not a colour of the card (${PROMO_PALETTE_KEYS.join(", ")})`);
+ else if (!HEX.test(String(c))) errors.push(`${where}.palette.${k} is #rrggbb`);
+ }
+ }
+ errors.push(...timingErrors(v, where));
+ if (v.captions !== undefined && typeof v.captions !== "boolean") errors.push(`${where}.captions is true (the captions stay over the card) or false`);
+ return errors;
+}
+
+function timingErrors(v, where) {
+ const errors = [];
+ for (const [k, b] of Object.entries(PROMO_TIMING)) {
+ if (v[k] !== undefined && !(num(v[k]) && v[k] >= b.min && v[k] <= b.max)) errors.push(`${where}.${k} is ${b.min}–${b.max} seconds`);
+ }
+ const lead = v.lead ?? PROMO_TIMING.lead.default;
+ const fade = v.fade ?? PROMO_TIMING.fade.default;
+ if (num(lead) && num(fade) && fade > lead) errors.push(`${where}.fade (${fade} s) is longer than its lead (${lead} s): the card would still be fading in at the clip's end`);
+ return errors;
+}
+
+/** Each thing wrong with a clip's `promo` ([] when fine, or absent). */
+export function clipPromoErrors(v, where = "clip.promo") {
+ if (v === undefined || v === false) return [];
+ if (!isObj(v)) return [`${where} is false (this clip ends without the card) or {${PROMO_CLIP_KEYS.join("?, ")}?}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!PROMO_CLIP_KEYS.includes(k)) errors.push(`${where}.${k} is not a key (${PROMO_CLIP_KEYS.join(", ")})`);
+ return [...errors, ...timingErrors(v, where)];
+}
+
+/** Every reason a manifest's promo cannot be drawn ([] when fine): the cut's and each clip's. */
+export function validatePromo(manifest) {
+ const errors = promoErrors(manifest?.render?.promo);
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.promo === undefined) continue;
+ if (e.type !== "clip") errors.push(`timeline ${e.id ?? "?"}: promo is a clip's`);
+ else errors.push(...clipPromoErrors(e.promo, `timeline ${e.id}.promo`));
+ }
+ return errors;
+}
+
+/**
+ * The promo a clip ends on: null when the cut sets none or the clip says `promo: false`; else the cut's with the
+ * clip's timing over it and the defaults under both. `seconds` (the clip's length as it plays) holds the lead inside
+ * it: at most the clip's length less a second (said in `note`).
+ */
+export function promoOf(entry, render, seconds = Infinity) {
+ const p = render?.promo;
+ if (!isObj(p) || entry?.promo === false) return null;
+ const own = isObj(entry?.promo) ? entry.promo : {};
+ const t = (k) => own[k] ?? p[k] ?? PROMO_TIMING[k].default;
+ let lead = t("lead");
+ let note = null;
+ if (Number.isFinite(seconds) && lead > seconds - 1) {
+ const was = lead;
+ lead = Math.max(0.5, Math.round((seconds - 1) * 100) / 100);
+ note = `its card's lead is ${was} s, longer than the clip less a second: ${lead} s`;
+ }
+ return { ...p, lead, fade: Math.min(t("fade"), lead), hold: t("hold"), captions: p.captions !== false, note };
+}
+
+/** "#rrggbb" mixed toward another by `t` (0–1). */
+export function mixHex(a, b, t) {
+ const h = (s) => [1, 3, 5].map((i) => parseInt(String(s).slice(i, i + 2), 16));
+ const [x, y] = [h(a), h(b)];
+ return `#${x.map((v, i) => Math.round(v + (y[i] - v) * t).toString(16).padStart(2, "0")).join("")}`;
+}
+
+/** A url's host's own colour (PROMO_LINK_COLOURS), else null. */
+export function linkColourOf(url) {
+ try {
+ const host = new URL(String(url)).hostname.toLowerCase().replace(/^(?:www|m)\./, "");
+ for (const [h, c] of Object.entries(PROMO_LINK_COLOURS)) if (host === h || host.endsWith(`.${h}`)) return c;
+ } catch {
+ // not a url: no platform colour
+ }
+ return null;
+}
+
+/** The card's colours: the cut's palette, the promo's over it. */
+export function promoPalette(render, promo) {
+ const pal = isObj(render?.palette) ? render.palette : {};
+ const ok = (c) => (HEX.test(String(c ?? "")) ? String(c) : null);
+ const base = {
+ ground: ok(pal.bg) ?? "#12100c",
+ ink: ok(pal.fg) ?? "#f6f1e6",
+ accent: ok(pal.amber) ?? ok(pal.accent) ?? "#f2a531",
+ };
+ const own = isObj(promo?.palette) ? promo.palette : {};
+ const out = { ...base, ...Object.fromEntries(Object.entries(own).filter(([, c]) => ok(c))) };
+ out.link = ok(own.link) ?? linkColourOf(promo?.url) ?? out.accent;
+ // The code's plate: WHITE whatever the palette (a scanner wants black on white), unless the promo names one.
+ out.plate = ok(own.plate) ?? "#ffffff";
+ out.lift = mixHex(out.ground, out.accent, 0.12);
+ return out;
+}
+
+/** The url as the card shows it: its host (with a "/" after it) and its path, no scheme, no trailing "/". */
+export function urlParts(url) {
+ try {
+ const u = new URL(String(url));
+ const host = u.hostname.replace(/^www\./, "");
+ const rest = `${u.pathname}${u.search}`.replace(/\/$/, "").replace(/^\//, "");
+ return { host: rest ? `${host}/` : host, rest };
+ } catch {
+ return { host: String(url ?? ""), rest: "" };
+ }
+}
+
+/**
+ * Where a frame of `width`×`height` keeps its captions while the card is up (px from the top: `y0`, `y1`), and the
+ * box the card's content keeps to: in a 9:16 frame the card stands in the upper safe area (the top 8 % kept) and the
+ * captions in a band above the bottom 20 %; in a 16:9 one the band runs along the foot. `captions: false` gives the
+ * card the whole safe area.
+ */
+export function promoBand({ width, height, captions = true }) {
+ const vertical = height > width;
+ const H = height;
+ if (vertical) {
+ const box = { x0: Math.round(width * 0.08), x1: Math.round(width * 0.88), y0: Math.round(H * 0.08), y1: Math.round(H * (captions ? 0.6 : 0.8)) };
+ return { vertical, box, band: captions ? { y0: Math.round(H * 0.62), y1: Math.round(H * 0.79) } : null };
+ }
+ const box = { x0: Math.round(width * 0.06), x1: Math.round(width * 0.94), y0: Math.round(H * 0.06), y1: Math.round(H * (captions ? 0.74 : 0.94)) };
+ return { vertical, box, band: captions ? { y0: Math.round(H * 0.78), y1: Math.round(H * 0.93) } : null };
+}
+
+const esc = (s) => String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
+const cssUrl = (u) => String(u).replace(/'/g, "%27");
+
+/**
+ * The card's page (PURE): portrait in its ring, the name stacked (the second line in the accent), the url (its host in
+ * the link colour), the code on a plate -- a row in 16:9, a column in 9:16, fitted (scaled down, never up) into the
+ * band's content box. `portraitUrl`, `qrUrl` are file urls; `fonts` the faces' file urls.
+ *
+ * @param {{ promo: Record<string, any>, width: number, height: number, palette: ReturnType<typeof promoPalette>,
+ * portraitUrl?: string | null, qrUrl?: string | null, fonts: { display: string, text: string } }} o
+ */
+export function promoCardHtml({ promo, width, height, palette, portraitUrl = null, qrUrl = null, fonts }) {
+ const { vertical, box } = promoBand({ width, height, captions: promo.captions !== false });
+ const vmin = Math.min(width, height) / 100;
+ const px = (n) => `${Math.round(n * vmin)}px`;
+ const lines = nameLines(promo.name);
+ const { host, rest } = urlParts(promo.url);
+ const sz = vertical ? { f: 38, h: 18, k: 3.3, u: 5.4, q: 23, gap: 4 } : { f: 38, h: 15.5, k: 2.5, u: 4.2, q: 21, gap: 6 };
+ const pb = Array.isArray(promo.portrait?.box) ? promo.portrait.box : null;
+ return `<!doctype html>
+<html lang="en" class="${vertical ? "v" : "h"}"><head><meta charset="utf-8"><meta name="viewport" content="width=${width}, height=${height}">
+<style>
+@font-face { font-family: 'PromoDisplay'; src: url('${cssUrl(fonts.display)}'); font-weight: 100 900; font-stretch: 62% 125%; }
+@font-face { font-family: 'PromoText'; src: url('${cssUrl(fonts.text)}'); font-weight: 100 700; font-stretch: 85% 100%; }
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html, body { width: ${width}px; height: ${height}px; overflow: hidden; }
+body { background: radial-gradient(120% 90% at 30% 20%, ${palette.lift} 0%, ${palette.ground} 62%); color: ${palette.ink}; font-family: 'PromoText', sans-serif; -webkit-font-smoothing: antialiased; font-synthesis: none; position: relative; }
+.area { position: absolute; left: ${box.x0}px; top: ${box.y0}px; width: ${box.x1 - box.x0}px; height: ${box.y1 - box.y0}px; display: flex; align-items: center; justify-content: center; }
+.card { display: flex; align-items: center; gap: ${px(sz.gap)}; transform-origin: center center; }
+.v .card { flex-direction: column; text-align: center; }
+.face { position: relative; width: ${px(sz.f)}; height: ${px(sz.f)}; flex: none; border-radius: 50%; overflow: hidden; }
+.face img { position: absolute; display: block; }
+.face img.cover { width: 100%; height: 100%; object-fit: cover; object-position: center 30%; left: 0; top: 0; }
+.ring { position: absolute; border-radius: 50%; border: ${px(0.5)} solid ${palette.accent}; pointer-events: none; }
+.kicker { font-size: ${px(sz.k)}; letter-spacing: .32em; text-transform: uppercase; color: ${palette.ink}; opacity: .62; font-weight: 500; margin-bottom: ${px(1.6)}; }
+h1 { font-family: 'PromoDisplay', sans-serif; font-weight: 850; font-stretch: 72%; font-size: ${px(sz.h)}; line-height: .92; letter-spacing: .01em; text-transform: uppercase; margin: 0 0 ${px(3)}; }
+h1 span { display: block; white-space: nowrap; }
+h1 .u { color: ${palette.accent}; }
+.row { display: flex; align-items: center; gap: ${px(3.2)}; }
+.v .row { flex-direction: column; gap: ${px(4)}; }
+.url { font-size: ${px(sz.u)}; font-weight: 600; white-space: nowrap; }
+.url b { color: ${palette.link}; font-weight: 700; }
+.qr { background: ${palette.plate}; padding: 0; border-radius: ${px(1.2)}; width: ${px(sz.q)}; height: ${px(sz.q)}; flex: none; overflow: hidden; }
+.qr img { width: 100%; height: 100%; display: block; image-rendering: pixelated; }
+</style></head>
+<body data-promo-ready="0">
+<div class="area"><div class="card" data-promo-card="">
+ ${portraitUrl ? `<div class="face" data-promo-face=""><img src="${esc(portraitUrl)}" alt="" class="${pb ? "" : "cover"}"></div>` : ""}
+ <div class="words">
+ ${promo.kicker ? `<div class="kicker" data-promo-kicker="">${esc(promo.kicker)}</div>` : ""}
+ <h1 data-promo-name="">${lines.map((l, i) => `<span class="${i === 1 ? "u" : ""}">${esc(l)}</span>`).join("")}</h1>
+ <div class="row">
+ <div class="url" data-promo-url=""><b>${esc(host)}</b>${esc(rest)}</div>
+ ${qrUrl ? `<div class="qr" data-promo-qr=""><img src="${esc(qrUrl)}" alt=""></div>` : ""}
+ </div>
+ </div>
+</div></div>
+<script>
+(async () => {
+ const box = ${q(pb)};
+ const img = document.querySelector('[data-promo-face] img');
+ if (img) {
+ await (img.complete ? Promise.resolve() : new Promise((r) => { img.onload = r; img.onerror = r; }));
+ if (box && img.naturalWidth) {
+ const F = img.parentElement.clientWidth, nw = img.naturalWidth, nh = img.naturalHeight;
+ const side = Math.max(box[2] * nw, box[3] * nh), s = F / side;
+ img.style.width = (nw * s) + 'px'; img.style.height = (nh * s) + 'px';
+ img.style.left = (-(box[0] * nw + (box[2] * nw - side) / 2) * s) + 'px';
+ img.style.top = (-(box[1] * nh + (box[3] * nh - side) / 2) * s) + 'px';
+ }
+ }
+ await document.fonts.ready;
+ const face = document.querySelector('[data-promo-face]');
+ if (face) {
+ face.parentElement.style.position = 'relative';
+ const ring = document.createElement('div');
+ ring.className = 'ring';
+ const inset = ${Math.round(1.4 * vmin)};
+ ring.style.left = (face.offsetLeft - inset) + 'px'; ring.style.top = (face.offsetTop - inset) + 'px';
+ ring.style.width = (face.offsetWidth + 2 * inset) + 'px'; ring.style.height = (face.offsetHeight + 2 * inset) + 'px';
+ face.parentElement.insertBefore(ring, face);
+ }
+ // Fitted into the content box: scaled down when it would not fit, never up.
+ const area = document.querySelector('.area'), card = document.querySelector('[data-promo-card]');
+ const k = Math.min(1, (area.clientWidth * 0.98) / card.scrollWidth, (area.clientHeight * 0.98) / card.scrollHeight);
+ card.style.transform = 'scale(' + k + ')';
+ document.body.dataset.promoScale = String(Math.round(k * 1000) / 1000);
+ document.body.dataset.promoReady = '1';
+})();
+</script>
+</body></html>`;
+}
+
+/**
+ * The card's key: everything drawn (the page's inputs, the portrait's and the code's bytes, the size).
+ */
+export function promoCardKey({ html, portraitSha = null, qrText = null, width, height }) {
+ return createHash("sha256").update(JSON.stringify({ v: 1, html, portraitSha, qrText, width, height })).digest("hex").slice(0, 20);
+}
+
+/** The faces the card is drawn in (the repository's own). */
+export const PROMO_FONTS = Object.freeze({ display: path.join(/* turbopackIgnore: true */ FONTS_DIR, "Archivo[wdth,wght].ttf"), text: path.join(/* turbopackIgnore: true */ FONTS_DIR, "IBMPlexSans[wdth,wght].ttf") });
+
+const exists = (p) => access(/* turbopackIgnore: true */ p).then(() => true, () => false);
+
+/**
+ * Draw the card at `width`×`height`: `<dir>/promo-<key>.png` (kept: the same card is not drawn again). The portrait is
+ * read from `manifestDir`; the code drawn by qrencode. Returns `{file, key, cached, scale}`.
+ *
+ * @param {{ promo: Record<string, any>, render: Record<string, any>, width: number, height: number, dir: string,
+ * manifestDir: string, loadChromium?: () => Promise<any> }} o
+ */
+export async function renderPromoCard({ promo, render, width, height, dir, manifestDir, loadChromium = null }) {
+ await mkdir(/* turbopackIgnore: true */ dir, { recursive: true });
+ const palette = promoPalette(render, promo);
+ const portraitFile = promo.portrait?.file ? path.resolve(/* turbopackIgnore: true */ manifestDir, promo.portrait.file) : null;
+ const portraitBytes = portraitFile ? await readFile(/* turbopackIgnore: true */ portraitFile).catch(() => null) : null;
+ if (portraitFile && !portraitBytes) throw new Error(`render.promo.portrait ${promo.portrait.file}: not a file of the project`);
+ const portraitSha = portraitBytes ? createHash("sha256").update(portraitBytes).digest("hex") : null;
+ const qrText = promo.qr === false ? null : (promo.qr ?? promo.url);
+ const fonts = { display: pathToFileURL(PROMO_FONTS.display).href, text: pathToFileURL(PROMO_FONTS.text).href };
+ // The page's own text with placeholder urls: the key reads what is drawn, not where this run keeps its files.
+ const stable = promoCardHtml({ promo, width, height, palette, portraitUrl: portraitFile ? "portrait" : null, qrUrl: qrText ? "qr" : null, fonts: { display: "display", text: "text" } });
+ const key = promoCardKey({ html: stable, portraitSha, qrText, width, height });
+ const file = path.join(/* turbopackIgnore: true */ dir, `promo-${key}.png`);
+ const meta = `${file}.json`;
+ if ((await exists(file)) && (await exists(meta))) return { file, key, cached: true, ...JSON.parse(await readFile(/* turbopackIgnore: true */ meta, "utf8")) };
+ // Its own work dir per call (two draws of one card at once -- the page asks for both shapes together -- never share one).
+ const work = path.join(/* turbopackIgnore: true */ dir, `.promo-${key}-${process.pid}-${randomBytes(4).toString("hex")}`);
+ await mkdir(/* turbopackIgnore: true */ work, { recursive: true });
+ try {
+ let qrUrl = null;
+ if (qrText) {
+ const qrPng = path.join(/* turbopackIgnore: true */ work, "qr.png");
+ // A real quiet zone: four modules of white inside the plate (the code's own margin), the plate's corners round.
+ await execFileP(process.env.QRENCODE_BIN ?? "qrencode", ["-o", qrPng, "-s", "10", "-m", String(PROMO_QR_QUIET), "-l", "M", "--", qrText]);
+ qrUrl = pathToFileURL(qrPng).href;
+ }
+ let portraitUrl = null;
+ if (portraitBytes) {
+ const ext = path.extname(portraitFile).toLowerCase();
+ const copy = path.join(/* turbopackIgnore: true */ work, `portrait${ext}`);
+ await writeFile(/* turbopackIgnore: true */ copy, portraitBytes);
+ portraitUrl = pathToFileURL(copy).href;
+ }
+ const html = promoCardHtml({ promo, width, height, palette, portraitUrl, qrUrl, fonts });
+ const page = path.join(/* turbopackIgnore: true */ work, "card.html");
+ await writeFile(/* turbopackIgnore: true */ page, html, "utf8");
+ const chromium = await (loadChromium ?? (await import("./post-render.mjs")).loadChromium)();
+ const browser = await chromium.launch({ headless: true });
+ let scale = 1;
+ try {
+ const ctx = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" });
+ const p = await ctx.newPage();
+ await p.goto(pathToFileURL(page).href, { waitUntil: "load" });
+ await p.waitForSelector("body[data-promo-ready='1']", { timeout: 15000 });
+ scale = Number(await p.evaluate(() => document.body.dataset.promoScale)) || 1;
+ const tmp = path.join(/* turbopackIgnore: true */ work, "card.png");
+ await p.screenshot({ path: tmp, clip: { x: 0, y: 0, width, height } });
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } finally {
+ await browser.close();
+ }
+ const metaTmp = path.join(/* turbopackIgnore: true */ work, "meta.json");
+ await writeFile(/* turbopackIgnore: true */ metaTmp, JSON.stringify({ scale }) + "\n");
+ await rename(/* turbopackIgnore: true */ metaTmp, meta);
+ return { file, key, cached: false, scale };
+ } finally {
+ await rm(/* turbopackIgnore: true */ work, { recursive: true, force: true });
+ }
+}
+
+/**
+ * The filtergraph parts that end a segment on the card (PURE): the picture `vIn` held `hold` seconds past its end
+ * (its last frame cloned), the card (input `cardIdx`, a looped still) faded in from `seconds - lead` over `fade` and
+ * laid over it; the sound `aIn` faded out over its last PROMO_SOUND_OUT seconds and silence for the hold. Returns the
+ * parts and the pads they end on.
+ */
+export function promoFilterParts({ vIn, aIn, cardIdx, seconds, lead, fade, hold, fps }) {
+ const at = Math.max(0, seconds - lead);
+ const f = (n) => Number(n).toFixed(3);
+ return {
+ parts: [
+ `${vIn}tpad=stop_mode=clone:stop_duration=${f(hold)}[pmv]`,
+ `[${cardIdx}:v]fps=${fps},format=rgba,fade=t=in:st=0:d=${f(fade)}:alpha=1,setpts=PTS+${f(at)}/TB[pmc]`,
+ `[pmv][pmc]overlay=0:0:eof_action=pass:enable='gte(t,${f(at)})':format=auto[pmo]`,
+ `${aIn}afade=t=out:st=${f(Math.max(0, seconds - PROMO_SOUND_OUT))}:d=${f(PROMO_SOUND_OUT)},apad=pad_dur=${f(hold)}[pma]`,
+ ],
+ v: "[pmo]",
+ a: "[pma]",
+ seconds: seconds + hold,
+ at,
+ };
+}
+
+/** The card's input: the still looped for as long as it is up (its lead and its hold, a frame more). */
+export const promoCardInput = ({ file, lead, hold, fps }) => ["-loop", "1", "-framerate", String(fps), "-t", (lead + hold + 1 / fps).toFixed(3), "-i", file];
diff --git a/umtool/report-to-video/promo-card.test.mjs b/umtool/report-to-video/promo-card.test.mjs
@@ -0,0 +1,128 @@
+// The channel promo (lane clip-kit, slice D): its rules, its colours, its page, its timing in the segment's graph,
+// and the captions moved into its band.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ PROMO_TIMING, clipPromoErrors, linkColourOf, nameLines, promoBand, promoCardHtml, promoErrors, promoFilterParts, promoOf, promoPalette,
+ urlParts, validatePromo,
+} from "./promo-card.mjs";
+import { captionGroups, clipGeometry, desktopGeometry, verticalAss } from "./vertical.mjs";
+import { parseBox, parsePortraitFrom } from "../lib/report/promoCli.mjs";
+
+const PROMO = { name: ["Example Channel", "Live"], url: "https://kick.com/synth" };
+
+test("the rules: name and url needed, a portrait of the project's, timing in bounds, the fade inside the lead", () => {
+ assert.deepEqual(promoErrors(PROMO), []);
+ assert.deepEqual(promoErrors({ ...PROMO, qr: false, portrait: { file: "shots/a.png", box: [0.5, 0, 0.3, 0.5] }, kicker: "Clipped from", palette: { ground: "#101010", link: "#53fc18" }, lead: 4.5, fade: 0.7, hold: 1.5, captions: false }), []);
+ const no = (v, re) => assert.match(promoErrors(v).join("\n"), re, JSON.stringify(v));
+ no({ url: PROMO.url }, /name is the channel's name/);
+ no({ ...PROMO, name: ["a", "b", "c"] }, /one or two lines/);
+ no({ ...PROMO, name: "x".repeat(60) }, /at most 24/);
+ no({ ...PROMO, url: "kick.com/synth" }, /url is the channel's page/);
+ no({ ...PROMO, portrait: { file: "/etc/a.png" } }, /portrait is \{file, box\?\}/);
+ no({ ...PROMO, portrait: { file: "../a.png" } }, /portrait is \{file, box\?\}/);
+ no({ ...PROMO, portrait: { file: "a.png", box: [0.9, 0, 0.3, 1] } }, /box is \[x, y, w, h\]/);
+ no({ ...PROMO, palette: { ground: "black" } }, /palette\.ground is #rrggbb/);
+ no({ ...PROMO, palette: { sky: "#000000" } }, /palette\.sky is not a colour/);
+ no({ ...PROMO, lead: 20 }, /lead is 1–10 seconds/);
+ no({ ...PROMO, lead: 1, fade: 1.5 }, /fade \(1\.5 s\) is longer than its lead/);
+ no({ ...PROMO, wiggle: true }, /wiggle is not a key/);
+ assert.deepEqual(clipPromoErrors(false), []);
+ assert.deepEqual(clipPromoErrors({ hold: 2 }), []);
+ assert.match(clipPromoErrors({ name: "x" }).join(), /promo\.name is not a key/);
+ assert.match(validatePromo({ render: {}, timeline: [{ type: "post", id: "p", promo: false }] }).join(), /promo is a clip's/);
+});
+
+test("a clip's promo: the cut's with its own timing over it; none for `promo: false` or a cut that sets none; the lead held inside the clip", () => {
+ assert.equal(promoOf({ type: "clip" }, {}), null);
+ assert.equal(promoOf({ type: "clip", promo: false }, { promo: PROMO }), null);
+ const p = promoOf({ type: "clip", promo: { hold: 2 } }, { promo: { ...PROMO, lead: 3 } }, 30);
+ assert.deepEqual([p.lead, p.fade, p.hold, p.captions, p.note], [3, PROMO_TIMING.fade.default, 2, true, null]);
+ const short = promoOf({ type: "clip" }, { promo: PROMO }, 4);
+ assert.equal(short.lead, 3);
+ assert.match(short.note, /lead is 4\.5 s, longer than the clip less a second: 3 s/);
+ assert.equal(promoOf({ type: "clip" }, { promo: { ...PROMO, captions: false } }).captions, false);
+});
+
+test("the colours: the cut's palette, the promo's over it, the url's host in its platform's colour", () => {
+ const pal = promoPalette({ palette: { bg: "#12100c", fg: "#f6f1e6", accent: "#c8752a", amber: "#ffc860" } }, PROMO);
+ assert.deepEqual([pal.ground, pal.ink, pal.accent, pal.link, pal.plate], ["#12100c", "#f6f1e6", "#ffc860", "#53fc18", "#ffffff"], "the code's plate white whatever the palette");
+ // A streamer's own colours, for the card alone.
+ const own = promoPalette({ palette: { bg: "#12100c", fg: "#f6f1e6", accent: "#c8752a" } }, { ...PROMO, url: "https://example.org/me", palette: { ground: "#001122", accent: "#ff00aa" } });
+ assert.deepEqual([own.ground, own.accent, own.link], ["#001122", "#ff00aa", "#ff00aa"]);
+ assert.equal(linkColourOf("https://www.twitch.tv/x"), "#a970ff");
+ assert.equal(linkColourOf("nope"), null);
+ assert.deepEqual(urlParts("https://www.kick.com/synth/"), { host: "kick.com/", rest: "synth" });
+ assert.deepEqual(nameLines("Bread Baking Channel"), ["Bread Baking", "Channel"]);
+ assert.deepEqual(nameLines("Short"), ["Short"]);
+});
+
+test("the card's page: only portrait, name, url and code -- a kicker only when given; laid out inside the safe area, the captions' band kept clear", () => {
+ const fonts = { display: "file:///d.ttf", text: "file:///t.ttf" };
+ const palette = promoPalette({}, PROMO);
+ const html = promoCardHtml({ promo: PROMO, width: 1080, height: 1920, palette, portraitUrl: "file:///p.png", qrUrl: "file:///q.png", fonts });
+ assert.match(html, /<span class="">Example Channel<\/span><span class="u">Live<\/span>/);
+ assert.match(html, /<b>kick\.com\/<\/b>synth/);
+ assert.match(html, /data-promo-qr/);
+ assert.match(html, /data-promo-face/);
+ assert.ok(!/data-promo-kicker/.test(html), "no kicker unless the promo gives one");
+ assert.ok(!/Live on|Clipped from/.test(html.replace(/Live<\/span>/, "")), "no platform line, no stock kicker");
+ assert.match(promoCardHtml({ promo: { ...PROMO, kicker: "Clipped from" }, width: 1080, height: 1920, palette, fonts }), /data-promo-kicker="">Clipped from/);
+ assert.ok(!/data-promo-qr/.test(promoCardHtml({ promo: PROMO, width: 1080, height: 1920, palette, qrUrl: null, fonts })));
+ // A still: no animation in the page.
+ assert.ok(!/@keyframes|animation:|transition:/.test(html));
+ for (const [W, H] of [[1080, 1920], [1920, 1080]]) {
+ const b = promoBand({ width: W, height: H });
+ assert.ok(b.box.y1 < b.band.y0, `${W}x${H}: the card's content above the captions' band`);
+ if (H > W) {
+ assert.ok(b.box.y0 >= H * 0.08 && b.band.y1 <= H * 0.8 && b.box.x1 <= W * 0.88, "9:16: inside the platforms' safe area (top 8 %, bottom 20 %, right 12 %)");
+ }
+ assert.equal(promoBand({ width: W, height: H, captions: false }).band, null);
+ }
+});
+
+test("the segment's graph: held past its end, the card faded in at end - lead, the sound faded out and silent for the hold", () => {
+ const g = promoFilterParts({ vIn: "[vp]", aIn: "[al]", cardIdx: 3, seconds: 20, lead: 4.5, fade: 0.7, hold: 1.5, fps: 30 });
+ assert.deepEqual(g.parts, [
+ "[vp]tpad=stop_mode=clone:stop_duration=1.500[pmv]",
+ "[3:v]fps=30,format=rgba,fade=t=in:st=0:d=0.700:alpha=1,setpts=PTS+15.500/TB[pmc]",
+ "[pmv][pmc]overlay=0:0:eof_action=pass:enable='gte(t,15.500)':format=auto[pmo]",
+ "[al]afade=t=out:st=19.850:d=0.150,apad=pad_dur=1.500[pma]",
+ ]);
+ assert.deepEqual([g.v, g.a, g.seconds, g.at], ["[pmo]", "[pma]", 21.5, 15.5]);
+ // No zoom, no push: a still laid over.
+ assert.ok(!g.parts.join(";").includes("zoompan"));
+});
+
+test("the captions over the card: no group across its start, those after it in its band, the tag and the hook fading with it", () => {
+ const words = [0.2, 0.5, 0.8, 1.1, 1.4, 1.7, 2.0, 2.3].map((t, i) => ({ text: `w${i}`, start: t, end: t + 0.2 }));
+ const groups = captionGroups(words, { maxChars: 40, lines: 2, breaks: [1.3] });
+ assert.ok(groups.every((g) => g.words.every((w) => w.start < 1.3) || g.words.every((w) => w.start >= 1.3)), "none runs across the break");
+ assert.ok(groups.filter((g) => g.start < 1.3).every((g) => g.end <= 1.3), "none held past it");
+ const band = promoBand({ width: 1080, height: 1920 }).band;
+ const geo = clipGeometry("framed", {}, 1080, 1920);
+ const promo = { from: 1.3, fade: 0.5, captions: true, band };
+ const doc = verticalAss({ geo, render: {}, words, seconds: 3, tag: "Synth", hook: "A hook", promo });
+ const caps = doc.split("\n").filter((l) => l.includes(",cap,,"));
+ assert.ok(caps.some((l) => l.startsWith("Dialogue: 1,0:00:00.20") && !l.includes("\\pos")), "before the card: where they always are");
+ assert.ok(caps.filter((l) => /,0:00:0[12]\.[0-9]{2},cap/.test(l) && new RegExp(`\\\\an2\\\\pos\\(\\d+,${band.y1}\\)`).test(l)).length >= 1, "after: in the band, centred in the captions' margins");
+ assert.match(doc, /Dialogue: 0,0:00:00\.00,0:00:01\.80,tag,,0,0,0,,\{\\fad\(0,500\)\}Synth/);
+ assert.match(doc, /Dialogue: 0,0:00:00\.00,0:00:01\.80,hook,,0,0,0,,\{\\fad\(0,500\)\}A hook/);
+ // captions: false -- none said under the card.
+ const off = verticalAss({ geo, render: {}, words, seconds: 3, promo: { ...promo, captions: false, band: null } });
+ assert.ok(off.split("\n").filter((l) => l.includes(",cap,,")).every((l) => !/Dialogue: 1,0:00:0(1\.[3-9]|2)/.test(l)));
+ // A desktop clip's band, along its foot.
+ const dband = promoBand({ width: 1920, height: 1080 }).band;
+ const ddoc = verticalAss({ geo: desktopGeometry({}, 1920, 1080), render: {}, words, seconds: 3, W: 1920, H: 1080, promo: { from: 1.3, fade: 0.5, captions: true, band: dband } });
+ assert.ok(ddoc.includes(`\\pos(960,${dband.y1})`));
+ // No promo: the document it always wrote.
+ assert.equal(verticalAss({ geo, render: {}, words, seconds: 3, tag: "Synth", hook: "A hook" }), verticalAss({ geo, render: {}, words, seconds: 3, tag: "Synth", hook: "A hook", promo: null }));
+});
+
+test("umtool promo's arguments", () => {
+ assert.deepEqual(parsePortraitFrom("w01@10650.2"), { clip: "w01", at: 10650.2 });
+ assert.throws(() => parsePortraitFrom("w01"), /<clip>@<source second>/);
+ assert.deepEqual(parseBox("0.5,0,0.3,0.5"), [0.5, 0, 0.3, 0.5]);
+ assert.throws(() => parseBox("0.9,0,0.3,1"), /inside it/);
+});
diff --git a/umtool/report-to-video/reframe.mjs b/umtool/report-to-video/reframe.mjs
@@ -99,7 +99,8 @@ export function builtSpans(pieces, schedule) {
export async function assembleShort({ pieces, segmentsDir, built, outFile, render, schedule = null, log = () => {} }) {
const target = verticalKnobs(render).loudness;
- const whole = pieces.every((p) => !p.from && p.to === null);
+ // A hard join (a cold open into its clip: vertical-plan.mjs) is cut from the segments, never the build's crossfade.
+ const whole = pieces.every((p) => !p.from && p.to === null && !p.hard);
let src = built;
if (!whole) {
src = `${outFile}.joined-${process.pid}.mp4`;
diff --git a/umtool/report-to-video/vertical-plan.mjs b/umtool/report-to-video/vertical-plan.mjs
@@ -17,6 +17,8 @@
// take was made, and a short is cut from the take's items as the project now
// frames them.
+import { zoomEnd } from "./clip-zoom.mjs";
+
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const num = (v) => typeof v === "number" && Number.isFinite(v);
const r3 = (n) => Math.round(n * 1000) / 1000;
@@ -35,15 +37,67 @@ export function beatsOf(doc) {
});
}
-/** The project's per-clip framing (vertical, side) laid over a take's entry. */
+/**
+ * The keys of a clip a short reads from the PROJECT over the take's: set with `umtool set` after the take was made
+ * (its framing, its side post, the clip kit's keys). A batch's record snapshots them (lib/report/shortsBatch.mjs).
+ */
+export const PROJECT_KEYS = Object.freeze(["vertical", "side", "qr", "promo", "zooms", "coldOpen", "censor"]);
+
+/**
+ * A clip's hidden regions from two sources, ADD-ONLY (clip-censor.mjs: a privacy control): the boxes of both, never
+ * fewer than either had. A side that says none (absent, null) adds nothing; `false` (an opt-out) only stands when
+ * the other side has no boxes either.
+ */
+export function mergeCensor(a, b) {
+ const boxesOf = (v) => (isObj(v) && Array.isArray(v.boxes) ? v.boxes : []);
+ const all = [...boxesOf(a)];
+ for (const x of boxesOf(b)) if (!all.some((y) => JSON.stringify(y) === JSON.stringify(x))) all.push(x);
+ if (all.length) return { ...(isObj(b) ? b : {}), ...(isObj(a) ? a : {}), boxes: all };
+ if (a === false || b === false) return false;
+ return a ?? b ?? undefined;
+}
+
+/** The project's per-clip framing (PROJECT_KEYS) laid over a take's entry; its hidden regions added to the take's. */
export function withProjectFraming(entry, projectById) {
const own = projectById?.get?.(entry?.id);
if (!own || entry?.type !== "clip") return entry;
const out = { ...entry };
- for (const k of ["vertical", "side"]) if (own[k] !== undefined) out[k] = own[k];
+ for (const k of PROJECT_KEYS) {
+ if (k === "censor") {
+ const m = mergeCensor(own.censor, entry.censor);
+ if (m === undefined) delete out.censor;
+ else out.censor = m;
+ } else if (own[k] !== undefined) out[k] = own[k];
+ }
return out;
}
+/**
+ * The project's entries with a snapshot laid over them (`{<id>: {<key>: value | null}}`, a batch record's): each
+ * named key set (null: removed), so a rebuild reads each clip as the record saw it. Null: the entries as they are.
+ */
+export function withOverrides(timeline, overrides) {
+ if (!isObj(overrides)) return timeline;
+ return (timeline ?? []).map((e) => {
+ const o = typeof e?.id === "string" && isObj(overrides[e.id]) ? overrides[e.id] : null;
+ if (!o) return e;
+ const out = { ...e };
+ for (const [k, v] of Object.entries(o)) {
+ if (!PROJECT_KEYS.includes(k)) continue;
+ // Hidden regions: the snapshot's and the clip's boxes now, both (a box added since a batch was built is kept).
+ if (k === "censor") {
+ const m = mergeCensor(e.censor, v);
+ if (m === undefined) delete out.censor;
+ else out.censor = m;
+ continue;
+ }
+ if (v === null) delete out[k];
+ else out[k] = v;
+ }
+ return out;
+ });
+}
+
/** A clip entry cut to the source span [a, b]: its gaps inside kept, its own cut points dropped. */
export function cutClip(entry, a, b, id = entry.id) {
const { cutStart: _a, cutEnd: _b, ...rest } = entry;
@@ -70,7 +124,22 @@ export function cutClip(entry, a, b, id = entry.id) {
* @param {{ timeline: any[], beats?: any[] | null, items?: string[] | null, schedule?: any, cuts?: Map<string, any>,
* project?: any[] }} o
*/
-export function planVerticalCut({ timeline, beats = null, items = null, schedule = null, cuts = new Map(), project = [] }) {
+/**
+ * A clip's COLD OPEN (lane clip-kit, slice G; clip-kit.mjs coldOpenErrors): its `coldOpen` span cut out as an entry
+ * of its own, `<id>~co`, played before it with a hard cut -- its own words captioned, its own sound -- and ending on
+ * no card, carrying no code and no zooms outside its span; null for a clip with none.
+ */
+export function coldOpenEntry(entry) {
+ const co = entry?.coldOpen;
+ if (entry?.type !== "clip" || !isObj(co) || !num(co.from) || !num(co.to) || co.to <= co.from) return null;
+ const { coldOpen: _c, promo: _p, qr: _q, zooms, ...rest } = entry;
+ const out = { ...cutClip(rest, co.from, co.to, `${entry.id}~co`), promo: false, qr: false };
+ const inside = Array.isArray(zooms) ? zooms.filter((z) => num(z?.at) && z.at >= co.from && zoomEnd(z) <= co.to) : [];
+ if (inside.length) out.zooms = inside;
+ return out;
+}
+
+export function planVerticalCut({ timeline, beats = null, items = null, schedule = null, cuts = new Map(), project = [], coldOpens = true }) {
const projectById = new Map((project ?? []).filter((e) => typeof e?.id === "string").map((e) => [e.id, e]));
const byId = new Map((timeline ?? []).filter((e) => typeof e?.id === "string").map((e) => [e.id, withProjectFraming(e, projectById)]));
const out = [];
@@ -89,6 +158,15 @@ export function planVerticalCut({ timeline, beats = null, items = null, schedule
for (const id of items) {
const e = byId.get(id);
if (!e) throw new VerticalPlanError(`no item ${id} in the take`);
+ // Its cold open first (a hard cut into the clip: both pieces joined, not crossfaded by the build).
+ const co = coldOpens ? coldOpenEntry(e) : null;
+ if (co) {
+ out.push(co);
+ pieces.push({ id: co.id, from: 0, to: null, hard: true });
+ out.push({ ...e, id: uniq(id) });
+ pieces.push({ id: out[out.length - 1].id, from: 0, to: null, hard: true });
+ continue;
+ }
add({ ...e, id: uniq(id) });
}
return { timeline: out, pieces };
@@ -132,8 +210,8 @@ export function planVerticalCut({ timeline, beats = null, items = null, schedule
return { timeline: out, pieces };
}
-/** Is every piece played whole? (Then the build's own joined file is the short.) */
-export const piecesWhole = (pieces) => pieces.every((p) => !p.from && p.to === null);
+/** Is every piece played whole, none joined by a hard cut? (Then the build's own joined file is the short.) */
+export const piecesWhole = (pieces) => pieces.every((p) => !p.from && p.to === null && !p.hard);
/** A short's name for its files: the reel's, else "items". */
export const shortName = ({ reel = null, name = null } = {}) => String(name ?? reel ?? "items").replace(/[^A-Za-z0-9._-]+/g, "-");
diff --git a/umtool/report-to-video/vertical.mjs b/umtool/report-to-video/vertical.mjs
@@ -22,7 +22,7 @@
// command (lib/report/verticalCli.mjs) call it.
import {
- VERTICAL_HEIGHT, VERTICAL_WIDTH, clipLayoutOf, sidePostOf, sideSpan, stackedDeckWanted, verticalKnobs, verticalOn,
+ DESKTOP_HEIGHT, DESKTOP_WIDTH, VERTICAL_HEIGHT, VERTICAL_WIDTH, clipLayoutOf, desktopKnobs, sidePostOf, sideSpan, stackedDeckWanted, verticalKnobs, verticalOn,
} from "yt-dlp-transcript-common/lib/report/vertical.mjs";
import { assColour, assTime, captionText, cropPixels } from "./look.mjs";
@@ -32,6 +32,7 @@ export {
VERTICAL_DEFAULTS, VERTICAL_HEIGHT, VERTICAL_HOOKS, VERTICAL_KEYS, VERTICAL_POST_LAYOUTS, VERTICAL_SIDE_LAYOUTS,
VERTICAL_WIDTH, clipLayoutOf, sideErrors, sidePostOf, sideSpan, validateClipSides, validateVerticalFormat,
validateVerticalRender, verticalKnobs, verticalOn,
+ DESKTOP_CAPTION_SIZES, DESKTOP_DEFAULTS, DESKTOP_HEIGHT, DESKTOP_KEYS, DESKTOP_QR_CORNERS, DESKTOP_QR_SIZE, DESKTOP_WIDTH, desktopKnobs, validateDesktopRender,
} from "yt-dlp-transcript-common/lib/report/vertical.mjs";
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
@@ -77,6 +78,65 @@ export function verticalRender(render = {}) {
};
}
+/**
+ * The render a DESKTOP clip is built with (lane clip-kit): 1920x1080 at the cut's fps, the picture full frame -- no
+ * header, footer, corner QR, rail, deck, montage or intro -- the cut's palette, fonts and caption labels kept, its
+ * loudness the desktop knobs'. `render.desktop` stays: the geometry reads it.
+ */
+export function desktopRender(render = {}) {
+ const { chrome: _c, rail: _r, chromeEngine: _e, brand: _b, montage: _m, intro: _i, room: _ro, format: _f, ...rest } = render;
+ const k = desktopKnobs(render);
+ return {
+ ...rest,
+ width: DESKTOP_WIDTH,
+ height: DESKTOP_HEIGHT,
+ headerHeight: 0,
+ footerHeight: 0,
+ qr: false,
+ captions: { style: "speakers", ...(isObj(render.captions?.labels) ? { labels: render.captions.labels } : {}), size: "l" },
+ loudness: { target: k.loudness },
+ // What says this render IS a desktop build (the lint measures its code): `render.desktop` alone is a look key a
+ // landscape cut may carry for its batch.
+ desktopBuild: true,
+ };
+}
+
+/** The desktop clip's safe area in px (render.desktop.safe): every text keeps inside it. */
+export function desktopSafeArea(render, W = DESKTOP_WIDTH, H = DESKTOP_HEIGHT) {
+ const s = desktopKnobs(render).safe;
+ return { x0: Math.round(W * s.left), x1: Math.round(W * (1 - s.right)), y0: Math.round(H * s.top), y1: Math.round(H * (1 - s.bottom)) };
+}
+
+/** The desktop caption face's size (px) for its caption size. */
+export const desktopCaptionSize = (render, W = DESKTOP_WIDTH) => Math.round(W * ({ m: 0.028, l: 0.034, xl: 0.04 }[desktopKnobs(render).captions.size] ?? 0.034));
+
+/**
+ * A desktop clip's geometry: the picture full frame (fitted, never cropped), the source line top-left on a plate,
+ * the hook under it, the captions along the foot of the safe area; `qr` (clip-kit.mjs desktopQrBox) at a bottom
+ * corner narrows the captions on both sides so they keep centred and clear of it.
+ */
+export function desktopGeometry(render, W = DESKTOP_WIDTH, H = DESKTOP_HEIGHT, { qr = null } = {}) {
+ const a = desktopSafeArea(render, W, H);
+ const size = desktopCaptionSize(render, W);
+ // A code at the top left: the source line stands to its right.
+ const topLeftQr = qr && qr.x <= a.x0 + 1 && qr.y <= a.y0 + 1;
+ const tag = { x: topLeftQr ? qr.x + qr.size + Math.round(W * 0.012) : a.x0, y: a.y0, size: Math.round(W * 0.016) };
+ const bottomQr = qr && qr.y + qr.size > a.y1 - Math.round(H * 0.25);
+ const inset = bottomQr ? qr.size + Math.round(W * 0.015) : 0;
+ return {
+ layout: "desktop", size, tag, safe: a,
+ video: { x: 0, y: 0, w: W, h: H, aspect: W / H, fill: "fit" },
+ background: false,
+ hook: { top: tag.y + Math.round(tag.size * 2.2), size: Math.round(W * 0.026) },
+ captions: { align: 2, marginL: a.x0 + inset, marginR: W - a.x1 + inset, marginV: H - a.y1 },
+ };
+}
+
+/** The desktop clip's hook (render.desktop.hook, from the cut's own copy only), or null. */
+export function desktopHookOf(entry, render, sections = null) {
+ return hookText(desktopKnobs(render).hook, { entry, sectionTitle: sections?.get?.(entry?.id) ?? null });
+}
+
/** The safe area in px: text keeps inside x0..x1, y0..y1. */
export function safeArea(render, W = VERTICAL_WIDTH, H = VERTICAL_HEIGHT) {
const s = verticalKnobs(render).safe;
@@ -167,6 +227,17 @@ export function aspectCrop(sw, sh, aspect, crop = null) {
}
/**
+ * The part of the source a clip's layout shows (px: {x, y, w, h}) and the enlargement it shows it at (the frame's
+ * pixels over the source's) -- the box verticalClipGraph cuts, measured. A zoom (clip-zoom.mjs) multiplies it.
+ */
+export function pictureRegion(geo, srcW, srcH, crop = null) {
+ const v = geo.video;
+ if (v.fill === "fit") return { region: { x: 0, y: 0, w: srcW, h: srcH }, rest: Math.min(v.w / srcW, v.h / srcH) };
+ const box = v.aspect === 9 / 16 ? cropPixels(crop, srcW, srcH) : aspectCrop(srcW, srcH, v.aspect, crop);
+ return { region: box, rest: Math.min(v.w / box.w, v.h / box.h) };
+}
+
+/**
* The picture of a vertical clip as ONE filtergraph from a single input pad
* (written after the build's `${pic}`) to its last filter (the build names it):
* the source's own blur first (`blur`: clip-blur's filters on the source
@@ -240,7 +311,7 @@ export function landscapeSideOverlay(geo, side, W) {
* Words (segment seconds) to caption groups: at most `maxWords`, at most
* `maxChars` × `lines` characters, broken at a pause. `{start, end, words}`.
*/
-export function captionGroups(words, { maxWords = VERTICAL_GROUP_WORDS, maxChars = 24, lines = 2, pause = VERTICAL_GROUP_PAUSE, seconds = Infinity } = {}) {
+export function captionGroups(words, { maxWords = VERTICAL_GROUP_WORDS, maxChars = 24, lines = 2, pause = VERTICAL_GROUP_PAUSE, seconds = Infinity, breaks = [] } = {}) {
const used = (words ?? [])
.map((w) => ({ text: captionText(w.text), start: Number(w.start), end: Number(w.end) }))
.filter((w) => w.text && Number.isFinite(w.start) && Number.isFinite(w.end) && w.end > 0 && w.start < seconds)
@@ -252,7 +323,9 @@ export function captionGroups(words, { maxWords = VERTICAL_GROUP_WORDS, maxChars
for (const w of used) {
const chars = cur ? cur.words.reduce((n, x) => n + x.text.length + 1, 0) + w.text.length : 0;
const prev = cur?.words[cur.words.length - 1];
- if (!cur || cur.words.length >= maxWords || chars > budget || (cur.words.length >= 2 && w.start - prev.end >= pause)) {
+ // A break (the promo card's start): no group runs across it.
+ const across = cur && breaks.some((b) => cur.words[0].start < b && w.start >= b);
+ if (!cur || across || cur.words.length >= maxWords || chars > budget || (cur.words.length >= 2 && w.start - prev.end >= pause)) {
cur = { words: [w] };
groups.push(cur);
} else cur.words.push(w);
@@ -261,8 +334,10 @@ export function captionGroups(words, { maxWords = VERTICAL_GROUP_WORDS, maxChars
const start = g.words[0].start;
const last = g.words[g.words.length - 1].end;
const next = groups[i + 1]?.words[0].start ?? Infinity;
- const end = Math.min(seconds, Math.max(last, Math.min(next, last + VERTICAL_HOLD)));
- return { start, end: Math.max(end, start + 0.25), words: g.words };
+ // Never held across a break it was said before.
+ const wall = breaks.find((b) => start < b) ?? Infinity;
+ const end = Math.min(seconds, wall, Math.max(last, Math.min(next, last + VERTICAL_HOLD)));
+ return { start, end: Math.max(end, Math.min(start + 0.25, wall)), words: g.words };
});
}
@@ -312,15 +387,20 @@ export function hookText(hook, { entry = null, sectionTitle = null } = {}) {
* citation. `words` in segment seconds; `hook` the line (verticalHookOf), `side` the side post's span (captions
* move above an overlay card while it is up).
*/
-export function verticalAss({ geo, render, words = [], seconds, tag = null, hook = null, side = null, W = VERTICAL_WIDTH, H = VERTICAL_HEIGHT, font = VERTICAL_FONT }) {
- const k = verticalKnobs(render);
+export function verticalAss({ geo, render, words = [], seconds, tag = null, hook = null, side = null, W = VERTICAL_WIDTH, H = VERTICAL_HEIGHT, font = VERTICAL_FONT, knobs = null, promo = null }) {
+ // `promo` (promo-card.mjs; {from, fade, captions, band}): from `from` the card is up -- the captions move into its
+ // band (or, `captions: false`, stop there), the tag and the hook fade out with the card's fade in.
+ // `knobs` (a desktop clip's: desktopKnobs) speak over the vertical ones for its lines and its tag.
+ const k = knobs ?? verticalKnobs(render);
const quote = geo.layout === "quote";
const size = geo.size;
const width = W - geo.captions.marginL - geo.captions.marginR;
const maxChars = lineChars(width, size);
- const groups = captionGroups(words, quote
- ? { maxWords: VERTICAL_QUOTE_WORDS, maxChars, lines: 4, pause: 0.9, seconds }
- : { maxChars, lines: k.captions.lines, seconds });
+ const breaks = promo ? [promo.from] : [];
+ const groups0 = captionGroups(words, quote
+ ? { maxWords: VERTICAL_QUOTE_WORDS, maxChars, lines: 4, pause: 0.9, seconds, breaks }
+ : { maxChars, lines: k.captions.lines, seconds, breaks });
+ const groups = promo && !promo.captions ? groups0.filter((g) => g.start < promo.from) : groups0;
const C = VERTICAL_CAPTION_COLOURS;
const pal = { accent: "#c8752a", bg: "#12100c", ...(render?.palette ?? {}) };
const outline = Math.max(2, Math.round(size * 0.075));
@@ -339,15 +419,21 @@ export function verticalAss({ geo, render, words = [], seconds, tag = null, hook
const above = geo.captionsAbove;
for (const g of groups) {
const over = above && side && g.start < side.to && g.end > side.from;
- const mv = over ? `{\\an${above.align}\\pos(${Math.round(W / 2 + (above.marginL - above.marginR) / 2)},${H - above.marginV})}` : "";
+ const onCard = promo?.band && g.start >= promo.from;
+ const mv = onCard
+ ? `{\\an2\\pos(${Math.round(W / 2 + (cap.marginL - cap.marginR) / 2)},${promo.band.y1})}`
+ : over ? `{\\an${above.align}\\pos(${Math.round(W / 2 + (above.marginL - above.marginR) / 2)},${H - above.marginV})}` : "";
events.push(`Dialogue: 1,${assTime(g.start)},${assTime(g.end)},cap,,0,0,0,,${mv}${karaokeText(g)}`);
}
- if (tag && k.tag && geo.tag) events.push(`Dialogue: 0,${assTime(0)},${end},tag,,0,0,0,,${captionText(tag)}`);
+ // Under the card, the tag and the hook go as it comes up.
+ const fixedEnd = promo ? assTime(Math.min(seconds, promo.from + promo.fade)) : end;
+ const fadeOut = promo ? `{\\fad(0,${Math.round(promo.fade * 1000)})}` : "";
+ if (tag && k.tag && geo.tag) events.push(`Dialogue: 0,${assTime(0)},${fixedEnd},tag,,0,0,0,,${fadeOut}${captionText(tag)}`);
const h = typeof hook === "string" && hook.trim() ? hook.trim() : null;
- if (h && geo.hook) events.push(`Dialogue: 0,${assTime(0)},${end},hook,,0,0,0,,${captionText(h)}`);
+ if (h && geo.hook) events.push(`Dialogue: 0,${assTime(0)},${fixedEnd},hook,,0,0,0,,${fadeOut}${captionText(h)}`);
if (quote) {
- events.push(`Dialogue: 0,${assTime(0)},${end},mark,,0,0,0,,“`);
- if (tag) events.push(`Dialogue: 0,${assTime(0)},${end},cite,,0,0,0,,— ${captionText(tag)}`);
+ events.push(`Dialogue: 0,${assTime(0)},${fixedEnd},mark,,0,0,0,,${fadeOut}“`);
+ if (tag) events.push(`Dialogue: 0,${assTime(0)},${fixedEnd},cite,,0,0,0,,${fadeOut}— ${captionText(tag)}`);
}
return [
"[Script Info]",