commit a23976c8dcedf05170d5e362effe5f6609b3f5b7 parent 70bf0f44400b84d845c30075815e673117e37ae8 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Wed, 4 Nov 2026 02:21:15 -0500 umtool: media scenes -- consecutive post items with the same attachment are one scene: the attachment shown once and held in place, each message stacking in beside it, the one before shrinking and dimming as the next comes in (operator: "make it obvious he's posted multiple different messages about this same picture") report-to-video/post-media-scene.mjs, pure and memoised: the scenes planned from the timeline over the combo counter's repeat groups (repeatGroups -- the X media id, the bytes, the sound; no second matcher), the item as its scene plays it (sceneEntry: the anchor's file, crop and censor, the item's own timing, no push-in; a join item gains the slot), and the column (sceneLayout over a narrated item's thread layout, sceneSchedule for an un-narrated one, in the thread read's shape so read-follow pans it and the card draws it). The build, Play (postPlayEntry), the card's route and the bench draw the same scene; the combo badge pops on each repeat as before. Knobs: render.posts.scene.on (umtool posts scenes <p> on|off, which also lists the scenes), an item's scene=false|"join" (posts set-item scene=off| join|auto, the bench's media scene block). A conversation thread scene (lane/thread-tree) wins over a media scene: documented. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
19 files changed, 881 insertions(+), 49 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -5,10 +5,13 @@ import { avatarUrls } from "umtool-report-to-video/post-avatars"; import { jobState, startJob } from "@/lib/research/case-editor"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, manifestToken, updatePostFx, updatePostItem, updatePostNarration } from "@/lib/report/manifest.mjs"; -import { pickedTake } from "umtool-report-to-video/post-narration"; +import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { scriptWordTimes } from "umtool-report-to-video/word-zoom"; import { followKnobs } from "umtool-report-to-video/read-follow"; import { threadLayout } from "umtool-report-to-video/post-thread"; +import { mediaSceneById, sceneEntry, sceneLayout } from "umtool-report-to-video/post-media-scene"; +import { projectCombos } from "umtool-report-to-video/post-combo-prints"; +import { channelsDirFor } from "@/lib/projects/report.mjs"; import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxCli.mjs"; import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; @@ -173,8 +176,21 @@ export async function GET(request: Request) { } catch (e) { return new Response(e instanceof Error ? e.message : String(e), { status: 500 }); } - const followOn = q.get("phase") !== "media" && followKnobs(found.item, (found.manifest.render ?? render) as Record<string, unknown>).on; - const html = postCardHtml(found.item, { + const cutRender = (found.manifest.render ?? render) as Record<string, unknown>; + const followOn = q.get("phase") !== "media" && followKnobs(found.item, cutRender).on; + // Its MEDIA SCENE (post-media-scene.mjs): neighbours that carry the same attachment, by the combo counter's + // groups -- the card drawn as the scene plays it (a join item gains the attachment's slot), the scene's + // earlier messages above it. Only looked for beside another post item. + const tl = (Array.isArray(found.manifest.timeline) ? found.manifest.timeline : []) as Entry[]; + const at = tl.findIndex((e) => e?.id === found.item!.id); + const besidePost = tl[at - 1]?.type === "post" || tl[at + 1]?.type === "post"; + const groups = besidePost + ? ((await projectCombos(r.project.dir, found.manifest, { channelsDir: channelsDirFor(r.project.dir, found.manifest) }).catch(() => ({ groups: [] }))).groups as unknown[]) + : []; + const scene = groups.length ? mediaSceneById(tl, found.item.id, groups as never, cutRender) : null; + const item = sceneEntry(found.item, scene) as Entry; + const tlayout = threadLayout(item, cutRender, { prev: found.prev }); + const html = postCardHtml(item, { width: w, height: h, avatars, palette: (render.palette ?? {}) as Record<string, string>, fonts: { regular: `${base}&font=regular`, bold: `${base}&font=bold` }, @@ -182,8 +198,9 @@ export async function GET(request: Request) { parentShotUrl: parentShot, // Its read-follow (read-follow.mjs): the blocks and the flow Play lights and pans, as the build's page has them. follow: followOn, - // A threaded card (post-thread.mjs): its tiles, as the plan's follow.thread has them. - thread: followOn ? threadLayout(found.item, (found.manifest.render ?? render) as Record<string, unknown>, { prev: found.prev }) : null, + // A threaded card (post-thread.mjs): its tiles, as the plan's follow.thread has them -- a media scene's + // earlier messages above them (a narrated item's thread read is its base; un-narrated, none). + thread: followOn ? (scene ? sceneLayout(isNarrated(item) ? tlayout : null, item, scene) ?? tlayout : tlayout) : null, redaction, }); return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } }); diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -17,6 +17,7 @@ import ComboBadge, { type ComboInfo } from "./review/ComboBadge"; import { liveCombo } from "umtool-report-to-video/post-combo"; import PostZoomPanel from "./PostZoomPanel"; import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; +import { sceneEntry } from "umtool-report-to-video/post-media-scene"; // --------------------------------------------------------------------------- // THE POST BENCH, the client half (PostBenchPage.tsx): the item played on its @@ -74,8 +75,11 @@ const CROPS: Array<{ label: string; crop: number[] | null }> = [ { label: "bottom half", crop: [0, 0.5, 1, 0.5] }, ]; +/** Its media scene (post-media-scene.mjs mediaSceneOf), as the page counted it. */ +type Scene = { key: string; n: number; of: number; ids: string[]; media: number | null; anchor: { id: string; media: number; entry: { id: string; post: string; media: Array<Record<string, unknown>> } }; before: Array<Record<string, unknown>> } | null; + export default function PostBench({ - project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null, + project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null, scene: savedScene = null, }: { project: string; entry: Entry; @@ -92,6 +96,8 @@ export default function PostBench({ combo?: ComboInfo | null; /** The timeline entry before it in the cut (post-thread.mjs: a parent that is that item is carried in). */ before?: Record<string, unknown> | null; + /** Its media scene (post-media-scene.mjs): the neighbours with the same attachment, as saved. */ + scene?: Scene; }) { const router = useRouter(); const [entry, setEntry] = useState<Entry>(initial); @@ -99,7 +105,11 @@ export default function PostBench({ const [token, setToken] = useState(initialToken); const [status, setStatus] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); - const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry, render, { prev: before }) as PostPlan)), [entry, initial, initialPlan, render, before]); + // In a media scene (post-media-scene.mjs) the item plays as the scene does: the shared attachment the + // anchor's, the scene's earlier messages above its card. Out of it (scene: false, unsaved) at once. + const scene = entry.scene === false ? null : savedScene; + const shown = useMemo(() => sceneEntry(entry, scene) as Entry, [entry, scene]); + const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(shown, render, { prev: before, mediaScene: scene }) as PostPlan)), [entry, shown, initial, initialPlan, render, before, scene]); const total = plan.total; const [s, setS] = useState(0); const [playing, setPlaying] = useState(false); @@ -161,6 +171,8 @@ export default function PostBench({ redact: typeof e.redact === "boolean" ? e.redact : null, // Its read-follow (read-follow.mjs): false is off; its knobs, each null when it is the cut's. follow: e.follow === false ? false : e.follow && typeof e.follow === "object" ? { on: null, dim: null, ease: null, ...(e.follow as Record<string, unknown>) } : null, + // Its media scene (post-media-scene.mjs): false (never in one), "join", or null (by its attachment). + scene: e.scene === false || e.scene === "join" ? e.scene : null, // Its thread read (post-thread.mjs): its knobs, each null when it is the cut's. thread: e.thread && typeof e.thread === "object" ? { parent: null, quoted: null, carry: null, reveal: null, shrink: null, dim: null, seconds: null, pan: null, ...(e.thread as Record<string, unknown>) } : null, media: Object.fromEntries( @@ -215,7 +227,9 @@ export default function PostBench({ setSaved(j.entry); setToken(j.token ?? null); setStatus("saved"); - }, [entry, project, token]); + // A scene knob changed: the page counts the scene again (its neighbours are read on the server). + if ((saved.scene ?? null) !== (j.entry.scene ?? null)) router.refresh(); + }, [entry, project, token, saved, router]); // Transcribe a video attachment through the editor (a job), then follow it. const [jobs, setJobs] = useState<Record<number, { job: string; state: string; error?: string }>>({}); @@ -280,8 +294,8 @@ export default function PostBench({ </span> </div> <div className="relative w-full overflow-hidden rounded border border-seam bg-black" style={{ aspectRatio: `${box.width} / ${box.height}` }}> - <PostItemPlayer project={project} entry={entry} plan={plan} box={box} s={s} playing={playing} cardKey={token} /> - <ComboBadge project={project} entry={entry} plan={plan} combo={liveCombo(combo, render, entry) as ComboInfo | null} box={box} s={s} playing={playing} /> + <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} /> + <ComboBadge project={project} entry={shown} plan={plan} combo={liveCombo(combo, render, entry) as ComboInfo | null} box={box} s={s} playing={playing} /> </div> <div className="flex items-center gap-2 text-[12px]"> <button type="button" className={btn} data-post-bench-play="" onClick={() => (s >= total ? (setS(0), setPlaying(true)) : setPlaying((p) => !p))}> @@ -402,6 +416,41 @@ export default function PostBench({ </label> </section> + <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-bench-scene={savedScene ? savedScene.key : ""}> + <h2 className="micro mb-2">media scene</h2> + {savedScene && entry.scene !== false ? ( + <p className="m-0 text-text-2" data-post-bench-scene-members=""> + message {savedScene.n + 1} of {savedScene.of} about one attachment:{" "} + {savedScene.ids.map((id, k) => ( + <span key={id}> + {k > 0 && " → "} + {id === entry.id ? <b>{id}</b> : <Link href={postBenchHref(project, id, fromPlay ? { play: { at: 0 } } : {})} className="ink-link">{id}</Link>} + </span> + ))} + . The attachment stays put through it; the earlier messages stack above this one. + {savedScene.anchor.id !== entry.id && ( + <span className="block" data-post-bench-scene-anchor={savedScene.anchor.id}> + It is drawn as <Link href={postBenchHref(project, savedScene.anchor.id, fromPlay ? { play: { at: 0 } } : {})} className="ink-link">{savedScene.anchor.id}</Link>'s (the scene's first to carry it): set its crop and censor there. + </span> + )} + </p> + ) : ( + <p className="m-0 text-text-2">{entry.scene === false ? "kept out of any scene" : "in no scene: no neighbour carries the same attachment"}</p> + )} + <label className="mt-2 flex items-center gap-2"> + in a scene + <select + value={entry.scene === false ? "off" : entry.scene === "join" ? "join" : "auto"} + onChange={(e) => setEntry((x) => ({ ...x, scene: e.target.value === "off" ? false : e.target.value === "join" ? "join" : undefined }))} + data-post-bench-scene-knob="" + > + <option value="auto">auto (when a neighbour shares its attachment)</option> + <option value="off">never (this item breaks a scene)</option> + <option value="join">join the scene beside it (no attachment of its own)</option> + </select> + </label> + </section> + {combo && ( <PostComboPanel project={project} diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -7,6 +7,7 @@ import { projectHref, playHref } from "@/lib/hrefs"; import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; import { postItemPlan } from "umtool-report-to-video/post-item"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; +import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; import type { ProjectRef } from "@/lib/project-types"; import type { PostPlan } from "./review/PostItemPlayer"; import type { ComboInfo } from "./review/ComboBadge"; @@ -33,8 +34,11 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj const k = neighbours.indexOf(id); const fromPlay = search.from === "play"; // Its combo (post-combo.mjs): counted over the whole cut, as the build counts it. - const combos = (await projectCombos(project.dir, m, { channelsDir: channelsDirFor(project.dir, m) }).catch(() => ({ combos: {} }))).combos as Record<string, ComboInfo>; + const counted = await projectCombos(project.dir, m, { channelsDir: channelsDirFor(project.dir, m) }).catch(() => ({ combos: {}, groups: [] })); + const combos = counted.combos as Record<string, ComboInfo>; const combo = combos[id] ?? null; + // Its media scene (post-media-scene.mjs): its neighbours with the same attachment, by the combo's groups. + const scene = mediaSceneOf(tl, at, counted.groups, render); const back = fromPlay ? playHref(project.id, { clip: id, at: Number(search.at ?? 0) || null }) : projectHref(project.id, { tab: "cut" }); return ( <div className="flex h-full flex-col"> @@ -49,7 +53,8 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj entry={entry} token={await manifestToken(project.dir)} box={{ width: box.width, height: box.height }} - plan={postItemPlan(entry, render, { prev: at > 0 ? tl[at - 1] : null }) as unknown as PostPlan} + plan={postItemPlan(sceneEntry(entry, scene), render, { prev: at > 0 ? tl[at - 1] : null, mediaScene: scene }) as unknown as PostPlan} + scene={scene} render={render} before={at > 0 ? tl[at - 1] : null} combo={combo} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -124,6 +124,8 @@ export type PlayEntry = { postPlan?: PostPlan; /** Its combo badge (post-combo.mjs): the attachment it repeats, its count, the knobs. */ postCombo?: ComboInfo; + /** Its media scene (post-media-scene.mjs): which, its place in it, its items, the anchor. */ + postScene?: { key: string; n: number; of: number; ids: string[]; anchor: string }; }; export type PlayViewData = { @@ -854,6 +856,7 @@ export default function PlayCut({ speed={rate} published={asPublished} uncensored={uncensored} + scene={postNow.entry.postScene ?? null} /> ) : null; // A post item that repeats an earlier one's attachment: its combo badge, beside the player. diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -348,7 +348,7 @@ function MediaEl({ } export default function PostItemPlayer({ - project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, + project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, }: { project: string; take?: string | null; @@ -366,6 +366,8 @@ export default function PostItemPlayer({ published?: boolean; /** With `published`: the UNCENSORED cut -- the slurs as posted (post-slurs.mjs), the redaction kept. */ uncensored?: boolean; + /** Its media scene (post-media-scene.mjs): which, and its place in it. */ + scene?: { key: string; n: number; of: number } | null; }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); @@ -527,6 +529,8 @@ export default function PostItemPlayer({ data-post-follow-offset={followNow && followRoute?.segments.length ? String(Math.round(followNow.offset)) : undefined} data-post-follow-pans={followRoute ? String(followRoute.segments.length) : undefined} data-post-thread={follow?.thread ? String(follow.thread.tiles.length) : undefined} + data-post-scene={scene ? scene.key : undefined} + data-post-scene-n={scene ? `${scene.n + 1}/${scene.of}` : undefined} data-post-thread-tiles={followNow?.tiles ? Object.entries(followNow.tiles).map(([sc, v]) => `${sc}=${v[0]}/${v[1]}`).join(" ") : undefined} className="pointer-events-none absolute inset-0 overflow-hidden" > diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -837,6 +837,24 @@ in the build's words (`validatePostCombos`). `k=` (empty) takes the default (the | attach what a capture holds to a post item that carries none (captured after it went in): its media copied in and set, nothing else of the entry changed; then it plays and counts | — | `umtool posts attach <p> <item>… \| --all [--dry-run]` | — | | the badge on the item's clock | Play the cut, the post bench (the player) | the build: `segments/<id>.mp4` (the plain one `<id>.plain.mp4`, the record `<id>.combo.json`) | — | +## Media scenes (one attachment, several messages) + +Consecutive post items that carry the same attachment are one scene: the attachment shown once and held in +place, each message stacking in beside it ([report-video.md](report-video.md#media-scenes): what counts, the +anchor, the column, the thread rule). The rule is `report-to-video/post-media-scene.mjs` over the combo +counter's groups. The cut's knob rides on `render.posts.scene` (`updatePostSceneRender`), an item's on the item +(`updatePostItem`), each refused in the build's words (`validatePostSceneRender`, `validatePostScene`). + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `render.posts.scene.on` — scenes at all (default on) | — | `umtool posts scenes <p> off` (`on`, `auto`: the default) | — | +| `scene` on a post item — `false`: never in a scene (it breaks one); `"join"`: an item with no attachment of its own joins the scene beside it (after a scene: that one; before: the next); absent: in one when a neighbour shares its attachment | post bench, **media scene**: its scene (message n of N, each item linked, the anchor named), **in a scene** (auto / never / join) | `umtool posts set-item <p> <item> scene=off` · `scene=join` · `scene=auto` | `POST /api/report/post-item {project, op: "set", id, patch: {scene: false \| "join" \| null}, token}` | +| the scene's look — the attachment is the ANCHOR's (its first item that carries it): its crop and censor; its motion is the thread read's | the anchor's bench (`media[i].crop`, `media[i].blur`); `thread.shrink` / `.dim` / `.seconds` / `.pan` on the item | `umtool posts set-item <p> <anchor> media.0.censor=below:0.38` · `umtool posts set-item <p> <item> thread.shrink=0.5` | as above | + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| the scenes: each one's items in order and its anchor | the post bench's **media scene** block; Play the cut draws them (the player's `data-post-scene`) | `umtool posts scenes <p> [--json]` | — | + ## The source backlog (Sources · Prioritize · Re-sweep when complete) The Overview tab's **sources** line (`components/projects/report/SourceBacklog.tsx`, `lib/report/sourceBacklog.*`): for each diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -889,6 +889,58 @@ went in: it draws nothing and does not count until it plays the attachment). and measured as `posts reel` would have made it, nothing else of the entry changed -- and from then it plays and counts. +### Media scenes + +CONSECUTIVE post items that carry the same attachment are ONE SCENE (operator, 4 Nov, on +the Mr. Obvious cut: *"show all these 'jiggle' messages in a way that makes it obvious +he's posted multiple different messages about this same picture"*). +`report-to-video/post-media-scene.mjs` is the rule (pure, memoised per timeline); the +build, Play, the card's route, the post bench and `umtool posts scenes` all read it. + +**What is the same attachment** is the combo counter's answer: its repeat groups (the X +media id, the bytes, `match: "audio"` the sound), never a second matcher. Two items are +in one scene when they are next to each other in the cut and share a group; anything else +between them (a clip, a post with another attachment, an item with `scene: false`) +breaks it. A post that talks about the picture without carrying it joins with +`scene: "join"`: after a scene it joins that scene, before one the scene that follows. + +**The attachment** is shown ONCE and stays put: every item of the scene draws the +scene's ANCHOR's (its first item that carries it) -- its file, its crop, its censor -- +in the same box from the first frame, never pushed in. Set the crop and censor on the +anchor (a later item's bench says so and links it). A video or a GIF keeps each item's +own in and out point (each read is timed to its own); an image is held. A join item +gains the attachment's slot beside its words. + +**The card**: an item after the scene's first is drawn as a column of tiles, the thread +read's (`post-thread.mjs`; read-follow pans it): the scene's earlier messages oldest +first, the one just before it in full as that item ended -- shrinking and dimming +(`thread.shrink`, `.dim`, over `.seconds`) as its own words come in under it -- the +older ones already small and dim. A narrated item's own thread read is kept under them +(the posts it answers and quotes, each shown in full while it is read); a post that is +both an earlier message and the post it answers (carried) is drawn once, as the +thread's. An un-narrated item draws the posts it answers small and dim above its words. +Each earlier message is drawn under its own redaction, slur mask and author rule. The +column rides on read-follow (on by default): with `follow: false` each card is drawn +alone and only the attachment carries the scene. + +**A thread scene and a media scene on the same item: the thread scene wins.** A +conversation thread drawn across items (lane/thread-tree's `post-conversation.mjs` +`planContext`) takes the card; the media scene keeps only the attachment. + +The combo badge still pops on each repeat (×2, ×3 … as each new message comes in); +redaction bars, the slur pill and beep, read-follow, word zooms, the author blur (with +an item's `redact: false` honoured) and the attachment's trims all play as before. + +```jsonc +"render": { "posts": { "scene": { "on": true } } }, // the cut's (default on) +"timeline": [ { "type": "post", "id": "p-…", "scene": false }, // never in a scene + { "type": "post", "id": "p-…", "scene": "join" } ] +``` + +`umtool posts scenes <p>` lists each scene, its items in order and its anchor; +`umtool posts scenes <p> off` turns them off for the cut; `umtool posts set-item <p> +<item> scene=off|join|auto` one item's. + ## The on-screen deck (`render.chrome`) Its knobs — the stamp's moment and count per clip, the stamp's look and words, the markers, a clip's sync and diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -70,6 +70,7 @@ import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs"; import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./rejectReasons.mjs"; import { DELIVERABLES_MODES } from "./storage.mjs"; import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, validatePostCombo, validatePostComboRender } from "umtool-report-to-video/post-combo"; +import { SCENE_DEFAULTS, validatePostSceneRender } from "umtool-report-to-video/post-media-scene"; import { createSnapshot, listSnapshots } from "./snapshots.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs"; @@ -2354,7 +2355,7 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i } /** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */ -export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact", "follow", "thread"]); +export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact", "follow", "thread", "scene"]); /** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */ export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ @@ -2362,7 +2363,7 @@ export const POST_CONTEXT_KNOBS = Object.freeze(["paraphrase"]); /** * SET A POST ITEM's KNOBS (the post bench, `umtool posts set-item`): `patch` - * is `{ hold?, mediaLayout?, redact?, follow?: false | { on?, dim?, ease? }, thread?: { parent?, quoted?, carry?, + * is `{ hold?, mediaLayout?, redact?, scene?: false | "join", follow?: false | { on?, dim?, ease? }, thread?: { parent?, quoted?, carry?, * reveal?, shrink?, dim?, seconds?, pan? }, media?: { <i>: { start?, end?, mute?, * crop?, push?, words?, blur? } }, quoted?: { paraphrase? }, parents?: { <i>: * { paraphrase? } } }`; a null clears a knob (the default again), and so @@ -2544,6 +2545,37 @@ export async function updatePostComboRender(dir, patch, { token = null } = {}) { } /** + * THE CUT's MEDIA SCENES (`render.posts.scene`; `umtool posts scenes <p> + * on|off`): `{ on }` -- consecutive post items with the same attachment drawn + * as one scene (post-media-scene.mjs), on by default; a null knob back to the + * default. Validated with the build's check. + * + * @param {string} dir + * @param {Record<string, any>} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostSceneRender(dir, patch, { token = null } = {}) { + if (!isObj(patch) || !Object.keys(patch).length) throw new Error("nothing to set"); + for (const k of Object.keys(patch)) if (!(k in SCENE_DEFAULTS)) throw new Error(`${k} is not a scene knob (${Object.keys(SCENE_DEFAULTS).join(", ")})`); + return structural(dir, "post-scene-cut", token, (m) => { + if (!isObj(m.render)) m.render = {}; + const posts = isObj(m.render.posts) ? m.render.posts : {}; + const c = isObj(posts.scene) ? posts.scene : {}; + for (const [k, v] of Object.entries(patch)) { + if (v === null || v === undefined) delete c[k]; + else c[k] = v; + } + if (Object.keys(c).length) posts.scene = c; + else delete posts.scene; + if (Object.keys(posts).length) m.render.posts = posts; + else delete m.render.posts; + const errors = [...validatePostSceneRender(m.render), ...validatePostComboRender(m.render)]; + if (errors.length) throw new StructureRefused(errors); + return { scene: m.render.posts?.scene ?? null }; + }); +} + +/** * ATTACH A CAPTURE's MEDIA to post items that carry none (`umtool posts * attach`): `patches` is `{ <id>: media[] }`, each list already copied into * the project; an item that has an attachment by now is left as it is. One diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -21,6 +21,7 @@ import { readWorkingCut } from "./workingCut.mjs"; import { sectionModel } from "./sectionEdit.mjs"; import { manifestToken } from "./manifest.mjs"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; +import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; const fin = (v) => typeof v === "number" && Number.isFinite(v); const text = (v) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : ""); @@ -40,8 +41,10 @@ export function headingOf(e) { * @param {Record<string, any>} e * @param {Record<string, any>} [render] * @param {Record<string, any> | null} [prev] the item before it in the cut + * @param {Record<string, any> | null} [mediaScene] its media scene (post-media-scene.mjs mediaSceneOf): `post` is + * the item as the scene plays it (the shared attachment the anchor's), its plan's card the scene's column */ -export function postPlayEntry(e, render = undefined, prev = null) { +export function postPlayEntry(e, render = undefined, prev = null, mediaScene = null) { const day = postDay(e.date); const dateKey = day ? Number(day.replace(/-/g, "")) : null; const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim(); @@ -54,9 +57,10 @@ export function postPlayEntry(e, render = undefined, prev = null) { dateLabel: dateKeyLabel(dateKey), date: day || null, quote: words || null, - post: e, + post: sceneEntry(e, mediaScene), // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in). - postPlan: postItemPlan(e, render, { prev }), + postPlan: postItemPlan(sceneEntry(e, mediaScene), render, { prev, mediaScene }), + ...(mediaScene ? { postScene: { key: mediaScene.key, n: mediaScene.n, of: mediaScene.of, ids: mediaScene.ids, anchor: mediaScene.anchor.id } } : {}), }; } @@ -109,9 +113,14 @@ export async function playView(project, { take = null, bare = false } = {}) { const { starts } = scheduleFrom(durs, D); const segments = timeline.map((e, i) => ({ id: e.id, start: Math.round(starts[i] * 1000) / 1000, duration: Math.round(durs[i] * 1000) / 1000 })); const cache = await projectCache(project, manifest); + // The combo counter's repeat groups (post-combo.mjs), counted over the cut played: its badges, and its media + // scenes (post-media-scene.mjs: neighbours with the same attachment). + const { combos, groups: repeatGroups } = timeline.some((e) => e.type === "post") + ? await projectCombos(project.dir, selected, { channelsDir: channelsDirFor(project.dir, base) }).catch(() => ({ combos: {}, groups: [] })) + : { combos: {}, groups: [] }; const entries = await Promise.all( timeline.map(async (e, i) => { - if (e.type === "post") return postPlayEntry(e, render, timeline[i - 1] ?? null); + if (e.type === "post") return postPlayEntry(e, render, timeline[i - 1] ?? null, mediaSceneOf(timeline, i, repeatGroups, render)); if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null }; const win = pickWindow(await windowsFor(project, e, cache), null); const dateKey = clipDateKey(e); @@ -157,10 +166,7 @@ export async function playView(project, { take = null, bare = false } = {}) { ); // The combo counter (post-combo.mjs): a post item that repeats an earlier one's attachment carries its badge // (`postCombo`: its count, which attachment, the knobs, whether it shows), counted over the cut played. - if (entries.some((e) => e.type === "post")) { - const { combos } = await projectCombos(project.dir, selected, { channelsDir: channelsDirFor(project.dir, base) }).catch(() => ({ combos: {} })); - for (const e of entries) if (e.type === "post" && combos[e.id]) Object.assign(e, { postCombo: combos[e.id] }); - } + for (const e of entries) if (e.type === "post" && combos[e.id]) Object.assign(e, { postCombo: combos[e.id] }); // The counter (the deck's tally): each stamp's landing second and count on // the estimate's clock, and each verdict's word -- the reel strip's // staircase before (or without) the chrome's own schedule. diff --git a/umtool/lib/report/postComboCli.mjs b/umtool/lib/report/postComboCli.mjs @@ -5,6 +5,7 @@ // umtool posts repeats <project> [--match id|file|audio] [--json] // umtool posts combo <project> [k=v …] [--json] the cut's (render.posts.combo) // umtool posts combo <project> <item> off|on|auto|k=v … [--json] one item's (`combo`) +// umtool posts scenes <project> [on|off] [--json] the media scenes (post-media-scene.mjs) // // `repeats` lists each repeated attachment with its posts in the cut's order // (their dates, the tier that matched) and the badge each draws; a post item @@ -19,7 +20,8 @@ import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { copyFile, mkdir, realpath, stat } from "node:fs/promises"; import path from "node:path"; -import { attachPostMedia, manifestToken, updatePostCombo, updatePostComboRender } from "./manifest.mjs"; +import { attachPostMedia, manifestToken, updatePostCombo, updatePostComboRender, updatePostSceneRender } from "./manifest.mjs"; +import { mediaScenes, sceneKnobs, sceneLines } from "umtool-report-to-video/post-media-scene"; import { mediaKindOf, probeMediaFile } from "./postReel.mjs"; export class ComboError extends Error {} @@ -35,6 +37,11 @@ export const REPEATS_USAGE = [ " the cut's badge (render.posts.combo; k= back to the default); no knobs prints them.", " umtool posts combo <project> <item> off|on|auto [label=…] [position=…] [color=…] [scale=…] [sfx=…] [--json]", " one post item's: off draws no badge on it (it still counts), on/auto the cut's again; its own label, …", + " umtool posts scenes <project> [on|off] [--json]", + " the MEDIA SCENES: neighbouring post items that carry the same attachment (matched as above), each scene's", + " items in order and its anchor (the first to carry it: its crop and censor are the scene's). The attachment", + " stays put through a scene; each message stacks in beside it. on|off: the cut's (render.posts.scene.on,", + " default on). One item: umtool posts set-item <project> <item> scene=off|join|auto.", " umtool posts attach <project> [<item> … | --all] [--dry-run] [--json]", " a post item with no attachment whose capture holds one (captured after it went in): its media copied in and", " set, as posts reel would have made it -- nothing else of the entry changes. One write (one undo point).", @@ -118,6 +125,26 @@ export async function repeatsView(project, { match = null, cacheDir = undefined, return { project: project.id, match: cut.match, knobs: comboKnobs(manifest.render), groups, combos: cut.combos }; } +/** + * THE MEDIA SCENES VIEW (post-media-scene.mjs): the cut's scenes over the + * combo counter's groups -- `{ project, on, scenes: [{ key, ids, anchor, + * members }], lines }`. Off for the cut: none, `on` false. + * + * @param {{ id: string, dir: string }} project + */ +export async function scenesView(project, { channelsDir = null } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new ComboError(`${project.id} has no manifest`); + const cut = await projectCombos(project.dir, manifest, { channelsDir: channelsDir ?? channelsDirFor(project.dir, manifest) }); + const { scenes } = mediaScenes(manifest.timeline, cut.groups, manifest.render); + return { + project: project.id, + on: sceneKnobs(manifest.render).on, + scenes: scenes.map((s) => ({ key: s.key, ids: s.ids, anchor: s.anchor.id, group: s.group, members: s.members.map((m) => ({ id: m.id, media: m.media, joins: m.media === null })) })), + lines: sceneLines(scenes, manifest.timeline), + }; +} + const TIER_WORDS = { "media-id": "X media id", sha256: "same file", audio: "same sound" }; const MATCH_WORDS = { id: "the X media id", file: "the X media id, then the file's bytes", audio: "the X media id, the bytes, then the sound" }; @@ -241,6 +268,23 @@ async function comboRun(verb, words, flags, { root, json, out, err }) { } return 0; } + if (verb === "scenes") { + const word = rest.find((w) => !w.startsWith("--")); + if (word !== undefined) { + const w = word.toLowerCase(); + if (!ON.has(w) && !OFF.has(w) && w !== "auto") throw new ComboError(`posts scenes takes on, off or auto (the default), not ${word}`); + const { result, editNotes } = await withEditNotes(project, async () => updatePostSceneRender(project.dir, { on: w === "auto" ? null : ON.has(w) }, { token: await manifestToken(project.dir) })); + out(json ? JSON.stringify({ ok: true, scene: result.scene, token: result.token, editNotes }, null, 2) : `the cut's media scenes: ${result.scene?.on === false ? "off" : "on"}`); + return 0; + } + const v = await scenesView(project); + if (json) out(JSON.stringify({ ok: true, ...v }, null, 2)); + else { + out(`${v.scenes.length} media scene(s) in ${project.id}${v.on ? "" : " (OFF for the cut: render.posts.scene.on false)"}`); + for (const l of v.lines) out(` ${l}`); + } + return 0; + } if (verb === "repeats") { const m = flags.get("--match"); if (m !== undefined && !["id", "file", "audio"].includes(String(m))) throw new ComboError("--match takes id, file or audio"); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -73,7 +73,7 @@ export const POSTS_USAGE = [ " POST ITEMS: each archived post as an entry of the cut, its card and its attachments (report-video.md, \"Post items\"):", " the channels merged in time order, de-duplicated by post id; a post already in the cut is skipped, so a re-run", " adds only what is new -- in ONE write (one undo point), at the end unless --after.", - " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [follow=on|off|auto] [follow.dim=<0.2-1>] [follow.ease=<s>]", + " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [scene=off|join|auto] [follow=on|off|auto] [follow.dim=<0.2-1>] [follow.ease=<s>]", " [thread.parent[.<i>]=auto|full|excerpt|context|carry|hidden] [thread.quoted=auto|full|excerpt|context|hidden]", " [thread.carry=auto|on|off] [thread.reveal=on|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>]", " [thread.seconds=<0-3>] [thread.pan=<0.1-3>] [thread=auto]", @@ -91,6 +91,8 @@ export const POSTS_USAGE = [ " media.<i>.blur=on: the attachment CENSORED in the render -- a real blur (strength 1-10, default 7) of the whole", " frame, or of its boxes (fractions of the picture as shown: x,y,w,h;…), labelled \"Censored\" (label=… or off);", " its file is never touched. Play and the bench preview it; the bench draws boxes on a paused frame.", + " scene=off: never in a MEDIA SCENE (neighbours with the same attachment: it stays put, the messages stack beside it;", + " umtool posts scenes); join: an item with no attachment of its own joins the scene beside it; auto: by its attachment.", " media.<i>.censor=below:0.38[:blur|black|pixelate][:<strength>]: a BAND -- everything below a line across the picture", " (above:<f>, between:<a>,<b>; :left:<f> / :right:<f> narrows it to one side of an upright line) censored in a style;", " the blur on, the rest of its settings kept; off turns it off. Stays on in an uncensored cut (a presentation choice).", @@ -124,6 +126,7 @@ export const POSTS_USAGE = [ " umtool posts repeats <project> [--match id|file|audio] [--json] the attachments played more than once (the combo counter)", " umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (umtool posts repeats --help)", " umtool posts attach <project> [<item> … | --all] [--dry-run] a capture's media onto items that carry none", + " umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment", ].join("\n"); const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker"]); @@ -453,7 +456,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con if (verb === "avatars" && projectArg && !flags.has("--help")) return await avatarsCommand(projectArg, { root, json, dryRun, out }); if (verb === "context" && projectArg && !flags.has("--help")) return await contextCommand(projectArg, { root, json, dryRun, out }); // The combo counter (postComboCli.mjs): the attachments played more than once, the badge's knobs. - if (verb === "repeats" || verb === "combo" || verb === "attach") return await (await import("./postComboCli.mjs")).comboCommand(verb, words.slice(1), flags, { root, json, out, err }); + if (verb === "repeats" || verb === "combo" || verb === "attach" || verb === "scenes") return await (await import("./postComboCli.mjs")).comboCommand(verb, words.slice(1), flags, { root, json, out, err }); if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) { err(POSTS_USAGE); return 2; @@ -633,6 +636,11 @@ export function postItemPatchOf(pairs) { if (k === "hold") out.hold = OFF.has(v) || v === "" ? null : Number(raw); else if (k === "layout") out.mediaLayout = v === "sequence" ? null : v; else if (k === "redact") out.redact = v === "auto" || v === "" ? null : onOff(v, k); + // Its media scene (post-media-scene.mjs): off (never in one), join (joins the scene beside it), auto (by its attachment). + else if (k === "scene") { + if (!["off", "join", "auto", "on", ""].includes(v) && !OFF.has(v)) throw new CliError("scene= takes off, join or auto"); + out.scene = OFF.has(v) ? false : v === "join" ? "join" : null; + } // Its read-follow (read-follow.mjs): follow=on|off|auto, follow.dim=<0.2-1>, follow.ease=<s> (auto/default: the cut's). else if (k === "follow") out.follow = v === "auto" || v === "default" || v === "" ? null : onOff(v, k) ? { on: true } : false; else if (k === "follow.dim" || k === "follow.ease") { @@ -693,7 +701,7 @@ export function postItemPatchOf(pairs) { } } else { const m = /^media\.(\d+)\.(start|end|mute|crop|push|trim)$/.exec(k); - if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, follow=, follow.dim|ease=, thread=, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan=, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes|.band|.style]=, media.<i>.censor=, quoted.paraphrase=, parent.<i>.paraphrase=)`); + if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, scene=, follow=, follow.dim|ease=, thread=, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan=, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes|.band|.style]=, media.<i>.censor=, quoted.paraphrase=, parent.<i>.paraphrase=)`); const media = (out.media ??= {}); const one = (media[m[1]] ??= {}); if (m[2] === "start" || m[2] === "end") one[m[2]] = OFF.has(v) || v === "" ? null : Number(raw); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -221,6 +221,7 @@ import { dropMarks, redactEntry } from "./post-redact.mjs"; import { avatarUrls } from "./post-avatars.mjs"; import { applyPostCombo } from "./post-combo-render.mjs"; import { projectCombos } from "./post-combo-prints.mjs"; +import { mediaSceneById, sceneEntry } from "./post-media-scene.mjs"; export { snap }; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; @@ -6313,9 +6314,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly if (only && !entries.length) throw new Error(`no timeline entry with id ${only}`); // The combo counter (post-combo.mjs): each post item's repeat of an earlier one's attachment, counted // over the WHOLE cut, so an `--only` rebuild draws the count the full build would. - const postCombos = manifest.timeline.some((e) => e?.type === "post" && e.media?.length) - ? (await projectCombos(manifestDir, manifest, { channelsDir })).combos - : {}; + const { combos: postCombos, groups: postGroups } = manifest.timeline.some((e) => e?.type === "post" && e.media?.length) + ? await projectCombos(manifestDir, manifest, { channelsDir }) + : { combos: {}, groups: [] }; // Under the deck, the box every footage segment is framed into: the posts // feed's when this cut is a feed -- decided on the cut's WHOLE timeline, so // an `--only` rebuild frames a clip as the full build would. @@ -6434,11 +6435,13 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly redaction: POST_REDACTION, // The item before it in the cut (post-thread.mjs: a parent that is that item is carried in, not cut to). prev: manifest.timeline[manifest.timeline.findIndex((x) => x?.id === entry.id) - 1] ?? null, + // Its media scene (post-media-scene.mjs): neighbours with the same attachment, over the WHOLE cut's groups. + mediaScene: mediaSceneById(manifest.timeline, entry.id, postGroups, render), }); if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr }); // Its combo badge (post-combo-render.mjs): a pass over the segment when its attachment repeats an earlier one's. if (postCombos[entry.id]) { - await applyPostCombo(seg, entry, { + await applyPostCombo(seg, sceneEntry(entry, mediaSceneById(manifest.timeline, entry.id, postGroups, render)), { combo: postCombos[entry.id], render, outDir, box: df ? df.box : { x: 0, y: 0, width: render.width, height: render.height }, encode: encodeArgs(render), exec: execFileP, ffmpeg: FFMPEG, emit: (ev, f) => EMIT(ev, f), }); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -67,6 +67,7 @@ "./post-item": "./post-item.mjs", "./post-narration": "./post-narration.mjs", "./post-censor": "./post-censor.mjs", + "./post-media-scene": "./post-media-scene.mjs", "./post-redact": "./post-redact.mjs", "./post-redact-files": "./post-redact-files.mjs", "./post-slurs": "./post-slurs.mjs", diff --git a/umtool/report-to-video/post-combo.mjs b/umtool/report-to-video/post-combo.mjs @@ -418,8 +418,9 @@ export function validatePostComboRender(render) { const p = render?.posts; if (p === undefined || p === null) return []; if (!isObj(p)) return ["render.posts must be an object (its `combo` knobs)"]; - // render.posts is shared: `redact` and `slurs` are post-redact.mjs's (validatePostsRender checks them). - const errors = Object.keys(p).filter((k) => !["combo", "redact", "slurs"].includes(k)).map((k) => `render.posts.${k} is not a knob (combo, redact, slurs)`); + // render.posts is shared: `redact` and `slurs` are post-redact.mjs's (validatePostsRender checks them), `scene` + // post-media-scene.mjs's (validatePostSceneRender). + const errors = Object.keys(p).filter((k) => !["combo", "redact", "slurs", "scene"].includes(k)).map((k) => `render.posts.${k} is not a knob (combo, redact, slurs, scene)`); if (p.combo === undefined) return errors; if (!isObj(p.combo)) return [...errors, "render.posts.combo must be an object of knobs"]; return [...errors, ...knobErrors(p.combo, "render.posts.combo", Object.keys(COMBO_DEFAULTS))]; diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -11,7 +11,7 @@ // media?: [{ src, kind: "image"|"video"|"gif", seconds?, width?, height?, audio?, // start?, end?, mute?, crop?: [x, y, w, h], push?, words?, // blur?: { on, strength?, boxes?, label? } }], (post-censor.mjs) -// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen?, +// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen?, scene?: false|"join", (post-media-scene.mjs) // fx?: [{ kind: "word-zoom", match, target?, occurrence?, at?, lead?, hold?, scale?, ease?, highlight? }] } // // (`fx`: the card pushed in on a word as it is read -- word-zoom.mjs.) @@ -37,6 +37,7 @@ import { blurErrors } from "./post-censor.mjs"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, cardWordsOf, findMatch, targetTextOf, validatePostFx } from "./word-zoom.mjs"; import { FOLLOW_MIN_SIZE, followBlocks, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs"; import { validatePostThread } from "./post-thread.mjs"; +import { validatePostScene, validatePostSceneRender } from "./post-media-scene.mjs"; /** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */ export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]); @@ -224,12 +225,19 @@ export function postItemSeconds(entry, render = undefined) { * * @param {Record<string, any>} entry * @param {Record<string, any>} [render] - * @param {{ prev?: Record<string, any> | null }} [o] the item before it in the cut (post-thread.mjs carries a parent that is it) + * `mediaScene` (post-media-scene.mjs mediaSceneOf): its media scene -- the + * scene's earlier messages in its card's column (`follow.thread`). The entry + * is the one the scene plays (sceneEntry: the shared attachment the + * anchor's): the caller makes it, so a channel's markup is laid on first. + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {{ prev?: Record<string, any> | null, mediaScene?: Record<string, any> | null }} [o] the item before it in the cut (post-thread.mjs carries a parent that is it) * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number, narration?: Record<string, any>, follow?: Record<string, any> }} */ -export function postItemPlan(entry, render = undefined, { prev = null } = {}) { +export function postItemPlan(entry, render = undefined, { prev = null, mediaScene = null } = {}) { const hold = fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : null; - return planOf(entry, render, hold, prev); + return planOf(entry, render, hold, prev, mediaScene); } /** @@ -237,14 +245,15 @@ export function postItemPlan(entry, render = undefined, { prev = null } = {}) { * @param {Record<string, any> | undefined} render * @param {number | null} hold * @param {Record<string, any> | null} [prev] + * @param {Record<string, any> | null} [mediaScene] */ -function planOf(entry, render, hold, prev = null) { +function planOf(entry, render, hold, prev = null, mediaScene = null) { const narrated = isNarrated(entry); const k = postNarrationKnobs(entry, render); const sch = narrated ? narrationSchedule(entry, render) : null; // Its read-follow (read-follow.mjs): each block's start on the item's clock -- null when it is off. `prev`: the // item before it in the cut (post-thread.mjs: a parent that is that item is carried in, not cut to). - const follow = followSchedule(entry, render, { hold, narration: sch, prev }); + const follow = followSchedule(entry, render, { hold, narration: sch, prev, mediaScene }); const extra = { ...(sch ? { narration: sch } : {}), ...(follow ? { follow } : {}) }; if (sch && k.attach === "after") { const voiceOnly = round3(sch.at + sch.seconds + k.tail); @@ -483,6 +492,8 @@ export function validatePostItem(e) { errors.push(...validatePostFollow(e)); // Its thread read's knobs (post-thread.mjs): what each context post is on screen, the shrink and dim. errors.push(...validatePostThread(e)); + // Its media scene (post-media-scene.mjs): false (never in one) or "join". + errors.push(...validatePostScene(e)); return errors; } @@ -521,7 +532,7 @@ export function validatePostItems(manifest) { const errors = []; const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; for (const e of tl) if (e?.type === "post") errors.push(...validatePostItem(e)); - errors.push(...validatePostsRender(manifest?.render)); + errors.push(...validatePostsRender(manifest?.render), ...validatePostSceneRender(manifest?.render)); // A word zoom on a word the project's list blanks (the corpus's and a post's markup are checked by the build). const own = { terms: projectRedactOf(manifest?.render) }; for (const e of tl) if (e?.type === "post") errors.push(...fxRedactionErrors(e, own)); @@ -904,6 +915,10 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p const cut = (scope) => (tmode(scope) === "excerpt" && fmap ? new Set(fmap.blocks.filter((b) => b.scope === scope && b.part === null).map((b) => b.k)) : null); const cutCss = []; const tileHtml = []; + // A MEDIA SCENE (post-media-scene.mjs): the scene's earlier messages, oldest first, each drawn as its own post tile was. + for (const t of tiles) { + if (t.scope.startsWith("scene:") && isObj(t.entry)) tileHtml.push(sceneTileHtml(t, { k, pal, size: (text) => sizeFor(text, innerW, innerH - 170 * k), redaction, avatars })); + } for (let i = parents.length - 1; i >= 0; i -= 1) { const scope = `parent:${i}`; const mode = tmode(scope); @@ -1023,3 +1038,34 @@ ${BAR_CSS(pal.fg)} })(); </script></body></html>`; } + +/** + * A MEDIA SCENE's earlier message as a tile of a later item's column + * (post-media-scene.mjs; postCardHtml's threaded card): drawn as its own post + * tile was while it was read -- the repost line, its author (under its own + * privacy rule), its words at the size that fits it alone, its counts -- + * with its own redaction laid on. `t`: the tile (`scope`, `mode`, `entry`: + * its card). + * + * @param {{ scope: string, mode: string, entry: Record<string, any> }} t + * @param {{ k: number, pal: Record<string, string>, size: (text: string) => number, redaction?: any, avatars?: Record<string, string> }} o + */ +export function sceneTileHtml(t, { k, pal, size, redaction = null, avatars = {} }) { + const e = redactEntry(t.entry, redaction); + const authors = cardAuthors(e); + const blurred = authors.filter((a) => a.redact && a.handle).map((a) => a.handle); + const red = (where) => authors.find((a) => a.where === where)?.redact ?? false; + const ownRed = red("author"); + const own = { author: e.author, handle: e.handle }; + const words = cardText(e); + const n = e.engagement ?? {}; + const counts = [["replies", n.replies], ["reposts", n.reposts], ["likes", n.likes], ["quotes", n.quotes]] + .filter(([, v]) => fin(v) && v > 0) + .map(([k2, v]) => `<span class="count"><b>${countText(v)}</b> ${v === 1 ? String(k2).replace(/ies$/, "y").replace(/s$/, "") : k2}</span>`) + .join(""); + const repost = e.repostedBy ? `<div class="repost" data-post-repost="">↻ ${esc(str(e.repostedBy.author) || `@${e.repostedBy.handle}`)} reposted</div>` : ""; + const to = parentsOf(e)[0]?.handle ?? e.replyingTo; + const replying = to ? `<div class="replying">Replying to ${red("parents[0]") || red("replyingTo") ? '<span class="redact">@xxxxxxxx</span>' : `<span class="mention">@${esc(String(to).replace(/^@/, ""))}</span>`}</div>` : ""; + const head = `<div class="head"${ownRed ? ' data-redacted=""' : ""}>${avatarHtml(own, { redact: ownRed, size: Math.round(64 * k), accent: ownRed ? undefined : pal.accent, img: avatarUrlOf(avatars, own.handle) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(e.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[e.platform] ?? "")}</div></div>`; + return `<div class="tslot" data-thread-slot="${esc(t.scope)}"><div class="tile tpost" data-thread-tile="${esc(t.scope)}" data-thread-mode="${esc(t.mode)}" data-scene-post="${esc(e.id ?? "")}">${repost}${replying}${head}<div class="twords" style="font-size:${size(words)}px">${wordsHtml(words, blurred)}</div>${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div></div>`; +} diff --git a/umtool/report-to-video/post-media-scene.mjs b/umtool/report-to-video/post-media-scene.mjs @@ -0,0 +1,370 @@ +// A MEDIA SCENE (umtool/docs/report-video.md, "Media scenes"; operator, 4 Nov, +// on the Mr. Obvious cut: "show all these 'jiggle' messages in a way that makes +// it obvious he's posted multiple different messages about this same +// picture"): CONSECUTIVE post items of a cut that carry the same attachment +// are one scene. The attachment is shown ONCE and stays put -- the same +// picture in the same box from the scene's first frame to its last, never +// pushed in, never crossfaded in again -- and each message about it stacks +// in beside it: the one being read in full and lit, the ones before it shrunk +// and dimmed above it, the one just read giving way as the next comes in +// (the thread read's parent → reply motion, post-thread.mjs, on its knobs). +// +// WHAT IS "THE SAME ATTACHMENT" is the combo counter's question, answered by +// its matcher (post-combo.mjs repeatGroups: X's media id, then the bytes, +// then -- `match: "audio"` -- the sound): two items are in one scene when they +// are next to each other in the cut and share a repeat group. The planner +// takes those groups; it never matches files itself. +// +// render.posts.scene = { on } the cut's: scenes at all (default on) +// timeline[i].scene = false this item is never in a scene (it breaks one) +// | "join" this item, with no attachment of its own in +// the group, joins the scene beside it (a post +// that talks about the picture without carrying it) +// +// THE ATTACHMENT in the scene is the scene's ANCHOR's -- its first item that +// carries it: its file, its crop, its censor (set them there; a later item's +// own are not drawn while it is in the scene). A video or a GIF keeps each +// item's own in and out point (its read is timed to it); an image is held. +// +// THE CARD: an item after the first is drawn as a column of tiles (the thread +// read's: read-follow.mjs pans it, post-item.mjs draws it) -- the scene's +// earlier messages oldest first, then its own (and, narrated, the posts it +// answers and quotes, as its thread read draws them). The column rides on +// read-follow (on by default): with it off, each card is drawn alone and only +// the attachment carries the scene. A thread read's own tile for a post that +// is also an earlier message of the scene (the post it answers, just before +// it) is drawn once, as the thread's. +// +// PURE and dependency-free: the build, Play, the card's route, the bench, the +// lint and `umtool posts scenes` read the same plan from here. + +export const SCENE_DEFAULTS = Object.freeze({ on: true }); +/** A post item's own `scene`: false (never in one) or "join" (joins the scene beside it). */ +export const SCENE_ITEM_VALUES = Object.freeze([false, "join"]); +/** The card fields an earlier message of the scene is drawn from (its tile). */ +const CARD_KEYS = ["id", "post", "platform", "author", "handle", "badge", "date", "text", "url", "repostedBy", "parents", "replyingTo", "subjects", "redact", "engagement"]; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000; + +// --------------------------------------------------------------------------- +// The knobs. +// --------------------------------------------------------------------------- + +/** The cut's scene knobs, the defaults filled in. */ +export function sceneKnobs(render) { + const r = isObj(render?.posts) && isObj(render.posts.scene) ? render.posts.scene : {}; + return { ...SCENE_DEFAULTS, ...(typeof r.on === "boolean" ? { on: r.on } : {}) }; +} + +/** Every reason `render.posts.scene` cannot be built. */ +export function validatePostSceneRender(render) { + const v = render?.posts?.scene; + if (v === undefined) return []; + if (!isObj(v)) return ["render.posts.scene must be { on } (media scenes: consecutive post items with the same attachment)"]; + const errors = Object.keys(v).filter((k) => !(k in SCENE_DEFAULTS)).map((k) => `render.posts.scene.${k} is not a scene knob (${Object.keys(SCENE_DEFAULTS).join(", ")})`); + if (v.on !== undefined && typeof v.on !== "boolean") errors.push("render.posts.scene.on must be true or false"); + return errors; +} + +/** Every reason one post item's `scene` cannot be built. */ +export function validatePostScene(e) { + if (e?.scene === undefined) return []; + return SCENE_ITEM_VALUES.includes(e.scene) ? [] : [`timeline ${e?.id ?? "?"}.scene must be false (never in a media scene) or "join" (joins the scene beside it); absent: in one when it shares the attachment`]; +} + +// --------------------------------------------------------------------------- +// THE SCENES of a cut. +// --------------------------------------------------------------------------- + +/** One item's groups: `Map<groupKey, mediaIndex>` (the repeat groups it is a member of). */ +function groupsById(groups) { + const out = new Map(); + for (const g of Array.isArray(groups) ? groups : []) { + for (const m of Array.isArray(g?.members) ? g.members : []) { + if (!out.has(m.id)) out.set(m.id, new Map()); + if (!out.get(m.id).has(g.key)) out.get(m.id).set(g.key, m.i); + } + } + return out; +} + +const MEMO = new WeakMap(); + +/** + * THE SCENES, pure and memoised (per timeline, groups and the cut's `on`): + * `{ scenes: [{ key, group, at: [timeline indices], ids, anchor: { id, at, + * media }, members: [{ id, at, media }] }], byAt: Map<index, scene> }` -- each + * a run of at least two neighbouring post items sharing a repeat group (and + * the `join` items beside it), with at least one that carries the attachment. + * `groups`: post-combo.mjs repeatGroups' (its members' `id` and `i`). + * + * A run is broken by anything that is not a post item of the group: a clip, a + * post with another attachment, `scene: false`. A `join` item after a scene + * joins it; one before the first scene of a run joins the scene that follows. + * + * @param {Array<Record<string, any>>} timeline + * @param {Array<{ key: string, members: Array<{ id: string, i: number }> }>} groups + * @param {Record<string, any>} [render] + */ +export function mediaScenes(timeline, groups, render = undefined) { + const tl = Array.isArray(timeline) ? timeline : []; + const on = sceneKnobs(render).on; + const memo = MEMO.get(tl); + if (memo && memo.groups === groups && memo.on === on) return memo.value; + const value = planScenes(tl, groups, on); + MEMO.set(tl, { groups, on, value }); + return value; +} + +function planScenes(tl, groups, on) { + const byAt = new Map(); + const scenes = []; + if (!on) return { scenes, byAt }; + const gOf = groupsById(groups); + const order = (Array.isArray(groups) ? groups : []).map((g) => g.key); + /** null: breaks a run; "J": joins; else its groups. */ + const label = (e) => { + if (!isObj(e) || e.type !== "post" || typeof e.id !== "string" || e.scene === false) return null; + const own = gOf.get(e.id); + if (own?.size) return own; + return e.scene === "join" ? "J" : null; + }; + const labels = tl.map(label); + let run = null; + let pending = []; + const close = () => { + if (run && run.at.length >= 2 && run.at.some((k) => labels[k] !== "J")) { + const members = run.at.map((k) => ({ id: tl[k].id, at: k, media: labels[k] === "J" ? null : labels[k].get(run.group) })); + const a = members.find((m) => m.media !== null); + const scene = { key: `s${scenes.length + 1}`, group: run.group, at: [...run.at], ids: members.map((m) => m.id), anchor: { id: a.id, at: a.at, media: a.media }, members }; + scenes.push(scene); + for (const k of run.at) byAt.set(k, scene); + } + run = null; + }; + /** The group a run starting at `k` takes: the one it shares with the next item that carries one, else its first. */ + const groupFrom = (k) => { + const mine = labels[k]; + let j = k + 1; + while (j < labels.length && labels[j] === "J") j += 1; + const next = labels[j]; + const shared = next instanceof Map ? order.filter((g) => mine.has(g) && next.has(g)) : []; + return shared[0] ?? order.find((g) => mine.has(g)); + }; + labels.forEach((lab, k) => { + if (lab === null) { + close(); + pending = []; + return; + } + if (lab === "J") { + if (run) run.at.push(k); + else pending.push(k); + return; + } + if (run && lab.has(run.group)) { + run.at.push(k); + return; + } + close(); + run = { group: groupFrom(k), at: [...pending, k] }; + pending = []; + }); + close(); + return { scenes, byAt }; +} + +/** The card fields of an item (its tile in a later item's column). */ +export const sceneCardOf = (e) => Object.fromEntries(CARD_KEYS.filter((k) => e?.[k] !== undefined).map((k) => [k, e[k]])); + +/** + * ITEM `i`'s SCENE, pure (memoised through mediaScenes): `{ key, n, of, ids, + * media, anchor: { id, media, entry: { id, post, media } }, before: [cards] }` + * -- `n` its place (0: the first), `media` the index of the shared attachment + * in its own media (null: a join item), `before` the earlier messages' cards, + * oldest first. Null when the item is in no scene. + * + * @param {Array<Record<string, any>>} timeline + * @param {number} i + * @param {Array<Record<string, any>>} groups + * @param {Record<string, any>} [render] + */ +export function mediaSceneOf(timeline, i, groups, render = undefined) { + const tl = Array.isArray(timeline) ? timeline : []; + const s = mediaScenes(tl, groups, render).byAt.get(i); + if (!s) return null; + const n = s.at.indexOf(i); + const a = tl[s.anchor.at]; + return { + key: s.key, + n, + of: s.at.length, + ids: s.ids, + media: s.members[n].media, + anchor: { id: a.id, media: s.anchor.media, entry: { id: a.id, post: a.post, media: a.media } }, + before: s.at.slice(0, n).map((k) => sceneCardOf(tl[k])), + }; +} + +/** + * The scene of the item with id `id` in a timeline (mediaSceneOf by id). + * + * @param {Array<Record<string, any>>} timeline + * @param {string} id + * @param {Array<Record<string, any>>} groups + * @param {Record<string, any>} [render] + */ +export function mediaSceneById(timeline, id, groups, render = undefined) { + const tl = Array.isArray(timeline) ? timeline : []; + const at = tl.findIndex((e) => e?.id === id); + return at < 0 ? null : mediaSceneOf(tl, at, groups, render); +} + +// --------------------------------------------------------------------------- +// THE ITEM AS THE SCENE PLAYS IT. +// --------------------------------------------------------------------------- + +/** An attachment's timing (its own in a scene: its read is timed to it). */ +const TIMING = ["start", "end", "mute", "words", "seconds", "audio"]; + +/** + * ITEM `entry` AS ITS SCENE PLAYS IT, pure: the shared attachment drawn as + * the anchor's (its file, size, crop and censor), with the item's own timing + * (in and out, sound, words) and never pushed in; a join item gains it as its + * first attachment (the anchor's timing). `censor(entry)` lays a channel's + * markup on the anchor first (post-censor.mjs censorEntry). The entry itself + * when it is in no scene. + * + * @param {Record<string, any>} entry + * @param {ReturnType<typeof mediaSceneOf>} scene + * @param {{ censor?: (e: Record<string, any>) => Record<string, any> }} [o] + */ +export function sceneEntry(entry, scene, { censor = null } = {}) { + if (!scene || !isObj(entry)) return entry; + const anchor = censor ? censor(scene.anchor.entry) : scene.anchor.entry; + const am = Array.isArray(anchor?.media) ? anchor.media[scene.anchor.media] : null; + if (!isObj(am)) return entry; + const look = Object.fromEntries(Object.entries(am).filter(([k]) => !TIMING.includes(k) && k !== "push")); + const own = Array.isArray(entry.media) ? entry.media : []; + if (scene.media === null) { + const { push, ...m } = am; + void push; + return { ...entry, media: [m, ...own].slice(0, 4) }; + } + if (!isObj(own[scene.media])) return entry; + const media = own.map((m, k) => { + if (k !== scene.media) return m; + const time = Object.fromEntries(Object.entries(m).filter(([kk]) => TIMING.includes(kk))); + return { ...look, ...time }; + }); + return { ...entry, media }; +} + +// --------------------------------------------------------------------------- +// THE COLUMN: the scene's earlier messages as tiles over the card's own. +// --------------------------------------------------------------------------- + +/** The archive id of an item's post (`<channel>/<postId>` → `<postId>`). */ +const postIdOf = (e) => String(e?.post ?? "").split("/")[1] ?? ""; + +/** + * THE SCENE's TILES over item `entry`'s card, pure: `{ on, scene, tiles, + * roles }` -- the scene's earlier messages (`scene:<j>`, oldest first; the + * one just before it `carry`, in full as that item ended, the rest + * `context`), then the card's own tiles: `base` (post-thread.mjs threadLayout, + * a narrated item's: the posts it answers and quotes as its read draws them) + * or, without one, the posts it answers as `context`, its post in full, the + * post it quotes. Each scene tile carries its message's card (`entry`). A post + * the thread draws (the post it answers, carried) is not drawn twice. `base` + * itself when the item is the scene's first (nothing above it), or in none. + * + * @param {Record<string, any> | null} base + * @param {Record<string, any>} entry + * @param {ReturnType<typeof mediaSceneOf>} scene + */ +export function sceneLayout(base, entry, scene) { + if (!scene || scene.n === 0 || !scene.before.length) return base; + const parents = (Array.isArray(entry?.parents) ? entry.parents : []).filter(isObj).slice(0, 2); + const drawn = new Set(); + if (base?.tiles) { + for (const t of base.tiles) { + const m = /^parent:(\d)$/.exec(t.scope); + if (m && t.mode !== "hidden" && parents[Number(m[1])]?.id) drawn.add(String(parents[Number(m[1])].id)); + } + } + const baseCarries = !!base?.tiles?.some((t) => t.mode === "carry"); + const scenes = []; + scene.before.forEach((card, j) => { + if (drawn.has(postIdOf(card))) return; + scenes.push({ scope: `scene:${j}`, mode: "context", read: false, entry: card }); + }); + if (!baseCarries && scenes.length && scene.before.length - 1 === Number(scenes[scenes.length - 1].scope.slice(6))) scenes[scenes.length - 1].mode = "carry"; + let own; + if (base?.tiles) own = base.tiles; + else { + // Un-narrated: the posts it answers small and dim above its words (an earlier message carried is drawn once). + const carried = new Set(scene.before.map(postIdOf)); + own = []; + for (let i = parents.length - 1; i >= 0; i -= 1) { + const p = parents[i]; + const words = typeof p.paraphrase === "string" && p.paraphrase.trim() ? p.paraphrase : typeof p.text === "string" ? p.text : ""; + if (!words.trim() || carried.has(String(p.id ?? ""))) continue; + own.push({ scope: `parent:${i}`, mode: "context", read: false }); + } + own.push({ scope: "post", mode: "full", read: true }); + if (isObj(entry?.quoted) && String(entry.quoted.paraphrase ?? entry.quoted.text ?? "").trim()) own.push({ scope: "quoted", mode: "full", read: false }); + } + if (!scenes.length) return base; + return { on: true, scene: scene.key, tiles: [...scenes, ...own], roles: base?.roles ?? [] }; +} + +/** + * THE SCHEDULE of an UN-NARRATED item's column (a narrated one's is the thread + * read's, threadSchedule, over sceneLayout's tiles), pure, in the thread's + * shape (read-follow.mjs pans it, Play and the build draw it): the message + * before it in full as that item ended, shrinking and dimming (`knobs`: the + * thread read's shrink, dim, seconds) as its words come in under it -- from + * its first block's start, less `lead` -- the older ones small and dim. + * + * @param {{ shrink: number, dim: number, seconds: number, pan: number, reveal?: boolean }} knobs + * @param {{ layout: Record<string, any>, blocks: Array<{ start: number | null }>, lead?: number }} o + */ +export function sceneSchedule(knobs, { layout, blocks, lead = 0.4 }) { + if (!layout?.on) return null; + const starts = (blocks ?? []).map((b) => b.start).filter(fin); + const T = starts.length ? Math.min(...starts) : 0; + const t0 = r3(Math.max(0, T - lead)); + const win = { t0, t1: r3(t0 + knobs.seconds) }; + const small = [knobs.shrink, knobs.dim]; + const tiles = []; + for (const t of layout.tiles) { + if (t.mode === "hidden") continue; + const row = { scope: t.scope, mode: t.mode, read: !!t.read, from: [1, 1], to: [1, 1], t0: 0, t1: 0 }; + if (t.mode === "context") { + row.from = t.scope === "quoted" ? [1, knobs.dim] : small; + row.to = row.from; + } else if (t.mode === "carry") Object.assign(row, { to: small, ...win }); + else if (t.scope === "post" && knobs.reveal !== false) Object.assign(row, { from: [1, 0], to: [1, 1], ...win }); + tiles.push(row); + } + return { shrink: knobs.shrink, dim: knobs.dim, seconds: knobs.seconds, pan: knobs.pan, contextRoom: 0.3, tiles }; +} + +/** A schedule's rows with the scene's messages on them (`entry`: what a `scene:<j>` tile draws), and the scene's key. */ +export function sceneRows(thread, layout) { + if (!thread || !layout?.scene) return thread; + const cards = new Map(layout.tiles.filter((t) => t.entry).map((t) => [t.scope, t.entry])); + return { ...thread, scene: layout.scene, tiles: thread.tiles.map((r) => (cards.has(r.scope) ? { ...r, entry: cards.get(r.scope) } : r)) }; +} + +/** The scene's lines for a person (`umtool posts scenes`): each scene, its items, the anchor. */ +export function sceneLines(scenes, timeline) { + const tl = Array.isArray(timeline) ? timeline : []; + return scenes.map((s) => { + const items = s.members.map((m) => `${m.id}${m.media === null ? " (joins)" : ""}${m.id === s.anchor.id ? " (anchor)" : ""}`); + const a = tl[s.anchor.at]?.media?.[s.anchor.media]; + return `${s.key}: ${items.join(" → ")}${a?.src ? ` -- ${a.src}` : ""}`; + }); +} diff --git a/umtool/report-to-video/post-media-scene.test.mjs b/umtool/report-to-video/post-media-scene.test.mjs @@ -0,0 +1,160 @@ +// post-media-scene.mjs: consecutive post items with the same attachment are one +// scene -- the planner over the combo counter's groups, the item as the scene +// plays it, the column's tiles and its schedule, the knobs' checks. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { mediaSceneById, mediaSceneOf, mediaScenes, sceneEntry, sceneLayout, sceneRows, sceneSchedule, validatePostScene, validatePostSceneRender } from "./post-media-scene.mjs"; +import { repeatGroups } from "./post-combo.mjs"; +import { postCardHtml, postItemPlan, validatePostItem, validatePostItems } from "./post-item.mjs"; +import { followStateAt, followPath } from "./read-follow.mjs"; +import { threadKnobs } from "./post-thread.mjs"; + +const gif = (id, o = {}) => [{ src: `posts-media/c-x/${id}/${id}_1.mp4`, kind: "gif", seconds: 0.8, width: 500, height: 280, ...o }]; +const post = (id, text, o = {}) => ({ type: "post", id, post: `c-x/${id.replace(/^p-/, "")}`, platform: "x", author: "Mr. Subject", handle: "subject", date: "2026-11-02T22:15:00.000Z", text, ...o }); +const clip = (id) => ({ type: "clip", id, video: "v", start: 0, end: 5 }); + +/** The cut: a clip, the same GIF three times running (one a join with none), another GIF, the first GIF again apart. */ +function cut() { + return [ + clip("c1"), + post("p-1", "Phat ass jiggle", { scene: "join" }), + post("p-2", "It jiggle.", { media: gif("2", { blur: { on: true, strength: 9, band: { below: 0.38 } }, push: true }) }), + post("p-3", "@Movail2 it jiggle", { media: gif("3", { start: 0.1 }), parents: [{ id: "77", handle: "Movail2", text: "Ready for more lessons?" }] }), + post("p-4", "Something else", { media: gif("4") }), + clip("c2"), + post("p-5", "The jiggle, once more", { media: gif("5") }), + ]; +} +/** Prints as post-combo-prints.mjs makes them: 2, 3 and 5 the same bytes; 4 another. */ +const PRINTS = { "p-2:0": { sha256: "aa" }, "p-3:0": { sha256: "aa" }, "p-4:0": { sha256: "bb" }, "p-5:0": { sha256: "aa" } }; +const groupsOf = (tl) => repeatGroups(tl, (id, i) => PRINTS[`${id}:${i}`]); + +test("THE SCENES: neighbours sharing a repeat group (the combo counter's matcher), a join item joined, a clip or another attachment breaks them", () => { + const tl = cut(); + const g = groupsOf(tl); + assert.equal(g.length, 1, "one repeat group: p-2, p-3, p-5"); + const { scenes, byAt } = mediaScenes(tl, g); + assert.equal(scenes.length, 1); + assert.deepEqual(scenes[0].ids, ["p-1", "p-2", "p-3"], "p-5 is the same GIF, but a clip and another GIF stand between"); + assert.deepEqual(scenes[0].anchor, { id: "p-2", at: 2, media: 0 }, "the anchor: its first to carry it"); + assert.deepEqual(scenes[0].members.map((m) => m.media), [null, 0, 0]); + assert.equal(byAt.get(6), undefined); + assert.equal(mediaScenes(tl, g), mediaScenes(tl, g), "memoised: the same plan for the same timeline and groups"); + // Off for the cut: none. + assert.equal(mediaScenes(tl, g, { posts: { scene: { on: false } } }).scenes.length, 0); + // One item out (scene: false) breaks it: p-1 and p-2 alone (a join and one carrier) are still a scene. + const out = cut(); + out[3].scene = false; + assert.deepEqual(mediaScenes(out, groupsOf(out)).scenes.map((s) => s.ids), [["p-1", "p-2"]]); + // A join item with nothing to join is in no scene; one carrier alone is none either. + const lone = [post("p-1", "words", { scene: "join" }), post("p-4", "x", { media: gif("4") })]; + assert.equal(mediaScenes(lone, []).scenes.length, 0); + // A join after a scene joins it. + const after = [post("p-2", "a", { media: gif("2") }), post("p-3", "b", { media: gif("3") }), post("p-9", "c", { scene: "join" })]; + assert.deepEqual(mediaScenes(after, groupsOf(after)).scenes[0].ids, ["p-2", "p-3", "p-9"]); +}); + +test("an item's scene: its place, the earlier messages' cards, the anchor; the item as the scene plays it", () => { + const tl = cut(); + const g = groupsOf(tl); + assert.equal(mediaSceneOf(tl, 0, g), null, "a clip"); + const s1 = mediaSceneOf(tl, 1, g); + assert.deepEqual([s1.n, s1.of, s1.media, s1.anchor.id, s1.before.length], [0, 3, null, "p-2", 0]); + const s3 = mediaSceneById(tl, "p-3", g); + assert.deepEqual([s3.n, s3.of, s3.media, s3.before.map((b) => b.id)], [2, 3, 0, ["p-1", "p-2"]]); + assert.equal(s3.before[1].media, undefined, "a card, not the entry: no media, no narration"); + // p-3 plays the ANCHOR's look (its file, its censor) with its OWN timing; never pushed in. + const e3 = sceneEntry(tl[3], s3); + assert.equal(e3.media[0].src, "posts-media/c-x/2/2_1.mp4"); + assert.deepEqual(e3.media[0].blur, { on: true, strength: 9, band: { below: 0.38 } }); + assert.equal(e3.media[0].start, 0.1, "its own in point"); + assert.equal(e3.media[0].push, undefined); + assert.equal(tl[3].media[0].src, "posts-media/c-x/3/3_1.mp4", "the entry is never rewritten"); + // The anchor itself: not pushed in either (the picture stays put through the scene). + assert.equal(sceneEntry(tl[2], mediaSceneOf(tl, 2, g)).media[0].push, undefined); + // A join item gains the attachment: a slot beside its words, the same picture. + const e1 = sceneEntry(tl[1], s1); + assert.equal(e1.media.length, 1); + assert.equal(e1.media[0].src, "posts-media/c-x/2/2_1.mp4"); + assert.equal(postItemPlan(e1).steps.length, 1); + // A channel's markup on the anchor is laid on first (the build's censorEntry). + const marked = sceneEntry(tl[3], s3, { censor: (e) => ({ ...e, media: e.media.map((m) => ({ ...m, blur: { on: true, style: "black" } })) }) }); + assert.deepEqual(marked.media[0].blur, { on: true, style: "black" }); + assert.equal(sceneEntry(tl[4], null), tl[4]); +}); + +test("THE COLUMN: the earlier messages as tiles over the card -- the one just before carried, older ones context -- its own after", () => { + const tl = cut(); + const g = groupsOf(tl); + const s3 = mediaSceneOf(tl, 3, g); + const L = sceneLayout(null, tl[3], s3); + assert.deepEqual(L.tiles.map((t) => `${t.scope}:${t.mode}`), ["scene:0:context", "scene:1:carry", "parent:0:context", "post:full"]); + assert.equal(L.tiles[1].entry.id, "p-2"); + assert.equal(sceneLayout(null, tl[1], mediaSceneOf(tl, 1, g)), null, "the scene's first: nothing above it"); + // A narrated item's thread layout is the base: its own tiles kept, the scene's above them. + const base = { on: true, roles: [{ role: "parent:0" }], tiles: [{ scope: "parent:0", mode: "full", read: true }, { scope: "post", mode: "full", read: true }] }; + const N = sceneLayout(base, tl[3], s3); + assert.deepEqual(N.tiles.map((t) => `${t.scope}:${t.mode}`), ["scene:0:context", "scene:1:carry", "parent:0:full", "post:full"]); + assert.deepEqual(N.roles, base.roles); + // The post it answers IS an earlier message (carried by the thread read): drawn once, as the thread's. + const reply = cut(); + reply[3].parents = [{ id: "2", handle: "subject", text: "It jiggle." }]; + const carried = { on: true, roles: [], tiles: [{ scope: "parent:0", mode: "carry", read: false }, { scope: "post", mode: "full", read: true }] }; + const C = sceneLayout(carried, reply[3], mediaSceneOf(reply, 3, groupsOf(reply))); + assert.deepEqual(C.tiles.map((t) => `${t.scope}:${t.mode}`), ["scene:0:context", "parent:0:carry", "post:full"]); +}); + +test("THE SCHEDULE (un-narrated): the message before in full, shrinking and dimming as its words come in; the older ones small; the plan carries it", () => { + const tl = cut(); + const g = groupsOf(tl); + const s3 = mediaSceneOf(tl, 3, g); + const e3 = sceneEntry(tl[3], s3); + const k = threadKnobs(e3, undefined); + const L = sceneLayout(null, e3, s3); + const sch = sceneSchedule(k, { layout: L, blocks: [{ start: 1.2 }, { start: 2 }], lead: 0.4 }); + const row = (sc) => sch.tiles.find((t) => t.scope === sc); + assert.deepEqual([row("scene:1").from, row("scene:1").to, row("scene:1").t0, row("scene:1").t1], [[1, 1], [0.62, 0.5], 0.8, 1.5]); + assert.deepEqual([row("scene:0").from, row("scene:0").to], [[0.62, 0.5], [0.62, 0.5]]); + assert.deepEqual([row("post").from, row("post").to], [[1, 0], [1, 1]], "his words revealed under it"); + const rows = sceneRows(sch, L); + assert.equal(rows.tiles.find((t) => t.scope === "scene:0").entry.id, "p-1"); + assert.equal(rows.scene, "s1"); + // The plan: postItemPlan carries the column on its follow (read-follow on by default). + const plan = postItemPlan(e3, undefined, { mediaScene: s3 }); + assert.deepEqual(plan.follow.thread.tiles.map((t) => t.scope), ["scene:0", "scene:1", "parent:0", "post"]); + assert.equal(plan.follow.thread.scene, "s1"); + // Follow off: no column (each card alone), the attachment still the scene's. + assert.equal(postItemPlan({ ...e3, follow: false }, undefined, { mediaScene: s3 }).follow, undefined); + // The state on the clock: at 0 the one before in full and his post hidden; after, small and his post up. + const geo = { H: 900, C: 1400, blocks: {}, tiles: { "scene:0": { top: 0, height: 300 }, "scene:1": { top: 322, height: 300 }, "parent:0": { top: 644, height: 200 }, post: { top: 866, height: 300 } } }; + const path = followPath(plan.follow, geo); + const at0 = followStateAt(plan.follow, path, 0).tiles; + const late = followStateAt(plan.follow, path, 5).tiles; + assert.deepEqual([at0["scene:1"][0], at0.post[1]], [1, 0]); + assert.deepEqual([late["scene:1"][0], late["scene:1"][1], late.post[1]], [0.62, 0.5, 1]); +}); + +test("the card draws the scene's messages as tiles above his own (redacted, their authors under their own rule)", () => { + const tl = cut(); + const g = groupsOf(tl); + const s3 = mediaSceneOf(tl, 3, g); + const e3 = sceneEntry(tl[3], s3); + const plan = postItemPlan(e3, undefined, { mediaScene: s3 }); + const html = postCardHtml(e3, { width: 1440, height: 810, follow: true, thread: plan.follow.thread, redaction: { terms: [{ term: "jiggle" }] } }); + assert.match(html, /data-thread-slot="scene:0"/); + assert.match(html, /data-scene-post="p-2"[^>]*>|data-thread-tile="scene:1"[^>]*data-scene-post="p-2"/); + assert.match(html, /data-post-thread="4"/); + assert.match(html, /Phat ass/, "the earliest message's words drawn"); + assert.doesNotMatch(html, /Phat ass jiggle/, "a redacted word in an earlier message is a bar too"); + assert.ok(html.indexOf('data-thread-slot="scene:1"') < html.indexOf('data-thread-slot="post"'), "oldest first, his own last"); +}); + +test("the knobs' checks: an item's scene false or join; the cut's { on }", () => { + assert.deepEqual(validatePostScene({ id: "p", scene: "join" }), []); + assert.deepEqual(validatePostScene({ id: "p", scene: false }), []); + assert.match(validatePostScene({ id: "p", scene: true })[0], /must be false .* or "join"/); + assert.ok(validatePostItem({ ...post("p-1", "x"), scene: "yes" }).some((e) => e.includes(".scene must be"))); + assert.deepEqual(validatePostSceneRender({ posts: { scene: { on: false } } }), []); + assert.equal(validatePostSceneRender({ posts: { scene: { on: 1, x: 2 } } }).length, 2); + assert.ok(validatePostItems({ timeline: [], render: { posts: { scene: "no" } } }).some((e) => e.includes("render.posts.scene must be"))); +}); diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -24,6 +24,7 @@ import { applyFollowState, followPath, followStateAt, followStateKey, measureFol import { redactEntry, redactionOn, shownLine, termsFor } from "./post-redact.mjs"; import { bleepFilters, slursOn, takeBleeps } from "./post-slurs.mjs"; import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs"; +import { sceneEntry } from "./post-media-scene.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; @@ -440,19 +441,23 @@ export function postZoomPlan(entry, render, total = Infinity) { * build-video's encode args and ffmpeg runner, the authors' pictures * (`{ <handle>: absolute file }`, post-avatars.mjs), the redaction it is * published with (`{ terms, markup }`, post-redact-files.mjs: its matches - * drawn as bars, dropped from its captions), and `prev` the timeline entry - * before it (post-thread.mjs carries a parent that is it). Returns the + * drawn as bars, dropped from its captions), `prev` the timeline entry + * before it (post-thread.mjs carries a parent that is it), and `mediaScene` + * its media scene (post-media-scene.mjs mediaSceneOf: the attachment the + * anchor's, the scene's earlier messages above its card). Returns the * segment's path. */ -export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null, prev = null }) { +export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null, prev = null, mediaScene = null }) { // A channel's markup may censor an attachment for every project (post-censor.mjs); the item's own blur wins. entry = censorEntry(entry, redaction); + // In a media scene (post-media-scene.mjs) the shared attachment is the anchor's -- its markup laid on too. + entry = sceneEntry(entry, mediaScene, { censor: (e) => censorEntry(e, redaction) }); // A word zoom on a redacted word is refused in the build's words (the corpus's terms and the markup included). const fxRed = fxRedactionErrors(entry, redaction); if (fxRed.length) throw new Error(fxRed.join("; ")); const seg = path.join(outDir, "segments", `${entry.id}.mp4`); // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in). - const plan = postItemPlan(entry, render, { prev }); + const plan = postItemPlan(entry, render, { prev, mediaScene }); const layout = postLayout(entry, box); const files = (entry.media ?? []).map((m) => path.resolve(manifestDir, m.src)); for (const [i, f] of files.entries()) { diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs @@ -46,7 +46,8 @@ import { cardText, contextReadSeconds, contextText, parentsOf, readSeconds } from "./post-item.mjs"; import { isNarrated, narrationSchedule, partStartOnItem, pickedTake, scriptParts } from "./post-narration.mjs"; import { cardTokens, easeOf, normWord, scriptWordsOf } from "./word-zoom.mjs"; -import { partRoles, threadGeoAt, threadLayout, threadSchedule, threadStateAt } from "./post-thread.mjs"; +import { partRoles, threadGeoAt, threadKnobs, threadLayout, threadSchedule, threadStateAt } from "./post-thread.mjs"; +import { sceneLayout, sceneRows, sceneSchedule } from "./post-media-scene.mjs"; export const FOLLOW_DEFAULTS = Object.freeze({ on: true, dim: 0.65, ease: 0.25 }); export const FOLLOW_LIMITS = Object.freeze({ dim: [0.2, 1], ease: [0, 2] }); @@ -313,9 +314,12 @@ const wordsIn = (t) => scriptWordsOf(t).length; * * @param {Record<string, any>} entry * @param {Record<string, any>} [render] - * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null }} [o] + * `o.mediaScene` (post-media-scene.mjs mediaSceneOf): the item's media scene -- + * the scene's earlier messages drawn above the card as tiles of the column. + * + * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null, mediaScene?: Record<string, any> | null }} [o] */ -export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null } = {}) { +export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null, mediaScene = null } = {}) { const k = followKnobs(entry, render); if (!k.on) return null; const map = followBlocks(entry); @@ -363,8 +367,12 @@ export function followSchedule(entry, render = undefined, { hold = null, narrati for (const b of blocks) if (b.start === null) b.end = null; // THREADED (post-thread.mjs): a narrated read of the post it answers or quotes -- the card a column of tiles, // each shown in full while it is read, then shrunk and dimmed as the next piece comes in. - const layout = isNarrated(entry) ? threadLayout(entry, render, { prev }) : null; - const thread = layout?.on ? threadSchedule(entry, render, { layout, blocks, lead: FOLLOW_PAN.lead }) : null; + const base = isNarrated(entry) ? threadLayout(entry, render, { prev }) : null; + // A MEDIA SCENE (post-media-scene.mjs): the scene's earlier messages above the card's own tiles -- a narrated + // item's on its thread read's schedule, an un-narrated one's on the scene's. + const layout = mediaScene ? sceneLayout(base, entry, mediaScene) : base; + const own = !layout?.on ? null : base ? threadSchedule(entry, render, { layout, blocks, lead: FOLLOW_PAN.lead }) : sceneSchedule(threadKnobs(entry, render), { layout, blocks, lead: FOLLOW_PAN.lead }); + const thread = mediaScene ? sceneRows(own, layout) : own; return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks, ...(thread ? { thread } : {}) }; }