264 lines
11 KiB
JavaScript
264 lines
11 KiB
JavaScript
// node --test test/rbx.test.js — /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
|
|
});
|