// CHECK JOINS (umtool/docs/report-video.md, "The join"; operator, 4 Nov, on mid-7: "the transition from some posts // hard cutting into the same post with children should be addressed. If one post is visible in the next scene, // there should be a transition"). A MEASURED check of a rendered take: for every boundary between two post items // where the next one draws a post the one before showed (its post, a parent, the quote, a scene tile, a manual // thread's stack), the master's last frame of the item before and the first frames of the next are read back // (ffmpeg, read-only) and scored over the two items' CARDS as laid out (cardRegion) -- the deck strip, the chrome and // the attachments' slots left out: // // edge THE VERDICT: the largest frame-to-frame change (the mean absolute difference, 0-255, of the box in // grey) into the frames around the boundary (the item before's last, this one's first and second) -- a // join's first frames barely move (its ease starts flat: 0.07 % of the way at its second frame), so // anything seen there over what was already moving (the item before's last frames: a video playing) is // a cut // ssim the item before's last frame against the next item's second (1: the same picture; dark flat cards make // it touchy -- a clock coming in faintly costs 0.07 -- so it is shown, not judged) // jump how far the largest frame-to-frame change across the boundary and the join after it (the mean // absolute difference, 0-255, of the box in grey) stands above its neighbours: a cut is one big step // alone, a morph or a dissolve many small ones alike // // The boundary's place in the master is where the concat put it: each segment starts at the sum of the files // before it AS THE CONCAT DEMUXER READS THEM (a file's length is its longest stream's: an audio stream a few ms // longer than the video moves every later segment, measured 0.33 s by the end of mid-7), else the schedule's. // // umtool check-joins --take [--json] [--all] [--limit ] // // Pure helpers first (tested), then the ffmpeg reads. import { execFile } from "node:child_process"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { chainOf, planContext } from "./post-conversation.mjs"; import { linksOf, panelEntry, parentsOf, postLayout } from "./post-item.mjs"; import { groupOf, shownIdOf } from "./post-thread.mjs"; const execFileP = promisify(execFile); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); const fin = (v) => typeof v === "number" && Number.isFinite(v); const r3 = (v) => Math.round(v * 1000) / 1000; /** A cut whose boundary scores below this SSIM, or jumps above this, is called a CUT (a join's frames move little). */ export const JOIN_CHECK = Object.freeze({ edge: 2.5 }); /** * The posts item `e` draws (its own, the posts it answers, its quote, the posts it links, the scene its run left on * screen): `Map` -- `what` "post", "parent", "quoted", "linked", "scene". * @param {Record} e * @param {{ scene?: { tiles?: Array> } | null }} [ctx] */ export function postsDrawnBy(e, { scene = null } = {}) { const out = new Map(); const add = (id, what) => { if (str(id) && !out.has(str(id))) out.set(str(id), what); }; add(shownIdOf(e), "post"); for (const p of parentsOf(e)) add(p?.id, "parent"); if (isObj(e?.quoted)) add(e.quoted.id, "quoted"); for (const l of linksOf(e)) add(l?.id, "linked"); for (const t of Array.isArray(scene?.tiles) ? scene.tiles : []) add(t?.id, "scene"); return out; } /** How item `b` relates to `a`, the item before it (the check's words). */ export function joinRelation(a, b) { const ida = shownIdOf(a); const pb = parentsOf(b); if (groupOf(a) && groupOf(a) === groupOf(b)) return "manual thread"; if (ida && str(pb[0]?.id) === ida) return str(a?.handle) && str(a?.handle).toLowerCase() === str(b?.handle).toLowerCase() ? "self-reply" : "reply to it"; if (ida && isObj(b?.quoted) && str(b.quoted.id) === ida) return "quotes it"; if (ida && pb.some((p) => str(p?.id) === ida)) return "a later reply"; if (ida && ida === shownIdOf(b)) return "the same post"; const ca = new Set(chainOf(a).filter(Boolean)); if (chainOf(b).some((id) => id && ca.has(id))) return "same thread"; return "shares a post"; } /** * THE BOUNDARIES, pure: each post-to-post boundary of the schedule (`schedule.segments`, by id into the timeline) * with what the two items share -- `{ i, from, to, at, shared: [id], relation, join, seconds }` (`join` the * planned join's seconds, or null: a cut). `all`: every post-to-post boundary, sharing or not. */ export function joinBoundaries(timeline, schedule, render = undefined, { all = false } = {}) { const tl = Array.isArray(timeline) ? timeline : []; const byId = new Map(tl.map((e, k) => [str(e?.id), k])); const segs = Array.isArray(schedule?.segments) ? schedule.segments : []; const out = []; for (let i = 1; i < segs.length; i += 1) { const sa = segs[i - 1]; const sb = segs[i]; if (sa?.type !== "post" || sb?.type !== "post") continue; const ka = byId.get(str(sa.id)); const kb = byId.get(str(sb.id)); if (ka === undefined || kb === undefined) continue; const a = tl[ka]; const b = tl[kb]; const ctxA = planContext(tl, ka, render); const ctxB = planContext(tl, kb, render); const drawnA = postsDrawnBy(a, ctxA); const drawnB = postsDrawnBy(b, ctxB); const shared = [...drawnB.keys()].filter((id) => drawnA.has(id)); if (!shared.length && !all) continue; out.push({ i, from: str(a.id), to: str(b.id), at: fin(sb.start) ? sb.start : null, shared, relation: shared.length ? joinRelation(a, b) : "none", join: ctxB.join && fin(ctxB.join.seconds) && kb === ka + 1 ? ctxB.join.seconds : null, }); } return out; } /** * Where each segment starts in the master: the sum of the files before it as the concat demuxer reads them * (`durations[i]`: segment i's file length, its longest stream's), else the schedule's start. * @param {{ segments: Array<{ start?: number }> }} schedule * @param {Array} [durations] */ export function masterStarts(schedule, durations = []) { const segs = schedule?.segments ?? []; const usable = durations.length === segs.length && durations.every(fin); let acc = 0; return segs.map((s, i) => { const t = usable ? acc : fin(s.start) ? s.start : acc; if (usable) acc += durations[i]; return r3(t); }); } /** ffmpeg's `metadata=print:file=-` lines → `[{ t, v }]` (the frame's pts time, the key's value). */ export function parseFrameMeta(text, key) { const out = []; let t = null; for (const line of String(text).split(/\r?\n/)) { const m = /pts_time:([-\d.]+)/.exec(line); if (m) t = Number(m[1]); const v = new RegExp(`${key.replace(/\./g, "\\.")}=([-\\d.e]+)`).exec(line); if (v && t !== null) out.push({ t, v: Number(v[1]) }); } return out; } /** The verdict of one measured boundary: "join" (it moved on smoothly), "cut" (a step), "planned cut". */ export function joinVerdict(row) { const bad = fin(row.edge) && row.edge > JOIN_CHECK.edge; if (!bad) return row.join ? "join" : "smooth"; return row.join ? "JUMPS" : "cut"; } /** Worst first: the biggest edge, then the lowest SSIM. */ export function rankJoins(rows) { const score = (r) => -(fin(r.edge) ? r.edge : 0) + (fin(r.ssim) ? r.ssim : 1) / 1000; return [...rows].sort((a, b) => score(a) - score(b)); } /** The table a person reads. */ export function joinsTable(rows) { const head = ["at (master)", "from → to", "relation", "shared", "join", "edge", "ssim", "jump", "verdict"]; const lines = rows.map((r) => [ fin(r.t) ? r.t.toFixed(2) : "?", `${r.from} → ${r.to}`, r.relation, String(r.shared.length), r.join ? `${r.join}s` : "cut", fin(r.edge) ? r.edge.toFixed(1) : "-", fin(r.ssim) ? r.ssim.toFixed(3) : "-", fin(r.jump) ? r.jump.toFixed(1) : "-", joinVerdict(r), ]); const w = head.map((h, k) => Math.max(h.length, ...lines.map((l) => l[k].length))); const fmt = (l) => l.map((c, k) => c.padEnd(w[k])).join(" ").trimEnd(); return [fmt(head), fmt(w.map((n) => "-".repeat(n))), ...lines.map(fmt)].join("\n"); } // --------------------------------------------------------------------------- // The reads (ffmpeg / ffprobe, read-only). // --------------------------------------------------------------------------- /** * THE CARDS' REGION in the master, pure: the union of the items' cards as laid out (post-item.mjs postLayout, the * cut's panel rule on) in the post box `box` (the deck's, where the segment lays its box), even-sized for ffmpeg. */ export function cardRegion(entries, box, render = undefined) { const cards = entries.filter(Boolean).map((e) => postLayout(panelEntry(e, render), { width: box.width, height: box.height }).card).filter((c) => c && [c.x, c.y, c.width, c.height].every(fin)); if (!cards.length) return box; const x0 = Math.max(0, Math.floor(Math.min(...cards.map((c) => c.x)))); const y0 = Math.max(0, Math.floor(Math.min(...cards.map((c) => c.y)))); const x1 = Math.min(box.width, Math.ceil(Math.max(...cards.map((c) => c.x + c.width)))); const y1 = Math.min(box.height, Math.ceil(Math.max(...cards.map((c) => c.y + c.height)))); const w = x1 - x0 - ((x1 - x0) % 2); const h = y1 - y0 - ((y1 - y0) % 2); return w > 8 && h > 8 ? { x: box.x + x0, y: box.y + y0, width: w, height: h } : box; } /** A file's length as the concat demuxer reads it (its format duration), or null. */ async function fileSeconds(file, ffprobe) { try { const { stdout } = await execFileP(ffprobe, ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file]); const v = Number(String(stdout).trim()); return fin(v) ? v : null; } catch { return null; } } /** The files concat.txt lists, in order. */ export function concatFiles(text) { return String(text).split(/\r?\n/).map((l) => /^file\s+'(.*)'\s*$/.exec(l.trim())).filter(Boolean).map((m) => m[1].replace(/'\\''/g, "'")); } /** * Measure boundary `row` in `master` at `t` (where segment `to` starts): the SSIM of the frame 1.5 frames before * against the one 1.5 frames after, and the largest frame-to-frame change from 3 frames before to the join's end * (+0.4 s), over `box` scaled to half, in grey. */ export async function measureBoundary(master, t, { box, fps = 30, join = null, ffmpeg = "ffmpeg" }) { const crop = `crop=${box.width}:${box.height}:${box.x}:${box.y},scale=${Math.round(box.width / 2)}:-2,format=gray`; const ta = Math.max(0, t - 1.5 / fps); const tb = t + 1.5 / fps; const ss = await execFileP(ffmpeg, ["-nostdin", "-v", "info", "-ss", ta.toFixed(4), "-i", master, "-ss", tb.toFixed(4), "-i", master, "-frames:v", "1", "-lavfi", `[0:v]${crop}[a];[1:v]${crop}[b];[a][b]ssim`, "-f", "null", "-"], { maxBuffer: 1 << 24 }); const m = /All:([\d.]+)/.exec(String(ss.stderr)); const from = Math.max(0, t - 3 / fps); const span = (fin(join) ? join : 0) + 0.4 + 3 / fps; const d = await execFileP(ffmpeg, ["-nostdin", "-v", "error", "-ss", from.toFixed(4), "-i", master, "-t", span.toFixed(4), "-vf", `${crop},tblend=all_mode=difference,signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-`, "-f", "null", "-"], { maxBuffer: 1 << 24 }); const diffs = parseFrameMeta(String(d.stdout) + String(d.stderr), "lavfi.signalstats.YAVG"); const j = jumpOf(diffs); return { edge: r3(edgeOf(diffs.map((x) => ({ t: from + x.t, v: x.v })), t, fps)), ssim: m ? Number(m[1]) : null, jump: r3(j.jump), jumpAt: r3(from + j.t), peak: r3(j.peak) }; } /** * THE EDGE, pure: the largest change into the frames around the boundary -- the item before's last, this one's first * and second -- over the largest among the item before's six frames before them (what was already moving: a video * playing, a pan) (`diffs` on * the master's clock, each the change INTO its frame; `t` where this item starts). */ export function edgeOf(diffs, t, fps = 30) { const max = (a, b) => diffs.filter((x) => x.t > a && x.t <= b).reduce((m, x) => Math.max(m, x.v), 0); // Over what was already moving: a video playing in the slot, a pan -- the item before's last frames' own change. return Math.max(0, max(t - 1.5 / fps, t + 1.5 / fps) - max(t - 7.5 / fps, t - 1.5 / fps)); } /** * THE JUMP in a run of frame-to-frame changes (`[{ t, v }]`), pure: how far one step stands above the larger of its * neighbours -- a cut is one step (big, its neighbours still), a morph or a dissolve many alike (small) -- `{ jump, * t, peak }` (`peak` the largest step itself). */ export function jumpOf(diffs) { let out = { jump: 0, t: 0, peak: 0 }; diffs.forEach((x, i) => { const near = Math.max(diffs[i - 1]?.v ?? 0, diffs[i + 1]?.v ?? 0); const j = Math.max(0, x.v - near); if (j > out.jump) out = { ...out, jump: j, t: x.t }; if (x.v > out.peak) out.peak = x.v; }); return out; } /** * CHECK A TAKE: `{ rows, master, offsets }` -- each boundary (joinBoundaries) measured in the take's master. * `takeDir` the take's folder (its video.manifest.json, out/.mp4, out/sourced/{schedule.json,concat.txt}). */ export async function checkJoins(takeDir, { all = false, ffmpeg = "ffmpeg", ffprobe = "ffprobe", onRow = () => {} } = {}) { const manifest = JSON.parse(await readFile(path.join(takeDir, "video.manifest.json"), "utf8")); const out = path.join(takeDir, "out"); const sourced = path.join(out, "sourced"); const schedule = JSON.parse(await readFile(path.join(sourced, "schedule.json"), "utf8")); const master = path.join(out, `${str(manifest.slug)}.mp4`); const fps = fin(schedule.fps) ? schedule.fps : manifest.render?.fps ?? 30; const files = concatFiles(await readFile(path.join(sourced, "concat.txt"), "utf8").catch(() => "")); const durations = files.length === schedule.segments.length ? await Promise.all(files.map((f) => fileSeconds(f, ffprobe))) : []; const starts = masterStarts(schedule, durations); const rows = joinBoundaries(manifest.timeline, schedule, manifest.render, { all }); const measured = []; for (const r of rows) { const seg = schedule.segments[r.i]; const cut = JSON.parse(await readFile(path.join(sourced, "segments", `${seg.id}.cut.json`), "utf8").catch(() => "null")); const fb = cut?.framing?.box; const box = isObj(fb) && [fb.x, fb.y, fb.width, fb.height].every(fin) ? { x: Math.round(fb.x), y: Math.round(fb.y), width: Math.round(fb.width) - (Math.round(fb.width) % 2), height: Math.round(fb.height) - (Math.round(fb.height) % 2) } : { x: 0, y: 0, width: 1920, height: 880 }; const t = starts[r.i]; // Over the CARDS (the item before's and this one's, as laid out), never their attachments' slots: a video playing // through the boundary, or one cross-fading into another, is not the join's step. const byId = new Map(manifest.timeline.map((e) => [e?.id, e])); const region = cardRegion([byId.get(r.from), byId.get(r.to)], box, manifest.render); const m = await measureBoundary(master, t, { box: region, fps, join: r.join, ffmpeg }); const row = { ...r, t, box: region, ...m }; row.verdict = joinVerdict(row); measured.push(row); onRow(row); } return { rows: rankJoins(measured), master, offsets: durations.length ? r3(starts[starts.length - 1] - (schedule.segments.at(-1)?.start ?? 0)) : 0 }; }