Archilyzer · Source

archilyzer

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

commit 810e58efd7329dda3fe46d67f9dd595cae6a23a4
parent f60c232a6d75648dbf84e3e1548d3c2ae885ec45
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 24 Oct 2026 02:04:35 -0400

cut points: the render's snap path as one module, and a route that reads it

The build's silence detection, snap, room-at-the-edges and loudness measure
move out of build-video.mjs into report-to-video/snap.mjs (pure: snap,
snapCut, renderCut) and cut-points.mjs (ffmpeg: detectSilence,
detectRoomSilences, lookWords, roomOfCut, measureLoudnessWith); the build
calls them unchanged. fetchClip's on-disk branch is onDiskClipSource and
its clock alignment alignedClipSource, so a reader resolves the same file
over the same span the build snaps on.

lib/report/cutPoints.mjs + GET /api/report/cut-points: each clip's render
cut in source seconds (start, end, snapped, room's audible span, the
loudness gain, the clip's audio knobs) and the silences it was snapped on,
cached on disk per measurement (UMTOOL_CACHE_DIR/cut-points), so moving a
cut re-snaps without ffmpeg. cutPoints.test.mjs renders a fixture and
checks the route against the cut records, room and loudness included.

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

Diffstat:
Aumtool/app/api/report/cut-points/route.ts | 30++++++++++++++++++++++++++++++
Aumtool/lib/report/cutPoints.mjs | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/cutPoints.test.mjs | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 360++++++++++++++++++++++---------------------------------------------------------
Aumtool/report-to-video/cut-points.mjs | 246+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 2++
Aumtool/report-to-video/snap.mjs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 902 insertions(+), 260 deletions(-)

diff --git a/umtool/app/api/report/cut-points/route.ts b/umtool/app/api/report/cut-points/route.ts @@ -0,0 +1,30 @@ +import { REPORTS_ROOT } from "@/lib/paths.mjs"; +import { walkProjects } from "@/lib/projects/walk.mjs"; +import { cutPointsFor } from "@/lib/report/cutPoints.mjs"; + +export const dynamic = "force-dynamic"; + +// Where the render will cut each clip (lib/report/cutPoints.mjs): the build's +// own source resolution, silence detection and snap, cached on disk, so the +// Play view plays the render's edges and the clip bench draws them. +// +// GET ?project[&take][&clip=<id>...] every clip of the cut (or the named +// ones): { knobs, transition, montage, clips } +// +// Nothing is fetched and nothing in the project is written; the first read +// of a clip measures its source (two ffmpeg passes over the clip and its pad), +// every later one is read from the cache. +export async function GET(request: Request) { + const url = new URL(request.url); + const projectId = url.searchParams.get("project") ?? ""; + const take = url.searchParams.get("take") || null; + const clips = url.searchParams.getAll("clip").filter(Boolean); + const project = (await walkProjects(REPORTS_ROOT)).find((p: { id: string }) => p.id === projectId); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + try { + const got = await cutPointsFor(project, { take, clips: clips.length ? clips : null }); + return Response.json(got, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 422 }); + } +} diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -0,0 +1,247 @@ +// WHERE THE RENDER WILL CUT EACH CLIP, before it renders (umtool/docs/knobs.md, +// "Play the cut"): the edges the Play view plays and the clip bench draws as +// ghost markers. The build snaps every clip edge to the nearest silence +// within `render.snapWindow` (measured on the Huck cut: starts up to 1.0 s +// earlier, ends up to 1.0 s later than the manifest's), and a preview that +// plays the manifest's edges plays a different cut -- the join is where it +// differs most, and the join is what a preview is for. +// +// ONE IMPLEMENTATION. Everything that decides an edge is the build's own code: +// the same file over the same span (build-video.mjs onDiskClipSource and +// alignedClipSource -- the build's resolution, never the bench's widest +// window: the silence threshold is relative to what is measured), the same +// silencedetect (cut-points.mjs detectSilence), the same snap (snap.mjs +// renderCut), room at the edges (cut-points.mjs roomOfCut) and the loudness +// gain (render.loudness). cutPoints.test.mjs renders a fixture and checks the +// cut records against this, edge for edge. +// +// CACHED ON DISK, per measurement, under UMTOOL_CACHE_DIR/cut-points/: the +// silences by (file, its mtime and size, the span measured, silenceMinDur, +// silenceRelDb); a file's clock offset by (file, mtime, size); a loudness by +// (file, mtime, size, span). The snap itself is arithmetic on the cached +// silences, so moving a clip's cut (the bench's edge drag) costs nothing, and +// only a change of its extent -- a different span to measure -- runs ffmpeg +// again. Nothing here fetches: a clip with no source on disk is `missing`. +import { createHash } from "node:crypto"; +import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + DEFAULT_VARIANT, FFMPEG_BIN, alignedClipSource, localSources, onDiskClipSource, probeMedia, selectVariant, +} from "umtool-report-to-video/build-video"; +import { detectRoomSilences, detectSilence, lookWords, measureLoudnessWith, readLookSources, roomOfCut } from "umtool-report-to-video/cut-points"; +import { playWindow, transitionOf } from "umtool-report-to-video/deck"; +import { clipAudioOf } from "umtool-report-to-video/clip-audio"; +import { createLocalMedia, hasLocalMedia } from "umtool-report-to-video/local-media"; +import { loudnessGain, montageOn, parseIntegratedLoudness } from "umtool-report-to-video/montage"; +import { loudnessTargetOf } from "umtool-report-to-video/look"; +import { ROOM, clipRoom } from "umtool-report-to-video/room"; +import { renderCut, snapKnobs } from "umtool-report-to-video/snap"; +import { CACHE_DIR } from "../paths.mjs"; +import { channelsDirFor, cuesForSource, hasShadowChannels, readManifest } from "../projects/report.mjs"; + +/** Bump when what is cached changes shape. */ +const CACHE_VERSION = 1; +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Number(v.toFixed(3)); + +/** The cache directory (a function: the env is read when the route runs, as the e2e fixture sets it). */ +const cacheDir = () => path.join(/* turbopackIgnore: true */ CACHE_DIR, "cut-points"); + +/** A file's identity for a cache key: the path, its mtime and size. null when it is gone. */ +async function fileKey(file) { + const st = await stat(/* turbopackIgnore: true */ file).catch(() => null); + return st ? `${file}|${Math.round(st.mtimeMs)}|${st.size}` : null; +} + +/** + * A value computed once per key and kept on disk (tmp + rename), and in this + * process while it lives. A failed computation is not cached. + * + * @template T + * @param {string} kind + * @param {string} key + * @param {() => Promise<T>} make + * @returns {Promise<T>} + */ +const memo = new Map(); +async function cached(kind, key, make) { + const h = createHash("sha1").update(`${CACHE_VERSION}|${kind}|${key}`).digest("hex"); + if (memo.has(h)) return memo.get(h); + const file = path.join(/* turbopackIgnore: true */ cacheDir(), `${kind}-${h}.json`); + const p = (async () => { + const have = await readFile(/* turbopackIgnore: true */ file, "utf8").then((t) => JSON.parse(t), () => null); + if (have && have.key === key) return have.value; + const value = await make(); + try { + await mkdir(/* turbopackIgnore: true */ cacheDir(), { recursive: true }); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify({ key, value })); + await rename(/* turbopackIgnore: true */ tmp, file); + } catch { + // A cache that cannot be written is a slower route, not a broken one. + } + return value; + })(); + memo.set(h, p); + p.catch(() => memo.delete(h)); + if (memo.size > 2000) memo.delete(memo.keys().next().value); + return p; +} + +/** + * The manifest Play plays (the project's, or a take's, the default cut) and + * where the build would look for each clip's source. + * + * @param {{ id: string, dir: string }} project + * @param {string | null} take + */ +async function cutContext(project, take) { + let manifest = await readManifest(project.dir); + if (!manifest) throw new Error("this project has no video.manifest.json"); + let outRoot = path.join(/* turbopackIgnore: true */ project.dir, "out"); + if (take) { + const { resolveTakeManifest, takePlayDir } = await import("./takeManifest.mjs"); + manifest = (await resolveTakeManifest(project.dir, take)).manifest; + outRoot = path.join(/* turbopackIgnore: true */ takePlayDir(project.dir, take), "out"); + } + const selected = selectVariant(manifest, DEFAULT_VARIANT); + const render = selected.render ?? {}; + const provenance = selected.provenance ?? {}; + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + // A take renders into its own out/ (its clips-raw empty, as a rule: its + // sources are the corpus's windows or the project's cache); the project's + // raw cache is looked in after it, as the bench does. + const locals = [...new Set([outRoot, path.join(/* turbopackIgnore: true */ project.dir, "out")])].map((root) => + localSources({ rawDir: path.join(/* turbopackIgnore: true */ root, "clips-raw"), channelsDir, channelSlug: provenance.channelSlug ?? null }), + ); + const localMedia = createLocalMedia({ baseDir: project.dir, allowAbsolute: render.allowAbsoluteSrc === true }); + return { selected, render, provenance, channelsDir, locals, localMedia }; +} + +/** + * Each clip's render cut, in SOURCE seconds: + * + * cutStart / cutEnd where its segment starts and ends (`<id>.cut.json`'s + * `start`/`end`): the picture's span, room included + * snapped { start, end }: which edge moved to a silence + * sound [from, to] the sound is heard over, when room mutes + * an edge (else the whole segment) + * gainDb render.loudness's gain for the cut (none: absent) + * audio the clip's own audio knobs (clip-audio.mjs), absent when none + * playFrom / playTo the play window it was snapped from (deck.mjs playWindow) + * silences, fetchStart, window what was measured, so a client (the + * bench, dragging an edge) can snap a new cut itself + * with snap.mjs, on the same numbers + * montage true when render.montage cuts it (a phrase cut this + * does not model: its edges are snapped as a plain cut) + * missing no source on disk (nothing else is said) + * + * @param {{ id: string, dir: string }} project + * @param {{ take?: string | null, clips?: string[] | null, concurrency?: number }} [opts] + */ +export async function cutPointsFor(project, { take = null, clips = null, concurrency = 2 } = {}) { + const ctx = await cutContext(project, take); + const { selected, render } = ctx; + const timeline = (selected.timeline ?? []).filter((e) => e && typeof e.id === "string"); + const want = clips ? new Set(clips) : null; + const montage = montageOn(render); + const D = transitionOf(render); + const first = timeline[0]?.id ?? null; + const targets = timeline.filter((e) => e.type === "clip" && (hasLocalMedia(e) || (fin(e.start) && fin(e.end))) && (!want || want.has(e.id))); + const look = { promise: null }; + const out = new Array(targets.length); + let next = 0; + const work = async () => { + for (;;) { + const i = next++; + if (i >= targets.length) return; + const e = targets[i]; + try { + out[i] = await clipCutPoints(e, { ...ctx, montage, D, first: first === e.id, look, projectDir: project.dir }); + } catch (err) { + out[i] = { id: e.id, error: err instanceof Error ? err.message : String(err) }; + } + } + }; + await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, targets.length)) }, work)); + return { knobs: snapKnobs(render), transition: D, montage, clips: out }; +} + +/** One clip's render cut (cutPointsFor's row). */ +async function clipCutPoints(entry, ctx) { + const { render, locals, localMedia, montage, D } = ctx; + let src = null; + for (const local of locals) { + src = await onDiskClipSource(entry, null, render, local, { localMedia }); + if (src) break; + } + if (!src) return { id: entry.id, missing: true }; + const fk = await fileKey(src.path); + if (!fk) return { id: entry.id, missing: true }; + const { log: _log, ...disk } = src; + // The file's clock (a late-starting picture moves fetchStart), once per file. + const offset = await cached("offset", fk, async () => (await alignedClipSource(disk)).startOffset ?? 0); + const fetchStart = disk.fetchStart + offset; + const scan = disk.scan ? { from: Math.max(0, disk.scan.from - offset), to: disk.scan.to - offset } : null; + const k = snapKnobs(render); + const sil = await cached( + "silences", + `${fk}|${scan ? `${scan.from}-${scan.to}` : "whole"}|${k.silenceMinDur}|${k.silenceRelDb}`, + () => detectSilence(src.path, render, scan, { ffmpeg: FFMPEG_BIN }), + ); + const pw = playWindow(entry, render); + const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render }); + const { cutA, cutB } = cut.file; + let segA = cutA; + let segB = cutB; + /** @type {[number, number] | null} */ + let sound = null; + // Room at the edges: only with a join to make room for, never in a montage. + if (D > 0 && !montage && clipRoom(entry, render)) { + if (!ctx.look.promise) ctx.look.promise = readLookSources(ctx.projectDir); + const lookSrc = await ctx.look.promise; + const provenance = ctx.provenance; + const room = await roomOfCut({ + entry, render, D, first: ctx.first, fetchStart, cutA, cutB, file: src.path, + duration: await cached("duration", fk, async () => (await probeMedia(src.path)).duration ?? null), + words: (from, to) => lookWords(entry, provenance, lookSrc, from, to, { + channelsDir: ctx.channelsDir, + cues: async (e) => (await cuesForSource(ctx.projectDir, { video: e.video, channel: e.channel ?? provenance.channelSlug ?? null }, -Infinity, Infinity))?.cues ?? [], + }), + silences: (from, to) => detectRoomSilences(src.path, from, to, { ffmpeg: FFMPEG_BIN }), + }); + if (room) { + segA = room.plan.picA; + segB = room.plan.picB; + sound = room.record.sound; + } + } + const row = { + id: entry.id, + window: path.basename(src.path), + fetchStart: r3(fetchStart), + silences: sil, + playFrom: pw.from, + playTo: pw.to, + cutStart: r3(fetchStart + segA), + cutEnd: r3(fetchStart + segB), + snapped: cut.snapped, + ...(sound ? { sound } : {}), + ...(montage ? { montage: true } : {}), + }; + const target = loudnessTargetOf(render); + if (!montage && target != null) { + const from = cutA; + const to = sound ? sound[1] - fetchStart : cutB; + const measured = await cached("loudness", `${fk}|${from.toFixed(3)}-${to.toFixed(3)}`, () => + measureLoudnessWith(src.path, from, to, parseIntegratedLoudness, { ffmpeg: FFMPEG_BIN }), + ); + row.gainDb = loudnessGain(measured, target); + } + const audio = clipAudioOf(entry); + if (audio) row.audio = audio; + return row; +} + +/** Room's fade (seconds) at a muted edge, for the player: the build's afade length. */ +export const ROOM_FADE = ROOM.fade; diff --git a/umtool/lib/report/cutPoints.test.mjs b/umtool/lib/report/cutPoints.test.mjs @@ -0,0 +1,161 @@ +// The render's cut, from the render's code: a fixture RENDERED (build-video.mjs +// buildVideo) and read back through the cut-points route's function +// (cutPoints.mjs cutPointsFor) -- every clip's start, end, which edge +// snapped, room's audible span and the loudness gain must be the cut +// records', to the millisecond. And the route measures once: a second read is +// the cache, and a moved cut (the bench's edge drag) re-snaps on the cached +// silences without ffmpeg. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { readdir, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +// The corpus and the cache: set before the build (cues.mjs) and paths.mjs are loaded. +const CORPUS = mkdtempSync(path.join(os.tmpdir(), "cutpoints-corpus-")); +const CACHE = mkdtempSync(path.join(os.tmpdir(), "cutpoints-cache-")); +process.env.CHANNELS_DIR = CORPUS; +process.env.UMTOOL_CACHE_DIR = CACHE; + +const { buildVideo, setProgressMode } = await import("umtool-report-to-video/build-video"); +const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("umtool-report-to-video/brand"); +const { renderCut } = await import("umtool-report-to-video/snap"); +const { cutPointsFor } = await import("./cutPoints.mjs"); + +test.after(async () => { + await rm(CORPUS, { recursive: true, force: true }); + await rm(CACHE, { recursive: true, force: true }); +}); + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const CHANNEL = "synth"; +const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" }; +const RENDER = { + width: 320, height: 180, fps: 30, audioRate: 48000, audioChannels: 2, preset: "ultrafast", + headerHeight: 0, footerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, + fetchPad: 1, snapWindow: 0.8, silenceMinDur: 0.15, snapLead: 0.3, snapTail: 0.4, +}; + +const dir = path.join(CORPUS, CHANNEL, "data", "vid1"); +mkdirSync(dir, { recursive: true }); +writeFileSync(path.join(CORPUS, CHANNEL, "config.json"), JSON.stringify({ name: "Synth" })); +writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 20, uploadDate: "20240102", cues: [] })); +writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 20 })); + +/** + * A project cut from one 20 s window in out/clips-raw: a 440 Hz tone with + * gaps (pauses between "words") at 2.6-2.9, 5.4-5.9, 8.1-8.4, 11.2-11.6, + * 14.5-15.2 -- so every edge below has a pause within the snap window, and + * one (c3's start) has none. + */ +async function project(render = {}) { + const root = mkdtempSync(path.join(os.tmpdir(), "cutpoints-")); + mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); + const raw = path.join(root, "out", "clips-raw", "vid1_0.00-20.00.mp4"); + const gaps = [[2.6, 2.9], [5.4, 5.9], [8.1, 8.4], [11.2, 11.6], [14.5, 15.2]]; + const vol = gaps.map(([a, b]) => `volume=enable='between(t,${a},${b})':volume=0`).join(","); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=320x180:r=30:d=20", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=20", + "-filter_complex", `[1:a]${vol},volume=0.5[a]`, + "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, + ]); + assert.equal(r.status, 0, String(r.stderr)); + const manifestPath = path.join(root, "video.manifest.json"); + await writeFile(manifestPath, JSON.stringify({ + slug: "cutpoints", title: "Cut points", + provenance: { channelSlug: CHANNEL, channelsDir: CORPUS }, + render: { ...RENDER, ...render }, + timeline: [ + // A cut inside the extent (the lead-in before it): both edges snap. + { type: "clip", id: "c1", channel: CHANNEL, video: "vid1", start: 2, end: 6, cutStart: 3.3, cutEnd: 5.2, cite: 3, quote: "q" }, + // The extent alone: the start snaps back to 8.4 - lead, the end to 11.2 + tail. + { type: "clip", id: "c2", channel: CHANNEL, video: "vid1", start: 8.2, end: 11.0, cite: 9, quote: "q" }, + // No pause near its start (12.6): it stays; the end snaps into the long pause. + { type: "clip", id: "c3", channel: CHANNEL, video: "vid1", start: 12.6, end: 14.4, cite: 13, quote: "q" }, + ], + })); + return { root, manifestPath }; +} + +const quiet = () => setProgressMode(() => {}); +const record = async (root, id) => JSON.parse(await readFile(path.join(root, "out", "sourced", "segments", `${id}.cut.json`), "utf8")); + +async function agree(p, render) { + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, noXfade: render.transition === 0 } }); + const got = await cutPointsFor({ id: "fixture", dir: p.root }); + assert.equal(got.clips.length, 3); + for (const c of got.clips) { + const rec = await record(p.root, c.id); + assert.equal(c.cutStart, rec.start, `${c.id} start`); + assert.equal(c.cutEnd, rec.end, `${c.id} end`); + assert.deepEqual(c.snapped, rec.snapped, `${c.id} snapped`); + if (rec.room) assert.deepEqual(c.sound, rec.room.sound, `${c.id} room's sound`); + else assert.equal(c.sound, undefined, `${c.id} has no room`); + if (rec.loudness) assert.equal(c.gainDb, rec.loudness.gain, `${c.id} loudness gain`); + else assert.equal(c.gainDb, undefined); + } + return got; +} + +test("cut points: the route's edges are the render's cut records, edge for edge", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const p = await project({ transition: 0 }); + try { + const got = await agree(p, { transition: 0 }); + const byId = Object.fromEntries(got.clips.map((c) => [c.id, c])); + // Something actually moved, both ways: c1's start earlier than its play window, c2's end later. + assert.ok(byId.c1.cutStart < byId.c1.playFrom - 0.05, "c1's start snaps earlier"); + assert.ok(byId.c2.cutEnd > byId.c2.playTo + 0.05, "c2's end snaps later"); + assert.deepEqual(byId.c3.snapped, { start: false, end: true }); + // The client's snap (the bench's ghost marker) from the silences the route returned: the same edges. + for (const c of got.clips) { + const again = renderCut({ sil: c.silences, fetchStart: c.fetchStart, playFrom: c.playFrom, playTo: c.playTo, render: { ...RENDER, transition: 0 } }); + assert.equal(again.start, c.cutStart); + assert.equal(again.end, c.cutEnd); + } + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("cut points: with room at the edges and even loudness, the sound's span and the gain are the render's too", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const render = { transition: 0.4, room: { tail: true, head: true }, loudness: { target: -16 } }; + const p = await project(render); + try { + const got = await agree(p, render); + assert.ok(got.clips.some((c) => c.sound), "room widened at least one clip"); + assert.ok(got.clips.every((c) => typeof c.gainDb === "number"), "each clip has its gain"); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("cut points: measured once -- a second read and a moved cut reuse the cached silences", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const p = await project({ transition: 0 }); + try { + const t0 = performance.now(); + const first = await cutPointsFor({ id: "fixture", dir: p.root }); + const cold = performance.now() - t0; + const files = (await readdir(path.join(CACHE, "cut-points"))).filter((f) => f.startsWith("silences-")); + assert.ok(files.length >= 1, "the silences are on disk"); + // The cut moved (an edge edit): no new measurement, the edge follows. + const m = JSON.parse(await readFile(p.manifestPath, "utf8")); + m.timeline[0].cutEnd = 4.9; + await writeFile(p.manifestPath, JSON.stringify(m)); + const t1 = performance.now(); + const moved = await cutPointsFor({ id: "fixture", dir: p.root }); + const warm = performance.now() - t1; + assert.deepEqual((await readdir(path.join(CACHE, "cut-points"))).filter((f) => f.startsWith("silences-")).sort(), files.sort()); + assert.notEqual(moved.clips[0].playTo, first.clips[0].playTo); + assert.ok(warm < cold, `warm ${warm.toFixed(0)} ms < cold ${cold.toFixed(0)} ms`); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -187,10 +187,17 @@ import { } from "./look.mjs"; // Room at a clip's edges (release 36 lane E, render.room): the rule is pure, // in room.mjs; the build finds the words or silences and cuts the segment. +import { clipRoom, roomAudioFilter } from "./room.mjs"; +// Where a clip is cut (cut-points.mjs, snap.mjs): the silences, the snap, the +// room and the loudness measure -- one implementation, which umtool's +// cut-points route (the Play view, the bench's ghost edges) calls too. import { - ROOM, clipRoom, roomAudioFilter, roomPlan, speechStartFromSilences, speechStartFromWords, tailFromSilences, - tailFromWords, -} from "./room.mjs"; + detectRoomSilences as detectRoomSilencesWith, detectSilence as detectSilenceWith, lookWords, measureLoudnessWith, + readLookSources, roomOfCut, snapCut, +} from "./cut-points.mjs"; +// The snap itself (a montage's window snaps with it too), re-exported for the tests. +import { snap } from "./snap.mjs"; +export { snap }; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; import { pruneChromeFrames } from "./prune-frames.mjs"; @@ -974,43 +981,38 @@ async function startOffset(file) { /** fetchClip, with the window's clock aligned (startOffset): what every segment and tile cuts from. */ async function fetchClipAligned(entry, meta, render, local, opts) { - const r = await fetchClip(entry, meta, render, local, opts); - const off = await startOffset(r.path); - if (!off) return r; - EMIT("note", { message: `${entry.id}: ${path.basename(r.path)} starts ${off.toFixed(2)}s in — cut on its own clock` }); - return { - ...r, - fetchStart: r.fetchStart + off, - ...(r.scan ? { scan: { from: Math.max(0, r.scan.from - off), to: r.scan.to - off } } : {}), - startOffset: off, - }; + const r = await alignedClipSource(await fetchClip(entry, meta, render, local, opts)); + if (r.startOffset) EMIT("note", { message: `${entry.id}: ${path.basename(r.path)} starts ${r.startOffset.toFixed(2)}s in — cut on its own clock` }); + return r; } -async function fetchClip(entry, meta, render, local, opts) { - const { rawDir } = local; +/** + * A clip's source ON DISK, as the build cuts from it -- the file, the source + * second it starts at (`fetchStart`), the span silence detection measures + * (`scan`, none for a raw-cache window: measured whole) -- or null when only + * the network has it. `log` is the build's `fetch` event for it. The build's + * fetchClip asks this first; umtool's cut-points route asks only this (it + * never fetches), so both snap on the same file over the same span. + */ +export async function onDiskClipSource(entry, meta, render, local, opts = {}) { const { from, to } = fetchSpan(entry, render, opts); // A `src` clip IS its source: the whole file, [0, duration], beside the // manifest. Nothing is looked up and nothing is fetched. if (hasLocalMedia(entry)) { - const file = LOCAL.file(entry); + const file = (opts.localMedia ?? LOCAL).file(entry); const duration = entry.srcDuration ?? (await probeMedia(file)).duration; - EMIT("fetch", { - id: entry.id, video: clipLabel(entry), from, to: Number.isFinite(duration) ? Math.min(to, duration) : to, - cached: true, source: "src", - reuse: path.basename(file), local: file, window: [0, duration], - }); return { path: file, fetchStart: 0, cached: true, source: "src", scan: { from: Math.max(0, from), to: Number.isFinite(duration) ? Math.min(to, duration) : to }, + log: { + id: entry.id, video: clipLabel(entry), from, to: Number.isFinite(duration) ? Math.min(to, duration) : to, + cached: true, source: "src", + reuse: path.basename(file), local: file, window: [0, duration], + }, }; } - // Shared across variants, and deliberately so: this is the only expensive - // thing in a build, and the two cuts overlap almost entirely. - const name = rawWindowName(entry.video, from, to); - const dest = path.join(rawDir, name); - // ON DISK FIRST. The raw cache, then the editor's corpus windows, then a // saved whole source (sources.mjs). `--no-reuse` takes only the raw file // named for exactly this span. fetchStart is the SOURCE's start, not the @@ -1019,28 +1021,60 @@ async function fetchClip(entry, meta, render, local, opts) { // The audio tier only by audioUse's rule: before the network for a clip // with no picture to fetch; for one that should have a picture, only when // there is no network to ask AND --audio-fallback said so. + const name = rawWindowName(entry.video, from, to); const use = audioUse({ entry, meta, render, network: networkOn(opts), fallback: !!opts.audioFallback }); const hit = await local.resolve(entry, { from, to }, { exact: !!opts.noReuse, audio: use !== null }); + if (!hit) return null; // What the log calls it: a fallback is not the same fact as an audio-only clip. - const kind = hit?.kind === "audio" && use === "audio-fallback" ? "audio-fallback" : hit?.kind; - if (hit) { - EMIT("fetch", { + const kind = hit.kind === "audio" && use === "audio-fallback" ? "audio-fallback" : hit.kind; + return { + path: hit.path, + fetchStart: hit.windowStart, + cached: true, + source: kind, + // A whole container is hours long and silence detection decodes what it + // is given: give it the span a fetch would have produced, no more. + ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: to - hit.windowStart } }), + log: { id: entry.id, video: entry.video, from, to, cached: true, source: kind, ...(hit.kind !== "raw-cache" || hit.name !== name ? { reuse: hit.name } : {}), local: hit.path, window: [hit.windowStart, hit.windowEnd], ...(hit.height ? { height: hit.height } : {}), - }); - return { - path: hit.path, - fetchStart: hit.windowStart, - cached: true, - source: kind, - // A whole container is hours long and silence detection decodes what it - // is given: give it the span a fetch would have produced, no more. - ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: to - hit.windowStart } }), - }; + }, + }; +} + +/** + * A source's clock aligned (startOffset): a file whose picture starts late + * moves its `fetchStart` (and its `scan`) by the container's start_time. + * What fetchClipAligned does after a fetch; the cut-points route's too. + */ +export async function alignedClipSource(r) { + const off = await startOffset(r.path); + if (!off) return r; + return { + ...r, + fetchStart: r.fetchStart + off, + ...(r.scan ? { scan: { from: Math.max(0, r.scan.from - off), to: r.scan.to - off } } : {}), + startOffset: off, + }; +} + +async function fetchClip(entry, meta, render, local, opts) { + const { rawDir } = local; + const { from, to } = fetchSpan(entry, render, opts); + const disk = await onDiskClipSource(entry, meta, render, local, opts); + if (disk) { + const { log, ...r } = disk; + EMIT("fetch", log); + return r; } + + // Shared across variants, and deliberately so: this is the only expensive + // thing in a build, and the two cuts overlap almost entirely. + const name = rawWindowName(entry.video, from, to); + const dest = path.join(rawDir, name); if (opts.noNetwork) throw new Error(`--no-network set and no local source covers ${name}`); if (opts.skipFetch) throw new Error(`--skip-fetch set and no cached window covers ${name}`); @@ -1096,84 +1130,10 @@ async function fetchClip(entry, meta, render, local, opts) { return { path: dest, fetchStart: from, cached: false, source: "network" }; } -// Parse ffmpeg's silencedetect output into [{s, e}] intervals, in seconds -// relative to the start of the given file. -async function detectSilence(file, render, scan = null) { - 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 ?? "" })); - const log = stderr ?? ""; - - const out = []; - let open = null; - for (const line of 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; - } - } - return out; -} - -// Snap a desired cut to the nearest silence, so the clip begins and ends between -// words instead of through one. Returns the desired point unchanged when no -// silence is close enough — better a tight cut than a cut in the wrong place. -// -// How much of the pause is kept: 0.10 s before speech resumes, 0.18 s after it -// stops, unless the render says `snapLead` / `snapTail` -- and then never more -// than the pause holds, so a long one keeps its breath (room for the -// crossfade to fade over silence, not the last word) without reaching the -// next word. Exported for the tests. -export function snap(desired, intervals, kind, window, render = {}) { - let best = null; - for (const iv of intervals) { - // Starting: we want to resume just before speech does -> the silence's END. - // Ending: we want to stop just after speech does -> the silence's START. - const point = kind === "start" ? iv.e : iv.s; - const d = Math.abs(point - desired); - if (d > window) continue; - if (!best || d < best.d) best = { d, point, iv }; - } - if (!best) return { at: desired, snapped: false }; - const set = kind === "start" ? render.snapLead : render.snapTail; - let lead = kind === "start" ? -0.10 : 0.18; - if (Number.isFinite(set) && set >= 0) { - const room = best.iv.e - best.iv.s; - lead = (kind === "start" ? -1 : 1) * Math.min(set, room); - } - return { at: Math.max(0, best.point + lead), snapped: true }; -} +// The silences of a file, in its own seconds (cut-points.mjs detectSilence, +// with this build's ffmpeg). The snap that reads them is snap.mjs's `snap`, +// re-exported above for the tests. +const detectSilence = (file, render, scan = null) => detectSilenceWith(file, render, scan, { ffmpeg: FFMPEG }); // Encoder quality is manifest-driven so a cut can trade size for fidelity without // editing this file. Defaults reproduce the original hardcoded settings exactly. @@ -1265,11 +1225,12 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, entry, mont, raw, fetchStart, M: dirs.montage, render, provenance, sil, wantA, wantB, win, })); } - const a = mont ? mont.win.start : snap(wantA, sil, "start", win, render); - const b = mont ? mont.win.end : snap(wantB, sil, "end", win, render); - // Never let snapping invert or collapse the window. - const cutA = mont ? mont.win.cutA : Math.min(a.at, wantB - 1); - const cutB = mont ? mont.win.cutB : Math.max(b.at, cutA + 1); + // Snapped, and never inverted or collapsed (snap.mjs snapCut: the cut-points route's own). + const snapped = mont ? null : snapCut({ sil, wantA, wantB, render }); + const a = mont ? mont.win.start : snapped.a; + const b = mont ? mont.win.end : snapped.b; + const cutA = mont ? mont.win.cutA : snapped.cutA; + const cutB = mont ? mont.win.cutB : snapped.cutB; EMIT("snap", { id: entry.id, start: a.snapped, end: b.snapped, seconds: cutB - cutA }); // Room at the edges (render.room, room.mjs): the picture widened past the // snapped cut -- to the first silence and a join's length beyond, muted -- @@ -1619,69 +1580,12 @@ async function probeDims(file) { } /** - * What the captions 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. - */ -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. + * A clip's words, turns and speakers in [from, to] (source seconds): + * cut-points.mjs lookWords over this build's corpus and cue source (the + * captions and the room read the same words). */ -async function lookWordsFor(entry, provenance, look, from, to) { - 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) && FX_CHANNELS_DIR && entry.video) { - const slug = entry.channel ?? provenance?.channelSlug; - const key = `${slug}/${entry.video}`; - if (!look.transcripts.has(key)) { - look.transcripts.set(key, resolveVideoDir(FX_CHANNELS_DIR, 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 cues = fxWordsOf(await montageCues(entry, provenance), from - 0.05, to + 0.05).map(wordOf); - return { words: cues, turns, speakers, wordsFrom: "cues" }; +function lookWordsFor(entry, provenance, look, from, to) { + return lookWords(entry, provenance, look, from, to, { channelsDir: FX_CHANNELS_DIR, cues: (e) => montageCues(e, provenance) }); } /** @@ -1714,80 +1618,20 @@ async function segmentCaptions({ entry, provenance, look, render, outDir, from, // edges, and the plan its segment is cut by. /** - * 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. - */ -async function detectRoomSilences(file, from, to) { - 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 ?? "" })); - const out = []; - let open = null; - for (const line of String(stderr ?? "").split("\n")) { - const s = line.match(/silence_start:\s*(-?[\d.]+)/); - if (s) open = Number(s[1]) + a; - const e = line.match(/silence_end:\s*(-?[\d.]+)/); - if (e && open !== null) { - out.push({ s: open, e: Number(e[1]) + a }); - open = null; - } - } - if (open !== null) out.push({ s: open, e: to }); - return out; -} - -/** - * One clip's room (room.mjs's rule): where its sound stops and whether its - * head is muted, from its words -- the project's words.json, the corpus - * transcript, the cues (lookWordsFor) -- else silencedetect; 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. + * One clip's room (cut-points.mjs roomOfCut, room.mjs's rule): its words + * (lookWordsFor) else its silences, the plan its segment is cut by, and what + * its cut record says; its notes said here. Null when the clip has no room. */ async function segmentRoom({ entry, raw, render, provenance, look, D, first, fetchStart, cutA, cutB }) { - const room = clipRoom(entry, render); - if (!room) return null; - const head = room.head && !first; - if (!room.tail && !head) return null; + if (!clipRoom(entry, render)) return null; const media = await probeMedia(raw); - const got = look - ? await lookWordsFor(entry, provenance, look, fetchStart + cutA - 1, fetchStart + cutB + room.maxS + 1).catch(() => null) - : null; - const words = (got?.words ?? []).map((w) => ({ start: w.start - fetchStart, end: w.end - fetchStart })); - let via = words.length ? got.wordsFrom : "silence"; - let tail = room.tail && words.length ? tailFromWords(words, cutB, room) : null; - let speech = head && words.length ? speechStartFromWords(words, 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 && (!words.length || (via === "cues" && tail?.capped)); - if (detectTail || (head && !words.length)) { - const end = Math.min(media.duration ?? Infinity, cutB + room.maxS + 0.5); - const sil = await detectRoomSilences(raw, Math.min(cutA, cutB) - 0.5, end); - if (detectTail) { - tail = tailFromSilences(sil, cutB, room); - via = words.length ? `${via}+silence` : "silence"; - if (!tail.found) EMIT("note", { message: `${entry.id}: no silence within ${room.maxS} s of its end — its sound stops at the cut` }); - } - if (head && !words.length) speech = speechStartFromSilences(sil, cutA); - } - const plan = roomPlan({ cutA, cutB, D, soundEnd: tail ? tail.at : null, speechStart: head ? speech : null, duration: media.duration }); - if (plan.picA === cutA && plan.picB === cutB) return null; - if (tail?.capped) EMIT("note", { message: `${entry.id}: still talking ${room.maxS} s past its end — its sound fades there (render.room.maxS)` }); - for (const edge of plan.clamped) { - EMIT("note", { message: `${entry.id}: its ${edge === "tail" ? "tail" : "head"} room is clamped to ${path.basename(raw)}'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, - 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 } : {}), - }, - }; + const room = await roomOfCut({ + entry, render, D, first, fetchStart, cutA, cutB, duration: media.duration, file: raw, + words: (from, to) => (look ? lookWordsFor(entry, provenance, look, from, to) : Promise.resolve(null)), + silences: (from, to) => detectRoomSilencesWith(raw, from, to, { ffmpeg: FFMPEG }), + }); + for (const message of room?.notes ?? []) EMIT("note", { message }); + return room; } /** @@ -2001,11 +1845,7 @@ async function montageCheckSound({ entry, mont, raw, fetchStart, M, render, prov * null when it cannot be measured. */ export async function measureLoudness(raw, from, to) { - 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 parseIntegratedLoudness(stderr); + return measureLoudnessWith(raw, from, to, parseIntegratedLoudness, { ffmpeg: FFMPEG }); } /** The gain that brings a stretch of a source to the montage's loudness target: `{ measured, gain, target }`. */ diff --git a/umtool/report-to-video/cut-points.mjs b/umtool/report-to-video/cut-points.mjs @@ -0,0 +1,246 @@ +// 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<Array<{ start: number, end: number, text: string }>> }} 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<Array<{ s: number, e: number }>> }} 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 } : {}), + }, + }; +} diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -27,6 +27,7 @@ "./clip-blur": "./clip-blur.mjs", "./compose-chrome": "./compose-chrome.mjs", "./cues": "./cues.mjs", + "./cut-points": "./cut-points.mjs", "./deck": "./deck.mjs", "./drafts-review": "./drafts-review.mjs", "./factcheck": "./factcheck.mjs", @@ -52,6 +53,7 @@ "./resolve-windows": "./resolve-windows.mjs", "./room": "./room.mjs", "./shoot-page": "./shoot-page.mjs", + "./snap": "./snap.mjs", "./social": "./social.mjs", "./sources": "./sources.mjs", "./sync-report": "./sync-report.mjs", diff --git a/umtool/report-to-video/snap.mjs b/umtool/report-to-video/snap.mjs @@ -0,0 +1,116 @@ +// WHERE THE RENDER CUTS A CLIP, as arithmetic: a desired edge moved to the +// nearest silence (`snap`), and the two edges of a clip kept from inverting +// or collapsing (`snapCut`). Pure -- no ffmpeg, no fs -- so the build +// (build-video.mjs buildClipSegment), umtool's cut-points route (the Play view +// plays these edges) and the clip bench's ghost markers (drawn live while an +// edge is dragged, from the silences the route measured once) run ONE +// implementation, in the browser as on the server. The silences themselves are +// measured by cut-points.mjs `detectSilence`, the build's own. +// +// EVERYTHING HERE IS IN THE SOURCE FILE'S SECONDS (0 = the window's first +// sample, `fetchStart` in the recording) unless a name says `source`: that is +// the clock the build snaps on, and the same float arithmetic on the same +// clock is what makes the route's edges the build's to the millisecond. + +/** The render's defaults for the snap knobs (render.snapWindow, snapLead, snapTail, silence*). */ +export const SNAP_DEFAULTS = Object.freeze({ + snapWindow: 1.6, + silenceMinDur: 0.09, + silenceRelDb: 6, + lead: 0.10, + tail: 0.18, +}); + +/** + * Snap a desired cut to the nearest silence, so the clip begins and ends + * between words instead of through one. Returns the desired point unchanged + * when no silence is close enough -- better a tight cut than a cut in the + * wrong place. + * + * How much of the pause is kept: 0.10 s before speech resumes, 0.18 s after it + * stops, unless the render says `snapLead` / `snapTail` -- and then never more + * than the pause holds, so a long one keeps its breath (room for the + * crossfade to fade over silence, not the last word) without reaching the + * next word. + * + * @param {number} desired + * @param {Array<{ s: number, e: number }>} intervals the silences, file seconds + * @param {"start" | "end"} kind + * @param {number} window how far a silence may be (render.snapWindow) + * @param {{ snapLead?: number, snapTail?: number }} [render] + * @returns {{ at: number, snapped: boolean }} + */ +export function snap(desired, intervals, kind, window, render = {}) { + let best = null; + for (const iv of intervals) { + // Starting: we want to resume just before speech does -> the silence's END. + // Ending: we want to stop just after speech does -> the silence's START. + const point = kind === "start" ? iv.e : iv.s; + const d = Math.abs(point - desired); + if (d > window) continue; + if (!best || d < best.d) best = { d, point, iv }; + } + if (!best) return { at: desired, snapped: false }; + const set = kind === "start" ? render.snapLead : render.snapTail; + let lead = kind === "start" ? -SNAP_DEFAULTS.lead : SNAP_DEFAULTS.tail; + if (Number.isFinite(set) && set >= 0) { + const room = best.iv.e - best.iv.s; + lead = (kind === "start" ? -1 : 1) * Math.min(set, room); + } + return { at: Math.max(0, best.point + lead), snapped: true }; +} + +/** + * A clip's two edges as the render cuts them: each snapped (`snap`), then + * never inverted or collapsed -- the start at least a second before the + * desired end, the end at least a second after the start. + * + * @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any> }} o + * `wantA`/`wantB`: the play window's edges in the file's seconds + */ +export function snapCut({ sil, wantA, wantB, render = {} }) { + const win = render.snapWindow ?? SNAP_DEFAULTS.snapWindow; + const a = snap(wantA, sil, "start", win, render); + const b = snap(wantB, sil, "end", win, render); + const cutA = Math.min(a.at, wantB - 1); + const cutB = Math.max(b.at, cutA + 1); + return { win, a, b, cutA, cutB }; +} + +/** A source second as the cut record writes it (`<id>.cut.json`, three decimals). */ +export const recordSecond = (fetchStart, t) => Number((fetchStart + t).toFixed(3)); + +/** + * The render's cut of one clip in SOURCE seconds, from the silences of the + * file it is cut from: what `<id>.cut.json` records (`start`, `end`, + * `snapped`) for a clip with no room and no montage. `playFrom`/`playTo` are + * the play window (deck.mjs playWindow); `fetchStart` the file's first + * second in the recording. + * + * @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any> }} o + */ +export function renderCut({ sil, fetchStart, playFrom, playTo, render = {} }) { + const c = snapCut({ sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render }); + return { + start: recordSecond(fetchStart, c.cutA), + end: recordSecond(fetchStart, c.cutB), + snapped: { start: c.a.snapped, end: c.b.snapped }, + file: { cutA: c.cutA, cutB: c.cutB }, + }; +} + +/** + * The render knobs that move a snapped edge, and nothing else: what a cache of + * cut points is keyed by, so a change of any other knob reuses it. + * + * @param {Record<string, any>} render + */ +export function snapKnobs(render = {}) { + return { + snapWindow: render.snapWindow ?? SNAP_DEFAULTS.snapWindow, + silenceMinDur: render.silenceMinDur ?? SNAP_DEFAULTS.silenceMinDur, + silenceRelDb: render.silenceRelDb ?? SNAP_DEFAULTS.silenceRelDb, + snapLead: Number.isFinite(render.snapLead) ? render.snapLead : null, + snapTail: Number.isFinite(render.snapTail) ? render.snapTail : null, + }; +}