src/plan.js
// Production plan from a script: shot list, b-roll needs, on-screen text and a CMX3600 EDL.
// Deterministic rules over the script's own segments and timings; nothing is generated by a model.
import { captionText, checkSegments } from "./captions.js";
const STOP = new Set(
"a about above after again against all also am an and any are as at be because been before being below between both but by can could did do does doing down during each few for from further had has have having he her here hers him his how i if in into is it its itself just let me more most my no nor not now of off on once only or other our ours out over own same she should so some such than that the their theirs them then there these they this those through to too under until up very was we were what when where which while who whom why will with would you your yours yourself get got make made one two three like really thing things way want need know see look use using used every much many even still well back going go according said says reported based rather several per via".split(" "),
);
// A figure worth showing on screen: thousands separators only as ",ddd" (so "2025," reads as 2025), an
// optional currency sign and an optional unit. Bare years and bare one-digit counts are dropped below.
const NUM_RE = /(?:[$\u20ac\u00a3]\s?)?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:\s?(?:%|x\b|[kKmMbB]\b|million\b|billion\b|thousand\b|percent\b|per cent\b|km\b|kilomet(?:re|er)s?\b|miles?\b|mph\b|kg\b|hours?\b|minutes?\b|days?\b|weeks?\b|months?\b|years?\b))?/g;
/** Key figures in a segment as shown on screen ("18 percent" -> "18%"); years and lone digits are skipped. */
export function keyNumbers(text, n = 2) {
const out = [];
for (const raw of text.match(NUM_RE) ?? []) {
const x = raw.trim().replace(/\s?(?:percent|per cent)$/i, "%");
if (/^(?:1[89]|20)\d{2}$/.test(x) || /^\d$/.test(x)) continue;
if (!out.includes(x)) out.push(x);
}
return out.slice(0, n);
}
const shorten = (s, max) => {
const chars = [...s];
if (chars.length <= max) return s;
const cut = chars.slice(0, max - 1).join("");
const sp = cut.lastIndexOf(" ");
return `${(sp > max * 0.5 ? cut.slice(0, sp) : cut).replace(/[\s,;:.-]+$/u, "")}\u2026`;
};
export function keywords(text, n = 4) {
const counts = new Map();
// Web addresses and host names ("news.example.com") are attribution, not something to film.
const plain = text.replace(/\bhttps?:\/\/\S+/gi, " ").replace(/[\p{L}\p{N}-]+(?:\.[\p{L}][\p{L}\p{N}-]*)+/gu, " ");
for (const w of plain.toLowerCase().match(/[\p{L}][\p{L}\p{N}'-]{3,}/gu) ?? []) {
const k = w.replace(/'s$/, "");
if (STOP.has(k)) continue;
counts.set(k, (counts.get(k) ?? 0) + 1);
}
return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, n).map(([w]) => w);
}
const hostOf = (u) => {
try {
const x = new URL(u);
return /^https?:$/.test(x.protocol) ? x.hostname.replace(/^www\./, "") : null;
} catch {
return null;
}
};
const fold = (s) => captionText(s).toLowerCase();
function timecode(sec, fps) {
const f = Math.round(sec * fps);
const p = (n) => String(n).padStart(2, "0");
return `${p(Math.floor(f / (fps * 3600)))}:${p(Math.floor(f / (fps * 60)) % 60)}:${p(Math.floor(f / fps) % 60)}:${p(f % fps)}`;
}
const SAFE_AREA = {
"9:16": "Vertical: keep text and faces inside the centre; platform buttons and captions cover roughly the bottom 20% and the right 15%.",
"16:9": "Landscape: keep text inside the 90% title-safe area; leave the bottom 15% clear for captions.",
"1:1": "Square: keep text inside the central 80%; leave the bottom 15% clear for captions.",
"4:5": "Portrait 4:5: keep text inside the central 80%; leave the bottom 15% clear for captions.",
};
export function planProduction(input) {
const s = input.script;
const fps = input.fps ?? 30;
const aspect = input.aspect_ratio ?? "9:16";
const maxShot = input.max_shot_seconds ?? 6;
const reel = input.a_roll_reel ?? "AROLL";
const clip = captionText(input.a_roll_clip ?? "a_roll.mp4").slice(0, 200);
const maxText = input.max_text_chars ?? 32;
const warnings = [];
checkSegments(s.segments);
const segs = s.segments.map((x, i) => ({ ...x, i, text: captionText(x.text), kind: x.kind ?? "body" })).sort((a, b) => a.start - b.start || a.i - b.i);
for (let k = 1; k < segs.length; k++) {
const gap = segs[k].start - segs[k - 1].end;
if (gap < -0.001) warnings.push(`Segments ${segs[k - 1].i} and ${segs[k].i} overlap by ${Math.round(-gap * 1000) / 1000} s.`);
else if (gap > 0.5) warnings.push(`Gap of ${Math.round(gap * 1000) / 1000} s before segment ${segs[k].i} (silence or a missing line).`);
}
const lastEnd = Math.max(...segs.map((x) => x.end));
if (s.duration_seconds !== undefined && lastEnd > s.duration_seconds + 0.01) warnings.push(`Segments run to ${lastEnd} s, past duration_seconds ${s.duration_seconds}.`);
const duration = Math.max(lastEnd, s.duration_seconds ?? 0);
// Assign sourced claims to segments (explicit index, else the segment whose text contains the claim).
const claimsBySeg = new Map();
const unmatched = [];
for (const c of s.claims ?? []) {
const url = c.source_url ?? c.sources?.[0];
const host = url ? hostOf(url) : null;
if (!host) continue;
let seg = c.segment !== undefined ? segs.find((x) => x.i === c.segment) : undefined;
if (!seg) seg = segs.find((x) => fold(x.text).includes(fold(c.text)) || fold(c.text).includes(fold(x.text)));
if (!seg) {
unmatched.push({ url, host });
continue;
}
if (!claimsBySeg.has(seg.i)) claimsBySeg.set(seg.i, []);
claimsBySeg.get(seg.i).push({ url, host });
}
const shots = [];
const broll = [];
const texts = [];
const addText = (t) => {
const id = `T${String(texts.length + 1).padStart(2, "0")}`;
texts.push({ id, ...t });
return id;
};
let aCount = 0;
for (const seg of segs) {
const dur = seg.end - seg.start;
const n = Math.max(1, Math.ceil(dur / maxShot - 1e-9));
const sourced = claimsBySeg.get(seg.i) ?? [];
const segTexts = [];
if (seg.kind === "hook" && seg.text) segTexts.push(addText({ start: seg.start, end: seg.end, text: shorten(seg.text, maxText), role: "hook_title", position: "top_center" }));
if (seg.kind === "cta" && seg.text) segTexts.push(addText({ start: seg.start, end: seg.end, text: shorten(seg.text, maxText), role: "end_card", position: "center" }));
if (seg.kind !== "hook" && seg.kind !== "cta") {
const nums = keyNumbers(seg.text);
for (const num of nums) segTexts.push(addText({ start: seg.start, end: seg.end, text: num, role: "key_number", position: "center" }));
}
for (const c of sourced) segTexts.push(addText({ start: seg.start, end: seg.end, text: `Source: ${c.host}`, role: "source_credit", position: "lower_third" }));
let sourceCardUsed = false;
for (let j = 0; j < n; j++) {
const start = Math.round((seg.start + (dur * j) / n) * 1000) / 1000;
const end = j === n - 1 ? seg.end : Math.round((seg.start + (dur * (j + 1)) / n) * 1000) / 1000;
const id = `S${String(shots.length + 1).padStart(2, "0")}`;
const isB = seg.kind !== "hook" && seg.kind !== "cta" && j % 2 === 1;
const shot = { id, segment: seg.i, kind: seg.kind, start, end, duration: Math.round((end - start) * 1000) / 1000, type: isB ? "b_roll" : "a_roll", text_ids: j === 0 ? segTexts : [] };
if (isB) {
const bid = `B${String(broll.length + 1).padStart(2, "0")}`;
const kw = keywords(seg.text);
const card = sourced.length && !sourceCardUsed ? sourced[0] : null;
if (card) sourceCardUsed = true;
const b = card
? { id: bid, shot_id: id, start, end, need: `Source card or screenshot showing the claim from ${card.host}`, keywords: kw, source_url: card.url, rights_note: "Show only material you may use: your own screenshot of a public page with clear attribution, or a text citation card. Do not copy video, images or audio without permission." }
: { id: bid, shot_id: id, start, end, need: kw.length ? `Footage that shows: ${kw.join(", ")}` : `Footage that illustrates: "${shorten(seg.text, 80)}"`, keywords: kw, rights_note: "Use footage you shot, own or have licensed; credit stock footage where its licence requires." };
broll.push(b);
Object.assign(shot, { framing: "cutaway", description: `B-roll over continuing voice-over: ${b.need}`, broll_id: bid });
} else {
// Hook close-up, call to action medium; body A-roll alternates medium / medium close-up.
const framing = seg.kind === "hook" ? "close-up" : seg.kind === "cta" ? "medium" : aCount++ % 2 === 0 ? "medium" : "medium close-up";
Object.assign(shot, { framing, description: `Presenter to camera (${framing}): "${shorten(seg.text, 90)}"` });
}
shots.push(shot);
}
}
if (unmatched.length) {
const hosts = [...new Set(unmatched.map((u) => u.host))];
const last = segs[segs.length - 1];
addText({ start: last.start, end: last.end, text: `Sources: ${hosts.join(", ")}`, role: "sources_card", position: "lower_third" });
warnings.push(`${unmatched.length} sourced claim(s) did not match a segment; their sources are listed on a closing card.`);
}
if (!segs.some((x) => x.kind === "hook")) warnings.push('No segment has kind "hook": no opening title was planned.');
// CMX3600 EDL. A-roll timing follows the script (record = source timecode); B-roll is a video-only
// placeholder on reel BROLL while the A-roll audio continues.
const events = [];
for (const sh of shots) {
let inF = timecode(sh.start, fps);
let outF = timecode(sh.end, fps);
if (inF === outF) outF = timecode(sh.end + 1 / fps, fps);
if (sh.type === "a_roll") events.push({ event: events.length + 1, reel, track: "AA/V", transition: "C", source_in: inF, source_out: outF, record_in: inF, record_out: outF, clip, shot_id: sh.id });
else {
events.push({ event: events.length + 1, reel, track: "AA", transition: "C", source_in: inF, source_out: outF, record_in: inF, record_out: outF, clip, shot_id: sh.id });
events.push({ event: events.length + 1, reel: "BROLL", track: "V", transition: "C", source_in: timecode(0, fps), source_out: timecode(sh.end - sh.start, fps), record_in: inF, record_out: outF, clip: `${sh.broll_id} placeholder`, shot_id: sh.id, comment: broll.find((b) => b.id === sh.broll_id).need });
}
}
if (events.length > 999) warnings.push("More than 999 EDL events: CMX3600 allows at most 999; split the timeline.");
const ascii = (x) => String(x).replace(/[^\x20-\x7e]/g, "?");
const title = ascii(captionText(s.title ?? "Untitled")).slice(0, 70) || "Untitled";
const edlLines = [`TITLE: ${title}`, "FCM: NON-DROP FRAME", ""];
for (const e of events) {
edlLines.push(`${String(e.event).padStart(3, "0")} ${e.reel.padEnd(8)} ${e.track.padEnd(5)} ${e.transition.padEnd(8)} ${e.source_in} ${e.source_out} ${e.record_in} ${e.record_out}`);
edlLines.push(`* FROM CLIP NAME: ${ascii(e.clip).slice(0, 80)}`);
if (e.comment) edlLines.push(`* B-ROLL NEEDED: ${ascii(e.comment).slice(0, 120)}`);
}
warnings.push("The EDL assumes the A-roll recording follows the script timing (source = record timecode); adjust source timecodes after recording.");
return {
title: captionText(s.title ?? "Untitled") || "Untitled",
fps,
aspect_ratio: aspect,
duration_seconds: duration,
shots,
broll,
onscreen_text: texts,
edl: { format: "CMX3600", fps, text: `${edlLines.join("\n")}\n`, events },
safe_area: SAFE_AREA[aspect],
warnings,
};
}