Files
tv/src/media/subs.js
T
2026-10-27 05:49:38 -05:00

119 lines
4.4 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Subtitle fetch + conversion to WebVTT (VTT passthrough, SRT, ASS/SSA dialogue), cached.
const { fetchUpstream, readBody, cleanHeaders, LRU } = require('./net');
const cache = new LRU(200);
const inflight = new Map();
const TTL = 30 * 60 * 1000;
function decode(buf) {
if (buf[0] === 0xff && buf[1] === 0xfe) return new TextDecoder('utf-16le').decode(buf.subarray(2));
if (buf[0] === 0xfe && buf[1] === 0xff) return new TextDecoder('utf-16be').decode(buf.subarray(2));
try {
return new TextDecoder('utf-8', { fatal: true }).decode(buf).replace(/^/, '');
} catch {
return new TextDecoder('windows-1252').decode(buf);
}
}
const pad = (n, w = 2) => String(n).padStart(w, '0');
function fmt(ms) {
ms = Math.max(0, Math.round(ms));
const h = Math.floor(ms / 3600000);
const m = Math.floor((ms % 3600000) / 60000);
const s = Math.floor((ms % 60000) / 1000);
return `${pad(h)}:${pad(m)}:${pad(s)}.${pad(ms % 1000, 3)}`;
}
// "01:02:03,456" | "1:02:03.45" | "02:03,456" → ms
function parseTime(t) {
const m = String(t).trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{1,2})(?:[.,:](\d{1,3}))?$/);
if (!m) return NaN;
const frac = m[4] ? Number(m[4].padEnd(3, '0')) : 0;
return ((Number(m[1] || 0) * 60 + Number(m[2])) * 60 + Number(m[3])) * 1000 + frac;
}
function srtToVtt(text) {
const out = ['WEBVTT', ''];
for (const block of text.replace(/\r\n?/g, '\n').split(/\n{2,}/)) {
const lines = block.split('\n');
const ti = lines.findIndex((l) => l.includes('-->'));
if (ti < 0) continue;
const [a, b] = lines[ti].split('-->');
const start = parseTime(a);
const end = parseTime(String(b).trim().split(/\s+/)[0]);
if (Number.isNaN(start) || Number.isNaN(end)) continue;
const body = lines
.slice(ti + 1)
.join('\n')
.replace(/\{\\[^}]*\}/g, '')
.replace(/<\/?font[^>]*>/gi, '')
.trim();
if (!body) continue;
out.push(`${fmt(start)} --> ${fmt(end)}`, body.replace(/-->/g, '→'), '');
}
return out.join('\n');
}
function assToVtt(text) {
const cues = [];
let inEvents = false;
let format = ['layer', 'start', 'end', 'style', 'name', 'marginl', 'marginr', 'marginv', 'effect', 'text'];
for (const raw of text.replace(/\r\n?/g, '\n').split('\n')) {
const line = raw.trim();
if (/^\[.*\]$/.test(line)) {
inEvents = /^\[events\]$/i.test(line);
continue;
}
if (!inEvents) continue;
if (/^format\s*:/i.test(line)) {
format = line.replace(/^format\s*:/i, '').split(',').map((s) => s.trim().toLowerCase());
continue;
}
if (!/^dialogue\s*:/i.test(line)) continue;
const parts = line.replace(/^dialogue\s*:/i, '').split(',');
const fields = parts.slice(0, format.length - 1).concat(parts.slice(format.length - 1).join(','));
const get = (k) => (fields[format.indexOf(k)] ?? '').trim();
const start = parseTime(get('start'));
const end = parseTime(get('end'));
const body = get('text')
.replace(/\{[^}]*\}/g, '')
.replace(/\\[Nn]/g, '\n')
.replace(/\\h/g, ' ')
.trim();
if (Number.isNaN(start) || Number.isNaN(end) || !body) continue;
cues.push({ start, end, body });
}
cues.sort((a, b) => a.start - b.start);
return ['WEBVTT', '', ...cues.flatMap((c) => [`${fmt(c.start)} --> ${fmt(c.end)}`, c.body, ''])].join('\n');
}
function toVtt(buf) {
const text = decode(buf);
const head = text.trimStart().slice(0, 200);
if (/^WEBVTT/.test(head)) return text.replace(/\r\n?/g, '\n');
if (/^\[script info\]/i.test(head) || /^\[v4\+? styles\]/i.test(head) || /\n\s*dialogue\s*:/i.test(text.slice(0, 20000)) && /\[events\]/i.test(text))
return assToVtt(text);
return srtToVtt(text);
}
async function getVtt(tok) {
const key = `${tok.u}|${JSON.stringify(tok.h || {})}`;
const hit = cache.get(key);
if (hit) return hit;
if (inflight.has(key)) return inflight.get(key);
const p = (async () => {
const up = await fetchUpstream(tok.u, { headers: { ...cleanHeaders(tok.h), 'accept-encoding': 'gzip, br' } });
if (up.statusCode >= 400) {
up.body.resume();
throw Object.assign(new Error(`upstream ${up.statusCode}`), { status: 502 });
}
const vtt = toVtt(await readBody(up, 10 * 1024 * 1024));
cache.set(key, vtt, TTL);
return vtt;
})().finally(() => inflight.delete(key));
inflight.set(key, p);
return p;
}
module.exports = { getVtt, toVtt, srtToVtt, assToVtt, subsStats: () => ({ cached: cache.size }) };