Archilyzer · Source

archilyzer

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

commit 9e1301b69ad4972f43ede5479477710d31964bed
parent 725a908c1f36b869d1f4036f3fa62a75ce881d09
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 21:26:01 -0500

clip kit D: the channel promo -- the card a per-clip build ends on

render.promo {name, url, qr?, portrait?, kicker?, palette?, lead?, fade?, hold?, captions?}
(report-to-video promo-card.mjs): the last clip of a short, a desktop clip or a batch
ends on the streamer's card -- portrait in a ring, the name stacked, the channel's page
(its host in the platform's colour), its code; a kicker only when given; a still. The
picture dissolves into it `lead` (4.5) s before the clip's end over `fade` (0.7), the
clip's sound on under it, then it holds `hold` (1.5) s in silence: composed inside the
segment's own encode (promoFilterParts), no extra pass.

The captions stay over the card in a band it keeps clear (verticalAss `promo`: no group
across its start, those after it moved there; the tag and hook fade with it). Colours
from render.palette, render.promo.palette over them for the card alone; the faces are
the repository's (Archivo, IBM Plex Sans). Drawn by chromium from one template in both
shapes, cached by key.

A clip's `promo` (false | {lead, fade, hold}); `umtool vertical --no-promo
--promo-lead/--promo-fade/--promo-hold`, `umtool shorts --no-promo`; build-video
--no-promo/--promo-knobs. `umtool promo <p> --portrait-from <clip>@<s> [--box]`,
`--draw`; /api/report/promo-card (the card's PNGs, the portrait); the Look panel's
Channel promo with Draw the card; the clip editor's End card and Use this frame as the
promo portrait. Validated by the writer (updateRender, updateClip), the lint (the
portrait's file) and the build.

No render.promo: argv and segments unchanged (render test: a clip's promo: false is
byte-identical to a cut with none). e2e: clip-kit.spec.ts (the look, the clip editor,
the batch through /api/cli).

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

Diffstat:
Mcommon/lib/report/look.d.mts | 2+-
Mcommon/lib/report/look.mjs | 2+-
Mcommon/lib/report/videoAssistOps.test.ts | 2+-
Meditor/CHANGELOG.md | 16++++++++++++++++
Aumtool/app/api/report/promo-card/route.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 2++
Mumtool/components/projects/report/LookPanel.tsx | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/ClipEditor.tsx | 38++++++++++++++++++++++++++++++++++++--
Mumtool/docs/cli.md | 8++++++--
Mumtool/docs/knobs.md | 45+++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/clip-kit.spec.ts | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 7+++++++
Mumtool/lib/cli/groups.mjs | 10++++++++++
Mumtool/lib/cli/verbs.mjs | 7+++++++
Mumtool/lib/report/clipEditorTypes.ts | 2+-
Mumtool/lib/report/clipKit.test.mjs | 26++++++++++++++++++++++++++
Mumtool/lib/report/knobsCli.mjs | 6+++++-
Mumtool/lib/report/look.test.mjs | 2+-
Mumtool/lib/report/manifest.mjs | 5++++-
Aumtool/lib/report/promoCli.mjs | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/shortsBatch.test.mjs | 4++--
Mumtool/lib/report/shortsCli.mjs | 22+++++++++++++++-------
Mumtool/lib/report/verticalCli.mjs | 35++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/build-video.mjs | 48++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/clip-kit-render.test.mjs | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/clip-kit.mjs | 9++++++---
Mumtool/report-to-video/clip-kit.test.mjs | 2+-
Mumtool/report-to-video/lint.mjs | 12++++++++++--
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/promo-card.mjs | 420+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/promo-card.test.mjs | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/vertical-plan.mjs | 2+-
Mumtool/report-to-video/vertical.mjs | 40+++++++++++++++++++++++++++-------------
33 files changed, 1363 insertions(+), 49 deletions(-)

diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts @@ -4,7 +4,7 @@ type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>; type Render = Record<string, unknown> | null | undefined; -export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic" | "tallWindows" | "desktop"; +export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic" | "tallWindows" | "desktop" | "promo"; export const LOOK_KEYS: readonly LookKey[]; export const QR_CORNERS: readonly ["br", "bl", "tr", "tl"]; export const QR_LINK_VALUES: readonly ["cite", "moment", "channel"]; diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs @@ -29,7 +29,7 @@ const round2 = (n) => Number(Number(n).toFixed(2)); /** 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"]); +export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows", "desktop", "promo"]); /** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */ export const BAND_MAX = 240; 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, 17); + assert.equal(LOOK_KEYS.length, 18); }); test("render.mode and render.basic: deck is the default (no key), basic the footage alone; the fades checked", () => { diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,22 @@ # Changelog ## [Unreleased] +- **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. 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 @@ -956,6 +956,8 @@ const COMMANDS = { 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. + 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/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx @@ -43,9 +43,13 @@ type Look = { slide?: { travel?: number; blur?: number; grain?: number } | null; blur?: string; intro?: string | { style?: string; [k: string]: unknown } | null; + promo?: Promo | 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. */ @@ -80,6 +84,15 @@ type Draft = { deskTag: boolean; deskQr: string; deskSize: string; + promoOn: boolean; + promoName1: string; + promoName2: string; + promoUrl: string; + promoQr: boolean; + promoLead: string; + promoFade: string; + promoHold: string; + promoCaptions: boolean; }; /** A desktop clip's code as the panel shows it: off, or its corner (br when on with none). */ @@ -102,6 +115,39 @@ function desktopNext(was: Look["desktop"], d: Draft): Look["desktop"] { 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; @@ -135,6 +181,7 @@ function draftOf(l: Look, mode: Mode = "deck"): Draft { deskTag: l.desktop?.tag !== false, deskQr: deskQrOf(l.desktop), deskSize: l.desktop?.captions?.size ?? "l", + ...promoDraftOf(l.promo), }; } @@ -184,6 +231,11 @@ 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 desktop clips (render.desktop, the clip kit): the source line, a code, the captions' size. { const next = desktopNext(was.desktop, d); @@ -217,6 +269,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" }); @@ -376,6 +430,58 @@ 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&rsquo;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")} diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -890,7 +890,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"} kit={clip.kit ?? {}} onKit={(patch, done) => void write({ op: "kit", clip: clip.id, kit: patch }, done)} /> + <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} /> <RenderTake project={project} render={render} takes={takes} takesHref={takesHref} /> </aside> </div> @@ -1591,7 +1591,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, kit = {}, onKit }: { +function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy, live = false, kit = {}, onKit, playhead = null }: { project: string; clipId: string; short: { mtimeMs: number; size: number; stale: boolean } | null; @@ -1607,6 +1607,8 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent // 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; }) { const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null); const [err, setErr] = useState<string | null>(null); @@ -1642,6 +1644,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> @@ -1694,6 +1707,27 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent </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&rsquo;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> + )} {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}` : ""}`} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -274,8 +274,9 @@ 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] [--landscape] [--desktop] [--dry-run] [--intro] [--no-intro] [--no-outro] [--deck stacked\|bare] [--qr on\|off] [--qr-corner tr\|tl\|br\|bl]` | a vertical short (1080x1920) of a take's items | form · queued · *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] [--replace] [--dry-run]` | a batch of shorts: each clip of a take in each format, into shorts-<take>/ | 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]` | a vertical short (1080x1920) of a take's items | form · queued · *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] [--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* | @@ -551,6 +552,9 @@ $U vertical emberparadox/mr-obvious --take mid-14 --reel short-die --reframe --j - `--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)). - **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)). diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -411,6 +411,51 @@ vertical,desktop`). X autoplays muted, so the words are on the picture: | 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 the LAST clip of a per-clip build ends on it; the stacked vertical deck's end card and a reel's outro are other + things. A take's 16:9 look (`--landscape`) draws none. + +| 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]` | + ## 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`), diff --git a/umtool/e2e/clip-kit.spec.ts b/umtool/e2e/clip-kit.spec.ts @@ -0,0 +1,135 @@ +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); + // 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`); + await expect + .poll(async () => ((await (await page.request.get(`/api/cli?qid=${queued.qid}`)).json()) as { step: { state: string } }).step.state, { timeout: 400_000, intervals: [2000] }) + .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 @@ -701,6 +701,16 @@ export const GROUPS = [ ], }, { + 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]", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -324,7 +324,13 @@ export const VERBS = Object.freeze([ 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"), 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)" }), ], Q), + 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)" }), @@ -332,6 +338,7 @@ export const VERBS = Object.freeze([ 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("--replace", "set a file there aside and make it again"), dry(), ], Q), diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -30,7 +30,7 @@ export type EditorClip = { /** 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; [k: string]: unknown }; + kit?: { qr?: false | { corner?: string; links?: string }; name?: string; promo?: false | { lead?: number; fade?: number; hold?: number }; [k: string]: unknown }; /** Room at its edges (release 36 lane E): the clip's own `room` as written (false: none), and the edges it gets. */ room?: false | { tail?: boolean; head?: boolean } | null; roomEdges?: { tail: boolean; head: boolean } | null; diff --git a/umtool/lib/report/clipKit.test.mjs b/umtool/lib/report/clipKit.test.mjs @@ -43,3 +43,29 @@ test("updateClip: a clip's qr (whole or one field) and name; refused in the buil 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 }); + } +}); diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -58,7 +58,7 @@ 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"]); +export const KIT_SET_KEYS = Object.freeze(["qr", "qr.corner", "qr.links", "name", "promo", "promo.lead", "promo.fade", "promo.hold"]); 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", @@ -122,6 +122,8 @@ export const SET_USAGE = [ " 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.", " 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`.", @@ -364,6 +366,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso 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 (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 ?? []; @@ -402,6 +405,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso 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 ("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) { 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", "desktop"]); + assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows", "desktop", "promo"]); 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,7 +38,8 @@ 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 } from "umtool-report-to-video/clip-kit"; +import { CLIP_KIT_KEYS, clipKitErrors, validateClipKit } from "umtool-report-to-video/clip-kit"; +import { validatePromo } from "umtool-report-to-video/promo-card"; /** 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"; @@ -1911,6 +1912,8 @@ 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 ?? [] })); if (errors.length) throw new RenderRefused(errors); manifest.render = render; const nextToken = await writeManifestAtomic(dir, manifest); diff --git a/umtool/lib/report/promoCli.mjs b/umtool/lib/report/promoCli.mjs @@ -0,0 +1,140 @@ +// `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"; + +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 { + still = await grabStill(project, manifest, clip, at); + } 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("; ")); + const dir = 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.test.mjs b/umtool/lib/report/shortsBatch.test.mjs @@ -64,7 +64,7 @@ test("formats, items and the record's again", () => { 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 }); + assert.deepEqual(snapshotOf(e, PROJECT_KEYS), { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null, qr: null, promo: 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] } }); @@ -118,7 +118,7 @@ test("umtool shorts: each clip in each format into shorts-<take>/, named, record 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. assert.deepEqual(calls.map((c) => [c.items[0], c.landscape, c.knobs.maxSeconds, c.knobs.clip]), [["m01", false, 180, "framed"], ["m01", true, 140, "framed"], ["w01", false, 180, "framed"], ["w01", true, 140, "framed"]]); - assert.deepEqual(calls[2].overrides, { w01: { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null, qr: null } }); + assert.deepEqual(calls[2].overrides, { w01: { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null, qr: null, promo: 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"]); diff --git a/umtool/lib/report/shortsCli.mjs b/umtool/lib/report/shortsCli.mjs @@ -16,14 +16,15 @@ 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, snapshotOf } from "./shortsBatch.mjs"; -import { CliError, buildShort, isRefusal, knobsOfFlags, takeManifestOf } from "./verticalCli.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] [--replace] [--dry-run] [--json]", + " [--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] [--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", @@ -34,10 +35,11 @@ export const SHORTS_USAGE = [ "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"]); -const BOOL = new Set(["--all", "--again", "--replace", "--dry-run", "--json", "--help"]); +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"]); function parse(args) { /** @type {Record<string, string>} */ @@ -112,7 +114,9 @@ export async function shortsCommand(args, { reportsRoot = REPORTS_ROOT, log = co } catch (e) { throw new CliError(e instanceof Error ? e.message : String(e)); } - const knobs = knobsOfFlags(p.flags); + // 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 } : {}) }; const takeManifest = await takeManifestOf(dir, take); let entries; try { @@ -177,9 +181,13 @@ export async function shortsCommand(args, { reportsRoot = REPORTS_ROOT, log = co await rename(file.replace(/\.mp4$/, ".json"), aside.replace(/\.mp4$/, ".json")).catch(() => {}); } say(`shorts: ${c.id} (${c.name}) ${f} …`); - const fk = knobsForFormat(c.knobs, f); + const { promo: promoKnob, ...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 } }, + { + 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 } : {}), + }, { reportsRoot, say }, ); const rec = "record" in done ? done.record : null; diff --git a/umtool/lib/report/verticalCli.mjs b/umtool/lib/report/verticalCli.mjs @@ -29,6 +29,7 @@ export const VERTICAL_USAGE = [ " [--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 | --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]", "", "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", @@ -58,12 +59,15 @@ export const VERTICAL_USAGE = [ "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.", ].join("\n"); export class CliError extends Error {} -const VALUED = new Set(["--take", "--reel", "--beats", "--items", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max", "--name", "--out", "--deck", "--qr", "--qr-corner"]); -const BOOL = new Set(["--reframe", "--landscape", "--desktop", "--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", "--dry-run", "--json", "--help", "--intro", "--no-intro", "--no-outro"]); export function parse(args) { /** @type {Record<string, string>} */ @@ -163,6 +167,21 @@ 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 { @@ -177,6 +196,7 @@ export function shortOptionsOf(p) { reframe: p.has("--reframe"), landscape: p.has("--landscape"), desktop: p.has("--desktop"), + ...promoOptionsOf(p.flags), dryRun: p.has("--dry-run"), intro: p.has("--intro"), noIntro: p.has("--no-intro"), @@ -250,6 +270,11 @@ export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} 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 promoArgs = 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(); @@ -299,7 +324,7 @@ export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} 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, + "--skip-fetch", "--no-chapters", "--desktop", "--desktop-knobs", JSON.stringify(dknobs), "--vertical-work", work, "--vertical-out", built, ...promoArgs, "--vertical-sections", JSON.stringify(Object.fromEntries(plan.timeline.map((e) => [e.id, sections.get(e.id.replace(/~\d+$/, "")) ?? null]))), ]; say(`vertical --desktop: building ${plan.timeline.length} item(s) 16:9 in the heavy slot …`); @@ -321,7 +346,7 @@ export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} 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, + "--skip-fetch", "--no-chapters", "--vertical", "--vertical-knobs", JSON.stringify(knobs), "--vertical-work", work, "--vertical-out", built, ...promoArgs, // 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]))), ]; @@ -357,7 +382,7 @@ export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} } 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, + knobs, ...(o.promo === false ? { promo: false } : o.promoKnobs ? { promo: o.promoKnobs } : {}), 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: 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), }; diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -237,6 +237,8 @@ import { 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"; // 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"; @@ -1860,6 +1862,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, geo, srcW: sw, srcH: sh, crop: entry.vertical?.crop ?? null, blur: await blurPicture(sw, sh), 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({ @@ -1868,12 +1873,27 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, 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 } : {}), ...(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: [ @@ -1884,9 +1904,10 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ...levelParts(null, g.a), `${g.v}${graph}${qrBox ? "[vp0]" : "[vp]"}`, ...qrParts, - cap ? `[vp]${cap.filter}[v]` : "[vp]null[v]", + ...(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, ], @@ -2244,7 +2265,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, ...(vertical.knobs ? { knobs: vertical.knobs } : {}) })); + 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"; @@ -6908,7 +6929,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), ...validateClipKit(whole), + ...validateGapEntries(whole), ...measureSettingsProblems(whole), ...validateAnalysisEntries(whole), ...validateClipKit(whole), ...validatePromo(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } @@ -7033,6 +7054,21 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly 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) { + const clips = (manifest.timeline ?? []).filter((e) => e?.type === "clip"); + dirs.vertical.promoFor = clips.length ? clips[clips.length - 1].id : null; + 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 @@ -8084,6 +8120,7 @@ async function main() { " [--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" + @@ -8150,6 +8187,9 @@ async function main() { // 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-kit-render.test.mjs b/umtool/report-to-video/clip-kit-render.test.mjs @@ -129,3 +129,78 @@ test("a short's code: at the top right of the safe area; none unless asked, the for (const p of ps) await rm(p.root, { recursive: true, force: true }); } }); + +// ---- slice D: the channel promo ------------------------------------------------------------------------------------- +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); + +/** 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 }); + } +}); diff --git a/umtool/report-to-video/clip-kit.mjs b/umtool/report-to-video/clip-kit.mjs @@ -23,6 +23,7 @@ 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"; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const q = (v) => JSON.stringify(v); @@ -33,7 +34,7 @@ export const QR_KEYS = Object.freeze(["scale", "quiet", "ecc", "margin", "corner 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"]); +export const CLIP_KIT_KEYS = Object.freeze(["qr", "name", "promo"]); /** A clip's pinned file name in a batch (shortsBatch.mjs): at most this many characters. */ export const CLIP_NAME_MAX = 60; @@ -61,8 +62,10 @@ export function clipKitErrors(entry, where = "clip") { 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`); } - if ((entry.qr !== undefined || entry.name !== undefined) && entry.type !== undefined && entry.type !== "clip") { - errors.push(`${where}: qr and name are a clip's`); + // Its channel promo (promo-card.mjs): false, or its own timing. + errors.push(...clipPromoErrors(entry.promo, `${where}.promo`)); + if ((entry.qr !== undefined || entry.name !== undefined || entry.promo !== undefined) && entry.type !== undefined && entry.type !== "clip") { + errors.push(`${where}: qr, name and promo are a clip's`); } return errors; } diff --git a/umtool/report-to-video/clip-kit.test.mjs b/umtool/report-to-video/clip-kit.test.mjs @@ -68,7 +68,7 @@ test("the rules refuse what cannot be drawn, by name", () => { 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 and name are a clip's/); + assert.match(clipKitErrors({ type: "post", qr: false }, "p1").join(), /qr, name and promo 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. diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -124,6 +124,7 @@ import { roomWindowWarnings } from "./room.mjs"; import { qrUrlFor } from "./render-cards.mjs"; import { archiveMomentUrl } from "./site-links.mjs"; import { clipQrUrl, cornerQrOf, desktopQrOf, expiringLinkNote, validateClipKit, verticalQrOf } from "./clip-kit.mjs"; +import { validatePromo } from "./promo-card.mjs"; import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs"; import { validatePodcast } from "./build-podcast.mjs"; import { draftsReviewFromNarration, draftsReviewProblems, readDraftsReview } from "./drafts-review.mjs"; @@ -362,8 +363,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). - ...validateClipKit(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), // 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). @@ -506,6 +507,13 @@ 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 })); + // 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)`); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -29,6 +29,7 @@ "./vertical-deck": "./vertical-deck.mjs", "./vertical-plan": "./vertical-plan.mjs", "./clip-kit": "./clip-kit.mjs", + "./promo-card": "./promo-card.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,420 @@ +// 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 } 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; +/** 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; + out.plate = ok(own.plate) ?? out.ink; + 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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); +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: ${px(1.6)}; border-radius: ${px(1.6)}; width: ${px(sz.q)}; height: ${px(sz.q)}; flex: none; } +.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")) }; + const work = path.join(/* turbopackIgnore: true */ dir, `.promo-${key}-${process.pid}`); + await mkdir(/* turbopackIgnore: true */ work, { recursive: true }); + try { + let qrUrl = null; + if (qrText) { + const qrPng = path.join(/* turbopackIgnore: true */ work, "qr.png"); + await execFileP(process.env.QRENCODE_BIN ?? "qrencode", ["-o", qrPng, "-s", "10", "-m", "0", "-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(); + } + await writeFile(/* turbopackIgnore: true */ meta, JSON.stringify({ scale }) + "\n"); + 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", "#f6f1e6"]); + // 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/vertical-plan.mjs b/umtool/report-to-video/vertical-plan.mjs @@ -39,7 +39,7 @@ export function beatsOf(doc) { * 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"]); +export const PROJECT_KEYS = Object.freeze(["vertical", "side", "qr", "promo"]); /** The project's per-clip framing (PROJECT_KEYS) laid over a take's entry. */ export function withProjectFraming(entry, projectById) { diff --git a/umtool/report-to-video/vertical.mjs b/umtool/report-to-video/vertical.mjs @@ -300,7 +300,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) @@ -312,7 +312,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); @@ -321,8 +323,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 }; }); } @@ -372,16 +376,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, knobs = null }) { +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)); @@ -400,15 +408,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]",