// Roblox transcode sessions: one ffmpeg per session turns an API playback path (/v1/p, /v1/remux, // /v1/torrent) into numbered 2 s MPEG-TS segments (mpeg1video + mp2, the jsmpeg recipe) in a temp // dir, because Roblox can only fetch whole bodies and decodes video in Luau. ffmpeg reads the source // over loopback from this server, so the usual signed-token + SSRF rules still apply upstream. // ffmpeg runs as fast as it can but is SIGSTOPped once it is AHEAD segments past the highest // segment requested; segments far behind it are deleted, so disk use stays bounded. const { spawn } = require('child_process'); const fs = require('fs'); const os = require('os'); const path = require('path'); const http = require('http'); const crypto = require('crypto'); const { verify } = require('../sign'); const { CORS, json, error } = require('../http'); const remux = require('./remux'); const AHEAD = 30; // SIGSTOP ffmpeg when this many segments are ready past the highest request const RESUME = 24; // SIGCONT when the lead drops back to this const BEHIND = 10; // keep this many segments before the highest request, delete older ones const WAIT_MS = 25000; // a segment request waits this long for the segment to be written const POLL_MS = 200; const FPS = [23.976, 24, 25, 29.97, 30]; // MPEG-1 frame_rate_code values ≤ 30 (jsmpeg's table) const MP2_RATES = [32, 48, 56, 64, 80, 96, 112, 128, 160, 192]; // kbit/s, stereo layer II ≤ 192k const sessions = new Map(); // id -> session let opening = 0; // sessions being probed (they count against the cap) let cfgRef = { host: '127.0.0.1', port: 8789, remux: { ffmpeg: 'ffmpeg' } }; let sweeper = null; const stats = { opened: 0, failed: 0, closed: 0, idle: 0 }; function rcfg() { const r = cfgRef.rbx || {}; return { maxSessions: Number(r.maxSessions) || 4, segment: Math.min(10, Math.max(1, Number(r.segment) || 2)), idleSec: Number(r.idleSec) || 60, tmpDir: r.tmpDir || path.join(os.tmpdir(), 'bug-tv-rbx'), }; } function init(cfg) { cfgRef = cfg; const dir = rcfg().tmpDir; fs.mkdirSync(dir, { recursive: true }); // leftovers from a previous run that died without cleaning up for (const name of fs.readdirSync(dir)) if (/^s-[\w-]+$/.test(name)) fs.rmSync(path.join(dir, name), { recursive: true, force: true }); if (!sweeper) { sweeper = setInterval(sweep, 2000).unref(); process.on('exit', killAllSync); // without a handler these signals skip 'exit'; keep their default "die" behaviour for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) { if (!process.listenerCount(sig)) process.once(sig, () => process.exit(128 + os.constants.signals[sig])); } } } function loopbackBase() { const h = cfgRef.host; const host = !h || h === '0.0.0.0' ? '127.0.0.1' : h === '::' ? '[::1]' : h.includes(':') ? `[${h}]` : h; return `http://${host}:${cfgRef.port}`; } // ---- parameters ---- function num(v, def, min, max) { const n = parseFloat(v); return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : def; } // "450k" / "1.2M" / "450000" -> bit/s function bitrate(v, def) { const m = String(v ?? '').trim().match(/^(\d+(?:\.\d+)?)\s*([kKmM]?)$/); if (!m) return def; return Math.round(parseFloat(m[1]) * (m[2] ? (/m/i.test(m[2]) ? 1e6 : 1e3) : 1)); } const even = (n) => Math.max(2, Math.round(n / 2) * 2); function params(q) { const fps = num(q.get('fps'), 24, 1, 30); const abK = Math.min(192, Math.max(32, bitrate(q.get('ab'), 96000) / 1000)); const audio = q.get('audio'); return { start: num(q.get('start'), 0, 0, 1e7), width: even(num(q.get('w'), 320, 32, 640)), height: even(num(q.get('h'), 180, 32, 360)), fps: FPS.reduce((a, b) => (Math.abs(b - fps) < Math.abs(a - fps) ? b : a)), vb: Math.min(1500e3, Math.max(64e3, bitrate(q.get('vb'), 450e3))), ab: MP2_RATES.filter((r) => r <= abK).pop() * 1000, audio: audio != null && /^\d+$/.test(audio) ? Number(audio) : null, }; } // API-relative playback path -> { kind, token, url (what ffmpeg reads), probe }, or { status, error } function parseSrc(src) { if (typeof src !== 'string' || !src) return { status: 400, error: 'src required' }; if (!src.startsWith('/') || src.startsWith('//') || /[\\\s]/.test(src)) return { status: 400, error: 'src must be an API-relative path (/v1/p/…, /v1/remux/…, /v1/torrent/…)' }; let u; try { u = new URL(src, 'http://api.invalid'); } catch { return { status: 400, error: 'bad src' }; } if (u.host !== 'api.invalid') return { status: 400, error: 'bad src' }; const base = loopbackBase(); let m; if ((m = u.pathname.match(/^\/v1\/p\/([^/]+)\/./))) { const tok = verify(decodeURIComponent(m[1])); if (!tok || typeof tok.o !== 'string') return { status: 403, error: 'invalid token' }; return { kind: 'p', url: base + u.pathname + u.search }; } if ((m = u.pathname.match(/^\/v1\/remux\/([^/]+)$/))) { const tok = verify(decodeURIComponent(m[1])); if (!tok || typeof tok.u !== 'string') return { status: 403, error: 'invalid token' }; return { kind: 'remux', tok, path: u.pathname, audio: u.searchParams.get('audio') }; } if ((m = u.pathname.match(/^\/v1\/torrent\/([^/]+)\/(stream|raw)$/))) { const tok = verify(decodeURIComponent(m[1])); if (!tok || typeof tok.m !== 'string') return { status: 403, error: 'invalid token' }; // read /raw (range-served file), not /stream (which may itself remux): real input seeking, one ffmpeg return { kind: 'torrent', url: `${base}/v1/torrent/${m[1]}/raw`, probe: `${base}/v1/torrent/${m[1]}/probe` }; } return { status: 400, error: 'src must start with /v1/p/, /v1/remux/ or /v1/torrent/' }; } // GET a JSON endpoint of this server over loopback function getJson(url, timeoutMs) { return new Promise((resolve, reject) => { const req = http.get(url, { timeout: timeoutMs }, (r) => { let body = ''; r.setEncoding('utf8'); r.on('data', (c) => (body = body.length < 1e6 ? body + c : body)); r.on('end', () => { let obj = null; try { obj = JSON.parse(body); } catch {} if (r.statusCode !== 200) return reject(Object.assign(new Error(obj?.error || `HTTP ${r.statusCode}`), { status: r.statusCode })); resolve(obj); }); }); req.on('timeout', () => req.destroy(new Error('probe timeout'))); req.on('error', reject); }); } // ---- ffmpeg ---- function buildArgs({ input, seek, offset, audioMap, silence, p, seg, dir, reconnect }) { const { width: w, height: h, fps } = p; const args = ['-hide_banner', '-loglevel', 'error', '-nostdin', '-fflags', '+genpts+discardcorrupt']; if (reconnect) args.push('-reconnect', '1', '-reconnect_on_network_error', '1', '-reconnect_delay_max', '4'); if (seek > 0) args.push('-ss', String(seek)); args.push('-i', input); if (silence) args.push('-f', 'lavfi', '-i', 'anullsrc=r=44100:cl=stereo'); args.push('-map', '0:v:0?', '-map', silence ? '1:a:0' : audioMap); if (silence) args.push('-shortest'); args.push( '-vf', `scale=${w}:${h}:force_original_aspect_ratio=decrease:force_divisible_by=2,pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p`, '-r', String(fps), '-c:v', 'mpeg1video', '-b:v', String(p.vb), '-maxrate', String(Math.round(p.vb * 1.5)), '-bufsize', String(p.vb), // one closed GOP per segment, no B-frames, keyframes only where we force them '-g', String(Math.round(fps * seg)), '-bf', '0', '-flags', '+cgop', '-sc_threshold', '1000000000', '-force_key_frames', `expr:gte(t,n_forced*${seg})`, '-c:a', 'mp2', '-ar', '44100', '-ac', '2', '-b:a', String(p.ab), '-sn', '-dn', '-map_metadata', '-1', '-max_muxing_queue_size', '2048', // pts inside the TS = source time, so X-Rbx-Pts and the demuxed pts agree '-output_ts_offset', String(offset), '-f', 'segment', '-segment_time', String(seg), '-segment_time_delta', String(0.5 / fps), '-segment_format', 'mpegts', '-segment_list', path.join(dir, 'list.csv'), '-segment_list_type', 'csv', '-reset_timestamps', '0', '-muxdelay', '0', '-muxpreload', '0', '-progress', 'pipe:1', '-stats_period', '1', path.join(dir, 'seg_%05d.ts'), ); return args; } // Resolve the source: what ffmpeg reads, where it seeks, the real start, duration and audio tracks. async function resolveSource(src, p) { if (src.kind === 'remux') { // The remux starts at the keyframe at/before ?start= (stream copy), and its output says nothing // about where that was, so find it here with a generous timeout (the remux route's own lookup // gives up after 8 s, which slow hosts exceed; its X-Bug-Tv-Offset then falls back to `start`). const info = await remux.probe(src.tok.u, src.tok.h, { timeoutMs: 30000 }); const kf = p.start > 0 && info?.video ? await remux.keyframeAt(src.tok.u, src.tok.h, p.start, info.startTime, 25000) : null; const audio = p.audio ?? (src.audio != null && /^\d+$/.test(src.audio) ? Number(src.audio) : null); const qs = new URLSearchParams(); if (p.start > 0) qs.set('start', String(p.start)); if (audio != null) qs.set('audio', String(audio)); const start = p.start > 0 ? (kf != null && kf <= p.start + 0.001 ? Math.round(kf * 1000) / 1000 : p.start) : 0; const input = `${loopbackBase()}${src.path}${qs.size ? `?${qs}` : ''}`; return { info, input, seek: 0, start, exact: p.start === 0 || kf != null, audioMap: '0:a:0?', reconnect: false }; } const info = src.kind === 'torrent' ? await getJson(src.probe, 120000) : await remux.probe(src.url, {}, { trusted: true, timeoutMs: 30000 }); const track = p.audio != null && info?.audio?.find((a) => a.index === p.audio); // transcoding from an input seek is frame accurate: output t=0 is exactly `start` return { info, input: src.url, seek: p.start, start: p.start, exact: true, audioMap: track ? `0:${track.index}` : '0:a:0?', reconnect: true }; } // ---- sessions ---- async function open(req, res, q) { if (req.method === 'HEAD') return error(req, res, 405, 'use GET'); const src = parseSrc(q.get('src')); if (src.error) return error(req, res, src.status, src.error); const { maxSessions, segment: seg, tmpDir } = rcfg(); if (sessions.size + opening >= maxSessions) return error(req, res, 503, 'too many transcode sessions', { max: maxSessions }); const p = params(q); opening++; let s; try { let r; try { r = await resolveSource(src, p); } catch (e) { stats.failed++; return error(req, res, e.status === 403 || e.code === 'EBLOCKED' ? 403 : 502, `source probe failed: ${e.message}`); } if (res.destroyed) return; const duration = Number(r.info?.duration) || null; if (duration && r.start >= duration) return error(req, res, 400, 'start is past the end', { duration }); const id = crypto.randomBytes(9).toString('base64url'); const dir = path.join(tmpDir, `s-${id}`); fs.mkdirSync(dir, { recursive: true }); const silence = !!r.info && Array.isArray(r.info.audio) && r.info.audio.length === 0; const args = buildArgs({ input: r.input, seek: r.seek, offset: r.start, audioMap: r.audioMap, silence, p, seg, dir, reconnect: r.reconnect }); const ff = spawn(cfgRef.remux?.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'] }); s = { id, dir, ff, seg, start: r.start, duration, p, segs: [], // [{ file, pts }] complete segments, in order listOffset: 0, listRest: '', reading: false, deleted: 0, // segments below this index were deleted maxReq: -1, last: Date.now(), active: 0, stopped: false, ended: false, closed: false, error: null, speed: null, stderr: '', waiters: new Set(), timer: null, watcher: null, progAt: Date.now(), progT: 0, stoppedAt: 0, // first speed sample spans from spawn }; sessions.set(id, s); stats.opened++; wire(s); return json(req, res, 200, { id, segment: seg, start: r.start, startExact: r.exact, duration, width: p.width, height: p.height, fps: p.fps, sampleRate: 44100, channels: 2, videoBitrate: p.vb, audioBitrate: p.ab, audioTracks: r.info?.audio || [], }); } finally { opening--; } } function wire(s) { const { ff } = s; let out = ''; ff.stdout.setEncoding('utf8'); ff.stdout.on('data', (c) => { out += c; const lines = out.split('\n'); out = lines.pop(); for (const l of lines) { // ffmpeg's own speed= is N/A for some inputs (e.g. the fragmented-MP4 remux pipe), so measure // media seconds per wall second between progress reports (~1 s apart) const m = l.match(/^out_time_us=(\d+)/); if (!m) continue; const now = Date.now(); const t = Number(m[1]) / 1e6; if (now - s.progAt > 200) s.speed = Math.round(((t - s.progT) / ((now - s.progAt) / 1000)) * 10) / 10; s.progAt = now; s.progT = t; } }); ff.stderr.on('data', (c) => (s.stderr = (s.stderr + c).slice(-4000))); ff.on('error', (e) => { s.error = `ffmpeg spawn failed: ${e.message}`; finish(s); }); ff.on('close', async (code, signal) => { if (!s.closed) { await readList(s); if (code !== 0 && !s.error) s.error = s.stderr.trim().split('\n').slice(-3).join(' | ') || `ffmpeg exited (${code ?? signal})`; if (s.error) stats.failed++; } finish(s); }); s.timer = setInterval(() => tick(s), POLL_MS); // react to new files at once: at 50-100x real time ffmpeg writes several segments per poll try { s.watcher = fs.watch(s.dir, () => tick(s)); s.watcher.on('error', () => {}); } catch {} } function finish(s) { if (s.ended) return; s.ended = true; clearInterval(s.timer); s.watcher?.close(); wake(s); if (s.closed) rmDir(s); } function wake(s) { for (const w of s.waiters) w(); s.waiters.clear(); } // read the new lines of ffmpeg's segment list (one "seg_00000.ts,start,end" line per finished segment) async function readList(s) { if (s.reading || s.closed) return; s.reading = true; let fh; try { fh = await fs.promises.open(path.join(s.dir, 'list.csv'), 'r'); const { size } = await fh.stat(); if (size > s.listOffset) { const buf = Buffer.alloc(size - s.listOffset); const { bytesRead } = await fh.read(buf, 0, buf.length, s.listOffset); s.listOffset += bytesRead; const lines = (s.listRest + buf.toString('utf8', 0, bytesRead)).split('\n'); s.listRest = lines.pop(); const before = s.segs.length; for (const line of lines) { const [file, t0] = line.trim().split(','); if (!/^seg_\d+\.ts$/.test(file || '')) continue; // the segment muxer reports 0 as segment 0's start; its first frame is really at `start` s.segs.push({ file, pts: s.segs.length === 0 ? s.start : Number(t0) }); } if (s.segs.length > before) wake(s); } } catch (e) { if (e.code !== 'ENOENT') s.stderr += `\nlist: ${e.message}`; } finally { await fh?.close().catch(() => {}); s.reading = false; } } async function tick(s) { await readList(s); if (s.ended || s.closed) return; const lead = s.segs.length - (s.maxReq + 1); if (!s.stopped && lead > AHEAD) { s.stopped = true; s.stoppedAt = Date.now(); s.ff.kill('SIGSTOP'); } else if (s.stopped && lead <= RESUME) { s.stopped = false; s.progAt += Date.now() - s.stoppedAt; // keep the pause out of the next speed sample s.ff.kill('SIGCONT'); } } function rmDir(s) { return fs.promises.rm(s.dir, { recursive: true, force: true }).catch(() => {}); } // resolves once the dir is gone when ffmpeg had already exited; otherwise ffmpeg's 'close' removes it function close(s, why = 'closed') { if (s.closed) return Promise.resolve(); s.closed = true; s.closeReason = why; sessions.delete(s.id); stats[why === 'idle' ? 'idle' : 'closed']++; clearInterval(s.timer); s.watcher?.close(); wake(s); if (s.ended || s.ff.exitCode !== null || s.ff.signalCode !== null) return rmDir(s); s.ff.kill('SIGKILL'); // works on a SIGSTOPped process too return Promise.resolve(); } function sweep() { const idleMs = rcfg().idleSec * 1000; const now = Date.now(); for (const s of sessions.values()) if (s.active === 0 && now - s.last > idleMs) close(s, 'idle'); } function killAllSync() { for (const s of sessions.values()) { try { s.ff.kill('SIGKILL'); } catch {} try { fs.rmSync(s.dir, { recursive: true, force: true }); } catch {} } sessions.clear(); } // wait until segment n is complete, the process ended, the session closed, or the timeout async function waitFor(s, n, ms) { const deadline = Date.now() + ms; for (;;) { if (n < s.segs.length || s.ended || s.closed) return; const left = deadline - Date.now(); if (left <= 0) return; await new Promise((resolve) => { const t = setTimeout(done, Math.min(left, 1000)); function done() { clearTimeout(t); s.waiters.delete(done); resolve(); } s.waiters.add(done); }); await readList(s); } } async function segment(req, res, id, n) { const s = sessions.get(id); if (!s) return error(req, res, 404, 'no such session'); s.last = Date.now(); if (n > s.maxReq) { s.maxReq = n; tick(s); // may SIGCONT right away } if (n < s.deleted) return error(req, res, 410, 'segment already discarded', { oldest: s.deleted }); s.active++; try { await waitFor(s, n, WAIT_MS); } finally { s.active--; s.last = Date.now(); } if (s.closed) return error(req, res, 410, 'session closed'); if (n >= s.segs.length) { if (!s.ended) return error(req, res, 504, 'segment not ready', { produced: s.segs.length }); if (s.error) return error(req, res, 502, s.error, { produced: s.segs.length }); res.writeHead(204, { ...CORS, 'Cache-Control': 'no-store' }); return res.end(); } const seg = s.segs[n]; const file = path.join(s.dir, seg.file); // drop segments the client has moved well past while (s.deleted < s.maxReq - BEHIND && s.deleted < s.segs.length) { fs.promises.rm(path.join(s.dir, s.segs[s.deleted].file), { force: true }).catch(() => {}); s.deleted++; } let buf; try { buf = await fs.promises.readFile(file); } catch (e) { return error(req, res, s.closed ? 410 : 500, e.message); } res.writeHead(200, { ...CORS, 'Content-Type': 'video/mp2t', 'Content-Length': buf.length, 'Cache-Control': 'no-store', 'X-Rbx-Pts': String(Math.round(seg.pts * 1000) / 1000), }); res.end(req.method === 'HEAD' ? undefined : buf); } function status(req, res, id) { const s = sessions.get(id); if (!s) return error(req, res, 404, 'no such session'); s.last = Date.now(); return json(req, res, 200, { produced: s.segs.length, ended: s.ended, error: s.error, speed: s.speed, paused: s.stopped, requested: s.maxReq, start: s.start, duration: s.duration, segment: s.seg, }); } async function closeRoute(req, res, id) { const s = sessions.get(id); if (!s) return error(req, res, 404, 'no such session'); await close(s); return json(req, res, 200, { ok: true }); } function rbxStats() { return { sessions: sessions.size, max: rcfg().maxSessions, ...stats }; } module.exports = { init, open, segment, status, close: closeRoute, rbxStats, params, parseSrc, buildArgs, killAllSync, _sessions: sessions };