src/captions.js
// SRT and WebVTT export from script segments: line wrapping, cue splitting by text length, overlap
// fixing and markup removal. Script text is untrusted and only ever written as caption text.
import { ToolError } from "./errors.js";
/** Plain caption text: no control characters, markup tags, ASS overrides or cue arrows. */
export function captionText(s) {
return String(s ?? "")
.normalize("NFC")
.replace(/[\u0000-\u001f\u007f\u200b\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, " ")
.replace(/<\/?[A-Za-z][^>]{0,200}>/g, " ")
.replace(/\{\\[^}]{0,200}\}/g, " ")
.replace(/-->/g, "->")
.replace(/\s+/g, " ")
.trim();
}
export function wrapLines(text, max) {
const lines = [];
let cur = "";
for (let w of text.split(" ")) {
while ([...w].length > max) {
if (cur) {
lines.push(cur);
cur = "";
}
const chars = [...w];
lines.push(chars.slice(0, max).join(""));
w = chars.slice(max).join("");
}
if (!w) continue;
if (!cur) cur = w;
else if ([...`${cur} ${w}`].length <= max) cur += ` ${w}`;
else {
lines.push(cur);
cur = w;
}
}
if (cur) lines.push(cur);
return lines;
}
/**
* Balanced line breaks: the same number of lines as greedy wrapping at `max`, but at the narrowest
* width that still needs no more lines (so a cue reads "According to transport.example.org" /
* "and news.example.com" rather than a full line and a stub). Never narrower than the longest word.
*/
export function balancedLines(text, max) {
const greedy = wrapLines(text, max);
if (greedy.length <= 1) return greedy;
const longest = Math.max(...text.split(" ").map((w) => [...w].length));
let best = greedy;
for (let w = max - 1; w >= Math.max(longest, 8); w--) {
const l = wrapLines(text, w);
if (l.length > greedy.length) break;
best = l;
}
return best;
}
/**
* Splits one segment's text into cue-sized chunks (each fits max_lines lines of max_chars). Uses the
* fewest cues needed, preferring breaks after sentence or clause punctuation and cues of similar
* length (dynamic programming over word positions). Falls back to greedy grouping for unbreakable text.
*/
export function cueChunks(text, maxChars, maxLines) {
const greedyLines = wrapLines(text, maxChars);
if (greedyLines.length <= maxLines) return [text];
const words = text.split(" ");
const n = words.length;
const target = [...text].length / Math.ceil(greedyLines.length / maxLines);
const cost = new Array(n + 1).fill(Infinity);
const from = new Array(n + 1).fill(-1);
cost[0] = 0;
for (let j = 1; j <= n; j++) {
const last = words[j - 1];
const brk = j === n || /[.!?]["'\u201D)\]]?$/.test(last) ? 0 : /[,;:\u2013\u2014]["'\u201D)\]]?$/.test(last) ? 1 : 5;
for (let i = j - 1; i >= 0; i--) {
const chunk = words.slice(i, j).join(" ");
if (wrapLines(chunk, maxChars).length > maxLines) break; // longer chunks will not fit either
if (cost[i] === Infinity) continue;
const len = [...chunk].length;
const c = cost[i] + 1 + brk + 2 * ((len - target) / target) ** 2;
if (c < cost[j]) {
cost[j] = c;
from[j] = i;
}
}
}
if (cost[n] === Infinity) {
const groups = [];
for (let k = 0; k < greedyLines.length; k += maxLines) groups.push(greedyLines.slice(k, k + maxLines).join(" "));
return groups;
}
const chunks = [];
for (let j = n; j > 0; j = from[j]) chunks.unshift(words.slice(from[j], j).join(" "));
return chunks;
}
const p2 = (n, w = 2) => String(n).padStart(w, "0");
function stamp(sec, sep) {
const ms = Math.round(sec * 1000);
const h = Math.floor(ms / 3600000);
const m = Math.floor((ms % 3600000) / 60000);
const s = Math.floor((ms % 60000) / 1000);
return `${p2(h)}:${p2(m)}:${p2(s)}${sep}${p2(ms % 1000, 3)}`;
}
export function checkSegments(segments) {
for (const [i, s] of segments.entries()) {
if (!(s.end > s.start)) throw new ToolError("invalid_input", `script.segments[${i}]: end must be after start.`);
}
}
export function buildCaptions(script, opts = {}) {
const maxChars = opts.max_chars_per_line ?? 42;
const maxLines = opts.max_lines ?? 2;
const minCue = opts.min_cue_seconds ?? 1;
const offset = opts.offset_seconds ?? 0;
const warnings = [];
checkSegments(script.segments);
const segs = script.segments.map((s, i) => ({ ...s, i })).sort((a, b) => a.start - b.start || a.i - b.i);
let cues = [];
let short = 0;
let stripped = 0;
for (const s of segs) {
const text = captionText(s.text);
if (text !== String(s.text ?? "").replace(/\s+/g, " ").trim()) stripped++;
if (!text) {
warnings.push(`Segment ${s.i} has no caption text and was skipped.`);
continue;
}
const groups = cueChunks(text, maxChars, maxLines).map((c) => balancedLines(c, maxChars));
const total = groups.reduce((n, g) => n + g.join(" ").length, 0);
const dur = s.end - s.start;
if (groups.length > 1 && dur / groups.length < minCue) short++;
let t = s.start;
groups.forEach((g, k) => {
const end = k === groups.length - 1 ? s.end : t + (dur * g.join(" ").length) / total;
cues.push({ start: t + offset, end: end + offset, lines: g });
t = end;
});
}
if (short) warnings.push(`${short} segment(s) were split into cues shorter than ${minCue} s; shorten the text or lengthen the segment.`);
if (stripped) warnings.push(`${stripped} segment(s) had markup, control characters or "-->" removed from the caption text.`);
// Fix overlaps (a cue ends where the next starts) and drop cues pushed before 0.
let overlaps = 0;
for (let k = 0; k < cues.length - 1; k++) {
if (cues[k].end > cues[k + 1].start) {
cues[k].end = cues[k + 1].start;
overlaps++;
}
}
if (overlaps) warnings.push(`${overlaps} overlapping cue(s) were shortened to end when the next begins.`);
const before = cues.length;
cues = cues.map((c) => ({ ...c, start: Math.max(0, c.start) })).filter((c) => c.end - c.start >= 0.001);
if (cues.length < before) warnings.push(`${before - cues.length} cue(s) were dropped (zero length after fixing overlaps or offset).`);
const out = cues.map((c, k) => ({ index: k + 1, start: Math.round(c.start * 1000) / 1000, end: Math.round(c.end * 1000) / 1000, lines: c.lines }));
const srt = out.map((c) => `${c.index}\n${stamp(c.start, ",")} --> ${stamp(c.end, ",")}\n${c.lines.join("\n")}\n`).join("\n");
const vttEsc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
const vtt = `WEBVTT\n\n${out.map((c) => `${c.index}\n${stamp(c.start, ".")} --> ${stamp(c.end, ".")}\n${c.lines.map(vttEsc).join("\n")}\n`).join("\n")}`;
return { captions_srt: srt, captions_vtt: vtt, cues: out, warnings };
}