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

236 lines
9.1 KiB
JavaScript

// ffmpeg remux: any container ffmpeg can read → fragmented MP4 on stdout, video copied,
// audio copied when the browser can play it (aac/mp3/opus) else AAC stereo.
// Seeking = new request with ?start=<sec> (input seeking, so ffmpeg uses the container index /
// HTTP range requests); the response carries X-Bug-Tv-Offset so the player can offset its clock.
const { spawn } = require('child_process');
const { CORS, error } = require('../http');
const { assertPublicUrl, LRU } = require('./net');
const probeCache = new LRU(200);
const probeInflight = new Map();
const procs = new Set();
let cfgRef = { remux: { ffmpeg: 'ffmpeg', ffprobe: 'ffprobe', maxProcs: 4 } };
const stats = { started: 0, failed: 0 };
const COPY_AUDIO = new Set(['aac', 'mp3', 'opus']);
function init(cfg) {
cfgRef = cfg;
}
function maxProcs() {
return Number(cfgRef.remux?.maxProcs) || 4;
}
// ffmpeg/ffprobe input options for http headers
function inputArgs(url, headers = {}) {
const args = [];
if (!/^https?:/i.test(url)) return args;
let extra = '';
for (const [k, v] of Object.entries(headers || {})) {
if (typeof v !== 'string' || /[\r\n]/.test(v) || /[\r\n:]/.test(k)) continue;
if (k.toLowerCase() === 'user-agent') args.push('-user_agent', v);
else extra += `${k}: ${v}\r\n`;
}
if (extra) args.push('-headers', extra);
return args;
}
function runProbe(url, headers, timeoutMs = 30000) {
return new Promise((resolve, reject) => {
const args = ['-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', ...inputArgs(url, headers), '-i', url];
const p = spawn(cfgRef.remux?.ffprobe || 'ffprobe', args, { stdio: ['ignore', 'pipe', 'pipe'] });
let out = '';
let err = '';
const t = setTimeout(() => p.kill('SIGKILL'), timeoutMs);
p.stdout.on('data', (c) => (out += c));
p.stderr.on('data', (c) => (err = (err + c).slice(-2000)));
p.on('error', (e) => (clearTimeout(t), reject(e)));
p.on('close', (code) => {
clearTimeout(t);
if (code !== 0) return reject(new Error(`ffprobe failed (${code}): ${err.trim() || 'timeout'}`));
try {
resolve(JSON.parse(out));
} catch (e) {
reject(e);
}
});
});
}
function shape(raw) {
const streams = raw.streams || [];
const v = streams.find((s) => s.codec_type === 'video' && !s.disposition?.attached_pic);
const dur = Number(raw.format?.duration) || Number(v?.duration) || null;
return {
duration: dur,
startTime: Number(raw.format?.start_time) || 0,
container: raw.format?.format_name || null,
video: v ? { codec: v.codec_name, width: v.width, height: v.height, profile: v.profile || null, pixFmt: v.pix_fmt || null } : null,
audio: streams
.filter((s) => s.codec_type === 'audio')
.map((s) => ({
index: s.index,
codec: s.codec_name,
lang: s.tags?.language || '',
channels: s.channels || null,
title: s.tags?.title || '',
default: !!s.disposition?.default,
})),
subtitles: streams
.filter((s) => s.codec_type === 'subtitle')
.map((s) => ({ index: s.index, codec: s.codec_name, lang: s.tags?.language || '', title: s.tags?.title || '' })),
};
}
// Time (relative to the container start) of the keyframe ffmpeg will actually start from when
// input-seeking to `start` with stream copy — it is the keyframe at/before `start`, so the
// remux's t=0 is this, not `start`. Resolves null on failure.
function keyframeAt(url, headers, start, startTime = 0, timeoutMs = 8000) {
return new Promise((resolve) => {
const args = ['-v', 'error', ...inputArgs(url, headers), '-read_intervals', `${start + startTime}%+#1`,
'-select_streams', 'v:0', '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', '-i', url];
const p = spawn(cfgRef.remux?.ffprobe || 'ffprobe', args, { stdio: ['ignore', 'pipe', 'ignore'] });
let out = '';
const t = setTimeout(() => p.kill('SIGKILL'), timeoutMs);
p.stdout.on('data', (c) => (out += c));
p.on('error', () => (clearTimeout(t), resolve(null)));
p.on('close', () => {
clearTimeout(t);
const v = parseFloat(out.trim().split(/\s+/)[0]);
resolve(Number.isFinite(v) ? Math.max(0, v - startTime) : null);
});
});
}
// cached probe → contract shape
async function probe(url, headers, { trusted = false, timeoutMs } = {}) {
const key = `${url}|${JSON.stringify(headers || {})}`;
const hit = probeCache.get(key);
if (hit) return hit;
if (probeInflight.has(key)) return probeInflight.get(key);
const p = (async () => {
if (!trusted) await assertPublicUrl(url);
const info = shape(await runProbe(url, headers, timeoutMs));
probeCache.set(key, info, 6 * 60 * 60 * 1000);
return info;
})().finally(() => probeInflight.delete(key));
probeInflight.set(key, p);
return p;
}
function buildArgs({ url, headers, start, audioStream, video }) {
const args = ['-hide_banner', '-loglevel', 'error', '-nostdin', '-fflags', '+genpts+discardcorrupt'];
if (/^https?:/i.test(url)) args.push('-reconnect', '1', '-reconnect_on_network_error', '1', '-reconnect_delay_max', '4');
args.push(...inputArgs(url, headers));
if (start > 0) args.push('-ss', String(start));
args.push('-i', url, '-map', '0:v:0?');
args.push('-map', audioStream ? `0:${audioStream.index}` : '0:a:0?');
args.push('-c:v', 'copy');
if (video?.codec === 'hevc') args.push('-tag:v', 'hvc1');
if (audioStream && COPY_AUDIO.has(audioStream.codec)) args.push('-c:a', 'copy');
else args.push('-c:a', 'aac', '-b:a', '192k', '-ac', '2');
args.push(
'-sn', '-dn', '-map_metadata', '-1', '-max_muxing_queue_size', '2048',
'-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov+default_base_moof', 'pipe:1',
);
return args;
}
/**
* Stream a remux to `res`.
* opts: { url, headers, start, audio (absolute stream index), trusted (skip SSRF check: internal URLs) }
*/
async function remux(req, res, opts) {
const start = Math.max(0, Number(opts.start) || 0);
const baseHeaders = {
...CORS,
'Content-Type': 'video/mp4',
'Cache-Control': 'no-store',
'X-Bug-Tv-Offset': String(start),
'Accept-Ranges': 'none',
};
if (req.method === 'HEAD') {
res.writeHead(200, baseHeaders);
return res.end();
}
if (procs.size >= maxProcs()) return error(req, res, 503, 'too many concurrent remux sessions', { max: maxProcs() });
let info = null;
try {
if (!opts.trusted) await assertPublicUrl(opts.url);
} catch (e) {
return error(req, res, 403, e.message);
}
try {
info = await probe(opts.url, opts.headers, { trusted: true, timeoutMs: opts.probeTimeoutMs || 20000 });
} catch {
info = null; // ffmpeg will still try; audio gets transcoded
}
if (res.destroyed) return;
if (procs.size >= maxProcs()) return error(req, res, 503, 'too many concurrent remux sessions', { max: maxProcs() });
let audioStream = null;
if (info) {
const want = opts.audio != null && opts.audio !== '' ? Number(opts.audio) : null;
audioStream =
(want != null && info.audio.find((a) => a.index === want)) || info.audio.find((a) => a.default) || info.audio[0] || null;
}
const args = buildArgs({ url: opts.url, headers: opts.headers, start, audioStream, video: info?.video });
const ff = spawn(cfgRef.remux?.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'] });
// in parallel: find the real start (keyframe) so X-Bug-Tv-Offset matches the output's t=0
const offsetP = start > 0 && info?.video ? keyframeAt(opts.url, opts.headers, start, info.startTime) : Promise.resolve(null);
procs.add(ff);
stats.started++;
let stderr = '';
let killed = false;
const kill = () => {
if (killed || ff.exitCode !== null) return;
killed = true;
ff.kill('SIGTERM');
setTimeout(() => ff.exitCode === null && ff.kill('SIGKILL'), 2000).unref();
};
ff.stderr.on('data', (c) => (stderr = (stderr + c).slice(-4000)));
res.on('close', kill);
await new Promise((resolve) => {
let started = false;
ff.stdout.once('data', async (chunk) => {
started = true;
ff.stdout.pause();
const real = await offsetP;
if (res.destroyed) return;
const off = real != null && real <= start + 0.001 ? real : start;
res.writeHead(200, { ...baseHeaders, 'X-Bug-Tv-Offset': String(Math.round(off * 1000) / 1000) });
res.write(chunk);
ff.stdout.pipe(res);
});
ff.on('error', (e) => {
stats.failed++;
if (!res.headersSent) error(req, res, 500, `ffmpeg spawn failed: ${e.message}`);
resolve();
});
ff.on('close', (code) => {
procs.delete(ff);
res.off('close', kill);
if (!started) {
stats.failed++;
if (!res.headersSent && !res.destroyed) error(req, res, 502, 'remux failed', { code, stderr: stderr.trim().slice(-800) });
} else if (code !== 0 && !killed) {
res.destroy(); // truncated output: let the player notice
}
resolve();
});
});
}
function remuxStats() {
return { ffmpeg: procs.size, maxProcs: maxProcs(), probesCached: probeCache.size, ...stats };
}
function killAll() {
for (const p of procs) p.kill('SIGKILL');
}
module.exports = { init, remux, probe, keyframeAt, remuxStats, killAll, buildArgs };