From fceda10d9073e7d5d65aec64144d2d8f1bc03c06 Mon Sep 17 00:00:00 2001 From: Josh Date: Fri, 13 Nov 2026 11:38:39 -0500 Subject: [PATCH] Run the retroLabs backend and add the Roku tuner --- .dockerignore | 7 + .env.example | 6 + .gitignore | 6 + HANDOFF.md | 222 ++++++++++++++++++++++ README.md | 43 +++++ bridge/app.py | 282 ++++++++++++++++++++++++++++ bridge/discovery.py | 55 ++++++ bridge/requirements.txt | 3 + compose.yaml | 37 ++++ deploy/bridge.Dockerfile | 7 + roku/.gitignore | 1 + roku/README.md | 28 +++ roku/build.sh | 13 ++ roku/components/BridgeTask.brs | 132 +++++++++++++ roku/components/BridgeTask.xml | 8 + roku/components/Guide.brs | 105 +++++++++++ roku/components/RetroScene.brs | 330 +++++++++++++++++++++++++++++++++ roku/components/RetroScene.xml | 46 +++++ roku/manifest | 5 + roku/source/main.brs | 12 ++ tests/test_bridge.py | 99 ++++++++++ 21 files changed, 1447 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 HANDOFF.md create mode 100644 bridge/app.py create mode 100644 bridge/discovery.py create mode 100644 bridge/requirements.txt create mode 100644 compose.yaml create mode 100644 deploy/bridge.Dockerfile create mode 100644 roku/.gitignore create mode 100644 roku/README.md create mode 100755 roku/build.sh create mode 100644 roku/components/BridgeTask.brs create mode 100644 roku/components/BridgeTask.xml create mode 100644 roku/components/Guide.brs create mode 100644 roku/components/RetroScene.brs create mode 100644 roku/components/RetroScene.xml create mode 100644 roku/manifest create mode 100644 roku/source/main.brs create mode 100644 tests/test_bridge.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e3e1543 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +.git +.env +data +.venv +**/__pycache__ +roku +tests diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..d7234b5 --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +RETROTV_PORT=4242 +# Use the LAN IPv4 address of this machine. +RETROTV_LAN_IP=192.168.0.203 +RETROTV_NAME=retroLabs +RETROTV_MEDIA_DIR=./data/media +TUNARR_LOOPBACK_PORT=14242 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2b1b269 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.env +/data/ +__pycache__/ +.pytest_cache/ +.venv/ +*.zip diff --git a/HANDOFF.md b/HANDOFF.md new file mode 100644 index 0000000..aab2398 --- /dev/null +++ b/HANDOFF.md @@ -0,0 +1,222 @@ +# retroLabs Project Handoff + +Updated: 2026-11-13 + +## Status + +The initial bridge, Compose stack, and Roku client are implemented. The backend runs on the current machine at `192.168.0.203:4242`. See [README.md](README.md) to set up programming and build the Roku package. Tunarr programming and physical Roku acceptance remain open. The `visionLabs` reference checkout was unavailable on this machine. + +## Product goal + +Build a Roku app that behaves like an old cable television system while using the owner's personal media library: + +- Automatically find its backend on the local network. +- Tune channels with up/down controls and join programs already in progress. +- Provide configurable channels, weekly schedules, sequential episodes, marathons, commercials, bumpers, and filler. +- Provide a classic program guide and retro channel banner/static transitions. +- Include an original WeatherSTAR-inspired channel with live current conditions, forecasts, and alerts. +- Keep normal playback local to the LAN; internet access is only needed for live weather and optional metadata. +- Run the backend on the current machine. + +The user clarified that **REA means “reverse engineer anything.”** For this project, use that as permission to study behavior, protocols, and permissively licensed open-source implementations. Preserve license notices, build original branding/assets, and do not bypass DRM or copy protected branding. + +## Agreed technical direction + +Use **Tunarr as the scheduling and streaming core**, with a small custom **RetroTV Bridge** and a custom Roku SceneGraph app. + +Do not make FieldStation42's local player the primary runtime. FieldStation42 is a valuable design/configuration reference and may get an importer later, but its player renders locally through MPV and its WeatherStar integration is a web channel. A Roku client needs network HLS and cannot directly embed that browser experience. + +Tunarr was selected because it already supplies: + +- Local-folder, Plex, Jellyfin, and Emby media sources. +- Channel creation and EPG data. +- Time-slot, sequential, cyclic, and randomized scheduling. +- Filler, bumpers, commercials, and mid-roll breaks. +- FFmpeg-backed HLS suitable for Roku. +- Docker and Linux ARM64 support. + +The RetroTV Bridge owns the Roku-specific integration and keeps Tunarr replaceable. + +## Target architecture + +```text +Roku SceneGraph app + | + | SSDP discovery (UDP 1900) + | Roku JSON API + HLS (HTTP, externally exposed port 4242) + v +RetroTV Bridge / reverse proxy on the current machine + |-- stable server identity and health endpoint + |-- device pairing/token management + |-- Roku-friendly channel and guide API + |-- live weather provider/cache + |-- special-channel injection (weather initially) + |-- proxy/rewrite Tunarr HLS and admin traffic + v +Tunarr (internal-only port, expected 8000) + |-- catalog and schedule database + |-- FFmpeg/HLS channel workers + `-- read-only media mounts +``` + +Only one configurable HTTP port should need to be exposed to the LAN. Use `4242` by default because it is memorable and matches FieldStation42's convention. Internal container ports do not count as externally exposed service ports. + +## Discovery behavior + +Do not start with a blind scan of every LAN address. + +1. Try the last saved server URL and verify its stable server ID. +2. Send an SSDP `M-SEARCH` request with a retroLabs-specific service type. +3. The bridge responds with its identity and `LOCATION`, including its configured HTTP port. +4. If multiple servers respond, show a server picker. +5. Remember the selected server in the Roku registry. +6. Provide manual IP/port entry when multicast is blocked by a guest network, VLAN, or AP isolation. +7. A bounded fixed-port `/24` probe may be added later as an optional fallback, not the primary method. + +Proposed discovery identity: + +```text +ST: urn:retrolabs:service:retrotv:1 +LOCATION: http://:4242/api/v1/device.xml +USN: uuid:::urn:retrolabs:service:retrotv:1 +``` + +## Initial bridge API contract + +Keep this versioned and small: + +```text +GET /api/v1/health +GET /api/v1/server +POST /api/v1/pair/start +POST /api/v1/pair/complete +GET /api/v1/channels +GET /api/v1/channels/{channelId}/now +GET /api/v1/guide?from=&hours= +GET /api/v1/weather +GET /stream/{channelId}/master.m3u8 +GET /admin/... +``` + +The bridge should normalize Tunarr responses into compact JSON rather than making BrightScript parse M3U/XMLTV or depend on Tunarr's internal API shapes. + +## Roku app behavior + +Use classic BrightScript and SceneGraph for broad device compatibility. + +Core screens/components: + +- Discovery/pairing screen. +- Full-screen tuner using a SceneGraph `Video` node and HLS. +- Channel banner with number, name, now/next, progress, and clock. +- Program guide. +- Native weather channel. +- Settings/server diagnostics. + +Remote behavior for the first milestone: + +- Up/down: previous/next channel. +- OK: show or extend the channel banner. +- Star: open the guide/settings menu. +- Replay or left: previous channel, if reliable across the target devices. +- Back: leave the guide first, then exit playback/app. + +The server clock is authoritative. Tuning a linear channel must join the current program at the correct wall-clock point rather than restarting it. Two Roku devices tuning the same channel should see approximately the same moment. + +## Weather channel + +Implement weather natively in SceneGraph rather than attempting to embed a web page. + +Initial rotation: + +- Current conditions. +- Hourly forecast. +- Extended forecast. +- Sunrise/sunset and basic almanac values. +- Active alerts with an interrupting crawl/banner. + +Use a provider adapter. Start with the US National Weather Service when the configured location is in the United States, cache responses on the bridge, and retain the last good observation during temporary outages. Add an international provider later. Radar animation is a later milestone because it adds tile-provider, attribution, and performance decisions. + +The visual treatment should evoke late-1980s/1990s cable weather systems while using an original name, layout, graphics, and licensed/user-supplied music. + +## FieldStation42 compatibility, later + +An optional importer can map FieldStation42 concepts without running its player: + +- `standard` and `loop` stations -> Tunarr channels. +- `content_dir` -> local media sources/playlists. +- `commercial_dir` and `bump_dir` -> filler lists. +- Hourly/day rules -> Tunarr time slots. +- Streaming stations -> remote-stream channels. +- Guide/weather/web stations -> native Roku special channels or a clear unsupported warning. + +Do not block the first milestone on this importer. + +## Planned project layout + +The new project may adjust names, but start near this shape: + +```text +retroLabs/ + roku/ # manifest, source/, components/, images/ + bridge/ # discovery, normalized API, weather, proxy + deploy/ # Compose/service configuration + tests/ # API/contract tests and fixtures + docs/ + README.md + HANDOFF.md +``` + +Recommended bridge implementation: Python 3.12+ with FastAPI/uvicorn because the existing Roku workspace already uses Python bridges and it keeps SSDP, weather caching, and API work straightforward. Keep the reverse proxy/HLS path streaming; never buffer entire video segments into memory. + +## First vertical slice + +The first milestone is complete only when all of the following work on a real Roku and the current machine: + +1. A Compose stack starts Tunarr and the RetroTV Bridge. +2. The bridge exposes `GET /api/v1/health` on LAN port `4242`. +3. The Roku discovers the bridge automatically on the same subnet and remembers it. +4. Tunarr indexes one small read-only test-media folder. +5. Two channels appear in the Roku lineup. +6. Both channels play through the Roku `Video` node as HLS. +7. Up/down changes channels and shows a basic channel banner. +8. Tuning joins the program in progress based on server time. +9. A basic guide lists now/next programming. +10. A placeholder native weather channel appears in the lineup and can later be wired to live data. +11. Rebooting the Roku or backend recovers without reconfiguration. + +Defer polished CRT effects, advanced guide styling, radar, a FieldStation importer, and Roku Store distribution until this slice is stable. + +## Current deployment + +The current machine runs Linux x86-64 and Docker Compose. The bridge listens on LAN TCP port 4242, with Tunarr reached internally through host loopback port 14242. Compose mounts the configured media path read-only and persists application state in named volumes. The default media directory is `data/media/`. Use a compatible H.264/AAC sample first and verify playback before enabling hardware transcoding. + +## Existing local reference + +The sibling project `../visionLabs` already demonstrates: + +- Roku BrightScript/SceneGraph packaging. +- LAN HLS playback through a Python/FFmpeg bridge. +- A simple ZIP build script. +- Real-device behavior when direct upstream streams are not Roku-compatible. + +Study it as a reference, especially its HLS playback and packaging, but do not couple retroLabs to it or change its files. + +Roku permits only one sideloaded development app at a time. Testing retroLabs will temporarily replace the installed development build of visionLabs on the device, but both source trees and ZIP artifacts remain independent. Move to a Roku beta/public package later if both apps need to remain installed concurrently. + +## Remaining setup and acceptance + +Add a media source and program two channels in Tunarr, then sideload the Roku ZIP and run the first vertical slice checks. Set the weather location when connecting the live provider. + +## Primary references + +- FieldStation42: https://fieldstation42.com/docs/ +- FieldStation42 channel recipes: https://fieldstation42.com/docs/guides/channel-recipes/ +- Tunarr: https://tunarr.com/ +- Tunarr local media: https://tunarr.com/configure/media_sources/local/ +- Tunarr scheduling: https://tunarr.com/configure/scheduling/ +- Tunarr HLS/transcoding: https://tunarr.com/configure/channels/transcoding/ +- Roku UDP sockets: https://developer.roku.com/dev/docs/rodatagramsocket +- Roku streaming formats: https://developer.roku.com/dev/docs/media +- National Weather Service API: https://www.weather.gov/documentation/services-web-api +- MIT-licensed Roku reference, Nostalgex: https://github.com/chadMueller/Nostalgex/tree/main/roku diff --git a/README.md b/README.md index e69de29..0bf8e65 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,43 @@ +# retroLabs + +retroLabs runs a private cable-style TV lineup from your media library. Tunarr handles programming and linear HLS. The RetroTV Bridge serves the Roku app and forwards Tunarr's web UI over the same LAN port. + +## Set up programming + +The stack on this machine uses [Tunarr at 192.168.0.203:4242](http://192.168.0.203:4242/web/). + +1. Put a few compatible test videos in `data/media/`, or set `RETROTV_MEDIA_DIR` in `.env` to an existing library and run `docker compose up -d`. The directory is mounted read-only at `/media` inside Tunarr. +2. In Tunarr's media sources, add a Local source and a library under `/media`. Start a scan. You can also connect an existing Plex, Jellyfin, or Emby source. +3. Create two channels with different numbers. Use HLS as the channel's stream mode for the initial Roku test. Add programming to each channel, save, and use Tunarr's Guide and Watch actions to verify the schedule and playback. +4. Open the [Roku channel lineup](http://192.168.0.203:4242/api/v1/channels) to check that both channels and the native weather placeholder are present. + +See the [Tunarr setup walkthrough](https://tunarr.com/getting-started/setup/) and [scheduling documentation](https://tunarr.com/configure/scheduling/) for time slots, sequential programming, and filler. + +## Start the stack on another checkout + +Requires Linux, Docker with Compose, and an available LAN IPv4 address. + +```sh +mkdir -p data/media +cp .env.example .env +# Set RETROTV_LAN_IP in .env to this machine's LAN IPv4. +docker compose up -d --build +docker compose ps +docker compose logs -f bridge tunarr +``` + +Use `http://:4242/web/` for the programming UI and `/api/v1/health` for the bridge health check. Tunarr's internal port 8000 is published only on host loopback port 14242. The bridge uses host networking for SSDP on UDP 1900 and binds HTTP to the configured LAN IP. Admin and device access currently share the trusted LAN with no bridge-level authentication. Compose persists Tunarr's configuration and the bridge's UUID in named volumes. + +## Roku + +Run `./roku/build.sh` to produce `roku/dist/retroLabs.zip`. See [Roku setup and controls](roku/README.md) for sideloading and manual server entry. + +## Backend contract tests + +```sh +python3 -m venv .venv +.venv/bin/pip install -r bridge/requirements.txt +.venv/bin/python -m unittest discover -s tests -v +``` + +The tests exercise lineup and guide normalization, server ID persistence, Tunarr admin writes, and HLS manifest/segment forwarding. Physical Roku discovery, playback, live tuning, and reboot recovery are the remaining device acceptance checks. Pairing and live weather are deferred. diff --git a/bridge/app.py b/bridge/app.py new file mode 100644 index 0000000..58ac8e0 --- /dev/null +++ b/bridge/app.py @@ -0,0 +1,282 @@ +import asyncio +import os +import re +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from urllib.parse import urljoin, urlsplit +from uuid import UUID, uuid4 +from xml.etree import ElementTree as XML + +import httpx +from fastapi import FastAPI, HTTPException, Query, Request +from fastapi.responses import RedirectResponse, Response, StreamingResponse +from starlette.background import BackgroundTask + +from .discovery import SERVICE, start_discovery + +WEATHER_ID = "weather" +HOP_HEADERS = { + "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", + "te", "trailer", "transfer-encoding", "upgrade", +} +URI_ATTRIBUTE = re.compile(r'\bURI="([^"]+)"') + + +def utc_string(value: datetime): + return value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") + + +def lineup(data): + channels = [ + { + "id": channel["id"], + "number": channel["number"], + "name": channel["name"], + "type": "linear", + "streamUrl": f'/stream/{channel["id"]}/master.m3u8', + } + for channel in data if not channel.get("stealth") + ] + used = {channel["number"] for channel in channels} + number = 99 + while number in used: + number += 1 + channels.append({ + "id": WEATHER_ID, "number": number, "name": "retroLabs Weather", + "type": "weather", "streamUrl": None, + }) + return sorted(channels, key=lambda channel: channel["number"]) + + +def programs(channel_guide): + result = [] + for item in sorted(channel_guide.get("programs", []), key=lambda p: p["start"]): + title = item.get("title") or (item.get("program") or {}).get("title") + result.append({ + "title": title or ("Off air" if item["type"] == "flex" else "Programming"), + "start": utc_string(datetime.fromtimestamp(item["start"] / 1000, UTC)), + "stop": utc_string(datetime.fromtimestamp(item["stop"] / 1000, UTC)), + }) + return result + + +def rewrite_playlist(body, upstream_url): + def rewrite(uri): + target = urlsplit(urljoin(str(upstream_url), uri)) + if target.netloc != urlsplit(str(upstream_url)).netloc: + return uri + return target.path + (f"?{target.query}" if target.query else "") + + lines = [] + for line in body.splitlines(): + if line.startswith("#"): + line = URI_ATTRIBUTE.sub(lambda match: f'URI="{rewrite(match[1])}"', line) + elif line.strip(): + line = rewrite(line.strip()) + lines.append(line) + return "\n".join(lines) + "\n" + + +def forwarded_headers(headers, excluded): + connection = set(headers.get("connection", "").lower().replace(" ", "").split(",")) + blocked = HOP_HEADERS | excluded | connection + return [(key.decode("latin-1"), value.decode("latin-1")) + for key, value in headers.raw if key.decode("latin-1").lower() not in blocked] + + +def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None): + ip = os.getenv("RETROTV_LAN_IP", "127.0.0.1") + port = int(os.getenv("RETROTV_PORT", "4242")) + base_url = f"http://{ip}:{port}" + name = os.getenv("RETROTV_NAME", "retroLabs") + upstream = tunarr_url or os.getenv("RETROTV_TUNARR_URL", "http://127.0.0.1:14242") + identity = Path(id_file or os.getenv("RETROTV_ID_FILE", "data/server-id")) + + @asynccontextmanager + async def lifespan(app): + identity.parent.mkdir(parents=True, exist_ok=True) + if not identity.exists(): + temporary = identity.with_suffix(".tmp") + temporary.write_text(f"{uuid4()}\n") + temporary.replace(identity) + app.state.server_id = str(UUID(identity.read_text().strip())) + ssdp = await start_discovery(ip, app.state.server_id, base_url) if discover else None + try: + async with httpx.AsyncClient( + base_url=upstream, transport=transport, trust_env=False, + timeout=httpx.Timeout(120, connect=5), + ) as client: + app.state.tunarr = client + yield + finally: + if ssdp: + ssdp.close() + + app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) + + async def upstream_json(path, **params): + try: + response = await app.state.tunarr.get(path, params=params, timeout=10) + response.raise_for_status() + return response.json() + except (httpx.HTTPError, ValueError) as exc: + raise HTTPException(502, "Tunarr did not return usable data") from exc + + async def guide_data(start, hours): + return await upstream_json( + "/api/guide/channels", dateFrom=utc_string(start), + dateTo=utc_string(start + timedelta(hours=hours)), + ) + + @app.get("/api/v1/health") + async def health(): + return {"status": "ok"} + + @app.get("/api/v1/server") + async def server(): + return {"id": app.state.server_id, "name": name, "baseUrl": base_url} + + @app.get("/api/v1/device.xml") + async def device(): + root = XML.Element("root", xmlns="urn:schemas-upnp-org:device-1-0") + spec = XML.SubElement(root, "specVersion") + XML.SubElement(spec, "major").text = "1" + XML.SubElement(spec, "minor").text = "0" + node = XML.SubElement(root, "device") + XML.SubElement(node, "deviceType").text = "urn:retrolabs:device:retrotv:1" + XML.SubElement(node, "friendlyName").text = name + XML.SubElement(node, "UDN").text = f"uuid:{app.state.server_id}" + services = XML.SubElement(node, "serviceList") + service = XML.SubElement(services, "service") + XML.SubElement(service, "serviceType").text = SERVICE + return Response(XML.tostring(root, encoding="utf-8", xml_declaration=True), + media_type="application/xml") + + @app.get("/api/v1/channels") + async def channels(): + return {"channels": lineup(await upstream_json("/api/channels"))} + + @app.get("/api/v1/guide") + async def guide( + start: datetime | None = Query(None, alias="from"), + hours: int = Query(3, ge=1, le=24), + ): + now = datetime.now(UTC) + if start is not None and start.utcoffset() is None: + raise HTTPException(422, "Guide start must include a timezone") + channel_data, schedules = await asyncio.gather( + upstream_json("/api/channels"), guide_data(start or now, hours) + ) + return { + "serverTime": utc_string(now), + "channels": [ + {**channel, "programs": programs(schedules.get(channel["id"], {}))} + for channel in lineup(channel_data) + ], + } + + @app.get("/api/v1/channels/{channel_id}/now") + async def now_next(channel_id: str): + now = datetime.now(UTC) + stamp = utc_string(now) + if channel_id == WEATHER_ID: + return {"now": None, "next": None, "serverTime": stamp} + channel_data, schedules = await asyncio.gather( + upstream_json("/api/channels"), guide_data(now, 24) + ) + if not any(channel["id"] == channel_id for channel in lineup(channel_data)): + raise HTTPException(404, "Channel not found") + entries = programs(schedules.get(channel_id, {})) + return { + "now": next((p for p in entries if p["start"] <= stamp < p["stop"]), None), + "next": next((p for p in entries if p["start"] > stamp), None), + "serverTime": stamp, + } + + @app.get("/api/v1/weather") + async def weather(): + return {"status": "placeholder"} + + async def proxy(request, path, *, playlist=False, params=None): + client = app.state.tunarr + headers = forwarded_headers( + request.headers, {"host", "content-length", "x-forwarded-for", + "x-forwarded-host", "x-forwarded-proto"} + ) + if request.client: + headers.append(("x-forwarded-for", request.client.host)) + headers.extend([ + ("x-forwarded-host", request.url.netloc), + ("x-forwarded-proto", request.url.scheme), + ]) + has_body = "content-length" in request.headers or "transfer-encoding" in request.headers + raw_path = request.scope["raw_path"] if path == request.url.path else path.encode("ascii") + target = httpx.Request( + request.method, client.base_url.copy_with(raw_path=raw_path), + params=params if params is not None else request.url.query, + headers=headers, content=request.stream() if has_body else None, + ) + try: + response = await client.send(target, stream=True) + client.cookies.clear() + except httpx.HTTPError as exc: + raise HTTPException(502, "Tunarr is unavailable") from exc + is_playlist = playlist and request.method == "GET" and response.is_success + excluded = {"date", "server"} + if is_playlist: + excluded.update({"content-length", "content-encoding", "etag"}) + response_headers = forwarded_headers(response.headers, excluded) + if is_playlist: + try: + await response.aread() + body = rewrite_playlist(response.text, response.url) + except httpx.HTTPError as exc: + raise HTTPException(502, "Tunarr playlist could not be read") from exc + finally: + await response.aclose() + result = Response(body.encode("utf-8"), status_code=response.status_code) + response_headers = [(k, v) for k, v in response_headers if k.lower() != "content-type"] + response_headers.append(("content-type", "application/vnd.apple.mpegurl")) + else: + async def body_stream(): + try: + async for chunk in response.aiter_raw(): + yield chunk + finally: + await response.aclose() + + result = StreamingResponse(body_stream(), status_code=response.status_code, + background=BackgroundTask(response.aclose)) + for key, value in response_headers: + if key.lower() == "location": + location = urlsplit(value) + if location.netloc == client.base_url.netloc.decode(): + value = location.path or "/" + if location.query: + value += "?" + location.query + if location.fragment: + value += "#" + location.fragment + result.raw_headers.append((key.lower().encode("latin-1"), value.encode("latin-1"))) + return result + + @app.api_route("/stream/{channel_id}/master.m3u8", methods=["GET", "HEAD"]) + async def tune(request: Request, channel_id: UUID): + return await proxy(request, f"/stream/channels/{channel_id}.m3u8", playlist=True) + + @app.get("/admin", include_in_schema=False) + @app.get("/admin/", include_in_schema=False) + async def admin(): + return RedirectResponse("/") + + @app.api_route("/{path:path}", methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]) + async def tunarr_admin_and_assets(request: Request, path: str): + if path == "api/v1" or path.startswith("api/v1/"): + raise HTTPException(404, "Unknown retroLabs endpoint") + return await proxy(request, f"/{path}", + playlist=path.startswith("stream/") and path.endswith(".m3u8")) + + return app + + +app = create_app() diff --git a/bridge/discovery.py b/bridge/discovery.py new file mode 100644 index 0000000..5a01d50 --- /dev/null +++ b/bridge/discovery.py @@ -0,0 +1,55 @@ +import asyncio +import logging +import socket + +SERVICE = "urn:retrolabs:service:retrotv:1" +GROUP = "239.255.255.250" +LOG = logging.getLogger(__name__) + + +class Discovery(asyncio.DatagramProtocol): + def __init__(self, server_id: str, base_url: str): + self.transport = None + self.reply = ( + "HTTP/1.1 200 OK\r\n" + "CACHE-CONTROL: max-age=120\r\n" + "EXT:\r\n" + f"LOCATION: {base_url}/api/v1/device.xml\r\n" + "SERVER: Linux UPnP/1.1 retroLabs/0.1\r\n" + f"ST: {SERVICE}\r\n" + f"USN: uuid:{server_id}::{SERVICE}\r\n\r\n" + ).encode("ascii") + + def connection_made(self, transport): + self.transport = transport + + def datagram_received(self, data, addr): + lines = data.decode("ascii", errors="ignore").splitlines() + if not lines or lines[0].strip().upper() != "M-SEARCH * HTTP/1.1": + return + headers = {} + for line in lines[1:]: + name, _, value = line.partition(":") + headers[name.strip().lower()] = value.strip().lower() + if headers.get("man") == '"ssdp:discover"' and headers.get("st") == SERVICE: + self.transport.sendto(self.reply, addr) + + +async def start_discovery(ip: str, server_id: str, base_url: str): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("", 1900)) + sock.setsockopt( + socket.IPPROTO_IP, + socket.IP_ADD_MEMBERSHIP, + socket.inet_aton(GROUP) + socket.inet_aton(ip), + ) + transport, _ = await asyncio.get_running_loop().create_datagram_endpoint( + lambda: Discovery(server_id, base_url), sock=sock + ) + return transport + except OSError: + sock.close() + LOG.exception("SSDP unavailable. The Roku can connect using manual server entry.") + return None diff --git a/bridge/requirements.txt b/bridge/requirements.txt new file mode 100644 index 0000000..ab15ad1 --- /dev/null +++ b/bridge/requirements.txt @@ -0,0 +1,3 @@ +fastapi==0.115.14 +httpx==0.28.1 +uvicorn==0.34.3 diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..bd0ad0a --- /dev/null +++ b/compose.yaml @@ -0,0 +1,37 @@ +services: + tunarr: + image: ghcr.io/chrisbenincasa/tunarr:2026.11.2@sha256:50919e89db8c60f7fe9f3561f84ef77fb5710ccaac5db5599e9b9993c519dea9 + restart: unless-stopped + environment: + TZ: America/New_York + TUNARR_SERVER_TRUST_PROXY: "true" + ports: + - "127.0.0.1:${TUNARR_LOOPBACK_PORT:-14242}:8000" + volumes: + - tunarr-data:/config/tunarr + - type: bind + source: ${RETROTV_MEDIA_DIR:-./data/media} + target: /media + read_only: true + bind: + create_host_path: false + bridge: + build: + context: . + dockerfile: deploy/bridge.Dockerfile + restart: unless-stopped + network_mode: host + depends_on: + - tunarr + environment: + RETROTV_LAN_IP: ${RETROTV_LAN_IP:?Set RETROTV_LAN_IP in .env} + RETROTV_PORT: ${RETROTV_PORT:-4242} + RETROTV_NAME: ${RETROTV_NAME:-retroLabs} + RETROTV_TUNARR_URL: http://127.0.0.1:${TUNARR_LOOPBACK_PORT:-14242} + RETROTV_ID_FILE: /state/server-id + volumes: + - bridge-data:/state + +volumes: + tunarr-data: + bridge-data: diff --git a/deploy/bridge.Dockerfile b/deploy/bridge.Dockerfile new file mode 100644 index 0000000..9f422d5 --- /dev/null +++ b/deploy/bridge.Dockerfile @@ -0,0 +1,7 @@ +FROM python:3.12-slim +WORKDIR /app +COPY bridge/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY bridge ./bridge +ENV PYTHONUNBUFFERED=1 +CMD ["sh", "-c", "exec uvicorn bridge.app:app --host \"$RETROTV_LAN_IP\" --port \"$RETROTV_PORT\" --no-proxy-headers"] diff --git a/roku/.gitignore b/roku/.gitignore new file mode 100644 index 0000000..178135c --- /dev/null +++ b/roku/.gitignore @@ -0,0 +1 @@ +/dist/ diff --git a/roku/README.md b/roku/README.md new file mode 100644 index 0000000..dcc8e9a --- /dev/null +++ b/roku/README.md @@ -0,0 +1,28 @@ +# retroLabs on Roku + +Build the sideload ZIP from the project root. + +```sh +./roku/build.sh +unzip -t roku/dist/retroLabs.zip +``` + +With the bridge running, put the Roku and this server on the same network. +Enable Roku Developer Mode and open the Development Application Installer at +`http://` in a browser. Sign in as `rokudev` with the password you set +when enabling Developer Mode, then upload and install `roku/dist/retroLabs.zip`. +Installing a development ZIP replaces the current sideloaded app. + +On first launch, the app searches for the bridge. If multicast discovery is +unavailable, select **Enter server address** and enter the bridge host's LAN +IP or hostname. Use `IP:port` if the bridge uses a port other than `4242`. + +- **Up / Down** tunes the previous or next channel. +- **OK** shows the banner or retries a failed channel. +- **Left / Replay** returns to the last channel. +- **Star** opens the program guide, channel refresh, and server selection. +- **Back** closes the guide or menu, then exits from the tuner. + +The guide shows current and upcoming titles. The weather channel is a native +placeholder. Playback starts from the live HLS playlist supplied by the bridge. +SSDP discovery, playback, and live timing require validation on Roku hardware. diff --git a/roku/build.sh b/roku/build.sh new file mode 100755 index 0000000..204faa9 --- /dev/null +++ b/roku/build.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail + +app_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +dist_dir="$app_dir/dist" +mkdir -p "$dist_dir" +archive_dir="$(mktemp -d "$dist_dir/.build.XXXXXX")" +trap 'rm -rf -- "$archive_dir"' EXIT + +cd -- "$app_dir" +zip -q -r "$archive_dir/retroLabs.zip" manifest source components +mv -f -- "$archive_dir/retroLabs.zip" "$dist_dir/retroLabs.zip" +printf '%s\n' "$dist_dir/retroLabs.zip" diff --git a/roku/components/BridgeTask.brs b/roku/components/BridgeTask.brs new file mode 100644 index 0000000..5e97935 --- /dev/null +++ b/roku/components/BridgeTask.brs @@ -0,0 +1,132 @@ +sub init() + m.top.functionName = "runRequest" +end sub + +sub runRequest() + request = m.top.request + if request.kind = "discover" + registry = CreateObject("roRegistrySection", "server") + baseUrl = request.baseUrl + serverId = request.serverId + if request.useSaved + baseUrl = registry.Read("url") + serverId = registry.Read("id") + end if + servers = [] + if baseUrl <> "" + saved = readServer(baseUrl) + if saved <> invalid and (serverId = "" or saved.id = serverId) + servers.Push(saved) + end if + end if + + if servers.Count() = 0 and request.manual = false + for each baseUrl in discoverUrls() + server = readServer(baseUrl) + if server <> invalid + if server.id = serverId + servers = [server] + exit for + end if + duplicate = false + for each existing in servers + if existing.id = server.id then duplicate = true + end for + if not duplicate then servers.Push(server) + end if + end for + end if + m.top.result = {servers: servers} + else if request.kind = "connect" + registry = CreateObject("roRegistrySection", "server") + registry.Write("url", request.server.baseUrl) + registry.Write("id", request.server.id) + registry.Flush() + m.top.result = {data: readJson(request.server.baseUrl + "/api/v1/channels")} + else + m.top.result = {data: readJson(request.url)} + end if +end sub + +function readServer(baseUrl as string) as dynamic + data = readJson(baseUrl + "/api/v1/server") + if data = invalid or GetInterface(data.id, "ifString") = invalid or data.id = "" then return invalid + if GetInterface(data.name, "ifString") = invalid then return invalid + return {id: data.id, name: data.name, baseUrl: baseUrl} +end function + +function readJson(url as string) as dynamic + port = CreateObject("roMessagePort") + transfer = CreateObject("roUrlTransfer") + transfer.SetMessagePort(port) + transfer.SetUrl(url) + transfer.AddHeader("Accept", "application/json") + if not transfer.AsyncGetToString() then return invalid + event = Wait(3500, port) + if Type(event) = "roUrlEvent" and event.GetResponseCode() = 200 + data = ParseJson(event.GetString()) + if GetInterface(data, "ifAssociativeArray") <> invalid then return data + end if + transfer.AsyncCancel() + return invalid +end function + +function discoverUrls() as object + urls = [] + socket = CreateObject("roDatagramSocket") + port = CreateObject("roMessagePort") + socket.SetMessagePort(port) + localAddress = CreateObject("roSocketAddress") + if not localAddress.SetAddress("0.0.0.0:0") then return urls + if not socket.SetAddress(localAddress) then return urls + + multicast = CreateObject("roSocketAddress") + if not multicast.SetAddress("239.255.255.250:1900") then return urls + if not socket.SetSendToAddress(multicast) then return urls + socket.NotifyReadable(true) + + serviceType = "urn:retrolabs:service:retrotv:1" + newline = Chr(13) + Chr(10) + request = "M-SEARCH * HTTP/1.1" + newline + request += "HOST: 239.255.255.250:1900" + newline + request += "MAN: " + Chr(34) + "ssdp:discover" + Chr(34) + newline + request += "MX: 1" + newline + request += "ST: " + serviceType + newline + newline + socket.SendStr(request) + + timer = CreateObject("roTimespan") + timer.Mark() + while timer.TotalMilliseconds() < 1800 and urls.Count() < 5 + event = Wait(1800 - timer.TotalMilliseconds() + 1, port) + if Type(event) = "roSocketEvent" and socket.IsReadable() + baseUrl = responseUrl(socket.ReceiveStr(2048), serviceType) + if baseUrl <> "" + duplicate = false + for each existing in urls + if existing = baseUrl then duplicate = true + end for + if not duplicate then urls.Push(baseUrl) + end if + end if + end while + socket.Close() + return urls +end function + +function responseUrl(response as string, serviceType as string) as string + lines = response.Split(Chr(10)) + if lines.Count() = 0 or Left(lines[0], 12) <> "HTTP/1.1 200" then return "" + headers = {} + for each line in lines + separator = Instr(1, line, ":") + if separator > 1 + key = LCase(Left(line, separator - 1).Trim()) + headers[key] = Mid(line, separator + 1).Replace(Chr(13), "").Trim() + end if + end for + if headers.st <> serviceType or headers.location = invalid then return "" + pattern = CreateObject("roRegex", "^(http://[A-Za-z0-9.-]+:[0-9]{1,5})/api/v1/device[.]xml$", "i") + match = pattern.Match(headers.location) + if match.Count() = 2 then return match[1] + return "" +end function diff --git a/roku/components/BridgeTask.xml b/roku/components/BridgeTask.xml new file mode 100644 index 0000000..84ce691 --- /dev/null +++ b/roku/components/BridgeTask.xml @@ -0,0 +1,8 @@ + + + + + + +