commit e2e921ec985b6fa0877fe6482729185dd22b93b9
parent ee45c99a8e2ced0f0e0dd54fa4338f4045bbf4f2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 18 Oct 2026 03:03:25 -0400
umtool: a near-silent montage cut is a mislocated phrase — relocated by the sound; windows cut on their own clock; the consensus may not shift a tile into a pause
The slow-news s70 tile measured −53.7 LUFS: its window (a Rumble section cut) starts its picture 0.94 s in, and
ffmpeg's -ss counts from there while the window's name counts from zero, so every cut from such a window
landed start_time late (5 of the project's 73 windows) — s70's phrase fell in the pause after "…slow news
week". fetchClipAligned moves fetchStart by the container's start_time when the picture starts late (> 0.05
s; an mp3's encoder delay is left alone), measured against the cues on three of the five windows.
Then, under render.montage.loudness: a clip cut measured near-silent (< −40 LUFS, or 15 LU under the run's
median so far) is relocated by the sound (relocateBySound: the speech-level stretch nearest the estimate,
within the clip's extent) and cut again; so is an exclusive wall's tile at its phrase. Each is said in the
build log and recorded as relocated {from, to, why}; near-silence is never raised (gain 0). The synced wall's
consensus shift is refused when it lands 10 dB quieter than the estimate (shiftAllowed: held). Manifests
without loudness render as main's (wall-finale, build-to-wall).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
3 files changed, 338 insertions(+), 16 deletions(-)
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -181,7 +181,7 @@ import {
clipPhrase, cutStyleParts, locatePhrase, montageFont, montageOn, montageOverlayFilters, montagePieces,
montagePiecesGraph, montageSplit, montageWindow, parseClipDate, planMontage, refineOnset, resolveMontage,
bandFeatures, consensusLags, templateOnset,
- validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, loudnessGain, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords,
+ validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, median, nearSilent, relocateBySound, shiftAllowed, speechEnvelope, loudnessGain, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords,
} from "./montage.mjs";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
@@ -873,6 +873,46 @@ export function needsFetchMessage(missing) {
const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger"]);
const isClipEntry = (e) => !NON_CLIP_TYPES.has(e?.type);
+/**
+ * A window's clock, as ffmpeg seeks it. Some section downloads (Rumble's HLS
+ * cuts) keep their source timestamps, so the picture starts a second or two
+ * in: `-ss X` then lands X seconds after that start, while the window's name
+ * says where its time ZERO is. Measured on the slow-news windows (cues
+ * against silences): such a file's content at `-ss X` is the source's
+ * `from + start_time + X`. So a file whose PICTURE starts late (a video
+ * stream with start_time > 0.05 s) moves its `fetchStart` by the container's
+ * start_time; any other file (an mp3's encoder delay included) is as it was.
+ */
+async function startOffset(file) {
+ const { stdout } = await execFileP(FFPROBE, [
+ "-v", "error", "-show_entries", "format=start_time:stream=codec_type,start_time", "-of", "json", file,
+ ]).catch(() => ({ stdout: "{}" }));
+ let doc;
+ try {
+ doc = JSON.parse(stdout);
+ } catch {
+ return 0;
+ }
+ const video = (doc.streams ?? []).find((st) => st.codec_type === "video");
+ const vStart = Number(video?.start_time);
+ const fStart = Number(doc.format?.start_time);
+ return Number.isFinite(vStart) && vStart > 0.05 && Number.isFinite(fStart) && fStart > 0 ? fStart : 0;
+}
+
+/** 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,
+ };
+}
+
async function fetchClip(entry, meta, render, local, opts) {
const { rawDir } = local;
const { from, to } = fetchSpan(entry, render, opts);
@@ -1092,7 +1132,7 @@ const encodeArgsVideoOnly = (render) => [
async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, provenance, framing = null) {
const outDir = dirs.dir;
- const { path: raw, fetchStart, scan } = await fetchClip(entry, meta, render, dirs.local, opts);
+ const { path: raw, fetchStart, scan } = await fetchClipAligned(entry, meta, render, dirs.local, opts);
// Its source in hand, and only then: a link to another take's files is
// unlinked before anything is written (detachSegmentFiles), so a clip whose
// source cannot be had leaves this take's segment as it was.
@@ -1142,9 +1182,17 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const sil = await detectSilence(raw, render, scan);
// A montage cuts to the phrase (montageCut); every other clip as it always was.
- const mont = dirs.montage
+ let mont = dirs.montage
? await montageCut({ entry, M: dirs.montage, render, provenance, fetchStart, sil, wantA, wantB, win, raw })
: null;
+ // Even loudness measures the cut; a near-silent cut is a phrase looked for
+ // in the wrong place, found again by the sound (montageCheckSound).
+ let level = null;
+ if (mont?.settings.loudness) {
+ ({ mont, level } = await montageCheckSound({
+ 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.
@@ -1322,7 +1370,6 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// framing below then leaves as it is. Its sound replaces `0:a`; a poster
// shares it through an asplit.
// Even loudness (render.montage.loudness): the cut's sound measured, one gain.
- const level = mont?.settings.loudness ? await montageLevel(raw, cutA, cutB, mont.settings.loudness) : null;
const mg = mont ? montageSegmentGraph({ mont, render, box: { w: VW, h: VH }, hasVideo: media.hasVideo, cutA, cutB, gainDb: level?.gain ?? null }) : null;
const pic = mg?.v ?? (pst ? "[pic]" : "[0:v]");
const lead = mg
@@ -1370,6 +1417,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
if (mont) {
dirs.montage.cuts.set(entry.id, {
raw, cutA, cutB, phrase: mont.phrase, via: mont.via, year: mont.ctx.year, hasVideo: media.hasVideo,
+ ...(level?.relocated ? { relocated: level.relocated } : {}),
});
}
return seg;
@@ -1422,13 +1470,15 @@ async function montageCues(entry, provenance) {
* (`cutStart`/`cutEnd`, else the extent) stands in for the phrase where a
* punch-in or a stutter needs one.
*/
-async function montageCut({ entry, M, render, provenance, fetchStart, sil, wantA, wantB, win }) {
+async function montageCut({ entry, M, render, provenance, fetchStart, sil, wantA, wantB, win, override = null }) {
const s = M.settings;
const ctx = M.ctx.get(entry.id) ?? { k: 0, n: 1, number: 1, of: 1, cap: null, stutter: false, date: null, year: null, yearChange: false, platform: null, first: false, last: false };
const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd);
- const { found, via } = s.tighten === "phrase" || s.punch?.mode === "snap" || ctx.stutter
- ? await findMontagePhrase(entry, M, provenance)
- : { found: null, via: null };
+ const { found, via } = override
+ ? { found: override, via: "sound" }
+ : s.tighten === "phrase" || s.punch?.mode === "snap" || ctx.stutter
+ ? await findMontagePhrase(entry, M, provenance)
+ : { found: null, via: null };
const at = found ?? (hasCut ? { start: entry.cutStart, end: entry.cutEnd } : { start: entry.start, end: entry.end });
const phrase = { start: at.start - fetchStart, end: at.end - fetchStart };
const w = montageWindow({
@@ -1465,18 +1515,92 @@ async function findMontagePhrase(entry, M, provenance) {
*/
async function montageWallSource({ entry, M, render, provenance, local, opts }) {
const meta = await clipMeta(entry, provenance);
- const { path: raw, fetchStart } = await fetchClip(entry, meta, render, local, opts);
+ const { path: raw, fetchStart } = await fetchClipAligned(entry, meta, render, local, opts);
const { found, via } = await findMontagePhrase(entry, M, provenance);
const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd);
const at = found ?? (hasCut ? { start: entry.cutStart, end: entry.cutEnd } : { start: entry.start, end: entry.end });
const media = await probeMedia(raw);
+ let phrase = { start: at.start - fetchStart, end: at.end - fetchStart };
+ let relocated = null;
+ let viaNow = via;
+ // A tile measured near-silent at its phrase is looked for again by the sound.
+ if (M.settings.loudness) {
+ const len = Math.min(RELOCATE_LEN, Math.max(0.4, phrase.end - phrase.start));
+ const measured = await measureLoudness(raw, phrase.start, phrase.start + len);
+ if (nearSilent(measured)) {
+ const t = await relocatePhrase(raw, entry.start - fetchStart, entry.end - fetchStart, phrase.start, phrase.end - phrase.start);
+ if (t != null) {
+ relocated = { from: Number(at.start.toFixed(3)), to: Number((fetchStart + t).toFixed(3)), why: `measured ${measured ?? "no"} LUFS` };
+ EMIT("note", { message: `${entry.id}: its tile's phrase measured near-silent (${relocated.why}) — relocated by the sound from ${relocated.from}s to ${relocated.to}s` });
+ phrase = { start: t, end: t + len };
+ viaNow = "sound";
+ }
+ }
+ }
return {
raw, cutA: entry.start - fetchStart, cutB: entry.end - fetchStart,
- phrase: { start: at.start - fetchStart, end: at.end - fetchStart }, via,
+ phrase, via: viaNow, ...(relocated ? { relocated } : {}),
year: M.ctx.get(entry.id)?.year ?? parseClipDate(entry.montage?.date)?.y ?? null, hasVideo: media.hasVideo,
};
}
+/** A mislocated phrase is looked for again over this much of it at most, seconds. */
+const RELOCATE_LEN = 1.5;
+
+/**
+ * Where a phrase that measured near-silent really is: the speech in the
+ * clip's extent (raw-file seconds `a`–`b`) nearest the estimate `est`
+ * (montage.mjs relocateBySound over a `len`-second stretch). Null when the
+ * extent holds no speech, or the speech is where it was looked for.
+ */
+async function relocatePhrase(raw, a, b, est, len) {
+ const rate = 16000;
+ const from = Math.max(0, a);
+ const ex = await speechExcerpt(raw, from, Math.max(0.5, b - from), rate).catch(() => null);
+ if (!ex) return null;
+ // In dBFS: the speech threshold is absolute.
+ const t = relocateBySound(speechEnvelope(Float32Array.from(ex, (v) => v / 32768), rate), { start: from, est, len: Math.min(len, RELOCATE_LEN) });
+ return t != null && Math.abs(t - est) > 0.1 ? t : null;
+}
+
+/**
+ * A montage cut's sound, checked: measured (montageLevel), and when it is
+ * near-silent -- under −40 LUFS, or 15 LU under the run's median so far --
+ * the phrase is relocated by the sound and the clip cut again from there,
+ * said in the build log and recorded (`relocated: {from, to, why}`, SOURCE
+ * seconds). Near-silence is never raised (loudnessGain gives it 0).
+ */
+async function montageCheckSound({ entry, mont, raw, fetchStart, M, render, provenance, sil, wantA, wantB, win }) {
+ const target = mont.settings.loudness;
+ M.levels ??= [];
+ let level = await montageLevel(raw, mont.win.cutA, mont.win.cutB, target);
+ if (nearSilent(level.measured, M.levels.length >= 5 ? median(M.levels) : null)) {
+ const est = mont.phrase.start;
+ const len = Math.max(0.3, mont.phrase.end - mont.phrase.start);
+ const t = await relocatePhrase(raw, entry.start - fetchStart, entry.end - fetchStart, est, len);
+ const why = `measured ${level.measured ?? "no"} LUFS`;
+ if (t != null) {
+ const span = Math.min(len, RELOCATE_LEN);
+ const next = await montageCut({
+ entry, M, render, provenance, fetchStart, sil, wantA, wantB, win,
+ override: { start: fetchStart + t, end: fetchStart + t + span },
+ });
+ const again = await montageLevel(raw, next.win.cutA, next.win.cutB, target);
+ const relocated = { from: Number((fetchStart + est).toFixed(3)), to: Number((fetchStart + t).toFixed(3)), why };
+ EMIT("note", {
+ message: `${entry.id}: its phrase measured near-silent (${why}) — relocated by the sound from ` +
+ `${relocated.from}s to ${relocated.to}s (now ${again.measured ?? "?"} LUFS)`,
+ });
+ mont = next;
+ level = { ...again, relocated };
+ } else {
+ EMIT("note", { message: `${entry.id}: its cut measured near-silent (${why}) and no speech was found near it — left as it is, not raised` });
+ }
+ }
+ if (Number.isFinite(level.measured)) M.levels.push(level.measured);
+ return { mont, level };
+}
+
/**
* A stretch of a source's integrated loudness (LUFS, ffmpeg's ebur128), or
* null when it cannot be measured.
@@ -1539,9 +1663,15 @@ async function wallOnsets(tiles) {
// Then all of them together onto where their mean loudness rises.
const anchor = templateOnset(feats, lags, { origin, window: 0.3, hop: ONSET_HOP });
const shift = anchor?.shift ?? 0;
- tiles.forEach((t, i) => out.set(t.id, {
- at: t.phrase.start + lags[i] * ONSET_HOP + shift, by: "consensus", r: Number(r[i].toFixed(2)),
- }));
+ // A shift into a span 10 dB quieter than the estimate's is a shift into a
+ // pause: that tile keeps its estimate (shiftAllowed).
+ tiles.forEach((t, i) => {
+ const move = lags[i] * ONSET_HOP + shift;
+ const env = speechEnvelope(ex[i], rate);
+ out.set(t.id, shiftAllowed(env, { pre: ONSET_PRE, shift: move })
+ ? { at: t.phrase.start + move, by: "consensus", r: Number(r[i].toFixed(2)) }
+ : { at: t.phrase.start, by: "estimate", r: Number(r[i].toFixed(2)), held: "the consensus shift lands in a pause" });
+ });
out.anchor = Number(shift.toFixed(3));
return out;
}
@@ -1640,7 +1770,10 @@ async function buildMontageWall({ M, entries, render, outDir, timeline, provenan
const to = Math.min(c.cutB, Math.max(onset + 0.4, c.phrase.end + (onset - est) + WALL_TAIL));
sources.set(id, {
from, to, lead: onset - from,
- sync: { estimate: Number(est.toFixed(3)), onset: Number(onset.toFixed(3)), via: c.via ?? null, by: o.by, r: o.r ?? null },
+ sync: {
+ estimate: Number(est.toFixed(3)), onset: Number(onset.toFixed(3)), via: c.via ?? null, by: o.by, r: o.r ?? null,
+ ...(o.held ? { held: o.held } : {}), ...(c.relocated ? { relocated: c.relocated } : {}),
+ },
});
}
const tiles = chosen.map((id) => {
diff --git a/umtool/report-to-video/montage.mjs b/umtool/report-to-video/montage.mjs
@@ -1186,6 +1186,71 @@ export function wallTileLabel(label, { number = null, year = null } = {}) {
// ---- even loudness (`render.montage.loudness`) ---------------------------------------
+/** Integrated loudness under this (LUFS) is near-silence: the phrase is not where it was looked for. */
+export const SILENT_LUFS = -40;
+/** …and so is a stretch this far (LU) under the run's median so far. */
+export const SILENT_UNDER_MEDIAN = 15;
+
+/**
+ * Is a measured stretch near-silent: under SILENT_LUFS, unmeasurable, or
+ * SILENT_UNDER_MEDIAN under `median` (the run's so far, when known)?
+ */
+export function nearSilent(measured, median = null) {
+ if (!num(measured)) return true;
+ return measured < SILENT_LUFS || (num(median) && measured < median - SILENT_UNDER_MEDIAN);
+}
+
+/** The median of the numbers given, or null. */
+export function median(values) {
+ const v = values.filter(num).sort((a, b) => a - b);
+ if (!v.length) return null;
+ return v.length % 2 ? v[(v.length - 1) / 2] : (v[v.length / 2 - 1] + v[v.length / 2]) / 2;
+}
+
+/**
+ * Where a mislocated phrase really is, by the sound: of every `len`-second
+ * stretch of the excerpt (`env`, speechEnvelope dBFS frames every `hop` s from
+ * `start`) that is speech (`share` of its frames at ≥ `speechDb`), the one starting
+ * nearest `est` -- a phrase estimated into the silence after a long cue
+ * lands on the speech that ends there. Ties go to the later. Null when the
+ * excerpt holds no speech.
+ */
+export function relocateBySound(env, { hop = 0.005, start = 0, est, len, speechDb = -35, share = 0.9 }) {
+ const n = Math.max(1, Math.round(len / hop));
+ if (env.length < n) return null;
+ // Frames at speech level, counted over a sliding window: a stretch is
+ // speech when `share` of it is.
+ let sum = 0;
+ for (let k = 0; k < n; k += 1) sum += env[k] >= speechDb ? 1 : 0;
+ let best = null;
+ for (let k = 0; k + n <= env.length; k += 1) {
+ if (k > 0) sum += (env[k + n - 1] >= speechDb ? 1 : 0) - (env[k - 1] >= speechDb ? 1 : 0);
+ if (sum < share * n) continue;
+ const t = start + k * hop;
+ const d = Math.abs(t - est);
+ if (!best || d < best.d - 1e-9 || Math.abs(d - best.d) <= 1e-9) best = { d, t };
+ }
+ return best ? Number(best.t.toFixed(3)) : null;
+}
+
+/**
+ * Whether a consensus shift may stand: the `span` seconds after the shifted
+ * onset may be no more than `maxDrop` dB quieter (mean of `env`, dB frames
+ * every `hop` from the excerpt's start) than the span after the estimate,
+ * which sits `pre` seconds in. A shift into a pause is refused.
+ */
+export function shiftAllowed(env, { hop = 0.005, pre, shift, span = 0.4, maxDrop = 10 }) {
+ const mean = (t) => {
+ const a = Math.max(0, Math.round(t / hop));
+ const b = Math.min(env.length, a + Math.max(1, Math.round(span / hop)));
+ if (b <= a) return -100;
+ let s = 0;
+ for (let k = a; k < b; k += 1) s += env[k];
+ return s / (b - a);
+ };
+ return mean(pre + shift) >= mean(pre) - maxDrop;
+}
+
/** No clip is raised or lowered by more than this, dB. */
export const LOUDNESS_MAX_GAIN = 20;
/** Below this a measurement is silence or too short to trust: no gain. */
@@ -1196,7 +1261,8 @@ export const LOUDNESS_FLOOR = -60;
* held to ±LOUDNESS_MAX_GAIN; 0 for a silence or an unmeasurable clip.
*/
export function loudnessGain(measured, target) {
- if (!num(measured) || measured <= LOUDNESS_FLOOR) return 0;
+ // Near-silence is a phrase in the wrong place, never a quiet clip to raise.
+ if (!num(measured) || measured <= LOUDNESS_FLOOR || measured < SILENT_LUFS) return 0;
return Number(Math.max(-LOUDNESS_MAX_GAIN, Math.min(LOUDNESS_MAX_GAIN, target - measured)).toFixed(2));
}
diff --git a/umtool/report-to-video/montage.test.mjs b/umtool/report-to-video/montage.test.mjs
@@ -21,6 +21,7 @@ import {
wallComposeArgs, wallPlan, wallTileClips, whisperWords, wallGroups, wallBeats, wallFirstGap, montageSplit,
refineOnset, speechEnvelope, envelopeLag, WALL_SLIDE_FRAMES, bandFeatures, consensusLags, templateOnset,
clipStream, distinctTileClips, wallCells, wallTileLabel, wallTileArgs, loudnessGain, parseIntegratedLoudness, levelFilters,
+ nearSilent, median, relocateBySound, shiftAllowed, SILENT_LUFS,
} from "./montage.mjs";
import { applyMontageStyle, MONTAGE_STYLE_NAMES, mergePatch } from "./montage-styles.mjs";
import { buildVideo, snap } from "./build-video.mjs";
@@ -1171,7 +1172,8 @@ test("wallTileLabel and wallTileArgs: year, number or both; today's year label u
test("loudness: the gain to the target, held to ±20 dB, none for silence; ebur128's summary read; a leveled segment's chain", () => {
assert.equal(loudnessGain(-30, -16), 14);
assert.equal(loudnessGain(-8.5, -16), -7.5);
- assert.equal(loudnessGain(-50, -16), 20);
+ assert.equal(loudnessGain(-39, -16), 20, "held to +20");
+ assert.equal(loudnessGain(-50, -16), 0, "near-silence is not raised");
assert.equal(loudnessGain(-70, -16), 0);
assert.equal(loudnessGain(null, -16), 0);
const log = "[Parsed_ebur128_0 @ 0x1] t: 1.9 M: -20 S: -21 I: -25.0 LUFS\n[Parsed_ebur128_0 @ 0x1] Summary:\n\n Integrated loudness:\n I: -21.8 LUFS\n Threshold: -31.8 LUFS\n";
@@ -1251,3 +1253,124 @@ test("render: a tail wall keeps one stream's repeats apart, labels its tiles, le
await rm(root, { recursive: true, force: true });
}
});
+
+// ---- release 33 silent-tile: a near-silent cut is a mislocated phrase -------------------------
+
+test("nearSilent and median: under −40 LUFS, unmeasurable, or 15 LU under the run's median", () => {
+ assert.equal(SILENT_LUFS, -40);
+ assert.equal(nearSilent(-53.7), true);
+ assert.equal(nearSilent(-38.6), false);
+ assert.equal(nearSilent(-38.6, -21), true, "17.6 LU under the median");
+ assert.equal(nearSilent(-30, -21), false);
+ assert.equal(nearSilent(null), true);
+ assert.equal(median([3, 1, 2]), 2);
+ assert.equal(median([4, 1, 3, 2]), 2.5);
+ assert.equal(median([]), null);
+ // Near-silence is never raised.
+ assert.equal(loudnessGain(-45, -16), 0);
+ assert.equal(loudnessGain(-38.6, -16), 20);
+});
+
+/** dB frames every 5 ms: speech (−20 dB) over [a, b) seconds, silence (−100) elsewhere, `len` seconds long. */
+const envOf = (len, spans) => Float64Array.from({ length: Math.round(len / 0.005) }, (_, k) => (spans.some(([a, b]) => k * 0.005 >= a && k * 0.005 < b) ? -20 : -100));
+
+test("relocateBySound: a phrase estimated into the silence after a long cue lands on the speech that ends there", () => {
+ // A 7.8 s cue of speech from 1.1 s to 9.4 s, silence after; the even-spread estimate put "slow news" at 9.7.
+ const env = envOf(12, [[1.1, 9.4]]);
+ const t = relocateBySound(env, { start: 0, est: 9.7, len: 1.2 });
+ // Nearest the estimate with 90% of it speech: ending at most 0.12 s into the silence.
+ assert.ok(t >= 9.4 - 1.2 - 0.006 && t <= 9.4 - 1.2 + 0.121, `${t}`);
+ // The excerpt's own start is added.
+ assert.ok(Math.abs(relocateBySound(env, { start: 355, est: 364.7, len: 1.2 }) - (355 + t)) <= 0.006);
+ // Speech either side: the nearest wins.
+ const two = envOf(12, [[0.5, 3], [6, 9]]);
+ // (Up to a tenth of the stretch may be the silence beside the speech.)
+ assert.ok(Math.abs(relocateBySound(two, { start: 0, est: 4.5, len: 1 }) - 6) <= 0.101);
+ assert.ok(Math.abs(relocateBySound(two, { start: 0, est: 3.6, len: 1 }) - 2) <= 0.101);
+ assert.equal(relocateBySound(envOf(5, []), { start: 0, est: 2, len: 1 }), null, "no speech");
+ assert.equal(relocateBySound(envOf(0.5, [[0, 0.5]]), { start: 0, est: 0, len: 1 }), null, "shorter than the phrase");
+});
+
+test("shiftAllowed: a consensus shift into a pause is refused", () => {
+ // Excerpt from est − 0.8: speech 0.6–1.6 s into it, then silence.
+ const env = envOf(2.4, [[0.6, 1.6]]);
+ assert.equal(shiftAllowed(env, { pre: 0.8, shift: 0.1 }), true);
+ assert.equal(shiftAllowed(env, { pre: 0.8, shift: 0.9 }), false, "into the silence after");
+ assert.equal(shiftAllowed(env, { pre: 0.8, shift: -0.1 }), true);
+ assert.equal(shiftAllowed(envOf(2.4, []), { pre: 0.8, shift: 0.3 }), true, "silence to silence is no drop");
+});
+
+/** One clip of six seconds: a tone (speech) over `speech` [a, b), silence elsewhere; one long cue; montage on. */
+async function oneClip({ speech, cues, montage, shiftTs = 0 }) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "rtv-silent-"));
+ await mkdir(path.join(root, "media"), { recursive: true });
+ const full = path.join(root, "media", "full.mp4");
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x808080:s=320x180:r=${FPS}:d=6`,
+ "-f", "lavfi", "-i", `aevalsrc='0.4*sin(2*PI*330*t)*between(t,${speech[0]},${speech[1]})+0.002*sin(2*PI*50*t)':s=48000:d=6`,
+ "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", full,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ let media = "media/full.mp4";
+ if (shiftTs) {
+ // A section cut that keeps its source's clock: content from shiftTs on, its picture starting shiftTs in.
+ const cut = path.join(root, "media", "cut.mp4");
+ const c = spawnSync("ffmpeg", ["-v", "error", "-y", "-ss", String(shiftTs), "-i", full, "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-output_ts_offset", String(shiftTs), cut]);
+ assert.equal(c.status, 0, String(c.stderr));
+ media = "media/cut.mp4";
+ }
+ await writeFile(path.join(root, "media", "c.json"), JSON.stringify({ cues }));
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "demo", title: "Demo", render: { ...RENDER, montage },
+ timeline: [
+ { id: "c1", type: "clip", src: media, cues: "media/c.json", start: shiftTs ? 1.1 : 0.1, end: shiftTs ? 4.9 : 5.9, title: "C", channelTitle: "Demo", montage: { n: 1, date: "20260922", match: "slow news week" } },
+ { id: "c2", type: "clip", src: "media/full.mp4", cues: "media/c.json", start: shiftTs ? 1.1 : 0.1, end: shiftTs ? 4.9 : 5.9, title: "D", channelTitle: "Demo", montage: { n: 2, date: "20260923", match: "slow news week" } },
+ ],
+ }));
+ return { root, manifestPath };
+}
+
+test("render: a cut measured near-silent is relocated onto the speech and leveled, not raised from silence", { skip: !have && "needs ffmpeg" }, async () => {
+ // Speech 0.4–3.6 s, then silence; one long cue to 5.6 s ending "…slow news week": the estimate sits in the silence.
+ const { root, manifestPath } = await oneClip({
+ speech: [0.4, 3.6],
+ cues: [{ start: 0.4, end: 5.6, text: "rest up you know it is kind of a slow news week" }],
+ montage: { tighten: "phrase", phrasePad: 0.3, loudness: { target: -18 } },
+ });
+ try {
+ await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const seg = path.join(root, "out", "sourced", "segments");
+ const rec = JSON.parse(await readFile(path.join(seg, "c1.cut.json"), "utf8"));
+ const loud = rec.montage.loudness;
+ assert.ok(loud.relocated, JSON.stringify(rec.montage));
+ assert.ok(loud.relocated.from > 3.6, `estimated in the silence: ${loud.relocated.from}`);
+ assert.ok(loud.relocated.to < 3.6 && loud.relocated.to > 1.5, `relocated onto the speech: ${loud.relocated.to}`);
+ assert.match(loud.relocated.why, /^measured (-?[\d.]+|no) LUFS$/);
+ assert.equal(rec.montage.found, "sound");
+ assert.ok(loud.measured > -40, `now ${loud.measured}`);
+ assert.ok(Math.abs(lufs(path.join(seg, "c1.mp4")) + 18) <= 1, "leveled");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("render: a window whose picture starts late is cut on its own clock", { skip: !have && "needs ffmpeg" }, async () => {
+ // c1's file is c2's from 1.0 s on, its timestamps kept (start_time 1.0): the same source seconds.
+ const { root, manifestPath } = await oneClip({
+ speech: [1.5, 4.5],
+ cues: [{ start: 1.5, end: 2.5, text: "it is a slow" }, { start: 2.5, end: 3.5, text: "news week folks" }],
+ montage: { tighten: "phrase", phrasePad: 0.3 },
+ shiftTs: 1,
+ });
+ try {
+ await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const seg = path.join(root, "out", "sourced", "segments");
+ const [a, b] = await Promise.all(["c1", "c2"].map(async (id) => JSON.parse(await readFile(path.join(seg, `${id}.cut.json`), "utf8"))));
+ assert.ok(Math.abs(a.start - b.start) <= 0.05 && Math.abs(a.end - b.end) <= 0.05, `${a.start}–${a.end} vs ${b.start}–${b.end}`);
+ // The same sound: the two segments' loudness agrees.
+ assert.ok(Math.abs(lufs(path.join(seg, "c1.mp4")) - lufs(path.join(seg, "c2.mp4"))) <= 1);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});