commit 5e72b9e58f0ff0f163b3d6b4861ef008c0d3f7e6
parent 50df6fe6a35522bf194fcee8b5e9fac7f5ad8984
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 16:01:28 -0400
report-to-video: render.room -- room at a clip's edges: the sound runs on to the first silence in its words (else silencedetect) and fades, the picture runs a join's length further muted, a muted head when speech starts at once; inside the source, captions and loudness on what is heard; absent = byte-identical
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
7 files changed, 748 insertions(+), 13 deletions(-)
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -172,6 +172,12 @@ import {
assDocument, assFilter, captionGeometry, captionLines, captionsOn, loudnessTargetOf, shortRender, validateLook,
verticalFilters,
} 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 {
+ ROOM, clipRoom, roomAudioFilter, roomPlan, speechStartFromSilences, speechStartFromWords, tailFromSilences,
+ tailFromWords,
+} from "./room.mjs";
// 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";
@@ -1217,28 +1223,42 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const cutA = mont ? mont.win.cutA : Math.min(a.at, wantB - 1);
const cutB = mont ? mont.win.cutB : Math.max(b.at, cutA + 1);
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 --
+ // the sound heard over [cutA, soundB] only. Null when off: the cut as ever.
+ const room = dirs.room && !mont && !dirs.short
+ ? await segmentRoom({ entry, raw, render, provenance, look: dirs.look, D: dirs.room.D, first: dirs.room.first === entry.id, fetchStart, cutA, cutB })
+ : null;
+ const segA = room ? room.plan.picA : cutA;
+ const segB = room ? room.plan.picB : cutB;
// Where in the SOURCE this segment really starts and ends, snapped: what a
// `muteFrom` (source seconds) is measured from at the join, long after this
- // function is gone (`--chrome-only` rebuilds no segment).
+ // function is gone (`--chrome-only` rebuilds no segment). With room, the
+ // picture's span; `room.sound` is the part that is heard.
const cutRecord = {
version: 1, id: entry.id, video: entry.video,
- start: Number((fetchStart + cutA).toFixed(3)), end: Number((fetchStart + cutB).toFixed(3)),
+ start: Number((fetchStart + segA).toFixed(3)), end: Number((fetchStart + segB).toFixed(3)),
snapped: { start: a.snapped, end: b.snapped },
+ ...(room ? { room: room.record } : {}),
};
// Even loudness for a cut that is not a montage (render.loudness, release
// 36): the cut as it will play, measured, one gain toward the target
// (montage.mjs loudnessGain), in the cut record. A montage levels with its
// own key; absent, nothing here runs.
if (!mont && loudnessTargetOf(render) != null) {
- level = await montageLevel(raw, cutA, cutB, { target: loudnessTargetOf(render) });
+ // With room, the audible part: the muted edges would only pull it down.
+ level = await montageLevel(raw, cutA, room ? room.plan.soundB : cutB, { target: loudnessTargetOf(render) });
cutRecord.loudness = level;
}
// The sound's graph: `[0:a]` levelled to `[al]` (an asplit first when a
// poster's waveform also reads it), else nothing and `0:a` as ever.
- const leveled = !mont && level != null;
+ // Room's fades (muted head and tail) after the gain.
+ const roomAf = room ? roomAudioFilter(room.plan) : "";
+ const soundChain = [!mont && level != null ? levelFilters(level.gain) : "", roomAf].filter(Boolean).join(",");
+ const leveled = !mont && soundChain !== "";
const levelParts = (posterParts) => (leveled
? [
- ...(posterParts ? [`[0:a]asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${levelFilters(level.gain)}[al]`] : [`[0:a]${levelFilters(level.gain)}[al]`]),
+ ...(posterParts ? [`[0:a]asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${soundChain}[al]`] : [`[0:a]${soundChain}[al]`]),
]
: (posterParts ?? []));
const audioMap = leveled ? "[al]" : "0:a";
@@ -1270,7 +1290,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// about it. Same cut, same audio map, same encode as every other segment.
// No picture in the source: a poster stands in for `[0:v]` (see above).
const media = await probeMedia(raw);
- const posterSeconds = Math.max(1 / render.fps, (media.duration != null ? Math.min(cutB, media.duration) : cutB) - cutA);
+ const posterSeconds = Math.max(1 / render.fps, (media.duration != null ? Math.min(segB, media.duration) : segB) - segA);
if (!media.hasVideo) EMIT("note", { message: `${entry.id}: no picture in ${path.basename(raw)} — a poster plays under its sound` });
const poster = (box, posterIdx) =>
media.hasVideo
@@ -1285,7 +1305,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
FFMPEG,
[
"-nostdin", "-v", "error", "-y",
- ...cutArgs(raw, cutA, cutB),
+ ...cutArgs(raw, segA, segB),
...(pst ? pst.input : []),
"-filter_complex", [
...levelParts(pst ? pst.parts : null),
@@ -1373,9 +1393,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// the main extends the output, and the fix for that (shortest=1) would instead
// truncate the clip to the strip. Ending early is free: overlay's default
// eof_action=repeat holds the strip's last frame, which is the parked bar.
- const barT = Math.max(0.2, cutB - cutA - 0.25);
+ const barT = Math.max(0.2, segB - segA - 0.25);
- const inputs = cutArgs(raw, cutA, cutB);
+ const inputs = cutArgs(raw, segA, segB);
let nextIdx = 1;
let footerIdx, markerIdx, barIdx, qrIdx;
if (hasFooter) {
@@ -1446,7 +1466,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
if (dirs.look && captionsOn(render)) {
const cap = await segmentCaptions({
entry, provenance, look: dirs.look, render, outDir,
- from: cutRecord.start, seconds: cutB - cutA, bottom: FH,
+ from: cutRecord.start, seconds: segB - segA, bottom: FH,
+ // With room: only the words heard -- none over a muted edge.
+ ...(room ? { audible: { from: fetchStart + cutA, to: fetchStart + room.plan.soundB } } : {}),
});
if (cap) {
parts.push(`${vOut}${cap.filter}[vc]`);
@@ -1567,8 +1589,10 @@ async function lookWordsFor(entry, provenance, look, from, to) {
* and the filter that burns it in, or null (a note) when the clip has no
* words. `from` is the source second the segment starts at.
*/
-async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, bottom }) {
- const src = await lookWordsFor(entry, provenance, look, from, from + seconds);
+async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, bottom, audible = null }) {
+ // `audible` (room at the edges): the words of that span only, and no line past its end.
+ const src = await lookWordsFor(entry, provenance, look, audible ? audible.from : from, audible ? audible.to : from + seconds);
+ if (audible) seconds = Math.min(seconds, audible.to - from);
if (!src.words.length) {
EMIT("note", { message: `${entry.id}: no words to caption — it plays without captions` });
return null;
@@ -1585,6 +1609,87 @@ async function segmentCaptions({ entry, provenance, look, render, outDir, from,
return { filter: assFilter(file, FONTS_DIR), lines: lines.length, wordsFrom: src.wordsFrom };
}
+// ---- room at the edges (render.room; release 36 lane E) --------------------
+// The build's side of room.mjs: the words (or the silences) around a clip's
+// 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.
+ */
+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;
+ 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 } : {}),
+ },
+ };
+}
+
/**
* A short's segment to <project>/shorts/<id>.mp4 (tmp + rename), with a
* record beside it (<id>.json: the cut, the crop, the size, the loudness,
@@ -5304,6 +5409,13 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
EMIT("note", { message: "render.montage: the cut styles are in the segments, so they are joined with hard cuts (render.transition is not used)" });
}
const D = opts.noXfade || montage || (render.transition ?? 0.5) === 0 ? 0 : render.transition ?? 0.5;
+ // Room at the clips' edges (render.room or a clip's own room): only with a
+ // join to make room for, never in a montage or a short. Its words are read
+ // where the captions' are (readLookSources).
+ if (D > 0 && !montage && !opts.short && manifest.timeline.some((e) => e?.type === "clip" && clipRoom(e, render))) {
+ dirs.room = { D, first: manifest.timeline[0]?.id ?? null };
+ dirs.look ??= await readLookSources(manifestDir);
+ }
// The montage's plan across the WHOLE cut (a clip's place, its year, its
// ramp cap), so an `--only` rebuild cuts a clip as the full build would.
// A clip with no date of its own takes its record's upload date.
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -89,6 +89,7 @@ import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { validateFxEntries } from "./fx.mjs";
import { validateTransitionStyle } from "./transition.mjs";
import { validateLook } from "./look.mjs";
+import { roomWindowWarnings } from "./room.mjs";
import { qrUrlFor } from "./render-cards.mjs";
import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs";
import { validatePodcast } from "./build-podcast.mjs";
@@ -305,6 +306,8 @@ export function lintManifest(manifest, {
// The social posts and the video's URL are not the video's: a problem there
// is said, never a refusal (release 29 G2's review).
warnings.push(...publishWarnings(whole));
+ // Room at the clips' edges (render.room): a fetched window it can reach past.
+ warnings.push(...roomWindowWarnings(only ? { ...manifest, timeline: (manifest.timeline ?? []).filter((e) => e?.id === only) } : manifest));
for (const { where, src } of imageSrcsOf(manifest, { only })) {
if (path.isAbsolute(src) || src.startsWith("~")) {
diff --git a/umtool/report-to-video/look.mjs b/umtool/report-to-video/look.mjs
@@ -23,6 +23,8 @@
// other #F6F1E6 paper bottom centre (a third voice, or a word heard in no turn)
// Black outline (3 px at 1080p), soft shadow. ASS colours are &HAABBGGRR.
+import { validateRoom } from "./room.mjs";
+
export const CAPTION_STYLES = Object.freeze(["speakers"]);
export const CAPTION_SIZES = Object.freeze(["m", "l"]);
export const CAPTION_ROLES = Object.freeze(["host", "subject", "other"]);
@@ -146,7 +148,8 @@ export function validateVertical(manifest) {
/** All of the look's keys: the build's validators and the lint call this. */
export function validateLook(manifest) {
- return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest)];
+ // render.room and a clip's room (room.mjs, release 36 lane E) are part of the look.
+ return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest)];
}
// ---------------------------------------------------------------------------
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -44,6 +44,7 @@
"./prune-frames": "./prune-frames.mjs",
"./render-cards": "./render-cards.mjs",
"./resolve-windows": "./resolve-windows.mjs",
+ "./room": "./room.mjs",
"./shoot-page": "./shoot-page.mjs",
"./social": "./social.mjs",
"./sources": "./sources.mjs",
diff --git a/umtool/report-to-video/room-render.test.mjs b/umtool/report-to-video/room-render.test.mjs
@@ -0,0 +1,205 @@
+// Room at a clip's edges (render.room, release 36 lane E), rendered for real:
+// a clip's sound runs on to the end of its words and is silent after it while
+// its picture runs the join's length further; the next clip's picture starts
+// a join's length early, muted; the joined cut is the segments' sum less the
+// joins, with each clip's sound still on its picture; captions stop at the
+// silence point; loudness is measured on what is heard; with no words the
+// silence is found in the sound. Absent, null or with neither edge on, the
+// render is byte for byte what it was.
+//
+// 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 { readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+// The corpus the build reads metadata and cues from: set before build-video
+// (cues.mjs) is loaded, so it is this file's own.
+const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-room-corpus-"));
+process.env.CHANNELS_DIR = CORPUS;
+
+const { buildVideo, measureLoudness, probeDuration, setProgressMode } = await import("./build-video.mjs");
+const { lintManifest } = await import("./lint.mjs");
+const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs");
+
+test.after(() => rm(CORPUS, { recursive: true, force: true }));
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0)
+ && /\bass\b/.test(String(spawnSync("ffmpeg", ["-hide_banner", "-filters"]).stdout));
+const FPS = 30;
+const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" };
+const RENDER = {
+ width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0.4,
+ headerHeight: 0, footerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE,
+ fetchPad: 0, snapWindow: 0.05, silenceMinDur: 0.1,
+};
+const CHANNEL = "synth";
+
+// vid1 has cues (one long one); vid2 an empty cue list.
+for (const [video, cues] of [["vid1", true], ["vid2", false]]) {
+ const dir = path.join(CORPUS, CHANNEL, "data", video);
+ 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: video, title: "Synthetic", duration: 12, uploadDate: "20240102", cues: cues ? [{ start: 0.2, end: 11.8, text: "filler words only and more filler words here" }] : [] }));
+ writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: video, title: "Synthetic", duration: 12 }));
+}
+
+// c1's words run on past its end (4.0) to 4.75, then a gap; c2's first word
+// is 0.05 s after its start (6.0); nothing near c2's end (9.0).
+const WORDS = [[1.1, 1.5], [2, 2.4], [3.5, 3.9], [3.95, 4.3], [4.4, 4.75], [5.5, 5.8], [6.05, 6.4], [6.6, 7], [8, 8.5]]
+ .map(([start, end], i) => ({ w: `w${i}`, start, end }));
+
+/**
+ * A project: two clips of `video` (c1 1-4 s, c2 6-9 s), cut from one window
+ * in out/clips-raw (12 s, a grey picture, a 440 Hz tone -- silent over
+ * `gap` when given), with reactions.json + words.json for vid1 when `words`.
+ */
+async function project(render = {}, { video = "vid1", words = true, gap = null, clips = [{}, {}] } = {}) {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-room-"));
+ mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true });
+ const raw = path.join(root, "out", "clips-raw", `${video}_0.00-12.00.mp4`);
+ const vol = gap ? `volume=enable='between(t,${gap[0]},${gap[1]})':volume=0,volume=0.5` : "volume=0.5";
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=320x180:r=${FPS}:d=12`,
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12",
+ "-filter_complex", `[1:a]${vol}[a]`,
+ "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ if (words) {
+ await writeFile(path.join(root, "reactions.json"), JSON.stringify({
+ version: 1,
+ source: { channel: CHANNEL, video, duration: 12, words: "words.json" },
+ speakers: [{ index: 0, role: "host", label: "Host", how: "auto" }, { index: 1, role: "subject", label: "Subject", how: "auto" }],
+ turns: [{ start: 0, end: 12, speaker: 1 }],
+ laughs: [], moments: [], proposals: [],
+ }));
+ await writeFile(path.join(root, "words.json"), JSON.stringify({ words: WORDS }));
+ }
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "room", title: "Room",
+ provenance: { channelSlug: CHANNEL, channelsDir: CORPUS },
+ render: { ...RENDER, ...render },
+ timeline: [
+ { type: "clip", id: "c1", channel: CHANNEL, video, start: 1, end: 4, cite: 1, quote: "q", ...clips[0] },
+ { type: "clip", id: "c2", channel: CHANNEL, video, start: 6, end: 9, cite: 6, quote: "q", ...clips[1] },
+ ],
+ }));
+ return { root, manifestPath, raw, seg: (id) => path.join(root, "out", "sourced", "segments", `${id}.mp4`) };
+}
+
+const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0];
+const quiet = () => setProgressMode(() => {});
+const record = async (p, id) => JSON.parse(await readFile(p.seg(id).replace(/\.mp4$/, ".cut.json"), "utf8"));
+
+/** The RMS of a file's sound over [a, b] (s), mono 8 kHz, 16-bit. */
+function rms(file, a, b) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 26 });
+ const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, Math.floor(r.stdout.length / 2));
+ let sum = 0;
+ let n = 0;
+ for (let i = Math.floor(a * 8000); i < Math.min(pcm.length, Math.floor(b * 8000)); i += 1) {
+ sum += pcm[i] * pcm[i];
+ n += 1;
+ }
+ return n ? Math.sqrt(sum / n) : 0;
+}
+const LOUD = 1500;
+const SILENT = 30;
+const near = (a, b, tol, what) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`);
+
+test("render: without room (absent, null, or neither edge on) the cut is byte for byte the same", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ const ps = [await project({}), await project({ room: null }), await project({ room: { tail: false, head: false } })];
+ try {
+ for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ for (const f of ["room.mp4", "sourced/segments/c1.mp4", "sourced/segments/c2.mp4", "sourced/segments/c1.cut.json", "sourced/segments/c2.cut.json"]) {
+ const sums = ps.map((p) => md5(path.join(p.root, "out", f)));
+ assert.equal(new Set(sums).size, 1, `${f}: ${sums.join(" ")}`);
+ }
+ assert.equal((await record(ps[0], "c1")).room, undefined);
+ } finally {
+ for (const p of ps) await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("render: the sound runs to the end of the words and is silent after; the picture runs D + pad past it; a muted head; sum − joins", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ const p = await project({ room: { tail: true, head: true }, loudness: { target: -16 }, captions: { style: "speakers" } });
+ try {
+ const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ const c1 = await record(p, "c1");
+ const c2 = await record(p, "c2");
+ // c1: the first clip, so no head; its words run to 4.75; picture to 4.75 + 0.4 + 0.1.
+ assert.deepEqual([c1.start, c1.end], [1, 5.25]);
+ assert.deepEqual(c1.room.sound, [1, 4.75]);
+ assert.equal(c1.room.via, "words.json");
+ assert.equal(c1.room.head, 0);
+ assert.equal(c1.room.tail, 0.5);
+ // c2: speech 0.05 s after its start -> 0.4 s of muted head; no word near its end.
+ assert.deepEqual([c2.start, c2.end], [5.6, 9.5]);
+ assert.deepEqual(c2.room.sound, [6, 9]);
+ assert.equal(c2.room.head, 0.4);
+ const d1 = await probeDuration(p.seg("c1"), FPS);
+ const d2 = await probeDuration(p.seg("c2"), FPS);
+ near(d1, 4.25, 1 / FPS + 1e-6, "c1's length");
+ near(d2, 3.9, 1 / FPS + 1e-6, "c2's length");
+ // The tail: heard to the silence point (3.75 s into c1), silent after it.
+ assert.ok(rms(p.seg("c1"), 3.2, 3.7) > LOUD, "c1 heard before the silence point");
+ assert.ok(rms(p.seg("c1"), 3.85, 4.2) < SILENT, `c1 silent after it: ${rms(p.seg("c1"), 3.85, 4.2)}`);
+ // The head: silent until the cut's start (0.4 s into c2), heard after.
+ assert.ok(rms(p.seg("c2"), 0, 0.33) < SILENT, "c2's head muted");
+ assert.ok(rms(p.seg("c2"), 0.45, 1) > LOUD, "c2 heard from its cut");
+ // Loudness measured on what is heard.
+ near(await measureLoudness(p.seg("c1"), 0, 3.7), -16, 0.6, "c1's audible loudness");
+ // Captions stop at the silence point: c1's last line ends by 3.75 s.
+ const ass = await readFile(p.seg("c1").replace(/\.mp4$/, ".captions.ass"), "utf8");
+ const ends = ass.split("\n").filter((l) => l.startsWith("Dialogue:")).map((l) => {
+ const [h, m, s] = l.split(",")[2].split(":").map(Number);
+ return h * 3600 + m * 60 + s;
+ });
+ assert.ok(ends.length > 0 && Math.max(...ends) <= 3.751, `caption ends ${ends}`);
+ // The cut: the sum less one join; the join plays over silence; c2's sound on its picture.
+ const total = await probeDuration(r.out, FPS);
+ near(total, d1 + d2 - 0.4, 2 / FPS, "the cut's length");
+ const join = d1 - 0.4; // c2 starts here in the cut
+ assert.ok(rms(r.out, join + 0.02, d1 - 0.1) < SILENT, "the join is quiet");
+ assert.ok(rms(r.out, join + 0.5, join + 1) > LOUD, "c2 heard from its cut, in the cut");
+ assert.ok(rms(r.out, 2.5, 3.6) > LOUD, "c1 heard in the cut");
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("render: no words -- the silence is found in the sound; a clip's room: false keeps its edge", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ // vid2 has no cues and no words file; its tone is silent 4.6-5.6 s.
+ const p = await project({ room: { tail: true, head: true } }, { video: "vid2", words: false, gap: [4.6, 5.6], clips: [{}, { room: false }] });
+ try {
+ await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ const c1 = await record(p, "c1");
+ assert.equal(c1.room.via, "silence");
+ near(c1.room.sound[1], 4.6, 0.05, "c1's sound stops where the silence starts");
+ near(c1.end, c1.room.sound[1] + 0.5, 0.002, "and its picture 0.5 s later");
+ const c2 = await record(p, "c2");
+ assert.equal(c2.room, undefined);
+ assert.deepEqual([c2.start, c2.end], [6, 9]);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("the lint: a fetched window the room can reach past; validators refuse a bad room", () => {
+ const m = {
+ slug: "x", title: "x", provenance: { channelSlug: CHANNEL }, render: { ...RENDER, fetchPad: 1, room: { tail: true } },
+ timeline: [{ type: "clip", id: "c1", video: "v", start: 1, end: 4 }],
+ };
+ const lint = lintManifest(m, { manifestDir: os.tmpdir() });
+ assert.ok(lint.warnings.some((w) => /c1: its room can run 3 s past the cut but a fetched window ends 1 s after it/.test(w)), lint.warnings.join("; "));
+ const bad = lintManifest({ ...m, render: { ...m.render, room: { tail: "yes" } } }, { manifestDir: os.tmpdir() });
+ assert.ok(bad.errors.some((x) => /render\.room\.tail must be true or false/.test(x)), bad.errors.join("; "));
+});
diff --git a/umtool/report-to-video/room.mjs b/umtool/report-to-video/room.mjs
@@ -0,0 +1,283 @@
+// ROOM AT A CLIP'S EDGES (release 36 lane E): a join plays over quiet picture,
+// never over the end of a sentence or the start of the next one.
+//
+// render.room {tail?: true, head?: true, minGap?: 0.35, maxS?: 2.5}
+// clip.room false (no room for this clip), or {tail?: boolean, head?: boolean}
+// (that edge for this clip, whatever the cut says)
+//
+// An edge is on when its key is `true` (the clip's key, else the cut's).
+// Absent (or null, or neither edge on) = off, and the render is byte for byte
+// what it was. Room needs a join: with `render.transition` 0 (or a montage,
+// or a short) it does nothing.
+//
+// THE RULE, in the source's seconds (D = render.transition):
+//
+// TAIL From the cut's end, the SOUND runs on to the first silence: the end
+// of the run of words that crosses the cut's end or starts within
+// `minGap` after it, the run stopping at the first gap between two
+// words of at least `minGap`; never more than `maxS` past the cut's
+// end. A 60 ms fade starts there. The PICTURE then keeps going, muted,
+// for D + 0.1 s, so the join's D seconds lie wholly over quiet video.
+// HEAD When speech starts within D of the cut's start (a word crosses it or
+// begins less than D after it), the picture starts D earlier, muted,
+// and the sound fades in over the 60 ms that end at the cut's start.
+// Only when something comes before the clip in the cut.
+//
+// The words: the project's words.json when the clip is from the recording
+// reactions.json describes, else the corpus transcript's whisper words,
+// else the cues spread over their words. When there are none -- or the
+// cues' run reaches the cap, which says the cues abut rather than that
+// anyone talks on -- silencedetect on the source (-35 dB, 0.3 s): the
+// silence the cut's end is in (the sound stops there), else the next one
+// to start within maxS; no silence found leaves the sound at the cut's end.
+//
+// Every extension stays inside the file the clip is cut from: a saved
+// whole video has room to spare, a fetched window (the extent plus the
+// fetch pad) clamps it -- the build says so, and the lint warns when the
+// room can reach past the window.
+
+export const ROOM = Object.freeze({
+ /** A gap between two words this long (s) is the silence the sound stops at. */
+ minGap: 0.35,
+ /** The sound never runs more than this (s) past the cut's end. */
+ maxS: 2.5,
+ /** The fade at the silence point, and the fade in at a muted head (s). */
+ fade: 0.06,
+ /** Muted picture past D, so the fade is done before the join begins (s). */
+ pad: 0.1,
+ /** silencedetect, when there are no words: noise floor (dB) and least length (s). */
+ detectDb: -35,
+ detectD: 0.3,
+});
+export const ROOM_EDGES = Object.freeze(["tail", "head"]);
+const MIN_GAP = [0.1, 2];
+const MAX_S = [0, 10];
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const q = (v) => JSON.stringify(v);
+const r3 = (n) => Math.round(n * 1000) / 1000;
+
+/** Does the cut's render block turn room on for either edge? */
+export const roomOn = (render) => isObj(render?.room) && (render.room.tail === true || render.room.head === true);
+
+/**
+ * One clip's room: `{tail, head, minGap, maxS}` with at least one edge on, or
+ * null. The clip's `room` (false, or per-edge booleans) beats the cut's.
+ */
+export function clipRoom(entry, render) {
+ const r = isObj(render?.room) ? render.room : null;
+ const c = entry?.room;
+ if (c === false) return null;
+ const edge = (k) => (isObj(c) && typeof c[k] === "boolean" ? c[k] : r?.[k] === true);
+ const tail = edge("tail");
+ const head = edge("head");
+ if (!tail && !head) return null;
+ return {
+ tail,
+ head,
+ minGap: num(r?.minGap) ? r.minGap : ROOM.minGap,
+ maxS: num(r?.maxS) ? r.maxS : ROOM.maxS,
+ };
+}
+
+/** `render.room` and every clip's `room`: each problem in a sentence naming the key. */
+export function validateRoom(manifest) {
+ const render = manifest?.render ?? {};
+ const errors = [];
+ const room = render.room;
+ if (room !== undefined && room !== null) {
+ if (!isObj(room)) errors.push(`render.room must be an object ({tail: true, head: true}) or absent, not ${q(room)}`);
+ else {
+ for (const k of Object.keys(room)) {
+ if (!["tail", "head", "minGap", "maxS"].includes(k)) errors.push(`render.room.${k} is not a setting here (tail, head, minGap, maxS)`);
+ }
+ for (const k of ROOM_EDGES) {
+ if (room[k] !== undefined && typeof room[k] !== "boolean") errors.push(`render.room.${k} must be true or false, not ${q(room[k])}`);
+ }
+ if (room.minGap !== undefined && (!num(room.minGap) || room.minGap < MIN_GAP[0] || room.minGap > MIN_GAP[1])) {
+ errors.push(`render.room.minGap must be seconds from ${MIN_GAP[0]} to ${MIN_GAP[1]}, not ${q(room.minGap)}`);
+ }
+ if (room.maxS !== undefined && (!num(room.maxS) || room.maxS < MAX_S[0] || room.maxS > MAX_S[1])) {
+ errors.push(`render.room.maxS must be seconds from ${MAX_S[0]} to ${MAX_S[1]}, not ${q(room.maxS)}`);
+ }
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.room does not combine with render.montage (a montage cuts to its phrases)");
+ }
+ }
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.room === undefined) return;
+ const who = `timeline[${i}] (${e?.id ?? "?"}).room`;
+ if (e?.type !== "clip") errors.push(`${who}: only a clip has room at its edges`);
+ else if (e.room === false || e.room === null) return;
+ else if (!isObj(e.room)) errors.push(`${who} must be false or {tail?, head?}, not ${q(e.room)}`);
+ else {
+ for (const [k, v] of Object.entries(e.room)) {
+ if (!ROOM_EDGES.includes(k)) errors.push(`${who}.${k} is not a setting here (tail, head)`);
+ else if (typeof v !== "boolean") errors.push(`${who}.${k} must be true or false, not ${q(v)}`);
+ }
+ }
+ });
+ return errors;
+}
+
+/** Timed words, in time order (any of the transcribers' keys for the text is fine; only times are read). */
+function timed(words) {
+ return (Array.isArray(words) ? words : [])
+ .map((w) => ({ start: Number(w?.start), end: Number(w?.end) }))
+ .filter((w) => Number.isFinite(w.start) && Number.isFinite(w.end) && w.end >= w.start)
+ .sort((a, b) => a.start - b.start);
+}
+
+/**
+ * Where a clip's SOUND stops, from its words: the end of the run of words
+ * that crosses `cutEnd` or starts within `minGap` after it, the run ending at
+ * the first gap of at least `minGap`; never more than `maxS` past `cutEnd`.
+ * `cutEnd` itself when no word is in reach.
+ *
+ * @returns {{ at: number, extended: boolean, capped: boolean }}
+ */
+export function tailFromWords(words, cutEnd, { minGap = ROOM.minGap, maxS = ROOM.maxS } = {}) {
+ const ws = timed(words);
+ const i = ws.findIndex((w) => w.end > cutEnd);
+ if (i < 0 || ws[i].start >= cutEnd + minGap) return { at: cutEnd, extended: false, capped: false };
+ let end = ws[i].end;
+ for (let j = i + 1; j < ws.length; j += 1) {
+ if (ws[j].start - end >= minGap) break;
+ end = Math.max(end, ws[j].end);
+ }
+ const cap = cutEnd + maxS;
+ return { at: r3(Math.min(end, cap)), extended: end > cutEnd, capped: end > cap };
+}
+
+/** Where speech starts at a clip's head, from its words: the first word not over before `cutStart` (Infinity: none). */
+export function speechStartFromWords(words, cutStart) {
+ const w = timed(words).find((x) => x.end > cutStart);
+ return w ? Math.max(cutStart, w.start) : Infinity;
+}
+
+/**
+ * The same two answers from silences (`[{s, e}]`, silencedetect's), when
+ * there are no words: the sound stops at `cutEnd` when it is in a silence,
+ * else where the next silence within `maxS` begins; no silence in reach
+ * leaves it at `cutEnd` (nothing says where the speech ends).
+ *
+ * @returns {{ at: number, extended: boolean, capped: boolean, found: boolean }}
+ */
+export function tailFromSilences(silences, cutEnd, { maxS = ROOM.maxS } = {}) {
+ const sil = (Array.isArray(silences) ? silences : []).filter((x) => num(x?.s) && num(x?.e)).sort((a, b) => a.s - b.s);
+ if (sil.some((x) => x.s <= cutEnd && x.e > cutEnd)) return { at: cutEnd, extended: false, capped: false, found: true };
+ const next = sil.find((x) => x.s > cutEnd && x.s <= cutEnd + maxS);
+ if (!next) return { at: cutEnd, extended: false, capped: false, found: false };
+ return { at: r3(next.s), extended: true, capped: false, found: true };
+}
+
+/** Where speech starts at a clip's head, from silences: the end of the silence `cutStart` is in, else `cutStart`. */
+export function speechStartFromSilences(silences, cutStart) {
+ const hit = (Array.isArray(silences) ? silences : []).find((x) => num(x?.s) && num(x?.e) && x.s <= cutStart && x.e > cutStart);
+ return hit ? hit.e : cutStart;
+}
+
+/**
+ * The segment a clip with room plays, in the seconds of the file it is cut
+ * from (`cutA`/`cutB`: the snapped cut; `soundEnd`: tailFromWords' or
+ * tailFromSilences' `at`, or null with the tail off; `speechStart`: where
+ * speech begins, or null with the head off; `duration`: the file's length,
+ * when known). The picture is [picA, picB]; the sound is heard over
+ * [cutA, soundB] (muted before and after, with the fades).
+ *
+ * @returns {{ picA: number, picB: number, soundA: number, soundB: number, head: number, tail: number,
+ * clamped: Array<"head" | "tail"> }} head/tail: the muted seconds before cutA / after soundB
+ */
+export function roomPlan({ cutA, cutB, D, soundEnd = null, speechStart = null, duration = null }) {
+ const len = num(duration) && duration > 0 ? duration : Infinity;
+ const clamped = [];
+ let picA = cutA;
+ if (speechStart !== null && speechStart < cutA + D) {
+ picA = cutA - D;
+ if (picA < 0) {
+ picA = 0;
+ clamped.push("head");
+ }
+ }
+ let soundB = soundEnd === null ? cutB : Math.max(cutB, soundEnd);
+ let picB = soundEnd === null ? cutB : soundB + D + ROOM.pad;
+ if (picB > len) {
+ picB = len;
+ soundB = Math.min(soundB, len);
+ clamped.push("tail");
+ }
+ picA = r3(picA);
+ picB = r3(picB);
+ soundB = r3(soundB);
+ return { picA, picB, soundA: cutA, soundB, head: r3(cutA - picA), tail: r3(picB - soundB), clamped };
+}
+
+/**
+ * The sound's filters for a plan, in the segment's own clock (0 = picA): a
+ * fade in ending at the cut's start when the head is muted, a fade out from
+ * the silence point when the tail is. "" when neither edge moved.
+ */
+export function roomAudioFilter(plan, { fade = ROOM.fade } = {}) {
+ const parts = [];
+ if (plan.head > 0) parts.push(`afade=t=in:st=${Math.max(0, plan.head - fade).toFixed(3)}:d=${fade}`);
+ if (plan.picB > plan.soundB) parts.push(`afade=t=out:st=${(plan.soundB - plan.picA).toFixed(3)}:d=${fade}`);
+ return parts.join(",");
+}
+
+/**
+ * What the clip editor's strip shades for one clip (its unsnapped cut, the
+ * neighbourhood's words or cues): the muted head [a, b] and the muted tail
+ * [soundEnd, end], each null when that edge is off or does not move. The
+ * build snaps the cut first, so this is the rule on the cut as drawn.
+ *
+ * @param {{ cutStart: number, cutEnd: number, room: { tail: boolean, head: boolean, minGap?: number, maxS?: number } | null,
+ * D: number, words?: Array<{ start: number, end: number }> | null, cues?: Array<{ start: number, end: number }> | null }} o
+ * @returns {{ head: number[] | null, tail: number[] | null, soundEnd: number | null }}
+ */
+export function roomShade({ cutStart, cutEnd, room, D, words = null, cues = null }) {
+ if (!room || !(D > 0)) return { head: null, tail: null, soundEnd: null };
+ const ws = Array.isArray(words) && words.length ? words : Array.isArray(cues) ? cues : [];
+ let tail = null;
+ let soundEnd = null;
+ if (room.tail) {
+ soundEnd = ws.length ? tailFromWords(ws, cutEnd, room).at : cutEnd;
+ tail = [soundEnd, r3(soundEnd + D + ROOM.pad)];
+ }
+ let head = null;
+ if (room.head && (!ws.length || speechStartFromWords(ws, cutStart) < cutStart + D)) head = [r3(Math.max(0, cutStart - D)), cutStart];
+ return { head, tail, soundEnd };
+}
+
+/**
+ * The lint's word on a clip's room: a fetched window (the extent plus the
+ * fetch pad) that the room can reach past -- the build clamps it there; a
+ * saved whole video would not.
+ */
+export function roomWindowWarnings(manifest) {
+ const render = manifest?.render ?? {};
+ const D = render.transition ?? 0.5;
+ const out = [];
+ const timeline = manifest?.timeline ?? [];
+ const anyRoom = timeline.some((e) => e?.type === "clip" && clipRoom(e, render));
+ if (!anyRoom) return out;
+ if (!(D > 0)) {
+ out.push("render.room: the cut has no transition (render.transition 0), so there is no join to make room for -- room does nothing");
+ return out;
+ }
+ const pad = render.fetchPad ?? 3.0;
+ for (const e of timeline) {
+ if (e?.type !== "clip") continue;
+ const room = clipRoom(e, render);
+ if (!room || !num(e.start) || !num(e.end)) continue;
+ const cutStart = num(e.cutStart) ? e.cutStart : e.start;
+ const cutEnd = num(e.cutEnd) ? e.cutEnd : e.end;
+ const reach = cutEnd + room.maxS + D + ROOM.pad;
+ if (room.tail && reach > e.end + pad + 1e-6) {
+ out.push(`${e.id}: its room can run ${r3(reach - cutEnd)} s past the cut but a fetched window ends ${r3(e.end + pad - cutEnd)} s after it -- a fetched source clamps the tail there (a saved whole video does not)`);
+ }
+ if (room.head && cutStart - D < Math.max(0, e.start - pad) - 1e-6) {
+ out.push(`${e.id}: its muted head (${D} s) starts before a fetched window does -- a fetched source clamps it`);
+ }
+ }
+ return out;
+}
diff --git a/umtool/report-to-video/room.test.mjs b/umtool/report-to-video/room.test.mjs
@@ -0,0 +1,128 @@
+// Room at a clip's edges (room.mjs, release 36 lane E): the silence rule on
+// synthetic words and silences, the plan, the sound's filters, the
+// validators, the strip's shading and the lint's window warning.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ ROOM, clipRoom, roomAudioFilter, roomOn, roomPlan, roomShade, roomWindowWarnings, speechStartFromSilences,
+ speechStartFromWords, tailFromSilences, tailFromWords, validateRoom,
+} from "./room.mjs";
+
+/** Words at the given [start, end] pairs. */
+const W = (...pairs) => pairs.map(([start, end], i) => ({ w: `w${i}`, start, end }));
+
+test("tailFromWords: a cut through a word runs to the end of its run, stopping at the first gap of minGap", () => {
+ // 10.0 cuts "w1" (9.8-10.2); w2 follows 0.1 s later; then a 0.5 s gap.
+ const words = W([9.0, 9.5], [9.8, 10.2], [10.3, 10.9], [11.4, 11.8]);
+ assert.deepEqual(tailFromWords(words, 10.0), { at: 10.9, extended: true, capped: false });
+});
+
+test("tailFromWords: a word starting within minGap after the cut belongs to the run; one starting later does not", () => {
+ assert.equal(tailFromWords(W([9, 9.9], [10.2, 10.6]), 10.0).at, 10.6);
+ assert.deepEqual(tailFromWords(W([9, 9.9], [10.5, 10.9]), 10.0), { at: 10.0, extended: false, capped: false });
+ // A narrower minGap: the same word is out of reach.
+ assert.equal(tailFromWords(W([9, 9.9], [10.2, 10.6]), 10.0, { minGap: 0.15 }).at, 10.0);
+});
+
+test("tailFromWords: the cap -- never more than maxS past the cut", () => {
+ const words = [];
+ for (let t = 9.8; t < 16; t += 0.3) words.push({ start: t, end: t + 0.25 });
+ assert.deepEqual(tailFromWords(words, 10.0), { at: 12.5, extended: true, capped: true });
+ assert.equal(tailFromWords(words, 10.0, { maxS: 1 }).at, 11.0);
+});
+
+test("tailFromWords: no words at all leaves the sound at the cut", () => {
+ assert.deepEqual(tailFromWords([], 10), { at: 10, extended: false, capped: false });
+ assert.deepEqual(tailFromWords(null, 10), { at: 10, extended: false, capped: false });
+});
+
+test("silences (no words): in a silence the sound stops at the cut; else at the next silence within maxS; none found, at the cut", () => {
+ const sil = [{ s: 4, e: 4.6 }, { s: 11.2, e: 11.9 }];
+ assert.deepEqual(tailFromSilences(sil, 4.2), { at: 4.2, extended: false, capped: false, found: true });
+ assert.deepEqual(tailFromSilences(sil, 10.0), { at: 11.2, extended: true, capped: false, found: true });
+ assert.deepEqual(tailFromSilences(sil, 6.0), { at: 6.0, extended: false, capped: false, found: false });
+ assert.equal(speechStartFromSilences(sil, 4.1), 4.6);
+ assert.equal(speechStartFromSilences(sil, 5), 5);
+});
+
+test("speechStartFromWords: the first word not over before the cut's start", () => {
+ const words = W([1, 1.4], [2.1, 2.5], [2.6, 3]);
+ assert.equal(speechStartFromWords(words, 2.0), 2.1);
+ assert.equal(speechStartFromWords(words, 2.2), 2.2);
+ assert.equal(speechStartFromWords(words, 5), Infinity);
+});
+
+test("roomPlan: the picture runs D + pad past the silence point; a head starts D early; both clamped into the file", () => {
+ const p = roomPlan({ cutA: 2, cutB: 6, D: 0.4, soundEnd: 6.8, speechStart: 2.1, duration: 20 });
+ assert.deepEqual(p, { picA: 1.6, picB: 7.3, soundA: 2, soundB: 6.8, head: 0.4, tail: 0.5, clamped: [] });
+ // Speech starts later than D after the cut: no head.
+ assert.equal(roomPlan({ cutA: 2, cutB: 6, D: 0.4, soundEnd: null, speechStart: 2.5, duration: 20 }).picA, 2);
+ // A window that ends early clamps the tail; one that starts late clamps the head.
+ const c = roomPlan({ cutA: 0.2, cutB: 6, D: 0.4, soundEnd: 6.8, speechStart: 0.2, duration: 7 });
+ assert.equal(c.picA, 0);
+ assert.equal(c.picB, 7);
+ assert.deepEqual(c.clamped, ["head", "tail"]);
+ // Tail off: the cut's own end.
+ assert.equal(roomPlan({ cutA: 2, cutB: 6, D: 0.4, soundEnd: null, speechStart: null }).picB, 6);
+});
+
+test("roomAudioFilter: a fade in ending at the cut, a fade out from the silence point, in the segment's clock", () => {
+ const p = roomPlan({ cutA: 2, cutB: 6, D: 0.4, soundEnd: 6.8, speechStart: 2.1, duration: 20 });
+ assert.equal(roomAudioFilter(p), `afade=t=in:st=0.340:d=${ROOM.fade},afade=t=out:st=5.200:d=${ROOM.fade}`);
+ assert.equal(roomAudioFilter(roomPlan({ cutA: 2, cutB: 6, D: 0.4 })), "");
+});
+
+test("clipRoom / roomOn: an edge is on when its key is true; a clip's room beats the cut's", () => {
+ const render = { room: { tail: true, head: true } };
+ assert.equal(roomOn({}), false);
+ assert.equal(roomOn({ room: {} }), false);
+ assert.equal(roomOn(render), true);
+ assert.deepEqual(clipRoom({}, render), { tail: true, head: true, minGap: ROOM.minGap, maxS: ROOM.maxS });
+ assert.equal(clipRoom({ room: false }, render), null);
+ assert.deepEqual(clipRoom({ room: { tail: false } }, render), { tail: false, head: true, minGap: 0.35, maxS: 2.5 });
+ assert.equal(clipRoom({ room: { tail: false, head: false } }, render), null);
+ assert.deepEqual(clipRoom({ room: { tail: true } }, {}), { tail: true, head: false, minGap: 0.35, maxS: 2.5 });
+ assert.equal(clipRoom({}, { room: { tail: true, minGap: 0.5, maxS: 1 } }).maxS, 1);
+ assert.equal(clipRoom({}, {}), null);
+});
+
+test("validateRoom: absent or null says nothing; each problem in a sentence naming the key", () => {
+ const m = (room, timeline = [], extra = {}) => ({ render: { room, ...extra }, timeline });
+ assert.deepEqual(validateRoom(m(undefined)), []);
+ assert.deepEqual(validateRoom(m(null)), []);
+ assert.deepEqual(validateRoom(m({ tail: true, head: true, minGap: 0.35, maxS: 2.5 })), []);
+ assert.match(validateRoom(m(true))[0], /render\.room must be an object/);
+ assert.match(validateRoom(m({ tail: "yes" }))[0], /render\.room\.tail must be true or false/);
+ assert.match(validateRoom(m({ tail: true, pad: 1 }))[0], /render\.room\.pad is not a setting here/);
+ assert.match(validateRoom(m({ tail: true, minGap: 5 }))[0], /render\.room\.minGap must be seconds from 0\.1 to 2/);
+ assert.match(validateRoom(m({ tail: true, maxS: -1 }))[0], /render\.room\.maxS must be seconds from 0 to 10/);
+ assert.match(validateRoom(m({ tail: true }, [], { montage: {} }))[0], /does not combine with render\.montage/);
+ const clip = (room) => ({ type: "clip", id: "c1", room });
+ assert.deepEqual(validateRoom(m(undefined, [clip(false), clip({ tail: false })])), []);
+ assert.match(validateRoom(m(undefined, [clip("off")]))[0], /timeline\[0\] \(c1\)\.room must be false or/);
+ assert.match(validateRoom(m(undefined, [clip({ middle: true })]))[0], /\.room\.middle is not a setting here/);
+ assert.match(validateRoom(m(undefined, [{ type: "card", id: "k", room: false }]))[0], /only a clip has room/);
+});
+
+test("roomShade: the strip's muted head and tail, from the words; nothing with room off or no join", () => {
+ const room = clipRoom({}, { room: { tail: true, head: true } });
+ const words = W([2.05, 2.4], [5.6, 6.1], [6.2, 6.7], [7.5, 8]);
+ assert.deepEqual(roomShade({ cutStart: 2, cutEnd: 6, room, D: 0.4, words }), { head: [1.6, 2], tail: [6.7, 7.2], soundEnd: 6.7 });
+ assert.deepEqual(roomShade({ cutStart: 2, cutEnd: 6, room: null, D: 0.4, words }), { head: null, tail: null, soundEnd: null });
+ assert.deepEqual(roomShade({ cutStart: 2, cutEnd: 6, room, D: 0, words }), { head: null, tail: null, soundEnd: null });
+ // No words: the nominal room.
+ assert.deepEqual(roomShade({ cutStart: 2, cutEnd: 6, room, D: 0.4 }), { head: [1.6, 2], tail: [6, 6.5], soundEnd: 6 });
+});
+
+test("roomWindowWarnings: room that can reach past a fetched window; no transition", () => {
+ const clip = { type: "clip", id: "c1", video: "v", start: 10, end: 20, cutStart: 10, cutEnd: 20 };
+ assert.deepEqual(roomWindowWarnings({ render: { transition: 0.4 }, timeline: [clip] }), []);
+ assert.deepEqual(roomWindowWarnings({ render: { transition: 0.4, room: { tail: true, head: true } }, timeline: [clip] }), []);
+ const w = roomWindowWarnings({ render: { transition: 0.4, fetchPad: 1, room: { tail: true } }, timeline: [clip] });
+ assert.equal(w.length, 1);
+ assert.match(w[0], /c1: its room can run 3 s past the cut but a fetched window ends 1 s after it/);
+ assert.match(roomWindowWarnings({ render: { transition: 0, room: { tail: true } }, timeline: [clip] })[0], /room does nothing/);
+});