Files
tv/docs/api.md
T
4DBugandClaude Opus 5.5 68d4924a77 api: /v1/rbx Roblox transcode sessions (mpeg1video + mp2 MPEG-TS segments)
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]>
2026-10-31 07:42:22 -05:00

25 KiB
Raw Blame History

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/ffprobe come 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>.js exports { routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }. path is an exact string or a RegExp; capture groups → ctx.params (URI-decoded). ctx = { cfg, url, params }. Loaded modules: health providers streams proxy torrent remux subs rbx openapi.
  • Helpers in src/http.js: send(req,res,status,body,type,extraHeaders) (auto br/gzip for text >1KB), json(req,res,status,obj), error(req,res,status,msg,extra), sse(req,res) → {event(name,data), close(), closed}, CORS headers object.
  • src/sign.js: sign(obj) → token, verify(token) → obj|null (HMAC, URL-safe, no /).
  • src/config.js loadConfig() → cfg:
    { host, port, tmdbKey, enabledProviders: [..] ([] = all), disabledProviders: [..] (default ["torrentio"]), providerSettings: {..} (→ global.SCRAPER_SETTINGS),
      timeoutMs, workers (0 = auto, min(cpus,4)), cacheTtlSec, secret,
      torrent: { enable, cacheDir, maxSizeGB }, remux: { enable, ffmpeg, ffprobe },
      rbx: { enable, maxSessions, segment, idleSec, tmpDir },
      filters: { minQuality, audioCodec, subtitles, subtitleLang } }
    
    Config file path: $BUG_TV_CONFIG or ./config.json.

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) and fallback = proxy URL; otherwise url = proxy URL, no fallback.
  • remux: types mkv/avi/other non-browser containers → url = remux URL.
  • torrent: magnet: URLs (or infoHash) → 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'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)

  • Worker pool (worker_threads), providers require()d once per worker at boot.
  • global.SCRAPER_SETTINGS = cfg.providerSettings in every worker.
  • Fetch shim in workers: any api.themoviedb.org/3/... request is answered from a cache keyed by path+query minus api_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) for cfg.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 against getBase()).
  • 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, key bug-tv.resume.v1 kept); 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) (append images,credits,similar,recommendations,external_ids), season(tvId, n), search(q), image helpers img(path, size).
  • router.js: history router; navigate(path), routes: / home, /title/:type/:id title page, /watch/:type/:id[/:season/:episode] player, /search?q=, /list my list, /settings. Static hosting fallback: 404.html = copy of index.html, and hash fallback (#/title/…) must work when served from file:// 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 as s/e in the torrent token). Also accepts stream.infoHash (magnet built with default trackers) and stream.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 use src/sign.js, so playbackFor must run where sign.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), and GET /v1/torrent/<token>/probe (same shape as remux probe).
  • /status adds infoHash, bufferedBytes and error; buffered = fraction of the file downloaded contiguously from byte 0; progress = fraction of the chosen file downloaded. Before metadata arrives /status returns immediately with ready:false (never blocks). /files//stream wait 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 tagged hvc1. 503 when more than cfg.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. Env BUG_TV_WEBTORRENT overrides 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 takes onError(err); params.providers (array) overrides config.getProviders(). If EventSource errors before the first event, it falls back to ?format=json and replays the result as meta/streams/provider/done. A drop mid-stream counts as done, so EventSource does not reconnect and replay the scrape.
  • views/watch.js also exports update(params). Switching episodes in place calls router.navigate('/watch/tv/:id/:s/:e', { replace: true }) (keeping the query string). The router then calls update(), which returns true for the same title, so the view is not re-rendered.
  • Prefs names follow storage.js, not the task text: subtitleLang (not subLang; "" = off), plus subtitleSize (s|m|l|xl), volume, muted, autoplayNext, and lastProvider ({ "<type>:<id>": providerName }, which adds a ranking bonus).
  • Subtitles are fetched with fetch() and attached as blob-URL <track>s, so <video> needs no crossorigin and 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 /status replaced by /probe), or from status.file.duration / status.duration when present.
  • Remux audio tracks come from the probe's audio[]. Switching a track reloads with ?start=<t>&audio=<ffprobe index>.
  • Resume records also carry backdrop and still, as documented in storage.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 params minQuality (720/720p/…), audioCodec, subtitles (any|required|lang) and subtitleLang. They override cfg.filters. fresh=1 ignores cached provider results, but in-flight scrapes are still joined (used by scripts/bench.js). id= is accepted as an alias of tmdb=.
  • SSE provider events carry cached: true and ms: 0 for results served from the cache. Providers that are unknown or whose manifest supportedTypes lacks the type get an immediate error ("unknown provider") or empty ("tv not supported") event. count is the count after filtering.
  • done adds debug: { 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.timeoutMs is the largest adaptive budget among the providers being scraped (0 when everything was cached).
  • JSON mode adds providers: { name: { status, ms, count, cached? } } and ms. total = number of streams returned (after filters).
  • Stream records omit raw url/headers (use playback). Streams with no playable playback are dropped. quality is "" 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/timeout are not cached.
  • GET /v1/providers adds description and health.{empty,budgetMs} per provider, plus a top-level stats: { tmdb, pool, results }. POST /v1/prefetch behaves like GET. queued lists only providers that were not already cached.
  • Legacy GET /streams keeps the v4 JSON shape (raw url, headers, v4 subtitle objects, matched, loadErrors). Legacy GET /providers returns { 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 sets UV_THREADPOOL_SIZE=24 if 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=1 shows provider console output, prefixed [w<thread> <provider>]. It is silent by default. The optional cfg.providersDir overrides the providers directory used by workers (for tests).
  • Health stats are kept in memory only, with no persistence.
  • X-Bug-Tv-Offset is 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 requested start; the player should use the header value, not its own requested value.
  • Dependency note: [email protected] crashes on every add() with the currently resolved [email protected] (arr2hex(string) in Torrent._onTorrentId). webtorrent@^3.0.21 fixes it and is API-compatible with src/media/torrent.js (tested); package.json should bump to it.

Integration

  • /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.
  • 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.

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 …" 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.