// A POST ITEM's SEGMENT (post-item.mjs; umtool/docs/report-video.md, "Post // items"): the card drawn by a browser from the archived post -- the deck's // palette and faces, never a screenshot of the platform -- and its // attachments laid into the card's slot by ffmpeg, on the item's plan // (postItemPlan): the words read first, then each attachment in turn, a // video with its sound, a GIF looped, an image held (pushed in on, when it // asks). Framed into the deck's footage box like a clip, so the deck's rail, // section bars and date stamp ride over it as over any segment. // // buildPostSegment(entry, ctx) render the card PNG(s), then one encode // postSegmentArgs(...) that encode's argv, PURE (the tests read it) // // The card is rendered once per change: `.post.json` beside the segment // records the key (the entry, the box, the palette and faces, each // attachment's size and mtime), and a build whose key matches keeps the // segment it has. import { createHash } from "node:crypto"; import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { POST_ENTER_FADE, POST_PICTURE_XFADE, POST_PUSH, cardAuthors, fxRedactionErrors, joinCarryOf, mediaTimeAt, panelEntry, postCardHtml, postItemPlan, postLayout, stepAt, stepBoxes } from "./post-item.mjs"; import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, postNarrationKnobs, rootTakeOf } from "./post-narration.mjs"; import { applyFollowState, followPath, followRuns, followStateAt, isDrawnState, measureFollow, readInViewErrors, shotStateAt } from "./read-follow.mjs"; 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 { LIMITED_RANGE, isFullRange } from "./color-range.mjs"; import { CAPTION_OUT, CAPTION_SLIDE, captionCss, captionInnerHtml, captionPlan, measureCaptionWords, mountCaptions, placeCaption, setCaptionState, slideDir } from "./post-caption.mjs"; import { clockCss, clockFace, clockFrameTimes, clockHtml, clockPlan, clockStateAt, measureClockPlace, mountClock, setClockState } from "./post-clock.mjs"; import { POST_PROGRESS_DRAW_V, measureProgressPlace, mountProgress, progressCss, progressFilters, progressHeight, progressPlan, setProgressState } from "./post-progress.mjs"; import { SLAM_BAR, SLAM_DUST, SLAM_FACE_STACK, SLAM_MOTION, mountSlams, slamBarOf, setSlamState, slamCss, slamCoverErrors, slamHits, slamLayout, slamListAt, slamPlan, slamShakeExpr, slamSize, slamVars } from "./post-slam.mjs"; import { TRAILER_AUDIO, TRAILER_HIT_TIERS, trailerHitsGraph } from "./trailer-hits.mjs"; import { panelReadErrors } from "./post-thread.mjs"; import { POST_SCREEN_DRAW_V, hasScreens, screenDrawErrors } from "./post-screens.mjs"; import { applyJoinState, endMediaOf, joinClockOf } from "./post-join.mjs"; import { applyVisitState } from "./post-link-visit.mjs"; import { applyMapState, mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; import { poolFetch, poolFor, poolPut } from "./render-pool.mjs"; import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; const num = (v) => String(r3(v)); /** The record beside a post item's segment: what it was built from. */ export const postRecordPath = (seg) => seg.replace(/\.mp4$/, ".post.json"); /** * The cues of a video attachment's transcript (`media[i].words`: the editor's * transcribe result, `{cues: [{start, end, text}]}` on the file's clock), or []. */ export async function readMediaCues(file) { try { const doc = JSON.parse(await readFile(file, "utf8")); const cues = Array.isArray(doc?.cues) ? doc.cues : Array.isArray(doc) ? doc : []; return cues .filter((c) => c && Number.isFinite(c.start) && Number.isFinite(c.end) && typeof c.text === "string" && c.text.trim()) .map((c) => ({ start: c.start, end: c.end, text: c.text.replace(/\s+/g, " ").trim() })); } catch { return []; } } /** A step's cues on the ITEM's clock: each cue inside its source span, moved to where it plays. */ export function stepCaptions(step, cues) { if (step?.kind !== "video" || !cues?.length) return []; const end = step.at + step.seconds; return cues .filter((c) => c.end > step.srcFrom && c.start < step.srcTo) .map((c) => ({ from: r3(Math.max(step.at, step.at + c.start - step.srcFrom)), to: r3(Math.min(end, step.at + c.end - step.srcFrom)), text: c.text })) .filter((c) => c.to - c.from > 0.05); } /** A scroll's keyframes (post-thread.mjs panelSchedule) as an ffmpeg expression of t: 0..1, linear between them. */ export function scrollExpr(keys) { if (!Array.isArray(keys) || !keys.length) return "0"; let e = num(keys[keys.length - 1][1]); for (let i = keys.length - 1; i >= 1; i -= 1) { const [t1, f1] = keys[i]; const [t0, f0] = keys[i - 1]; const seg = t1 > t0 ? `${num(f0)}+(${num(f1 - f0)})*(t-${num(t0)})/${num(t1 - t0)}` : num(f1); e = `if(lt(t,${num(t1)}),${seg},${e})`; } return `if(lt(t,${num(keys[0][0])}),${num(keys[0][1])},${e})`; } /** * The encode, pure. `cards`: the read-phase PNG and (a stack layout) the * media-phase one; `files[i]`: attachment i's absolute path; `captions`: * `[{from, to, textfile}]` on the item's clock (drawn over the slot's foot); * `place`: the deck's framing filters after the box (deckFraming's `place`), * none without the deck; `encode`: build-video's encodeArgs. * * @returns {string[]} */ /** * The clock's place over a join, an ffmpeg expression on `t`: `base + d` at the join's start, `base` from its end, * eased between as the card is (post-join.mjs joinEase, in-out cubic). */ export function clockJoinExpr(base, d, seconds) { const p = `min(1,t/${num(seconds)})`; const e = `if(lt(${p},0.5),4*pow(${p},3),1-pow(2-2*${p},3)/2)`; return `${num(base)}+${num(d)}*(1-${e})`; } export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, panelFiles = [], join = null, map = null, captionFx = [], clock = null, slams = [], slamHitList = [], progress = null, pics = [], picSounds = [] }) { const fps = render.fps ?? 30; const T = plan.total; const inputs = []; const parts = []; const add = (args) => { inputs.push(...args); return inputs.filter((a) => a === "-i").length - 1; }; const read = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", cards.read]); parts.push(`[${read}:v]scale=${box.width}:${box.height},setsar=1,fps=${fps}[b0]`); let cur = "b0"; let n = 0; const lay = (label, x, y, a, b) => { const next = `b${++n}`; parts.push(`[${cur}][${label}]overlay=x=${x}:y=${y}:enable='between(t,${num(a)},${num(b)})'[${next}]`); cur = next; }; // READ-FOLLOW (read-follow.mjs): the card's region as the browser drew it frame by frame -- the block being read // lit, the words panned -- one shot per distinct state, held for its frames (a concat list), over the card. if (follow) { const fi = add(["-f", "concat", "-safe", "0", "-i", follow.list]); parts.push(`[${fi}:v]fps=${fps},setsar=1,setpts=PTS-STARTPTS[rf]`); const next = `b${++n}`; parts.push(`[${cur}][rf]overlay=x=${follow.clip.x}:y=${follow.clip.y}:eof_action=repeat[${next}]`); cur = next; } // PICTURE-ONLY posts' GIFs and videos (post-picture.mjs, measurePics): played over their stills in their cards // while the card is still, looped and silent, fading back to the still -- under the zooms, captions and slams. pics.forEach((pc, pi) => { const { m, box: b, t0, t1, file } = pc; if (!file || !(t1 > t0)) return; const label = `pic${pi}`; const raw = blurOn(m) ? `${label}r` : label; const crop = Array.isArray(m.crop) ? `crop=iw*${num(m.crop[2])}:ih*${num(m.crop[3])}:iw*${num(m.crop[0])}:ih*${num(m.crop[1])},` : ""; // A video whose sound plays from its beat's start (`soundAt`): its picture in step with it. const from = (Number.isFinite(m.start) && m.start > 0 ? m.start : 0) + (Number.isFinite(pc.soundAt) && t0 > pc.soundAt ? t0 - pc.soundAt : 0); const len = t1 - t0; const k = add(["-stream_loop", "-1", ...(from > 0 ? ["-ss", num(from)] : []), "-t", num(len + 0.1), "-i", file]); const fadeAt = Math.max(0, len - POST_PIC_FADE); parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},format=rgba${t1 < T - 0.05 ? `,fade=t=out:st=${num(fadeAt)}:d=${num(Math.min(POST_PIC_FADE, len))}:alpha=1` : ""},setpts=PTS-STARTPTS+${num(t0)}/TB[${raw}]`); if (raw !== label) parts.push(...blurFilters(raw, label, m, b)); const next = `b${++n}`; parts.push(`[${cur}][${label}]overlay=x=${b.x}:y=${b.y}:eof_action=pass:enable='between(t,${num(t0)},${num(t1)})'[${next}]`); cur = next; }); if (layout.mode === "stack" && cards.media && plan.steps.length) { const mi = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", cards.media]); parts.push(`[${mi}:v]scale=${box.width}:${box.height},setsar=1,fps=${fps}[mc]`); lay("mc", 0, 0, plan.steps[0].at, T); } // WORD ZOOMS (word-zoom.mjs): the card's region, shot at k× (crisp when pushed in), zoomed toward the word on // the curve -- frame by frame, zoompan on the item's second -- its highlight fading in under the word; laid over // the card's region only while it is up, before the attachments (which it never covers). zooms.forEach((zm, zi) => { const { span, region, target, k } = zm; const D = Math.max(1 / fps, span.t3 - span.t0); const pi = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", zm.plain]); parts.push(`[${pi}:v]scale=${region.width * k}:${region.height * k},setsar=1,format=rgba[wzp${zi}]`); let src = `wzp${zi}`; if (zm.hl) { const hi = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", zm.hl]); parts.push( `[${hi}:v]scale=${region.width * k}:${region.height * k},setsar=1,format=rgba,fade=t=in:st=0:d=${num(Math.max(0.04, span.t1 - span.t0))}:alpha=1,` + `fade=t=out:st=${num(span.t2 - span.t0)}:d=${num(Math.max(0.04, span.t3 - span.t2))}:alpha=1[wzh${zi}]`, `[wzp${zi}][wzh${zi}]overlay=0:0:format=auto[wzc${zi}]`, ); src = `wzc${zi}`; } const ex = zoompanExprs(span, target, k, `(${num(span.t0)}+on/${fps})`); parts.push(`[${src}]zoompan=z='${ex.z}':x='${ex.x}':y='${ex.y}':d=1:s=${region.width}x${region.height}:fps=${fps},setsar=1,setpts=PTS-STARTPTS+${num(span.t0)}/TB[wz${zi}]`); const next = `b${++n}`; parts.push(`[${cur}][wz${zi}]overlay=x=${region.x}:y=${region.y}:eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`); cur = next; }); // CAPTIONS (post-caption.mjs): each chip shot alone on a clear page, laid over the card while it is up -- fading // and sliding in toward its phrase, the underline fading under the words, both tracking the words as the card // pans -- after the zooms (a caption waits for one to be out), before the attachments (it stays on the card). captionFx.forEach((c, ci) => { const { span } = c; const D = Math.max(1 / fps, span.t3 - span.t0); // Static: a pan that moves its phrase ends it first (shootCaptions), so nothing rides over words. const track = (axis) => trackExpr(c.track ?? [], axis); const layer = (shot, label, slide) => { const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", shot.file]); parts.push( `[${k}:v]format=rgba,fade=t=in:st=0:d=${num(Math.max(0.04, span.t1 - span.t0))}:alpha=1,` + `fade=t=out:st=${num(span.t2 - span.t0)}:d=${num(Math.max(0.04, span.t3 - span.t2))}:alpha=1,setpts=PTS-STARTPTS+${num(span.t0)}/TB[${label}]`, ); const left = span.t1 > span.t0 ? `pow(1-clip((t-${num(span.t0)})/${num(span.t1 - span.t0)},0,1),3)` : "0"; const sx = slide && slide.x ? `+${num(slide.x)}*${left}` : ""; const sy = slide && slide.y ? `+${num(slide.y)}*${left}` : ""; const next = `b${++n}`; parts.push(`[${cur}][${label}]overlay=x='${shot.x}${track("dx")}${sx}':y='${shot.y}${track("dy")}${sy}':eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`); cur = next; }; if (c.mark) layer(c.mark, `cpm${ci}`, null); layer(c.chip, `cpc${ci}`, c.slide); }); // THE PROGRESS BAR (post-progress.mjs): its track and its fill shot alone, laid along the card's foot -- the fill // clipped at the read's progress frame by frame (real read seconds: a part read faster moves it faster, never a jump). if (progress) { const ti = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", progress.track]); const fi = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", progress.fill]); const next = `b${++n}`; parts.push(...progressFilters({ ti, fi, inLabel: cur, outLabel: next, x: progress.x, y: progress.y, pp: progress.plan, T }).chains); cur = next; } // THE CLOCK (post-clock.mjs): its frames shot alone -- the run from the item before's time, then held -- laid // over the card's corner from the first frame (a stack card's: until its media phase). if (clock) { const ci = add(["-f", "concat", "-safe", "0", "-i", clock.list]); // THE JOIN (post-join.mjs): it opens where the item before's clock sat and moves with the card (its ease), or, // the item before showing none, comes in over the join. const cj = clock.join && clock.join.seconds > 0 ? clock.join : null; const fadeIn = cj?.fadeIn ? `,fade=t=in:st=0:d=${num(cj.seconds)}:alpha=1` : ""; parts.push(`[${ci}:v]fps=${fps},format=rgba,setsar=1,setpts=PTS-STARTPTS${fadeIn}[clk]`); const pos = (base, d) => (cj?.from && Math.abs(d) >= 0.5 ? `'${clockJoinExpr(base, d, cj.seconds)}'` : String(base)); const next = `b${++n}`; parts.push(`[${cur}][clk]overlay=x=${pos(clock.x, cj?.from?.dx ?? 0)}:y=${pos(clock.y, cj?.from?.dy ?? 0)}:eof_action=repeat${clock.until < T ? `:enable='lt(t,${num(clock.until)})'` : ""}[${next}]`); cur = next; } const audio = []; const picture = (st) => !!st && (st.kind === "image" || st.kind === "grid" || st.kind === "gif"); plan.steps.forEach((step, si) => { const last = si === plan.steps.length - 1; // Pictures cycle like a video: the next one crossfades in over this one, which stays up under it. const xfIn = si > 0 && picture(step) && picture(plan.steps[si - 1]) ? POST_PICTURE_XFADE : 0; const xfOut = !last && picture(step) && picture(plan.steps[si + 1]) ? POST_PICTURE_XFADE : 0; const until = last ? T : Math.min(T, step.at + step.seconds + xfOut); // ITS OWN ATTACHMENT entering with his own post (post-item.mjs ownMediaEnterAt): crossfaded in from that moment. const enterIn = si === 0 && plan.enter > 0 ? POST_ENTER_FADE : 0; const fadeIn = (from) => (xfIn ? `,format=rgba,fade=t=in:st=${num(from)}:d=${num(xfIn)}:alpha=1` : enterIn ? `,format=rgba,fade=t=in:st=${num(from)}:d=${num(enterIn)}:alpha=1` : ""); // Beside the card, the first attachment is up from the first frame (its first frame while the words are read) -- // unless it enters with his own post. const shownFrom = si === 0 && layout.mode === "side" && !(plan.enter > 0) ? 0 : step.at; const boxes = stepBoxes(step, layout.slot); step.items.forEach((m, j) => { const b = boxes[j]; const file = files[m.i]; const crop = Array.isArray(m.crop) ? `crop=iw*${num(m.crop[2])}:ih*${num(m.crop[3])}:iw*${num(m.crop[0])}:ih*${num(m.crop[1])},` : ""; const label = `m${si}_${j}`; // A censored attachment (post-censor.mjs): its chain ends in a raw label, blurred into `label`. const raw = blurOn(m) ? `${label}r` : label; if (step.kind === "image" || step.kind === "grid") { if (m.push === true) { const frames = Math.max(1, Math.round((until - shownFrom) * fps)); const k = add(["-i", file]); parts.push( `[${k}:v]${crop}scale=${b.width * 2}:${b.height * 2},setsar=1,` + `zoompan=z='1+${POST_PUSH}*on/${frames}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${b.width}x${b.height}:fps=${fps},` + `setpts=PTS-STARTPTS+${num(shownFrom)}/TB${fadeIn(shownFrom)}[${raw}]`, ); } else { const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]); parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}${fadeIn(shownFrom)}[${raw}]`); } } else { // A video or a GIF: its span from srcFrom, its first frame held from the item's start until it plays. A step // that HOLDS (post-item.mjs: a screen's span, post-screens.mjs) plays no further than its span: its last frame held. const len = until - step.at; const play = step.hold === true && Number.isFinite(step.srcTo) ? Math.min(len, Math.max(0.05, step.srcTo - step.srcFrom)) : len; const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(play), "-i", file]); parts.push( `[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,` + `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}${fadeIn(shownFrom)}[${raw}]`, ); if (step.sound) { const ms = Math.round(step.at * 1000); const dur = Math.min(step.seconds, play); audio.push({ label: `a${si}`, chain: `[${k}:a]aresample=${render.audioRate ?? 48000},aformat=channel_layouts=stereo,asetpts=PTS-STARTPTS,atrim=0:${num(dur)},afade=t=in:d=0.04,afade=t=out:st=${num(Math.max(0, dur - 0.06))}:d=0.06,adelay=${ms}|${ms}[a${si}]` }); } } // THE JOIN (post-join.mjs): another attachment than the one the item before ended on fades in over it. if (si === 0 && join?.fadeIn) parts[parts.length - 1] = parts[parts.length - 1].replace(new RegExp(`\\[${raw}\\]$`), `,format=rgba,fade=t=in:st=${num(join.seconds * 0.35)}:d=${num(join.seconds * 0.65)}:alpha=1[${raw}]`); if (raw !== label) parts.push(...blurFilters(raw, label, m, b)); lay(label, b.x, b.y, shownFrom, until); // Its label ("Censored") on the frame, at the attachment's corner, while it is up. const lf = blurOn(m) ? labelFilter(cur, `b${n + 1}`, m, b, { from: shownFrom, to: until, fontfile, scale: box.height / 1080 }) : null; if (lf) { parts.push(lf); cur = `b${++n}`; } }); }); // THE PANEL (post-thread.mjs panelSchedule): a context post's attachment over the slot while it is on screen -- // crossfaded in and out over the item's own; a tall picture read through scrolled top to foot (its crop's y on t). if (plan.panel && layout.slot) { const fade = plan.panel.fade ?? 0.3; plan.panel.shows.forEach((show, pi) => { const items = show.media.map((m, j) => ({ ...m, i: j })); const boxes = stepBoxes({ items }, layout.slot); const until = Math.min(T, show.t1 + fade); items.forEach((m, j) => { const file = panelFiles[pi]?.[j]; if (!file) return; const label = `pn${pi}_${j}`; const raw = blurOn(m) ? `${label}r` : label; const fades = `format=rgba${show.t0 > 0.001 ? `,fade=t=in:st=${num(show.t0)}:d=${num(fade)}:alpha=1` : ""}${until < T - 0.001 ? `,fade=t=out:st=${num(show.t1)}:d=${num(fade)}:alpha=1` : ""}`; let b = boxes[j]; if (show.scroll && j === 0 && m.kind === "image" && (m.height ?? 0) / Math.max(1, m.width ?? 1) > (layout.slot.height / layout.slot.width) * 1.4) { // Scrolled: the picture at a readable width, a window of the slot's height panned down it as it is read. const w = Math.max(2, Math.floor(Math.min(layout.slot.width, layout.slot.height * 0.8) / 2) * 2); const fullH = Math.max(2, Math.floor((w * (m.height ?? 1)) / Math.max(1, m.width ?? 1) / 2) * 2); const h = Math.max(2, Math.floor(layout.slot.height / 2) * 2); const range = Math.max(0, fullH - h); b = { x: Math.round(layout.slot.x + (layout.slot.width - w) / 2), y: layout.slot.y, width: w, height: h }; const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]); parts.push(`[${k}:v]scale=${w}:${fullH},setsar=1,fps=${fps},crop=${w}:${h}:0:'${num(range)}*(${scrollExpr(show.scroll)})',${fades}[${raw}]`); } else if (m.kind === "image") { const crop = Array.isArray(m.crop) ? `crop=iw*${num(m.crop[2])}:ih*${num(m.crop[3])}:iw*${num(m.crop[0])}:ih*${num(m.crop[1])},` : ""; const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]); parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},${fades}[${raw}]`); } else { // A video or a GIF of a context post: looped, silent, from its first frame as it comes up. const k = add(["-stream_loop", "-1", "-t", num(Math.max(0.1, until - show.t0)), "-i", file]); parts.push(`[${k}:v]scale=${b.width}:${b.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,tpad=start_duration=${num(show.t0)}:start_mode=clone,${fades}[${raw}]`); } if (raw !== label) parts.push(...blurFilters(raw, label, m, b)); lay(label, b.x, b.y, show.t0, until); }); }); } // THE JOIN (post-join.mjs): what the item before ended on in its slot, fading out over the join (a video playing on). if (join?.from?.length) { const J = join.seconds; join.from.forEach((f, ji) => { const label = `jf${ji}`; const raw = blurOn(f.m) ? `${label}r` : label; const crop = Array.isArray(f.m.crop) ? `crop=iw*${num(f.m.crop[2])}:ih*${num(f.m.crop[3])}:iw*${num(f.m.crop[0])}:ih*${num(f.m.crop[1])},` : ""; const k = f.m.kind === "image" ? add(["-loop", "1", "-framerate", String(fps), "-t", num(J), "-i", f.file]) : add([...(f.m.kind === "gif" ? ["-stream_loop", "-1"] : []), "-ss", num(f.t), "-t", num(J + 0.1), "-i", f.file]); parts.push(`[${k}:v]${crop}scale=${f.box.width}:${f.box.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,tpad=stop_mode=clone:stop_duration=${num(J)},format=rgba,fade=t=out:st=0:d=${num(J)}:alpha=1[${raw}]`); if (raw !== label) parts.push(...blurFilters(raw, label, f.m, f.box)); lay(label, f.box.x, f.box.y, 0, J); }); } // THE BRANCH MAP (post-branch-map.mjs): over everything, where mapPlace put it, while it is up. if (map) { const mi = add(["-f", "concat", "-safe", "0", "-i", map.list]); parts.push(`[${mi}:v]fps=${fps},format=rgba,setpts=PTS-STARTPTS+${num(map.t0)}/TB[bmap]`); const next = `b${++n}`; parts.push(`[${cur}][bmap]overlay=x=${map.x}:y=${map.y}:eof_action=pass:enable='between(t,${num(map.t0)},${num(map.t3)})'[${next}]`); cur = next; } // A video attachment's words (its transcript), at the slot's foot. if (captions.length && fontfile && layout.slot) { const size = Math.round(34 * (box.height / 1080)); const y = Math.round(layout.slot.y + layout.slot.height - size * 2.2); const cx = Math.round(layout.slot.x + layout.slot.width / 2); for (const c of captions) { const next = `b${++n}`; parts.push( `[${cur}]drawtext=fontfile='${fontfile}':textfile='${c.textfile}':fontsize=${size}:fontcolor=white:box=1:boxcolor=black@0.62:boxborderw=${Math.round(size * 0.35)}:` + `x=${cx}-text_w/2:y=${y}:enable='between(t,${num(c.from)},${num(c.to)})'[${next}]`, ); cur = next; } } // SLAMS (post-slam.mjs): their frames shot alone over the whole box, laid over everything while each is up; then // the frame's punch at each hit -- the box padded in the card's ground and cropped back, moved on t. for (const [si, sl] of slams.entries()) { const li = add(["-f", "concat", "-safe", "0", "-i", sl.list]); parts.push(`[${li}:v]fps=${fps},format=rgba,setsar=1,setpts=PTS-STARTPTS+${num(sl.t0)}/TB[slm${si}]`); const next = `b${++n}`; parts.push(`[${cur}][slm${si}]overlay=x=0:y=0:eof_action=pass:enable='between(t,${num(sl.t0)},${num(sl.t3)})'[${next}]`); cur = next; } const landings = slams.flatMap((sl) => sl.landings ?? []); if (landings.length) { const amp = SLAM_MOTION.shake.amp * (box.height / 1080); const P = Math.ceil(amp * 2.2) + 2; const bg = String(render.palette?.bg ?? "#12100c").replace("#", "0x"); const next = `b${++n}`; parts.push(`[${cur}]pad=iw+${2 * P}:ih+${2 * P}:${P}:${P}:color=${bg},crop=${box.width}:${box.height}:'${P}+${slamShakeExpr(landings, "x", amp)}':'${P}+${slamShakeExpr(landings, "y", amp)}'[${next}]`); cur = next; } parts.push(`[${cur}]format=yuv420p${place.length ? `,${place.join(",")}` : ",setsar=1"}[v]`); const sil = add(["-f", "lavfi", "-t", num(T), "-i", `anullsrc=channel_layout=stereo:sample_rate=${render.audioRate ?? 48000}`]); // Narrated (post-narration.mjs): the item's own sound is the bed the narrator reads over -- muffled, then clean. // THE SLAM's HITS (post-slam.mjs, trailer-hits.mjs): mixed in after the item's own sound and the read -- no duck. const outA = slamHitList.length ? "apre" : "a"; // A PICTURE-ONLY post's video SPEAKING through its beat (post-picture.mjs): mixed in after the read's mix -- never // ducked under the read (the beat is before it), as the item's own attachment's sound is mixed: unlevelled, faded. const preSound = picSounds.length ? "aps" : outA; const media = narration && plan.narration ? "pm" : preSound; if (audio.length) { parts.push(...audio.map((a) => a.chain)); parts.push(`[${sil}:a]${audio.map((a) => `[${a.label}]`).join("")}amix=inputs=${audio.length + 1}:normalize=0:duration=first[${media}]`); } else parts.push(`[${sil}:a]anull[${media}]`); if (media === "pm") { const vi = add(["-i", narration.file]); // A take that says a slur the cut masks (post-slurs.mjs takeBleeps): silenced or beeped over it, on the take's own clock. const bl = narration.bleeps?.spans?.length ? bleepFilters(`${vi}:a`, "pnbl", narration.bleeps, { audioRate: render.audioRate ?? 48000, seconds: narration.bleeps.seconds ?? 600 }) : []; parts.push(...bl); parts.push(...postNarrationFilters({ media: "pm", voice: bl.length ? "pnbl" : `${vi}:a`, out: preSound, sch: plan.narration, gainDb: narration.gainDb ?? 0, audioRate: render.audioRate ?? 48000 })); } if (picSounds.length) { const labels = picSounds.map((ps, i) => { const from = Number.isFinite(ps.m.start) && ps.m.start > 0 ? ps.m.start : 0; const dur = Math.max(0.1, ps.t1 - ps.t0); const k = add([...(from > 0 ? ["-ss", num(from)] : []), "-t", num(dur + 0.1), "-i", ps.file]); const ms = Math.round(ps.t0 * 1000); parts.push(`[${k}:a]aresample=${render.audioRate ?? 48000},aformat=channel_layouts=stereo,asetpts=PTS-STARTPTS,atrim=0:${num(dur)},afade=t=in:d=0.04,afade=t=out:st=${num(Math.max(0, dur - 0.12))}:d=0.12,adelay=${ms}|${ms}[psd${i}]`); return `[psd${i}]`; }); parts.push(`[aps]${labels.join("")}amix=inputs=${labels.length + 1}:normalize=0:duration=first[${outA}]`); } if (slamHitList.length) { parts.push(trailerHitsGraph(slamHitList, { seconds: T, rate: render.audioRate ?? 48000, layout: "stereo", prefix: "sl" })); // A ceiling just under full scale: a hit on a loud word never clips (the read is untouched below it). parts.push(`[apre][sla]amix=inputs=2:normalize=0:duration=first,alimiter=limit=0.95:level=0:latency=1:attack=2:release=60[a]`); } return [ "-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", parts.join(";"), "-map", "[v]", "-map", "[a]", ...encode, // Limited range, converted: a JPEG input would make the segment full range (color-range.mjs). ...LIMITED_RANGE, "-t", num(T), outPath, ]; } /** * A caption's track (`[{ t, dx, dy }]`: how far its phrase has moved from where * it was placed, from item second t) as an ffmpeg term of `t` to add to its * x or y ("" when it never moves). */ export function trackExpr(track, axis) { const steps = []; for (const p of track) if (!steps.length ? p[axis] !== 0 : p[axis] !== steps[steps.length - 1].v) steps.push({ t: p.t, v: p[axis] }); if (!steps.length) return ""; // Nested from the last change back: before each change, what held until it. let e = String(steps[steps.length - 1].v); for (let k = steps.length - 1; k >= 0; k -= 1) e = `if(lt(t,${num(steps[k].t)}),${k ? steps[k - 1].v : 0},${e})`; return `+(${e})`; } export async function loadChromium() { let mod; try { mod = await import("@playwright/test"); } catch (err) { throw new Error(`a post item's card is drawn by a browser, and Playwright is not available here (it ships with umtool): ${err.message}`); } const chromium = mod.chromium ?? mod.default?.chromium; if (!chromium) throw new Error("Playwright loaded but has no chromium export"); return chromium; } /** * Draw the card's pages as PNGs, `box` px each: `read` always, `media` for a * stack layout. The page is a file beside them, so its faces and the parent * shot load from disk (an about:blank page may not read file: urls). */ export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, joinFrom = null, captions = [], clock = null, obstacles = [], slams = [], progress = null, pics = [], cardPics = null }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", bold: render.fontBold ? pathToFileURL(render.fontBold).href : "", }; const parentShotUrl = typeof entry.parentShot === "string" ? pathToFileURL(path.resolve(manifestDir, entry.parentShot)).href : null; const phases = layout.mode === "stack" ? ["read", "media"] : ["read"]; const chromium = await loadChromium(); const browser = await chromium.launch({ headless: true }); const out = {}; try { const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); // THE JOIN (post-join.mjs): the item before's card as it ENDED -- its page drawn, its last frame's state set, its // card shot -- and where its post's words sat; this card opens on it and morphs into its own. // The shot is the item before's LAST FRAME as its segment draws it (check-joins.mjs measures it): its page (its // parent's shot too), its read-follow's last state, a link visit's pointer, and its clock -- in the shot when // this item has none (it fades with the card), else this item's clock starts where that one sat and moves. let join = null; if (follow?.join && joinFrom?.entry) { const fps = render.fps ?? 30; const pe = joinFrom.entry; const pf = joinFrom.plan?.follow ?? null; const pShot = typeof pe.parentShot === "string" ? pathToFileURL(path.resolve(manifestDir, pe.parentShot)).href : null; const ph = postCardHtml(pe, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl: pShot, avatars: av, follow: !!pf, thread: pf?.thread ?? null, redaction, join: joinFrom.carry ?? null, ...(cardPics ?? {}) }); const pfile = path.join(dir, "join-from.html"); await writeFile(pfile, ph, "utf8"); await page.goto(pathToFileURL(pfile).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); const endS = Math.max(0, joinFrom.plan.total - 1 / fps); const pl0 = postLayout(pe, box); // Its clock, placed as its own segment placed it (clockPlaceOn), shown at its end unless a stack card's media // phase hid it. const pClock = joinFrom.clock && !(pl0.mode === "stack" && joinFrom.plan.steps?.length) ? joinFrom.clock : null; let clockFrom = null; if (pClock) { const k = box.height / 1080; const face = clockFace(pClock.to, pClock.zone); const size = await page.evaluate(mountClock, { css: clockCss({ height: box.height, palette: render.palette }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } }); await page.evaluate(() => document.fonts.ready.then(() => true)); const at = size ? await clockPlaceOn(page, { follow: pf, total: joinFrom.plan.total, size, k }) : null; if (at) clockFrom = { x: at.x, y: at.y, st: clockStateAt(pClock, endS) }; } if (pf) { const pgeo = await page.evaluate(measureFollow); // Its own join's opening frame (its record's `joinAnchor`): a read that never pans again ends where it opened. if (pgeo && Number.isFinite(joinFrom.anchorY)) pgeo.joinAnchor = { y: joinFrom.anchorY }; const st = followStateAt(pf, followPath(pf, pgeo), endS); await page.evaluate(applyFollowState, st); if (pf.visits?.length) await page.evaluate(applyVisitState, { visits: pf.visits, st: st.visit ?? null }); } const m = await page.evaluate(() => { const card = document.querySelector("[data-post-card]"); if (!card) return null; const c = card.getBoundingClientRect(); // His post's head where the item before drew it (a threaded card's post tile; a plain card's head), and its words' size. // Its HEAD (name and date): where the carried post's head goes (a relation line above it moves its tile, not it). const post = document.querySelector('[data-thread-slot="post"] .head') ?? card.querySelector(".head"); const words = document.querySelector('[data-thread-slot="post"] .twords') ?? document.querySelector("[data-post-words]"); const pr = post ? post.getBoundingClientRect() : null; return { A: { x: c.left, y: c.top, width: c.width, height: c.height }, anchor: pr ? pr.top - c.top : null, size: words ? parseFloat(getComputedStyle(words).fontSize) : null, plain: !document.querySelector('[data-thread-slot="post"]'), headSize: post ? parseFloat(getComputedStyle(post).fontSize) : null }; }); if (m) { const png = path.join(dir, "join-from.png"); const x = Math.max(0, Math.floor(m.A.x)); const y = Math.max(0, Math.floor(m.A.y)); const clip = { x, y, width: Math.min(box.width - x, Math.ceil(m.A.width)), height: Math.min(box.height - y, Math.ceil(m.A.height)) }; await page.screenshot({ path: png, clip }); // And with its clock on it, as it ended (laid in the shot when this item's clock does not carry on from it). let pngClock = null; if (clockFrom) { pngClock = path.join(dir, "join-from-clock.png"); await page.evaluate(setClockState, clockFrom); await page.screenshot({ path: pngClock, clip }); await page.evaluate(setClockState, null); } const pl = postLayout(pe, box); const same = Math.abs(m.A.width - layout.card.width) < 2 && !!(follow.thread?.tiles ?? []).some((t) => t.mode === "carry" || (t.mode === "scene" && t.wasPost)); join = { A: { x, y, width: Math.ceil(m.A.width), height: Math.ceil(m.A.height) }, slotA: pl.slot && pl.mode === "side" ? pl.slot : null, fromUrl: pathToFileURL(png).href, size: m.size, same, anchor: m.anchor, plain: m.plain, headSize: m.headSize }; out.joinFrom = { A: join.A, layout: pl, clock: clockFrom ? { x: clockFrom.x, y: clockFrom.y } : null, pngClock }; } } // THE CLOCK (post-clock.mjs), shot before the read's frames: over a join, where it opens decides the shot the // card opens on (joinClockOf: carried on from the item before's clock, or that one laid in the shot, fading). if (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total, cardPics }); if (join) { const jc = joinClockOf({ from: out.joinFrom?.clock ?? null, own: out.clock?.at ?? null, k: box.height / 1080 }); if (jc.bake && out.joinFrom?.pngClock) join.fromUrl = pathToFileURL(out.joinFrom.pngClock).href; if (out.clock) out.clock.join = { seconds: follow.join.seconds, from: jc.move, fadeIn: jc.fadeIn }; } let picPath = null; for (const phase of phases) { const html = postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl, avatars: av, follow: !!follow && phase === "read", // A threaded card (post-thread.mjs): the plan's tiles. thread: follow?.thread ?? null, redaction, ...(join && phase === "read" ? { join } : {}), // PICTURE-ONLY posts (post-picture.mjs): their pictures in their cards, the files and the GIFs' stills. ...(cardPics ?? {}), }); const file = path.join(dir, `${phase}.html`); await writeFile(file, html, "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); const png = path.join(dir, `${phase}.png`); await page.screenshot({ path: png, clip: { x: 0, y: 0, width: box.width, height: box.height } }); out[phase] = png; if (phase === "read" && follow) { const fps = render.fps ?? 30; const geo = await page.evaluate(measureFollow); // THE JOIN: the carried post opens where the item before's post sat (its top this far down the window). if (join && geo && join.anchor !== null) { const own = await page.evaluate(() => { const c = document.querySelector("[data-post-card]")?.getBoundingClientRect(); const w = document.querySelector("[data-post-words]")?.getBoundingClientRect(); const tile = document.querySelector("[data-join-anchor]"); const head = tile?.querySelector(".head")?.getBoundingClientRect(); const slot = tile?.closest("[data-thread-slot]")?.getBoundingClientRect(); return c && w ? { win: w.top - c.top, width: c.width, head: head && slot ? head.top - slot.top : 0 } : null; }); if (own) geo.joinAnchor = { y: Math.round((join.anchor / (join.A.width / own.width) - own.win - own.head) * 100) / 100 }; if (geo.joinAnchor) out.joinAnchor = geo.joinAnchor.y; } out.follow = await shootFollow(page, { follow, total, fps, box, dir, geo }); // THE BRANCH MAP (post-branch-map.mjs): its own layer, shot on a transparent page, laid over the attachments. if (follow.thread?.map) out.map = await shootMap(ctx, { map: follow.thread.map, layout, box, fps, dir, render, fonts, entry }); // THE INVARIANT (read-follow.mjs readInViewErrors): what each part reads is in view, whole and lit, in the // frames as they are shot -- or, with none shot, in the page as drawn. const fpath = out.follow?.path ?? followPath(follow, geo); picPath = fpath; out.inView = readInViewErrors(follow, geo, shotStateAt(follow, fpath, fps, !!out.follow), { total, id: entry.id }); } // PICTURE-ONLY posts' GIFs and videos (post-picture.mjs): where each is drawn while its card is at full size // and still -- the build plays it over that place then (the page draws its still the rest of the time). if (phase === "read" && pics.some(movingPic)) out.pics = await measurePics(page, { pics, follow, path: picPath, total, fps: render.fps ?? 30, joined: !!join }); } await ctx.close(); if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow, cardPics }); // The progress bar (post-progress.mjs): along the card's foot, short of the clock on its line. if (progress) { const k = box.height / 1080; const cb = out.clock?.box ? { x: out.clock.box.x + Math.round(240 * k), y: out.clock.box.y, width: out.clock.box.width - Math.round(240 * k), height: out.clock.box.height } : null; out.progress = await shootProgress(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, progress, redaction, follow, total, avoid: cb ? [cb] : [], cardPics }); } // A caption covers none of the attachments (`obstacles`: their boxes) nor the clock. if (captions.length) out.captions = await shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction, follow, obstacles: [...obstacles, ...(out.clock ? [out.clock.box] : [])], cardPics }); if (slams.length) out.slams = await shootSlams(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, slams, redaction, follow, cardPics }); } finally { await browser.close(); } return out; } /** * A shot's line in a frames list (ffconcat): its image read at the item's rate. Without it each PNG is read on the * image demuxer's 1/25 s clock, its start rounded to a 40 ms step, and the 30 fps output drops one shot in six and * holds its neighbour -- every pan, join and clock run juddered (measured: a held frame every 0.2 s in mid-7's joins). */ export const concatRate = (fps) => [`option framerate ${fps}`]; /** * READ-FOLLOW's FRAMES (read-follow.mjs): on the drawn card page, the pan's * path from its geometry (`geo`, measureFollow's: measured here when not * given), then every frame's state (followStateAt at frame i / fps); each * distinct state applied and the card's region shot once, and a concat list * holding each shot for its frames. Null only when every frame is the page * as drawn (isDrawnState: nothing dimmed, panned or shrunk) -- a threaded * card's context post is small and dim from its first frame, so it is shot * even when one part is read and nothing moves. `{ list, clip, shots, frames, * geo, path }`. */ export async function shootFollow(page, { follow, total, fps, box, dir, geo = null }) { geo ??= await page.evaluate(measureFollow); const path0 = followPath(follow, geo); const frames = Math.max(1, Math.round(total * fps)); const runs = followRuns(follow, path0, total, fps); if (runs.every((run) => isDrawnState(run.st))) return null; const r = await page.evaluate(() => { const b = document.querySelector("[data-post-card]")?.getBoundingClientRect(); return b ? { x: b.left, y: b.top, width: b.width, height: b.height } : null; }); if (!r) return null; const x = Math.max(0, Math.floor(r.x)); const y = Math.max(0, Math.floor(r.y)); // A JOIN (post-join.mjs) moves the card and the slot's well: the whole box is shot. const joined = !!follow.join && (await page.evaluate(() => !!document.body.getAttribute("data-join"))); const clip = joined ? { x: 0, y: 0, width: box.width, height: box.height } : { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height) - y) }; const fdir = path.join(dir, "follow"); await rm(fdir, { recursive: true, force: true }); await mkdir(fdir, { recursive: true }); const shots = new Map(); for (const run of runs) { if (shots.has(run.key)) continue; const file = path.join(fdir, `f-${String(shots.size).padStart(5, "0")}.png`); await page.evaluate(applyFollowState, run.st); if (joined) await page.evaluate(applyJoinState, run.st.join ?? null); // A LINK VISIT (post-link-visit.mjs): the pointer and its click over the link where the state puts it. if (follow.visits?.length) await page.evaluate(applyVisitState, { visits: follow.visits, st: run.st.visit ?? null }); await page.screenshot({ path: file, clip }); shots.set(run.key, file); } await page.evaluate(applyFollowState, null); if (joined) await page.evaluate(applyJoinState, null); if (follow.visits?.length) await page.evaluate(applyVisitState, { visits: follow.visits, st: null }); const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, ...concatRate(fps), `duration ${(run.n / fps).toFixed(6)}`); lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); const list = path.join(fdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); return { list, clip, shots: shots.size, frames, geo, path: path0 }; } /** A picture-only post whose picture moves (a GIF, a video): the build plays it in its card. */ const movingPic = (p) => p?.media?.[0]?.kind === "gif" || p?.media?.[0]?.kind === "video"; /** * WHERE A PICTURE-ONLY POST's GIF OR VIDEO PLAYS (post-picture.mjs), measured on the card's page: `[{ scope, m, box, * t0, t1 }]` -- each span of the item, at least POST_PIC_MIN_SPAN s, through which its card's tile is at full size * and strength and its picture's place does not move (no pan, no join, no shrink); the page's still is what shows * the rest of the time. A card with no read-follow is still: the whole item. */ export async function measurePics(page, { pics, follow, path: fpath = null, total, fps, joined = false }) { const rectOf = (scope) => page.evaluate((sc) => { const el = document.querySelector(`[data-post-pic="${sc}"]`); if (!el) return null; const r = el.getBoundingClientRect(); const win = document.querySelector("[data-post-words]")?.getBoundingClientRect() ?? null; return { x: r.left, y: r.top, width: r.width, height: r.height, w0: el.offsetWidth, h0: el.offsetHeight, win: win ? { top: win.top, bottom: win.bottom } : null }; }, scope); const out = []; const moving = pics.filter(movingPic); if (!follow) { for (const p of moving) { const r = await rectOf(p.scope); if (r) out.push({ scope: p.scope, m: p.media[0], box: evenBox(r), t0: 0, t1: r3(total) }); } return out; } const runs = followRuns(follow, fpath ?? followPath(follow, await page.evaluate(measureFollow)), total, fps); const samples = new Map(moving.map((p) => [p.scope, []])); let frame = 0; for (const run of runs) { await page.evaluate(applyFollowState, run.st); if (joined) await page.evaluate(applyJoinState, run.st.join ?? null); for (const p of moving) { const r = await rectOf(p.scope); const st = run.st.tiles?.[p.scope] ?? [1, 1]; const full = !!r && st[0] >= 0.999 && st[1] >= 0.999 && Math.abs(r.width - r.w0) < 0.6 && Math.abs(r.height - r.h0) < 0.6; const inView = !!r && (!r.win || (r.y >= r.win.top - 0.5 && r.y + r.height <= r.win.bottom + 0.5)); samples.get(p.scope).push({ f0: frame, f1: frame + run.n, ok: full && inView, r }); } frame += run.n; } await page.evaluate(applyFollowState, null); if (joined) await page.evaluate(applyJoinState, null); for (const p of moving) { let cur = null; const close = () => { if (cur && (cur.f1 - cur.f0) / fps >= POST_PIC_MIN_SPAN) out.push({ scope: p.scope, m: p.media[0], box: evenBox(cur.r), t0: r3(cur.f0 / fps), t1: r3(Math.min(total, cur.f1 / fps)) }); cur = null; }; for (const sm of samples.get(p.scope)) { const same = cur && Math.abs(sm.r.x - cur.r.x) < 0.6 && Math.abs(sm.r.y - cur.r.y) < 0.6; if (!sm.ok) close(); else if (same) cur.f1 = sm.f1; else { close(); cur = { f0: sm.f0, f1: sm.f1, r: sm.r }; } } close(); } return out; } /** The shortest span a picture-only post's GIF is played over its still (s). */ export const POST_PIC_MIN_SPAN = 0.3; /** Its fade back to the still at a span's end (s). */ export const POST_PIC_FADE = 0.25; /** The drawing of a picture-only post (postSegmentKeyOf `pics`): bump it when the card draws one differently. */ export const POST_PICTURE_DRAW_V = 2; const evenBox = (r) => ({ x: Math.round(r.x), y: Math.round(r.y), width: Math.max(2, Math.round(r.width / 2) * 2), height: Math.max(2, Math.round(r.height / 2) * 2) }); /** * THE BRANCH MAP's FRAMES (post-branch-map.mjs): the map alone on a transparent page, each distinct state (its * strength, its light's place) shot once over its span, a concat list holding each for its frames; `{ list, x, y, * t0, t3 }` -- where it is laid (mapPlace: over the slot, or beside a card alone) and when. */ async function shootMap(ctx, { map, layout, box, fps, dir, render, fonts, entry }) { const k = box.height / 1080; const size = mapSize(map, k); const at = mapPlace(layout, box, size, k); const pal = { fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...(render.palette ?? {}) }; const blurred = cardAuthors(entry).filter((a) => a.redact && a.handle).map((a) => a.handle); const page = await ctx.newPage(); try { await page.setViewportSize({ width: Math.max(2, size.width + 4), height: Math.max(2, size.height + 4) }); const file = path.join(dir, "map.html"); await writeFile(file, mapPageHtml(map, { width: size.width + 4, height: size.height + 4, k, accent: pal.accent, fg: pal.fg, muted: pal.muted, blurred, fonts }), "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); const el = await page.evaluate(() => { const m = document.querySelector("[data-thread-map]"); if (!m) return null; m.style.display = "block"; const r = m.getBoundingClientRect(); return { width: Math.ceil(r.width), height: Math.ceil(r.height) }; }); if (!el) return null; const mdir = path.join(dir, "map"); await rm(mdir, { recursive: true, force: true }); await mkdir(mdir, { recursive: true }); const { t0, t3 } = map.times; const frames = Math.max(1, Math.round((t3 - t0) * fps)); const runs = []; for (let i = 0; i < frames; i += 1) { const st = mapStateAt(map, t0 + i / fps) ?? { op: 0, p: 0 }; const key = JSON.stringify(st); const last = runs[runs.length - 1]; if (last && last.key === key) last.n += 1; else runs.push({ key, st, n: 1 }); } const shots = new Map(); for (const run of runs) { if (shots.has(run.key)) continue; const png = path.join(mdir, `m-${String(shots.size).padStart(4, "0")}.png`); await page.evaluate(applyMapState, run.st); await page.screenshot({ path: png, clip: { x: 0, y: 0, width: el.width, height: el.height }, omitBackground: true }); shots.set(run.key, png); } const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, ...concatRate(fps), `duration ${(run.n / fps).toFixed(6)}`); lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); const list = path.join(mdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); return { list, x: Math.round(at.x), y: Math.round(at.y), t0, t3 }; } finally { await page.close(); } } /** The device scale a word zoom's shots are taken at: crisp at its scale (2–4). */ export const zoomShotScale = (zooms) => Math.min(4, Math.max(2, Math.ceil(Math.max(1, ...zooms.map((z) => z.scale ?? WORD_ZOOM_DEFAULTS.scale))))); /** * Each WORD ZOOM's shots and geometry: the card's page at k× (zoomShotScale), * its card's box inset by its corner (the REGION a zoom fills), the matched * words' box (their spans' union, `data-w=":"`) -- refused when a * word is cut off the card (a clamped context post, a post shrunk to fit) -- * and the region shot plain and with the zoom's highlight under the words. * `zooms`: `[{ i, scope, from, to, scale, highlight }]`. */ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction = null, follow = null, cardPics = null }) { const k = zoomShotScale(zooms); const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: k, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); const load = async (name, highlight) => { const file = path.join(dir, `${name}.html`); await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, redaction, follow: !!follow, thread: follow?.thread ?? null, ...(cardPics ?? {}) }), "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); }; // Following (read-follow.mjs): each zoom is shot as the card is at its peak -- that block lit, the words panned there. let fpath = null; const atZoom = async (z) => { if (!follow) return; fpath ??= followPath(follow, await page.evaluate(measureFollow)); await page.evaluate(applyFollowState, followStateAt(follow, fpath, z.span.t1)); }; const out = []; try { await load("zoom", null); const radius = Math.round(18 * (box.height / 1080)) + 1; for (const z of zooms) { await atZoom(z); const geo = await page.evaluate(({ scope, from, to, radius: r }) => { const rect = (el) => { const b = el.getBoundingClientRect(); return { x: b.left, y: b.top, width: b.width, height: b.height }; }; const card = document.querySelector("[data-post-card]"); if (!card) return { error: "the card is not drawn" }; const c = rect(card); const spans = []; for (let i = from; i <= to; i += 1) { const el = document.querySelector(`[data-w="${scope}:${i}"]`); if (!el) return { error: `word ${i} is not on the card` }; spans.push(el); } let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; for (const el of spans) { const b = rect(el); const clip = el.closest(".words, .ptext, .qtext"); const cb = clip ? clip.getBoundingClientRect() : card.getBoundingClientRect(); if (b.y + b.height > cb.bottom + 1 || b.y < cb.top - 1 || b.width === 0) return { error: "cut off the card (the text is longer than the card shows)" }; x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y); x1 = Math.max(x1, b.x + b.width); y1 = Math.max(y1, b.y + b.height); } const even = (v) => Math.max(2, Math.floor(v / 2) * 2); const region = { x: Math.ceil(c.x + r), y: Math.ceil(c.y + r), width: even(c.width - 2 * r), height: even(c.height - 2 * r) }; return { region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } }; }, { scope: z.scope, from: z.from, to: z.to, radius }); if (geo.error) throw new Error(`${entry.id}: word zoom ${z.i + 1}: the word is ${geo.error}`); out.push({ ...z, k, region: geo.region, word: geo.word }); } const clip = (r) => ({ x: r.x, y: r.y, width: r.width, height: r.height }); for (const z of out) { z.plain = path.join(dir, `zoom-${z.i}.png`); await atZoom(z); await page.screenshot({ path: z.plain, clip: clip(z.region) }); } for (const z of out) { if (!z.highlight) continue; await load(`zoom-hl-${z.i}`, { scope: z.scope, from: z.from, to: z.to, color: z.highlight }); await atZoom(z); z.hl = path.join(dir, `zoom-hl-${z.i}.png`); await page.screenshot({ path: z.hl, clip: clip(z.region) }); } } finally { await ctx.close(); } return out; } /** * Each CAPTION's shots and place (post-caption.mjs): on the card page as it is * drawn when the caption is fully in (read-follow's state at its t1), the * phrase measured -- refused when it is cut off the card -- and the words read * while it is up; the chip placed by them (placeCaption: never covering one), * then shot alone on a clear page (the chip with its notch; the underline * apart, as it does not slide). Following, the phrase is measured frame by * frame over the caption's span: its `track`, which the chip rides. * `captions`: captionPlan's. Returns `[{ ...caption, chip, mark, slide, track, placed }]`. */ export async function shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction = null, follow = null, obstacles: fixed = [], cardPics = null }) { const fps = render.fps ?? 30; const k = box.height / 1080; const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); const out = []; try { const file = path.join(dir, "caption.html"); await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null, ...(cardPics ?? {}) }), "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); await page.evaluate(() => document.fonts.ready.then(() => true)); const sizes = await page.evaluate(mountCaptions, { css: captionCss({ height: box.height, palette: render.palette }), chips: captions.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k }); await page.evaluate(() => document.fonts.ready.then(() => true)); const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; const stateAt = async (s) => { if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); }; const inset = Math.round(12 * k); const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset }; for (const c0 of captions) { let c = c0; // A pan moving the phrase while it is up: the caption is gone before it moves (the chip never rides over words). if (follow) { let base = null; for (let f = Math.floor(c.span.t0 * fps); f <= Math.ceil(c.span.t3 * fps); f += 1) { await stateAt(f / fps); const g = await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: [] }); if (g.error) continue; base ??= g.word; if (Math.abs(g.word.y - base.y) > 1 || Math.abs(g.word.x - base.x) > 1) { const tm = r3(f / fps); if (tm > c.span.t1 + 0.2) c = { ...c, span: { ...c.span, t2: r3(Math.max(c.span.t1, tm - CAPTION_OUT)), t3: tm }, cutByPan: tm }; break; } } } // Its place: judged where the card is as it comes in, while it is up and as it goes (a pan's other words too). const looks = []; for (const s of follow ? [c.span.t1, c.span.t0, c.span.t3 - 0.01] : [c.span.t1]) { await stateAt(s); looks.push(await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: c.avoid })); } await stateAt(c.span.t1); const geo = looks[0]; if (geo.error) throw new Error(`${entry.id}: caption ${c.i + 1}: the phrase is ${geo.error}`); const obstacles = [...fixed, ...looks.flatMap((l) => l.obstacles ?? [])]; const size = sizes.find((x) => x.i === c.i); const placed = placeCaption({ word: geo.word, sizes: size.sizes, bounds, card: geo.card, column: geo.column, place: c.place, obstacles, gap: Math.round(10 * k) }); if (!placed) throw new Error(`${entry.id}: caption ${c.i + 1}: the chip fits nowhere in the frame`); // Shot alone: the card hidden, the page clear. await page.evaluate(() => { const st = document.createElement("style"); st.setAttribute("data-pcap-solo", ""); st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-fx-captions]) { visibility: hidden !important; }"; document.head.appendChild(st); }); const pad = Math.round(40 * k); const clipOf = (r) => { const x = Math.max(0, Math.floor(r.x - pad)); const y = Math.max(0, Math.floor(r.y - pad)); return { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width + pad) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height + pad) - y) }; }; const state = { i: c.i, x: placed.x, y: placed.y, max: placed.max, opacity: 1, marks: geo.lines, mark: 1, leader: placed.leader }; const stroke = Math.max(2, Math.round(2.4 * k)); await page.evaluate(setCaptionState, { list: [state], only: "chip", stroke }); const chipClip = clipOf(placed); const chip = { file: path.join(dir, `caption-${c.i}.png`), x: chipClip.x, y: chipClip.y }; await page.screenshot({ path: chip.file, clip: chipClip, omitBackground: true }); await page.evaluate(setCaptionState, { list: [state], only: "mark", stroke }); // The underline and the leader (which does not slide): their union. const pts = [...(placed.leader ?? []), [geo.word.x, geo.word.y + geo.word.height * 0.6], [geo.word.x + geo.word.width, geo.word.y + geo.word.height * 1.2]]; const mx0 = Math.min(...pts.map((p) => p[0])); const my0 = Math.min(...pts.map((p) => p[1])); const markClip = clipOf({ x: mx0, y: my0, width: Math.max(...pts.map((p) => p[0])) - mx0, height: Math.max(...pts.map((p) => p[1])) - my0 }); const mark = { file: path.join(dir, `caption-${c.i}-mark.png`), x: markClip.x, y: markClip.y }; await page.screenshot({ path: mark.file, clip: markClip, omitBackground: true }); await page.evaluate(setCaptionState, { list: [] }); await page.evaluate(() => document.querySelectorAll("style[data-pcap-solo]").forEach((el) => el.remove())); const rel = placed.y >= geo.word.y + geo.word.height ? "below" : placed.y + placed.height <= geo.word.y ? "above" : placed.x >= geo.word.x ? "side-right" : "side-left"; const d = slideDir(rel); // What it would cover of the words read, or of anything drawn: none, unless nothing in the frame is free. out.push({ ...c, chip, mark, slide: { x: d.x * CAPTION_SLIDE * k, y: d.y * CAPTION_SLIDE * k }, track: [], placed: { ...placed, rel, word: geo.word } }); } } finally { await ctx.close(); } return out; } /** * WHERE THE CLOCK SITS on a card page with the clock mounted (`size` its box): placed as the card is when its own * post is in (the read's end: a threaded card's counts row is there), and judged over the read (its start, middle * and end) -- the place covering fewest words over all three wins; the follow put back at its start. Null: no card. * The item's own shot (shootClock) and the join's (the item before's clock, where it sat) place it alike. */ async function clockPlaceOn(page, { follow, total, size, k }) { const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; const states = follow ? [total, 0, total / 2] : [0]; const looks = []; for (const s of states) { if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); looks.push(await page.evaluate(measureClockPlace, { size, inset: Math.round(22 * k), fixed: looks[0]?.tries ?? null })); } const at0 = looks[0]; const at = at0 ? at0.tries.map((t, i) => ({ ...t, covers: looks.reduce((a, l) => a + (l?.tries?.[i]?.covers ?? 0), 0) })).sort((a, b) => a.covers - b.covers)[0] : null; if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, 0)); return at; } /** * Each SLAM's FRAMES (post-slam.mjs): on the card page as it is drawn at its * first hit (read-follow's state then), its words measured -- the matched * words' lines and the words read at a hit, which it may not cover, and the * rest of what is drawn, which it may (the gag, for its window) -- the units * mounted at their size, the row placed (slamLayout: above the line, else * below it; refused when neither is clear), then the layer shot alone on a * clear page at every frame of its span (each distinct state once; a pan * moves the row with the words, measured frame by frame) and a concat list * holding each for its frames. `slams`: slamPlan's. Returns `[{ ...slam, * list, t0, t3, layout, size, shots }]`. */ export async function shootSlams(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, slams, redaction = null, follow = null, cardPics = null }) { const fps = render.fps ?? 30; const k = box.height / 1080; const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); const out = []; try { const file = path.join(dir, "slam.html"); await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null, ...(cardPics ?? {}) }), "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); await page.evaluate(() => document.fonts.ready.then(() => true)); const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; const stateAt = async (s) => { if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); }; const inset = Math.round(12 * k); const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset }; const cardRect = () => page.evaluate(() => { const b = document.querySelector("[data-post-card]")?.getBoundingClientRect(); return b ? { x: b.left, y: b.top, width: b.width, height: b.height } : null; }); for (const p of slams) { await stateAt(p.span.landings[0]); // Judged at each hit (a pan's words too): what it may not cover, and what it lies over. const looks = []; if (p.scope) { for (const L of follow ? p.span.landings : [p.span.landings[0]]) { await stateAt(L); const g = await page.evaluate(measureCaptionWords, { scope: p.scope, from: p.from, to: p.to, avoid: p.avoid }); if (g.error) throw new Error(`${entry.id}: slam ${p.i + 1}: its words are ${g.error}`); looks.push(g); } await stateAt(p.span.landings[0]); } const geo = looks[0] ?? null; const card = geo ? geo.card : await cardRect(); if (!card) throw new Error(`${entry.id}: slam ${p.i + 1}: the card is not drawn`); // Its size by the words' line (one line's height, not a phrase's wrapped box). const line = geo ? geo.lines.reduce((a, l) => (l.height > a.height ? l : a), geo.lines[0]) : null; const size = slamSize(p.fx, line, k); const units = p.units.map((text, kk) => ({ i: p.i, k: kk, text, size, face: SLAM_FACE_STACK[p.fx.face] ?? SLAM_FACE_STACK.jp, vars: slamVars(p.fx, size) })); // Its translation bar (with `bar`): the row lands on it, placed with it as one block. const bar = slamBarOf(p, k); const arg = { css: slamCss(), units, dust: [...SLAM_DUST], bars: bar ? [bar] : [] }; await page.evaluate(mountSlams, arg); await page.evaluate(() => document.fonts.ready.then(() => true)); // Measured again once its face is in. const boxes = await page.evaluate(mountSlams, arg); const layout = slamLayout({ word: geo ? geo.word : null, card, bounds, units: boxes, place: p.fx.place, gap: Math.round(6 * k), protect: looks.flatMap((l) => [...l.lines, ...l.avoid]), obstacles: looks.flatMap((l) => l.obstacles), }); const errs = slamCoverErrors(entry.id, p.i, layout); if (errs.length) throw new Error(errs.join("; ")); const q = { ...p, centers: layout.centers, bar: layout.bar }; // Shot alone: the card hidden, the page clear. await page.evaluate(() => { const st = document.createElement("style"); st.setAttribute("data-pslam-solo", ""); st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-fx-slams]) { visibility: hidden !important; }"; document.head.appendChild(st); }); const sdir = path.join(dir, `slam-${p.i}`); await rm(sdir, { recursive: true, force: true }); await mkdir(sdir, { recursive: true }); const f0 = Math.max(0, Math.floor(p.span.t0 * fps)); const f1 = Math.max(f0 + 1, Math.ceil(p.span.t3 * fps)); const shots = new Map(); const runs = []; const base = geo ? geo.word : null; for (let f = f0; f < f1; f += 1) { const s = f / fps; let dx = 0; let dy = 0; if (follow && p.scope && base) { await stateAt(s); const g = await page.evaluate(measureCaptionWords, { scope: p.scope, from: p.from, to: p.to, avoid: [] }); if (!g.error) { dx = Math.round(g.word.x - base.x); dy = Math.round(g.word.y - base.y); } } const list = slamListAt(q, s, dx, dy); const key = JSON.stringify(list); if (!shots.has(key)) { const png = path.join(sdir, `s-${String(shots.size).padStart(4, "0")}.png`); await page.evaluate(setSlamState, { list, shake: null }); await page.screenshot({ path: png, clip: { x: 0, y: 0, width: box.width, height: box.height }, omitBackground: true }); shots.set(key, png); } if (runs.length && runs[runs.length - 1].key === key) runs[runs.length - 1].n += 1; else runs.push({ key, n: 1 }); } await page.evaluate(setSlamState, { list: [], shake: null }); await page.evaluate(() => document.querySelectorAll("style[data-pslam-solo]").forEach((el) => el.remove())); await stateAt(0); const qq = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; for (const r of runs) lines.push(`file ${qq(shots.get(r.key))}`, ...concatRate(fps), `duration ${(r.n / fps).toFixed(6)}`); lines.push(`file ${qq(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); const list = path.join(sdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); out.push({ ...q, list, t0: f0 / fps, t3: f1 / fps, landings: p.span.landings, layout, size, shots: shots.size }); } } finally { await ctx.close(); } return out; } /** * THE PROGRESS BAR's STILLS (post-progress.mjs): on the card page as drawn, the bar mounted and placed * (measureProgressPlace: the card's foot under its counts row, short of `avoid` -- the clock -- judged over the read: * its start, middle and end, the place covering fewest words), then its track and its fill shot alone on a clear * page. `{ track, fill, x, y, width, height, place, covers, plan }`. */ export async function shootProgress(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, progress, redaction = null, follow = null, total = 0, avoid = [], cardPics = null }) { const k = box.height / 1080; const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); try { const file = path.join(dir, "progress.html"); await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null, ...(cardPics ?? {}) }), "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); const css = progressCss({ height: box.height, palette: render.palette }); const h = progressHeight(box.height); await page.evaluate(mountProgress, { css, ticks: progress.ticks, part: "track" }); const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; const states = follow ? [total, 0, total / 2] : [0]; const looks = []; for (const s of states) { if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); looks.push(await page.evaluate(measureProgressPlace, { height: h, inset: Math.round(22 * k), avoid, fixed: looks[0]?.tries ?? null })); } if (!looks[0]) throw new Error(`${entry.id}: the progress bar has no card to sit on`); // Each place's words over all three states: the fewest wins (the foot first when none). const at = looks[0].tries.map((t, i) => ({ ...t, covers: looks.reduce((a, l) => a + (l?.counts?.[i] ?? 0), 0) })).sort((a, b) => a.covers - b.covers)[0]; if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, 0)); await page.evaluate(() => { const st = document.createElement("style"); st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-progress-layer]) { visibility: hidden !important; }"; document.head.appendChild(st); }); const clip = { x: at.x, y: at.y, width: Math.min(box.width - at.x, at.width), height: Math.min(box.height - at.y, h) }; const shot = async (part) => { await page.evaluate(mountProgress, { css, ticks: progress.ticks, part }); await page.evaluate(setProgressState, { x: at.x, y: at.y, width: at.width, frac: 1, opacity: 1 }); const f = path.join(dir, `progress-${part}.png`); await page.screenshot({ path: f, clip, omitBackground: true }); return f; }; return { track: await shot("track"), fill: await shot("fill"), x: clip.x, y: clip.y, width: clip.width, height: clip.height, place: at.place, covers: at.covers, plan: progress }; } finally { await ctx.close(); } } /** * THE CLOCK's FRAMES (post-clock.mjs): on the card page as drawn, the chip * mounted at its widest and placed (measureClockPlace: the bottom-right corner * by the counts row, else the top-right -- over no word), then shot alone on a * clear page at each frame of its run and its badge's fade (each distinct one * once) and a concat list holding each for its frames, the last to the end. * `{ list, x, y, place, covers, shots }`. */ export async function shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction = null, follow = null, total = 0, cardPics = null }) { const fps = render.fps ?? 30; const k = box.height / 1080; const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); try { const file = path.join(dir, "clock.html"); await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null, ...(cardPics ?? {}) }), "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); const face = clockFace(clock.to, clock.zone); const size = await page.evaluate(mountClock, { css: clockCss({ height: box.height, palette: render.palette }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } }); await page.evaluate(() => document.fonts.ready.then(() => true)); const at = await clockPlaceOn(page, { follow, total, size, k }); if (!at) throw new Error(`${entry.id}: the clock has no card to sit on`); await page.evaluate(() => { const st = document.createElement("style"); st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-clock-layer]) { visibility: hidden !important; }"; document.head.appendChild(st); }); // The clip: the chip and its badge to its left. const left = Math.round(300 * k); const x = Math.max(0, at.x - left); const y = Math.max(0, at.y - Math.round(10 * k)); const clip = { x, y, width: Math.min(box.width - x, at.x + size.width + Math.round(16 * k) - x), height: Math.min(box.height - y, size.height + Math.round(20 * k)) }; const fdir = path.join(dir, "clock"); await rm(fdir, { recursive: true, force: true }); await mkdir(fdir, { recursive: true }); const shots = new Map(); const runs = []; for (const s of clockFrameTimes(clock, fps)) { const st = clockStateAt(clock, s); const key = JSON.stringify([st.time, st.date, st.gap, Math.round(st.gapOpacity * 50), Math.round(st.hourTurn * 2), Math.round(st.minuteTurn), st.running]); if (!shots.has(key)) { const f = path.join(fdir, `c-${String(shots.size).padStart(4, "0")}.png`); await page.evaluate(setClockState, { x: at.x, y: at.y, st }); await page.screenshot({ path: f, clip, omitBackground: true }); shots.set(key, f); } if (runs.length && runs[runs.length - 1].key === key) runs[runs.length - 1].n += 1; else runs.push({ key, n: 1 }); } const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; runs.forEach((r, i) => lines.push(`file ${q(shots.get(r.key))}`, ...concatRate(fps), `duration ${(r.n / fps).toFixed(6)}`)); lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); const list = path.join(fdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); return { list, x: clip.x, y: clip.y, at: { x: at.x, y: at.y }, place: at.place, covers: at.covers, shots: shots.size, box: { x: at.x - Math.round(240 * k), y: at.y, width: size.width + Math.round(240 * k), height: size.height } }; } finally { await ctx.close(); } } /** * A post item's word zooms, resolved for the build: `[{ i, scope, from, to, * scale, highlight, span }]`, each on its time (wordZoomTimes) -- refused in * the build's words when one has no time, or two are up at once. */ export function postZoomPlan(entry, render, total = Infinity, schedule = undefined) { const fx = Array.isArray(entry?.fx) ? entry.fx : []; if (!fx.some((f) => f?.kind === "word-zoom")) return []; const times = wordZoomTimes(entry, render, schedule); const bad = times.filter((t) => t.error); if (bad.length) throw new Error(bad.map((t) => t.error).join("; ")); // Its captions (post-caption.mjs) are timed and drawn apart: only the word zooms here. const zooms = fx.flatMap((f0, i) => (f0?.kind === "word-zoom" ? [[f0, i]] : [])).map(([f0, i]) => { const f = resolveWordZoom(f0); const m = findMatch(targetTextOf(entry, f.target), f.match, f.occurrence); return { i, scope: targetScope(f.target), from: m.from, to: m.to, scale: f.scale, highlight: f.highlight === false ? null : f.highlight, t: times[i].t, source: times[i].source, span: zoomSpan(f0, times[i].t) }; }); const late = zooms.find((z) => z.span.t0 >= total - 0.05); if (late) throw new Error(`${entry.id}: word zoom ${late.i + 1} ("${resolveWordZoom(fx[late.i]).match}") starts at ${late.span.t0} s, after the post's ${total} s (move its at)`); const clash = overlappingZooms(zooms.map((z) => z.span)); if (clash) throw new Error(`${entry.id}: word zooms ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at, or shorten its hold)`); return zooms; } /** * THE SEGMENT KEY's fields for a caption, the clock and the pace (appended to * the key, never restructuring it): `{}` for an item with none of them, so its * key is the one it had before they existed and its segment is reused. The * entry itself is in the key (its `fx` -- each caption's text, match, at, * hold, place; its clock fx's on/rewind -- its `narration.pace`, its id: a * repeated item is its own segment); what it does NOT carry is added here: * captionV / clockV the chip's and the clock's drawing (bumped when their look changes) * slam a slam's drawing version, its motion and its trailer hit (post-slam.mjs) * clock clockPlan -- this post's time, the time it runs from (the * item before's, when that one is a clock item), the mode * (forward / rewind / none, a forced rewind) and the zone * pace the gap knobs the pace resolved to (lead, tail, ramp, linger: * a cut-level pace changes them without touching the entry) */ export const POST_CAPTION_DRAW_V = 2; /** * The join's drawing (in a joined item's key only: an item with no join keeps its key). 2: the item before's card * dissolves into this one's (never gone at the first frame), its last frame shot whole (its clock, its parent's shot, * a visit's pointer), the carried post's head drawn as a plain card drew it, this item's clock moving from that one's. */ export const POST_JOIN_DRAW_V = 2; export const POST_CLOCK_DRAW_V = 1; /** * A SLAM's drawing and sound (post-slam.mjs): bumped when its look changes. Its * fields are in the entry (`fx`); the key adds this, the motion it is drawn on * and the trailer hit's tier and level it sounds (trailer-hits.mjs) -- so a * change to the shared generator rebuilds the items that play it. */ export const POST_SLAM_DRAW_V = 1; /** A slam WITH a bar draws at this version (and its key carries the bar's look): one without keeps POST_SLAM_DRAW_V. */ export const POST_SLAM_BAR_DRAW_V = 2; export function postFxKeyFields(entry, render, prev = null, { plan = null, layout = null } = {}) { const out = {}; const fx = Array.isArray(entry?.fx) ? entry.fx : []; if (fx.some((f) => f?.kind === "caption")) out.captionV = POST_CAPTION_DRAW_V; if (fx.some((f) => f?.kind === "slam")) { const barred = fx.some((f) => f?.kind === "slam" && typeof f.bar === "string"); out.slam = { v: barred ? POST_SLAM_BAR_DRAW_V : POST_SLAM_DRAW_V, motion: SLAM_MOTION, hit: TRAILER_HIT_TIERS.title, audio: TRAILER_AUDIO, ...(barred ? { bar: SLAM_BAR } : {}) }; } const clk = clockPlan(entry, render, prev); if (clk) Object.assign(out, { clockV: POST_CLOCK_DRAW_V, clock: clk }); // The progress bar (post-progress.mjs): its plan (the read's span, the parts' ticks, when it goes) and its drawing. const pp = plan ? progressPlan(entry, render, plan, { stack: layout?.mode === "stack" }) : null; if (pp) out.progress = { v: POST_PROGRESS_DRAW_V, ...pp }; const k = postNarrationKnobs(entry, render); if (isNarrated(entry) && k.pace && k.pace !== "normal") out.pace = { pace: k.pace, lead: k.lead, tail: k.tail, ramp: k.ramp, linger: k.linger }; return out; } /** * THE SEGMENT's CACHE KEY's fields, pure (a build whose key matches keeps the segment it has): the entry as drawn * (and as published), the box and framing, the palette and faces, the encode, every file's stamp, the avatars, the * narration and its mix, the plan's follow -- which carries the thread's tiles and their schedule, their relations, * the scene, a manual thread's stack, the branch map, the link visits and the join's seconds -- the slurs; and, only * when an item has them (an item none of them touch keeps the key it had before them): * * joinFrom the join (post-join.mjs): the item before as its segment draws it, its follow, its length, what its slot * ended on -- its card and box are drawn from these * panel the plan's context media shows (post-thread.mjs panelSchedule) * layout a wide attachment's top/bottom layout (postLayout's `panel`), and its boxes * rv a renderer salt (POST_SEGMENT_RV), only when it is set: bump it (a string) when a card draws * differently from an UNCHANGED plan, so a segment built before is rebuilt, never reused. Unset: every * thread-scenes change to what a card draws rides on its plan (its follow: the tiles' relations, the * scene, the map, the visits, the join) or on the fields above -- checked over the whole of mid-6 * (post-render-key.test.mjs; an item with an unchanged key draws the same page as main's) */ export function postSegmentKeyOf({ entry, redaction = null, box, place = [], render, encode = [], stamps = [], avatars = {}, take = null, plan, bleeps = null, layout = null, from = null, prev = null }) { return { v: 1, entry, // A redaction that changes what the card draws changes the key; none leaves it as it was. ...(redactionOn(redaction) ? { published: redactEntry(entry, redaction), blank: termsFor(entry, redaction) } : {}), box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}), ...(plan.follow ? { follow: plan.follow } : {}), ...(bleeps ? { bleeps } : {}), ...(slursOn(redaction?.slurs) ? { slurs: redaction.slurs } : {}), // `jv`: the join's drawing (POST_JOIN_DRAW_V) and what the item before showed as it ended beyond its card -- its // clock (where this one's starts) and its parent's shot. ...(from ? { joinFrom: { entry: from.entry, follow: from.plan.follow ?? null, total: from.plan.total, media: from.media.map((x) => [x.m.src, x.t, x.box]), fadeIn: from.fadeIn, jv: POST_JOIN_DRAW_V, clock: from.clock ?? null, ...(from.carry ? { carry: from.carry } : {}), ...(Number.isFinite(from.anchorY) ? { anchorY: from.anchorY } : {}) } } : {}), ...(plan.panel ? { panel: plan.panel } : {}), // PICTURE-ONLY posts (post-picture.mjs): the pictures drawn in their cards -- only an item that has one. ...(plan.pics ? { pics: { v: POST_PICTURE_DRAW_V, list: plan.pics } } : {}), // Its own attachment entering with his own post (post-item.mjs ownMediaEnterAt): only an item that reads // something before its post carries it -- every other keeps its key. ...(plan.enter > 0 ? { enter: { at: plan.enter, fade: POST_ENTER_FADE } } : {}), ...(layout?.panel === "top" || layout?.panel === "bottom" ? { layout: { panel: layout.panel, card: layout.card, slot: layout.slot } } : {}), // A caption, the clock, the pace (post-caption.mjs, post-clock.mjs): nothing for an item with none of them. ...postFxKeyFields(entry, render, prev, { plan, layout }), // ITS SCREENS (post-screens.mjs): their drawing's version -- only an item that carries screens. ...(hasScreens(entry) ? { screens: POST_SCREEN_DRAW_V } : {}), ...(POST_SEGMENT_RV ? { rv: POST_SEGMENT_RV } : {}), }; } /** The renderer's salt (postSegmentKeyOf `rv`): null keeps every key as it was; a string rebuilds every post segment. */ export const POST_SEGMENT_RV = null; /** The key of postSegmentKeyOf's fields. */ export const postSegmentKey = (fields) => createHash("sha256").update(JSON.stringify(fields)).digest("hex"); /** * Build post item `entry`'s segment. `ctx`: `{ render, outDir, manifestDir, * box, place, encode, exec, ffmpeg, emit, avatars }` -- the box it fills (the * deck's footage box, or the frame), the deck's framing after it, * build-video's encode args and ffmpeg runner, the authors' pictures * (`{ : 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), `prev` the timeline entry * before it (post-thread.mjs carries a parent that is it), `scene` the posts * its conversation's run left on screen (post-conversation.mjs planContext), * and `mediaScene` its media scene (post-media-scene.mjs mediaSceneOf: the * attachment the anchor's, the scene's earlier messages above its card -- not * drawn when `scene` is). Returns the segment's path. */ export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", ffprobe = "ffprobe", emit = () => {}, avatars = {}, redaction = null, prev = null, scene = null, mediaScene = null, join = null, joinFrom = 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 WIDE attachment at full width above (or below) the card: the cut's rule laid on (post-item.mjs panelEntry). entry = panelEntry(entry, render); // 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); `scene`: what // its run left on screen (post-conversation.mjs) -- in plan.follow, so in the segment's key; a media scene too. const plan = postItemPlan(entry, render, { prev, scene, mediaScene, join }); const layout = postLayout(entry, box); // THE JOIN (post-join.mjs): the item before as ITS segment draws it (its markup, its media scene, the cut's panel // rule), its plan -- what this item opens on. `joinFrom`: its entry and its context (planContext's, mediaSceneOf's). let from = null; if (plan.follow?.join && joinFrom?.entry?.type === "post") { let pe = censorEntry(joinFrom.entry, redaction); pe = panelEntry(sceneEntry(pe, joinFrom.mediaScene ?? null, { censor: (e) => censorEntry(e, redaction) }), render); const pp = postItemPlan(pe, render, { prev: joinFrom.prev ?? null, scene: joinFrom.scene ?? null, mediaScene: joinFrom.scene ? null : joinFrom.mediaScene ?? null, join: joinFrom.join ?? null }); const pl = postLayout(pe, box); const ends = pl.slot && pl.mode === "side" ? endMediaOf(pp, { stepAt, mediaTimeAt, fps: render.fps ?? 30 }) : []; const boxesOf = (list) => (list.length ? stepBoxes({ items: list.map((x, j) => ({ ...x.m, i: j })) }, pl.slot) : []); const eb = boxesOf(ends); const firstOwn = plan.steps[0]?.items?.[0] ?? null; const ownBox = firstOwn && layout.slot && layout.mode === "side" ? stepBoxes(plan.steps[0], layout.slot)[0] : null; // The same attachment in the same box (a media scene): held, neither faded. const held = !!firstOwn && ends.length === 1 && ends[0].m.src === firstOwn.src && !!ownBox && Math.abs(ownBox.x - eb[0].x) < 2 && Math.abs(ownBox.y - eb[0].y) < 2 && Math.abs(ownBox.width - eb[0].width) < 2; // How ITS segment drew the post it carried in (its own join: post-item.mjs joinCarryOf of the item before it) -- // its page here drawn as it was, never with a carried post of another size (a re-wrapped tile at the first frame). let carry = null; const bf = joinFrom.join ? joinFrom.before : null; if (bf?.entry?.type === "post") { const be = panelEntry(sceneEntry(censorEntry(bf.entry, redaction), bf.mediaScene ?? null, { censor: (e) => censorEntry(e, redaction) }), render); carry = joinCarryOf(be, postItemPlan(be, render, { prev: bf.prev ?? null, scene: bf.scene ?? null, mediaScene: bf.scene ? null : bf.mediaScene ?? null, join: bf.join ?? null }), box, render); } // Where ITS read opened (its own join's anchor, in its record): its last frame is drawn from the same path. const prevRec = joinFrom.join ? await readFile(postRecordPath(path.join(outDir, "segments", `${joinFrom.entry.id}.mp4`)), "utf8").then((t) => JSON.parse(t), () => null) : null; from = { entry: pe, plan: pp, carry, anchorY: Number.isFinite(prevRec?.joinAnchor) ? prevRec.joinAnchor : null, // Its clock (post-clock.mjs) as its own segment runs it: from the clock item before IT. clock: clockPlan(pe, render, joinFrom.prev ?? null), media: held ? [] : ends.map((x, j) => ({ file: path.resolve(manifestDir, x.m.src), m: x.m, t: x.t, box: eb[j] })), // Entering with his own post (plan.enter): not faded in over the join -- the item before's goes, the slot waits. fadeIn: !held && !!firstOwn && !(plan.enter > 0), }; } const files = (entry.media ?? []).map((m) => path.resolve(manifestDir, m.src)); for (const [i, f] of files.entries()) { if (!(await stat(f).catch(() => null))) throw new Error(`${entry.id}: media[${i}] is not on disk: ${f} (src: ${entry.media[i].src})`); } // A context post's attachments (post-thread.mjs panelSchedule): files of the project, as the item's own are. const panelFiles = (plan.panel?.shows ?? []).map((sh) => sh.media.map((m) => path.resolve(manifestDir, m.src))); for (const [i, f] of panelFiles.flat().entries()) { if (!(await stat(f).catch(() => null))) throw new Error(`${entry.id}: a context post's attachment is not on disk: ${f} (${i})`); } // A picture-only post the run left on screen (a scene tile, post-item.mjs picturesOf `post`): its own attachment // censored by its channel's markup, as its own item's is. if (plan.pics) plan.pics = plan.pics.map((p) => (p.post ? { ...p, media: censorEntry({ post: p.post, media: p.media }, redaction).media } : p)); // PICTURE-ONLY posts' pictures (post-picture.mjs, plan.pics): files of the project, drawn in their cards. const picFiles = [...new Set([...(plan.pics ?? []), ...(from?.plan?.pics ?? [])].flatMap((p) => p.media.map((m) => path.resolve(manifestDir, m.src))))]; for (const f of picFiles) { if (!(await stat(f).catch(() => null))) throw new Error(`${entry.id}: a picture-only post's attachment is not on disk: ${f}`); } const wordFiles = (entry.media ?? []).map((m) => (typeof m.words === "string" ? path.resolve(manifestDir, m.words) : null)); // Its narration's picked take (post-narration.mjs): a file of the project, levelled by its measured loudness. const take = isNarrated(entry) ? pickedTake(entry) : null; const takeFile = take ? path.resolve(manifestDir, take.file) : null; if (takeFile && !(await stat(takeFile).catch(() => null))) throw new Error(`${entry.id}: its narration take is not on disk: ${takeFile} (${take.file})`); // The slurs its take SAYS, covered (post-slurs.mjs): a public render never plays one -- without word timings it is refused. const bleeps = take ? takeSlurBleeps(entry, take, redaction) : null; const stamps = await Promise.all([...files, ...panelFiles.flat(), ...picFiles.filter((f) => !files.includes(f)), ...(from?.media ?? []).map((x) => x.file), ...wordFiles.filter(Boolean), ...Object.values(avatars), ...(takeFile ? [takeFile] : []), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : []), ...(typeof from?.entry?.parentShot === "string" ? [path.resolve(manifestDir, from.entry.parentShot)] : [])].map(async (f) => { const st = await stat(f).catch(() => null); return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`; })); const key = postSegmentKey(postSegmentKeyOf({ entry, redaction, box, place, render, encode, stamps, avatars, take, plan, bleeps, layout, from, prev })); const record = postRecordPath(seg); const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null); // The render pool (render-pool.mjs): this item, by this key, built by any take of any project. const pool = await poolFor(outDir); // A segment encoded FULL range (before the pin, color-range.mjs) is rebuilt though its key matches: its page is a // shade off every other item's in the master. Only those -- the key is not bumped, so no other segment moves. const fullRange = async (f) => { const yes = await isFullRange(f, { exec, ffprobe }); if (yes) emit("note", { message: `${entry.id}: its segment is full range (yuvj420p) — rebuilt in limited range, as every other segment is` }); return yes; }; if (had?.key === key && (await stat(seg).catch(() => null)) && !(await fullRange(seg))) { emit("note", { message: `${entry.id}: post item unchanged — its segment kept` }); // (One the pool has not got -- built before it, or linked in by --from -- is filed now: the item as // post-render made it, which a combo badge's pass keeps beside it as `.plain.mp4`.) if (pool) { const badged = await stat(seg.replace(/\.mp4$/, ".combo.json")).catch(() => null); const plain = seg.replace(/\.mp4$/, ".plain.mp4"); const made = !badged ? seg : (await stat(plain).catch(() => null)) ? plain : null; if (made) await poolPut(pool, "post", key, { "seg.mp4": made, "post.json": record }); } return seg; } if (pool && (await poolFetch(pool, "post", key, { "seg.mp4": seg, "post.json": record })) && !(await fullRange(seg))) { emit("note", { message: `${entry.id}: post item from the render pool (key ${key.slice(0, 12)})` }); return seg; } const cardDir = path.join(outDir, "cards", `post-${entry.id}`); const zoomPlan = postZoomPlan(entry, render, plan.total, plan.narration); // Its captions (post-caption.mjs): each waits for a zoom it would be up with, and is gone by the media phase (a stack card). // Its slams (post-slam.mjs): never up with a zoom; gone by the media phase (a stack card), as a caption is. const fxEnd = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total; const slPlan = slamPlan(entry, render, { zooms: zoomPlan.map((z) => ({ ...z.span, i: z.i })), end: fxEnd, schedule: plan.narration ?? undefined }); // A caption up with a slam WAITS for it to be gone (the slam first, then the chip), as it waits for a zoom. const capPlan = captionPlan(entry, render, { zooms: [...zoomPlan.map((z) => ({ ...z.span, i: z.i })), ...slPlan.map((p) => ({ t0: p.span.t0, t3: p.span.t3, i: p.i }))], end: fxEnd, schedule: plan.narration ?? undefined }); // Its clock (post-clock.mjs): the post's own time, run from the clock item before it. const clk = clockPlan(entry, render, prev); // Its progress bar (post-progress.mjs): the read's span on the item's clock (a long read's, auto). const prog = progressPlan(entry, render, plan, { stack: layout.mode === "stack" }); // PICTURE-ONLY posts (post-picture.mjs): the page draws each picture in its card -- an image itself, a GIF's or a // video's middle frame (its still; the encode plays it over that place while the card is still). // The item before's too, when this one opens on it (the join's page draws it as it ended). let cardPics = null; const drawnPics = [...(plan.pics ?? []), ...(from?.plan?.pics ?? [])]; if (drawnPics.length) { await mkdir(cardDir, { recursive: true }); const posters = {}; for (const [pi, pc] of drawnPics.entries()) { const m = pc.media[0]; if ((m?.kind !== "gif" && m?.kind !== "video") || posters[m.src]) continue; const still = path.join(cardDir, `pic-${pi}.png`); // Its still is the frame at the middle of its span: a clip's first frame is often empty (a green screen before // the man walks in) -- and this is what a context post shows once its beat is over. const start = Number.isFinite(m.start) && m.start > 0 ? m.start : 0; const end = Number.isFinite(m.end) && m.end > start ? m.end : Number.isFinite(m.seconds) && m.seconds > start ? m.seconds : start; const from = Math.round((start + (end - start) / 2) * 1000) / 1000; try { await exec(ffmpeg, ["-nostdin", "-v", "error", "-y", "-ss", String(from), "-i", path.resolve(manifestDir, m.src), "-frames:v", "1", still], { maxBuffer: 1 << 24 }); posters[m.src] = pathToFileURL(still).href; } catch (err) { throw new Error(`${entry.id}: the still of a picture-only post's ${m.kind} could not be made (${m.src}): ${String(err?.stderr ?? err?.message ?? err).trim()}`); } } cardPics = { mediaUrl: (src) => pathToFileURL(path.resolve(manifestDir, src)).href, posters }; } // ITS SCREENS AS DRAWN (post-screens.mjs, after the redaction and anonymity passes): an excerpt no longer in its line // is never drawn whole -- the segment is refused, naming the line. const screenErr = hasScreens(entry) ? screenDrawErrors(redactEntry(entry, redaction)) : []; if (screenErr.length) throw new Error(`${entry.id}: a screen cannot be drawn as chosen:\n ${screenErr.join("\n ")}`); const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, pics: plan.pics ?? [], cardPics, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [], slams: slPlan, progress: prog }); // NO HIDDEN TEXT IS EVER NARRATED (operator, 4 Nov): a part whose words are not in view, whole and lit, while it // is said -- or a context post drawn over its context size -- refuses the build (READ_IN_VIEW=warn: a note). // A part read off a linked post's picture is on screen only while the panel shows it (post-thread.mjs panelReadErrors). const panelErr = panelReadErrors(plan.follow, plan.panel, { id: entry.id }); if (panelErr.length) cards.inView = [...(cards.inView ?? []), ...panelErr]; if (cards.inView?.length) { const msg = `${entry.id}: the read is not on screen while it is said (read-follow.mjs readInViewErrors):\n ${cards.inView.join("\n ")}`; if (process.env.READ_IN_VIEW === "warn") emit("note", { message: `warning: ${msg}` }); else throw new Error(`${msg}\n(READ_IN_VIEW=warn builds it anyway)`); } const zooms = (cards.zooms ?? []).map((z) => ({ ...z, target: zoomTarget(z.region, { ...z.word }, z.span.scale) })); // Its video attachments' words, when transcribed: one textfile per cue. const captions = []; for (const [si, step] of plan.steps.entries()) { if (step.kind !== "video") continue; const m = step.items[0]; const wf = wordFiles[m.i]; if (!wf) continue; for (const [ci, c0] of stepCaptions(step, await readMediaCues(wf)).entries()) { // A redacted term is left out of the burnt-in words, as it is left out of a read; a slur masked (post-slurs.mjs). const c = { ...c0, text: shownLine(c0.text, entry, redaction) }; if (!c.text.trim()) continue; const textfile = path.join(cardDir, `cue-${si}-${ci}.txt`); await writeFile(textfile, c.text, "utf8"); captions.push({ ...c, textfile }); } } const tmp = seg.replace(/\.mp4$/, ".post-tmp.mp4"); let narration = null; if (take) { const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg }); narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs, ...(bleeps ? { bleeps } : {}) }; } const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null, panelFiles, map: cards.map ?? null, join: from && cards.joinFrom ? { seconds: plan.follow.join.seconds, fadeIn: from.fadeIn, from: from.media } : null, captionFx: cards.captions ?? [], clock: cards.clock ? { ...cards.clock, until: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total } : null, slams: cards.slams ?? [], slamHitList: (cards.slams ?? []).flatMap((sl) => slamHits(sl.fx, sl.span).map((h) => ({ ...h, gain: h.gain * sl.fx.volume }))), progress: cards.progress ?? null, pics: (cards.pics ?? []).map((pc) => ({ ...pc, file: path.resolve(manifestDir, pc.m.src), soundAt: (plan.pics ?? []).find((p) => p.scope === pc.scope)?.sound?.t0 ?? null })), picSounds: (plan.pics ?? []).filter((p) => p.sound && p.media[0]).map((p) => ({ m: p.media[0], file: path.resolve(manifestDir, p.media[0].src), t0: p.sound.t0, t1: Math.min(plan.total, p.sound.t1) })) }); try { await exec(ffmpeg, argv, { maxBuffer: 1 << 24 }); } catch (err) { const detail = String(err?.stderr ?? "").trim() || err?.message || String(err); throw new Error(`${entry.id}: ffmpeg failed on the post item\n${detail}`); } await rename(tmp, seg); // The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides). if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true }); // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. await writeFileAtomic(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, ...(sl.layout.bar ? { bar: { text: sl.fx.bar, style: sl.fx.barStyle, x: sl.layout.bar.x, y: sl.layout.bar.y, width: sl.layout.bar.width, height: sl.layout.bar.height } } : {}), size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}), ...(Number.isFinite(cards.joinAnchor) ? { joinAnchor: cards.joinAnchor } : {}) }, null, 2) + "\n", "utf8"); if (pool) await poolPut(pool, "post", key, { "seg.mp4": seg, "post.json": record }); emit("note", { message: narration ? `${entry.id}: post item ${plan.total.toFixed(1)} s, narrated (${take.file}: ${plan.narration.seconds.toFixed(1)} s from ${plan.narration.at} s, muffled to ${plan.narration.voiceEnd.toFixed(1)} s)` : `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})`, }); for (const pc of plan.pics ?? []) { const shown = (cards.pics ?? []).filter((x) => x.scope === pc.scope); emit("note", { message: `${entry.id}: picture-only ${pc.scope === "post" ? "post" : pc.scope} -- its ${pc.media[0]?.kind ?? "picture"} drawn in its card${shown.length ? `, played ${shown.map((x) => `${x.t0}–${x.t1} s`).join(", ")}` : ""}${(plan.follow?.beats ?? []).filter((b) => b.scope === pc.scope).map((b) => `, its beat ${b.t0}–${b.t1} s before the read`).join("")}` }); } if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` }); if (cards.progress) emit("note", { message: `${entry.id}: progress bar over the read ${prog.from}–${prog.to} s (${prog.mode}${prog.ticks.length ? `, ${prog.ticks.length + 1} parts ticked` : ""}), ${cards.progress.place === "foot" ? "along the card's foot" : "under the card"}${cards.progress.covers ? ` -- WARNING: over ${cards.progress.covers} word(s)` : ""}` }); if (cards.clock) emit("note", { message: `${entry.id}: clock ${clockFace(clk.to, clk.zone).time} ${clockFace(clk.to, clk.zone).date} (${clk.mode === "none" ? "shown" : clk.mode === "rewind" ? "rewound" : "run forward"}${clk.mode === "none" ? "" : ` from the item before, ${clk.gap / 60000 | 0} min`}), ${cards.clock.place}${cards.clock.covers ? ` -- WARNING: over ${cards.clock.covers} word(s)` : ""}` }); for (const c of cards.captions ?? []) emit("note", { message: `${entry.id}: caption ${c.i + 1} "${c.text}" at ${c.t.toFixed(2)} s (${c.source === "at" ? "set by hand" : c.source === "words" ? "from the take's words" : "the reading estimate"}${c.span.waited !== null ? `, after ${entry.fx?.[c.span.waited]?.kind === "slam" ? "slam" : "word zoom"} ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.rel} the phrase ${c.placed.place === "card" ? "on the card" : "off the card"}${c.placed.leader ? ", a leader to it" : ""}${c.cutByPan ? ` (gone at ${c.cutByPan} s, before the card pans its phrase)` : ""}${c.placed.covers ? ` -- WARNING: no free space in the frame, it covers ${c.placed.covers} thing(s) drawn (shorten its text)` : ""}` }); for (const sl of cards.slams ?? []) emit("note", { message: `${entry.id}: slam ${sl.i + 1} "${sl.fx.text}" -- ${sl.landings.length} hit(s) at ${sl.landings.map((x) => x.toFixed(2)).join(", ")} s (${sl.source === "words" ? "spread over the words' spoken span" : sl.source === "at" ? "from its at" : "the reading estimate"}), up ${sl.span.t0}–${sl.span.t3} s, ${sl.layout.where} the words${sl.layout.covers ? `, over ${sl.layout.covers} other thing(s) drawn for its window (the gag)` : ""}${sl.fx.sfx === "off" ? ", silent" : ""}` }); for (const z of zooms) emit("note", { message: `${entry.id}: word zoom ${z.i + 1} at ${z.t.toFixed(2)} s (${z.source === "at" ? "set by hand" : "from the take's words"}), ${z.span.scale}× over ${z.span.t0}–${z.span.t3} s` }); return seg; } /** * The slurs post item `entry`'s take says that the cut masks, as its bleeps * (`{ mode, spans, seconds }`, post-slurs.mjs takeBleeps), or null. Its * audio's state is its own `slurs`, else its source take's (a derived take * reads what its source read). Throws, in the build's words, when the take * says one it has no word timings to find. */ export function takeSlurBleeps(entry, take, redaction) { const takes = Array.isArray(entry?.narration?.takes) ? entry.narration.takes : []; const root = rootTakeOf(takes, take); // The script it read: its own, else the post's (a take from before takes kept theirs). const b = takeBleeps(take, redaction?.slurs, { state: take.slurs ?? root?.slurs ?? null, script: typeof take.script === "string" ? take.script : String(entry?.narration?.script ?? "") }); if (b?.error) { throw new Error( `${entry.id}: ${b.error} -- a published cut never plays a slur: time its words (umtool posts narrate

${entry.id} --words), ` + `synthesize a take without it (umtool posts narrate

${entry.id} --take; the filter's voice skip or placeholder), or render the uncensored cut (--uncensored)`, ); } return b ? { ...b, seconds: take.seconds } : null; } /** A sound's integrated loudness (EBU R128, LUFS) by ffmpeg's ebur128 through `exec`; null when silent or unread. */ export async function measureLufsOf(file, { exec, ffmpeg = "ffmpeg" }) { try { const r = await exec(ffmpeg, ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-af", "ebur128=framelog=quiet", "-f", "null", "-"], { maxBuffer: 1 << 24 }); const all = [...String(r?.stderr ?? "").matchAll(/\bI:\s+(-?[\d.]+|-inf)\s+LUFS/g)]; const v = all.length ? Number(all.at(-1)[1]) : NaN; return Number.isFinite(v) && v > -70 ? v : null; } catch { return null; } }