open/<n>.ts/status/close: one ffmpeg per session reads an API playback path over loopback and writes 2 s closed-GOP segments (no B-frames, PAT/PMT + sequence header per segment, pts = source time, X-Rbx-Pts). Paced with SIGSTOP/SIGCONT 30 segments ahead of the highest request; old segments, idle sessions and exits clean up. cfg.rbx; docs/api.md; node --test test/. Co-Authored-By: Claude Opus 5.5 <[email protected]>
25 KiB
bug tv v5 — API & module contract
This is the single source of truth every workstream codes against. If you need to deviate, keep the deviation backwards compatible and note it at the bottom of this file.
Runtime
- Node 22+, CommonJS in
src/(providers are CommonJS). No TypeScript, no bundler. - npm deps allowed:
cheerio-without-node-native,crypto-js(providers),undici(keep-alive agent),webtorrent(torrents).ffmpeg/ffprobecome from PATH (cfg.remux.ffmpeg/cfg.remux.ffprobe). - Static site in
web/is vanilla ES modules (<script type="module">), no build step.
Server wiring (already written — src/server.js)
- Each
src/routes/<name>.jsexports{ routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }.pathis 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 rbx openapi. - Helpers in
src/http.js:send(req,res,status,body,type,extraHeaders)(auto br/gzip for text >1KB),json(req,res,status,obj),error(req,res,status,msg,extra),sse(req,res)→{event(name,data), close(), closed},CORSheaders object. src/sign.js:sign(obj) → token,verify(token) → obj|null(HMAC, URL-safe, no/).src/config.jsloadConfig()→ cfg:Config file path:{ host, port, tmdbKey, enabledProviders: [..] ([] = all), disabledProviders: [..] (default ["torrentio"]), providerSettings: {..} (→ global.SCRAPER_SETTINGS), timeoutMs, workers (0 = auto, min(cpus,4)), cacheTtlSec, secret, torrent: { enable, cacheDir, maxSizeGB }, remux: { enable, ffmpeg, ffprobe }, rbx: { enable, maxSessions, segment, idleSec, tmpDir }, filters: { minQuality, audioCodec, subtitles, subtitleLang } }$BUG_TV_CONFIGor./config.json.
Signed URL formats (owned by media workstream, consumed by scrape workstream)
All are relative to the API base; the client resolves them against its configured base.
| Purpose | URL | Token payload |
|---|---|---|
| proxy (any http media, playlists, keys, segments) | /v1/p/<token>/<path-and-query-of-upstream> |
{ o: "https://upstream.origin", h: {headers} } |
| remux (mkv/avi/etc → fragmented MP4) | /v1/remux/<token>?start=<sec> |
{ u: "absolute upstream url", h: {headers} } |
| remux probe | /v1/remux/<token>/probe → { duration, video:{codec,width,height}, audio:[{index,codec,lang,channels}], subtitles:[{index,codec,lang,title}] } |
same |
| torrent stream | /v1/torrent/<token>/stream?start=<sec> |
{ m: "magnet:…", s?: season, e?: episode, f?: fileIdx } |
| torrent status | /v1/torrent/<token>/status → { ready, name, file:{idx,name,size,container,remux}, peers, downSpeed, progress, buffered } |
same |
| torrent files | /v1/torrent/<token>/files → { files:[{idx,name,size}] } |
same |
| subtitles → VTT | /v1/subs/<token> (always text/vtt; SRT/ASS converted) |
{ u, h } |
Proxy rules: path-based so relative URIs inside m3u8 resolve to the same token naturally;
only absolute/cross-origin URIs inside playlists are rewritten (new token). Range requests are
passed through. Playlists may be cached ~5s; segments are never buffered in memory (stream pipe).
Remux responses set header X-Bug-Tv-Offset: <start> so the player can offset its clock;
seeking = reload with ?start=. Torrent /stream range-serves browser-native files (mp4/webm) and
remuxes others (honouring ?start=); status.file.remux tells the client which mode it is.
src/media/playback.js (media workstream) exports
playbackFor(stream) → { kind, url, fallback?, status? } and subtitleUrl(sub, headers) → string,
called by the scrape workstream during normalization:
kind:"hls" | "file" | "remux" | "torrent"hls/file: if the stream needs no headers beyond User-Agent,url= raw upstream URL (direct play, zero server cost) andfallback= proxy URL; otherwiseurl= proxy URL, no fallback.remux: types mkv/avi/other non-browser containers →url= remux URL.torrent:magnet:URLs (orinfoHash) →url= torrent stream URL,status= status URL.
Endpoints
GET /v1/streams?tmdb=<id>&type=movie|tv&season=&episode=&providers=a,b
Default response is SSE. Events, in order:
meta→{ tmdb, type, season, episode, providers: [names], timeoutMs, cached: [names] }streams(0..n, one per provider that returned something) →{ provider, ms, streams: [Stream] }provider(one per provider) →{ name, status: "ok"|"empty"|"error"|"timeout", ms, count, error? }done→{ total, ms }then the connection closes.
Cached provider results are emitted immediately. Client disconnect aborts outstanding scrapes whose results won't be cached (scrapes still in flight are allowed to finish into the cache).
?format=json or Accept: application/json (without text/event-stream) → aggregated:
{ tmdb_id, type, season, episode, total, streams: [Stream], providerErrors: {name: msg} }.
Stream:
{ id, // stable hash of provider+url
provider, name, title,
quality, // "1080p" | "2160p" | "" …
pixels, // 2160|1080|720|480|null (parsed from quality, else name/title)
audio, // aac|ac3|dts|opus|flac|mp3|multi|null
type, // m3u8|mp4|webm|mkv|avi|magnet|other
size, // bytes (number) or 0
sizeText, // human string if provider only gave text
language, // "" if unknown
seeds, // number|null (torrents)
subtitles: [{ url /* /v1/subs/… */, lang, label }],
playback: { kind, url, fallback?, status? } }
Ordering within an event: pixels desc, then provider health score.
GET /v1/prefetch?<same params as streams> → 202 { queued: [names] }
Starts the scrape in the background to fill the cache (used for next episode).
GET /v1/providers
{ defaults: [names], providers: [{ id, name, enabled, types, formats, language, logo, health: { ok, fail, timeouts, avgMs, p90Ms } }] }
(metadata from providers/manifest.json).
GET /healthz → { ok: true }
GET / Swagger UI, GET /api.json OpenAPI spec (src/routes/openapi.js).
Roblox transcode (/v1/rbx)
For clients that can't play browser media: Roblox only gets whole HTTP bodies (server-side
HttpService) and decodes video in Luau. A session runs one ffmpeg that turns a playback path into
numbered MPEG-TS segments, MPEG-1 video + MP2 audio (the jsmpeg recipe), in a temp dir.
Code: src/routes/rbx.js, src/media/rbx.js. Tests: node --test test/.
GET /v1/rbx/open?src=&start=&w=&h=&fps=&vb=&ab=&audio=
src(required): an API-relative playback path —/v1/p/<token>/…,/v1/remux/<token>or/v1/torrent/<token>/stream(a Stream'splayback.fallbackif present, elseplayback.urlwhen 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/…:startandaudioare passed to the remux (?start=&audio=). The remux starts at the keyframe at/beforestart; that keyframe is looked up first and reported asstart./v1/p/…: ffmpeg input-seeks (-ssbefore-i); transcoding makes it frame accurate./v1/torrent/<token>/stream: ffmpeg reads/v1/torrent/<token>/raw(range-served), seeking as above.
- Optional, clamped:
w32–640 (default 320),h32–360 (180), both rounded to even;fpssnapped to the nearest MPEG-1 rate ≤ 30 (23.976, 24, 25, 29.97, 30; default 24);vb64k–1500k (450k);ab32k–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 thancfg.rbx.maxSessionssessions → 503{error, max}. - Reply:
{ id, segment, start, startExact, duration, width, height, fps, sampleRate: 44100, channels: 2, videoBitrate, audioBitrate, audioTracks: [probe audio[]] }.startis where segment 0 really begins (source seconds);startExactis false only when a remux keyframe lookup failed andstartis the requested value.durationis 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 andX-Rbx-Ptsagree. - 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 × fpsframes; a closed GOP per segment.
- I-frame, then P-frames only (no B-frames),
- 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)
- Worker pool (
worker_threads), providersrequire()d once per worker at boot. global.SCRAPER_SETTINGS = cfg.providerSettingsin every worker.- Fetch shim in workers: any
api.themoviedb.org/3/...request is answered from a cache keyed by path+query minusapi_key(seeded by the main thread with details + external_ids for the current title, shared cache for everything else); per-fetch timeout; all fetches of a job abort when the job is cancelled; keep-alive undici dispatcher. - Adaptive per-provider budget from health stats (p90 × 1.5, clamped to [3s, cfg.timeoutMs]).
- Result cache per
(provider, tmdb, type, season, episode)forcfg.cacheTtlSec; in-flight dedupe.
Web (frontend workstreams)
ES modules under web/js/. Shared modules (owned by the UI-shell workstream; exports are frozen
as listed — add, don't rename):
config.js:getBase(), setBase(v), getTmdbKey(), setTmdbKey(v), getProviders(), setProviders(list), resolveUrl(relOrAbs)(resolves API-relative URLs againstgetBase()).storage.js: resume —resume.get(key), resume.save(record), resume.remove(key), resume.list(), resume.latestPerShow(), keyFor({type,tmdbId,season,episode})(record shape as in v4, keybug-tv.resume.v1kept); my list —myList.has(type,id), myList.toggle(item), myList.all(); prefs —prefs.get(name, fallback), prefs.set(name, value)(subtitle lang, volume, autoplay-next, …).tmdb.js(direct browser → TMDB, cached in memory):trending(type, window), popular(type), topRated(type), discover(type, params), details(type, id)(appendimages,credits,similar,recommendations,external_ids),season(tvId, n), search(q), image helpersimg(path, size).router.js: history router;navigate(path), routes:/home,/title/:type/:idtitle page,/watch/:type/:id[/:season/:episode]player,/search?q=,/listmy list,/settings. Static hosting fallback:404.html= copy ofindex.html, and hash fallback (#/title/…) must work when served fromfile://or a host without rewrites.ui/components return DOM nodes (no innerHTML with untrusted strings without escaping).
Player workstream owns web/js/api.js (bug-tv server client: streams(params, {onMeta,onStreams,onProvider,onDone}) → { close() } over EventSource, providers(), prefetch(params)),
web/js/views/watch.js, web/js/ui/player.js, and web/css/player.css.
Deviations
Media workstream (B)
playbackFor(stream, ctx?)takes an optional second arg{ season, episode }(stored ass/ein the torrent token). Also acceptsstream.infoHash(magnet built with default trackers) andstream.fileIdx(→f).type: "other"is sniffed by URL extension (.m3u8 → hls, .mp4/.webm/.m4v/.mov → file, else remux). Extra exports:proxyUrl(absUrl, headers),remuxUrl(absUrl, headers),magnetFor(stream). Tokens usesrc/sign.js, soplaybackFormust run wheresign.init(cfg.secret)was called (main thread, or init sign in the worker with the same secret).- Rewritten playlist URIs are emitted as relative paths (
../../<token>/path) so they work when the API is mounted under a path prefix. Root-relative (/x.ts) and../URIs are rewritten too, and every URI is rewritten when the upstream redirected. - Added (additive):
GET /v1/torrent/<token>/raw(range-serves the chosen file whatever its container; ffmpeg reads this over loopback for torrent remuxing, so?start=uses real input seeking), andGET /v1/torrent/<token>/probe(same shape as remux probe). /statusaddsinfoHash,bufferedBytesanderror;buffered= fraction of the file downloaded contiguously from byte 0;progress= fraction of the chosen file downloaded. Before metadata arrives/statusreturns immediately withready:false(never blocks)./files//streamwait up to 45s and return 504 on timeout, but the torrent keeps fetching metadata in the background (retry succeeds).- Remux probe adds
container,video.profile/pixFmt,audio[].title/default.?audio=<stream index>selects the audio track (absolute ffprobe index). HEVC is taggedhvc1. 503 when more thancfg.remux.maxProcs(default 4) ffmpeg processes run. /v1/subs/<token>also accepts a trailing.vtt.- New optional config keys:
allowPrivateTargets(default false; lets proxy/subs/remux reach private/loopback hosts — testing only),remux.maxProcs. EnvBUG_TV_WEBTORRENToverrides the webtorrent module specifier (testing). - Legacy
GET /proxy/media?url=&h=<json>kept (unsigned, SSRF-guarded); its playlists rewrite every URI to../v1/p/<token>/…. - Media stats for the health route:
require('./media/stats').mediaStats().
Player workstream (D)
api.streams(params, handlers)also takesonError(err);params.providers(array) overridesconfig.getProviders(). If EventSource errors before the first event, it falls back to?format=jsonand replays the result as meta/streams/provider/done. A drop mid-stream counts asdone, so EventSource does not reconnect and replay the scrape.views/watch.jsalso exportsupdate(params). Switching episodes in place callsrouter.navigate('/watch/tv/:id/:s/:e', { replace: true })(keeping the query string). The router then callsupdate(), which returns true for the same title, so the view is not re-rendered.- Prefs names follow
storage.js, not the task text:subtitleLang(notsubLang; "" = off), plussubtitleSize(s|m|l|xl),volume,muted,autoplayNext, andlastProvider({ "<type>:<id>": providerName }, which adds a ranking bonus). - Subtitles are fetched with
fetch()and attached as blob-URL<track>s, so<video>needs nocrossoriginand direct non-CORS media still plays. Non-WEBVTT bodies get a minimal SRT→VTT fix client-side. With remux the cues are shifted by the?start=offset. - Torrent remux duration comes from
/v1/torrent/<token>/probe(status URL with/statusreplaced by/probe), or fromstatus.file.duration/status.durationwhen present. - Remux audio tracks come from the probe's
audio[]. Switching a track reloads with?start=<t>&audio=<ffprobe index>. - Resume records also carry
backdropandstill, as documented instorage.js. The save/delete rules are unchanged from v4: skip if t < 10s, delete when t ≥ 95% or less than 15s remain, throttle to 3s, and force a save on pause, seek, pagehide and visibility change.
Scrape workstream (A)
/v1/streams(and/v1/prefetch) accept the v4 filter paramsminQuality(720/720p/…),audioCodec,subtitles(any|required|lang) andsubtitleLang. They overridecfg.filters.fresh=1ignores cached provider results, but in-flight scrapes are still joined (used byscripts/bench.js).id=is accepted as an alias oftmdb=.- SSE
providerevents carrycached: trueandms: 0for results served from the cache. Providers that are unknown or whose manifestsupportedTypeslacks the type get an immediateerror("unknown provider") orempty("tv not supported") event.countis the count after filtering. doneaddsdebug: { tmdb: { calls, local, remote, network } }:calls: TMDB requests the providers made.local: requests answered from the worker cache.remote: requests answered by the main-thread cache.network: real TMDB fetches made during the request. This is a global counter delta, so it is approximate when requests run concurrently.
meta.timeoutMsis the largest adaptive budget among the providers being scraped (0 when everything was cached).- JSON mode adds
providers: { name: { status, ms, count, cached? } }andms.total= number of streams returned (after filters). - Stream records omit raw
url/headers(useplayback). Streams with no playableplaybackare dropped.qualityis""when unknown.id= 12-char base64url SHA-1 of provider + url, so a season-pack magnet keeps the same id across episodes. - Client disconnect never aborts scrapes. Each scrape finishes within its own budget and lands in the cache.
- Result cache TTL:
ok→cacheTtlSec;empty→ min(5 min,cacheTtlSec);error/timeoutare not cached. GET /v1/providersaddsdescriptionandhealth.{empty,budgetMs}per provider, plus a top-levelstats: { tmdb, pool, results }.POST /v1/prefetchbehaves likeGET.queuedlists only providers that were not already cached.- Legacy
GET /streamskeeps the v4 JSON shape (rawurl,headers, v4 subtitle objects,matched,loadErrors). LegacyGET /providersreturns{ all, enabled }. - Workers resolve DNS through c-ares (
dns.Resolver, cached, with 30s negative caching for ENOTFOUND/ETIMEOUT) instead of getaddrinfo. The scrape module also setsUV_THREADPOOL_SIZE=24if it is unset. This matters: dead provider domains were exhausting libuv's 4-thread getaddrinfo pool and stalling every other provider by 5–10s. - Env
BUG_TV_DEBUG_PROVIDERS=1shows provider console output, prefixed[w<thread> <provider>]. It is silent by default. The optionalcfg.providersDiroverrides the providers directory used by workers (for tests). - Health stats are kept in memory only, with no persistence.
X-Bug-Tv-Offsetis the actual start of the remux (the keyframe at/before?start=, found with a parallel ffprobe), so it can be a little smaller than the requestedstart; the player should use the header value, not its own requested value.- Dependency note:
[email protected]crashes on everyadd()with the currently resolved[email protected](arr2hex(string)inTorrent._onTorrentId).webtorrent@^3.0.21fixes it and is API-compatible withsrc/media/torrent.js(tested); package.json should bump to it.
Integration
/v1/remux/<token>/probe?start=<sec>and/v1/torrent/<token>/probe?start=<sec>addkeyframe: the time the remux really starts at. The player uses it as its clock offset because a<video>element can't readX-Bug-Tv-Offset.- Extensionless stream URLs are sniffed by their first 1 KB (
src/media/sniff.js) and typed m3u8/mp4/webm/mkv beforeplaybackForruns. - The Swagger UI moved to
src/public/index.html,mod/andrest/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.
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 incomingroutecallsnavigate(path, {replace:true}). - Watch view, host: publishes a
playsnapshot 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-discorddocs/protocol.md. - Watch view, viewer:
- Never scrapes. It loads
snapshot.streamdirectly throughplayStreamand follows the clock: over 1.5s drift it seeks, and at 0.3–1.5s it setsplaybackRateto 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.
- Never scrapes. It loads
- Player:
createPlayer(video, { forceProxy }), or<meta name="bug-tv-force-proxy" content="1">, always playsplayback.fallbackwhen 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) overridehttps://api.themoviedb.org/3andhttps://image.tmdb.org/t/p/. In the Activity they are/tmdb/3and/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.nowseeds 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. Awelcome.playwhose path differs fromwelcome.routeis 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-onlyand 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) carrydata-party-allowfor the overlay's input blocking. Viewers never auto-advance to the next episode; a viewer-side source failure shows "Waiting for …" 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.qualityis the host's explicit menu pick (chooseLevel), reset to auto on source change, not hls.js's momentary level. - Watch handle:
views/watch.jsexportsactive()→{player, state, snapshot(), playStream, switchTo, switchEpisode, chooseSub, chooseLevel, role}for tooling/tests. - Player:
player.originalis the Stream passed toload();player.streamis the proxied copy under forceProxy.proxiedStream(s)is exported. - API base: a relative
bug-tv-api/?api=/ stored base such as/tvresolves againstlocation.origin(it used to becomehttps://tv). - Trailer: hidden by CSS (
html.party-host|party-viewer .js-trailer), andtrailerModal()is a no-op outside solo. - Tests:
node --test web/test/party.test.mjs.