// Gaps inside a clip (gaps.mjs), rendered for real and on the schedule: a clip // with a gap is ONE segment, the kept seconds long, with the gap's picture and // sound gone and its cut record naming what it left out; the cut is the // segments' sum less the joins, as ever; absent or `[]` the render is byte for // byte what it was. And every mapping of a source second onto the cut that // reads the record -- the mute mark at the join, a claim stamped at a source // second, the estimate's length -- jumps with the gap. // // 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, so it is this file's own. const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-gaps-corpus-")); process.env.CHANNELS_DIR = CORPUS; const { buildVideo, fetchSpans, piecesClock, probeDuration, setProgressMode, virtualEntry } = await import("./build-video.mjs"); const { deckSchedule, estimatedDuration, muteSegmentSeconds, segmentSoundEdits } = await import("./deck.mjs"); const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs"); const { renderCut, snapCut } = await import("./snap.mjs"); test.after(() => rm(CORPUS, { recursive: true, force: true })); const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); const FPS = 30; const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" }; const RENDER = { width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0.4, 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, }; const CHANNEL = "synth"; { const dir = path.join(CORPUS, CHANNEL, "data", "vid1"); 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: "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 })); } /** * A project: c1 1–6 s and c2 7–10 s of one 12 s window in out/clips-raw: a * grey picture and a tone, BLACK and SILENT over 3–4 s (the gap c1 may take * out), so what the render kept can be seen and heard. */ async function project(c1 = {}) { const root = mkdtempSync(path.join(os.tmpdir(), "rtv-gaps-")); 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", `color=c=gray:s=320x180:r=${FPS}:d=12`, "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", "-filter_complex", "[0:v]drawbox=c=black:t=fill:enable='between(t,3,3.99)'[v];[1:a]volume=enable='between(t,3,3.99)':volume=0,volume=0.5[a]", "-map", "[v]", "-map", "[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: "gaps", title: "Gaps", provenance: { channelSlug: CHANNEL, channelsDir: CORPUS }, render: RENDER, timeline: [ { type: "clip", id: "c1", channel: CHANNEL, video: "vid1", start: 1, end: 6, cite: 1, quote: "q", ...c1 }, { type: "clip", id: "c2", channel: CHANNEL, video: "vid1", start: 7, end: 10, cite: 7, quote: "q" }, ], })); return { root, manifestPath, seg: (id) => path.join(root, "out", "sourced", "segments", `${id}.mp4`) }; } const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0]; const quiet = () => setProgressMode(() => {}); const record = async (p, id) => JSON.parse(await readFile(p.seg(id).replace(/\.mp4$/, ".cut.json"), "utf8")); const near = (a, b, tol, what) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); /** Each frame's mean luma. */ function lumas(file) { const st = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"], { maxBuffer: 1 << 24 }); return st.stdout.toString().split("\n").filter((l) => l.includes("YAVG")).map((l) => Number(l.split("=")[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; } test("render: without gaps (absent or []) the cut is byte for byte the same, and the record says nothing new", { skip: !have && "needs ffmpeg" }, async () => { quiet(); const ps = [await project({}), await project({ gaps: [] })]; try { for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); for (const f of ["gaps.mp4", "sourced/segments/c1.mp4", "sourced/segments/c2.mp4", "sourced/segments/c1.cut.json"]) { const sums = ps.map((p) => md5(path.join(p.root, "out", f))); assert.equal(new Set(sums).size, 1, `${f}: ${sums.join(" ")}`); } assert.equal((await record(ps[0], "c1")).gaps, undefined); // The black and the silence are in c1 without the gap (2–3 s into it). assert.ok(Math.min(...lumas(ps[0].seg("c1"))) < 30, "the gap's black plays without gaps"); } finally { for (const p of ps) await rm(p.root, { recursive: true, force: true }); } }); test("render: a gap is taken out of ONE segment -- the kept seconds long, no black, no silence; the record names it; the cut is the sum less the join", { skip: !have && "needs ffmpeg" }, async () => { quiet(); const p = await project({ gaps: [{ from: 3, to: 4 }] }); try { const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); const rec = await record(p, "c1"); assert.deepEqual([rec.start, rec.end], [1, 6]); assert.deepEqual(rec.gaps, [{ from: 3, to: 4 }]); const d1 = await probeDuration(p.seg("c1"), FPS); near(d1, 4, 1 / FPS + 1e-6, "c1 is its 5 s less the 1 s gap"); const y = lumas(p.seg("c1")); assert.ok(Math.min(...y) > 60, `no black frame left in c1 (min YAVG ${Math.min(...y)})`); // Heard all through: before the join, across it (its fades are 25 ms), after. assert.ok(rms(p.seg("c1"), 0.2, 1.9) > 800, "before the join"); assert.ok(rms(p.seg("c1"), 1.9, 2.1) > 600, "across the join"); assert.ok(rms(p.seg("c1"), 2.1, 3.8) > 800, "after the join"); const d2 = await probeDuration(p.seg("c2"), FPS); near(await probeDuration(r.out, FPS), d1 + d2 - 0.4, 2 / FPS, "the cut's length"); // A gap changed is that segment re-rendered, and only that one. const c2Before = md5(p.seg("c2")); const m = JSON.parse(await readFile(p.manifestPath, "utf8")); m.timeline[0].gaps = [{ from: 2, to: 2.5 }]; await writeFile(p.manifestPath, JSON.stringify(m)); const events = []; setProgressMode((e) => events.push(e)); await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); near(await probeDuration(p.seg("c1"), FPS), 4.5, 1 / FPS + 1e-6, "c1 with the new gap"); assert.equal(md5(p.seg("c2")), c2Before, "c2 untouched"); const reused = events.filter((e) => e.ev === "note" && / segment unchanged /.test(e.message)).map((e) => e.message.split(":")[0]); assert.ok(reused.includes("c2"), `c2 was reused (${JSON.stringify(reused)})`); assert.ok(!reused.includes("c1"), `c1 was rebuilt (${JSON.stringify(reused)})`); } finally { await rm(p.root, { recursive: true, force: true }); } }); // ---- the mark at a gap's join (gap-mark.mjs; common gapCue.mjs) ------------------- /** Each frame's mean luma over a `w` × `h` crop at (x, y). */ function cropLumas(file, x, y, w, h) { const st = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `crop=${w}:${h}:${x}:${y},signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-`, "-f", "null", "-"], { maxBuffer: 1 << 24 }); return st.stdout.toString().split("\n").filter((l) => l.includes("YAVG")).map((l) => Number(l.split("=")[1])); } const setManifest = async (p, fn) => { const m = JSON.parse(await readFile(p.manifestPath, "utf8")); fn(m); await writeFile(p.manifestPath, JSON.stringify(m)); }; const reusedIds = (events) => events.filter((e) => e.ev === "note" && / segment unchanged /.test(e.message)).map((e) => e.message.split(":")[0]); test("the gap mark OFF -- nothing set, mark false, a gap's why, a marked gap under min -- is the segment it was: reused, the same key, nothing new in its record", { skip: !have && "needs ffmpeg" }, async () => { quiet(); const p = await project({ gaps: [{ from: 3, to: 4 }] }); try { await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); const was = await record(p, "c1"); const bytes = md5(p.seg("c1")); const offs = [ (m) => { m.render.gapCue = { mark: false }; }, (m) => { m.timeline[0].gaps[0].why = "dead-air"; m.timeline[0].gapCue = { corner: "br" }; }, // On, but the gap is 1 s: under the default 2 s minimum it draws nothing. (m) => { m.render.gapCue = { mark: true }; }, ]; for (const off of offs) { await setManifest(p, off); const events = []; setProgressMode((e) => events.push(e)); await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); assert.ok(reusedIds(events).includes("c1"), `c1 reused (${JSON.stringify(reusedIds(events))})`); const now = await record(p, "c1"); assert.equal(now.segKey, was.segKey, "the same key: the same argv, inputs and record"); assert.equal(now.gapMarks, undefined); assert.equal(md5(p.seg("c1")), bytes); } } finally { await rm(p.root, { recursive: true, force: true }); } }); test("the gap mark ON draws '» 1 s' at the join over its life, in the record; only that segment re-renders; off again it is the plain segment's bytes", { skip: !have && "needs ffmpeg" }, async () => { quiet(); const p = await project({ gaps: [{ from: 3, to: 4 }] }); const plain = await project({ gaps: [{ from: 3, to: 4 }] }); try { await buildVideo({ manifestPath: plain.manifestPath, opts: { noNetwork: true } }); await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); const c2 = md5(p.seg("c2")); await setManifest(p, (m) => { m.render.gapCue = { mark: true, min: 0.5 }; }); const events = []; setProgressMode((e) => events.push(e)); await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); assert.ok(!reusedIds(events).includes("c1") && reusedIds(events).includes("c2"), `c1 rebuilt, c2 reused (${JSON.stringify(reusedIds(events))})`); assert.equal(md5(p.seg("c2")), c2); const rec = await record(p, "c1"); // The join: 2 s into c1 (1–3 plays, 3–4 is out). Up 1.1 s, at the plain cut's top left. // Its border (variant B): the render's palette accent, recorded beside where it stood. const accent = JSON.parse(await readFile(p.manifestPath, "utf8")).render.palette.accent; assert.equal(accent, PALETTE.accent); assert.deepEqual(rec.gapMarks.map(({ rect, ...m }) => m), [{ at: 2, until: 3.1, seconds: 1, text: "» 1 s", corner: "tl", border: accent }]); assert.deepEqual([rec.gapMarks[0].rect.x, rec.gapMarks[0].rect.y], [8, 8], "the record says where it was drawn: the picture's top left, inset"); near(await probeDuration(p.seg("c1"), FPS), 4, 1 / FPS + 1e-6, "the mark adds no time"); // Its box at 320×180 (GAP_CUE_LOOK): inset 8, a 2 px accent border, then the dark box (5 px above a 12 px face): // the box's top inside the border is darker than the grey while it is up. const y = cropLumas(p.seg("c1"), 11, 10, 30, 4); const yPlain = cropLumas(plain.seg("c1"), 11, 10, 30, 4); const at = (arr, t) => arr[Math.floor(t * FPS)]; near(at(y, 1.5), at(yPlain, 1.5), 1, "before the join: as plain"); assert.ok(at(yPlain, 2.5) - at(y, 2.5) > 20, `up at 2.5 s (${at(y, 2.5)} vs ${at(yPlain, 2.5)})`); near(at(y, 3.5), at(yPlain, 3.5), 1, "gone after its life"); // Off again: the plain segment, byte for byte. await setManifest(p, (m) => { delete m.render.gapCue; }); await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); assert.equal(md5(p.seg("c1")), md5(plain.seg("c1"))); assert.equal((await record(p, "c1")).gapMarks, undefined); } finally { await rm(p.root, { recursive: true, force: true }); await rm(plain.root, { recursive: true, force: true }); } }); test("the gap mark draws a reason as written: a % and a backslash are words, the build never stops on them (review 1, 1)", { skip: !have && "needs ffmpeg" }, async () => { quiet(); const { clipGapCueOf } = await import("yt-dlp-transcript-common/lib/report/gapCue.mjs"); const { clipGapMarks } = await import("../lib/report/gapCueView.mjs"); for (const reason of ["100% idle", "a\\b c", "50% %d"]) { const p = await project({ gaps: [{ from: 3, to: 4, reason }] }); try { await setManifest(p, (m) => { m.render.gapCue = { mark: true, min: 0.5, label: "{s} (90%)[ · {why}]" }; }); const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); assert.equal(r.failures.length, 0, `${JSON.stringify(reason)}: ${JSON.stringify(r.failures)}`); const rec = await record(p, "c1"); // The text the page draws (gapCueView, the same rule) is the text the build drew, byte for byte. const m = JSON.parse(await readFile(p.manifestPath, "utf8")); const page = clipGapMarks({ cue: clipGapCueOf(m.render, m.timeline[0]), gaps: m.timeline[0].gaps, from: 1, to: 6 }); assert.equal(rec.gapMarks[0].text, `1 s (90%) · ${reason}`); assert.equal(rec.gapMarks[0].text, page[0].text); assert.equal(await readFile(path.join(p.root, "out", "sourced", "segments", "c1.gapmark-0.txt"), "utf8"), page[0].text, "what drawtext reads"); near(await probeDuration(p.seg("c1"), FPS), 4, 1 / FPS + 1e-6, "the segment is whole"); } finally { await rm(p.root, { recursive: true, force: true }); } } }); // ---- the mark off is the segment it was, in every layout that draws one -------------- // The deck (its footage framed for the chrome), a bare vertical cut (full), and the stacked vertical deck's // twocrop: each built with a gap, then with render.gapCue mark false (and a clip's gapCue saying nothing new), // then with the mark on and off again -- off, the same key and the same bytes as with nothing set. // SLICE 1d: under a deck (the deck, the stacked deck's twocrop) the mark is the gap-cue module's pages, so ON the // segment is STILL the plain one -- reused, the same key and bytes, no gapMarks -- and the schedule's slice // (gap-cue-slice.mjs) carries the mark from that very record; `--no-chrome` draws it into the segment instead, // and then the slice leaves the clip out (never both on one frame). A bare vertical cut draws it into the segment. const { verticalRender } = await import("./vertical.mjs"); const LAYOUTS = { deck: { render: { ...RENDER, width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }, clip: {} }, vertical: { render: { ...RENDER, format: "vertical" }, clip: {} }, twocrop: { render: { ...RENDER, format: "vertical", chrome: { engine: "hyperframes", layout: "deck", deck: {} } }, clip: { vertical: { layout: "twocrop", crops: [[0, 0, 0.5, 1], [0.5, 0, 0.5, 1]] } }, }, }; for (const [name, L] of Object.entries(LAYOUTS)) { test(`the gap mark OFF in the ${name} layout is the segment it was (the same key, the same bytes); ON it is drawn there`, { skip: !have && "needs ffmpeg" }, async () => { quiet(); const p = await project({ gaps: [{ from: 2.5, to: 5.5 }], ...L.clip }); const events = []; try { await setManifest(p, (m) => { m.render = L.render; }); const segOf = async () => { const dir = path.join(p.root, "out"); const { readdir } = await import("node:fs/promises"); for (const sub of await readdir(dir)) { const f = path.join(dir, sub, "segments", "c1.mp4"); if (spawnSync("test", ["-f", f]).status === 0) return f; } throw new Error("no c1 segment"); }; const build = async () => { events.length = 0; setProgressMode((e) => events.push(e)); const r = await buildVideo({ manifestPath: p.manifestPath, only: "c1", opts: { noNetwork: true } }); assert.equal(r.failures.length, 0, JSON.stringify(r.failures)); const seg = await segOf(); return { seg, rec: JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")), md5: md5(seg), reused: reusedIds(events).includes("c1") }; }; const plain = await build(); assert.equal(plain.rec.gapMarks, undefined); for (const off of [(m) => { m.render.gapCue = { mark: false }; }, (m) => { m.timeline[0].gapCue = { corner: "br" }; m.timeline[0].gaps[0].why = "idle"; }]) { await setManifest(p, off); const b = await build(); assert.ok(b.reused, `${name}: reused with the mark off`); assert.equal(b.rec.segKey, plain.rec.segKey, `${name}: the same key`); assert.equal(b.rec.gapMarks, undefined); assert.equal(b.md5, plain.md5); } await setManifest(p, (m) => { m.render.gapCue = { mark: true }; delete m.timeline[0].gapCue; }); const { gapCueSlice } = await import("./gap-cue-slice.mjs"); const sliceOf = async (rec) => { const m = JSON.parse(await readFile(p.manifestPath, "utf8")); const R = name === "twocrop" ? verticalRender(m.render) : m.render; const sched = { segments: [{ id: "c1", type: "clip", start: 10, duration: 2, end: 12, title: "", subtitle: "" }] }; return gapCueSlice(sched, { entries: m.timeline, render: R, records: new Map([["c1", rec]]) }); }; if (name !== "vertical") { // Under a deck: the plain segment, reused; the mark on the schedule from its record, at the cut's second. const on = await build(); assert.ok(on.reused, `${name}: reused with the mark on (the module draws it)`); assert.equal(on.rec.segKey, plain.rec.segKey, `${name}: the same key with the mark on`); assert.equal(on.md5, plain.md5, `${name}: the same bytes with the mark on`); assert.equal(on.rec.gapMarks, undefined, `${name}: nothing drawn into the segment`); assert.ok(events.some((e) => e.ev === "note" && e.message === "gap mark: drawn by the gap-cue page (chrome)"), `${name}: the build says who draws it`); const slice = await sliceOf(on.rec); assert.equal(slice.marks.length, 1); assert.equal(slice.marks[0].text, "» 3 s · idle"); near(slice.marks[0].at, 10 + 2.5 - on.rec.start, 0.01, "on the cut's clock: the segment's start plus the join"); assert.equal(slice.marks[0].place, "footage"); assert.equal(slice.marks[0].corner, name === "twocrop" ? "tr" : "bl"); if (name === "twocrop") { await setManifest(p, (m) => { delete m.render.gapCue; }); return; } // --no-chrome: drawn into the segment; the slice then leaves the clip out (inSegment). events.length = 0; setProgressMode((e) => events.push(e)); const r = await buildVideo({ manifestPath: p.manifestPath, only: "c1", opts: { noNetwork: true, noChrome: true } }); assert.equal(r.failures.length, 0, JSON.stringify(r.failures)); assert.ok(events.some((e) => e.ev === "note" && e.message === "gap mark: drawn into the clip segments (no chrome for the picture: --no-chrome)")); const seg = await segOf(); const nc = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); assert.equal(nc.gapMarks?.length, 1, "--no-chrome draws it into the segment"); assert.equal(nc.gapMarks[0].corner, "bl"); const left = await sliceOf(nc); assert.deepEqual(left, { marks: [], inSegment: ["c1"] }, "the chrome leaves a clip whose segment drew its marks"); await setManifest(p, (m) => { delete m.render.gapCue; }); const back = await build(); assert.equal(back.rec.segKey, plain.rec.segKey, `${name}: off again, the plain key`); assert.equal(back.md5, plain.md5, `${name}: off again, the plain bytes`); return; } const on = await build(); assert.ok(!on.reused, `${name}: rebuilt with the mark on`); assert.notEqual(on.rec.segKey, plain.rec.segKey); assert.equal(on.rec.gapMarks?.length, 1); assert.equal(on.rec.gapMarks[0].text, "» 3 s · idle"); // Drawn by that layout's path, where it puts it (gap-mark.mjs verticalMarkBox). const { rect, corner } = on.rec.gapMarks[0]; { assert.equal(on.rec.vertical?.layout, "full"); assert.equal(corner, "tr"); const { safeArea } = await import("./vertical.mjs"); const a = safeArea(verticalRender(L.render), 1080, 1920); assert.ok(rect.x >= a.x0 && rect.y >= a.y0 && rect.x + rect.w <= a.x1 && rect.y + rect.h <= a.y1, `inside the safe area (${JSON.stringify(rect)})`); } await setManifest(p, (m) => { delete m.render.gapCue; }); const back = await build(); assert.equal(back.rec.segKey, plain.rec.segKey, `${name}: off again, the plain key`); assert.equal(back.md5, plain.md5, `${name}: off again, the plain bytes`); } finally { quiet(); await rm(p.root, { recursive: true, force: true }); } }); } // ---- a gap-joined clip cut from its pieces ----------------------------------------- // Two moments of one recording joined by a gap: 1–5 s and 190–200 s. Only the // two pieces are on disk (two windows, the second WHITE with a higher tone), // never the 185 s between: --no-network builds it from them, one segment, the // kept 14 s, the record in the recording's own seconds. { const dir = path.join(CORPUS, CHANNEL, "data", "vid2"); mkdirSync(dir, { recursive: true }); writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: "vid2", title: "Long", duration: 300, uploadDate: "20240102", cues: [{ start: 0.2, end: 299, text: "words" }] })); writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid2", title: "Long", duration: 300 })); } test("render: a gap-joined clip whose pieces are minutes apart is cut from its two pieces -- never the seconds between", { skip: !have && "needs ffmpeg" }, async () => { const root = mkdtempSync(path.join(os.tmpdir(), "rtv-pieces-")); const raw = path.join(root, "out", "clips-raw"); mkdirSync(raw, { recursive: true }); const window = (name, colour, hz, d) => { const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=${colour}:s=320x180:r=${FPS}:d=${d}`, "-f", "lavfi", "-i", `sine=frequency=${hz}:sample_rate=48000:duration=${d}`, "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(raw, name), ]); assert.equal(r.status, 0, String(r.stderr)); }; window("vid2_0.00-12.00.mp4", "gray", 440, 12); window("vid2_185.00-205.00.mp4", "white", 880, 20); const manifestPath = path.join(root, "video.manifest.json"); await writeFile(manifestPath, JSON.stringify({ slug: "pieces", title: "Pieces", provenance: { channelSlug: CHANNEL, channelsDir: CORPUS }, render: RENDER, timeline: [{ type: "clip", id: "j1", channel: CHANNEL, video: "vid2", start: 1, end: 200, cite: 1, quote: "q", gaps: [{ from: 5, to: 190 }] }], })); const events = []; setProgressMode((e) => events.push(e)); try { await buildVideo({ manifestPath, opts: { noNetwork: true } }); const pieces = events.find((e) => e.ev === "pieces"); assert.ok(pieces, "the clip was cut from its pieces"); assert.deepEqual(pieces.pieces, [[1, 5], [190, 200]]); assert.deepEqual(events.filter((e) => e.ev === "fetch").map((e) => [e.from, e.to, e.reuse]), [[1, 5, "vid2_0.00-12.00.mp4"], [190, 200, "vid2_185.00-205.00.mp4"]]); const seg = path.join(root, "out", "sourced", "segments", "j1.mp4"); near(await probeDuration(seg, FPS), 14, 1 / FPS + 1e-6, "the kept seconds: 4 + 10"); const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); assert.deepEqual([rec.start, rec.end], [1, 200], "the record in the recording's seconds"); assert.deepEqual(rec.gaps, [{ from: 5, to: 190 }]); const y = lumas(seg); const at = (t) => y[Math.floor(t * FPS)]; assert.ok(at(2) > 60 && at(2) < 200, `the first piece is the grey window (YAVG ${at(2)})`); assert.ok(at(9) > 200, `the second piece is the white window (YAVG ${at(9)})`); assert.ok(rms(seg, 0.2, 3.8) > 800 && rms(seg, 4.2, 13.8) > 800, "heard through both pieces"); // Built again with nothing changed: the joined file and the segment are reused. events.length = 0; const before = md5(seg); await buildVideo({ manifestPath, opts: { noNetwork: true } }); assert.equal(md5(seg), before); assert.ok(events.some((e) => e.ev === "note" && / segment unchanged /.test(e.message) && e.message.split(":")[0] === "j1"), "the segment is reused"); // The mark on, no pad: the join between the pieces is no gap on the joined file's clock, but it is the // recording's 185 s -- marked, as Play and the bench mark it (review 1, 8). const marked = JSON.parse(await readFile(manifestPath, "utf8")); marked.render = { ...marked.render, gapCue: { mark: true } }; await writeFile(manifestPath, JSON.stringify(marked)); await buildVideo({ manifestPath, opts: { noNetwork: true } }); const mrec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); assert.deepEqual(mrec.gapMarks?.map((g) => [g.at, g.seconds, g.text]), [[4, 185, "» 3:05"]]); // Padded pieces (fetchPad 3): the pad between them is a gap on the joined clock; the same cut, the same mark. const m = JSON.parse(await readFile(manifestPath, "utf8")); m.render = { ...m.render, fetchPad: 3 }; await writeFile(manifestPath, JSON.stringify(m)); events.length = 0; await buildVideo({ manifestPath, opts: { noNetwork: true } }); assert.deepEqual(events.find((e) => e.ev === "pieces")?.pieces, [[0, 8], [187, 203]]); near(await probeDuration(seg, FPS), 14, 1 / FPS + 1e-6, "padded: the kept seconds still"); const padded = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); assert.deepEqual([padded.start, padded.end, padded.gaps], [1, 200, [{ from: 5, to: 190 }]]); assert.deepEqual(padded.gapMarks?.map((g) => [g.at, g.seconds, g.text]), [[4, 185, "» 3:05"]]); } finally { quiet(); await rm(root, { recursive: true, force: true }); } }); test("piecesClock / virtualEntry / fetchSpans: the pieces laid end to end, and back", () => { const clip = { type: "clip", id: "j", video: "v", start: 5385, end: 21812, cite: 5390, gaps: [{ from: 5400, to: 21800 }] }; const spans = fetchSpans(clip, { fetchPad: 3 }); assert.deepEqual(spans, [{ from: 5382, to: 5403 }, { from: 21797, to: 21815 }]); assert.deepEqual(fetchSpans({ ...clip, gaps: [] }, { fetchPad: 3 }), [{ from: 5382, to: 21815 }]); assert.deepEqual(fetchSpans(clip, { fetchPad: 3, montage: { style: "wall" } }), [{ from: 5382, to: 21815 }], "a montage applies no gaps"); const c = piecesClock(spans); assert.equal(c.total, 39); assert.equal(c.toVirtual(5385), 3); assert.equal(c.toVirtual(21800), 24); assert.equal(c.toVirtual(10000), 21, "between the pieces: the nearer edge"); assert.equal(c.toReal(3), 5385); assert.equal(c.toReal(24), 21800); assert.equal(c.toReal(-1), 5381); const v = virtualEntry(clip, c); assert.deepEqual([v.start, v.end, v.cite, v.gaps], [3, 36, 8, [{ from: 18, to: 24 }]]); assert.equal(clip.start, 5385, "the entry itself is untouched"); assert.deepEqual(c.realGaps(3, 36, [{ from: 18, to: 24 }]), [{ from: 5400, to: 21800 }]); // No pad: the pieces touch on the joined clock, the seconds between are still a gap. const bare = piecesClock([{ from: 1, to: 5 }, { from: 190, to: 200 }]); assert.deepEqual(bare.realGaps(0, 14, []), [{ from: 5, to: 190 }]); }); // ---- the schedule's mappings, no ffmpeg ------------------------------------------ const CLIP = { type: "clip", id: "c1", video: "v", start: 100, end: 120, cutStart: 102, cutEnd: 118 }; const GAPS = [{ from: 105, to: 107 }]; test("estimatedDuration: the play window less its gaps (and none in a montage)", () => { const r = { leadIn: 0.4 }; assert.ok(Math.abs(estimatedDuration(CLIP, r) - 16.4) < 1e-9); assert.ok(Math.abs(estimatedDuration({ ...CLIP, gaps: GAPS }, r) - 14.4) < 1e-9); assert.ok(Math.abs(estimatedDuration({ ...CLIP, gaps: GAPS }, { ...r, montage: { style: "wall" } }) - 16.4) < 1e-9); }); test("the mute mark on the segment's clock: after a gap, that much earlier (from the record's gaps)", () => { const e = { ...CLIP, gaps: GAPS, muteFrom: 110 }; const record = { video: "v", start: 101.6, end: 118, gaps: GAPS }; // The segment is 16.4 s less 2 s of gap. const m = muteSegmentSeconds({ entry: e, record, render: { fps: 30 }, seconds: 14.4 }); assert.equal(m.source, "record"); assert.equal(m.at, Number((110 - 101.6 - 2).toFixed(3))); // A record from before the gaps (no `gaps`, the old length) is not believed: the window's estimate, gap-aware. const old = muteSegmentSeconds({ entry: e, record: { video: "v", start: 101.6, end: 118 }, render: { fps: 30 }, seconds: 14.4 }); assert.equal(old.source, "window"); assert.equal(old.at, Number((110 - 101.6 - 2).toFixed(3))); // The joins' rule agrees. const ed = segmentSoundEdits({ entry: e, record, render: { fps: 30 }, seconds: 14.4 }); assert.equal(ed.mute, m.at); }); test("a claim stamped at a source second lands that much earlier after a gap; without gaps exactly where it did", () => { const render = { fps: 30, transition: 0.5, leadIn: 0.4, chrome: { engine: "hyperframes", layout: "deck" } }; const claim = { id: "k1", verdict: "CONTRADICTED", at: 110 }; const entries = [{ ...CLIP, claim }]; const plain = deckSchedule({ entries, durs: [16.4], D: 0.5, render }); const gapped = deckSchedule({ entries: [{ ...CLIP, claim, gaps: GAPS }], durs: [14.4], D: 0.5, render }); const landed = (s) => s.factcheck.stamps[0].landed; assert.ok(Math.abs(landed(plain) - (110 - 101.6)) < 1e-6, `plain ${landed(plain)}`); assert.ok(Math.abs(landed(gapped) - (110 - 101.6 - 2)) < 1e-6, `gapped ${landed(gapped)}`); // The record's gaps win over the manifest's (the frame grid's edges). const fromRecord = deckSchedule({ entries: [{ ...CLIP, claim, gaps: GAPS }], durs: [14.4], D: 0.5, render, clipClock: new Map([["c1", 101.6]]), clipGaps: new Map([["c1", [{ from: 105, to: 106 }]]]), }); assert.ok(Math.abs(landed(fromRecord) - (110 - 101.6 - 1)) < 1e-6); }); test("snapCut: no edge snaps across a gap, nor nearer it than half a second", () => { // A silence right after the start that would pull it inward, past the gap at 1.0 (file seconds). const sil = [{ s: 0.6, e: 1.4 }]; const free = snapCut({ sil, wantA: 0.5, wantB: 5, render: { snapWindow: 1.6 } }); assert.ok(free.a.at > 1, `without the gap it snaps inward (${free.a.at})`); const held = snapCut({ sil, wantA: 0.5, wantB: 5, render: { snapWindow: 1.6 }, gaps: [{ from: 1.2, to: 2 }] }); assert.deepEqual(held.a, { at: 0.5, snapped: false }); // renderCut takes source seconds. const rc = renderCut({ sil, fetchStart: 100, playFrom: 100.5, playTo: 105, render: { snapWindow: 1.6 }, gaps: [{ from: 101.2, to: 102 }] }); assert.equal(rc.start, 100.5); });