Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34ef0d23cf | ||
|
|
68d4924a77 | ||
|
|
ee0e36d2c7 | ||
|
|
5ab3683f44 |
No files matched your search
+87
-1
@@ -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`)
|
## Server wiring (already written — `src/server.js`)
|
||||||
- Each `src/routes/<name>.js` exports `{ routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }`.
|
- Each `src/routes/<name>.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).
|
`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),
|
- 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.
|
`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 `/`).
|
- `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),
|
{ host, port, tmdbKey, enabledProviders: [..] ([] = all), disabledProviders: [..] (default ["torrentio"]), providerSettings: {..} (→ global.SCRAPER_SETTINGS),
|
||||||
timeoutMs, workers (0 = auto, min(cpus,4)), cacheTtlSec, secret,
|
timeoutMs, workers (0 = auto, min(cpus,4)), cacheTtlSec, secret,
|
||||||
torrent: { enable, cacheDir, maxSizeGB }, remux: { enable, ffmpeg, ffprobe },
|
torrent: { enable, cacheDir, maxSizeGB }, remux: { enable, ffmpeg, ffprobe },
|
||||||
|
rbx: { enable, maxSessions, segment, idleSec, tmpDir },
|
||||||
filters: { minQuality, audioCodec, subtitles, subtitleLang } }
|
filters: { minQuality, audioCodec, subtitles, subtitleLang } }
|
||||||
```
|
```
|
||||||
Config file path: `$BUG_TV_CONFIG` or `./config.json`.
|
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 /healthz` → `{ ok: true }`
|
||||||
### `GET /` Swagger UI, `GET /api.json` OpenAPI spec (`src/routes/openapi.js`).
|
### `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/rbx.test.js` (needs ffmpeg/ffprobe on PATH).
|
||||||
|
|
||||||
|
### `GET /v1/rbx/open?src=&start=&w=&h=&fps=&vb=&ab=&audio=`
|
||||||
|
- `src` (required): an API-relative playback path — `/v1/p/<token>/…`, `/v1/remux/<token>` or
|
||||||
|
`/v1/torrent/<token>/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/<token>/stream`: ffmpeg reads `/v1/torrent/<token>/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/<id>/<n>.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/<id>/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/<id>/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` "" = `<os tmp>/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)
|
## Scrape internals (scrape workstream)
|
||||||
- Worker pool (`worker_threads`), providers `require()`d once per worker at boot.
|
- Worker pool (`worker_threads`), providers `require()`d once per worker at boot.
|
||||||
- `global.SCRAPER_SETTINGS = cfg.providerSettings` in every worker.
|
- `global.SCRAPER_SETTINGS = cfg.providerSettings` in every worker.
|
||||||
@@ -221,3 +272,38 @@ Player workstream owns `web/js/api.js` (bug-tv server client: `streams(params, {
|
|||||||
- `/v1/remux/<token>/probe?start=<sec>` and `/v1/torrent/<token>/probe?start=<sec>` add `keyframe`: the time the remux really starts at. The player uses it as its clock offset because a `<video>` element can't read `X-Bug-Tv-Offset`.
|
- `/v1/remux/<token>/probe?start=<sec>` and `/v1/torrent/<token>/probe?start=<sec>` add `keyframe`: the time the remux really starts at. The player uses it as its clock offset because a `<video>` element can't read `X-Bug-Tv-Offset`.
|
||||||
- Extensionless stream URLs are sniffed by their first 1 KB (`src/media/sniff.js`) and typed m3u8/mp4/webm/mkv before `playbackFor` runs.
|
- Extensionless stream URLs are sniffed by their first 1 KB (`src/media/sniff.js`) and typed m3u8/mp4/webm/mkv before `playbackFor` runs.
|
||||||
- The Swagger UI moved to `src/public/index.html`, `mod/` and `rest/` are removed, and webtorrent is bumped to ^3.0.21.
|
- The Swagger UI moved to `src/public/index.html`, `mod/` and `rest/` are removed, and webtorrent is bumped to ^3.0.21.
|
||||||
|
|
||||||
|
## Party (watch-together hooks)
|
||||||
|
`web/js/party.js` is inert unless a transport attaches, so the public site is unaffected. tv-discord's Activity overlay is the transport.
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { party } from './party.js'; // also exposed as window.bugtvParty (dispatches 'bugtv:party-ready')
|
||||||
|
party.mode // 'solo' | 'host' | 'viewer'
|
||||||
|
party.attach(transport) // transport = { send(type, data) }; the transport then calls:
|
||||||
|
party.receive(msg) // feed server messages: welcome / host / members / route / play / pong
|
||||||
|
party.now() // server-synced ms (falls back to Date.now())
|
||||||
|
party.publish(type, data) // host only: 'route' {path} | 'play' {snapshot}
|
||||||
|
party.on(type, fn) → off // 'mode' | 'members' | 'route' | 'play'
|
||||||
|
```
|
||||||
|
- **Router:** in host mode, every route change publishes `route`. In viewer mode, an incoming `route` calls `navigate(path, {replace:true})`.
|
||||||
|
- **Watch view, host:** publishes a `play` snapshot on load/source/subtitle/quality/audio/episode change, play/pause/seeked/ended, and every 2s while on the watch route. The snapshot shape is in tv-discord `docs/protocol.md`.
|
||||||
|
- **Watch view, viewer:**
|
||||||
|
- Never scrapes. It loads `snapshot.stream` directly through `playStream` and follows the clock: over 1.5s drift it seeks, and at 0.3–1.5s it sets `playbackRate` to 0.95/1.05.
|
||||||
|
- It applies the subtitle (by lang+label, index as fallback), the quality and the audio track.
|
||||||
|
- It hides every control except volume, mute and fullscreen.
|
||||||
|
- **Player:** `createPlayer(video, { forceProxy })`, or `<meta name="bug-tv-force-proxy" content="1">`, always plays `playback.fallback` when present. This is needed because the Activity CSP only allows mapped origins.
|
||||||
|
- **TMDB bases:** `<meta name="bug-tv-tmdb">` (API base) and `<meta name="bug-tv-img">` (image base) override `https://api.themoviedb.org/3` and `https://image.tmdb.org/t/p/`. In the Activity they are `/tmdb/3` and `/img/t/p/`.
|
||||||
|
- **Party mode** (`party.mode !== 'solo'`) hides the trailer button, because the YouTube iframe can't be mapped.
|
||||||
|
|
||||||
|
### Deviations / details (party layer)
|
||||||
|
- **Wire shape:** party calls `transport.send(type, data)` with `('route', {path})`, `('play', {snapshot})` (`{snapshot: null}` when the host leaves the watch page) and `('ping', {at})`; the transport sends `{t: type, ...data}`. party pings by itself (5× at 1s, then every 15s) and takes the median of the last 5 pong offsets; `welcome.now` seeds the offset before the first pong.
|
||||||
|
- **Extra API:** `party.resend()` (host: re-publish current route + snapshot, for the overlay after a reconnect; emits `'resend'`), `party.lastRoute` / `party.lastPlay`, `party.hostName()`, `attach()` returns a detach function. `on('error')` relays server errors. A `welcome.play` whose path differs from `welcome.route` is ignored.
|
||||||
|
- **Route privacy:** host route messages drop session params (`api`, `frame_id`, `instance_id`, `platform`, `guild_id`, `channel_id`, …); viewers keep their own.
|
||||||
|
- **Viewer UI:** controls other than volume/mute/fullscreen/PiP get `.pl-host-only` and are hidden under `.pl.is-viewer`; the seek bar stays visible but inert. Those controls and the autoplay fallback button `.pl-join` ("Click to join", local playback only) carry `data-party-allow` for the overlay's input blocking. Viewers never auto-advance to the next episode; a viewer-side source failure shows "Waiting for <host>…" and the next heartbeat reloads the host's stream.
|
||||||
|
- **Drift:** paused snapshots seek when |drift| > 0.5s; hls/file seeks are rate-limited to 1 per 1.5s, remux to 1 per 3s; a viewer stuck seeking/buffering for 5s (12s remux) is re-seeked. Playback speed is not mirrored.
|
||||||
|
- **Quality:** `snapshot.quality` is the host's explicit menu pick (`chooseLevel`), reset to auto on source change, not hls.js's momentary level.
|
||||||
|
- **Watch handle:** `views/watch.js` exports `active()` → `{player, state, snapshot(), playStream, switchTo, switchEpisode, chooseSub, chooseLevel, role}` for tooling/tests.
|
||||||
|
- **Player:** `player.original` is the Stream passed to `load()`; `player.stream` is the proxied copy under forceProxy. `proxiedStream(s)` is exported.
|
||||||
|
- **API base:** a relative `bug-tv-api` / `?api=` / stored base such as `/tv` resolves against `location.origin` (it used to become `https://tv`).
|
||||||
|
- **Trailer:** hidden by CSS (`html.party-host|party-viewer .js-trailer`), and `trailerModal()` is a no-op outside solo.
|
||||||
|
- **Tests:** `node --test web/test/party.test.mjs`.
|
||||||
@@ -25,6 +25,7 @@ stdenvNoCC.mkDerivation {
|
|||||||
|
|
||||||
cp -r . $out
|
cp -r . $out
|
||||||
chmod -R u+w $out
|
chmod -R u+w $out
|
||||||
|
rm -rf $out/test # node tests for the party layer, not part of the site
|
||||||
# no-op on pages without the tag
|
# no-op on pages without the tag
|
||||||
for page in $out/*.html; do
|
for page in $out/*.html; do
|
||||||
sed -i -E ${lib.escapeShellArg sedExpr} "$page"
|
sed -i -E ${lib.escapeShellArg sedExpr} "$page"
|
||||||
|
|||||||
+4
-1
@@ -21,6 +21,8 @@ const DEFAULTS = {
|
|||||||
secretFile: '',
|
secretFile: '',
|
||||||
torrent: { enable: true, cacheDir: '', maxSizeGB: 20 },
|
torrent: { enable: true, cacheDir: '', maxSizeGB: 20 },
|
||||||
remux: { enable: true, ffmpeg: 'ffmpeg', ffprobe: 'ffprobe' },
|
remux: { enable: true, ffmpeg: 'ffmpeg', ffprobe: 'ffprobe' },
|
||||||
|
// Roblox transcode sessions (/v1/rbx); tmpDir '' = <os tmp>/bug-tv-rbx
|
||||||
|
rbx: { enable: true, maxSessions: 4, segment: 2, idleSec: 60, tmpDir: '' },
|
||||||
filters: { minQuality: 'any', audioCodec: 'any', subtitles: 'any', subtitleLang: '' },
|
filters: { minQuality: 'any', audioCodec: 'any', subtitles: 'any', subtitleLang: '' },
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -31,7 +33,7 @@ function readSecretFile(file) {
|
|||||||
function loadConfig() {
|
function loadConfig() {
|
||||||
const saved = fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {};
|
const saved = fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {};
|
||||||
const cfg = { ...DEFAULTS, ...saved };
|
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;
|
const env = process.env;
|
||||||
if (env.BUG_TV_HOST) cfg.host = env.BUG_TV_HOST;
|
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
|
// 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');
|
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.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;
|
return cfg;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@ const zlib = require('zlib');
|
|||||||
|
|
||||||
const CORS = {
|
const CORS = {
|
||||||
'Access-Control-Allow-Origin': '*',
|
'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
|
// compress text bodies only; media is already compressed
|
||||||
|
|||||||
@@ -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 };
|
||||||
+2
-1
@@ -3,9 +3,10 @@ const { proxyStats } = require('./proxy');
|
|||||||
const { remuxStats } = require('./remux');
|
const { remuxStats } = require('./remux');
|
||||||
const { subsStats } = require('./subs');
|
const { subsStats } = require('./subs');
|
||||||
const { torrentStats } = require('./torrent');
|
const { torrentStats } = require('./torrent');
|
||||||
|
const { rbxStats } = require('./rbx');
|
||||||
|
|
||||||
function mediaStats() {
|
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 };
|
module.exports = { mediaStats };
|
||||||
@@ -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}/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}/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/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') } },
|
'/v1/subs/{token}': { get: { tags: ['media'], summary: 'Subtitle converted to WebVTT', parameters: [p('token', 'signed token')], responses: ok('vtt', 'text/vtt') } },
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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]),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
+1
-1
@@ -11,7 +11,7 @@ sign.init(cfg.secret);
|
|||||||
|
|
||||||
// Each routes module exports { routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }.
|
// 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.
|
// `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 = [];
|
const routes = [];
|
||||||
for (const name of MODULES) {
|
for (const name of MODULES) {
|
||||||
|
|||||||
@@ -0,0 +1,263 @@
|
|||||||
|
// 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
|
||||||
|
});
|
||||||
@@ -196,3 +196,9 @@
|
|||||||
.provider-grid { grid-template-columns: 1fr; }
|
.provider-grid { grid-template-columns: 1fr; }
|
||||||
.input--sm { max-width: none; flex: 1; }
|
.input--sm { max-width: none; flex: 1; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* watch party: the YouTube trailer iframe can't be mapped inside the Discord Activity */
|
||||||
|
html.party-host .js-trailer,
|
||||||
|
html.party-viewer .js-trailer {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
@@ -1290,3 +1290,45 @@ html.pl-open body {
|
|||||||
from { transform: scaleX(0); }
|
from { transform: scaleX(0); }
|
||||||
to { transform: scaleX(1); }
|
to { transform: scaleX(1); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- watch party: viewer mode (party.js) ---------------------------------------------- */
|
||||||
|
/* Viewers follow the host: only volume, mute, fullscreen and PiP stay usable. */
|
||||||
|
|
||||||
|
.pl.is-viewer .pl-host-only,
|
||||||
|
.pl.is-viewer .pl-load__count,
|
||||||
|
.pl.is-viewer .pl-load__bar,
|
||||||
|
.pl.is-viewer .pl-load__ticker {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
.pl.is-viewer .pl-seek {
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.pl.is-viewer .pl-seek__thumb,
|
||||||
|
.pl.is-viewer .pl-seek__tip,
|
||||||
|
.pl.is-viewer .pl-seek__hover {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.pl-join {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 14px 26px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--pl-accent);
|
||||||
|
color: #000;
|
||||||
|
font: inherit;
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
pointer-events: auto;
|
||||||
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.45);
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
.pl-join[hidden] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.pl-join .pl-ico {
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@
|
|||||||
*/
|
*/
|
||||||
import { h, debounce } from './util.js';
|
import { h, debounce } from './util.js';
|
||||||
import { getBase } from './config.js';
|
import { getBase } from './config.js';
|
||||||
|
import './party.js'; // window.bugtvParty for the watch-party overlay
|
||||||
import { start, navigate, href, onChange, current } from './router.js';
|
import { start, navigate, href, onChange, current } from './router.js';
|
||||||
import { toast } from './ui/toast.js';
|
import { toast } from './ui/toast.js';
|
||||||
import { icon } from './ui/icons.js';
|
import { icon } from './ui/icons.js';
|
||||||
|
|||||||
@@ -24,6 +24,11 @@ export const TMDB_KEY_STORAGE_KEY = 'bug-tv.tmdbKey.v1';
|
|||||||
function normalize(value) {
|
function normalize(value) {
|
||||||
let v = String(value || '').trim();
|
let v = String(value || '').trim();
|
||||||
if (!v) return '';
|
if (!v) return '';
|
||||||
|
// "/tv" (Discord Activity URL mapping): same-origin path
|
||||||
|
if (v.startsWith('/') && !v.startsWith('//')) {
|
||||||
|
const origin = typeof location !== 'undefined' && /^https?:$/.test(location.protocol) ? location.origin : '';
|
||||||
|
return (origin + v).replace(/\/+$/, '');
|
||||||
|
}
|
||||||
if (!/^https?:\/\//i.test(v)) v = `${/^(localhost|127\.|\[::1\])/.test(v) ? 'http' : 'https'}://${v}`;
|
if (!/^https?:\/\//i.test(v)) v = `${/^(localhost|127\.|\[::1\])/.test(v) ? 'http' : 'https'}://${v}`;
|
||||||
return v.replace(/\/+$/, '');
|
return v.replace(/\/+$/, '');
|
||||||
}
|
}
|
||||||
|
|||||||
+203
@@ -0,0 +1,203 @@
|
|||||||
|
/*
|
||||||
|
party.js — watch-together hooks (docs/api.md "Party"). Inert ('solo') until a
|
||||||
|
transport attaches and the server says who is host; the public site never
|
||||||
|
attaches one.
|
||||||
|
|
||||||
|
import { party } from './party.js' also window.bugtvParty, plus a
|
||||||
|
'bugtv:party-ready' window event
|
||||||
|
|
||||||
|
party.mode 'solo' | 'host' | 'viewer'
|
||||||
|
party.me / host user ids (from welcome / host messages)
|
||||||
|
party.members [{id, username, avatar}]
|
||||||
|
party.attach(transport) transport = { send(type, data) } → detach()
|
||||||
|
party sends: 'route' {path}, 'play' {snapshot}, 'ping' {at}
|
||||||
|
(the transport puts them on the wire as {t: type, ...data})
|
||||||
|
party.receive(msg) server messages {t: 'welcome'|'host'|'members'|'route'|'play'|'pong'|'error', …}
|
||||||
|
party.now() server-synced ms (Date.now() until a pong/welcome arrives)
|
||||||
|
party.publish(type, data) host only; no-op otherwise ('play' {snapshot: null} = left the watch page)
|
||||||
|
party.resend() host only: re-publish current route + snapshot (after a reconnect)
|
||||||
|
party.on(type, fn) → off 'mode' | 'members' | 'route' | 'play' | 'error' | 'resend'
|
||||||
|
party.lastRoute / lastPlay last relayed route path / snapshot (for late subscribers)
|
||||||
|
party.hostName() host's username ('' if unknown)
|
||||||
|
|
||||||
|
Pings: on attach party sends a few pings (1s apart), then one every 15s, and
|
||||||
|
takes the median of the last 5 offsets.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const listeners = new Map();
|
||||||
|
const offsets = [];
|
||||||
|
let offset = 0;
|
||||||
|
let pingTimer = null;
|
||||||
|
let pingCount = 0;
|
||||||
|
|
||||||
|
function emit(type, data) {
|
||||||
|
const set = listeners.get(type);
|
||||||
|
if (!set) return;
|
||||||
|
for (const fn of [...set]) {
|
||||||
|
try {
|
||||||
|
fn(data);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[party]', type, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setClasses(mode) {
|
||||||
|
if (typeof document === 'undefined') return;
|
||||||
|
const c = document.documentElement.classList;
|
||||||
|
c.toggle('party-host', mode === 'host');
|
||||||
|
c.toggle('party-viewer', mode === 'viewer');
|
||||||
|
}
|
||||||
|
|
||||||
|
function median(list) {
|
||||||
|
const s = list.slice().sort((a, b) => a - b);
|
||||||
|
const m = s.length >> 1;
|
||||||
|
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const party = {
|
||||||
|
mode: 'solo',
|
||||||
|
me: null,
|
||||||
|
host: null,
|
||||||
|
members: [],
|
||||||
|
transport: null,
|
||||||
|
lastRoute: null,
|
||||||
|
lastPlay: null,
|
||||||
|
|
||||||
|
attach(transport) {
|
||||||
|
this.transport = transport || null;
|
||||||
|
clearInterval(pingTimer);
|
||||||
|
pingCount = 0;
|
||||||
|
if (this.transport) {
|
||||||
|
const ping = () => {
|
||||||
|
pingCount++;
|
||||||
|
this._send('ping', { at: Date.now() });
|
||||||
|
if (pingCount === 5) {
|
||||||
|
clearInterval(pingTimer);
|
||||||
|
pingTimer = setInterval(ping, 15000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
ping();
|
||||||
|
pingTimer = setInterval(ping, 1000);
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
if (this.transport !== transport) return;
|
||||||
|
clearInterval(pingTimer);
|
||||||
|
this.transport = null;
|
||||||
|
this._setMode('solo');
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
receive(msg) {
|
||||||
|
if (!msg || typeof msg !== 'object') return;
|
||||||
|
const t = msg.t || msg.type;
|
||||||
|
switch (t) {
|
||||||
|
case 'welcome': {
|
||||||
|
this.me = msg.you ? String(msg.you.id) : this.me;
|
||||||
|
this.host = msg.host != null ? String(msg.host) : null;
|
||||||
|
this.members = Array.isArray(msg.members) ? msg.members : [];
|
||||||
|
if (typeof msg.now === 'number' && !offsets.length) offset = msg.now - Date.now();
|
||||||
|
this.lastRoute = msg.route || null;
|
||||||
|
// a stale snapshot (host already left the watch page) must not drag viewers back
|
||||||
|
this.lastPlay = msg.play && (!msg.route || msg.play.path === msg.route) ? msg.play : null;
|
||||||
|
this._setMode(this._derive());
|
||||||
|
emit('members', this.members);
|
||||||
|
if (this.mode === 'viewer') {
|
||||||
|
if (this.lastRoute) emit('route', { path: this.lastRoute });
|
||||||
|
if (this.lastPlay) emit('play', this.lastPlay);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'host':
|
||||||
|
this.host = msg.host != null ? String(msg.host) : null;
|
||||||
|
this._setMode(this._derive());
|
||||||
|
break;
|
||||||
|
case 'members':
|
||||||
|
this.members = Array.isArray(msg.members) ? msg.members : [];
|
||||||
|
emit('members', this.members);
|
||||||
|
break;
|
||||||
|
case 'route':
|
||||||
|
if (!msg.path) return;
|
||||||
|
this.lastRoute = msg.path;
|
||||||
|
if (this.mode === 'viewer') emit('route', { path: msg.path });
|
||||||
|
break;
|
||||||
|
case 'play':
|
||||||
|
// snapshot null: the host left the watch page
|
||||||
|
this.lastPlay = msg.snapshot || null;
|
||||||
|
if (this.mode === 'viewer' && msg.snapshot) emit('play', msg.snapshot);
|
||||||
|
break;
|
||||||
|
case 'pong': {
|
||||||
|
if (typeof msg.at !== 'number' || typeof msg.now !== 'number') return;
|
||||||
|
const rtt = Date.now() - msg.at;
|
||||||
|
if (rtt < 0 || rtt > 30000) return;
|
||||||
|
offsets.push(msg.now - (msg.at + rtt / 2));
|
||||||
|
if (offsets.length > 5) offsets.shift();
|
||||||
|
offset = median(offsets);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'error':
|
||||||
|
emit('error', msg);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
now() {
|
||||||
|
return Date.now() + offset;
|
||||||
|
},
|
||||||
|
|
||||||
|
publish(type, data) {
|
||||||
|
if (this.mode !== 'host') return;
|
||||||
|
this._send(type, data || {});
|
||||||
|
},
|
||||||
|
|
||||||
|
// host: re-publish the current route + snapshot (the overlay calls this after a reconnect)
|
||||||
|
resend() {
|
||||||
|
if (this.mode === 'host') emit('resend', {});
|
||||||
|
},
|
||||||
|
|
||||||
|
on(type, fn) {
|
||||||
|
if (!listeners.has(type)) listeners.set(type, new Set());
|
||||||
|
listeners.get(type).add(fn);
|
||||||
|
return () => listeners.get(type).delete(fn);
|
||||||
|
},
|
||||||
|
|
||||||
|
hostName() {
|
||||||
|
const m = this.members.find((x) => x && String(x.id) === this.host);
|
||||||
|
return (m && (m.global_name || m.username)) || '';
|
||||||
|
},
|
||||||
|
|
||||||
|
_send(type, data) {
|
||||||
|
if (!this.transport || typeof this.transport.send !== 'function') return;
|
||||||
|
try {
|
||||||
|
this.transport.send(type, data);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[party] send failed', e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
_derive() {
|
||||||
|
if (!this.transport || !this.me || !this.host) return 'solo';
|
||||||
|
return this.me === this.host ? 'host' : 'viewer';
|
||||||
|
},
|
||||||
|
|
||||||
|
_setMode(mode) {
|
||||||
|
if (mode === this.mode) return;
|
||||||
|
const prev = this.mode;
|
||||||
|
this.mode = mode;
|
||||||
|
setClasses(mode);
|
||||||
|
emit('mode', { mode, prev });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.bugtvParty = party;
|
||||||
|
try {
|
||||||
|
window.dispatchEvent(new CustomEvent('bugtv:party-ready', { detail: party }));
|
||||||
|
} catch (e) {
|
||||||
|
/* very old browsers */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default party;
|
||||||
@@ -15,8 +15,12 @@
|
|||||||
navigate(path, { replace }), href(path) → string for <a href>, back(fallbackPath),
|
navigate(path, { replace }), href(path) → string for <a href>, back(fallbackPath),
|
||||||
current() → { path, name, params, query }, register(name, pattern, loader),
|
current() → { path, name, params, query }, register(name, pattern, loader),
|
||||||
onChange(fn) → unsubscribe, start(outlet), mode, root
|
onChange(fn) → unsubscribe, start(outlet), mode, root
|
||||||
|
|
||||||
|
Party (party.js): the host publishes every route change; viewers follow the host's
|
||||||
|
`route` messages and the path of its `play` snapshots (replace, no history entries).
|
||||||
*/
|
*/
|
||||||
import { h } from './util.js';
|
import { h } from './util.js';
|
||||||
|
import { party } from './party.js';
|
||||||
|
|
||||||
const boot = window.__BUGTV_ROUTER || (() => {
|
const boot = window.__BUGTV_ROUTER || (() => {
|
||||||
const meta = document.querySelector('meta[name="bug-tv-root"]');
|
const meta = document.querySelector('meta[name="bug-tv-root"]');
|
||||||
@@ -302,4 +306,52 @@ export function start(el) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
resolve({ scroll: 'keep' });
|
resolve({ scroll: 'keep' });
|
||||||
|
wireParty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- party mirroring ---------------------------------------------------------- */
|
||||||
|
|
||||||
|
// session/transport params that must not travel to other members
|
||||||
|
const PRIVATE_PARAMS = /^(api|frame_id|instance_id|platform|guild_id|channel_id|location_id|referrer_id|custom_id|launch_id|user|instance)$/;
|
||||||
|
|
||||||
|
function publicPath(info) {
|
||||||
|
const q = new URLSearchParams(info.query);
|
||||||
|
for (const k of [...q.keys()]) if (PRIVATE_PARAMS.test(k)) q.delete(k);
|
||||||
|
const qs = q.toString();
|
||||||
|
return info.path + (qs ? `?${qs}` : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function hereKey() {
|
||||||
|
const loc = location_();
|
||||||
|
return publicPath({ path: loc.path, query: new URLSearchParams(loc.search) });
|
||||||
|
}
|
||||||
|
|
||||||
|
function follow(path) {
|
||||||
|
if (!path || party.mode !== 'viewer') return;
|
||||||
|
if (path === hereKey()) return;
|
||||||
|
// keep our own private params (e.g. ?api=) on the viewer's URL
|
||||||
|
const loc = location_();
|
||||||
|
const mine = new URLSearchParams(loc.search);
|
||||||
|
const target = new URL(path, 'http://x');
|
||||||
|
for (const [k, v] of mine) if (PRIVATE_PARAMS.test(k) && !target.searchParams.has(k)) target.searchParams.set(k, v);
|
||||||
|
navigate(target.pathname + target.search, { replace: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
let partyWired = false;
|
||||||
|
function wireParty() {
|
||||||
|
if (partyWired) return;
|
||||||
|
partyWired = true;
|
||||||
|
onChange((info) => {
|
||||||
|
if (party.mode === 'host') party.publish('route', { path: publicPath(info) });
|
||||||
|
});
|
||||||
|
party.on('mode', ({ mode: m }) => {
|
||||||
|
if (m === 'host') party.publish('route', { path: hereKey() });
|
||||||
|
else if (m === 'viewer' && party.lastRoute) follow(party.lastRoute);
|
||||||
|
});
|
||||||
|
party.on('resend', () => party.publish('route', { path: hereKey() }));
|
||||||
|
party.on('route', ({ path }) => follow(path));
|
||||||
|
party.on('play', (snap) => {
|
||||||
|
if (snap && snap.path && snap.path !== location_().path) follow(snap.path);
|
||||||
|
});
|
||||||
|
if (party.mode === 'viewer' && party.lastRoute) follow(party.lastRoute);
|
||||||
}
|
}
|
||||||
+10
-3
@@ -11,15 +11,22 @@
|
|||||||
import { getTmdbKey } from './config.js';
|
import { getTmdbKey } from './config.js';
|
||||||
import { safe } from './util.js';
|
import { safe } from './util.js';
|
||||||
|
|
||||||
const API = 'https://api.themoviedb.org/3';
|
// <meta name="bug-tv-tmdb"> / <meta name="bug-tv-img"> override the bases (the Discord Activity
|
||||||
export const IMG_BASE = 'https://image.tmdb.org/t/p/';
|
// maps them to /tmdb/3 and /img/t/p/). Relative values resolve against the page origin.
|
||||||
|
function metaBase(name) {
|
||||||
|
const el = typeof document !== 'undefined' && document.querySelector(`meta[name="${name}"]`);
|
||||||
|
const v = el && (el.getAttribute('content') || '').trim();
|
||||||
|
return v && !/^@.*@$/.test(v) ? v : '';
|
||||||
|
}
|
||||||
|
const API = (metaBase('bug-tv-tmdb') || 'https://api.themoviedb.org/3').replace(/\/+$/, '');
|
||||||
|
export const IMG_BASE = (metaBase('bug-tv-img') || 'https://image.tmdb.org/t/p/').replace(/\/*$/, '/');
|
||||||
const SESSION_PREFIX = 'bug-tv.tmdb.';
|
const SESSION_PREFIX = 'bug-tv.tmdb.';
|
||||||
const SESSION_TTL = 30 * 60 * 1000;
|
const SESSION_TTL = 30 * 60 * 1000;
|
||||||
|
|
||||||
const mem = new Map();
|
const mem = new Map();
|
||||||
|
|
||||||
function buildUrl(path, params) {
|
function buildUrl(path, params) {
|
||||||
const url = new URL(API + path);
|
const url = new URL(API + path, typeof location !== 'undefined' ? location.href : undefined);
|
||||||
url.searchParams.set('api_key', getTmdbKey());
|
url.searchParams.set('api_key', getTmdbKey());
|
||||||
if (!params || params.language === undefined) url.searchParams.set('language', 'en-US');
|
if (!params || params.language === undefined) url.searchParams.set('language', 'en-US');
|
||||||
for (const [k, v] of Object.entries(params || {})) {
|
for (const [k, v] of Object.entries(params || {})) {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
import { h } from '../util.js';
|
import { h } from '../util.js';
|
||||||
import { icon } from './icons.js';
|
import { icon } from './icons.js';
|
||||||
|
import { party } from '../party.js';
|
||||||
|
|
||||||
export function openModal(content, opts = {}) {
|
export function openModal(content, opts = {}) {
|
||||||
const prevFocus = document.activeElement;
|
const prevFocus = document.activeElement;
|
||||||
@@ -57,6 +58,7 @@ export function openModal(content, opts = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function trailerModal(key, title) {
|
export function trailerModal(key, title) {
|
||||||
|
if (party.mode !== 'solo') return () => {}; // the YouTube iframe can't be mapped inside the Activity
|
||||||
const frame = h('iframe.modal__video', {
|
const frame = h('iframe.modal__video', {
|
||||||
src: `https://www.youtube-nocookie.com/embed/${encodeURIComponent(key)}?autoplay=1&rel=0&modestbranding=1`,
|
src: `https://www.youtube-nocookie.com/embed/${encodeURIComponent(key)}?autoplay=1&rel=0&modestbranding=1`,
|
||||||
title: title ? `${title} — trailer` : 'Trailer',
|
title: title ? `${title} — trailer` : 'Trailer',
|
||||||
|
|||||||
+33
-2
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
PLAYER ENGINE — plays one Stream (docs/api.md "Stream") in a <video>.
|
PLAYER ENGINE — plays one Stream (docs/api.md "Stream") in a <video>.
|
||||||
|
|
||||||
createPlayer(video, { onState, onError, onLevels, onAudioTracks, onTorrent, onTime })
|
createPlayer(video, { onState, onError, onLevels, onAudioTracks, onTorrent, onTime, forceProxy })
|
||||||
load(stream, { startAt, autoplay }) start a source (tears down the previous one)
|
load(stream, { startAt, autoplay }) start a source (tears down the previous one)
|
||||||
play() / pause() / toggle()
|
play() / pause() / toggle()
|
||||||
seek(t) absolute seconds (offset-aware for remux)
|
seek(t) absolute seconds (offset-aware for remux)
|
||||||
@@ -25,6 +25,11 @@
|
|||||||
engine silently reloads the fallback at the same position. Anything that
|
engine silently reloads the fallback at the same position. Anything that
|
||||||
fails after that is reported to onError({ fatal: true }) so the caller can
|
fails after that is reported to onError({ fatal: true }) so the caller can
|
||||||
move on to the next source.
|
move on to the next source.
|
||||||
|
|
||||||
|
forceProxy (option, or <meta name="bug-tv-force-proxy" content="1">): always
|
||||||
|
play playback.fallback when present (the direct url is dropped). The Discord
|
||||||
|
Activity CSP only allows mapped origins. `player.stream` is then the proxied
|
||||||
|
copy; `player.original` is the Stream object passed to load().
|
||||||
*/
|
*/
|
||||||
import { resolveUrl } from '../config.js';
|
import { resolveUrl } from '../config.js';
|
||||||
|
|
||||||
@@ -84,7 +89,26 @@ export function probeUrl(url) {
|
|||||||
return `${path.replace(/\/+$/, '')}/probe${s ? `?${s}` : ''}`;
|
return `${path.replace(/\/+$/, '')}/probe${s ? `?${s}` : ''}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let metaForceProxy = null;
|
||||||
|
function forceProxyMeta() {
|
||||||
|
if (metaForceProxy == null) {
|
||||||
|
const el = typeof document !== 'undefined' && document.querySelector('meta[name="bug-tv-force-proxy"]');
|
||||||
|
const v = el && (el.getAttribute('content') || '').trim();
|
||||||
|
metaForceProxy = !!v && /^(1|true|yes|on)$/i.test(v);
|
||||||
|
}
|
||||||
|
return metaForceProxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stream with playback.url replaced by playback.fallback (and fallback dropped). */
|
||||||
|
export function proxiedStream(s) {
|
||||||
|
const pb = s && s.playback;
|
||||||
|
if (!pb || !pb.fallback) return s;
|
||||||
|
const { fallback, ...rest } = pb;
|
||||||
|
return { ...s, playback: { ...rest, url: fallback } };
|
||||||
|
}
|
||||||
|
|
||||||
export function createPlayer(video, handlers = {}) {
|
export function createPlayer(video, handlers = {}) {
|
||||||
|
const forceProxy = handlers.forceProxy != null ? !!handlers.forceProxy : forceProxyMeta();
|
||||||
const h = {
|
const h = {
|
||||||
onState() {},
|
onState() {},
|
||||||
onError() {},
|
onError() {},
|
||||||
@@ -96,6 +120,7 @@ export function createPlayer(video, handlers = {}) {
|
|||||||
|
|
||||||
let token = 0;
|
let token = 0;
|
||||||
let stream = null;
|
let stream = null;
|
||||||
|
let original = null;
|
||||||
let hls = null;
|
let hls = null;
|
||||||
let mode = ''; // hls | native-hls | file | remux
|
let mode = ''; // hls | native-hls | file | remux
|
||||||
let offset = 0;
|
let offset = 0;
|
||||||
@@ -450,7 +475,9 @@ export function createPlayer(video, handlers = {}) {
|
|||||||
|
|
||||||
function load(s, opts = {}) {
|
function load(s, opts = {}) {
|
||||||
reset();
|
reset();
|
||||||
stream = s;
|
original = s;
|
||||||
|
stream = forceProxy ? proxiedStream(s) : s;
|
||||||
|
s = stream;
|
||||||
wantPlay = opts.autoplay !== false;
|
wantPlay = opts.autoplay !== false;
|
||||||
const startAt = Math.max(0, Number(opts.startAt) || 0);
|
const startAt = Math.max(0, Number(opts.startAt) || 0);
|
||||||
const pb = s.playback || { kind: 'file', url: s.url };
|
const pb = s.playback || { kind: 'file', url: s.url };
|
||||||
@@ -715,6 +742,7 @@ export function createPlayer(video, handlers = {}) {
|
|||||||
function stop() {
|
function stop() {
|
||||||
reset();
|
reset();
|
||||||
stream = null;
|
stream = null;
|
||||||
|
original = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function destroy() {
|
function destroy() {
|
||||||
@@ -748,6 +776,9 @@ export function createPlayer(video, handlers = {}) {
|
|||||||
get stream() {
|
get stream() {
|
||||||
return stream;
|
return stream;
|
||||||
},
|
},
|
||||||
|
get original() {
|
||||||
|
return original;
|
||||||
|
},
|
||||||
get mode() {
|
get mode() {
|
||||||
return mode;
|
return mode;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ export async function render(root, params) {
|
|||||||
const actions = h('div.hero__actions',
|
const actions = h('div.hero__actions',
|
||||||
playBtn,
|
playBtn,
|
||||||
myListButton(item, { className: 'btn btn--glass btn--lg' }),
|
myListButton(item, { className: 'btn btn--glass btn--lg' }),
|
||||||
trailer ? h('button.btn.btn--glass.btn--lg', { type: 'button', onclick: () => trailerModal(trailer.key, item.title) }, icon('trailer'), h('span', 'Trailer')) : null,
|
trailer ? h('button.btn.btn--glass.btn--lg.js-trailer', { type: 'button', onclick: () => trailerModal(trailer.key, item.title) }, icon('trailer'), h('span', 'Trailer')) : null,
|
||||||
h('button.btn.btn--glass.btn--lg.btn--icon', { type: 'button', 'aria-label': 'Share', title: 'Share', onclick: () => shareTitle(item.title, titlePath(type, id)) }, icon('share')),
|
h('button.btn.btn--glass.btn--lg.btn--icon', { type: 'button', 'aria-label': 'Share', title: 'Share', onclick: () => shareTitle(item.title, titlePath(type, id)) }, icon('share')),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
+345
-11
@@ -9,6 +9,10 @@
|
|||||||
3. Fatal errors / startup stalls fail over to the next ranked source.
|
3. Fatal errors / startup stalls fail over to the next ranked source.
|
||||||
4. Progress is persisted with the v4 semantics (storage.resume).
|
4. Progress is persisted with the v4 semantics (storage.resume).
|
||||||
5. TV: prefetch next episode at 80%, "Next episode" card at the credits.
|
5. TV: prefetch next episode at 80%, "Next episode" card at the credits.
|
||||||
|
6. Party (party.js): the host publishes a `play` snapshot on every change and
|
||||||
|
every 2s; a viewer never scrapes, it loads the host's stream and follows
|
||||||
|
its clock (seek over 1.5s drift, playbackRate 0.95/1.05 under it), with
|
||||||
|
only volume/mute/fullscreen/PiP controls.
|
||||||
|
|
||||||
export render(root, params) → cleanup()
|
export render(root, params) → cleanup()
|
||||||
*/
|
*/
|
||||||
@@ -18,11 +22,17 @@ import * as router from '../router.js';
|
|||||||
import { resume, keyFor, prefs } from '../storage.js';
|
import { resume, keyFor, prefs } from '../storage.js';
|
||||||
import { h, formatSeconds } from '../util.js';
|
import { h, formatSeconds } from '../util.js';
|
||||||
import { createPlayer } from '../ui/player.js';
|
import { createPlayer } from '../ui/player.js';
|
||||||
|
import { party } from '../party.js';
|
||||||
|
|
||||||
const GRACE_MS = 1500;
|
const GRACE_MS = 1500;
|
||||||
const CONTROLS_HIDE_MS = 3000;
|
const CONTROLS_HIDE_MS = 3000;
|
||||||
const NEXT_COUNTDOWN = 10;
|
const NEXT_COUNTDOWN = 10;
|
||||||
const CREDITS_SEC = 30;
|
const CREDITS_SEC = 30;
|
||||||
|
const HEARTBEAT_MS = 2000;
|
||||||
|
const DRIFT_MS = 500;
|
||||||
|
const SEEK_DRIFT = 1.5;
|
||||||
|
const RATE_DRIFT = 0.3;
|
||||||
|
const PAUSED_DRIFT = 0.5;
|
||||||
|
|
||||||
/* ---- icons (static markup) ------------------------------------------------ */
|
/* ---- icons (static markup) ------------------------------------------------ */
|
||||||
|
|
||||||
@@ -140,6 +150,11 @@ function replaceUrl(path) {
|
|||||||
|
|
||||||
let activeView = null;
|
let activeView = null;
|
||||||
|
|
||||||
|
/** The mounted watch view's handle ({ player, state, snapshot(), playStream, switchTo, switchEpisode, chooseSub, role }) or null. */
|
||||||
|
export function active() {
|
||||||
|
return activeView;
|
||||||
|
}
|
||||||
|
|
||||||
/** Router hook: same-route change (e.g. another episode) handled in place. */
|
/** Router hook: same-route change (e.g. another episode) handled in place. */
|
||||||
export function update(params) {
|
export function update(params) {
|
||||||
return activeView ? activeView.update(params) : false;
|
return activeView ? activeView.update(params) : false;
|
||||||
@@ -219,6 +234,7 @@ export function render(root, params = {}) {
|
|||||||
const bigPlay = btn('pl-bigplay', 'play', 'Play', () => player.toggle());
|
const bigPlay = btn('pl-bigplay', 'play', 'Play', () => player.toggle());
|
||||||
const spinner = h('div.pl-spin', h('div.pl-ring'));
|
const spinner = h('div.pl-spin', h('div.pl-ring'));
|
||||||
const centerMsg = h('div.pl-center-msg');
|
const centerMsg = h('div.pl-center-msg');
|
||||||
|
const joinBtn = h('button.pl-join', { type: 'button', hidden: true }, icon('play'), h('span', 'Click to join'));
|
||||||
const rippleL = h('div.pl-ripple.pl-ripple--l', icon('rew'), h('span', '10s'));
|
const rippleL = h('div.pl-ripple.pl-ripple--l', icon('rew'), h('span', '10s'));
|
||||||
const rippleR = h('div.pl-ripple.pl-ripple--r', icon('fwd'), h('span', '10s'));
|
const rippleR = h('div.pl-ripple.pl-ripple--r', icon('fwd'), h('span', '10s'));
|
||||||
|
|
||||||
@@ -325,7 +341,7 @@ export function render(root, params = {}) {
|
|||||||
backdrop,
|
backdrop,
|
||||||
video,
|
video,
|
||||||
scrim,
|
scrim,
|
||||||
h('div.pl-center', bigPlay, spinner, centerMsg),
|
h('div.pl-center', bigPlay, spinner, centerMsg, joinBtn),
|
||||||
rippleL,
|
rippleL,
|
||||||
rippleR,
|
rippleR,
|
||||||
loading,
|
loading,
|
||||||
@@ -337,6 +353,14 @@ export function render(root, params = {}) {
|
|||||||
nextCard,
|
nextCard,
|
||||||
toastBox,
|
toastBox,
|
||||||
);
|
);
|
||||||
|
for (const x of [backBtn, bigPlay, playBtn, rewBtn, fwdBtn, nextBtn, epBtn, ccBtn, gearBtn, srcBtn, qualityTag, ldPick, menu, srcPanel, epPanel, nextCard]) {
|
||||||
|
x.classList.add('pl-host-only');
|
||||||
|
}
|
||||||
|
// the Activity overlay blocks viewer clicks except on [data-party-allow]
|
||||||
|
for (const x of [muteBtn, vol, fullBtn, pipBtn, joinBtn]) x.setAttribute('data-party-allow', '');
|
||||||
|
let role = party.mode; // 'solo' | 'host' | 'viewer'
|
||||||
|
const isViewer = () => role === 'viewer';
|
||||||
|
el.classList.toggle('is-viewer', isViewer());
|
||||||
root.replaceChildren(el);
|
root.replaceChildren(el);
|
||||||
document.documentElement.classList.add('pl-open');
|
document.documentElement.classList.add('pl-open');
|
||||||
disposers.push(() => document.documentElement.classList.remove('pl-open'));
|
disposers.push(() => document.documentElement.classList.remove('pl-open'));
|
||||||
@@ -470,13 +494,14 @@ export function render(root, params = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function playNext() {
|
function playNext() {
|
||||||
|
if (isViewer()) return;
|
||||||
const n = nextEpisodeRef();
|
const n = nextEpisodeRef();
|
||||||
if (!n) return;
|
if (!n) return;
|
||||||
switchEpisode(n.season, n.episode);
|
switchEpisode(n.season, n.episode);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function showNextCard(fromEnded) {
|
async function showNextCard(fromEnded) {
|
||||||
if (!isTv || state.nextDismissed || !nextCard.hidden) return;
|
if (!isTv || isViewer() || state.nextDismissed || !nextCard.hidden) return;
|
||||||
const n = nextEpisodeRef();
|
const n = nextEpisodeRef();
|
||||||
if (!n) return;
|
if (!n) return;
|
||||||
let ep = n.ep;
|
let ep = n.ep;
|
||||||
@@ -537,9 +562,12 @@ export function render(root, params = {}) {
|
|||||||
.map((x) => x.s);
|
.map((x) => x.s);
|
||||||
}
|
}
|
||||||
|
|
||||||
function startStreams() {
|
function startStreams(opts = {}) {
|
||||||
const gen = ++state.loadGen;
|
const gen = ++state.loadGen;
|
||||||
if (state.sse) state.sse.close();
|
if (state.sse) state.sse.close();
|
||||||
|
state.sse = null;
|
||||||
|
if (isViewer()) return; // viewers never scrape: they follow the host's snapshot
|
||||||
|
const keep = opts.keep ? state.current : null;
|
||||||
state.streams.clear();
|
state.streams.clear();
|
||||||
state.ranked = [];
|
state.ranked = [];
|
||||||
state.failed.clear();
|
state.failed.clear();
|
||||||
@@ -551,6 +579,11 @@ export function render(root, params = {}) {
|
|||||||
state.current = null;
|
state.current = null;
|
||||||
clearTimeout(state.graceTimer);
|
clearTimeout(state.graceTimer);
|
||||||
state.graceTimer = null;
|
state.graceTimer = null;
|
||||||
|
if (keep) {
|
||||||
|
// promoted viewer: keep what is playing, search in the background for the sources panel
|
||||||
|
state.current = keep;
|
||||||
|
state.started = true;
|
||||||
|
}
|
||||||
renderProviders();
|
renderProviders();
|
||||||
renderSources();
|
renderSources();
|
||||||
|
|
||||||
@@ -607,7 +640,7 @@ export function render(root, params = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function beginPlayback(why) {
|
function beginPlayback(why) {
|
||||||
if (state.started || destroyed) return;
|
if (state.started || destroyed || isViewer()) return;
|
||||||
clearTimeout(state.graceTimer);
|
clearTimeout(state.graceTimer);
|
||||||
const first = state.ranked.find((s) => !state.failed.has(s.id));
|
const first = state.ranked.find((s) => !state.failed.has(s.id));
|
||||||
if (!first) {
|
if (!first) {
|
||||||
@@ -630,15 +663,17 @@ export function render(root, params = {}) {
|
|||||||
ldCount.textContent = failed ? `${failed} source${failed === 1 ? '' : 's'} failed` : '';
|
ldCount.textContent = failed ? `${failed} source${failed === 1 ? '' : 's'} failed` : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function playStream(s, startAt) {
|
function playStream(s, startAt, autoplay = true) {
|
||||||
state.current = s;
|
state.current = s;
|
||||||
|
state.levelPick = -1; // new source starts on auto
|
||||||
qualityTag.textContent = qualityLabel(s);
|
qualityTag.textContent = qualityLabel(s);
|
||||||
if (!state.playingOnce) setPhase('starting');
|
if (!state.playingOnce) setPhase('starting');
|
||||||
ldStatus.textContent = `Starting ${s.provider} · ${qualityLabel(s)} ${kindBadge(s)}`;
|
ldStatus.textContent = `Starting ${s.provider} · ${qualityLabel(s)} ${kindBadge(s)}`;
|
||||||
player.load(s, { startAt, autoplay: true });
|
player.load(s, { startAt, autoplay });
|
||||||
applyVolume();
|
applyVolume();
|
||||||
renderSources();
|
renderSources();
|
||||||
renderMenus();
|
renderMenus();
|
||||||
|
publishSoon();
|
||||||
}
|
}
|
||||||
|
|
||||||
function switchTo(s, reason) {
|
function switchTo(s, reason) {
|
||||||
@@ -648,6 +683,21 @@ export function render(root, params = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function tryNext(msg) {
|
function tryNext(msg) {
|
||||||
|
if (isViewer()) {
|
||||||
|
// the host decides on failover; show the waiting screen until its next snapshot.
|
||||||
|
// back off retrying the same stream (2s, 4s, 8s … 30s) so a source that is dead only
|
||||||
|
// for this viewer doesn't reload on every heartbeat
|
||||||
|
if (viewer.loadedId) {
|
||||||
|
viewer.failCount = viewer.failedId === viewer.loadedId ? viewer.failCount + 1 : 1;
|
||||||
|
viewer.failedId = viewer.loadedId;
|
||||||
|
viewer.retryAt = Date.now() + Math.min(30000, 2000 * 2 ** (viewer.failCount - 1));
|
||||||
|
}
|
||||||
|
state.current = null;
|
||||||
|
viewer.loadedId = null;
|
||||||
|
setPhase(state.playingOnce ? 'buffering' : 'finding');
|
||||||
|
ldStatus.textContent = `Waiting for ${party.hostName() || 'the host'}…`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
const next = state.ranked.find((s) => !state.failed.has(s.id) && s !== state.current);
|
const next = state.ranked.find((s) => !state.failed.has(s.id) && s !== state.current);
|
||||||
if (!next) {
|
if (!next) {
|
||||||
state.current = null;
|
state.current = null;
|
||||||
@@ -675,12 +725,19 @@ export function render(root, params = {}) {
|
|||||||
state.playingOnce = true;
|
state.playingOnce = true;
|
||||||
setPhase('playing');
|
setPhase('playing');
|
||||||
rememberProvider();
|
rememberProvider();
|
||||||
|
joinBtn.hidden = true;
|
||||||
|
publishSoon();
|
||||||
break;
|
break;
|
||||||
case 'ready':
|
case 'ready':
|
||||||
case 'blocked':
|
case 'blocked':
|
||||||
case 'paused':
|
case 'paused':
|
||||||
if (state.playingOnce || st.phase !== 'paused') setPhase('paused');
|
if (state.playingOnce || st.phase !== 'paused') setPhase('paused');
|
||||||
state.playingOnce = state.playingOnce || st.phase === 'blocked' || st.phase === 'ready';
|
state.playingOnce = state.playingOnce || st.phase === 'blocked' || st.phase === 'ready';
|
||||||
|
if (st.phase === 'blocked' && isViewer()) {
|
||||||
|
viewer.blocked = true;
|
||||||
|
joinBtn.hidden = false;
|
||||||
|
}
|
||||||
|
if (st.phase === 'paused') publishSoon();
|
||||||
break;
|
break;
|
||||||
case 'buffering':
|
case 'buffering':
|
||||||
case 'seeking':
|
case 'seeking':
|
||||||
@@ -699,6 +756,7 @@ export function render(root, params = {}) {
|
|||||||
resume.remove(currentKey());
|
resume.remove(currentKey());
|
||||||
if (isTv) showNextCard(true);
|
if (isTv) showNextCard(true);
|
||||||
setPhase('paused');
|
setPhase('paused');
|
||||||
|
publishSoon();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
@@ -716,11 +774,15 @@ export function render(root, params = {}) {
|
|||||||
},
|
},
|
||||||
onLevels() {
|
onLevels() {
|
||||||
renderMenus();
|
renderMenus();
|
||||||
|
if (isViewer()) applyTracks();
|
||||||
|
else publishSoon();
|
||||||
const lv = player.playingLevel();
|
const lv = player.playingLevel();
|
||||||
if (lv && lv.height) qualityTag.textContent = lv.height >= 2160 ? '4K' : `${lv.height}p`;
|
if (lv && lv.height) qualityTag.textContent = lv.height >= 2160 ? '4K' : `${lv.height}p`;
|
||||||
},
|
},
|
||||||
onAudioTracks() {
|
onAudioTracks() {
|
||||||
renderMenus();
|
renderMenus();
|
||||||
|
if (isViewer()) applyTracks();
|
||||||
|
else publishSoon();
|
||||||
},
|
},
|
||||||
onTorrent(st) {
|
onTorrent(st) {
|
||||||
const parts = [];
|
const parts = [];
|
||||||
@@ -737,6 +799,7 @@ export function render(root, params = {}) {
|
|||||||
function rememberProvider() {
|
function rememberProvider() {
|
||||||
const s = state.current;
|
const s = state.current;
|
||||||
if (!s) return;
|
if (!s) return;
|
||||||
|
if (isViewer()) return applyTracks(); // the host picks subtitles
|
||||||
const map = lastProviderMap();
|
const map = lastProviderMap();
|
||||||
if (map[showKey] !== s.provider) {
|
if (map[showKey] !== s.provider) {
|
||||||
map[showKey] = s.provider;
|
map[showKey] = s.provider;
|
||||||
@@ -764,6 +827,7 @@ export function render(root, params = {}) {
|
|||||||
}
|
}
|
||||||
player.setSubtitle(activeSub);
|
player.setSubtitle(activeSub);
|
||||||
renderMenus();
|
renderMenus();
|
||||||
|
publishSoon();
|
||||||
}
|
}
|
||||||
|
|
||||||
function chooseSub(i, remember = true) {
|
function chooseSub(i, remember = true) {
|
||||||
@@ -776,6 +840,7 @@ export function render(root, params = {}) {
|
|||||||
prefs.set('subtitleLang', sub ? sub.lang || sub.label : '');
|
prefs.set('subtitleLang', sub ? sub.lang || sub.label : '');
|
||||||
}
|
}
|
||||||
renderMenus();
|
renderMenus();
|
||||||
|
publishSoon();
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleCc() {
|
function toggleCc() {
|
||||||
@@ -842,9 +907,9 @@ export function render(root, params = {}) {
|
|||||||
menu.appendChild(h('div.pl-menu__head', 'Quality'));
|
menu.appendChild(h('div.pl-menu__head', 'Quality'));
|
||||||
if (levels.length) {
|
if (levels.length) {
|
||||||
const playing = player.playingLevel();
|
const playing = player.playingLevel();
|
||||||
menu.appendChild(menuItem('Auto', cur < 0, () => player.setLevel(-1), cur < 0 && playing ? playing.label : ''));
|
menu.appendChild(menuItem('Auto', cur < 0, () => chooseLevel(-1), cur < 0 && playing ? playing.label : ''));
|
||||||
for (const l of levels.slice().sort((a, b) => b.height - a.height || b.bitrate - a.bitrate)) {
|
for (const l of levels.slice().sort((a, b) => b.height - a.height || b.bitrate - a.bitrate)) {
|
||||||
menu.appendChild(menuItem(l.label, l.index === cur, () => player.setLevel(l.index), l.bitrate ? `${(l.bitrate / 1e6).toFixed(1)} Mbps` : ''));
|
menu.appendChild(menuItem(l.label, l.index === cur, () => chooseLevel(l.index), l.bitrate ? `${(l.bitrate / 1e6).toFixed(1)} Mbps` : ''));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
menu.appendChild(h('div.pl-menu__empty', state.current ? `${qualityLabel(state.current)} · fixed by source` : 'No source yet'));
|
menu.appendChild(h('div.pl-menu__empty', state.current ? `${qualityLabel(state.current)} · fixed by source` : 'No source yet'));
|
||||||
@@ -853,7 +918,7 @@ export function render(root, params = {}) {
|
|||||||
if (tracks.length > 1) {
|
if (tracks.length > 1) {
|
||||||
menu.appendChild(h('div.pl-menu__head', 'Audio'));
|
menu.appendChild(h('div.pl-menu__head', 'Audio'));
|
||||||
const ca = player.currentAudioTrack();
|
const ca = player.currentAudioTrack();
|
||||||
for (const t of tracks) menu.appendChild(menuItem(t.label, t.index === ca, () => player.setAudioTrack(t.index), t.lang && !t.label.toLowerCase().includes(t.lang.toLowerCase()) ? t.lang : ''));
|
for (const t of tracks) menu.appendChild(menuItem(t.label, t.index === ca, () => (player.setAudioTrack(t.index), publishSoon()), t.lang && !t.label.toLowerCase().includes(t.lang.toLowerCase()) ? t.lang : ''));
|
||||||
}
|
}
|
||||||
menu.appendChild(h('div.pl-menu__head', 'Speed'));
|
menu.appendChild(h('div.pl-menu__head', 'Speed'));
|
||||||
const seg = h('div.pl-menu__seg');
|
const seg = h('div.pl-menu__seg');
|
||||||
@@ -870,6 +935,14 @@ export function render(root, params = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the host's quality pick (level height, -1 auto) for snapshots; hls.js may report auto mid-switch
|
||||||
|
function chooseLevel(i) {
|
||||||
|
const l = i >= 0 ? player.levels()[i] : null;
|
||||||
|
state.levelPick = l && l.height ? l.height : -1;
|
||||||
|
player.setLevel(i);
|
||||||
|
publishSoon();
|
||||||
|
}
|
||||||
|
|
||||||
function toggleMenu(name, anchor) {
|
function toggleMenu(name, anchor) {
|
||||||
if (openMenu === name) return closeMenu();
|
if (openMenu === name) return closeMenu();
|
||||||
closePanels();
|
closePanels();
|
||||||
@@ -1062,10 +1135,14 @@ export function render(root, params = {}) {
|
|||||||
const qs = params.query && String(params.query);
|
const qs = params.query && String(params.query);
|
||||||
replaceUrl(watchPath(type, id, season, episode) + (qs ? `?${qs}` : ''));
|
replaceUrl(watchPath(type, id, season, episode) + (qs ? `?${qs}` : ''));
|
||||||
setPhase('finding');
|
setPhase('finding');
|
||||||
ldStatus.textContent = 'Finding sources…';
|
ldStatus.textContent = isViewer() ? `Waiting for ${party.hostName() || 'the host'}…` : 'Finding sources…';
|
||||||
ldTorrent.hidden = true;
|
ldTorrent.hidden = true;
|
||||||
renderTitles();
|
renderTitles();
|
||||||
|
state.current = null;
|
||||||
|
viewer.loadedId = null;
|
||||||
startStreams();
|
startStreams();
|
||||||
|
publishSoon();
|
||||||
|
if (isViewer() && party.lastPlay) applySnapshot(party.lastPlay);
|
||||||
if (!state.seasonData || state.seasonData.season_number !== season) {
|
if (!state.seasonData || state.seasonData.season_number !== season) {
|
||||||
state.seasonData = null;
|
state.seasonData = null;
|
||||||
await loadSeason(season);
|
await loadSeason(season);
|
||||||
@@ -1207,7 +1284,10 @@ export function render(root, params = {}) {
|
|||||||
scrubbing = false;
|
scrubbing = false;
|
||||||
seek.classList.remove('is-scrub', 'is-hover');
|
seek.classList.remove('is-scrub', 'is-hover');
|
||||||
const d = player.duration();
|
const d = player.duration();
|
||||||
if (d && e.type === 'pointerup') player.seek(seekRatio(e.clientX) * d);
|
if (d && e.type === 'pointerup' && !isViewer()) {
|
||||||
|
player.seek(seekRatio(e.clientX) * d);
|
||||||
|
publishSoon();
|
||||||
|
}
|
||||||
paintTime();
|
paintTime();
|
||||||
};
|
};
|
||||||
listen(seek, 'pointerup', endScrub);
|
listen(seek, 'pointerup', endScrub);
|
||||||
@@ -1215,10 +1295,12 @@ export function render(root, params = {}) {
|
|||||||
listen(seek, 'click', (e) => e.stopPropagation());
|
listen(seek, 'click', (e) => e.stopPropagation());
|
||||||
|
|
||||||
function skip(delta) {
|
function skip(delta) {
|
||||||
|
if (isViewer()) return;
|
||||||
const d = player.duration();
|
const d = player.duration();
|
||||||
let t = player.currentTime() + delta;
|
let t = player.currentTime() + delta;
|
||||||
if (d) t = Math.min(d - 1, t);
|
if (d) t = Math.min(d - 1, t);
|
||||||
player.seek(Math.max(0, t));
|
player.seek(Math.max(0, t));
|
||||||
|
publishSoon();
|
||||||
showControls();
|
showControls();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1337,6 +1419,11 @@ export function render(root, params = {}) {
|
|||||||
if (openMenu) return closeMenu();
|
if (openMenu) return closeMenu();
|
||||||
if (openPanel) return closePanels();
|
if (openPanel) return closePanels();
|
||||||
if (el.dataset.phase === 'finding' || el.dataset.phase === 'starting' || el.dataset.phase === 'error') return;
|
if (el.dataset.phase === 'finding' || el.dataset.phase === 'starting' || el.dataset.phase === 'error') return;
|
||||||
|
if (isViewer()) {
|
||||||
|
if (el.classList.contains('show-ui')) hideControls();
|
||||||
|
else showControls();
|
||||||
|
return;
|
||||||
|
}
|
||||||
const touch = e.pointerType === 'touch' || (e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents);
|
const touch = e.pointerType === 'touch' || (e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents);
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const r = el.getBoundingClientRect();
|
const r = el.getBoundingClientRect();
|
||||||
@@ -1382,6 +1469,7 @@ export function render(root, params = {}) {
|
|||||||
const tag = ((e.target && e.target.tagName) || '').toLowerCase();
|
const tag = ((e.target && e.target.tagName) || '').toLowerCase();
|
||||||
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
|
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
|
||||||
const k = e.key;
|
const k = e.key;
|
||||||
|
if (isViewer() && !/^[mMfF]$/.test(k)) return;
|
||||||
const handled = () => {
|
const handled = () => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
showControls();
|
showControls();
|
||||||
@@ -1468,6 +1556,7 @@ export function render(root, params = {}) {
|
|||||||
/* ---- back ------------------------------------------------------------------ */
|
/* ---- back ------------------------------------------------------------------ */
|
||||||
|
|
||||||
function goBack() {
|
function goBack() {
|
||||||
|
if (isViewer()) return;
|
||||||
persistProgress(true);
|
persistProgress(true);
|
||||||
if (isFull()) {
|
if (isFull()) {
|
||||||
try {
|
try {
|
||||||
@@ -1481,6 +1570,233 @@ export function render(root, params = {}) {
|
|||||||
else router.navigate(fallback);
|
else router.navigate(fallback);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- party: host publishing --------------------------------------------------- */
|
||||||
|
|
||||||
|
function mediaRef() {
|
||||||
|
return { type, id: Number(id), season: isTv ? state.season : null, episode: isTv ? state.episode : null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function snapshot() {
|
||||||
|
const sub = activeSub >= 0 ? player.subtitles()[activeSub] : null;
|
||||||
|
return {
|
||||||
|
path: watchPath(type, id, state.season, state.episode),
|
||||||
|
media: mediaRef(),
|
||||||
|
stream: state.current || null, // the Stream object as loaded (player.original), never the proxied copy
|
||||||
|
subtitle: sub ? { index: sub.index, lang: sub.lang, label: sub.label } : null,
|
||||||
|
quality: state.levelPick > 0 ? state.levelPick : -1,
|
||||||
|
audio: state.current ? player.currentAudioTrack() : -1,
|
||||||
|
playing: !!state.current && !video.paused && !video.ended,
|
||||||
|
position: state.current ? player.currentTime() : 0,
|
||||||
|
duration: state.current ? player.duration() : 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let publishTimer = null;
|
||||||
|
function publishNow() {
|
||||||
|
clearTimeout(publishTimer);
|
||||||
|
publishTimer = null;
|
||||||
|
if (destroyed || role !== 'host' || party.mode !== 'host') return;
|
||||||
|
party.publish('play', { snapshot: snapshot() });
|
||||||
|
}
|
||||||
|
// bursts (load + subtitle + level events) collapse into one message
|
||||||
|
function publishSoon() {
|
||||||
|
if (role !== 'host' || publishTimer) return;
|
||||||
|
publishTimer = setTimeout(publishNow, 100);
|
||||||
|
}
|
||||||
|
listen(video, 'seeked', publishSoon);
|
||||||
|
const heartbeat = setInterval(publishNow, HEARTBEAT_MS);
|
||||||
|
disposers.push(() => clearInterval(heartbeat));
|
||||||
|
|
||||||
|
/* ---- party: viewer ------------------------------------------------------------- */
|
||||||
|
|
||||||
|
const viewer = {
|
||||||
|
snap: null, // last applied snapshot (for this media)
|
||||||
|
loadedId: null, // stream id we loaded for it
|
||||||
|
subKey: undefined, // applied subtitle key
|
||||||
|
lastSeek: 0,
|
||||||
|
stuckSince: 0,
|
||||||
|
blocked: false,
|
||||||
|
failedId: null, // stream that last failed for this viewer, and when to retry it
|
||||||
|
failCount: 0,
|
||||||
|
retryAt: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
function sameMedia(m) {
|
||||||
|
if (!m) return false;
|
||||||
|
const mt = m.type === 'tv' ? 'tv' : 'movie';
|
||||||
|
if (mt !== type || String(m.id) !== id) return false;
|
||||||
|
return !isTv || (Number(m.season) === state.season && Number(m.episode) === state.episode);
|
||||||
|
}
|
||||||
|
|
||||||
|
function targetTime(snap) {
|
||||||
|
const pos = Number(snap.position) || 0;
|
||||||
|
if (!snap.playing || !snap.at) return pos;
|
||||||
|
return pos + Math.max(0, party.now() - snap.at) / 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
function viewerWait() {
|
||||||
|
if (!state.playingOnce) setPhase('finding');
|
||||||
|
else setPhase('buffering');
|
||||||
|
ldStatus.textContent = `Waiting for ${party.hostName() || 'the host'}…`;
|
||||||
|
ldCount.textContent = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function applySnapshot(snap) {
|
||||||
|
if (destroyed || !isViewer() || !snap || !sameMedia(snap.media)) return;
|
||||||
|
viewer.snap = snap;
|
||||||
|
const s = snap.stream;
|
||||||
|
if (!s || !s.playback) {
|
||||||
|
if (state.current) player.stop();
|
||||||
|
state.current = null;
|
||||||
|
viewer.loadedId = null;
|
||||||
|
viewerWait();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (viewer.loadedId !== s.id || !state.current) {
|
||||||
|
if (s.id === viewer.failedId && Date.now() < viewer.retryAt) return;
|
||||||
|
viewer.loadedId = s.id;
|
||||||
|
viewer.subKey = undefined;
|
||||||
|
viewer.lastSeek = Date.now();
|
||||||
|
playStream(s, targetTime(snap), !!snap.playing && !viewer.blocked);
|
||||||
|
}
|
||||||
|
applyTracks();
|
||||||
|
if (snap.playing) {
|
||||||
|
if (video.paused && !viewer.blocked) player.play();
|
||||||
|
} else if (!video.paused) player.pause();
|
||||||
|
if (!snap.playing) joinBtn.hidden = true;
|
||||||
|
else if (viewer.blocked) joinBtn.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// subtitle / quality / audio from the snapshot; re-run when tracks or levels appear
|
||||||
|
function applyTracks() {
|
||||||
|
const snap = viewer.snap;
|
||||||
|
if (!isViewer() || !snap || !state.current || viewer.loadedId !== (snap.stream && snap.stream.id)) return;
|
||||||
|
const sub = snap.subtitle;
|
||||||
|
const key = sub ? `${sub.lang}|${sub.label}|${sub.index}` : 'off';
|
||||||
|
const subs = player.subtitles();
|
||||||
|
if (key !== viewer.subKey && (!sub || subs.length)) {
|
||||||
|
viewer.subKey = key;
|
||||||
|
let i = -1;
|
||||||
|
if (sub) {
|
||||||
|
const hit = subs.find((x) => x.lang === sub.lang && x.label === sub.label) || subs[sub.index];
|
||||||
|
i = hit ? hit.index : -1;
|
||||||
|
}
|
||||||
|
subsAppliedFor = state.current.id;
|
||||||
|
if (i !== activeSub) chooseSub(i, false);
|
||||||
|
}
|
||||||
|
const levels = player.levels();
|
||||||
|
if (levels.length) {
|
||||||
|
let want = -1;
|
||||||
|
if (snap.quality > 0) {
|
||||||
|
let best = null;
|
||||||
|
for (const l of levels) if (!best || Math.abs(l.height - snap.quality) < Math.abs(best.height - snap.quality)) best = l;
|
||||||
|
if (best) want = best.index;
|
||||||
|
}
|
||||||
|
if (want !== player.currentLevel()) player.setLevel(want);
|
||||||
|
}
|
||||||
|
const tracks = player.audioTracks();
|
||||||
|
if (snap.audio >= 0 && tracks[snap.audio] && player.currentAudioTrack() !== snap.audio) {
|
||||||
|
viewer.lastSeek = Date.now();
|
||||||
|
player.setAudioTrack(snap.audio);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function correctDrift() {
|
||||||
|
const snap = viewer.snap;
|
||||||
|
if (!isViewer() || !snap || !state.current || viewer.loadedId !== (snap.stream && snap.stream.id)) return;
|
||||||
|
if (viewer.blocked || document.hidden) return;
|
||||||
|
const now = Date.now();
|
||||||
|
// let a seek/buffer settle, but nudge one that has been stuck for a while
|
||||||
|
let stuck = false;
|
||||||
|
if (video.readyState < 2 || video.seeking) {
|
||||||
|
if (!viewer.stuckSince) viewer.stuckSince = now;
|
||||||
|
if (now - viewer.stuckSince < (player.mode === 'remux' ? 12000 : 5000)) return;
|
||||||
|
viewer.stuckSince = now;
|
||||||
|
stuck = true;
|
||||||
|
} else viewer.stuckSince = 0;
|
||||||
|
const target = targetTime(snap);
|
||||||
|
const d = player.duration();
|
||||||
|
if (d && target >= d - 0.5) return; // at the end: let it end on its own
|
||||||
|
const drift = player.currentTime() - target;
|
||||||
|
const abs = Math.abs(drift);
|
||||||
|
const remux = player.mode === 'remux';
|
||||||
|
if (!snap.playing) {
|
||||||
|
if (video.playbackRate !== 1) video.playbackRate = 1;
|
||||||
|
if (abs > PAUSED_DRIFT && (stuck || now - viewer.lastSeek > (remux ? 3000 : 1000))) {
|
||||||
|
viewer.lastSeek = now;
|
||||||
|
player.seek(target);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (video.paused) return;
|
||||||
|
if (abs > SEEK_DRIFT || (stuck && abs > PAUSED_DRIFT)) {
|
||||||
|
if (!stuck && now - viewer.lastSeek < (remux ? 3000 : 1500)) return;
|
||||||
|
viewer.lastSeek = now;
|
||||||
|
video.playbackRate = 1;
|
||||||
|
// remux reloads from the keyframe before t, hls/file land close to t
|
||||||
|
player.seek(target + (remux ? 0 : 0.2));
|
||||||
|
} else if (abs > RATE_DRIFT) {
|
||||||
|
video.playbackRate = drift < 0 ? 1.05 : 0.95;
|
||||||
|
} else if (video.playbackRate !== 1) video.playbackRate = 1;
|
||||||
|
}
|
||||||
|
const driftTimer = setInterval(correctDrift, DRIFT_MS);
|
||||||
|
disposers.push(() => clearInterval(driftTimer));
|
||||||
|
|
||||||
|
joinBtn.addEventListener('click', (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
viewer.blocked = false;
|
||||||
|
joinBtn.hidden = true;
|
||||||
|
if (viewer.snap && state.current) {
|
||||||
|
// local playback only: jump to the host's clock, then start
|
||||||
|
player.seek(targetTime(viewer.snap));
|
||||||
|
if (viewer.snap.playing) player.play();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function setRole(next) {
|
||||||
|
if (next === role || destroyed) return;
|
||||||
|
const was = role;
|
||||||
|
role = next;
|
||||||
|
el.classList.toggle('is-viewer', isViewer());
|
||||||
|
if (isViewer()) {
|
||||||
|
// stop scraping and follow the host from here on
|
||||||
|
state.loadGen++;
|
||||||
|
if (state.sse) state.sse.close();
|
||||||
|
state.sse = null;
|
||||||
|
clearTimeout(state.graceTimer);
|
||||||
|
state.graceTimer = null;
|
||||||
|
closeMenu();
|
||||||
|
closePanels();
|
||||||
|
hideNextCard();
|
||||||
|
viewer.loadedId = null;
|
||||||
|
if (party.lastPlay && sameMedia(party.lastPlay.media)) applySnapshot(party.lastPlay);
|
||||||
|
else {
|
||||||
|
if (state.current) player.stop();
|
||||||
|
state.current = null;
|
||||||
|
viewerWait();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (was === 'viewer') {
|
||||||
|
// promoted: keep playing what the old host had, search sources for the panel
|
||||||
|
video.playbackRate = 1;
|
||||||
|
joinBtn.hidden = true;
|
||||||
|
viewer.snap = null;
|
||||||
|
startStreams({ keep: true });
|
||||||
|
if (!state.current && el.dataset.phase === 'finding') ldStatus.textContent = 'Finding sources…';
|
||||||
|
}
|
||||||
|
publishSoon();
|
||||||
|
}
|
||||||
|
|
||||||
|
const partyOffs = [
|
||||||
|
party.on('mode', ({ mode: m }) => setRole(m)),
|
||||||
|
party.on('resend', () => publishNow()),
|
||||||
|
party.on('play', (snap) => applySnapshot(snap)),
|
||||||
|
party.on('members', () => {
|
||||||
|
if (isViewer() && !state.current) viewerWait();
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
|
||||||
/* ---- boot ---------------------------------------------------------------------- */
|
/* ---- boot ---------------------------------------------------------------------- */
|
||||||
|
|
||||||
renderTitles();
|
renderTitles();
|
||||||
@@ -1489,11 +1805,25 @@ export function render(root, params = {}) {
|
|||||||
setPhase('error');
|
setPhase('error');
|
||||||
ldStatus.textContent = 'Missing title id.';
|
ldStatus.textContent = 'Missing title id.';
|
||||||
} else {
|
} else {
|
||||||
|
if (isViewer()) viewerWait();
|
||||||
startStreams();
|
startStreams();
|
||||||
loadMeta();
|
loadMeta();
|
||||||
|
if (isViewer() && party.lastPlay) applySnapshot(party.lastPlay);
|
||||||
}
|
}
|
||||||
|
|
||||||
const view = {
|
const view = {
|
||||||
|
// handle for party/debug tooling
|
||||||
|
player,
|
||||||
|
state,
|
||||||
|
snapshot,
|
||||||
|
playStream,
|
||||||
|
switchTo,
|
||||||
|
switchEpisode,
|
||||||
|
chooseSub,
|
||||||
|
chooseLevel,
|
||||||
|
get role() {
|
||||||
|
return role;
|
||||||
|
},
|
||||||
update(p) {
|
update(p) {
|
||||||
if ((p.type === 'tv' ? 'tv' : 'movie') !== type || String(p.id) !== id) return false;
|
if ((p.type === 'tv' ? 'tv' : 'movie') !== type || String(p.id) !== id) return false;
|
||||||
if (!isTv) return true;
|
if (!isTv) return true;
|
||||||
@@ -1508,6 +1838,10 @@ export function render(root, params = {}) {
|
|||||||
return function cleanup() {
|
return function cleanup() {
|
||||||
persistProgress(true);
|
persistProgress(true);
|
||||||
destroyed = true;
|
destroyed = true;
|
||||||
|
clearTimeout(publishTimer);
|
||||||
|
for (const off of partyOffs) off();
|
||||||
|
// left the watch page: viewers stop following this snapshot
|
||||||
|
if (role === 'host' && party.mode === 'host') party.publish('play', { snapshot: null });
|
||||||
if (activeView === view) activeView = null;
|
if (activeView === view) activeView = null;
|
||||||
if (state.sse) state.sse.close();
|
if (state.sse) state.sse.close();
|
||||||
clearTimeout(state.graceTimer);
|
clearTimeout(state.graceTimer);
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// node --test web/test/ — party.js hub semantics (no DOM needed)
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { party } from '../js/party.js';
|
||||||
|
|
||||||
|
const sent = [];
|
||||||
|
const welcome = (me, host, extra = {}) => ({ t: 'welcome', you: { id: me, username: me }, host, members: [{ id: 'a', username: 'Ann' }, { id: 'b', username: 'Bob' }], now: Date.now(), ...extra });
|
||||||
|
|
||||||
|
test('solo until a transport attaches and welcome arrives; publish is a no-op', () => {
|
||||||
|
assert.equal(party.mode, 'solo');
|
||||||
|
party.publish('route', { path: '/x' });
|
||||||
|
party.receive(welcome('a', 'a')); // no transport → still solo
|
||||||
|
assert.equal(party.mode, 'solo');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode derives from welcome/host; publish only as host', () => {
|
||||||
|
const modes = [];
|
||||||
|
const off = party.on('mode', (m) => modes.push(m.mode));
|
||||||
|
const detach = party.attach({ send: (t, d) => sent.push([t, d]) });
|
||||||
|
assert.equal(sent[0][0], 'ping');
|
||||||
|
party.receive(welcome('a', 'a'));
|
||||||
|
assert.equal(party.mode, 'host');
|
||||||
|
party.publish('route', { path: '/movies' });
|
||||||
|
assert.deepEqual(sent.at(-1), ['route', { path: '/movies' }]);
|
||||||
|
party.receive({ t: 'host', host: 'b' });
|
||||||
|
assert.equal(party.mode, 'viewer');
|
||||||
|
assert.equal(party.hostName(), 'Bob');
|
||||||
|
const n = sent.length;
|
||||||
|
party.publish('route', { path: '/tv' });
|
||||||
|
assert.equal(sent.length, n);
|
||||||
|
assert.deepEqual(modes, ['host', 'viewer']);
|
||||||
|
off();
|
||||||
|
detach();
|
||||||
|
assert.equal(party.mode, 'solo');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('viewer gets route/play events; stale welcome snapshot is dropped', () => {
|
||||||
|
const got = [];
|
||||||
|
const offs = [party.on('route', (r) => got.push(['route', r.path])), party.on('play', (s) => got.push(['play', s.path]))];
|
||||||
|
const detach = party.attach({ send() {} });
|
||||||
|
party.receive(welcome('b', 'a', { route: '/title/movie/550', play: { path: '/watch/movie/550' } }));
|
||||||
|
assert.equal(party.lastPlay, null);
|
||||||
|
assert.deepEqual(got, [['route', '/title/movie/550']]);
|
||||||
|
party.receive({ t: 'play', snapshot: { path: '/watch/movie/550', at: 1 } });
|
||||||
|
assert.equal(party.lastPlay.path, '/watch/movie/550');
|
||||||
|
assert.deepEqual(got.at(-1), ['play', '/watch/movie/550']);
|
||||||
|
offs.forEach((o) => o());
|
||||||
|
detach();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clock offset is the median of the last 5 pong samples', () => {
|
||||||
|
const detach = party.attach({ send() {} });
|
||||||
|
const realNow = Date.now;
|
||||||
|
let t = 1_000_000;
|
||||||
|
Date.now = () => t;
|
||||||
|
try {
|
||||||
|
// rtt 0 → sample = now - at; offsets 100,100,5000(outlier),100,100 → median 100
|
||||||
|
for (const off of [100, 100, 5000, 100, 100]) party.receive({ t: 'pong', at: t, now: t + off });
|
||||||
|
assert.equal(party.now() - t, 100);
|
||||||
|
} finally {
|
||||||
|
Date.now = realNow;
|
||||||
|
detach();
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in new issue
Block a user