diff --git a/docs/api.md b/docs/api.md index 9bf8e8a..669eeeb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -13,7 +13,7 @@ deviate, keep the deviation backwards compatible and note it at the bottom of th ## Server wiring (already written — `src/server.js`) - Each `src/routes/.js` exports `{ routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }`. `path` is an exact string or a RegExp; capture groups → `ctx.params` (URI-decoded). - `ctx = { cfg, url, params }`. Loaded modules: `health providers streams proxy torrent remux subs openapi`. + `ctx = { cfg, url, params }`. Loaded modules: `health providers streams proxy torrent remux subs rbx openapi`. - Helpers in `src/http.js`: `send(req,res,status,body,type,extraHeaders)` (auto br/gzip for text >1KB), `json(req,res,status,obj)`, `error(req,res,status,msg,extra)`, `sse(req,res)` → `{event(name,data), close(), closed}`, `CORS` headers object. - `src/sign.js`: `sign(obj) → token`, `verify(token) → obj|null` (HMAC, URL-safe, no `/`). @@ -22,6 +22,7 @@ deviate, keep the deviation backwards compatible and note it at the bottom of th { host, port, tmdbKey, enabledProviders: [..] ([] = all), disabledProviders: [..] (default ["torrentio"]), providerSettings: {..} (→ global.SCRAPER_SETTINGS), timeoutMs, workers (0 = auto, min(cpus,4)), cacheTtlSec, secret, torrent: { enable, cacheDir, maxSizeGB }, remux: { enable, ffmpeg, ffprobe }, + rbx: { enable, maxSessions, segment, idleSec, tmpDir }, filters: { minQuality, audioCodec, subtitles, subtitleLang } } ``` Config file path: `$BUG_TV_CONFIG` or `./config.json`. @@ -97,6 +98,56 @@ Starts the scrape in the background to fill the cache (used for next episode). ### `GET /healthz` → `{ ok: true }` ### `GET /` Swagger UI, `GET /api.json` OpenAPI spec (`src/routes/openapi.js`). +## Roblox transcode (`/v1/rbx`) +For clients that can't play browser media: Roblox only gets whole HTTP bodies (server-side +HttpService) and decodes video in Luau. A session runs one ffmpeg that turns a playback path into +numbered MPEG-TS segments, **MPEG-1 video + MP2 audio** (the jsmpeg recipe), in a temp dir. +Code: `src/routes/rbx.js`, `src/media/rbx.js`. Tests: `node --test test/`. + +### `GET /v1/rbx/open?src=&start=&w=&h=&fps=&vb=&ab=&audio=` +- `src` (required): an API-relative playback path — `/v1/p//…`, `/v1/remux/` or + `/v1/torrent//stream` (a Stream's `playback.fallback` if present, else `playback.url` when relative). + ffmpeg reads it from this server over loopback, so upstream fetches keep the token + SSRF rules. + Absolute URLs or other paths → 400; a bad token signature → 403. + - `/v1/remux/…`: `start` and `audio` are passed to the remux (`?start=&audio=`). The remux starts at + the keyframe at/before `start`; that keyframe is looked up first and reported as `start`. + - `/v1/p/…`: ffmpeg input-seeks (`-ss` before `-i`); transcoding makes it frame accurate. + - `/v1/torrent//stream`: ffmpeg reads `/v1/torrent//raw` (range-served), seeking as above. +- Optional, clamped: `w` 32–640 (default 320), `h` 32–360 (180), both rounded to even; `fps` snapped to + the nearest MPEG-1 rate ≤ 30 (23.976, 24, 25, 29.97, 30; default 24); `vb` 64k–1500k (450k); + `ab` 32k–192k (96k), rounded down to an MP2 bitrate; `audio` = absolute ffprobe stream index. +- The source is probed first (≈1–8 s): a dead source fails here with 502 (403 for a blocked target). + `start` ≥ duration → 400. More than `cfg.rbx.maxSessions` sessions → 503 `{error, max}`. +- Reply: `{ id, segment, start, startExact, duration, width, height, fps, sampleRate: 44100, channels: 2, + videoBitrate, audioBitrate, audioTracks: [probe audio[]] }`. `start` is where segment 0 really begins + (source seconds); `startExact` is false only when a remux keyframe lookup failed and `start` is the + requested value. `duration` is the source duration or null. + +### `GET /v1/rbx//.ts` +Segment n (0-based), `video/mp2t`. Waits (up to 25 s) until ffmpeg has finished it. +- Header `X-Rbx-Pts`: the segment's first video frame in source seconds. The PES timestamps inside + the TS are source time too (`-output_ts_offset start`), so demuxed pts and `X-Rbx-Pts` agree. +- Each segment is independently decodable: PAT/PMT (after an SDT), then a sequence header + GOP header + + I-frame, then P-frames only (no B-frames), `segment × fps` frames; a closed GOP per segment. +- 204 once ffmpeg finished and n is past the last segment; 502 `{error}` if ffmpeg failed instead; + 504 if not ready after 25 s; 410 if n was discarded (more than 10 behind the highest n requested) or + the session closed meanwhile; 404 for an unknown session. +### `GET /v1/rbx//status` +`{ produced, ended, error, speed, paused, requested, start, duration, segment }` — `produced` = complete +segments, `speed` = media seconds encoded per wall second over the last ~1 s, `paused` = ffmpeg is +SIGSTOPped, `requested` = highest n requested (-1 = none). +### `GET /v1/rbx//close` +Kills ffmpeg and deletes the temp dir → `{ ok: true }` (404 if unknown). + +Lifecycle: any request to a session keeps it alive; after `idleSec` (60) without one it is closed. +ffmpeg encodes as fast as it can but is paused (SIGSTOP) once 30 segments are ready beyond the highest +requested n and resumed (SIGCONT) at 24. Seeking = open a new session with `start=` (close the old one). +Server exit (SIGINT/SIGTERM/SIGHUP/normal exit) kills every session and removes its dir; stale dirs +are cleared at boot. Config: `rbx: { enable: true, maxSessions: 4, segment: 2, idleSec: 60, tmpDir: "" }` +(`tmpDir` "" = `/bug-tv-rbx`). ffmpeg (`cfg.remux.ffmpeg`) needs the `mpeg1video` and `mp2` +encoders and the `segment` muxer (all in standard builds, including nixpkgs `ffmpeg-headless`). +A remux source also counts against `cfg.remux.maxProcs`. + ## Scrape internals (scrape workstream) - Worker pool (`worker_threads`), providers `require()`d once per worker at boot. - `global.SCRAPER_SETTINGS = cfg.providerSettings` in every worker. diff --git a/src/config.js b/src/config.js index 7ed11f3..9fe648d 100644 --- a/src/config.js +++ b/src/config.js @@ -21,6 +21,8 @@ const DEFAULTS = { secretFile: '', torrent: { enable: true, cacheDir: '', maxSizeGB: 20 }, remux: { enable: true, ffmpeg: 'ffmpeg', ffprobe: 'ffprobe' }, + // Roblox transcode sessions (/v1/rbx); tmpDir '' = /bug-tv-rbx + rbx: { enable: true, maxSessions: 4, segment: 2, idleSec: 60, tmpDir: '' }, filters: { minQuality: 'any', audioCodec: 'any', subtitles: 'any', subtitleLang: '' }, }; @@ -31,7 +33,7 @@ function readSecretFile(file) { function loadConfig() { const saved = fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {}; const cfg = { ...DEFAULTS, ...saved }; - for (const key of ['torrent', 'remux', 'filters']) cfg[key] = { ...DEFAULTS[key], ...(saved[key] || {}) }; + for (const key of ['torrent', 'remux', 'rbx', 'filters']) cfg[key] = { ...DEFAULTS[key], ...(saved[key] || {}) }; const env = process.env; if (env.BUG_TV_HOST) cfg.host = env.BUG_TV_HOST; @@ -47,6 +49,7 @@ function loadConfig() { // signs proxy/remux/subtitle tokens; random per boot unless pinned cfg.secret = cfg.secret || readSecretFile(cfg.secretFile) || env.BUG_TV_SECRET || crypto.randomBytes(32).toString('hex'); if (!cfg.torrent.cacheDir) cfg.torrent.cacheDir = path.join(require('os').tmpdir(), 'bug-tv-torrents'); + if (!cfg.rbx.tmpDir) cfg.rbx.tmpDir = path.join(require('os').tmpdir(), 'bug-tv-rbx'); return cfg; } diff --git a/src/http.js b/src/http.js index cfe8458..1e2c8c9 100644 --- a/src/http.js +++ b/src/http.js @@ -2,7 +2,7 @@ const zlib = require('zlib'); const CORS = { 'Access-Control-Allow-Origin': '*', - 'Access-Control-Expose-Headers': 'Content-Length, Content-Range, Accept-Ranges, X-Bug-Tv-Offset', + 'Access-Control-Expose-Headers': 'Content-Length, Content-Range, Accept-Ranges, X-Bug-Tv-Offset, X-Rbx-Pts', }; // compress text bodies only; media is already compressed diff --git a/src/media/rbx.js b/src/media/rbx.js new file mode 100644 index 0000000..f40f243 --- /dev/null +++ b/src/media/rbx.js @@ -0,0 +1,484 @@ +// 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 }; diff --git a/src/media/stats.js b/src/media/stats.js index 9232488..52e66ae 100644 --- a/src/media/stats.js +++ b/src/media/stats.js @@ -3,9 +3,10 @@ const { proxyStats } = require('./proxy'); const { remuxStats } = require('./remux'); const { subsStats } = require('./subs'); const { torrentStats } = require('./torrent'); +const { rbxStats } = require('./rbx'); function mediaStats() { - return { proxy: proxyStats(), remux: remuxStats(), subs: subsStats(), torrent: torrentStats() }; + return { proxy: proxyStats(), remux: remuxStats(), subs: subsStats(), torrent: torrentStats(), rbx: rbxStats() }; } module.exports = { mediaStats }; diff --git a/src/routes/openapi.js b/src/routes/openapi.js index fd8be9b..ac6d6c2 100644 --- a/src/routes/openapi.js +++ b/src/routes/openapi.js @@ -37,6 +37,33 @@ const spec = { '/v1/torrent/{token}/stream': { get: { tags: ['media'], summary: 'Stream a torrent file (range or remux)', parameters: [p('token', 'signed token'), q('start', 'start offset seconds (remux)', { type: 'number' })], responses: ok('media', 'video/mp4') } }, '/v1/torrent/{token}/status': { get: { tags: ['media'], summary: 'Torrent readiness, peers, speed', parameters: [p('token', 'signed token')], responses: ok('status') } }, '/v1/torrent/{token}/files': { get: { tags: ['media'], summary: 'Files in the torrent', parameters: [p('token', 'signed token')], responses: ok('files') } }, + '/v1/rbx/open': { + get: { + tags: ['roblox'], + summary: 'Open a Roblox transcode session (MPEG-TS segments: mpeg1video + mp2)', + parameters: [ + q('src', 'API-relative playback path: /v1/p/…, /v1/remux/… or /v1/torrent/…/stream (absolute URLs are rejected)', { type: 'string' }, true), + q('start', 'start offset seconds', { type: 'number' }), + q('w', 'width (≤ 640, default 320)', { type: 'integer' }), + q('h', 'height (≤ 360, default 180)', { type: 'integer' }), + q('fps', 'frame rate, snapped to 23.976/24/25/29.97/30 (default 24)', { type: 'number' }), + q('vb', 'video bitrate, e.g. 450k (64k–1500k)'), + q('ab', 'audio bitrate, e.g. 96k (32k–192k)'), + q('audio', 'audio track (absolute ffprobe stream index)', { type: 'integer' }), + ], + responses: { ...ok('{ id, segment, start, startExact, duration, width, height, fps, sampleRate, channels, videoBitrate, audioBitrate, audioTracks }'), 400: { description: 'bad src/params' }, 403: { description: 'invalid token' }, 502: { description: 'source probe failed' }, 503: { description: 'session cap reached' } }, + }, + }, + '/v1/rbx/{id}/{n}.ts': { + get: { + tags: ['roblox'], + summary: 'Segment n (0-based); waits up to 25 s for it. X-Rbx-Pts = first frame time (source seconds)', + parameters: [p('id', 'session id'), p('n', 'segment number')], + responses: { ...ok('MPEG-TS', 'video/mp2t'), 204: { description: 'past the last segment' }, 404: { description: 'no such session' }, 410: { description: 'segment discarded (too far behind) or session closed' }, 502: { description: 'ffmpeg failed' }, 504: { description: 'not ready after 25 s' } }, + }, + }, + '/v1/rbx/{id}/status': { get: { tags: ['roblox'], summary: '{ produced, ended, error, speed, paused, requested, start, duration, segment }', parameters: [p('id', 'session id')], responses: ok('status') } }, + '/v1/rbx/{id}/close': { get: { tags: ['roblox'], summary: 'Kill the session and delete its segments', parameters: [p('id', 'session id')], responses: ok('{ ok: true }') } }, '/v1/subs/{token}': { get: { tags: ['media'], summary: 'Subtitle converted to WebVTT', parameters: [p('token', 'signed token')], responses: ok('vtt', 'text/vtt') } }, }, }; diff --git a/src/routes/rbx.js b/src/routes/rbx.js new file mode 100644 index 0000000..b068711 --- /dev/null +++ b/src/routes/rbx.js @@ -0,0 +1,43 @@ +const { error } = require('../http'); +const rbx = require('../media/rbx'); +const net = require('../media/net'); +const remux = require('../media/remux'); + +let enabled = true; + +function gate(req, res) { + if (enabled) return true; + error(req, res, 501, 'roblox transcode disabled'); + return false; +} + +module.exports = { + init(cfg) { + enabled = cfg.rbx?.enable !== false; + net.init(cfg); + remux.init(cfg); + if (enabled) rbx.init(cfg); + }, + routes: [ + { + method: 'GET', + path: '/v1/rbx/open', + handler: (req, res, ctx) => gate(req, res) && rbx.open(req, res, ctx.url.searchParams), + }, + { + method: 'GET', + path: /^\/v1\/rbx\/([\w-]+)\/(\d{1,6})\.ts$/, + handler: (req, res, ctx) => gate(req, res) && rbx.segment(req, res, ctx.params[0], Number(ctx.params[1])), + }, + { + method: 'GET', + path: /^\/v1\/rbx\/([\w-]+)\/status$/, + handler: (req, res, ctx) => gate(req, res) && rbx.status(req, res, ctx.params[0]), + }, + { + method: 'GET', + path: /^\/v1\/rbx\/([\w-]+)\/close$/, + handler: (req, res, ctx) => gate(req, res) && rbx.close(req, res, ctx.params[0]), + }, + ], +}; diff --git a/src/server.js b/src/server.js index 9be0c3e..1f30936 100644 --- a/src/server.js +++ b/src/server.js @@ -11,7 +11,7 @@ sign.init(cfg.secret); // Each routes module exports { routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }. // `path` is a string (exact) or a RegExp whose groups become ctx.params. -const MODULES = ['health', 'providers', 'streams', 'proxy', 'torrent', 'remux', 'subs', 'openapi']; +const MODULES = ['health', 'providers', 'streams', 'proxy', 'torrent', 'remux', 'subs', 'rbx', 'openapi']; const routes = []; for (const name of MODULES) { diff --git a/test/rbx.test.js b/test/rbx.test.js new file mode 100644 index 0000000..44ee864 --- /dev/null +++ b/test/rbx.test.js @@ -0,0 +1,263 @@ +// node --test test/ — /v1/rbx transcode sessions against a real server + ffmpeg. +// Input: a generated 90 s testsrc + sine mp4 served by a local range server +// (allowPrivateTargets), reached through the API's own proxy / remux tokens. +const { test, before, after } = require('node:test'); +const assert = require('node:assert/strict'); +const { spawn, execFileSync } = require('child_process'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const http = require('http'); +const sign = require('../src/sign'); + +const SECRET = 'rbx-test-secret'; +const LEN = 90; // seconds of input +let tmp, fileSrv, server, base, rbxDir; + +function freePort() { + return new Promise((resolve) => { + const s = http.createServer().listen(0, '127.0.0.1', () => { + const { port } = s.address(); + s.close(() => resolve(port)); + }); + }); +} + +// minimal static server with Range support +function rangeServer(file) { + const size = fs.statSync(file).size; + return http.createServer((req, res) => { + const m = String(req.headers.range || '').match(/bytes=(\d+)-(\d*)/); + const start = m ? Number(m[1]) : 0; + const end = m && m[2] ? Number(m[2]) : size - 1; + if (start >= size) return res.writeHead(416, { 'Content-Range': `bytes */${size}` }).end(); + res.writeHead(m ? 206 : 200, { + 'Content-Type': 'video/mp4', + 'Accept-Ranges': 'bytes', + 'Content-Length': end - start + 1, + ...(m ? { 'Content-Range': `bytes ${start}-${end}/${size}` } : {}), + }); + if (req.method === 'HEAD') return res.end(); + fs.createReadStream(file, { start, end }).pipe(res); + }); +} + +async function get(p) { + const r = await fetch(base + p); + const buf = Buffer.from(await r.arrayBuffer()); + let body = null; + try { + body = JSON.parse(buf.toString('utf8')); + } catch {} + return { status: r.status, headers: r.headers, buf, body }; +} + +const pSrc = () => `/v1/p/${sign.sign({ o: `http://127.0.0.1:${fileSrv.address().port}`, h: {} })}/in.mp4`; +const remuxSrc = () => `/v1/remux/${sign.sign({ u: `http://127.0.0.1:${fileSrv.address().port}/in.mp4`, h: {} })}`; +const open = (src, extra = '') => get(`/v1/rbx/open?src=${encodeURIComponent(src)}${extra}`); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +function ffmpegRunning(dir) { + for (const pid of fs.readdirSync('/proc')) { + if (!/^\d+$/.test(pid)) continue; + try { + if (fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').includes(dir)) return true; + } catch {} + } + return false; +} + +function pictTypes(buf) { + const f = path.join(tmp, `probe-${Math.random()}.ts`); + fs.writeFileSync(f, buf); + const out = execFileSync('ffprobe', ['-v', 'error', '-select_streams', 'v', '-show_entries', 'frame=pict_type', '-of', 'csv=p=0', f], { encoding: 'utf8' }); + fs.rmSync(f); + return out.replace(/[^A-Z]/g, ''); +} + +function firstPts(buf, type) { + const f = path.join(tmp, `probe-${Math.random()}.ts`); + fs.writeFileSync(f, buf); + const out = execFileSync('ffprobe', ['-v', 'error', '-select_streams', type, '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', f], { encoding: 'utf8' }); + fs.rmSync(f); + return parseFloat(out.trim().split('\n')[0]); +} + +before(async () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bug-tv-rbx-test-')); + const input = path.join(tmp, 'in.mp4'); + // keyframe every 1 s (so the remux seek lands on a whole second) + execFileSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', `testsrc=size=640x360:rate=30:duration=${LEN}`, + '-f', 'lavfi', '-i', `sine=frequency=440:sample_rate=48000:duration=${LEN}`, '-c:v', 'libx264', '-preset', 'ultrafast', '-g', '30', + '-c:a', 'aac', '-shortest', '-movflags', '+faststart', '-y', input]); + fileSrv = rangeServer(input); + await new Promise((r) => fileSrv.listen(0, '127.0.0.1', r)); + + const port = await freePort(); + base = `http://127.0.0.1:${port}`; + rbxDir = path.join(tmp, 'rbx'); + fs.mkdirSync(path.join(tmp, 'providers')); + fs.writeFileSync(path.join(tmp, 'config.json'), JSON.stringify({ + tmdbKey: 'test', host: '127.0.0.1', port, secret: SECRET, allowPrivateTargets: true, workers: 1, + providersDir: path.join(tmp, 'providers'), + rbx: { maxSessions: 2, idleSec: 3, tmpDir: rbxDir }, + })); + sign.init(SECRET); + server = spawn(process.execPath, [path.join(__dirname, '..', 'src', 'server.js')], { + env: { ...process.env, BUG_TV_CONFIG: path.join(tmp, 'config.json'), BUG_TV_CACHE_DIR: path.join(tmp, 'cache') }, + stdio: ['ignore', 'pipe', 'ignore'], + }); + await new Promise((resolve, reject) => { + server.stdout.on('data', (c) => String(c).includes('bug.tv api') && resolve()); + server.on('exit', (c) => reject(new Error(`server exited ${c}`))); + }); +}); + +after(async () => { + server?.kill('SIGTERM'); + await new Promise((r) => (server.exitCode !== null ? r() : server.on('exit', r))); + fileSrv?.close(); + // SIGTERM must have cleaned up every session dir + assert.deepEqual(fs.existsSync(rbxDir) ? fs.readdirSync(rbxDir) : [], []); + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +test('rejects absolute, foreign and badly signed src', async () => { + for (const src of ['http://127.0.0.1:1/x.mp4', '//evil.example/v1/p/x/y', '/healthz', '/v1/p/../../healthz', 'https://api-tv.bug.tools/v1/p/a/b']) { + const r = await open(src); + assert.equal(r.status, 400, src); + } + assert.equal((await open('/v1/remux/forged.token')).status, 403); + assert.equal((await get('/v1/rbx/open')).status, 400); +}); + +test('open → all segments are independent MPEG-TS with mpeg1video + mp2, then 204', async () => { + const o = await open(pSrc(), '&w=320&h=180&fps=24&vb=450k&ab=96k'); + assert.equal(o.status, 200, JSON.stringify(o.body)); + const b = o.body; + assert.equal(typeof b.id, 'string'); + assert.equal(b.segment, 2); + assert.equal(b.start, 0); + assert.ok(Math.abs(b.duration - LEN) < 0.5, `duration ${b.duration}`); + assert.deepEqual([b.width, b.height, b.fps, b.sampleRate, b.channels], [320, 180, 24, 44100, 2]); + let n = 0; + let lastPts = -1; + for (;; n++) { + const r = await get(`/v1/rbx/${b.id}/${n}.ts`); + if (r.status === 204) break; + assert.equal(r.status, 200, `segment ${n}: ${r.buf}`); + assert.equal(r.headers.get('content-type'), 'video/mp2t'); + const { buf } = r; + assert.equal(buf.length % 188, 0); + for (let i = 0; i < buf.length; i += 188) assert.equal(buf[i], 0x47, `sync byte at ${i}`); + // PAT (pid 0) and PMT come before the first PES packet (ffmpeg puts its SDT first) + const pids = []; + for (let i = 0; i < buf.length && !(buf[i + 1] & 0x40 && buf.readUInt32BE(i + 4) >>> 8 === 1); i += 188) pids.push(buf.readUInt16BE(i + 1) & 0x1fff); + assert.ok(pids.includes(0) && pids.includes(0x1000), `pids before first PES: ${pids}`); + assert.ok(buf.indexOf(Buffer.from([0, 0, 1, 0xb3])) > 0, 'sequence header'); + assert.ok(buf.indexOf(Buffer.from([0, 0, 1, 0xb8])) > 0, 'GOP header'); + assert.ok(buf.indexOf(Buffer.from([0, 0, 1, 0xc0])) > 0, 'mp2 PES'); + const pts = Number(r.headers.get('x-rbx-pts')); + assert.ok(pts > lastPts, `pts ${pts} after ${lastPts}`); + assert.ok(Math.abs(firstPts(buf, 'v') - pts) < 0.05, 'X-Rbx-Pts = first video pts'); + if (n > 0) assert.ok(Math.abs(pts - n * 2) < 0.1, `segment ${n} pts ${pts}`); + if (n % 7 === 1) { + const types = pictTypes(buf); // decodable on its own: I first, then P only (no B-frames) + assert.match(types, /^IP+$/, `segment ${n} frames ${types}`); + assert.ok(Math.abs(types.length - 48) <= 1, `segment ${n} has ${types.length} frames`); + } + lastPts = pts; + } + assert.ok(n >= LEN / 2 - 1 && n <= LEN / 2 + 1, `${n} segments`); + assert.equal((await get(`/v1/rbx/${b.id}/${n + 3}.ts`)).status, 204); + const st = (await get(`/v1/rbx/${b.id}/status`)).body; + assert.equal(st.ended, true); + assert.equal(st.error, null); + assert.equal(st.produced, n); + assert.ok(st.speed > 1, `speed ${st.speed}`); + // segments far behind the highest request were discarded + assert.equal((await get(`/v1/rbx/${b.id}/0.ts`)).status, 410); + assert.equal((await get(`/v1/rbx/${b.id}/close`)).status, 200); + assert.equal(fs.existsSync(path.join(rbxDir, `s-${b.id}`)), false); +}); + +test('start offset is honoured (input seek, frame accurate)', async () => { + const o = await open(pSrc(), '&start=40.5'); + assert.equal(o.status, 200, JSON.stringify(o.body)); + assert.equal(o.body.start, 40.5); + const s0 = await get(`/v1/rbx/${o.body.id}/0.ts`); + assert.equal(s0.status, 200); + assert.equal(Number(s0.headers.get('x-rbx-pts')), 40.5); + assert.ok(Math.abs(firstPts(s0.buf, 'v') - 40.5) < 0.05); + const s1 = await get(`/v1/rbx/${o.body.id}/1.ts`); + assert.ok(Math.abs(Number(s1.headers.get('x-rbx-pts')) - 42.5) < 0.1); + await get(`/v1/rbx/${o.body.id}/close`); + assert.equal((await open(pSrc(), `&start=${LEN + 5}`)).status, 400); +}); + +test('remux source: start goes to the remux, reported start = its keyframe', async () => { + const o = await open(remuxSrc(), '&start=30.4&audio=1'); + assert.equal(o.status, 200, JSON.stringify(o.body)); + assert.equal(o.body.start, 30); // keyframes every 1 s + assert.equal(o.body.audioTracks.length, 1); + const s0 = await get(`/v1/rbx/${o.body.id}/0.ts`); + assert.equal(s0.status, 200); + assert.equal(Number(s0.headers.get('x-rbx-pts')), 30); + assert.ok(Math.abs(firstPts(s0.buf, 'v') - 30) < 0.05); + assert.ok(s0.buf.indexOf(Buffer.from([0, 0, 1, 0xc0])) > 0, 'mp2 PES'); + await get(`/v1/rbx/${o.body.id}/close`); +}); + +test('close kills ffmpeg and removes the temp dir; session cap → 503', async () => { + const a = (await open(pSrc())).body; + const b = (await open(pSrc())).body; + const dir = path.join(rbxDir, `s-${a.id}`); + assert.ok(ffmpegRunning(dir) || fs.existsSync(dir)); + const c = await open(pSrc()); + assert.equal(c.status, 503); + assert.equal((await get(`/v1/rbx/${a.id}/close`)).status, 200); + await sleep(500); + assert.equal(ffmpegRunning(dir), false); + assert.equal(fs.existsSync(dir), false); + assert.equal((await get(`/v1/rbx/${a.id}/status`)).status, 404); + assert.equal((await get(`/v1/rbx/${a.id}/0.ts`)).status, 404); + assert.equal((await get(`/v1/rbx/${b.id}/close`)).status, 200); + assert.equal((await get(`/v1/rbx/${b.id}/close`)).status, 404); +}); + +test('ffmpeg pauses ~30 segments ahead of the highest request, resumes when asked', async () => { + const o = (await open(pSrc(), '&w=160&h=90')).body; + let st; + for (let i = 0; i < 40; i++) { + st = (await get(`/v1/rbx/${o.id}/status`)).body; + if (st.paused) break; + await sleep(250); + } + assert.equal(st.paused, true); + assert.ok(st.produced >= 31 && st.produced <= 36, `produced ${st.produced}`); + await sleep(1000); + assert.equal((await get(`/v1/rbx/${o.id}/status`)).body.produced, st.produced); + await get(`/v1/rbx/${o.id}/20.ts`); + for (let i = 0; i < 40; i++) { + st = (await get(`/v1/rbx/${o.id}/status`)).body; + if (st.ended) break; + await sleep(250); + } + assert.equal(st.ended, true); + await get(`/v1/rbx/${o.id}/close`); +}); + +test('idle sessions are killed', async () => { + const o = (await open(pSrc())).body; + const dir = path.join(rbxDir, `s-${o.id}`); + await sleep(6500); // idleSec 3 + sweep every 2 s + assert.equal((await get(`/v1/rbx/${o.id}/status`)).status, 404); + assert.equal(ffmpegRunning(dir), false); + assert.equal(fs.existsSync(dir), false); +}); + +test('a live session is cleaned up when the server exits', async () => { + const o = (await open(pSrc())).body; + assert.ok(o.id); + // after() sends SIGTERM and asserts the rbx dir is empty +});