Archilyzer · Source

archilyzer

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

commit 5abf0009900ad6d3017a90d7a0aa7fd85a8d0b4c
parent ca21d22b0dfe3e2d00294cfc3108e0326250eb17
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 17:26:28 -0500

umtool: check-joins -- a measured check of a rendered take's post joins: every boundary of its master where the next post item draws a post the one before showed (its post, a parent, the quote, a linked post, a scene tile), its relation, its planned join, the SSIM of the last frame before against the first after over the post box, and the largest frame-to-frame step standing above its neighbours across it and its join, worst first; the boundary placed where the concat demuxer put it (the files' lengths, 0.33-0.39 s after the schedule by the end of mid-7) (operator, 4 Nov, mid-7: "If one post is visible in the next scene, there should be a transition")

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/bin/umtool.mjs | 5+++++
Mumtool/docs/cli.md | 1+
Aumtool/lib/report/checkJoinsCli.mjs | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/check-joins.mjs | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/check-joins.test.mjs | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
6 files changed, 359 insertions(+), 0 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -16,6 +16,7 @@ // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json) // umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json) +// umtool check-joins <project> --take <id> [--json] [--all] do the post joins of a rendered take carry on, or jump // umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct // umtool decisions [--json] // umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them @@ -851,6 +852,8 @@ function usage() { " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead", " umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each", " clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list", + " umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>] every boundary of the take's master where the", + " next post item draws a post the one before showed: its join, the SSIM across it, the largest jump", " umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy", " (provenance.linkPolicy): cite via site X, these channels direct; --fix rewrites the clips that break it", " umtool patch-markers <project> [<file>.patch.json] [--fix] [--json] take patches whose deck markers name a", @@ -1107,6 +1110,8 @@ const COMMANDS = { links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), // Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs. "speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))), + // Do a rendered take's post joins carry on (operator, 4 Nov, mid-7): lib/report/checkJoinsCli.mjs. + "check-joins": async () => process.exit(await (await import("../lib/report/checkJoinsCli.mjs")).checkJoinsCommand(argv.slice(argv.indexOf("check-joins") + 1))), // The project's link policy (UI notes #10): lib/report/linksCli.mjs. "link-policy": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linkPolicyCommand(argv.slice(argv.indexOf("link-policy") + 1))), // A take patch's markers back on the cut (UI notes #6): lib/report/linksCli.mjs. diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -72,6 +72,7 @@ Inbox cannot disagree about what is wrong with one. | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | | `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | | `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) | +| `check-joins <project> --take <id> [--json] [--all] [--limit <n>]` | do a rendered take's **post joins carry on**: every boundary of its master where the next post item draws a post the one before showed, its planned join, the SSIM across it and the largest frame-to-frame step (read-only, ffmpeg) -- worst first ([report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)) | | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | | `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) | diff --git a/umtool/lib/report/checkJoinsCli.mjs b/umtool/lib/report/checkJoinsCli.mjs @@ -0,0 +1,62 @@ +// `umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>]` -- the measured check of a rendered +// take's joins (report-to-video/check-joins.mjs): every boundary where the next post item draws a post the one before +// showed, its planned join, and how alike the master's frames are across it. Read-only. + +import { existsSync } from "node:fs"; +import path from "node:path"; + +import { checkJoins, joinsTable } from "umtool-report-to-video/check-joins"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { takesDirOf } from "./takes.mjs"; + +class CliError extends Error {} + +export const CHECK_JOINS_USAGE = [ + "usage: umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>]", + " Every boundary of the take's master where the next post item draws a post the one before showed (its post, a", + " parent, the quote, a scene tile, a manual thread's stack): its planned join, the SSIM of the last frame before", + " against the first after (over the post box), and the largest frame-to-frame change across it and its join.", + " Worst first. --all: every post-to-post boundary. Read-only (ffmpeg reads the master).", +].join("\n"); + +export async function checkJoinsCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) { + try { + const words = []; + const flags = {}; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (["--take", "--limit"].includes(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + flags[a] = args[++i]; + } else if (["--json", "--all", "--help"].includes(a)) flags[a] = true; + else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`); + else words.push(a); + } + if (flags["--help"] || !words.length || !flags["--take"]) { + log(CHECK_JOINS_USAGE); + return flags["--help"] ? 0 : 2; + } + const r = await resolveProject(words[0], reportsRoot); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const takeDir = path.join(takesDirOf(r.project.dir), String(flags["--take"])); + if (!existsSync(path.join(takeDir, "out", "sourced", "schedule.json"))) throw new CliError(`${flags["--take"]}: no rendered take at ${takeDir} (out/sourced/schedule.json)`); + const limit = flags["--limit"] ? Number(flags["--limit"]) : Infinity; + if (!(limit > 0)) throw new CliError("--limit takes a positive number"); + const got = await checkJoins(takeDir, { all: !!flags["--all"], onRow: flags["--json"] ? () => {} : (row) => err(` ${row.t.toFixed(2)} ${row.from} → ${row.to}: ssim ${row.ssim?.toFixed(3) ?? "-"}, jump ${row.jump}`) }); + const rows = got.rows.slice(0, limit); + if (flags["--json"]) { + log(JSON.stringify({ take: flags["--take"], master: got.master, drift: got.offsets, rows }, null, 2)); + return 0; + } + log(`${flags["--take"]}: ${got.rows.length} boundar${got.rows.length === 1 ? "y" : "ies"} where the next post item draws a post the one before showed${flags["--all"] ? " (--all: every post-to-post boundary)" : ""}, worst first`); + if (got.offsets) log(` (the master's segments sit ${got.offsets.toFixed(3)} s after the schedule's by the end: the concat demuxer's file lengths)`); + log(joinsTable(rows)); + const bad = got.rows.filter((x) => x.verdict === "JUMPS" || x.verdict === "cut"); + log(`${bad.length} jump or cut where a post stays on screen`); + return 0; + } catch (e) { + err(e instanceof CliError ? `umtool check-joins: ${e.message}` : `umtool check-joins: ${e?.stack ?? e}`); + return 1; + } +} diff --git a/umtool/report-to-video/check-joins.mjs b/umtool/report-to-video/check-joins.mjs @@ -0,0 +1,251 @@ +// 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 post box -- the deck strip and the rest of the chrome left out: +// +// ssim the item before's last frame against the next item's first (1: the same picture) +// 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 <project> --take <id> [--json] [--all] [--limit <n>] +// +// 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, parentsOf } 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({ ssim: 0.97, jump: 3 }); + +/** + * 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<id, what>` -- `what` "post", "parent", "quoted", "linked", "scene". + * @param {Record<string, any>} e + * @param {{ scene?: { tiles?: Array<Record<string, any>> } | 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<number | null>} [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.ssim) && row.ssim < JOIN_CHECK.ssim) || (fin(row.jump) && row.jump > JOIN_CHECK.jump); + if (!bad) return row.join ? "join" : "smooth"; + return row.join ? "JUMPS" : "cut"; +} + +/** Worst first: the lowest SSIM, then the biggest jump. */ +export function rankJoins(rows) { + const score = (r) => (fin(r.ssim) ? r.ssim : 1) - (fin(r.jump) ? r.jump / 255 : 0); + 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", "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.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). +// --------------------------------------------------------------------------- + +/** 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 { ssim: m ? Number(m[1]) : null, jump: r3(j.jump), jumpAt: r3(from + j.t), peak: r3(j.peak) }; +} + +/** + * 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/<slug>.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]; + const m = await measureBoundary(master, t, { box, fps, join: r.join, ffmpeg }); + const row = { ...r, t, box, ...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 }; +} diff --git a/umtool/report-to-video/check-joins.test.mjs b/umtool/report-to-video/check-joins.test.mjs @@ -0,0 +1,39 @@ +// CHECK JOINS (check-joins.mjs): the measured check of a rendered take's joins -- its pure parts. +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { concatFiles, joinBoundaries, jumpOf, joinRelation, joinVerdict, joinsTable, masterStarts, parseFrameMeta, postsDrawnBy, rankJoins } from "./check-joins.mjs"; + +const at = (h) => `2026-11-04T${String(h).padStart(2, "0")}:00:00.000Z`; +const narrate = (e, parts) => ({ ...e, narration: { takes: [{ file: `narration/${e.id}.wav`, seconds: 6, parts: parts.map((p) => ({ text: p.join(" ") })) }], picked: 0 } }); +const post = (id, text, h, extra = {}) => ({ type: "post", id: `p-${id}`, post: `ObviousRises-x/${id}`, platform: "x", author: "MR. OBVIOUS", handle: "ObviousRises", date: at(h), text, url: `https://x.com/ObviousRises/status/${id}`, ...extra }); +const ref = (id, text, h) => ({ id, author: "MR. OBVIOUS", handle: "ObviousRises", date: at(h), text }); + +test("CHECK JOINS: the boundaries where the next item draws a post the one before showed, their relation and planned join; the master's starts from the files as the concat reads them; worst first", () => { + const a = narrate(post("10", "mercy", 7), [["mercy"]]); + const b = narrate(post("11", "notice", 8, { parents: [ref("10", "mercy", 7)] }), [["notice"]]); + const c = narrate(post("99", "unrelated", 9), [["unrelated"]]); + const tl = [a, b, c]; + assert.deepEqual([...postsDrawnBy(b).entries()], [["11", "post"], ["10", "parent"]]); + assert.equal(joinRelation(a, b), "self-reply"); + assert.equal(joinRelation(a, { ...b, handle: "Other" }), "reply to it"); + assert.equal(joinRelation(a, { ...c, quoted: { id: "10", text: "mercy" } }), "quotes it"); + const schedule = { fps: 30, segments: [{ id: "p-10", type: "post", start: 0, duration: 15.9 }, { id: "p-11", type: "post", start: 15.9, duration: 10 }, { id: "p-99", type: "post", start: 25.9, duration: 5 }] }; + const rows = joinBoundaries(tl, schedule); + assert.deepEqual(rows.map((r) => [r.from, r.to, r.shared, r.relation, r.join]), [["p-10", "p-11", ["10"], "self-reply", 0.6]]); + assert.equal(joinBoundaries(tl, schedule, undefined, { all: true }).length, 2); + // The audio a few ms longer than the video: every later segment later than the schedule says. + assert.deepEqual(masterStarts(schedule, [15.905, 10.003, 5]), [0, 15.905, 25.908]); + assert.deepEqual(masterStarts(schedule, []), [0, 15.9, 25.9]); + assert.deepEqual(concatFiles("ffconcat version 1.0\nfile '/a/b.mp4'\nfile '/a/it'\\''s.mp4'\n"), ["/a/b.mp4", "/a/it's.mp4"]); + assert.deepEqual(parseFrameMeta("frame:0 pts:512 pts_time:0.0333\nlavfi.signalstats.YAVG=0.5\nframe:1 pts:1024 pts_time:0.0667\nlavfi.signalstats.YAVG=9.25\n", "lavfi.signalstats.YAVG"), [{ t: 0.0333, v: 0.5 }, { t: 0.0667, v: 9.25 }]); + // A cut: one step alone; a dissolve: many alike. + assert.equal(jumpOf([{ t: 0, v: 0 }, { t: 1, v: 9 }, { t: 2, v: 0.2 }]).jump, 8.8); + assert.ok(jumpOf([{ t: 0, v: 2 }, { t: 1, v: 2.5 }, { t: 2, v: 2.2 }, { t: 3, v: 1.9 }]).jump < 0.5); + const measured = [{ from: "a", to: "b", shared: ["1"], relation: "self-reply", join: 0.6, t: 1, ssim: 0.79, jump: 10.7 }, { from: "c", to: "d", shared: ["2"], relation: "manual thread", join: 0.6, t: 2, ssim: 0.998, jump: 1.2 }]; + assert.deepEqual(rankJoins(measured).map((r) => r.from), ["a", "c"]); + assert.equal(joinVerdict(measured[0]), "JUMPS"); + assert.equal(joinVerdict(measured[1]), "join"); + assert.equal(joinVerdict({ ...measured[0], join: null }), "cut"); + assert.match(joinsTable(measured), /a → b\s+self-reply\s+1\s+0\.6s\s+0\.790\s+10\.7\s+JUMPS/); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -23,6 +23,7 @@ "./brand-ids": "./brand-ids.mjs", "./build-video": "./build-video.mjs", "./check-availability": "./check-availability.mjs", + "./check-joins": "./check-joins.mjs", "./chunked-encode": "./chunked-encode.mjs", "./claims": "./claims.mjs", "./clip-audio": "./clip-audio.mjs",