// A VERTICAL SHORT'S LAST STEPS (lane vertical): the pieces joined and brought // to the short's loudness (assembleShort), and R -- the REFRAME -- a short // recomposed from a finished take's 16:9 master, nothing cut again // (reframeTake). // // R lays each item's regions of the master into 9:16 over a blurred, // darkened enlargement of them: // a clip its footage box (the take's cut record, `framing.box`) at full // width in the middle, the schedule's title and subtitle (the // deck's date and source line) above it // a post its card's box over its attachment's box (post-item.mjs // postLayout on the footage box), stacked and fitted inside the // safe area; a post with no attachment, its card alone // Its text comes from the take's own schedule: nothing is written that the // cut does not say. import { execFile } from "node:child_process"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { postLayout } from "./post-item.mjs"; import { VERTICAL_HEIGHT, VERTICAL_WIDTH, safeArea, verticalKnobs } from "./vertical.mjs"; import { assColour, assTime, captionText } from "./look.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = process.env.FFMPEG ?? "ffmpeg"; const FFPROBE = process.env.FFPROBE ?? "ffprobe"; const even = (n) => Math.max(2, 2 * Math.round(n / 2)); const f3 = (n) => Number(n).toFixed(3); const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); /** The short's encode: the take's settings, at 1080x1920. */ export const shortEncode = (render) => [ "-c:v", "libx264", "-preset", render?.preset ?? "medium", "-crf", String(render?.crf ?? 20), "-pix_fmt", "yuv420p", "-r", String(render?.fps ?? 30), "-c:a", "aac", "-b:a", render?.audioBitrate ?? "160k", "-ar", String(render?.audioRate ?? 48000), "-ac", String(render?.audioChannels ?? 2), "-movflags", "+faststart", ]; /** A file's length (s). */ export async function probeSeconds(file) { const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", file]); return Number(stdout.trim()); } /** The heavy slot (heavy-gate.mjs) around an encode, with a small declared estimate. */ async function inSlot(cmd, fn) { const { withRenderSlot } = await import("./heavy-gate.mjs"); return withRenderSlot(cmd, fn, { estimateMb: 1500 }); } /** The loudnorm filter's two passes: measured, then applied linearly at `target` LUFS. Returns the measure. */ export async function normalizeLoudness(input, output, target, { log = () => {} } = {}) { const spec = `I=${target}:TP=-1.5:LRA=11`; const { stderr } = await execFileP(FFMPEG, ["-nostdin", "-hide_banner", "-i", input, "-af", `loudnorm=${spec}:print_format=json`, "-f", "null", "-"], { maxBuffer: 1 << 26 }); const m = JSON.parse(stderr.slice(stderr.lastIndexOf("{"), stderr.lastIndexOf("}") + 1)); const tmp = tmpPathFor(output, { ext: ".mp4" }); await execFileP(FFMPEG, [ "-nostdin", "-v", "error", "-y", "-i", input, "-c:v", "copy", "-af", `loudnorm=${spec}:measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}:linear=true`, "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-movflags", "+faststart", tmp, ], { maxBuffer: 1 << 24 }); await rename(tmp, output); log(`loudness: ${Number(m.input_i).toFixed(1)} LUFS measured, brought to ${target}`); return { target, measured: Number(m.input_i) }; } /** * The pieces joined into the short: the build's own joined file when every * piece plays whole, else each segment's part cut and joined; then the * short's loudness. `{seconds, loudness}`. */ /** * Where each piece is cut from a stacked deck's BUILT cut (the build's schedule), or null when a piece is not in it. * A segment overlaps its neighbours by the crossfade (deck.mjs scheduleFrom), so a piece keeps out of them -- the * dissolve in, after its start + D, and the one out, before its end − D -- or every dissolve would play twice once * the pieces are joined; and its `to` never runs past its own segment. Pure. * * @param {Array<{ id: string, from: number, to: number | null }>} pieces * @param {{ segments?: Array<{ id: string, start: number, duration: number }>, transition?: number } | null} schedule * @returns {Array<{ from: number, to: number }> | null} */ export function builtSpans(pieces, schedule) { const segs = Array.isArray(schedule?.segments) ? schedule.segments : []; const index = new Map(segs.map((s, i) => [s.id, i])); if (!segs.length || !pieces.every((p) => index.has(p.id))) return null; const D = Math.max(0, Number(schedule.transition) || 0); return pieces.map((p) => { const i = index.get(p.id); const s = segs[i]; const start = Number(s.start); const dur = Number(s.duration); const lo = i > 0 ? D : 0; const hi = i < segs.length - 1 ? dur - D : dur; const from = Math.min(Math.max(lo, Number(p.from) || 0), hi); const to = Math.max(from, Math.min(hi, p.to === null || p.to === undefined ? hi : Number(p.to))); return { from: Math.round((start + from) * 1000) / 1000, to: Math.round((start + to) * 1000) / 1000 }; }); } export async function assembleShort({ pieces, segmentsDir, built, outFile, render, schedule = null, log = () => {} }) { const target = verticalKnobs(render).loudness; // A hard join (a cold open into its clip: vertical-plan.mjs) is cut from the segments, never the build's crossfade. const whole = pieces.every((p) => !p.from && p.to === null && !p.hard); let src = built; if (!whole) { src = `${outFile}.joined-${process.pid}.mp4`; const inputs = []; const parts = []; // THE STACKED VERTICAL DECK (vertical-deck.mjs): its segments are the picture alone -- the deck is laid over the // built cut -- so a piece is cut from the built cut at its segment's place (the build's schedule), deck and all. const span = builtSpans(pieces, schedule); pieces.forEach((p, i) => { const b = span ? span[i] : null; const a0 = b ? b.from : p.from; const end = b ? b.to : p.to; inputs.push("-i", b ? built : path.join(segmentsDir, `${p.id}.mp4`)); const trim = end === null ? `trim=start=${f3(a0)}` : `trim=start=${f3(a0)}:end=${f3(end)}`; const atrim = end === null ? `atrim=start=${f3(a0)}` : `atrim=start=${f3(a0)}:end=${f3(end)}`; parts.push(`[${i}:v]${trim},setpts=PTS-STARTPTS,fps=${render?.fps ?? 30},format=yuv420p,setsar=1[v${i}]`, `[${i}:a]${atrim},asetpts=PTS-STARTPTS,afade=t=in:d=0.08,areverse,afade=t=in:d=0.12,areverse[a${i}]`); }); parts.push(`${pieces.map((_, i) => `[v${i}][a${i}]`).join("")}concat=n=${pieces.length}:v=1:a=1[v][a]`); log(`vertical: joining ${pieces.length} piece(s)`); await inSlot(["umtool", "vertical", "join"], () => execFileP(FFMPEG, ["-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", parts.join(";"), "-map", "[v]", "-map", "[a]", ...shortEncode(render), src], { maxBuffer: 1 << 24 })); } await mkdir(path.dirname(outFile), { recursive: true }); const loudness = await normalizeLoudness(src, outFile, target, { log }); if (!whole) await rm(src, { force: true }); await rm(built, { force: true }); return { seconds: await probeSeconds(outFile), loudness }; } // --------------------------------------------------------------------------- // R: the reframe. // --------------------------------------------------------------------------- /** * The master spans a short covers, in order: `{id, type, a, b, seg}` -- from * clip beats (their source seconds through the cut record), master beats, or * whole items. Pure. */ export function masterSpans({ beats = null, items = null, schedule, cuts = new Map() }) { const segs = Array.isArray(schedule?.segments) ? schedule.segments : []; const byId = new Map(segs.map((s) => [s.id, s])); const out = []; if (items?.length) { for (const id of items) { const s = byId.get(id); if (s) out.push({ id, type: s.type, a: s.start, b: s.end, seg: s }); } return out; } for (const bt of beats ?? []) { if (bt.kind === "clip") { const s = byId.get(bt.id); const c = cuts.get(bt.id); if (!s || !c) continue; const a = s.start + Math.max(0, bt.start - c.start); const b = Math.min(s.end, s.start + (bt.end - c.start)); if (b - a > 0.2) out.push({ id: bt.id, type: "clip", a, b, seg: s }); continue; } const A = bt.at; const B = bt.at + bt.dur; for (const s of segs) { if (!(s.end > A + 0.05 && s.start < B - 0.05)) continue; out.push({ id: s.id, type: s.type, a: Math.max(A, s.start), b: Math.min(B, s.end), seg: s }); } } return out; } /** * One span's 9:16 recomposition as a filtergraph on the master `[0:v]` * (already cut to the span): its regions, fitted and stacked in the safe * area, over a blurred enlargement. `regions` in master px; `text` the ASS * file of its title/subtitle (or null). */ export function reframeGraph({ regions, W = VERTICAL_WIDTH, H = VERTICAL_HEIGHT, safe, fps = 30, ass = null, fontsDir = null }) { const gap = 24; const top = safe.y0 + 150; const avail = safe.y1 - top; const maxW = W - 2 * 40; // One scale for the stack: as wide as the frame allows, as tall as the safe area allows. const sumH = regions.reduce((n, r) => n + r.h, 0) + gap * (regions.length - 1); const s = Math.min(maxW / Math.max(...regions.map((r) => r.w)), (avail - gap * (regions.length - 1)) / Math.max(1, sumH - gap * (regions.length - 1))); const sized = regions.map((r) => ({ ...r, sw: even(r.w * s), sh: even(r.h * s) })); const total = sized.reduce((n, r) => n + r.sh, 0) + gap * (sized.length - 1); let y = Math.round(top + (avail - total) / 2); const big = regions.reduce((a, r) => (r.w * r.h > a.w * a.h ? r : a), regions[0]); const parts = [`[0:v]split=${regions.length + 1}[rbg]${regions.map((_, i) => `[r${i}]`).join("")}`]; parts.push(`[rbg]crop=${big.w}:${big.h}:${big.x}:${big.y},scale=${W}:${H}:force_original_aspect_ratio=increase,crop=${W}:${H},gblur=sigma=40:steps=2,eq=brightness=-0.3:saturation=0.7,setsar=1[b0]`); sized.forEach((r, i) => { parts.push(`[r${i}]crop=${r.w}:${r.h}:${r.x}:${r.y},scale=${r.sw}:${r.sh}:flags=lanczos,setsar=1[c${i}]`); parts.push(`[b${i}][c${i}]overlay=x=${Math.round((W - r.sw) / 2)}:y=${y}[b${i + 1}]`); y += r.sh + gap; }); const last = `[b${sized.length}]`; parts.push(ass ? `${last}ass=filename='${ass}'${fontsDir ? `:fontsdir='${fontsDir}'` : ""},fps=${fps},format=yuv420p[v]` : `${last}fps=${fps},format=yuv420p[v]`); return parts.join(";"); } /** The ASS of a reframed span's title and subtitle (the schedule's), top of the safe area. */ export function reframeAss({ title = "", subtitle = "", seconds, W = VERTICAL_WIDTH, H = VERTICAL_HEIGHT, safe, font = "IBM Plex Sans" }) { const st = (name, fs, colour, mv, bold) => `Style: ${name},${[font, fs, assColour(colour), assColour(colour), assColour("#000000"), assColour("#000000", 0x80), bold, 0, 0, 0, 100, 100, 0, 0, 1, 3, 1, 7, safe.x0, W - safe.x1, mv, 1].join(",")}`; const end = assTime(seconds); return [ "[Script Info]", "ScriptType: v4.00+", `PlayResX: ${W}`, `PlayResY: ${H}`, "WrapStyle: 0", "ScaledBorderAndShadow: yes", "", "[V4+ Styles]", "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding", st("title", 58, "#F6F1E6", safe.y0 + 8, -1), st("sub", 36, "#D9D2C3", safe.y0 + 84, 0), "", "[Events]", "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text", ...(title ? [`Dialogue: 0,0:00:00.00,${end},title,,0,0,0,,${captionText(title)}`] : []), ...(subtitle ? [`Dialogue: 0,0:00:00.00,${end},sub,,0,0,0,,${captionText(subtitle)}`] : []), "", ].join("\n"); } /** A span's regions in master px: a clip's box; a post's card over its attachments (postLayout on the box). */ export function spanRegions({ type, box, entry = null }) { if (!box) return null; if (type !== "post" || !entry) return [{ x: box.x, y: box.y, w: even(box.width), h: even(box.height) }]; const L = postLayout(entry, { width: box.width, height: box.height }); const rect = (r) => ({ x: Math.round(box.x + r.x), y: Math.round(box.y + r.y), w: even(r.width), h: even(r.height) }); const out = []; if (L.card) out.push(rect(L.card)); if (L.slot && L.mode !== "text") out.push(rect(L.slot)); return out.length ? out : [{ x: box.x, y: box.y, w: even(box.width), h: even(box.height) }]; } /** * R over a take: each span of its master recomposed 9:16, joined, brought to * the short's loudness. `{seconds, loudness}`. */ export async function reframeTake({ takeDir, outDir, slug, beats = null, items = null, render, outFile, log = () => {} }) { const sourced = path.join(outDir, "sourced"); const schedule = await readJson(path.join(sourced, "schedule.json")); if (!schedule) throw new Error(`${path.basename(takeDir)} has no out/sourced/schedule.json: render the take first`); const manifest = await readJson(path.join(takeDir, "video.manifest.json")); const byId = new Map((manifest?.timeline ?? []).map((e) => [e.id, e])); const cuts = new Map(); for (const s of schedule.segments ?? []) { const c = await readJson(path.join(sourced, "segments", `${s.id}.cut.json`)); if (c) cuts.set(s.id, c); } const spans = masterSpans({ beats, items, schedule, cuts }); if (!spans.length) throw new Error("nothing of the master is under the beats"); const master = path.join(outDir, `${slug}.mp4`); const work = path.join(outDir, `reframe-${process.pid}`); await mkdir(work, { recursive: true }); const safe = safeArea(render); const fps = render?.fps ?? 30; const { FONTS_DIR } = await import("./brand.mjs"); const files = []; try { await inSlot(["umtool", "vertical", "--reframe"], async () => { for (const [i, sp] of spans.entries()) { const box = cuts.get(sp.id)?.framing?.box ?? null; const regions = spanRegions({ type: sp.type, box, entry: byId.get(sp.id) ?? null }) ?? [{ x: 0, y: 0, w: render.width ?? 1920, h: render.height ?? 1080 }]; const ass = path.join(work, `${i}.ass`); await writeFile(ass, reframeAss({ title: sp.seg.title ?? "", subtitle: sp.seg.subtitle ?? "", seconds: sp.b - sp.a, safe }), "utf8"); const file = path.join(work, `${i}.mp4`); log(`reframe: ${sp.id} ${sp.a.toFixed(2)}–${sp.b.toFixed(2)} (${regions.length} region${regions.length === 1 ? "" : "s"})`); await execFileP(FFMPEG, [ "-nostdin", "-v", "error", "-y", "-ss", f3(sp.a), "-t", f3(sp.b - sp.a), "-i", master, "-filter_complex", reframeGraph({ regions, safe, fps, ass, fontsDir: FONTS_DIR }), "-map", "[v]", "-map", "0:a", ...shortEncode(render), file, ], { maxBuffer: 1 << 24 }); files.push(file); } const list = path.join(work, "list.txt"); await writeFile(list, files.map((f) => `file '${f}'`).join("\n") + "\n", "utf8"); await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", list, "-c", "copy", path.join(work, "joined.mp4")]); }); await mkdir(path.dirname(outFile), { recursive: true }); const loudness = await normalizeLoudness(path.join(work, "joined.mp4"), outFile, verticalKnobs(render).loudness, { log }); return { seconds: await probeSeconds(outFile), loudness, spans: spans.map((s) => ({ id: s.id, a: s.a, b: s.b })) }; } finally { await rm(work, { recursive: true, force: true }); } }