// 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 }); } });