// THE BEST PART OF AN ATTACHMENT (`umtool posts fit`, the post bench's // "Re-pick best"; report-to-video/post-narration.mjs `clip: "read"`). // Operator, 2 Nov: "read out every post, and not linger too long after // finishing the read. Clipping away some attachment runtime is preferable to // sitting through a long video after a short post, but we'll want to pick // the best part of the attachment to keep even if it's not necessarily just // truncated off the end." // // A narrated post plays for lead + its read + tail + linger; a video // attachment longer than that is cut to a WINDOW of that length, and this // picks the window: a scored scan of the attachment -- // // loudness its sound's RMS per 0.1 s (decoded by ffmpeg), on its own range: // the window's mean and its peak (laughter, a shout, the music's hit) // speech with a transcript of it (`media[i].words`), the share of the // window that is speech // activity its scene cuts (ffmpeg scdet, scenesCli's scan) inside the window // // -- the window's start snapped to a pause (a silence, detectSilence's, or a // quiet frame) or a scene cut near it, never past the file. The winner is // recorded on the entry (`narration.window`: {media, start, end, score, // reason, at}) so the bench can say why. PURE scoring (scoreWindows) and an // async scan (scanAttachment) around it. import { spawn } from "node:child_process"; import path from "node:path"; import { readFile } from "node:fs/promises"; import { detectSilence } from "umtool-report-to-video/cut-points"; import { isNarrated, postNarrationKnobs, readSpanSeconds } from "umtool-report-to-video/post-narration"; import { parseSceneLog } from "./scenesCli.mjs"; /** The scan's frame: 0.1 s. */ export const FIT_HOP = 0.1; /** Candidate windows start this often. */ export const FIT_STEP = 0.25; /** How far an edge may move to land on a pause or a cut. */ export const FIT_SNAP = 0.75; /** The weights of the score's parts. */ export const FIT_WEIGHTS = Object.freeze({ mean: 1, peak: 0.6, speech: 0.8, cuts: 0.25, early: 0.05 }); const r2 = (v) => Math.round(v * 100) / 100; const r3 = (v) => Math.round(v * 1000) / 1000; /** RMS per hop of mono float samples at `rate`. */ export function rmsFrames(samples, rate, hop = FIT_HOP) { const n = Math.max(1, Math.round(rate * hop)); const out = []; for (let i = 0; i < samples.length; i += n) { let acc = 0; const z = Math.min(samples.length, i + n); for (let j = i; j < z; j += 1) acc += samples[j] * samples[j]; out.push(Math.sqrt(acc / Math.max(1, z - i))); } return out; } /** RMS as dB, floored at -80. */ const db = (x) => (x > 1e-4 ? 20 * Math.log10(x) : -80); /** * SCORE EVERY WINDOW of length `L` over a file of `duration` seconds and pick * the best, PURE: `rms` per `hop` seconds, `cuts` scene cuts (seconds), * `pauses` quiet seconds an edge may snap to, `cues` its transcript (or none). * * @returns {{ start: number, end: number, score: number, reason: string, parts: Record } | null} */ export function scoreWindows({ rms, hop = FIT_HOP, duration, L, cuts = [], pauses = [], cues = null, step = FIT_STEP, weights = FIT_WEIGHTS }) { if (!(duration > 0) || !(L > 0)) return null; if (L >= duration - 0.05) return { start: 0, end: r3(duration), score: 0, reason: "the whole attachment fits the read", parts: {} }; const dbs = rms.map(db); const hear = dbs.filter((d) => d > -80); const lo = hear.length ? Math.min(...hear) : -80; const hi = hear.length ? Math.max(...hear) : -80; const norm = (d) => (hi - lo > 1 ? Math.max(0, (d - lo) / (hi - lo)) : 0); const at = (t) => Math.min(dbs.length - 1, Math.max(0, Math.floor(t / hop))); const speechIn = (a, b) => { if (!cues?.length) return 0; let s = 0; for (const c of cues) s += Math.max(0, Math.min(b, c.end) - Math.max(a, c.start)); return Math.min(1, s / (b - a)); }; let best = null; for (let a = 0; a + L <= duration + 1e-6; a += step) { const b = a + L; let sum = 0; let peak = 0; let n = 0; for (let i = at(a); i <= at(b - hop / 2); i += 1) { const v = norm(dbs[i]); sum += v; peak = Math.max(peak, v); n += 1; } const mean = n ? sum / n : 0; const speech = speechIn(a, b); const cutsIn = cuts.filter((c) => c > a + 0.2 && c < b - 0.2).length; const parts = { mean, peak, speech, cuts: Math.min(1, cutsIn / Math.max(1, L / 4)), early: -a / duration }; const score = weights.mean * parts.mean + weights.peak * parts.peak + weights.speech * parts.speech + weights.cuts * parts.cuts + weights.early * parts.early; if (!best || score > best.score + 1e-9) best = { a, score, parts, cutsIn, speech }; } if (!best) return null; // The start snapped to the nearest pause or cut within FIT_SNAP (kept inside the file). const marks = [...pauses.map((t) => ({ t, what: "a pause" })), ...cuts.map((t) => ({ t, what: "a scene cut" }))] .filter((m) => Math.abs(m.t - best.a) <= FIT_SNAP && m.t >= 0 && m.t + L <= duration + 1e-6) .sort((x, y) => Math.abs(x.t - best.a) - Math.abs(y.t - best.a)); const snap = marks[0] ?? null; const start = r2(snap ? snap.t : best.a); const meanDb = (() => { let s = 0; let n = 0; for (let i = at(start); i <= at(start + L - hop / 2); i += 1) { s += dbs[i]; n += 1; } return n ? s / n : -80; })(); const fileDb = dbs.length ? dbs.reduce((x, y) => x + y, 0) / dbs.length : -80; const why = [ start < 0.3 ? "from the start" : `from ${start.toFixed(1)} s`, `its sound ${meanDb.toFixed(0)} dB (the file ${fileDb.toFixed(0)} dB), peak ${Math.round(best.parts.peak * 100)}% of its range`, ...(cues?.length ? [`speech ${Math.round(best.speech * 100)}%`] : []), ...(best.cutsIn ? [`${best.cutsIn} scene cut${best.cutsIn === 1 ? "" : "s"}`] : []), ...(snap ? [`start on ${snap.what}`] : []), ]; return { start, end: r2(start + L), score: r3(best.score), reason: why.join("; "), parts: Object.fromEntries(Object.entries(best.parts).map(([k, v]) => [k, r3(v)])) }; } function run(cmd, args, { binary = false } = {}) { return new Promise((resolve, reject) => { const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); const chunks = []; let log = ""; child.stdout.on("data", (d) => chunks.push(d)); child.stderr.on("data", (d) => { log += d; }); child.on("error", (e) => reject(new Error(`${cmd} did not start: ${e.message}`))); child.on("exit", (code) => (code === 0 ? resolve({ out: binary ? Buffer.concat(chunks) : Buffer.concat(chunks).toString("utf8"), log }) : reject(new Error(`${cmd} exited ${code}: ${log.trim().split("\n").slice(-2).join(" / ")}`)))); }); } /** A file's sound as mono floats at 8 kHz (empty when it has none). */ export async function decodeMono(file, { ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg", rate = 8000 } = {}) { try { const { out } = await run(ffmpeg, ["-nostdin", "-v", "error", "-i", file, "-vn", "-ac", "1", "-ar", String(rate), "-f", "f32le", "-"], { binary: true }); const buf = /** @type {Buffer} */ (out); return { samples: new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4)), rate }; } catch { return { samples: new Float32Array(0), rate }; } } /** Its scene cuts (seconds), by ffmpeg's scdet. */ export async function sceneCuts(file, { ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg", threshold = 8 } = {}) { try { const { log } = await run(ffmpeg, ["-hide_banner", "-nostdin", "-nostats", "-loglevel", "info", "-i", file, "-an", "-sn", "-dn", "-vf", `scale=-2:240,scdet=threshold=${threshold}`, "-f", "null", "-"]); return parseSceneLog(log).cuts.map((c) => c.t); } catch { return []; } } /** * SCAN ONE ATTACHMENT for its best `L` seconds: decode its sound, find its * cuts and pauses, read its transcript when it has one, score. * * @param {string} file absolute * @param {{ duration: number, L: number, wordsFile?: string | null, ffmpeg?: string }} o */ export async function scanAttachment(file, { duration, L, wordsFile = null, ffmpeg = undefined }) { const { samples, rate } = await decodeMono(file, ffmpeg ? { ffmpeg } : {}); const rms = rmsFrames(samples, rate); const cuts = await sceneCuts(file, ffmpeg ? { ffmpeg } : {}); const silences = samples.length ? await detectSilence(file, { silenceMinDur: 0.2 }, null, ffmpeg ? { ffmpeg } : {}).catch(() => []) : []; const pauses = silences.map((x) => (x.s + x.e) / 2); let cues = null; if (wordsFile) { try { const doc = JSON.parse(await readFile(wordsFile, "utf8")); cues = (Array.isArray(doc?.cues) ? doc.cues : []).filter((c) => Number.isFinite(c?.start) && Number.isFinite(c?.end)); } catch { cues = null; } } return scoreWindows({ rms, duration, L, cuts, pauses, cues }); } /** * THE FIT of one narrated post item, not written: for its first video * attachment longer than the read's span, the best window of that length * (`media` patch + the `window` record); null when there is nothing to fit * (not narrated, `clip: "full"`, no video, or one no longer than the read). * * @param {Record} entry * @param {Record} render * @param {string} projectDir * @param {{ linger?: number | null, scan?: typeof scanAttachment }} [o] */ export async function fitPostItem(entry, render, projectDir, { linger = null, scan = scanAttachment } = {}) { if (!isNarrated(entry)) return null; const k = postNarrationKnobs(entry, render); if (k.clip === "full" || k.attach === "after") return null; const media = Array.isArray(entry.media) ? entry.media : []; const i = media.findIndex((m) => m?.kind === "video"); if (i < 0) return null; const m = media[i]; const span = readSpanSeconds(entry, render); const L = r2(span - k.linger + (linger ?? k.linger)); const duration = Number(m.seconds); if (!(duration > L + 0.05)) return { i, L, duration, untouched: true }; const file = path.join(projectDir, ...String(m.src).split("/")); const wordsFile = typeof m.words === "string" ? path.join(projectDir, ...m.words.split("/")) : null; const w = await scan(file, { duration, L, wordsFile }); if (!w) return null; return { i, L, duration, window: { media: i, start: w.start, end: w.end, score: w.score, reason: w.reason, at: new Date().toISOString() }, media: { [i]: { start: w.start > 0 ? w.start : null, end: w.end } }, }; }