// trailer.mjs: a trailer cut from a finished master. The mapping (a clip's // source seconds → master seconds by the take's own records), the edges kept // out of the master's crossfades, the seamless runs, the refusals, the // ffmpeg graph's shape, and the run (the runner stubbed). import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { TrailerError, filterPath, loadTakeBuild, makeTrailer, parseBeats, planTrailer, scheduleSpans, trailerArgs, trailerOutPath, trailerRecordPath, trailerRuns, } from "./trailer.mjs"; // A master of four segments, 30 fps, 0.5 s dissolves: the brand intro, then // three clips. Each starts where the last one's dissolve begins. const SCHEDULE = { version: 1, kind: "deck", fps: 30, transition: 0.5, total: 40.167, segments: [ { id: "brand-intro", type: "intro", start: 0, duration: 4.167, end: 4.167 }, { id: "c1", type: "clip", start: 3.667, duration: 12, end: 15.667 }, { id: "c2", type: "clip", start: 15.167, duration: 10, end: 25.167 }, { id: "c3", type: "clip", start: 24.667, duration: 15.5, end: 40.167 }, ], }; // c1 was cut from source 100.2 (snapped), c2 from 500, c3 from 2000. const RECORDS = new Map([ ["c1", { version: 1, id: "c1", start: 100.2, end: 112.2, snapped: { start: true, end: true } }], ["c2", { version: 1, id: "c2", start: 500, end: 510 }], ["c3", { version: 1, id: "c3", start: 2000, end: 2015.5 }], ]); const plan = (beats, o = {}) => planTrailer({ schedule: SCHEDULE, records: RECORDS, beats: parseBeats(beats), ...o }); const close = (a, b, eps = 1 / 60) => assert.ok(Math.abs(a - b) <= eps, `${a} ≉ ${b}`); test("a clip beat lands at segment.start + (source − the cut record's snapped start), on a frame", () => { const p = plan([{ id: "c1", start: 104.2, end: 108.2 }]); const [c] = p.pieces; // 3.667 + (104.2 − 100.2) = 7.667: frame 230. assert.equal(c.frames.start, 230); assert.equal(c.frames.count, 120); close(c.master.start, 7.667); close(c.master.end, 11.667); close(c.source.start, 104.2); assert.equal(c.at, 0); assert.equal(p.total, 4); assert.deepEqual(p.notes, []); }); test("the snapped start is what counts, not the manifest's: the same beat moves with the record", () => { const records = new Map(RECORDS); records.set("c1", { ...RECORDS.get("c1"), start: 100.5 }); const p = planTrailer({ schedule: SCHEDULE, records, beats: parseBeats([{ id: "c1", start: 104.2, end: 108.2 }]) }); close(p.pieces[0].master.start, 3.667 + 3.7); }); test("an edge inside the master's crossfade is pulled in only as far as the trailer's crossfade hides it", () => { // c2's first 0.5 s (15.167–15.667) is the master's dissolve from c1. Second // piece, so a 0.3 s trailer crossfade covers its first 0.3 s: it may start // at 15.167 + 0.5 − 0.3 = 15.367 (source 500.2), not before. const p = plan([{ id: "c1", start: 104, end: 106 }, { id: "c2", start: 500.05, end: 505 }], { xfade: 0.3 }); const c2 = p.pieces[1]; close(c2.master.start, 15.367); close(c2.source.start, 500.2); assert.ok(c2.moved?.start); assert.match(p.notes.join("\n"), /c2: starts at master 15\.37, not 15\.22/); // Hard cuts: nothing hides the dissolve, so all of it is skipped. const hard = plan([{ id: "c1", start: 104, end: 106 }, { id: "c2", start: 500.05, end: 505 }], { xfade: 0 }); close(hard.pieces[1].master.start, 15.667); // The FIRST piece has no crossfade in: the whole dissolve is skipped. const first = plan([{ id: "c2", start: 500.05, end: 505 }]); close(first.pieces[0].master.start, 15.667); }); test("the end is kept out of the master's dissolve into the next segment the same way", () => { // c1's last 0.5 s (15.167–15.667) dissolves into c2; a middle piece may end 0.3 s into it. const p = plan([{ id: "c1", start: 110, end: 112.2 }, { id: "c3", start: 2001, end: 2003 }]); close(p.pieces[0].master.end, 15.467); assert.ok(p.pieces[0].moved?.end); // The last piece has no crossfade out. const last = plan([{ id: "c1", start: 110, end: 112.2 }]); close(last.pieces[0].master.end, 15.167); }); test("pieces overlap by the crossfade: each lands at the running total less one crossfade", () => { const p = plan([{ id: "c1", start: 104, end: 108 }, { id: "c3", start: 2001, end: 2004 }, { id: "c2", start: 502, end: 504 }]); assert.deepEqual(p.pieces.map((x) => x.at), [0, 3.7, 6.4]); close(p.total, 4 + 3 + 2 - 0.6, 1e-6); }); test("--intro opens on the brand intro and runs SEAMLESSLY into a beat that starts inside it", () => { const p = plan([{ id: "c1", start: 100.3, end: 104 }], { intro: true }); const [intro, c1] = p.pieces; assert.equal(intro.kind, "intro"); assert.equal(intro.master.start, 0); // c1's beat starts at master 3.767, inside the intro (0–4.167): one run of the master. assert.equal(c1.seamless, true); assert.equal(intro.frames.start + intro.frames.count, c1.frames.start); assert.equal(c1.at, intro.master.duration); assert.equal(c1.moved, undefined, "a seam pulls no edge in: the master's own dissolve plays"); assert.deepEqual(trailerRuns(p), [{ start: 0, count: c1.frames.start + c1.frames.count }]); assert.match(p.notes.join("\n"), /intro runs straight into c1/); }); test("--intro before a beat elsewhere ends where the master's dissolve out of it is hidden", () => { const p = plan([{ id: "c3", start: 2002, end: 2005 }], { intro: true }); close(p.pieces[0].master.end, 4.167 - 0.5 + 0.3); assert.equal(p.pieces[1].seamless, undefined); }); test("--finale S closes on the master's last S seconds; a beat it starts inside runs on into it, never twice", () => { const p = plan([{ id: "c1", start: 104, end: 106 }], { finale: 5 }); const fin = p.pieces.at(-1); assert.equal(fin.kind, "finale"); close(fin.master.start, 35.167); close(fin.master.end, 40.167); // c3 2010–2014 is master 34.667–38.667; the finale starts at 35.167, inside it. const q = plan([{ id: "c3", start: 2010, end: 2014 }], { finale: 5 }); assert.equal(q.pieces[1].seamless, true); close(q.pieces[0].master.end, 35.167); assert.equal(trailerRuns(q).length, 1); assert.ok(!q.notes.some((n) => /twice/.test(n))); }); test("the same master seconds twice, not adjacent, are said", () => { const p = plan([{ id: "c1", start: 104, end: 108 }, { id: "c3", start: 2001, end: 2004 }, { id: "c1", start: 106, end: 109 }]); assert.match(p.notes.join("\n"), /c1 and c1 share master .*twice/); }); test("a raw beat is master seconds as written", () => { const p = plan([{ at: 20, dur: 3 }]); assert.equal(p.pieces[0].kind, "raw"); close(p.pieces[0].master.start, 20); assert.equal(p.pieces[0].frames.count, 90); }); test("refusals, by name", () => { assert.throws(() => plan([{ id: "nope", start: 1, end: 2 }]), (e) => e instanceof TrailerError && /no clip "nope"/.test(e.message)); assert.throws(() => plan([{ id: "c1", start: 99, end: 104 }]), /c1 99–104 is outside the source seconds its segment was cut from, 100\.2–112\.2/); assert.throws(() => plan([{ id: "c1", start: 110, end: 113 }]), /outside the source seconds/); assert.throws( () => planTrailer({ schedule: SCHEDULE, records: new Map(), beats: parseBeats([{ id: "c1", start: 104, end: 105 }]) }), /"c1" has no cut record with source seconds/, ); assert.throws(() => plan([{ at: 39, dur: 3 }]), /runs past the master's end/); assert.throws(() => plan([{ id: "c1", start: 104, end: 106 }, { id: "c2", start: 503, end: 503.5 }, { id: "c3", start: 2001, end: 2003 }]), /c2: 0\.50 s left .* too short for a 0\.30 s crossfade either side/); assert.throws(() => plan([{ id: "c1", start: 104, end: 106 }], { finale: 99 }), /--finale 99: the master is 40\.17 s/); const noIntro = { ...SCHEDULE, segments: SCHEDULE.segments.slice(1) }; assert.throws(() => planTrailer({ schedule: noIntro, records: RECORDS, beats: [], intro: true }), /no brand intro/); assert.throws(() => planTrailer({ schedule: SCHEDULE, records: RECORDS, beats: [] }), /nothing to cut/); }); test("parseBeats: a list or { beats }, each a clip beat or a raw one, refused by place", () => { assert.equal(parseBeats({ beats: [{ at: 1, dur: 2 }] })[0].kind, "raw"); assert.equal(parseBeats([{ id: "x", start: 1, end: 2, label: "L" }])[0].label, "L"); assert.throws(() => parseBeats("x"), /a JSON array of beats/); assert.throws(() => parseBeats([]), /empty/); assert.throws(() => parseBeats([{ id: "x", start: 2, end: 1 }]), /beat 1 \(x\): end 1 is not after start 2/); assert.throws(() => parseBeats([{ at: 1, dur: 1 }, { id: "x", start: "1", end: 2 }]), /beat 2 \(x\): start and end are source seconds/); assert.throws(() => parseBeats([{ start: 1 }]), /beat 1: \{ "id", "start", "end" \}/); }); test("scheduleSpans: a rail schedule (starts only) ends each segment where the next one's dissolve ends", () => { const { spans } = scheduleSpans({ fps: 30, transition: 0.5, total: 20, segments: [{ id: "a", start: 0 }, { id: "b", start: 9.5 }] }); assert.equal(spans.get("a").end, 10); assert.equal(spans.get("b").end, 20); }); test("the ffmpeg graph: one movie source per run, trimmed by the master's timestamps, crossfaded, the master's encode", () => { const p = plan([{ id: "c1", start: 104.2, end: 108.2 }, { id: "c3", start: 2001, end: 2004 }], { intro: false, finale: 2 }); const render = { fps: 30, crf: 21, preset: "slow", audioBitrate: "160k", audioRate: 48000, audioChannels: 2 }; const argv = trailerArgs({ plan: p, master: "/m/master.mp4", render, outPath: "/o/t.mp4" }); assert.ok(!argv.includes("-i"), "no -i inputs: the sources are in the graph, read when the chain asks"); const graph = argv[argv.indexOf("-filter_complex") + 1]; assert.equal(graph.match(/movie=filename=\/m\/master\.mp4:/g).length, 3); // The first run: frame 230 (7.667 s) for 120 frames, the source seeked a second ahead. assert.match(graph, /movie=filename=\/m\/master\.mp4:seek_point=6\.666667:streams=dv\+da:dec_threads=2\[m0v\]\[m0a\]/); assert.match(graph, /\[m0v\]trim=start=7\.650000:end=11\.650000,setpts=PTS-STARTPTS\[v0\]/); assert.match(graph, /\[m0a\]atrim=start=7\.666667:end=11\.666667,asetpts=PTS-STARTPTS,apad=whole_dur=4\.000000,atrim=end=4\.000000\[a0\]/); assert.match(graph, /\[v0\]\[v1\]xfade=transition=fade:duration=0\.300000:offset=3\.700000\[xv1\]/); assert.match(graph, /\[a0\]\[a1\]acrossfade=d=0\.300000:c1=tri:c2=tri\[xa1\]/); assert.match(graph, /\[xv1\]\[v2\]xfade=.*offset=6\.400000\[xv2\]/); assert.deepEqual(argv.slice(argv.indexOf("-map"), argv.indexOf("-map") + 4), ["-map", "[xv2]", "-map", "[xa2]"]); assert.equal(argv[argv.indexOf("-crf") + 1], "21"); assert.equal(argv[argv.indexOf("-preset") + 1], "slow"); assert.equal(argv[argv.indexOf("-b:a") + 1], "160k"); assert.equal(argv.at(-1), "/o/t.mp4"); }); test("the ffmpeg graph: --xfade 0 is a concat; a run at the master's start seeks to 0", () => { const p = plan([{ id: "c3", start: 2001, end: 2004 }], { intro: true, xfade: 0 }); const argv = trailerArgs({ plan: p, master: "/m.mp4", render: { fps: 30 }, outPath: "/o.mp4" }); const graph = argv[argv.indexOf("-filter_complex") + 1]; assert.match(graph, /\[v0\]\[a0\]\[v1\]\[a1\]concat=n=2:v=1:a=1\[cv\]\[ca\]/); assert.doesNotMatch(graph, /xfade/); assert.match(graph, /seek_point=0\.000000:.*\[m0v\]trim=start=0\.000000:/); }); test("the ffmpeg graph: a seamless pair is one source, one run", () => { const p = plan([{ id: "c1", start: 100.3, end: 104 }], { intro: true }); const argv = trailerArgs({ plan: p, master: "/m.mp4", render: { fps: 30 }, outPath: "/o.mp4" }); const graph = argv[argv.indexOf("-filter_complex") + 1]; assert.equal(graph.match(/movie=/g).length, 1); assert.deepEqual(argv.slice(argv.indexOf("-map"), argv.indexOf("-map") + 2), ["-map", "[v0]"]); }); test("filterPath: a file name escaped for the movie option, then for the graph", () => { assert.equal(filterPath("/a/b.mp4"), "/a/b.mp4"); assert.equal(filterPath("/x/it's:a,[b];c.mp4"), "/x/it\\\\\\'s\\\\:a\\,\\[b\\]\\;c.mp4"); }); test("output paths: the default, a bare --out name, a path; the record beside", () => { assert.equal(trailerOutPath("/r/takes/t", "slug"), "/r/takes/t/out/slug.trailer.mp4"); assert.equal(trailerOutPath("/r/takes/t", "slug", "teaser"), "/r/takes/t/out/teaser.mp4"); assert.equal(trailerOutPath("/r/takes/t", "slug", "/tmp/x/y.mp4"), "/tmp/x/y.mp4"); assert.equal(trailerRecordPath("/a/slug.trailer.mp4"), "/a/slug.trailer.json"); assert.equal(trailerRecordPath("/a/teaser.mp4"), "/a/teaser.trailer.json"); }); async function takeFixture({ schedule = SCHEDULE } = {}) { const root = await mkdtemp(path.join(tmpdir(), "trailer-")); const take = path.join(root, "takes", "final"); const seg = path.join(take, "out", "sourced", "segments"); await mkdir(seg, { recursive: true }); await writeFile(path.join(take, "video.manifest.json"), JSON.stringify({ slug: "cut", render: { fps: 30, crf: 21, preset: "slow", audioBitrate: "160k", audioRate: 48000, audioChannels: 2 } })); await writeFile(path.join(take, "out", "cut.mp4"), "master"); if (schedule) await writeFile(path.join(take, "out", "sourced", "schedule.json"), JSON.stringify(schedule)); for (const [id, rec] of RECORDS) await writeFile(path.join(seg, `${id}.cut.json`), JSON.stringify(rec)); return { root, take }; } test("a take with no build is refused by name; a master that is not the build's is refused", async () => { const { root, take } = await takeFixture({ schedule: null }); try { await assert.rejects(loadTakeBuild(take), /final has no build: no out\/sourced\/schedule\.json/); await writeFile(path.join(take, "out", "sourced", "schedule.json"), JSON.stringify(SCHEDULE)); const beats = parseBeats([{ id: "c1", start: 104, end: 106 }]); await assert.rejects(makeTrailer({ takeDir: take, beats, probe: async () => 12, run: async () => {} }), /is 12\.00 s but its build records describe a 40\.17 s cut/); await assert.rejects(makeTrailer({ takeDir: take, beats, probe: async () => null, run: async () => {} }), /has no master/); } finally { await rm(root, { recursive: true, force: true }); } }); test("makeTrailer: the encode runs in the slot, the file lands by rename, the record says what was cut", async () => { const { root, take } = await takeFixture(); try { let slotted = 0; let ran = null; const res = await makeTrailer({ takeDir: take, beats: parseBeats([{ id: "c1", start: 100.3, end: 104 }, { id: "c3", start: 2001, end: 2004 }]), intro: true, finale: 2, probe: async () => 40.167, slot: async (fn) => { slotted += 1; return fn(); }, run: async (argv) => { ran = argv; await writeFile(argv.at(-1), "trailer"); }, now: (() => { let t = 0; return () => (t += 1500); })(), }); assert.equal(slotted, 1); assert.equal(res.outPath, path.join(take, "out", "cut.trailer.mp4")); assert.match(path.basename(ran.at(-1)), /^\.cut\.trailer\.tmp-\d+-\d+-[0-9a-f]{8}\.mp4$/); assert.equal(await readFile(res.outPath, "utf8"), "trailer"); const rec = JSON.parse(await readFile(path.join(take, "out", "cut.trailer.json"), "utf8")); assert.equal(rec.kind, "trailer"); assert.equal(rec.source.take, "final"); assert.deepEqual(rec.pieces.map((p) => p.kind), ["intro", "clip", "clip", "finale"]); assert.equal(rec.pieces[1].source.asked.start, 100.3); assert.equal(rec.encode.crf, 21); assert.equal(rec.encodeSeconds, 1.5); assert.equal(rec.seconds, res.plan.total); } finally { await rm(root, { recursive: true, force: true }); } }); test("makeTrailer: a failed encode leaves nothing at the name; --dry-run encodes and writes nothing", async () => { const { root, take } = await takeFixture(); try { const beats = parseBeats([{ id: "c1", start: 104, end: 106 }]); let tmp = null; await assert.rejects( makeTrailer({ takeDir: take, beats, probe: async () => 40.167, run: async (argv) => { tmp = argv.at(-1); await writeFile(tmp, "half"); throw new Error("ffmpeg failed: boom"); } }), /boom/, ); await assert.rejects(stat(tmp), { code: "ENOENT" }); await assert.rejects(stat(path.join(take, "out", "cut.trailer.mp4")), { code: "ENOENT" }); let ran = false; const res = await makeTrailer({ takeDir: take, beats, dryRun: true, probe: async () => 40.167, run: async () => { ran = true; } }); assert.equal(ran, false); assert.equal(res.dryRun, true); await assert.rejects(stat(res.recordPath), { code: "ENOENT" }); } finally { await rm(root, { recursive: true, force: true }); } });