// `umtool scenes` (2026-10-25): where the picture cuts and where it goes black, // in one clip's FETCHED window, in SOURCE seconds -- what an agent reads to // choose `blur.from`/`blur.to` and a trim without watching the clip. Found by // hand first: eps-footage (BZCS-Azx_iE, window 227.36–299.00) is black // 250.49–251.09 and cuts at 251.09, so its blur ends there. // // umtool scenes [--black-min 0.05] [--threshold 8] [--pix-th 0.10] // [--pad 30 | --from S --to S] [--json] // // THE FILE IS THE BUILD'S. The window is found the way the render finds it // (report-to-video/sources.mjs resolveLocalSource over the build's fetch span: // the project's out/clips-raw, then the editor's window cache // channels//data//clips/-.mp4, then a saved whole source), // in the channels tree the project reads (channelsDirFor). Nothing is fetched: // a clip with no window on disk is refused, naming `umtool fetch`. // // THE CLOCK IS THE BUILD'S. A window's t = 0 is its `from`; a window whose // picture starts late is offset by clockOffset (the build's startOffset rule). // One ffmpeg pass, `blackdetect` then `scdet`, over the clip's extent ± --pad // (clamped to the window), scaled down first -- the scores are SAD over the // frame, and a small frame scores a cut as a big one does. // // Plain ESM: the CLI runs under bare node. import { spawn } from "node:child_process"; import { clockOffset } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; import { fetchSpan, localPieces } from "umtool-report-to-video/build-video"; import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { channelFor, channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; export const SCENES_USAGE = [ "usage: umtool scenes [--black-min 0.05] [--threshold 8] [--pix-th 0.10]", " [--pad 30 | --from S --to S] [--json]", " the picture's scene cuts (ffmpeg scdet, score ≥ --threshold) and black spans (blackdetect, at least", " --black-min s, a pixel black below --pix-th) in the clip's FETCHED window, in SOURCE seconds — for", " choosing blur.from / blur.to (umtool set) and a trim (umtool window). Scans the clip's extent ± --pad", " inside the window, or --from/--to (source seconds). Nothing is fetched: `umtool fetch ` first.", ].join("\n"); export const SCENE_DEFAULTS = Object.freeze({ blackMin: 0.05, threshold: 8, pixTh: 0.1, pad: 30 }); /** The frame height the scan decodes to: enough for a cut, a fraction of the decode's cost. */ const SCAN_HEIGHT = 360; class CliError extends Error {} const VALUED = new Set(["--black-min", "--threshold", "--pix-th", "--pad", "--from", "--to"]); const r2 = (n) => Math.round(n * 100) / 100; const r3 = (n) => Math.round(n * 1000) / 1000; /** * ffmpeg's log lines into the scan's events, still on the scan's own clock * (t = 0 at the scan's first frame). * * [Parsed_blackdetect_1 @ …] black_start:23.133333 black_end:23.733333 black_duration:0.6 * [Parsed_scdet_2 @ …] lavfi.scd.score: 26.976, lavfi.scd.time: 23.133333 * * @param {string} log ffmpeg's stderr * @returns {{ cuts: { t: number, score: number }[], black: { from: number, to: number }[] }} */ export function parseSceneLog(log) { const cuts = []; const black = []; for (const m of String(log).matchAll(/lavfi\.scd\.score:\s*([\d.]+),\s*lavfi\.scd\.time:\s*([\d.]+)/g)) { cuts.push({ t: Number(m[2]), score: Number(m[1]) }); } for (const m of String(log).matchAll(/black_start:\s*([\d.]+)\s+black_end:\s*([\d.]+)/g)) { black.push({ from: Number(m[1]), to: Number(m[2]) }); } return { cuts, black }; } /** * The scan's events in SOURCE seconds: `zero` is the source second at the * scan's t = 0 (the window's from + its clock offset + the seek into it). * `clip` marks each with whether it falls inside the clip's extent. */ export function toSourceSeconds({ cuts, black }, zero, clip = null) { const inside = (t) => (clip ? t >= clip.start - 0.005 && t <= clip.end + 0.005 : null); return { cuts: cuts.map((c) => { const at = r2(zero + c.t); return { at, score: r3(c.score), inClip: inside(at) }; }), black: black.map((b) => { const from = r2(zero + b.from); const to = r2(zero + b.to); return { from, to, dur: r2(to - from), inClip: clip ? from < clip.end && to > clip.start : null }; }), }; } /** The ffmpeg arguments for one scan of `file` from `seek` for `dur` seconds. */ export function scanArgs(file, { seek, dur, blackMin, threshold, pixTh }) { return [ "-hide_banner", "-nostdin", "-nostats", "-loglevel", "info", "-ss", Math.max(0, seek).toFixed(3), "-t", Math.max(0, dur).toFixed(3), "-i", file, "-an", "-sn", "-dn", "-vf", `scale=-2:${SCAN_HEIGHT},blackdetect=d=${blackMin}:pix_th=${pixTh},scdet=threshold=${threshold}`, "-f", "null", "-", ]; } function runFfmpeg(args, { ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg" } = {}) { return new Promise((resolve, reject) => { const child = spawn(ffmpeg, args, { stdio: ["ignore", "ignore", "pipe"] }); let log = ""; child.stderr.on("data", (d) => { log += d; }); child.on("error", (e) => reject(new Error(`ffmpeg did not start (${e.message}) — is it installed? \`umtool doctor\``))); child.on("exit", (code) => { if (code === 0) resolve(log); else reject(new Error(`ffmpeg exited ${code}: ${log.trim().split("\n").slice(-3).join(" / ")}`)); }); }); } const numFlag = (flags, name, dflt) => { if (!flags.has(name)) return dflt; const n = Number(flags.get(name)); if (!Number.isFinite(n) || n < 0) throw new CliError(`${name} must be a number ≥ 0`); return n; }; /** * The scan of one clip: the window the build would cut it from, and what is * in it. Exported for the tests (`ffmpeg` stubs the binary). */ export async function scanClip(project, clipId, opts = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); const entry = (manifest.timeline ?? []).find((e) => e?.id === clipId); if (!entry) throw new CliError(`no timeline entry with id ${clipId} in ${project.id}`); if (entry.type !== "clip") throw new CliError(`${clipId} is a ${entry.type ?? "non-clip"} entry, not a clip`); if (entry.src) throw new CliError(`${clipId} plays its own file (src: ${entry.src}), not a fetched window`); const { blackMin, threshold, pixTh, pad } = { ...SCENE_DEFAULTS, ...opts }; const slug = channelFor(manifest, entry); const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); const rawDir = path.join(project.dir, "out", "clips-raw"); // The build's lookup, with the manifest's render (its tallWindowCap): one call site. const lookup = (want) => resolveLocalSource(want, { rawDir, channelsDir, probe: ffprobeSource, render: manifest.render ?? null }); // What the build would fetch, then the extent alone (a window that holds the clip but not its pad). const span = fetchSpan(entry, manifest.render ?? {}); const hit = (await lookup({ video: entry.video, slug, from: span.from, to: span.to })) ?? (await lookup({ video: entry.video, slug, from: entry.start, to: entry.end })); const clipRow = { id: clipId, channel: slug, video: entry.video, start: entry.start, end: entry.end, ...(entry.cutStart != null && entry.cutEnd != null ? { cutStart: entry.cutStart, cutEnd: entry.cutEnd } : {}), ...(entry.blur && typeof entry.blur === "object" ? { blur: entry.blur } : {}), }; /** One window scanned over [from, to] (clamped into it): its events in source seconds, and what was scanned. */ const scanWindow = async (h, wantFrom, wantTo) => { const winFrom = h.windowStart; const winTo = h.windowEnd; const from = Math.max(winFrom, wantFrom); const to = Math.min(winTo, wantTo); if (!(to - from > 0)) return { h, empty: true, from, to, winFrom, winTo }; const off = await (opts.clockOffset ?? clockOffset)(h.path); const seek = Math.max(0, from - winFrom - off); const zero = winFrom + off + seek; const log = await runFfmpeg(scanArgs(h.path, { seek, dur: to - from, blackMin, threshold, pixTh }), opts.ffmpeg ? { ffmpeg: opts.ffmpeg } : {}); return { h, from, to, winFrom, winTo, off, events: toSourceSeconds(parseSceneLog(log), zero, { start: entry.start, end: entry.end }) }; }; if (!hit) { // A clip with gaps is fetched per kept piece (fetchSpans): scan each piece on disk. const local = { resolve: (e, sp) => lookup({ video: e.video, slug, from: sp.from, to: sp.to }) }; const had = await localPieces(entry, manifest.render ?? {}, local); if (had) { const wantFrom = opts.from ?? entry.start - pad; const wantTo = opts.to ?? entry.end + pad; const scans = []; // Two spans may be one window (a long file holds both): scanned once. const done = new Set(); for (let k = 0; k < had.hits.length; k += 1) { const h = had.hits[k]; const sp = had.spans[k]; const key = `${h.path}|${Math.max(sp.from, wantFrom)}|${Math.min(sp.to, wantTo)}`; if (done.has(key)) continue; done.add(key); scans.push(await scanWindow(h, Math.max(sp.from, wantFrom), Math.min(sp.to, wantTo))); } const live = scans.filter((x) => !x.empty); if (!live.length) throw new CliError(`nothing to scan: ${r2(wantFrom)}–${r2(wantTo)} is outside every piece's window`); const cuts = live.flatMap((x) => x.events.cuts).sort((a, b) => a.at - b.at); const black = live.flatMap((x) => x.events.black).sort((a, b) => a.from - b.from); return { project: project.id, clip: clipRow, window: { file: live[0].h.path, kind: "pieces", from: Math.min(...scans.map((x) => x.winFrom)), to: Math.max(...scans.map((x) => x.winTo)), clockOffset: 0, pieces: live.map((x) => ({ file: x.h.path, kind: x.h.kind, from: x.winFrom, to: x.winTo, clockOffset: x.off, scanned: { from: r2(x.from), to: r2(x.to) } })), }, scanned: { from: r2(Math.min(...live.map((x) => x.from))), to: r2(Math.max(...live.map((x) => x.to))) }, params: { blackMin, threshold, pixTh }, cuts, black, }; } // A state, not a usage error: exit 1, as a refused write is. throw new Error( `${clipId} (${slug}/${entry.video} ${entry.start}–${entry.end}) has no window on disk — ` + `\`umtool fetch ${project.id}\` asks the editor for it`, ); } const r = await scanWindow(hit, opts.from ?? entry.start - pad, opts.to ?? entry.end + pad); if (r.empty) throw new CliError(`nothing to scan: ${r2(r.from)}–${r2(r.to)} is outside the window ${r.winFrom}–${r.winTo}`); return { project: project.id, clip: clipRow, window: { file: hit.path, kind: hit.kind, from: r.winFrom, to: r.winTo, clockOffset: r.off }, scanned: { from: r2(r.from), to: r2(r.to) }, params: { blackMin, threshold, pixTh }, ...r.events, }; } /** * @param {string[]} args the words after `scenes` * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, ffmpeg?: string }} [opts] * @returns {Promise} the exit code */ export async function scenesCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), ffmpeg } = {}) { const words = []; const flags = new Map(); for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (VALUED.has(a)) { flags.set(a, args[i + 1] ?? ""); i += 1; } else if (a.startsWith("--")) flags.set(a, true); else words.push(a); } const json = flags.has("--json"); try { const [projectArg, clipId] = words; if (!projectArg || !clipId || flags.has("--help")) { err(SCENES_USAGE); return 2; } const r = await resolveProject(projectArg, root); if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${projectArg}"`); const opts = { blackMin: numFlag(flags, "--black-min", SCENE_DEFAULTS.blackMin), threshold: numFlag(flags, "--threshold", SCENE_DEFAULTS.threshold), pixTh: numFlag(flags, "--pix-th", SCENE_DEFAULTS.pixTh), pad: numFlag(flags, "--pad", SCENE_DEFAULTS.pad), from: flags.has("--from") ? numFlag(flags, "--from", 0) : undefined, to: flags.has("--to") ? numFlag(flags, "--to", 0) : undefined, ...(ffmpeg ? { ffmpeg } : {}), }; const s = await scanClip(r.project, clipId, opts); if (json) { out(JSON.stringify(s, null, 2)); return 0; } const c = s.clip; out(`${c.id} ${c.channel}/${c.video} extent ${c.start}–${c.end}${c.cutStart != null ? ` cut ${c.cutStart}–${c.cutEnd}` : ""}` + (c.blur ? ` blur ${c.blur.from ?? c.start}–${c.blur.to ?? c.end}` : "")); if (s.window.kind === "pieces") { out(`window ${s.window.from}–${s.window.to} (pieces: ${s.window.pieces.length}, a clip fetched per kept piece)`); for (const p of s.window.pieces) out(` ${p.from}–${p.to} (${p.kind}) ${p.file}${p.clockOffset ? ` clock +${p.clockOffset}` : ""} scanned ${p.scanned.from}–${p.scanned.to}`); } else { out(`window ${s.window.from}–${s.window.to} (${s.window.kind}) ${s.window.file}${s.window.clockOffset ? ` clock +${s.window.clockOffset}` : ""}`); } out(`scanned ${s.scanned.from}–${s.scanned.to}, source seconds`); const mark = (inClip) => (inClip ? " in clip" : ""); out(`\nblack (≥ ${s.params.blackMin} s): ${s.black.length || "none"}`); for (const b of s.black) out(` ${b.from.toFixed(2)}–${b.to.toFixed(2)} (${b.dur.toFixed(2)} s)${mark(b.inClip)}`); out(`\ncuts (score ≥ ${s.params.threshold}): ${s.cuts.length || "none"}`); for (const x of s.cuts) out(` ${x.at.toFixed(2)} score ${x.score.toFixed(1)}${mark(x.inClip)}`); return 0; } catch (e) { err(`umtool scenes: ${e instanceof Error ? e.message : String(e)}`); return e instanceof CliError ? 2 : 1; } }