// The clip kit, rendered for real (lane clip-kit): a desktop clip (slice C) and a short's code (slice B) on a // synthetic window -- the frame's size, the code where it is said to stand, the source line's plate -- and, with // none of the kit's keys, a short built exactly as before. // // 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. const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-kit-corpus-")); process.env.CHANNELS_DIR = CORPUS; const { buildVideo, setProgressMode } = await import("./build-video.mjs"); const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs"); const { desktopQrBox, verticalQrBox } = await import("./clip-kit.mjs"); const { clipGeometry, desktopSafeArea, safeArea } = await import("./vertical.mjs"); // Every module this file reads, loaded before the first test is declared: a test declared after a top-level await // can start after the root's after-hook has removed the corpus (node:test ends the root once its queue is empty). const { probeDuration } = await import("./build-video.mjs"); const { promoBand } = await import("./promo-card.mjs"); const havePw = await import("@playwright/test").then((m) => !!(m.chromium ?? m.default?.chromium), () => false); test.after(() => rm(CORPUS, { recursive: true, force: true })); const have = ["ffmpeg", "ffprobe", "qrencode"].every((b) => spawnSync(b, b === "qrencode" ? ["--version"] : ["-version"]).status === 0); const FPS = 30; const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" }; const RENDER = { width: 1920, height: 1080, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0, headerHeight: 0, footerHeight: 0, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, fetchPad: 0, snapWindow: 0.05, silenceMinDur: 0.1, }; const CHANNEL = "synth"; const VIDEO = "vid-0123456789"; { 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: 6, uploadDate: "20240102", cues: [{ start: 0.2, end: 5.8, text: "a line said over the clip" }] })); writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: VIDEO, title: "Synthetic", duration: 6, webpage_url: `https://kick.com/synth/videos/${VIDEO}` })); } /** A project: one clip, 1–4 s of a 6 s grey 1920x1080 window with a tone. */ async function project({ clip = {}, render = {} } = {}) { const root = mkdtempSync(path.join(os.tmpdir(), "rtv-kit-")); mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); const raw = path.join(root, "out", "clips-raw", `${VIDEO}_0.00-6.00.mp4`); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=1920x1080:r=${FPS}:d=6`, "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=6", "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, ]); assert.equal(r.status, 0, String(r.stderr)); const manifestPath = path.join(root, "video.manifest.json"); await writeFile(manifestPath, JSON.stringify({ slug: "kit", title: "Kit", provenance: { channelSlug: CHANNEL, channelsDir: CORPUS, siteOrigin: "" }, render: { ...RENDER, ...render }, timeline: [{ type: "clip", id: "c1", channel: CHANNEL, video: VIDEO, start: 1, end: 4, cite: 1, quote: "q", citeUrl: `https://kick.com/synth/videos/${VIDEO}`, ...clip }], })); return { root, manifestPath }; } const quiet = () => setProgressMode(() => {}); /** The picture's size. */ function dims(file) { const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]); return String(r.stdout).trim(); } /** The luma's min and max over a box of a frame `t` s in: a code is black and white, the grey ground is neither. */ function range(file, box, t = 1) { const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", `crop=${box.w}:${box.h}:${box.x}:${box.y},signalstats,metadata=print:file=-`, "-f", "null", "-"], { maxBuffer: 1 << 24 }); const out = String(r.stdout); const get = (k) => Number((new RegExp(`lavfi\\.signalstats\\.${k}=([0-9.]+)`).exec(out) ?? [])[1]); return { min: get("YMIN"), max: get("YMAX") }; } const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0]; test("a desktop clip: 1920x1080, the picture full frame, the code in its corner, the source line on its plate", { skip: !have && "needs ffmpeg and qrencode" }, async () => { quiet(); const p = await project(); try { const out = path.join(p.root, "out", "kit.desktop.mp4"); await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, desktop: true, desktopKnobs: { qr: { corner: "br" } }, verticalOut: out } }); assert.equal(dims(out), "1920,1080"); const seg = path.join(p.root, "out", "desktop", "segments", "c1.mp4"); const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); assert.equal(rec.vertical.layout, "desktop"); assert.equal(rec.vertical.qr.url, `https://kick.com/synth/videos/${VIDEO}?t=1`, "the source at the clip's second"); const box = desktopQrBox({ corner: "br", size: 0.09 }, { W: 1920, safe: desktopSafeArea({}, 1920, 1080) }); assert.deepEqual([rec.vertical.qr.x, rec.vertical.qr.y, rec.vertical.qr.size], [box.x, box.y, box.size]); const inQr = range(seg, { x: box.x + 8, y: box.y + 8, w: box.size - 16, h: box.size - 16 }); assert.ok(inQr.min < 40 && inQr.max > 215, `the code is drawn there (${JSON.stringify(inQr)})`); // The opposite corner: the grey picture alone (no letterbox, nothing drawn). const bare = range(seg, { x: 60, y: 1080 - box.size - 90, w: box.size, h: box.size }); assert.ok(bare.min > 100 && bare.max < 150, `the picture full frame there (${JSON.stringify(bare)})`); // The source line: its plate darkens the top left of the safe area. const s = desktopSafeArea({}, 1920, 1080); const plate = range(seg, { x: s.x0 + 4, y: s.y0 + 4, w: 40, h: 16 }); assert.ok(plate.min < 110, `the source line's plate (${JSON.stringify(plate)})`); } finally { await rm(p.root, { recursive: true, force: true }); } }); test("a short's code: at the top right of the safe area; none unless asked, the short as it was", { skip: !have && "needs ffmpeg and qrencode" }, async () => { quiet(); const ps = [await project(), await project({ render: { vertical: { qr: false } } }), await project()]; try { const outs = ps.map((p) => path.join(p.root, "out", "kit.vertical.mp4")); await buildVideo({ manifestPath: ps[0].manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: outs[0] } }); await buildVideo({ manifestPath: ps[1].manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: outs[1] } }); await buildVideo({ manifestPath: ps[2].manifestPath, opts: { noNetwork: true, vertical: true, verticalKnobs: { qr: true }, verticalOut: outs[2] } }); const segs = ps.map((p) => path.join(p.root, "out", "vertical", "segments", "c1.mp4")); // No code asked (absent, or false): the same segment, its record naming none. assert.equal(md5(segs[0]), md5(segs[1])); const rec0 = JSON.parse(await readFile(segs[0].replace(/\.mp4$/, ".cut.json"), "utf8")); assert.equal(rec0.vertical.qr, undefined); assert.equal(dims(outs[2]), "1080,1920"); const rec = JSON.parse(await readFile(segs[2].replace(/\.mp4$/, ".cut.json"), "utf8")); const geo = clipGeometry("full", { format: "vertical" }, 1080, 1920); const box = verticalQrBox({ corner: "tr", size: 0.16 }, { W: 1080, safe: safeArea({ format: "vertical" }, 1080, 1920), tag: geo.tag }); assert.deepEqual([rec.vertical.qr.x, rec.vertical.qr.y, rec.vertical.qr.corner], [box.x, box.y, "tr"]); const inQr = range(segs[2], { x: box.x + 8, y: box.y + 8, w: box.size - 16, h: box.size - 16 }); assert.ok(inQr.min < 40 && inQr.max > 215, `the code is drawn there (${JSON.stringify(inQr)})`); const without = range(segs[0], { x: box.x + 8, y: box.y + 8, w: box.size - 16, h: box.size - 16 }); assert.ok(without.max < 200, `no code without one asked (${JSON.stringify(without)})`); } finally { for (const p of ps) await rm(p.root, { recursive: true, force: true }); } }); // ---- slice D: the channel promo ------------------------------------------------------------------------------------- /** The picture's mean luma at `t` s. */ function yavg(file, t) { const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", "signalstats,metadata=print:file=-", "-f", "null", "-"], { maxBuffer: 1 << 24 }); return Number((/lavfi\.signalstats\.YAVG=([0-9.]+)/.exec(String(r.stdout)) ?? [])[1]); } /** The RMS of a file's sound over [a, b] (s), mono 8 kHz. */ 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 PROMO = { name: ["Example Channel", "Live"], url: "https://kick.com/synth", portrait: { file: "shots/face.png" }, lead: 2, fade: 0.5, hold: 1 }; async function promoProject(o = {}) { const p = await project({ render: { promo: PROMO }, ...o }); mkdirSync(path.join(p.root, "shots"), { recursive: true }); const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=400x400:d=1", "-frames:v", "1", path.join(p.root, "shots", "face.png")]); assert.equal(r.status, 0, String(r.stderr)); return p; } test("the promo: the clip dissolves into the card over its last seconds, its sound under it, then the card held in silence", { skip: (!have || !havePw) && "needs ffmpeg, qrencode and Playwright's chromium" }, async () => { quiet(); for (const fmt of ["vertical", "desktop"]) { const p = await promoProject(); try { const out = path.join(p.root, "out", `kit.${fmt}.mp4`); await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, [fmt]: true, verticalOut: out } }); const seg = path.join(p.root, "out", fmt, "segments", "c1.mp4"); const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); assert.deepEqual([rec.promo.lead, rec.promo.fade, rec.promo.hold, rec.promo.captions], [2, 0.5, 1, true], fmt); const S = 3; // the clip: 1–4 s const d = await probeDuration(seg, FPS); assert.ok(Math.abs(d - (S + 1)) <= 2 / FPS, `${fmt}: the segment is the clip and the hold (${d})`); assert.ok(yavg(seg, S - 2 - 0.4) > 100, `${fmt}: the clip before the card`); assert.ok(yavg(seg, S - 2 + 0.5 + 0.4) < 70, `${fmt}: the card up while the clip still plays`); assert.ok(yavg(seg, S + 0.6) < 70, `${fmt}: the card held`); assert.ok(rms(seg, S - 1.5, S - 0.3) > 800, `${fmt}: the clip's sound under the card`); assert.ok(rms(seg, S + 0.1, S + 0.95) < 20, `${fmt}: silence on the card`); // The captions over the card stand in its band. const ass = await readFile(seg.replace(/\.mp4$/, ".vertical.ass"), "utf8"); const [W, H] = fmt === "vertical" ? [1080, 1920] : [1920, 1080]; const band = promoBand({ width: W, height: H }).band; assert.match(ass, new RegExp(`\\\\pos\\(\\d+,${band.y1}\\)`), `${fmt}: a caption in the card's band`); assert.equal(dims(out), fmt === "vertical" ? "1080,1920" : "1920,1080"); } finally { await rm(p.root, { recursive: true, force: true }); } } }); test("the promo: a clip's `promo: false` ends without it, exactly as a cut that sets none", { skip: (!have || !havePw) && "needs ffmpeg, qrencode and Playwright's chromium" }, async () => { quiet(); const ps = [await project(), await promoProject({ clip: { promo: false } })]; try { for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: path.join(p.root, "out", "kit.vertical.mp4") } }); const segs = ps.map((p) => path.join(p.root, "out", "vertical", "segments", "c1.mp4")); assert.equal(md5(segs[0]), md5(segs[1])); assert.equal(JSON.parse(await readFile(segs[1].replace(/\.mp4$/, ".cut.json"), "utf8")).promo, undefined); } finally { for (const p of ps) await rm(p.root, { recursive: true, force: true }); } }); // ---- slice F: zoom at points ---------------------------------------------------------------------------------------- /** The mean luma of a box of a frame `t` s in. */ function boxAvg(file, box, t) { const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", `crop=${box.w}:${box.h}:${box.x}:${box.y},signalstats,metadata=print:file=-`, "-f", "null", "-"], { maxBuffer: 1 << 24 }); return Number((/lavfi\.signalstats\.YAVG=([0-9.]+)/.exec(String(r.stdout)) ?? [])[1]); } test("a zoom: the framed short's picture pushed in on its focus for its span, eased back out; refused past the sharp limit", { skip: !have && "needs ffmpeg and qrencode" }, async () => { quiet(); // A window whose left half is white and right half black: pushed in on its left edge, the picture is mostly white. const p = await project({ render: { vertical: { clip: "framed" } }, clip: { zooms: [{ at: 1.5, scale: 1.75, focus: [0, 0.5], hold: 1, ramp: 0.3 }] } }); const raw = path.join(p.root, "out", "clips-raw", `${VIDEO}_0.00-6.00.mp4`); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=black:s=1920x1080:r=${FPS}:d=6`, "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=6", "-filter_complex", "[0:v]drawbox=x=0:y=0:w=960:h=1080:c=white:t=fill[v]", "-map", "[v]", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, ]); assert.equal(r.status, 0, String(r.stderr)); try { await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: path.join(p.root, "out", "kit.vertical.mp4") } }); const seg = path.join(p.root, "out", "vertical", "segments", "c1.mp4"); const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); assert.deepEqual([rec.zooms[0].at, rec.zooms[0].scale, rec.zooms[0].focus], [0.5, 1.75, [0, 0.5]]); const v = clipGeometry("framed", { format: "vertical" }, 1080, 1920).video; const box = { x: 0, y: v.y + 40, w: 1080, h: v.h - 80 }; const before = boxAvg(seg, box, 0.2); const pushed = boxAvg(seg, box, 1.3); const after = boxAvg(seg, box, 2.6); assert.ok(before > 100 && before < 150, `half white before (${before})`); assert.ok(pushed > 180, `pushed in on the white (${pushed})`); assert.ok(Math.abs(after - before) < 12, `back out after (${after} vs ${before})`); // Past the sharp limit (a 1080 window in a full 9:16 crop is already past its pixels): refused, by name. const m = JSON.parse(await readFile(p.manifestPath, "utf8")); m.render.vertical = { clip: "full" }; await writeFile(p.manifestPath, JSON.stringify(m)); await assert.rejects(buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: path.join(p.root, "out", "kit2.vertical.mp4") } }), /zooms: c1: the zoom at 1\.5 s \(×1\.75\) plays its source at .* the limit here is ×1/); } finally { await rm(p.root, { recursive: true, force: true }); } }); // ---- the corner code in every entry type a cut with no deck draws (review B1) --------------------------------------- test("a cut with no deck, the QR on and off: a clip, a still with a citeUrl, a title card and a video entry all build; the codes where they always were", { skip: !have && "needs ffmpeg and qrencode" }, async () => { quiet(); for (const qr of [{ scale: 4 }, false, { corner: "tl" }]) { const p = await project({ render: { width: 640, height: 360, headerHeight: 0, qr } }); try { mkdirSync(path.join(p.root, "stills"), { recursive: true }); const still = path.join(p.root, "stills", "one.png"); const vid = path.join(p.root, "stills", "v.mp4"); assert.equal(spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=640x360:d=1", "-frames:v", "1", still]).status, 0); assert.equal(spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=640x360:r=${FPS}:d=2`, "-f", "lavfi", "-i", "sine=frequency=330:sample_rate=48000:duration=2", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", vid]).status, 0); const m = JSON.parse(await readFile(p.manifestPath, "utf8")); m.timeline.push( { type: "image", id: "i1", src: "stills/one.png", seconds: 1.5, citeUrl: "https://example.test/still/1" }, { type: "card", id: "k1", style: "title", heading: "A heading", seconds: 2 }, { type: "video", id: "v1", src: "stills/v.mp4" }, ); await writeFile(p.manifestPath, JSON.stringify(m)); const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); assert.ok(r.out, `built (qr ${JSON.stringify(qr)})`); const segs = path.join(p.root, "out", "sourced", "segments"); if (qr === false) continue; // The still's code: bottom right (as it always was), or the cut's corner. const size = 64; const at = qr.corner === "tl" ? { x: 28 + 4, y: 28 + 4 } : { x: 640 - 28 - size + 8, y: 360 - 28 - size + 8 }; const box = { ...at, w: 24, h: 24 }; const inStill = range(path.join(segs, "i1.mp4"), box, 0.5); assert.ok(inStill.max > 215 || inStill.min < 40, `the still's code is drawn at its corner (qr ${JSON.stringify(qr)}: ${JSON.stringify(inStill)})`); } finally { await rm(p.root, { recursive: true, force: true }); } } }); // ---- slice E: hidden regions ---------------------------------------------------------------------------------------- test("hidden regions: a recording's box on every clip of it, in a cut and in a short; a box over a span; on in the uncensored cut; another recording's changes nothing", { skip: !have && "needs ffmpeg and qrencode" }, async () => { quiet(); // The window is a grey picture with WHITE in its right quarter (a stand-in chat overlay); the box blacks it out. const white = async (p) => { const raw = path.join(p.root, "out", "clips-raw", `${VIDEO}_0.00-6.00.mp4`); const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=1920x1080:r=${FPS}:d=6`, "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=6", "-filter_complex", "[0:v]drawbox=x=1440:y=0:w=480:h=1080:c=white:t=fill[v]", "-map", "[v]", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw]); assert.equal(r.status, 0, String(r.stderr)); }; const CHAT = { video: VIDEO, boxes: [[0.75, 0, 0.25, 1]], style: "black" }; const ps = [ await project({ render: { qr: false, censor: [CHAT], blur: "off" } }), await project({ render: { qr: false, censor: [{ ...CHAT, boxes: [{ box: [0.75, 0, 0.25, 1], from: 2.5, to: 4 }] }] } }), await project({ render: { qr: false } }), await project({ render: { qr: false, censor: [{ ...CHAT, video: "another-recording" }] } }), ]; try { for (const p of ps) await white(p); for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); const seg = (p) => path.join(p.root, "out", "sourced", "segments", "c1.mp4"); const right = { x: 1500, y: 300, w: 300, h: 300 }; // The whole clip, in the uncensored variant too: black where the overlay was. assert.ok(boxAvg(seg(ps[0]), right, 1) < 40, `hidden (${boxAvg(seg(ps[0]), right, 1)})`); assert.deepEqual(JSON.parse(await readFile(seg(ps[0]).replace(/\.mp4$/, ".cut.json"), "utf8")).censor, [{ box: [0.75, 0, 0.25, 1], style: "black" }]); // Over its span only (source 2.5–4 s, the clip from 1 s): shown at 0.5 s, hidden at 2 s. assert.ok(boxAvg(seg(ps[1]), right, 0.5) > 200 && boxAvg(seg(ps[1]), right, 2) < 40, "over its span"); // Another recording's boxes change nothing: the segment as with none. assert.equal(md5(seg(ps[3])), md5(seg(ps[2]))); assert.equal(JSON.parse(await readFile(seg(ps[2]).replace(/\.mp4$/, ".cut.json"), "utf8")).censor, undefined); // A short of the same clip: the box is the same part of the recording (hidden under its framed layout too). const m = JSON.parse(await readFile(ps[0].manifestPath, "utf8")); m.render.vertical = { clip: "framed" }; await writeFile(ps[0].manifestPath, JSON.stringify(m)); await buildVideo({ manifestPath: ps[0].manifestPath, opts: { noNetwork: true, vertical: true, verticalOut: path.join(ps[0].root, "out", "kit.vertical.mp4") } }); const v = clipGeometry("framed", { format: "vertical" }, 1080, 1920).video; const vseg = path.join(ps[0].root, "out", "vertical", "segments", "c1.mp4"); assert.ok(boxAvg(vseg, { x: 860, y: v.y + 100, w: 180, h: 200 }, 1) < 40, "hidden in the short's picture"); } finally { for (const p of ps) await rm(p.root, { recursive: true, force: true }); } });