// The basic output mode (basic.mjs, render.mode "basic"): the spans as Play // has them, the fades at the right edges, the plan's notes and refusals, the // mode resolved last (a preset's, a patch's), and a real render through the // build's own door -- the one every take and `umtool build` goes through. // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { rm, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-basic-corpus-")); process.env.CHANNELS_DIR = CORPUS; const { basicPlan, basicShape, basicSpans, concatArgs, renderBasic, spanArgs, spanFades, spanFileName } = await import("./basic.mjs"); const { buildVideo, cliEstimateMb, selectVariant, setProgressMode } = await import("./build-video.mjs"); const { resolvePresetLayers } = await import("./presets.mjs"); const { BASIC_ESTIMATE_MB, manifestEstimateMb } = await import("./render-estimate.mjs"); test.after(() => rm(CORPUS, { recursive: true, force: true })); const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); const FADE = { audio: 0.03, video: 0.15 }; test("basicSpans: the cut's edges when it has them, else the extent; less the gaps; none in a montage", () => { assert.deepEqual(basicSpans({ type: "clip", start: 10, end: 20 }), [{ from: 10, to: 20 }]); assert.deepEqual(basicSpans({ type: "clip", start: 10, end: 20, cutStart: 12, cutEnd: 18 }), [{ from: 12, to: 18 }]); assert.deepEqual( basicSpans({ type: "clip", start: 10, end: 30, cutStart: 11, cutEnd: 29, gaps: [{ from: 20, to: 22 }, { from: 14, to: 15 }] }), [{ from: 11, to: 14 }, { from: 15, to: 20 }, { from: 22, to: 29 }], "sorted, the gaps out", ); assert.deepEqual(basicSpans({ type: "clip", start: 10, end: 20, gaps: [{ from: 10, to: 12 }] }), [{ from: 12, to: 20 }], "a gap at the edge leaves no empty span"); assert.deepEqual(basicSpans({ type: "clip", start: 10, end: 20, gaps: [{ from: 12, to: 14 }] }, { montage: {} }), [{ from: 10, to: 20 }], "a montage cuts no gaps"); assert.deepEqual(basicSpans({ type: "clip", start: 20, end: 10 }), []); }); test("spanFades: the sound at every span's edges, the picture from black at the cut's first frame and to black at its last", () => { assert.deepEqual(spanFades({ seconds: 5, first: false, last: false, fade: FADE }), { video: [], audio: ["afade=t=in:st=0:d=0.03", "afade=t=out:st=4.97:d=0.03"], }); assert.deepEqual(spanFades({ seconds: 5, first: true, last: false, fade: FADE }).video, ["fade=t=in:st=0:d=0.15"]); assert.deepEqual(spanFades({ seconds: 5, first: false, last: true, fade: FADE }).video, ["fade=t=out:st=4.85:d=0.15"]); assert.deepEqual(spanFades({ seconds: 5, first: true, last: true, fade: FADE }).video, ["fade=t=in:st=0:d=0.15", "fade=t=out:st=4.85:d=0.15"], "one span is the whole cut"); assert.deepEqual(spanFades({ seconds: 0.3, first: true, last: true, fade: FADE }).video, ["fade=t=in:st=0:d=0.1", "fade=t=out:st=0.2:d=0.1"], "never more than a third of a short span"); assert.deepEqual(spanFades({ seconds: 5, first: true, last: true, fade: { audio: 0, video: 0 } }), { video: [], audio: [] }, "0 is none"); }); test("basicPlan: clips and their spans in order; the rest left out by name; a blurred clip refused unless the cut is uncensored", () => { const m = { render: {}, timeline: [ { type: "card", id: "k1" }, { type: "clip", id: "c1", video: "v", start: 1, end: 3 }, { type: "post", id: "p1" }, { type: "teaser", id: "t1" }, { type: "clip", id: "c2", video: "v", start: 5, end: 9, gaps: [{ from: 6, to: 7 }], audio: { gain: -3, offset: 40 } }, ], }; const plan = basicPlan(m); assert.deepEqual(plan.items.map((i) => [i.id, i.spans.length, i.gain]), [["c1", 1, 0], ["c2", 2, -3]]); assert.deepEqual(plan.skipped.map((s) => s.id), ["k1", "p1", "t1"]); assert.match(plan.notes.join("\n"), /left out k1 \(a card: a basic cut is the footage alone\); p1 \(a post item/); assert.match(plan.notes.join("\n"), /c2's audio\.offset not applied/); assert.deepEqual(plan.errors, []); assert.deepEqual(plan.fade, FADE); assert.deepEqual(basicPlan(m, { only: "c2" }).items.map((i) => i.id), ["c2"]); const blurred = { render: {}, timeline: [{ type: "clip", id: "c1", video: "v", start: 1, end: 3, blur: { on: true } }] }; assert.match(basicPlan(blurred).errors[0], /c1 asks for its picture blurred.*blur=off/); assert.deepEqual(basicPlan({ ...blurred, render: { blur: "off" } }).errors, [], "the uncensored basic cut"); assert.match(basicPlan({ render: {}, timeline: [{ type: "post", id: "p1" }] }).errors[0], /needs at least one clip/); assert.deepEqual(basicPlan({ render: { basic: { fade: { video: 0.5 } } }, timeline: [] }).fade, { audio: 0.03, video: 0.5 }); }); test("basicPlan: a clip that hides regions is refused by name -- its own box or its recording's, in the uncensored cut too", () => { const clip = { type: "clip", id: "c1", video: "v", start: 1, end: 3 }; const own = basicPlan({ render: {}, timeline: [{ ...clip, censor: { boxes: [[0, 0, 0.5, 0.5]] } }] }); assert.match(own.errors[0], /c1 hides 1 region\(s\) of its picture .* a basic cut draws none/); assert.deepEqual(own.items, []); const rec = basicPlan({ render: { blur: "off", censor: [{ video: "v", boxes: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]] }] }, timeline: [clip] }); assert.match(rec.errors[0], /c1 hides 2 region\(s\)/, "render.blur off does not lift a hidden region"); assert.deepEqual(basicPlan({ render: { censor: [{ video: "another", boxes: [[0, 0, 0.5, 0.5]] }] }, timeline: [clip] }).errors, [], "another recording's: as before"); }); test("spanArgs: the file's seconds, fitted into the first window's shape, its fades and gain, the build's encode", () => { const shape = basicShape({ width: 1920, height: 1080, sar: "1:1", fps: "60/1" }); assert.deepEqual(shape, { W: 1920, H: 1080, fps: "60/1" }); assert.deepEqual(basicShape({ width: 720, height: 480, sar: "32:27", fps: "30000/1001" }), { W: 852, H: 480, fps: "30000/1001" }, "display size, even"); assert.equal(basicShape({ width: 640, height: 360, fps: "0/0" }).fps, "30", "no rate: 30"); const argv = spanArgs({ file: "/w.mp4", at: 12.5, seconds: 4, shape, fades: spanFades({ seconds: 4, first: true, last: false, fade: FADE }), gain: -3, encode: ["-c:v", "libx264"], out: "/o.mp4" }); const at = (k) => argv[argv.indexOf(k) + 1]; assert.equal(at("-ss"), "12.5"); assert.equal(at("-t"), "4"); assert.equal(at("-vf"), "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=60/1,fade=t=in:st=0:d=0.15,format=yuv420p"); assert.equal(at("-af"), "aresample=48000,volume=-3dB,afade=t=in:st=0:d=0.03,afade=t=out:st=3.97:d=0.03"); assert.equal(argv.at(-1), "/o.mp4"); const silent = spanArgs({ file: "/w.mp4", at: 0, seconds: 1, shape, fades: { video: [], audio: [] }, audio: false, encode: [], out: "/o.mp4" }); assert.ok(silent.includes("anullsrc=r=48000:cl=stereo") && silent.includes("1:a:0"), "a window with no sound gets silence"); assert.deepEqual(concatArgs("/l.txt", "/f.mp4").slice(-5), ["-c", "copy", "-movflags", "+faststart", "/f.mp4"]); assert.equal(spanFileName(3, "c 1", 0, argv), spanFileName(3, "c 1", 0, [...argv.slice(0, -1), "/elsewhere.mp4"]), "the out path is not part of the key"); assert.match(spanFileName(3, "c 1", 0, argv), /^003-c_1-0-[0-9a-f]{12}\.mp4$/); assert.notEqual(spanFileName(3, "c", 0, argv, { size: 1, mtimeMs: 1 }), spanFileName(3, "c", 0, argv, { size: 1, mtimeMs: 2 }), "a re-fetched window is another span"); }); test("the mode resolves last: a preset's basic wins its chrome, a patch's deck wins the preset; basic lays no intro or brand", () => { const m = { slug: "s", preset: "basic", render: { chrome: { layout: "deck" }, intro: "boot-dark" }, timeline: [{ type: "clip", id: "c1", video: "v", start: 1, end: 2 }] }; const seen = selectVariant(m); assert.equal(seen.render.mode, "basic"); assert.equal(seen.timeline.length, 1, "no intro entry prepended"); assert.equal(resolvePresetLayers(m, [{ render: { mode: "deck" } }]).render.mode, "deck", "a take's patch wins the preset"); const deck = selectVariant({ ...m, preset: undefined, render: { ...m.render } }); assert.ok(deck.timeline.length > 1, "a deck cut with an intro gets it"); assert.equal(manifestEstimateMb({ render: { mode: "basic" }, timeline: [] }, {}), BASIC_ESTIMATE_MB); assert.equal(manifestEstimateMb({ render: { mode: "basic" } }, { UMTOOL_RENDER_ESTIMATE_MB: "0" }), null, "the override still speaks"); }); test("renderBasic: refuses a span no window holds, by name, before an encode", async () => { const root = mkdtempSync(path.join(os.tmpdir(), "rtv-basic-miss-")); try { const ran = []; await assert.rejects( renderBasic({ manifest: { render: {}, provenance: { channelSlug: "ch" }, timeline: [{ type: "clip", id: "c1", video: "v1", start: 1, end: 3 }] }, dirs: { dir: root, final: path.join(root, "f.mp4") }, deps: { sourceOf: async () => null, encodeArgs: () => [], exec: async (...a) => ran.push(a) }, }), /no window on disk holds this span.*umtool fetch[\s\S]*c1 ch\/v1 1–3/, ); assert.equal(ran.length, 0); } finally { await rm(root, { recursive: true, force: true }); } }); test("a basic cut, rendered through buildVideo: the spans spliced at the window's size and rate, no deck, chrome not checked", { skip: !have && "no ffmpeg" }, async () => { const root = mkdtempSync(path.join(os.tmpdir(), "rtv-basic-")); try { mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); const raw = path.join(root, "out", "clips-raw", "vid1_0.00-10.00.mp4"); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=s=320x180:r=25:d=10", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=10", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, ]); assert.equal(r.status, 0, String(r.stderr)); writeFileSync(path.join(root, "video.manifest.json"), "{}"); const manifestPath = path.join(root, "video.manifest.json"); await writeFile(manifestPath, JSON.stringify({ slug: "basic-test", title: "Basic", provenance: { channelSlug: "synth", channelsDir: CORPUS }, render: { mode: "basic", width: 1920, height: 1080, fps: 30, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 30, // A chrome the build would refuse: a basic cut does not check it. chrome: { layout: "deck", engine: "hyperframes", deck: { nonsense: true } }, }, timeline: [ { type: "card", id: "k1", title: "left out" }, { type: "clip", id: "c1", channel: "synth", video: "vid1", start: 1, end: 4, gaps: [{ from: 2, to: 2.5 }] }, { type: "clip", id: "c2", channel: "synth", video: "vid1", start: 5, end: 9, cutStart: 6, cutEnd: 8 }, ], })); const events = []; setProgressMode((e) => events.push(e)); const { out } = await buildVideo({ manifestPath, opts: { skipFetch: true } }); setProgressMode("human"); assert.equal(out, path.join(root, "out", "basic-test.mp4")); const probe = JSON.parse(spawnSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,width,height,avg_frame_rate:format=duration", "-of", "json", out]).stdout.toString()); const v = probe.streams.find((s) => s.codec_type === "video"); assert.deepEqual([v.width, v.height], [320, 180], "the window's own size, not the render block's"); const [rn, rd] = String(v.avg_frame_rate).split("/").map(Number); assert.ok(Math.abs(rn / rd - 25) < 0.5, `the window's own rate (25), not the render block's 30: ${v.avg_frame_rate}`); assert.ok(probe.streams.some((s) => s.codec_type === "audio")); // c1 1–4 less 2–2.5 (2.5 s) + c2's cut 6–8 (2 s). assert.ok(Math.abs(Number(probe.format.duration) - 4.5) < 0.15, `duration ${probe.format.duration}`); assert.ok(events.some((e) => e.ev === "note" && /left out k1/.test(e.message))); assert.equal(events.filter((e) => e.ev === "segment").length, 3); assert.ok(!events.some((e) => e.ev === "chrome"), "no deck"); // Rendered again: the spans' files are reused. const again = []; setProgressMode((e) => again.push(e)); await buildVideo({ manifestPath, opts: { skipFetch: true } }); setProgressMode("human"); assert.ok(again.filter((e) => e.ev === "segment").every((e) => e.reused)); assert.ok((await stat(out)).size > 0); // The window re-fetched under the same name: the spans are cut again, not reused from the old bytes. const r2 = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=320x180:r=25:d=10", "-f", "lavfi", "-i", "sine=frequency=220:sample_rate=48000:duration=10", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, ]); assert.equal(r2.status, 0, String(r2.stderr)); const fresh = []; setProgressMode((e) => fresh.push(e)); await buildVideo({ manifestPath, opts: { skipFetch: true } }); setProgressMode("human"); assert.ok(fresh.filter((e) => e.ev === "segment").every((e) => !e.reused), "a new window, new spans"); const { readdir } = await import("node:fs/promises"); assert.deepEqual((await readdir(path.join(root, "out"))).filter((n) => /\.tmp/.test(n)), [], "no temporary file left beside the cut"); // `--only` writes beside the spans, never over the cut. const only = await buildVideo({ manifestPath, opts: { skipFetch: true }, only: "c2" }); assert.match(only.out, /out\/sourced\/basic\/only-c2\.mp4$/); await assert.rejects(buildVideo({ manifestPath, opts: { skipFetch: true, short: "c1" } }), /--short: a basic cut/); assert.ok((await cliEstimateMb(manifestPath, {}, {})) <= 1200); } finally { setProgressMode("human"); await rm(root, { recursive: true, force: true }); } }); test("renderBasic: a span whose encode fails leaves no temporary file, and the cut's file is not touched", async () => { const root = mkdtempSync(path.join(os.tmpdir(), "rtv-basic-fail-")); try { const src = path.join(root, "w.mp4"); writeFileSync(src, "bytes"); const { readdir } = await import("node:fs/promises"); await assert.rejects( renderBasic({ manifest: { render: {}, timeline: [{ type: "clip", id: "c1", video: "v1", start: 1, end: 3 }] }, dirs: { dir: root, final: path.join(root, "final.mp4") }, deps: { sourceOf: async () => ({ path: src, fetchStart: 0 }), encodeArgs: () => [], probe: async () => ({ width: 320, height: 180, sar: "1:1", fps: "25/1", hasVideo: true, hasAudio: true }), exec: async (_bin, args) => { writeFileSync(args.at(-1), "half"); throw new Error("ffmpeg died"); }, }, }), /ffmpeg died/, ); assert.deepEqual((await readdir(path.join(root, "basic"))).filter((n) => n.endsWith(".mp4")), []); assert.equal(existsSync(path.join(root, "final.mp4")), false); } finally { await rm(root, { recursive: true, force: true }); } });