// WHERE THE RENDER CUTS A CLIP, measured: the build's snap path as one module // the build (build-video.mjs buildClipSegment) and umtool's cut-points route // (lib/report/cutPoints.mjs, the Play view and the clip bench's ghost // markers) both call -- so what Play plays at a join is where the render cuts // it, from the render's code, never a second reading of it. // // detectSilence the silences of the file a clip is cut from (silencedetect // a few dB under the clip's own mean, `render.silenceMinDur`, // `render.silenceRelDb`) -- the input of snap.mjs's arithmetic // room* room at the edges (render.room, room.mjs): the words around // a clip's edges, else the silences, and the plan its sound // and picture are cut by // measureLoudness the cut's integrated loudness (render.loudness's gain) // // No imports from build-video.mjs: it imports this file. import { execFile } from "node:child_process"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { fxWordsOf } from "./fx.mjs"; import { hasLocalMedia } from "./local-media.mjs"; import { whisperWords } from "./montage.mjs"; import { ROOM, clipRoom, roomPlan, speechStartFromSilences, speechStartFromWords, tailFromSilences, tailFromWords, } from "./room.mjs"; export { snap, snapCut, renderCut, recordSecond, snapKnobs, SNAP_DEFAULTS } from "./snap.mjs"; const execFileP = promisify(execFile); const FFMPEG_DEFAULT = process.env.FFMPEG_BIN ?? "ffmpeg"; /** silencedetect's lines as [{s, e}], shifted by `shift`; a silence still open at the end runs to `openTo` when given. */ function parseSilences(log, shift, openTo = null) { const out = []; let open = null; for (const line of String(log ?? "").split("\n")) { const s = line.match(/silence_start:\s*(-?[\d.]+)/); if (s) open = Number(s[1]) + shift; const e = line.match(/silence_end:\s*(-?[\d.]+)/); if (e && open !== null) { out.push({ s: open, e: Number(e[1]) + shift }); open = null; } } if (open !== null && openTo !== null) out.push({ s: open, e: openTo }); return out; } /** * The silences of a file as [{s, e}], in seconds relative to its start. * * @param {string} file * @param {{ silenceMinDur?: number, silenceRelDb?: number }} render * @param {{ from: number, to: number } | null} [scan] measure only this span * @param {{ ffmpeg?: string }} [opts] */ export async function detectSilence(file, render, scan = null, { ffmpeg = FFMPEG_DEFAULT } = {}) { const minDur = render.silenceMinDur ?? 0.09; // A source wider than the fetch would have been (a corpus window, a whole // saved container) is measured over just that span: seeked, audio only, and // the silences shifted back onto the file's clock. A raw-cache window is // measured whole, as it always was, so no cached cut moves. const input = scan ? ["-ss", scan.from.toFixed(3), "-to", scan.to.toFixed(3), "-i", file, "-vn"] : ["-i", file]; const shift = scan ? scan.from : 0; // The threshold has to be RELATIVE to the clip, not absolute. These are game // streams: the gaps between words are full of game audio and music, so they // are quiet but nowhere near silent. A fixed -32 dB sits below the noise floor // of a typical clip here and finds literally zero silences (measured: mean // volume -21 dB, 0 hits at -32 dB, 25 hits at -26 dB). Measure the clip first // and cut a few dB under its own mean instead. const { stderr: volLog } = await execFileP( ffmpeg, ["-nostdin", ...input, "-af", "volumedetect", "-f", "null", "-"], { maxBuffer: 1 << 26 }, ).catch((e) => ({ stderr: e.stderr ?? "" })); const meanMatch = (volLog ?? "").match(/mean_volume:\s*(-?[\d.]+) dB/); const mean = meanMatch ? Number(meanMatch[1]) : -24; const noise = Math.max(-45, Math.min(-18, mean - (render.silenceRelDb ?? 6))); // ffmpeg exits 0 here, so stderr comes back on the resolved result. const { stderr } = await execFileP( ffmpeg, ["-nostdin", ...input, "-af", `silencedetect=noise=${noise.toFixed(1)}dB:d=${minDur}`, "-f", "null", "-"], { maxBuffer: 1 << 26 }, ).catch((e) => ({ stderr: e.stderr ?? "" })); return parseSilences(stderr ?? "", shift); } /** * A stretch of a source's integrated loudness (LUFS, ffmpeg's ebur128), or * null when it cannot be measured. * * @param {(log: string) => number | null} parse montage.mjs parseIntegratedLoudness */ export async function measureLoudnessWith(raw, from, to, parse, { ffmpeg = FFMPEG_DEFAULT } = {}) { const { stderr } = await execFileP(ffmpeg, [ "-nostdin", "-hide_banner", "-ss", Math.max(0, from).toFixed(3), "-to", to.toFixed(3), "-i", raw, "-vn", "-af", "ebur128", "-f", "null", "-", ], { maxBuffer: 1 << 26 }).catch((e) => ({ stderr: e.stderr ?? "" })); return parse(stderr); } // ---- room at the edges (render.room; release 36 lane E) -------------------- /** * silencedetect at a fixed floor (ROOM.detectDb, ROOM.detectD) over [from, to] * of a file (its own seconds), for a clip with no words. A silence still open * when the span ends runs to its end. */ export async function detectRoomSilences(file, from, to, { ffmpeg = FFMPEG_DEFAULT } = {}) { const a = Math.max(0, from); const { stderr } = await execFileP( ffmpeg, ["-nostdin", "-ss", a.toFixed(3), "-to", to.toFixed(3), "-i", file, "-vn", "-af", `silencedetect=noise=${ROOM.detectDb}dB:d=${ROOM.detectD}`, "-f", "null", "-"], { maxBuffer: 1 << 26 }, ).catch((e) => ({ stderr: e.stderr ?? "" })); return parseSilences(stderr ?? "", a, to); } /** * What the captions and the room read beside the manifest: reactions.json * (the clip finder's turns and roles, when it is version 1) and the words file * it names (`source.words`, else words.json), read once. */ export async function readLookSources(manifestDir) { let reactions = null; try { const doc = JSON.parse(await readFile(path.join(manifestDir, "reactions.json"), "utf8")); if (doc?.version === 1 && Array.isArray(doc.turns)) reactions = doc; } catch { reactions = null; } return { manifestDir, reactions, words: null, transcripts: new Map() }; } /** Does reactions.json describe this clip's recording? */ function lookMatches(entry, provenance, rx) { if (!rx?.source?.video || hasLocalMedia(entry) || entry.video !== rx.source.video) return false; const ch = entry.channel ?? provenance?.channelSlug ?? null; return !rx.source.channel || !ch || ch === rx.source.channel; } const wordOf = (w) => ({ text: String(w?.w ?? w?.word ?? w?.text ?? ""), start: Number(w?.start), end: Number(w?.end) }); /** * A clip's words, turns and speakers in [from, to] (source seconds): the * project's words file for the recording reactions.json describes, else the * corpus's whisper words (transcript.json), else its cues spread by * character. Turns and speakers only from reactions.json. * * @param {{ channelsDir: string | null, cues: (entry: any) => Promise> }} src * where the corpus is, and the clip's cues (the build's cue source, or umtool's) */ export async function lookWords(entry, provenance, look, from, to, { channelsDir, cues }) { const inSpan = (w) => Number.isFinite(w.start) && Number.isFinite(w.end) && (w.start + w.end) / 2 >= from - 0.05 && (w.start + w.end) / 2 <= to + 0.05; const rx = lookMatches(entry, provenance, look.reactions) ? look.reactions : null; const turns = rx ? rx.turns.filter((t) => t.end > from && t.start < to) : []; const speakers = rx?.speakers ?? []; if (rx) { look.words ??= readFile(path.join(look.manifestDir, typeof rx.source.words === "string" ? rx.source.words : "words.json"), "utf8") .then((t) => { const doc = JSON.parse(t); return (Array.isArray(doc) ? doc : doc?.words ?? []).map(wordOf); }) .catch(() => null); const ws = await look.words; if (ws?.length) { const got = ws.filter(inSpan); if (got.length) return { words: got, turns, speakers, wordsFrom: "words.json" }; } } if (!hasLocalMedia(entry) && channelsDir && entry.video) { const slug = entry.channel ?? provenance?.channelSlug; const key = `${slug}/${entry.video}`; if (!look.transcripts.has(key)) { look.transcripts.set(key, resolveVideoDir(channelsDir, slug, entry.video) .then((dir) => readFile(path.join(dir, "transcript.json"), "utf8")) .then((t) => whisperWords(JSON.parse(t))) .catch(() => null)); } const ws = await look.transcripts.get(key); const got = (ws ?? []).map(wordOf).filter(inSpan); if (got.length) return { words: got, turns, speakers, wordsFrom: "transcript.json" }; } const cs = fxWordsOf(await cues(entry), from - 0.05, to + 0.05).map(wordOf); return { words: cs, turns, speakers, wordsFrom: "cues" }; } /** * One clip's room (room.mjs's rule): where its sound stops and whether its * head is muted, from its words -- `words(from, to)`, the build's lookWords * -- else the silences (`silences(from, to)`, detectRoomSilences); the plan, * in the file's seconds; and what its cut record says. Null when the clip has * no room (or nothing moves). `first`: nothing comes before it, so no head. * `notes` are the build's log lines, said by the caller. * * @param {{ entry: any, render: any, D: number, first: boolean, fetchStart: number, cutA: number, cutB: number, * duration: number | null, file: string, * words: (from: number, to: number) => Promise<{ words: Array<{ start: number, end: number }>, wordsFrom: string } | null>, * silences: (from: number, to: number) => Promise> }} o */ export async function roomOfCut({ entry, render, D, first, fetchStart, cutA, cutB, duration, file, words, silences }) { const room = clipRoom(entry, render); if (!room) return null; const head = room.head && !first; if (!room.tail && !head) return null; const notes = []; const got = await words(fetchStart + cutA - 1, fetchStart + cutB + room.maxS + 1).catch(() => null); const ws = (got?.words ?? []).map((w) => ({ start: w.start - fetchStart, end: w.end - fetchStart })); let via = ws.length ? got.wordsFrom : "silence"; let tail = room.tail && ws.length ? tailFromWords(ws, cutB, room) : null; let speech = head && ws.length ? speechStartFromWords(ws, cutA) : null; // Cues abut: a run of them that reaches the cap says nothing about where // anybody stops, so the sound decides that edge instead. const detectTail = room.tail && (!ws.length || (via === "cues" && tail?.capped)); if (detectTail || (head && !ws.length)) { const end = Math.min(duration ?? Infinity, cutB + room.maxS + 0.5); const sil = await silences(Math.min(cutA, cutB) - 0.5, end); if (detectTail) { tail = tailFromSilences(sil, cutB, room); via = ws.length ? `${via}+silence` : "silence"; if (!tail.found) notes.push(`${entry.id}: no silence within ${room.maxS} s of its end — its sound stops at the cut`); } if (head && !ws.length) speech = speechStartFromSilences(sil, cutA); } const plan = roomPlan({ cutA, cutB, D, soundEnd: tail ? tail.at : null, speechStart: head ? speech : null, duration }); if (plan.picA === cutA && plan.picB === cutB) return null; if (tail?.capped) notes.push(`${entry.id}: still talking ${room.maxS} s past its end — its sound fades there (render.room.maxS)`); for (const edge of plan.clamped) { notes.push(`${entry.id}: its ${edge === "tail" ? "tail" : "head"} room is clamped to ${path.basename(file)}'s ${edge === "tail" ? "end" : "start"} (a fetched window; widen the extent or fetch it whole)`); } const s3 = (t) => Number((fetchStart + t).toFixed(3)); return { plan, notes, record: { sound: [s3(plan.soundA), s3(plan.soundB)], head: plan.head, tail: plan.tail, via, ...(tail?.capped ? { capped: true } : {}), ...(plan.clamped.length ? { clamped: plan.clamped } : {}), }, }; }