// The gap mark under a deck, built for real (lane gap-cue, slice 1d, review 1d): tiny encodes, the deck's renderer a // stub that writes transparent frames and logs how many each render drew. What a chrome-only pass does with the mark: // // - off (unset or `mark: false`): the schedule the build writes is the same bytes, no `gapCue` key; // - on, over an old take: the marks on the schedule from the cut records, no segment rebuilt, and the deck still // drawn ONLY where a chunk to encode reads it (deckWant keys the gap-cue windows without drawing them); // - a segment that drew its marks itself (`--no-chrome`): the chrome leaves its marks out, and says why, wanted or not; // - a segment cut before its clip had gaps: no mark at a join its picture does not have, and a note; // - `--clip-preview`: the module's marks, nothing drawn into the segment; // - a clip that is not first, after a real crossfade: its mark at that segment's start plus its join. // // Skipped without ffmpeg/ffprobe. Run with: pnpm test:scripts import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } 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(tmpdir(), "rtv-gapcue-corpus-")); process.env.CHANNELS_DIR = CORPUS; const { buildVideo, measureChromeSchedule, setProgressMode } = await import("./build-video.mjs"); const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs"); const { offsetIn } = await import("./gaps.mjs"); test.after(() => rmSync(CORPUS, { recursive: true, force: true })); const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); const FPS = 10; const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; const RENDER = { width: 640, height: 360, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0, 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, chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { show: false }, footageScale: 0.6 } }, }; { const dir = path.join(CORPUS, "synth", "data", "vid1"); mkdirSync(dir, { recursive: true }); writeFileSync(path.join(CORPUS, "synth", "config.json"), JSON.stringify({ name: "Synth" })); writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 12, uploadDate: "20240102", cues: [{ start: 0.2, end: 11.8, text: "words" }] })); writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 12, channel: "Synth", upload_date: "20240102" })); } const STUB = `#!/usr/bin/env node import { spawnSync } from "node:child_process"; import { appendFileSync, copyFileSync, mkdirSync, readFileSync } from "node:fs"; const a = process.argv.slice(2); const out = a[a.indexOf("--output") + 1]; const fps = Number(a[a.indexOf("--fps") + 1]); const html = readFileSync(a.at(-1) + "/index.html", "utf8"); const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]); const id = /data-composition-id="([^"]*)"/.exec(html)[1]; const w = Number((/data-width="(\\d+)"/.exec(html) ?? [0, 640])[1]); const h = Number((/data-height="(\\d+)"/.exec(html) ?? [0, 360])[1]); mkdirSync(out, { recursive: true }); const one = out + "/.one.png"; spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=black@0.0:size=" + w + "x" + h + ",format=rgba", "-frames:v", "1", one]); const n = Math.round(dur * fps); for (let i = 1; i <= n; i += 1) copyFileSync(one, out + "/frame_" + String(i).padStart(6, "0") + ".png"); appendFileSync(process.env.HF_LOG, id + " " + n + "\\n"); `; /** A project: c1 1–4 s and c2 5–11 s of one 12 s window (noise in bursts, never periodic); c2 may carry gaps. */ function project(t, { c2 = {}, render = {} } = {}) { const root = mkdtempSync(path.join(tmpdir(), "rtv-gapcue-")); const env = { bin: process.env.HYPERFRAMES_BIN, log: process.env.HF_LOG }; t.after(() => { for (const [k, v] of [["HYPERFRAMES_BIN", env.bin], ["HF_LOG", env.log]]) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } setProgressMode(() => {}); rmSync(root, { recursive: true, force: true }); }); const stub = path.join(root, "hf-stub.mjs"); writeFileSync(stub, STUB); chmodSync(stub, 0o755); process.env.HYPERFRAMES_BIN = stub; const log = path.join(root, "renders.log"); process.env.HF_LOG = log; mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); const raw = path.join(root, "out", "clips-raw", "vid1_0.00-12.00.mp4"); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", `testsrc2=s=640x360:r=${FPS}:d=12`, "-f", "lavfi", "-i", "aevalsrc='0.2*(random(0)*2-1)*(0.25+0.75*gt(sin(2*PI*1.3*t+3*sin(2*PI*0.37*t)),0.2))':s=48000:d=12", "-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"); const manifest = { slug: "gapcue", title: "Gap cue", provenance: { channelSlug: "synth", channelsDir: CORPUS }, render: { ...RENDER, ...render }, timeline: [ { type: "clip", id: "c1", channel: "synth", video: "vid1", start: 1, end: 4, cite: 1, quote: "q", onscreen: { title: "First" } }, { type: "clip", id: "c2", channel: "synth", video: "vid1", start: 5, end: 11, cite: 5, quote: "q", onscreen: { title: "Second" }, ...c2 }, ], }; const v = path.join(root, "out", "sourced"); const notes = []; const events = []; setProgressMode((e) => { events.push(e); if (e.ev === "note") notes.push(e.message); }); const p = { root, v, manifestPath, notes, events, write: (fn = null) => { if (fn) fn(manifest); writeFileSync(manifestPath, JSON.stringify(manifest)); }, build: async (opts = {}) => { notes.length = 0; events.length = 0; const { only = null, ...o } = opts; const res = await buildVideo({ manifestPath, ...(only ? { only } : {}), opts: { noNetwork: true, ...o } }); assert.equal(res.failures.length, 0, JSON.stringify(res.failures)); return res; }, schedule: () => readFileSync(path.join(v, "schedule.json"), "utf8"), record: (id) => JSON.parse(readFileSync(path.join(v, "segments", `${id}.cut.json`), "utf8")), md5: (id) => spawnSync("md5sum", [path.join(v, "segments", `${id}.mp4`)]).stdout.toString().split(" ")[0], drawn: () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map((l) => ({ id: l.split(" ")[0], n: Number(l.split(" ")[1]) })) : []), }; p.write(); return p; } const GAP = [{ from: 6.5, to: 9.5 }]; test("--chrome-only, the mark off then on over an old take: the same schedule off; on, the marks from the records, no segment rebuilt, the deck drawn only where a chunk to encode reads it", { skip: !have && "needs ffmpeg" }, async (t) => { const p = project(t, { c2: { gaps: GAP } }); await p.build(); const off = p.schedule(); assert.equal("gapCue" in JSON.parse(off), false, "off: no slice"); const seg0 = { c1: p.md5("c1"), c2: p.md5("c2") }; // Off said otherwise (`mark: false`): the very bytes, nothing drawn, nothing encoded. p.write((m) => { m.render.gapCue = { mark: false }; }); const before = p.drawn().length; await p.build({ chromeOnly: true }); assert.equal(p.schedule(), off, "mark false: the schedule the build wrote before, byte for byte"); assert.ok(p.notes.some((m) => /^final encode: (\d+)\/\1 chunk\(s\) unchanged/.test(m)), p.notes.join("\n")); assert.equal(p.drawn().length, before, "nothing drawn"); // ON, by the switch alone: the retrofit. p.write((m) => { m.render.gapCue = { mark: true }; }); await p.build({ chromeOnly: true }); const sched = JSON.parse(p.schedule()); const rec = p.record("c2"); assert.equal(rec.gapMarks, undefined, "the segment draws none"); assert.deepEqual({ c1: p.md5("c1"), c2: p.md5("c2") }, seg0, "no segment rebuilt"); assert.equal(sched.gapCue.marks.length, 1); const k = sched.gapCue.marks[0]; const s2 = sched.segments[1]; assert.equal(k.segment, "c2"); assert.ok(Math.abs(k.at - (s2.start + offsetIn(6.5, rec.start, rec.gaps))) < 1e-3, `at ${k.at}: c2's start ${s2.start} + its join`); assert.equal(k.text, "» 3 s"); // Lazy still (review 1d, 3): the deck's frames drawn only for the chunks the mark's window touches. const read = p.notes.find((m) => /chunk\(s\) to encode read \d+ of \d+ deck-frames frames/.test(m)); assert.ok(read, p.notes.join("\n")); const [, todo, chunks, need, frames] = /(\d+) of (\d+) chunk\(s\) to encode read (\d+) of (\d+) deck-frames/.exec(read).map(Number); assert.ok(todo < chunks && need < frames, `only the mark's chunks: ${read}`); const deckDrawn = p.drawn().slice(before).filter((d) => d.id === "deck"); assert.ok(deckDrawn.every((d) => d.n <= need), `the deck drew ${deckDrawn.map((d) => d.n)} of ${frames}`); assert.ok(p.drawn().slice(before).some((d) => d.id === "gap-cue"), "the mark's page was drawn"); assert.ok(!readdirSync(path.join(p.v, "chrome")).some((f) => f.endsWith(".keys")), "the keys' scratch projects are gone"); t.diagnostic(`retrofit cost: ${read}; deck frames drawn ${deckDrawn.map((d) => d.n).join("+") || 0}`); // Again: nothing to encode, and no deck frame drawn (the keys composed without drawing are the ones drawn). The // mark's own few frames were pruned after the mux, as every window module's are: those are captured again. const runs = p.drawn().length; await p.build({ chromeOnly: true }); assert.ok(p.notes.some((m) => /^final encode: (\d+)\/\1 chunk\(s\) unchanged/.test(m)), p.notes.join("\n")); assert.ok(p.notes.some((m) => /0 of \d+ chunk\(s\) to encode read 0 of \d+ deck-frames frames/.test(m)), p.notes.join("\n")); assert.deepEqual(p.drawn().slice(runs).filter((d) => d.id === "deck"), [], "no deck frame drawn"); // What it cost before (the deck lazy only when it is the one layer): a label change re-encodes the same one chunk, // but every deck frame is drawn. const { LAZY_BESIDE } = await import("./build-video.mjs"); LAZY_BESIDE.delete("gap-cue"); try { p.write((m) => { m.render.gapCue = { mark: true, label: "{s} later" }; }); const at = p.drawn().length; await p.build({ chromeOnly: true }); // Every frame asked for (no "only those are drawn" note); the capture still skips frames it can key as the same. assert.ok(!p.notes.some((m) => /deck-frames frames — only those are drawn/.test(m)), p.notes.join("\n")); const all = p.drawn().slice(at).filter((d) => d.id === "deck").reduce((n, d) => n + d.n, 0); const lazy = deckDrawn.reduce((n, d) => n + d.n, 0); assert.ok(all > lazy, `not lazy: ${all} deck frames drawn, lazily ${lazy}`); t.diagnostic(`without the gap-cue keys: all ${frames} deck frames asked for, ${all} drawn (lazily: ${need} asked for, ${lazy} drawn)`); } finally { LAZY_BESIDE.add("gap-cue"); } }); test("--chrome-only over a segment that drew its own marks (--no-chrome): the chrome leaves its marks out and says so, wanted or not", { skip: !have && "needs ffmpeg" }, async (t) => { const p = project(t, { c2: { gaps: GAP }, render: { gapCue: { mark: true } } }); await p.build({ noChrome: true }); assert.equal(p.record("c2").gapMarks?.length, 1, "--no-chrome drew it into the segment"); await p.build({ chromeOnly: true }); assert.deepEqual(JSON.parse(p.schedule()).gapCue, { marks: [], inSegment: ["c2"] }); assert.ok(p.notes.includes("c2: its gap marks are drawn in its segment (built with no chrome drawing them) — --chrome-only leaves the chrome's out for it; rebuild it (a build without --chrome-only, or --only c2) to let the chrome draw them"), p.notes.join("\n")); assert.ok(!p.events.some((e) => e.ev === "chrome" && e.region === "gap-cue"), "no gap-cue page"); p.write((m) => { m.render.gapCue = { mark: false }; }); await p.build({ chromeOnly: true }); assert.ok(p.notes.includes("c2: its segment still shows gap marks that are no longer wanted — --chrome-only cannot take them out; rebuild it (a build without --chrome-only, or --only c2)"), p.notes.join("\n")); assert.equal("gapCue" in JSON.parse(p.schedule()), false); }); test("--chrome-only over a segment cut before its clip had gaps: no mark at a join the picture does not have, and a note", { skip: !have && "needs ffmpeg" }, async (t) => { const p = project(t); await p.build(); assert.equal(p.record("c2").gaps, undefined); p.write((m) => { m.timeline[1].gaps = GAP; m.render.gapCue = { mark: true }; }); await p.build({ chromeOnly: true }); assert.equal("gapCue" in JSON.parse(p.schedule()), false, "no mark"); assert.ok(p.notes.includes("c2: its segment was cut before its gaps — the footage plays them and no gap mark is drawn for them; rebuild it (a build without --chrome-only, or --only c2) to cut them"), p.notes.join("\n")); }); test("--clip-preview lays the deck over its clip: the module's mark, nothing drawn into the segment", { skip: !have && "needs ffmpeg" }, async (t) => { const p = project(t, { c2: { gaps: GAP }, render: { gapCue: { mark: true } } }); await p.build({ clipPreview: "c2" }); assert.equal(p.record("c2").gapMarks, undefined); const pv = JSON.parse(readFileSync(path.join(p.v, "clip-preview", "schedule.json"), "utf8")); assert.equal(pv.gapCue.marks.length, 1); assert.equal(pv.gapCue.marks[0].segment, "c2"); assert.ok(p.events.some((e) => e.ev === "chrome" && e.region === "gap-cue" && e.phase !== "compose"), "its page drawn"); }); test("a clip that is not first, after a real crossfade: measureChromeSchedule puts its mark at its segment's start plus its join", { skip: !have && "needs ffmpeg" }, async (t) => { const p = project(t, { c2: { gaps: GAP }, render: { transition: 0.4, gapCue: { mark: true } } }); for (const id of ["c1", "c2"]) await p.build({ only: id }); const m = JSON.parse(readFileSync(p.manifestPath, "utf8")); const segments = ["c1", "c2"].map((id) => path.join(p.v, "segments", `${id}.mp4`)); const sched = await measureChromeSchedule({ manifest: m, entries: m.timeline, segments, D: 0.4 }); const [s1, s2] = sched.segments; assert.ok(Math.abs(s2.start - (s1.duration - 0.4)) < 1e-3, `c2 starts in c1's dissolve (${s2.start} vs ${s1.duration} - 0.4)`); const rec = p.record("c2"); const k = sched.gapCue.marks[0]; assert.ok(Math.abs(k.at - (s2.start + offsetIn(6.5, rec.start, rec.gaps))) < 1e-3, `at ${k.at}`); // The same with the mark off: no key; every other byte of the schedule the same. const off = await measureChromeSchedule({ manifest: { ...m, render: { ...m.render, gapCue: { mark: false } } }, entries: m.timeline, segments, D: 0.4 }); const { gapCue: _g, ...rest } = sched; assert.equal("gapCue" in off, false); assert.equal(JSON.stringify(off), JSON.stringify(rest)); });