src/srt.js
// SubRip (.srt) caption export. Each segment is split into cues of at most two lines of at most
// `maxChars` characters (a single longer word stays whole). When a segment needs several cues, the
// words are divided into cues of similar length, preferring breaks after sentence or clause
// punctuation, so no cue is a one-word orphan flashing on screen for a fraction of a second. Each
// cue's time is the segment's time split in proportion to word count.
const MAX_LINES = 2;
function timestamp(sec) {
const total = Math.max(0, Math.round(sec * 1000));
const h = Math.floor(total / 3600000);
const m = Math.floor((total % 3600000) / 60000);
const s = Math.floor((total % 60000) / 1000);
const ms = total % 1000;
const p = (n, w = 2) => String(n).padStart(w, "0");
return `${p(h)}:${p(m)}:${p(s)},${p(ms, 3)}`;
}
/** Greedy wrap: lines of at most maxChars characters (a longer single word gets its own line). */
export function wrap(words, maxChars) {
const lines = [];
let cur = [];
for (const w of words) {
const next = cur.length ? `${cur.join(" ")} ${w}` : w;
if (next.length > maxChars && cur.length) {
lines.push(cur);
cur = [w];
} else cur.push(w);
}
if (cur.length) lines.push(cur);
return lines;
}
/** Cost of breaking after a word: 0 after . ! ?, small after , ; : and dashes, larger mid-phrase
* (a sentence end up to about 60% of a cue's length away from the ideal point still wins). */
const breakPenalty = (word) => (/[.!?]["'”’)\]]*$/.test(word) ? 0 : /[,;:—–]["'”’)\]]*$/.test(word) ? 0.25 : 0.6);
/** Characters of words[from..to) joined by single spaces. */
const span = (len, from, to) => len.slice(from, to).reduce((a, n) => a + n, 0) + Math.max(0, to - from - 1);
/** Splits words into k chunks of similar character length, preferring punctuation breaks. */
function splitBalanced(words, k, maxChars) {
const len = words.map((w) => w.length);
const total = span(len, 0, words.length);
const per = total / k;
const cuts = [];
let prev = 0;
for (let j = 1; j < k; j++) {
const ideal = per * j;
let best = null;
// Cut after word index i-1 (chunk ends at i); leave at least one word for each remaining chunk.
for (let i = prev + 1; i <= words.length - (k - j); i++) {
if (best && wrap(words.slice(prev, i), maxChars).length > MAX_LINES) break; // chunk no longer fits
const at = span(len, 0, i);
const score = Math.abs(at - ideal) / per + breakPenalty(words[i - 1]);
if (!best || score < best.score) best = { i, score };
}
cuts.push(best.i);
prev = best.i;
}
const chunks = [];
let start = 0;
for (const c of [...cuts, words.length]) {
chunks.push(words.slice(start, c));
start = c;
}
return chunks;
}
/** Two balanced lines for a chunk that needs two (minimises the longer line, prefers punctuation). */
function balanceLines(words, maxChars) {
const greedy = wrap(words, maxChars);
if (greedy.length !== 2) return greedy;
const len = words.map((w) => w.length);
let best = null;
for (let i = 1; i < words.length; i++) {
const a = span(len, 0, i);
const b = span(len, i, words.length);
if (a > maxChars || b > maxChars) continue;
const score = Math.max(a, b) / maxChars + breakPenalty(words[i - 1]) * 0.5;
if (!best || score < best.score) best = { i, score };
}
return best ? [words.slice(0, best.i), words.slice(best.i)] : greedy;
}
/** Word chunks, each fitting in at most two lines. */
export function cueChunks(words, maxChars) {
const lines = wrap(words, maxChars);
if (lines.length <= MAX_LINES) return [words];
for (let k = Math.ceil(lines.length / MAX_LINES); k <= words.length; k++) {
const chunks = splitBalanced(words, k, maxChars);
if (chunks.every((c) => wrap(c, maxChars).length <= MAX_LINES)) return chunks;
}
// Fallback (not reached for ordinary text): greedy pairs of lines.
const out = [];
for (let i = 0; i < lines.length; i += MAX_LINES) out.push(lines.slice(i, i + MAX_LINES).flat());
return out;
}
export function toSrt(segments, maxChars = 42) {
const cues = [];
for (const seg of segments) {
// "-->" inside caption text can confuse SRT parsers; captions show "->" instead.
const words = String(seg.text).replace(/-->/g, "->").split(/\s+/).filter(Boolean);
if (!words.length) continue;
const segSpan = seg.end - seg.start;
let before = 0;
for (const chunk of cueChunks(words, maxChars)) {
const start = seg.start + (segSpan * before) / words.length;
before += chunk.length;
const end = seg.start + (segSpan * before) / words.length;
cues.push({ start, end, text: balanceLines(chunk, maxChars).map((l) => l.join(" ")).join("\n") });
}
}
return cues.map((c, i) => `${i + 1}\n${timestamp(c.start)} --> ${timestamp(c.end)}\n${c.text}\n`).join("\n");
}