commit 7a0b9431f899fa9a18221c8b39584d141ce17377
parent 572c5f5781e9b434b71a9183f011dda3f0f0a79f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 22 Oct 2026 10:32:32 -0400
report video: a clip's own audio -- offset, gain, fades -- at the segment encode
timeline entry "audio": { offset: ms -2000..2000 (+ = sound later), gain:
dB -20..20, fadeIn / fadeOut: s 0..5 }. The offset reads the sound from the
source again at the shifted window (one more input, the last; -itsoffset
past the file's head), so nothing is cut off the far end; gain and fades
follow any levelling and room. The cut record keeps the knobs it used.
validateClipAudio (exported for umtool's updateClip) and
validateClipAudioEntries (build and lint) refuse in sentences. A montage's
sound is its own: the knobs are not applied there, and the build says so.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
4 files changed, 275 insertions(+), 10 deletions(-)
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -146,7 +146,7 @@ import {
// The effects region (`render.chrome.fx`, release 35): pure, in fx.mjs.
import { fxOn, fxQuoteSpan, resolveFx, fxWhipJoins, fxWipeJoins, fxWordsOf, fxZoomJoins, validateFxEntries } from "./fx.mjs";
import { claimOf, stampsDrawn, validateClaims } from "./factcheck.mjs";
-import { AUDIO_ON_CLOCK } from "./clip-audio.mjs";
+import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs";
import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
@@ -1269,15 +1269,29 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
`its first frame held, silence under it`,
});
}
- const soundChain = [AUDIO_ON_CLOCK, !mont && level != null ? levelFilters(level.gain) : "", roomAf].filter(Boolean).join(",");
+ // The clip's own `audio` (clip-audio.mjs): its gain and fades last, in the
+ // segment's clock; its offset reads the sound from the source again, at
+ // the shifted window, as one more input (the LAST, so every other index is
+ // the one a clip without it uses). A montage's sound is its own.
+ const knobs = mont ? null : clipAudioOf(entry);
+ if (mont && clipAudioOf(entry)) EMIT("note", { message: `${entry.id}: a montage cuts its own sound — its audio settings are not applied` });
+ const shifted = offsetWindow(knobs, segA, segB);
+ const soundInput = shifted
+ ? [...(shifted.from < 0 ? ["-itsoffset", (-shifted.from).toFixed(3)] : []), ...cutArgs(raw, Math.max(0, shifted.from), shifted.to)]
+ : null;
+ const soundChain = [
+ AUDIO_ON_CLOCK, !mont && level != null ? levelFilters(level.gain) : "", roomAf, ...clipAudioFilters(knobs, segB - segA),
+ ].filter(Boolean).join(",");
const leveled = !mont && soundChain !== "";
- const levelParts = (posterParts) => {
+ // `ain`: the sound's input -- `[0:a]`, or the offset's own.
+ const levelParts = (posterParts, ain = "[0:a]") => {
if (!leveled) return posterParts ?? [];
// An asplit only when the poster reads the sound too (its waveform).
- if (!(posterParts ?? []).some((p) => p.includes("[0:a]"))) return [...(posterParts ?? []), `[0:a]${soundChain}[al]`];
- return [`[0:a]asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${soundChain}[al]`];
+ if (!(posterParts ?? []).some((p) => p.includes("[0:a]"))) return [...(posterParts ?? []), `${ain}${soundChain}[al]`];
+ return [`${ain}asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${soundChain}[al]`];
};
const audioMap = leveled ? "[al]" : "0:a";
+ if (knobs) cutRecord.audio = knobs;
const quotePath = path.join(outDir, "segments", `${entry.id}.quote.txt`);
const attribPath = path.join(outDir, "segments", `${entry.id}.attrib.txt`);
@@ -1323,8 +1337,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
"-nostdin", "-v", "error", "-y",
...cutArgs(raw, segA, segB),
...(pst ? pst.input : []),
+ ...(soundInput ?? []),
"-filter_complex", [
- ...levelParts(pst ? pst.parts : null),
+ ...levelParts(pst ? pst.parts : null, soundInput ? `[${pst ? 2 : 1}:a]` : "[0:a]"),
`${pst ? "[pic]" : "[0:v]"}${deckFramingFilter(render, { feed: fr.layout === "feed" })}[v]`,
].join(";"),
"-map", "[v]", "-map", audioMap,
@@ -1441,6 +1456,13 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
nextIdx += 1;
inputs.push(...pst.input);
}
+ // The clip's offset sound: after everything else.
+ let ain = "[0:a]";
+ if (soundInput) {
+ ain = `[${nextIdx}:a]`;
+ nextIdx += 1;
+ inputs.push(...soundInput);
+ }
// A montage's pieces come first: the picture and the sound of the cut,
// re-timed (a stutter), zoomed (a punch-in) and fitted to the box, which the
// framing below then leaves as it is. Its sound replaces `0:a`; a poster
@@ -1450,7 +1472,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const pic = mg?.v ?? (pst ? "[pic]" : "[0:v]");
const lead = mg
? [...(pst ? [`[0:a]asplit=2[mpa][mpw]`, ...pst.parts.map((p) => p.replaceAll("[0:a]", "[mpw]"))] : []), ...mg.parts]
- : levelParts(pst ? pst.parts : null);
+ : levelParts(pst ? pst.parts : null, ain);
const parts = hasFooter
? [
@@ -5241,7 +5263,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole),
...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole),
...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole), ...validateTransitionStyle(whole),
- ...validateLook(whole),
+ ...validateLook(whole), ...validateClipAudioEntries(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
diff --git a/umtool/report-to-video/clip-audio.mjs b/umtool/report-to-video/clip-audio.mjs
@@ -1,5 +1,13 @@
// A clip's sound at its segment encode: laid on its own clock, and the
-// per-clip `audio` knobs (offset, gain, fades).
+// per-clip `audio` knobs.
+//
+// timeline entry: "audio": { "offset": 120, "gain": -3, "fadeIn": 0.5, "fadeOut": 1 }
+//
+// `offset` (ms, −2000…2000) moves the sound against the picture: + is LATER.
+// It is read from the source again at the shifted window, so nothing is cut
+// off the far end. `gain` (dB, −20…20) after any levelling; `fadeIn` /
+// `fadeOut` (s, 0…5) at the segment's edges. Every key optional; absent,
+// the segment's sound is what it was.
//
// No imports from build-video.mjs: it imports this file, and so do the sync
// report and umtool's writers (K2's updateClip validates through
@@ -13,3 +21,96 @@
* counts samples (apad, acrossfade, concat) then counts the clock.
*/
export const AUDIO_ON_CLOCK = "aresample=async=1:min_hard_comp=0.01:first_pts=0";
+
+/** Each knob's range and unit. */
+export const CLIP_AUDIO_LIMITS = Object.freeze({
+ offset: Object.freeze({ min: -2000, max: 2000, unit: "ms" }),
+ gain: Object.freeze({ min: -20, max: 20, unit: "dB" }),
+ fadeIn: Object.freeze({ min: 0, max: 5, unit: "s" }),
+ fadeOut: Object.freeze({ min: 0, max: 5, unit: "s" }),
+});
+
+export const CLIP_AUDIO_KEYS = Object.freeze(Object.keys(CLIP_AUDIO_LIMITS));
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/**
+ * Every reason a clip's `audio` cannot be used, as sentences naming `where`
+ * (empty: it can). `undefined` / `null` is none. Unknown keys are refused.
+ *
+ * @param {unknown} audio
+ * @param {string} [where]
+ * @returns {string[]}
+ */
+export function validateClipAudio(audio, where = "audio") {
+ if (audio === undefined || audio === null) return [];
+ if (!isObj(audio)) return [`${where} must be { offset, gain, fadeIn, fadeOut }`];
+ const errors = [];
+ for (const k of Object.keys(audio)) {
+ if (!CLIP_AUDIO_KEYS.includes(k)) errors.push(`${where}.${k} is not an audio setting (${CLIP_AUDIO_KEYS.join(", ")})`);
+ }
+ for (const [k, { min, max, unit }] of Object.entries(CLIP_AUDIO_LIMITS)) {
+ const v = audio[k];
+ if (v === undefined) continue;
+ if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max) {
+ errors.push(`${where}.${k} must be a number from ${min} to ${max} (${unit})`);
+ }
+ }
+ return errors;
+}
+
+/** Every clip's `audio` in a manifest, checked (the build's and the lint's). */
+export function validateClipAudioEntries(manifest) {
+ const errors = [];
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.audio === undefined) return;
+ const where = `timeline[${i}] (${e.id ?? "?"}).audio`;
+ if (e.type && e.type !== "clip") { errors.push(`${where}: only a clip's sound has these settings`); return; }
+ errors.push(...validateClipAudio(e.audio, where));
+ });
+ return errors;
+}
+
+/** The knobs that do anything: an empty object (or none) changes nothing. */
+export function clipAudioOf(entry) {
+ const a = isObj(entry?.audio) ? entry.audio : null;
+ if (!a || validateClipAudio(a).length) return null;
+ const out = {};
+ if (a.offset) out.offset = a.offset;
+ if (a.gain) out.gain = a.gain;
+ if (a.fadeIn) out.fadeIn = a.fadeIn;
+ if (a.fadeOut) out.fadeOut = a.fadeOut;
+ return Object.keys(out).length ? out : null;
+}
+
+const num = (v) => String(Number(v.toFixed(4)));
+
+/**
+ * The gain and fades as filters on a segment `seconds` long, in its own clock
+ * (after AUDIO_ON_CLOCK). Empty without any.
+ *
+ * @returns {string[]}
+ */
+export function clipAudioFilters(audio, seconds) {
+ if (!audio) return [];
+ const out = [];
+ if (audio.gain) out.push(`volume=${num(audio.gain)}dB`);
+ if (audio.fadeIn) out.push(`afade=t=in:st=0:d=${num(Math.min(audio.fadeIn, seconds))}`);
+ if (audio.fadeOut) {
+ const d = Math.min(audio.fadeOut, seconds);
+ out.push(`afade=t=out:st=${num(Math.max(0, seconds - d))}:d=${num(d)}`);
+ }
+ return out;
+}
+
+/**
+ * Where the sound is read from for a segment cut at [a, b] of its source
+ * file: [a − offset, b − offset] (seconds), so at the segment's second t the
+ * source's t + a − offset plays -- the sound `offset` later. Null without an
+ * offset: the picture's own input carries it.
+ */
+export function offsetWindow(audio, a, b) {
+ if (!audio?.offset) return null;
+ const s = audio.offset / 1000;
+ return { from: a - s, to: b - s };
+}
diff --git a/umtool/report-to-video/clip-audio.test.mjs b/umtool/report-to-video/clip-audio.test.mjs
@@ -0,0 +1,141 @@
+// A clip's own `audio` (clip-audio.mjs): validated in sentences, and applied
+// at the segment encode -- the offset moves the sound against the picture by
+// reading the source again, the gain and fades after.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudio, validateClipAudioEntries,
+} from "./clip-audio.mjs";
+import { buildVideo } from "./build-video.mjs";
+import { MONO_FONT_FILE } from "./brand.mjs";
+
+test("validateClipAudio: none is fine; each knob in its range; unknown keys refused", () => {
+ assert.deepEqual(validateClipAudio(undefined), []);
+ assert.deepEqual(validateClipAudio(null), []);
+ assert.deepEqual(validateClipAudio({}), []);
+ assert.deepEqual(validateClipAudio({ offset: -2000, gain: 20, fadeIn: 0, fadeOut: 5 }), []);
+ assert.deepEqual(validateClipAudio({ offset: 2000, gain: -20 }), []);
+ assert.deepEqual(validateClipAudio("loud"), ["audio must be { offset, gain, fadeIn, fadeOut }"]);
+ assert.deepEqual(validateClipAudio({ offset: 2001 }), ["audio.offset must be a number from -2000 to 2000 (ms)"]);
+ assert.deepEqual(validateClipAudio({ gain: "3" }), ["audio.gain must be a number from -20 to 20 (dB)"]);
+ assert.deepEqual(validateClipAudio({ fadeIn: -1 }), ["audio.fadeIn must be a number from 0 to 5 (s)"]);
+ assert.deepEqual(validateClipAudio({ fadeOut: 6 }), ["audio.fadeOut must be a number from 0 to 5 (s)"]);
+ assert.deepEqual(validateClipAudio({ delay: 1 }), ["audio.delay is not an audio setting (offset, gain, fadeIn, fadeOut)"]);
+ assert.deepEqual(validateClipAudio({ offset: NaN }, "timeline[2] (c).audio"), ["timeline[2] (c).audio.offset must be a number from -2000 to 2000 (ms)"]);
+});
+
+test("validateClipAudioEntries: a clip's, named by its place; not on a card", () => {
+ const m = {
+ timeline: [
+ { id: "a", type: "clip", audio: { offset: 50 } },
+ { id: "b", type: "clip", audio: { gain: 40 } },
+ { id: "c", type: "card", audio: { gain: 1 } },
+ { id: "d", type: "clip" },
+ ],
+ };
+ assert.deepEqual(validateClipAudioEntries(m), [
+ "timeline[1] (b).audio.gain must be a number from -20 to 20 (dB)",
+ "timeline[2] (c).audio: only a clip's sound has these settings",
+ ]);
+});
+
+test("clipAudioOf / clipAudioFilters / offsetWindow: zeros do nothing; gain, then the fades at the edges", () => {
+ assert.equal(clipAudioOf({}), null);
+ assert.equal(clipAudioOf({ audio: { offset: 0, gain: 0, fadeIn: 0, fadeOut: 0 } }), null);
+ assert.equal(clipAudioOf({ audio: { gain: 99 } }), null, "an invalid one is not applied");
+ const a = clipAudioOf({ audio: { offset: -250, gain: -6, fadeIn: 0.5, fadeOut: 1 } });
+ assert.deepEqual(a, { offset: -250, gain: -6, fadeIn: 0.5, fadeOut: 1 });
+ assert.deepEqual(clipAudioFilters(a, 10), ["volume=-6dB", "afade=t=in:st=0:d=0.5", "afade=t=out:st=9:d=1"]);
+ assert.deepEqual(clipAudioFilters({ fadeOut: 5 }, 3), ["afade=t=out:st=0:d=3"]);
+ assert.deepEqual(clipAudioFilters(null, 3), []);
+ assert.equal(offsetWindow(null, 1, 5), null);
+ assert.deepEqual(offsetWindow({ offset: 300 }, 1, 5), { from: 0.7, to: 4.7 });
+ assert.deepEqual(offsetWindow({ offset: -500 }, 1, 5), { from: 1.5, to: 5.5 });
+ assert.match(AUDIO_ON_CLOCK, /^aresample=async=1:min_hard_comp=0\.01:first_pts=0$/);
+});
+
+// ---- the encode, for real ------------------------------------------------------
+
+const have = ["ffmpeg", "ffprobe", "magick"].every((b) => spawnSync(b, ["-version"]).status === 0);
+const PALETTE = { bg: "#15121c", fg: "#ece8f4", muted: "#9a93ad", accent: "#7c5cff", amber: "#f2b84b" };
+const RENDER = {
+ width: 320, height: 180, fps: 30, audioRate: 48000, audioChannels: 2, preset: "ultrafast",
+ transition: 0, headerHeight: 24, palette: PALETTE, fontRegular: MONO_FONT_FILE, snapWindow: 0.001,
+};
+
+/** The first loud 5 ms window's time in a file's sound, and the loudest window's RMS. */
+function onset(file) {
+ 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, r.stdout.length / 2);
+ let first = null;
+ let peak = 0;
+ for (let i = 0; i + 40 < pcm.length; i += 40) {
+ let sum = 0;
+ for (let k = i; k < i + 40; k += 1) sum += pcm[k] * pcm[k];
+ const rms = Math.sqrt(sum / 40);
+ if (rms > 1000 && first === null) first = i / 8000;
+ peak = Math.max(peak, rms);
+ }
+ return { first, peak };
+}
+
+test("the segment encode: offset moves the burst against the picture, both ways; gain lowers it", { skip: !have && "needs ffmpeg, ffprobe and magick" }, async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "rtv-clip-audio-"));
+ try {
+ await mkdir(path.join(root, "media"), { recursive: true });
+ // Six seconds of picture; a tone burst from 2.0 to 2.5 s.
+ const src = path.join(root, "media", "talk.mp4");
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=320x180:r=30:d=6",
+ "-f", "lavfi", "-i", "sine=f=800:r=48000:d=6",
+ "-filter_complex", "[1:a]volume=enable='not(between(t,2,2.5))':volume=0[a]",
+ "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ac", "2", src,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ await writeFile(path.join(root, "media", "talk.json"), JSON.stringify({
+ duration_seconds: 6, chunk_data: [{ start_time: 1, end_time: 5, text: "A tone." }],
+ }));
+ const manifestPath = path.join(root, "video.manifest.json");
+ const build = async (audio) => {
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "demo", title: "Demo", render: RENDER,
+ timeline: [{
+ id: "c1", type: "clip", src: "media/talk.mp4", cues: "media/talk.json", start: 1, end: 5,
+ title: "Talk", channelTitle: "Demo", date: "2026-01-02", ...(audio ? { audio } : {}),
+ }],
+ }));
+ const out = await buildVideo({ manifestPath, only: "c1", opts: { noNetwork: true } });
+ assert.equal(out.failures.length, 0);
+ const rec = JSON.parse(await readFile(path.join(root, "out", "sourced", "segments", "c1.cut.json"), "utf8"));
+ return { ...onset(out.out), start: rec.start, rec };
+ };
+ const plain = await build(null);
+ const want = 2.0 - plain.start;
+ assert.ok(Math.abs(plain.first - want) <= 0.012, `plain burst at ${plain.first}, expected ${want}`);
+ assert.equal(plain.rec.audio, undefined);
+
+ const later = await build({ offset: 300 });
+ assert.ok(Math.abs(later.first - (want + 0.3)) <= 0.012, `+300 ms burst at ${later.first}, expected ${want + 0.3}`);
+ assert.deepEqual(later.rec.audio, { offset: 300 });
+
+ const earlier = await build({ offset: -300 });
+ assert.ok(Math.abs(earlier.first - (want - 0.3)) <= 0.012, `-300 ms burst at ${earlier.first}, expected ${want - 0.3}`);
+
+ // An offset past the source's head: silence first, the burst still where it should be.
+ const past = await build({ offset: 1500 });
+ assert.ok(Math.abs(past.first - (want + 1.5)) <= 0.012, `+1500 ms burst at ${past.first}, expected ${want + 1.5}`);
+
+ const quiet = await build({ gain: -6 });
+ const ratio = quiet.peak / plain.peak;
+ assert.ok(ratio > 0.45 && ratio < 0.56, `-6 dB peak ratio ${ratio}`);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -81,6 +81,7 @@ import {
validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers,
} from "./deck.mjs";
import { validateClaims } from "./factcheck.mjs";
+import { validateClipAudioEntries } from "./clip-audio.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
import { validateStatsEntries } from "./stats.mjs";
@@ -226,7 +227,7 @@ export function imageSrcsOf(manifest, { only = null } = {}) {
/** The validators a build runs before it renders, as one list of sentences. */
export function validatorErrors(whole) {
const errors = [
- ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole),
+ ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateClipAudioEntries(whole),
...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole),
// The podcast's settings: its render refuses them, and `--lint` says so first.
...validatePodcast(whole),