diff --git a/.forgejo/workflows/modules-release.yml b/.forgejo/workflows/modules-release.yml
index b826f78..418c1bc 100644
--- a/.forgejo/workflows/modules-release.yml
+++ b/.forgejo/workflows/modules-release.yml
@@ -51,11 +51,35 @@ jobs:
| Asset | Contents |
|---|---|
- | `module-bbc-*.zip` | BBC iPlayer CLI + `module.yaml` (universal) |
- | `module-rte-*.zip` | RTÉ Player CLI + `module.yaml` template |
- | `module-tg4-*.zip` | TG4 CLI + `module.yaml` template |
+ | `bbc.zip` | BBC iPlayer CLI + `module.yaml` (universal) |
+ | `rte.zip` | RTÉ Player CLI + `module.yaml` template |
+ | `tg4.zip` | TG4 CLI + `module.yaml` template |
+ | `itv.zip` | ITVX CLI stub + `module.yaml` template |
+ | `c4.zip` | Channel 4 CLI + `module.yaml` template |
+ | `my5.zip` | Channel 5 (My5) CLI + `module.yaml` template |
| `SHA256SUMS-modules.txt` | Checksums |
- Unpack each zip into `modules//`. Fill sensitive fields in
- `module.yaml`. Host `drm` is released separately on `v*` tags.
+ Unpack each zip into `modules//` (e.g. `bbc.zip` → `modules/bbc/`).
+ Each zip contains `module.yaml` only (publish template renamed — no
+ `module-publish.yaml`). Fill sensitive fields in `module.yaml`.
+ Host `drm` is released separately on `v*` tags.
Phone capture still needs Magisk + `drm proxy install-ca --reinject`.
+
+ - name: Announce on Telegram
+ env:
+ TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
+ # Private DM chat (@error404developer). Override via secret if needed.
+ TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
+ RELEASE_TAG: ${{ github.ref_name }}
+ RELEASE_KIND: modules
+ RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }}
+ run: |
+ if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
+ echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
+ exit 0
+ fi
+ # Null DRM Telegram group → Releases topic (t.me/c/3721978702/16).
+ export TELEGRAM_CHAT_ID="-1003721978702"
+ export TELEGRAM_MESSAGE_THREAD_ID="16"
+ chmod +x scripts/notify-telegram.sh
+ ./scripts/notify-telegram.sh "${{ github.ref_name }}"
diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml
index 706a551..fc1d1ba 100644
--- a/.forgejo/workflows/release.yml
+++ b/.forgejo/workflows/release.yml
@@ -1,7 +1,16 @@
-# Build multi-platform drm binaries + Android MITM and attach them to a Forgejo release.
+# Build multi-platform streamd binaries + Android MITM and attach them to a Forgejo release.
#
-# Trigger: push a version tag
-# git tag v1.2.3 && git push origin v1.2.3
+# Triggers:
+# Stable: git tag v1.2.3 && git push origin v1.2.3
+# Beta: git tag v1.2.3-beta.1 && git push origin v1.2.3-beta.1
+#
+# Each version tag gets its own release. CI also retargets a rolling channel tag:
+# vX.Y.Z → release + update `stable` (always-latest download URL)
+# vX.Y.Z- → prerelease + update `beta` (always-latest beta URL)
+#
+# Download without pinning a version:
+# .../releases/download/stable/streamd-linux-amd64
+# .../releases/download/beta/streamd-linux-amd64
#
# Requires a Forgejo Actions runner registered against this instance
# (label must match runs-on below — default act_runner often uses "docker").
@@ -23,6 +32,35 @@ jobs:
with:
fetch-depth: 0
+ - name: Classify tag (stable vs beta)
+ id: meta
+ run: |
+ set -euo pipefail
+ TAG="${{ github.ref_name }}"
+ # Strict SemVer: v1.2.3 = stable; v1.2.3-beta.1 / -rc.1 / -alpha.1 = beta channel
+ if echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
+ CHANNEL=stable
+ PRERELEASE=false
+ TITLE="$TAG"
+ NOTES_KIND=stable
+ elif echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+-(beta|rc|alpha)(\.[0-9]+)?$'; then
+ CHANNEL=beta
+ PRERELEASE=true
+ TITLE="$TAG (beta)"
+ NOTES_KIND=beta
+ else
+ echo "Unsupported host tag '$TAG'." >&2
+ echo "Use vX.Y.Z for stable or vX.Y.Z-beta.N / -rc.N / -alpha.N for beta." >&2
+ exit 1
+ fi
+ {
+ echo "channel=$CHANNEL"
+ echo "prerelease=$PRERELEASE"
+ echo "title=$TITLE"
+ echo "notes_kind=$NOTES_KIND"
+ } >> "$GITHUB_OUTPUT"
+ echo "tag=$TAG channel=$CHANNEL prerelease=$PRERELEASE"
+
- name: Setup Go
uses: actions/setup-go@v5
with:
@@ -37,33 +75,104 @@ jobs:
./scripts/build-release.sh "${{ github.ref_name }}"
ls -la dist/release
- - name: Upload to Forgejo release
+ - name: Prepare release notes
+ run: |
+ set -euo pipefail
+ TAG="${{ github.ref_name }}"
+ CHANNEL="${{ steps.meta.outputs.channel }}"
+ NOTES="docs/releases/${TAG}.md"
+ if [ -f "$NOTES" ]; then
+ cp "$NOTES" /tmp/release-notes.md
+ echo "Using $NOTES"
+ else
+ cat > /tmp/release-notes.md <\`
+ - Beta: \`…/releases/download/beta/\`
+
+ Built with \`CGO_ENABLED=0\` via \`scripts/build-release.sh\`.
+ Phone capture still needs Magisk + \`streamd proxy install-ca --reinject\`.
+ EOF
+ echo "No $NOTES — using generic notes"
+ fi
+ cat > /tmp/channel-notes.md <
+
+
+
+Dashboard — health, live streams, and play links
+
+
+
+
+
+Streams — list, filters, start / stop / restart
+
+
+
+
+
+Stream detail — credentials, variants, and preview player
+
+
+
+
+
+People & keys — accounts and agent API keys
+
+Server setup guide: [docs/streamd-server-setup.md](docs/streamd-server-setup.md) · full reference: [docs/streamd.md](docs/streamd.md)
+
+---
+
+## 🚀 Quick start
+
+### 1️⃣ Download
+
+Host binaries ship on two rolling channels (always the newest build — no version pin):
+
+| Channel | Tag | When to use |
+|---------|-----|-------------|
+| **Stable** | [`stable`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/stable) | Everyday installs |
+| **Beta** | [`beta`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/beta) | Try pre-releases (`vX.Y.Z-beta.N`) |
+
+Provider zips still come from **`modules-v*`** releases (`bbc.zip`, `rte.zip`, …).
+Pick **one** host binary block for your machine, then run `chmod +x streamd` on Linux/macOS.
+
+**Linux Intel / AMD 64-bit (stable)**
+
+```bash
+curl -fL -o streamd \
+ "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
+chmod +x streamd
+```
+
+**Linux ARM 64-bit (stable)** — Raspberry Pi 4+, many cloud ARM VMs
+
+```bash
+curl -fL -o streamd \
+ "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-arm64"
+chmod +x streamd
+```
+
+**Beta channel (Linux Intel / AMD 64-bit pre-release)**
+
+```bash
+curl -fL -o streamd \
+ "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/beta/streamd-linux-amd64"
+chmod +x streamd
+```
+
+**Windows Intel / AMD 64-bit (stable, PowerShell)**
+
+```powershell
+Invoke-WebRequest -Uri "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-windows-amd64.exe" -OutFile streamd.exe
+```
+
+Other stable assets: `streamd-windows-arm64.exe`, `streamd-darwin-amd64`, `streamd-darwin-arm64`,
+`proxy-android-arm64`. For beta, swap `/download/stable/` → `/download/beta/` in any URL.
+Pinned install: swap `stable` / `beta` for a concrete tag such as `v0.1.5` or `v0.2.0-beta.1`.
```text
-Null-DRM/
- drm.exe # or drm on Linux/macOS
- bin/proxy-android-arm64 # optional; also embedded in release drm
- modules/
- bbc/ # unzip module-bbc-*.zip here
+Streamd/
+ streamd.exe # or ./streamd on Linux/macOS
+ bin/proxy-android-arm64 # optional; also embedded in the release binary
+ modules/ # or upload zips in the streamd Modules page
+ bbc/ # unzip bbc.zip here
rte/
tg4/
+ itv/
data/ # your .wvd, optional
outputs/ # created on first run
```
-On first run, `drm` creates the install scaffold next to the exe.
+On first run, `streamd` creates the install scaffold next to the exe.
-### 2. Prerequisites
+### 2️⃣ Prerequisites
| Need | Why |
-|---|---|
-| **adb** on `PATH` | phone capture |
-| Rooted Android (Magisk) | system CA for HTTPS MITM |
-| **`.wvd`** in `data/` | Widevine keys (RTE/TG4; BBC mobile streams are clear) |
-| Python 3.10+ + `.venv` | only if you fetch keys with `wvkey.py` |
+|------|-----|
+| 📱 **adb** on `PATH` | phone capture |
+| 🔐 Rooted Android (Magisk) | system CA for HTTPS MITM |
+| 🔑 **`.wvd`** in `data/` | Widevine keys (RTE/TG4/ITV; BBC mobile is often clear) |
+| 🐍 Python 3.10+ + `.venv` | only if you fetch keys with `wvkey.py` |
-### 3. Install a provider
+### 3️⃣ Install a provider
Unzip into `modules//`. Edit **`module.yaml`** — fill sensitive fields only
-(RTE license URL / KIDs; TG4 account + policy key + video ids). BBC needs almost
-nothing extra.
+(RTE license URL / KIDs; TG4 account + policy key + video ids). BBC / ITVX need
+almost nothing extra.
```bash
-drm modules
-# or: drm --modules-dir D:\mods modules
+streamd modules
+# or: streamd --modules-dir D:\mods modules
```
-### 4. Phone CA (once per device / CA)
+### 4️⃣ Phone CA (once per device / CA)
```bash
-drm proxy install-ca --reinject
+streamd proxy install-ca --reinject
adb shell am force-stop bbc.iplayer.android # or the app you will capture
```
-### 5. Capture
+### 5️⃣ Capture
```bash
# BBC + NordVPN UK on the phone (transparent MITM; --channel auto-plays)
-drm capture --app bbc --channel bbcone --wait 120
-drm capture --app bbc --channel s4c --wait 120
+streamd capture --app bbc --channel bbcone --wait 120
+streamd capture --app bbc --channel s4c --wait 120
+
+# ITVX (UK VPN; Live tab autoplay)
+streamd capture --app itv --channel itv1 --wait 90
+
+# Channel 4 — one channel, or every Live channel
+streamd capture --app c4 --channel channel4 --wait 90
+streamd capture --app c4 --all --wait 90
+
+# Grab every channel for any module
+streamd capture --app itv --all --wait 90
# RTE / TG4 (keys via --wvd when needed)
-drm capture --app rte --channel rteone --wvd data/device.wvd
-drm capture --app tg4 --channel ioi --wvd data/device.wvd
+streamd capture --app rte --channel rteone --wvd data/device.wvd
+streamd capture --app tg4 --channel ioi --wvd data/device.wvd
# Catalog only (no phone) — TG4
-drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
+streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
```
-Results: `outputs///` (and `latest/`).
+📁 Results land in `outputs///` (and `latest/`).
-### 6. Clean the phone after a run
+### 6️⃣ Clean the phone after a run
```bash
-drm proxy reset
+streamd proxy reset
```
Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fresh.
---
-## Command cheat sheet
+## 🧾 Command cheat sheet
```text
-drm [--modules-dir DIR] …
+streamd [--modules-dir DIR] …
-drm modules
-drm capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
-drm catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
-drm proxy install-ca [--reinject] | reset [--keep-captures]
- | transparent --package PKG | start | stop | push | discover | pull
-drm serve [--bind …] [--data …] [--token …]
-drm agent run|status|devices|enqueue|cancel [--config …]
+streamd modules
+streamd capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
+streamd catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
+streamd proxy install-ca [--reinject] | reset [--keep-captures]
+ | transparent --package PKG [--mitm-host HOST]
+ | start | stop | push | discover | pull
+streamd serve [--bind …] [--data …] [--token …]
+streamd agent run|status|devices|enqueue|cancel [--config …]
```
-Global: `--modules-dir DIR` or `$DRM_MODULES_DIR` (default: `./modules`).
+🌍 Global: `--modules-dir DIR` or `$STREAMD_MODULES_DIR` (default: `./modules`).
-`--channel` implies interactive auto-play (Explore → channel → Watch live for BBC).
+🎯 `--channel` implies interactive auto-play (provider-specific Live UI flow).
---
-## Config: publish vs local
+## ⚙️ Config: publish vs local
| File | In git / zips? | Purpose |
-|---|---|---|
-| `module-publish.yaml` | yes | Universal package, channels, UI |
-| `module.yaml` | **no** (local) | Secrets + overrides; overlays publish |
+|------|----------------|---------|
+| `module-publish.yaml` | git only | Universal package, channels, UI |
+| `module.yaml` | zips yes / git no | Secrets + overlays; release zips ship publish renamed |
-Release module zips ship `module-publish.yaml` renamed to `module.yaml`.
+Release module assets are `bbc.zip` / `rte.zip` / `tg4.zip` / `itv.zip` / `c4.zip` / `my5.zip`
+with `module.yaml` only (no `module-publish.yaml` inside the zip).
---
-## Building from source (optional)
+## 🛠️ Building from source *(optional)*
```bash
git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git
cd Null-DRM-Official
-go -C apps/cli build -o ../../bin/drm.exe . # Windows
+go -C apps/cli build -o ../../bin/streamd.exe . # Windows
# Host release: .\scripts\build-release.ps1 -Version v0.1.1
# Modules: .\scripts\build-modules-release.ps1 -Version modules-v0.1.1
```
-More detail: [docs/quickstart.md](docs/quickstart.md), [docs/architecture.md](docs/architecture.md),
-[docs/providers/bbc.md](docs/providers/bbc.md).
+More detail: [docs/quickstart.md](docs/quickstart.md) · [docs/architecture.md](docs/architecture.md) · [docs/providers/bbc.md](docs/providers/bbc.md)
-## Scope
+---
+
+## 💚 Support the project
+
+If Streamd saves you time, donations keep development going:
+
+| Coin | Address |
+|------|---------|
+| ⟠ **ETH** | `0xa6314ce4deaa8329abba301802e3f511b3fa80a6` |
+| Ł **LTC** | `ltc1qpm26uccjgn4gx5pqxwzvs89mdp9hcshx9xj5a6` |
+| ₿ **BTC** | `bc1qzr70ur76jhm5gjsuqelzqaskumpkhkk2ewjgha` |
+
+Thank you 🙏
+
+---
+
+## ⚖️ Scope
Only for services you are authorised to access, with content you have the right
to decrypt.
diff --git a/apps/agent/README.md b/apps/agent/README.md
index f68f9d1..a27d6de 100644
--- a/apps/agent/README.md
+++ b/apps/agent/README.md
@@ -1,6 +1,6 @@
# agent
-Always-on credentials refresher, hosted by the single binary as `drm agent`.
+Always-on credentials refresher, hosted by the single binary as `streamd agent`.
```text
apps/agent/
@@ -26,38 +26,54 @@ expire by themselves if the agent dies.
```bash
# terminal 1 — control plane
-./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET
+./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
-# terminal 2 — agent
-export STREAMD_TOKEN=SECRET
-./bin/drm agent run --config apps/agent/agent.yaml
+# terminal 2 — agent in the background (Linux / macOS / Windows)
+export STREAMD_API_KEY=ndk_…
+./bin/streamd agent start --config apps/agent/agent.yaml
+./bin/streamd agent status --config apps/agent/agent.yaml
+# foreground debug: ./bin/streamd agent run --config apps/agent/agent.yaml
+# stop / restart: ./bin/streamd agent stop|restart --config …
+# self-update: ./bin/streamd agent update [--beta] [--tag vX.Y.Z]
```
```bash
-./bin/drm agent status
-./bin/drm agent devices
-./bin/drm agent enqueue --stream tg4-ioi --reason manual
-./bin/drm agent cancel --job 3
+./bin/streamd agent devices
+./bin/streamd agent enqueue --stream tg4-ioi --reason manual
+./bin/streamd agent cancel --job 3
```
-App modules are compiled into the binary, so there is no `modules_dir` to set. The
-agent drives whichever module a stream names and contains no provider logic.
+With `sync_modules: true` (default in the sample config), the agent **pulls**
+provider modules from the streamd Modules page into `/modules/`. You do
+not need a hand-maintained `modules/` tree on each agent host. The agent drives
+whichever module a stream names and contains no provider logic.
## Config
-`agent.yaml` — `streamd_url`, `token` (or `STREAMD_TOKEN`), `poll_interval_sec`,
-`workers`, `max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised
-device), `wvd`, `user_agent`, `agent_id`, `data_dir`.
+`agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or
+env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
+`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
+`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
+(default `/modules`), `modules_sync_interval_sec`, `modules_prune`,
+`job_backoff` (default false — exponential delays only when several agents
+share work), plus daemon fields `log_file`, `pid_file`, `channel`, `asset`,
+`keep_old` for `agent start|stop|update`.
-`wvd` must be set or key fetches fail.
+Create the key in the streamd dashboard (role **operator**). The legacy shared
+`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
+
+`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
+bootstraps `apps/wvkey/` and creates `/.venv` with `pywidevine` using
+the system Python (Windows, Linux, or macOS) so Widevine key fetch works without
+a hand-made venv.
## Build
```bash
-go -C apps/cli build -o ../../bin/drm .
+go -C apps/cli build -o ../../bin/streamd .
# cross-compile
-GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/drm .
+GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/streamd .
```
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
diff --git a/apps/agent/agent.yaml b/apps/agent/agent.yaml
index 2dbd41a..4b7b511 100644
--- a/apps/agent/agent.yaml
+++ b/apps/agent/agent.yaml
@@ -1,8 +1,11 @@
# Always-on credentials agent (apps/agent → bin/agent.exe)
# Default path: apps/agent/agent.yaml
-streamd_url: http://127.0.0.1:8083
-# Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials).
-token: "SECRET"
+streamd_url: http://localhost:8083
+# Paste an operator API key from streamd → People & keys → New API key.
+# The dashboard shows the secret once — copy it into api_key (not the name).
+# api_key: ""
+# token: is a legacy alias for the same field (or set STREAMD_API_KEY / STREAMD_TOKEN).
+token: "REPLACE_WITH_API_KEY_SECRET"
# Stable id across restarts (default = hostname). Required for reclaim after crash.
# agent_id: my-agent
poll_interval_sec: 30
@@ -11,8 +14,23 @@ workers: 1 # concurrent ADB jobs
max_attempts: 5
capture_wait_sec: 180
devices: [] # empty = all adb "device" serials; never installs apps
-# wvd: data/device.wvd # path to .wvd (required for key fetch)
+# Pull modules from the streamd panel into the local cache (package.zip + yaml).
+sync_modules: true
+# modules_dir: # optional; default /modules
+# modules_sync_interval_sec: 300
+# modules_prune: false # delete local modules absent from the panel
+# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
+# Set true only when several agents share the same streams.
+# job_backoff: false
+# Background daemon (streamd agent start|stop|update):
+# log_file: agent.log
+# pid_file: agent.pid
+# channel: stable # or beta — used by agent update
+# asset: # optional streamd-* override
+# keep_old: 10
+# Required for key fetch. Relative paths resolve from the install/repo root.
+# Agent auto-creates .venv + installs pywidevine on first run (Win/Linux/macOS).
+# python: # optional override; default = /.venv/…
+wvd: data/device.wvd
# user_agent: "" # optional license-request User-Agent
-# App modules (rte, tg4, …) are compiled into the binary — there is no
-# modules directory to point at. Their local values live in
-# apps/modules//module.yaml; see apps/modules/README.md.
+
diff --git a/apps/agent/agentcmd/agentcmd.go b/apps/agent/agentcmd/agentcmd.go
index 4325901..9329025 100644
--- a/apps/agent/agentcmd/agentcmd.go
+++ b/apps/agent/agentcmd/agentcmd.go
@@ -9,16 +9,21 @@ import (
"os"
"os/signal"
"strconv"
+ "strings"
"syscall"
"text/tabwriter"
- "drmdecryption/apps/agent/internal/client"
- "drmdecryption/apps/agent/internal/config"
- "drmdecryption/apps/agent/internal/device"
- "drmdecryption/apps/agent/internal/poller"
- "drmdecryption/apps/agent/internal/queue"
- "drmdecryption/apps/agent/internal/worker"
- "drmdecryption/apps/agent/internal/wsclient"
+ "streamd/apps/agent/internal/client"
+ "streamd/apps/agent/internal/config"
+ "streamd/apps/agent/internal/device"
+ "streamd/apps/agent/internal/modsync"
+ "streamd/apps/agent/internal/poller"
+ "streamd/apps/agent/internal/queue"
+ "streamd/apps/agent/internal/worker"
+ "streamd/apps/agent/internal/wsclient"
+ "streamd/modhost"
+ "streamd/repo"
+ "streamd/wvkey"
)
// Run dispatches an agent subcommand. args[0] is the subcommand name.
@@ -34,6 +39,14 @@ func Run(args []string) error {
switch sub {
case "run":
runCmd(sub, rest)
+ case "start":
+ return startDaemonCmd(rest)
+ case "stop":
+ return stopDaemonCmd(rest)
+ case "restart":
+ return restartDaemonCmd(rest)
+ case "update":
+ return updateDaemonCmd(rest)
case "status":
statusCmd(sub, rest)
case "devices":
@@ -56,8 +69,13 @@ func Usage() {
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
Usage:
- agent run [--config apps/agent/agent.yaml]
- agent status [--config ...]
+ agent start [--config agent.yaml] # background (pid + log)
+ agent stop [--config ...]
+ agent restart [--config ...]
+ agent status [--config ...] # process + recent jobs
+ agent update [--config ...] [--beta] [--tag vX.Y.Z] [--no-restart]
+ agent run [--config ...] # foreground (debug)
+
agent devices [--config ...]
agent enqueue --stream NAME [--reason manual] [--config ...]
agent cancel --job ID [--config ...]
@@ -66,6 +84,9 @@ Polls streamd for enabled streams that are down / missing credentials,
enqueues jobs, claims a free phone that already has the app, captures
via MITM, POSTs credentials, then force-stops the app.
+Job retries default to immediate (job_backoff: false). Set job_backoff: true
+in agent.yaml for exponential delays when several agents share work.
+
Does not install apps. Does not run NRE/ffmpeg.
`)
}
@@ -81,6 +102,14 @@ func loadCfg(sub string, args []string) (config.Config, *flag.FlagSet) {
return cfg, fs
}
+// newAPI builds the streamd client with this agent's identity attached, so
+// audit rows in streamd name the agent and not just its API key.
+func newAPI(cfg config.Config) *client.Client {
+ c := client.New(cfg.StreamdURL, cfg.Token)
+ c.AgentID = cfg.AgentID
+ return c
+}
+
func openQueue(cfg config.Config) *queue.Store {
q, err := queue.Open(cfg.DataDir)
if err != nil {
@@ -91,10 +120,34 @@ func openQueue(cfg config.Config) *queue.Store {
func runCmd(sub string, args []string) {
cfg, _ := loadCfg(sub, args)
- api := client.New(cfg.StreamdURL, cfg.Token)
+ api := newAPI(cfg)
if err := api.Health(); err != nil {
log.Fatalf("streamd unreachable at %s: %v", cfg.StreamdURL, err)
}
+ // Health says the server is up; /api/me says our credential actually
+ // works. Without this a missing or revoked key failed silently on every
+ // poll instead of once, loudly, at startup.
+ me, err := api.Me()
+ if err != nil {
+ log.Fatalf("streamd rejected this agent at %s: %v", cfg.StreamdURL, err)
+ }
+ if me.Role != "operator" && me.Role != "admin" {
+ log.Fatalf("this agent's credential has role %q, but capturing needs at least `operator` — "+
+ "create an operator API key in the streamd dashboard", me.Role)
+ }
+ log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role)
+
+ // Widevine keys need apps/wvkey + a local .venv (pywidevine). Create them
+ // once per install root so Windows / Linux / macOS agents all work.
+ if rt, err := wvkey.EnsureRuntime(repo.Root()); err != nil {
+ log.Fatalf("widevine helper: %v", err)
+ } else {
+ log.Printf("widevine helper ready python=%s script=%s", rt.Python, rt.Script)
+ if strings.TrimSpace(cfg.Python) == "" {
+ cfg.Python = rt.Python
+ }
+ }
+
q := openQueue(cfg)
defer q.Close()
@@ -103,6 +156,16 @@ func runCmd(sub string, args []string) {
} else if n > 0 {
log.Printf("re-queued %d stuck running job(s) from previous run", n)
}
+ if n, err := q.ClearAllBackoffs(); err != nil {
+ log.Printf("clear backoffs: %v", err)
+ } else if n > 0 {
+ log.Printf("cleared backoff on %d queued job(s) — runnable now", n)
+ }
+ if cfg.JobBackoffEnabled() {
+ log.Printf("job_backoff=true (exponential delays after failures)")
+ } else {
+ log.Printf("job_backoff=false (retry failed captures immediately)")
+ }
pool := device.New("", cfg.Devices)
stop := make(chan struct{})
@@ -116,7 +179,60 @@ func runCmd(sub string, args []string) {
}
go p.Loop(stop)
+ // Prefer the panel-synced modules cache for capture jobs.
+ if cfg.ModulesDir != "" {
+ if err := modhost.SetModulesDir(cfg.ModulesDir); err != nil {
+ log.Fatalf("modules dir: %v", err)
+ }
+ log.Printf("modules dir %s", cfg.ModulesDir)
+ }
+
+ var ms *modsync.Syncer
+ if cfg.SyncModules {
+ ms = &modsync.Syncer{
+ API: api,
+ ModulesDir: cfg.ModulesDir,
+ Interval: cfg.ModulesSyncInterval(),
+ Prune: cfg.ModulesPrune,
+ Log: log.Default(),
+ }
+ go ms.Loop(stop)
+ log.Printf("modules pull sync enabled interval=%s dir=%s", cfg.ModulesSyncInterval(), cfg.ModulesDir)
+ }
+
ws := wsclient.New(cfg.StreamdURL, cfg.Token, cfg.AgentID, log.Default())
+ // streamd pushes a capture request when a viewer wakes an on-demand
+ // stream or a scheduled event is about to start. Reacting here is what
+ // makes those responsive instead of up to one poll interval late.
+ ws.OnCapture = func(streamID int64, name, app, channel, reason string) {
+ if cfg.PushedCapturesArePriority() {
+ p.EnqueueNow(streamID, name, app, channel, reason)
+ return
+ }
+ if j, added, err := q.EnqueueIfIdle(streamID, name, app, channel, reason, cfg.MaxAttempts); err != nil {
+ log.Printf("pushed capture for %s failed: %v", name, err)
+ } else if added {
+ log.Printf("enqueued job=%d stream=%s reason=%s (pushed by streamd)", j.ID, name, reason)
+ }
+ }
+ // A stream was edited: re-poll now rather than waiting out the interval.
+ ws.OnStreamChanged = func(name, reason string) {
+ go func() {
+ if err := p.Once(); err != nil {
+ log.Printf("re-poll after change to %s: %v", name, err)
+ }
+ }()
+ }
+ ws.OnModulesChanged = func(name, reason string) {
+ if ms == nil {
+ return
+ }
+ go func() {
+ if err := ms.Once(); err != nil {
+ log.Printf("modules sync after change to %s: %v", name, err)
+ }
+ }()
+ }
go ws.Loop()
for i := 0; i < cfg.Workers; i++ {
@@ -130,6 +246,7 @@ func runCmd(sub string, args []string) {
Python: cfg.Python,
WVD: cfg.WVD,
UserAgent: cfg.UserAgent,
+ JobBackoff: cfg.JobBackoffEnabled(),
Log: log.Default(),
}
go w.Loop(stop)
@@ -150,6 +267,7 @@ func runCmd(sub string, args []string) {
func statusCmd(sub string, args []string) {
cfg, _ := loadCfg(sub, args)
+ printDaemonStatus(cfg)
q := openQueue(cfg)
defer q.Close()
jobs, err := q.ListRecent(40)
@@ -199,7 +317,7 @@ func enqueueCmd(args []string) {
if err != nil {
log.Fatal(err)
}
- api := client.New(cfg.StreamdURL, cfg.Token)
+ api := newAPI(cfg)
streams, err := api.ListStreams()
if err != nil {
log.Fatal(err)
diff --git a/apps/agent/agentcmd/daemon.go b/apps/agent/agentcmd/daemon.go
new file mode 100644
index 0000000..b258c71
--- /dev/null
+++ b/apps/agent/agentcmd/daemon.go
@@ -0,0 +1,177 @@
+package agentcmd
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "streamd/apps/agent/internal/config"
+ "streamd/repo"
+)
+
+func readPID(pidFile string) (int, error) {
+ b, err := os.ReadFile(pidFile)
+ if err != nil {
+ return 0, err
+ }
+ return strconv.Atoi(strings.TrimSpace(string(b)))
+}
+
+func writePID(pidFile string, pid int) error {
+ if err := os.MkdirAll(filepath.Dir(pidFile), 0o755); err != nil {
+ return err
+ }
+ return os.WriteFile(pidFile, []byte(strconv.Itoa(pid)+"\n"), 0o644)
+}
+
+func removePID(pidFile string) { _ = os.Remove(pidFile) }
+
+func runningPID(cfg config.Config) (int, bool) {
+ pid, err := readPID(cfg.PIDFile)
+ if err != nil || pid <= 0 {
+ return 0, false
+ }
+ if !signalAlive(pid) {
+ removePID(cfg.PIDFile)
+ return pid, false
+ }
+ return pid, true
+}
+
+func printDaemonStatus(cfg config.Config) {
+ fmt.Printf("config: %s\n", cfgPathHint(cfg))
+ fmt.Printf("pid: %s\n", cfg.PIDFile)
+ fmt.Printf("log: %s\n", cfg.LogFile)
+ if pid, ok := runningPID(cfg); ok {
+ fmt.Printf("agent: running pid=%d\n", pid)
+ } else {
+ fmt.Println("agent: stopped")
+ }
+}
+
+func cfgPathHint(cfg config.Config) string {
+ // Best-effort: show data dir; exact yaml path was already resolved by Load.
+ return cfg.DataDir
+}
+
+func startDaemonCmd(args []string) error {
+ cfg, cfgFile := loadCfgWithPath("start", args)
+ if pid, ok := runningPID(cfg); ok {
+ fmt.Printf("agent already running (pid %d)\n", pid)
+ return nil
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ return err
+ }
+ if resolved, err := filepath.EvalSymlinks(exe); err == nil {
+ exe = resolved
+ }
+ runArgs := []string{"agent", "run"}
+ if cfgFile != "" {
+ runArgs = append(runArgs, "--config", cfgFile)
+ }
+ cmd := exec.Command(exe, runArgs...)
+ if err := os.MkdirAll(filepath.Dir(cfg.LogFile), 0o755); err != nil {
+ return err
+ }
+ logF, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
+ if err != nil {
+ return err
+ }
+ cmd.Stdout = logF
+ cmd.Stderr = logF
+ cmd.Stdin = nil
+ detachProcess(cmd)
+ if err := cmd.Start(); err != nil {
+ _ = logF.Close()
+ return fmt.Errorf("start agent: %w", err)
+ }
+ pid := cmd.Process.Pid
+ _ = cmd.Process.Release()
+ _ = logF.Close()
+ if err := writePID(cfg.PIDFile, pid); err != nil {
+ return err
+ }
+ time.Sleep(400 * time.Millisecond)
+ if !signalAlive(pid) {
+ removePID(cfg.PIDFile)
+ return fmt.Errorf("agent exited immediately — see %s", cfg.LogFile)
+ }
+ fmt.Printf("agent started pid=%d\n", pid)
+ fmt.Printf("logs: %s\n", cfg.LogFile)
+ return nil
+}
+
+func stopDaemonCmd(args []string) error {
+ cfg, _ := loadCfgWithPath("stop", args)
+ pid, err := readPID(cfg.PIDFile)
+ if err != nil {
+ if os.IsNotExist(err) {
+ fmt.Println("agent is not running")
+ return nil
+ }
+ return err
+ }
+ if !signalAlive(pid) {
+ removePID(cfg.PIDFile)
+ fmt.Println("agent is not running (stale pid file removed)")
+ return nil
+ }
+ if err := signalTerminate(pid); err != nil {
+ return fmt.Errorf("stop pid %d: %w", pid, err)
+ }
+ deadline := time.Now().Add(8 * time.Second)
+ for time.Now().Before(deadline) {
+ if !signalAlive(pid) {
+ removePID(cfg.PIDFile)
+ fmt.Printf("agent stopped (was pid %d)\n", pid)
+ return nil
+ }
+ time.Sleep(200 * time.Millisecond)
+ }
+ _ = signalKill(pid)
+ time.Sleep(200 * time.Millisecond)
+ removePID(cfg.PIDFile)
+ fmt.Printf("agent killed (pid %d)\n", pid)
+ return nil
+}
+
+func restartDaemonCmd(args []string) error {
+ _ = stopDaemonCmd(args)
+ return startDaemonCmd(args)
+}
+
+// loadCfgWithPath returns config and the resolved --config path (may be empty).
+func loadCfgWithPath(sub string, args []string) (config.Config, string) {
+ fs := flag.NewFlagSet(sub, flag.ExitOnError)
+ cfgPath := fs.String("config", "", "path to agent.yaml")
+ _ = fs.Parse(args)
+ path := strings.TrimSpace(*cfgPath)
+ cfg, err := config.Load(path)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "[!]", err)
+ os.Exit(1)
+ }
+ if path == "" {
+ // Mirror config.Load default discovery for daemon child argv.
+ path = defaultConfigPath()
+ } else if !filepath.IsAbs(path) {
+ abs, err := filepath.Abs(path)
+ if err == nil {
+ path = abs
+ }
+ }
+ return cfg, path
+}
+
+// defaultConfigPath matches config.Load("") discovery so the background child
+// reopens the same yaml the parent resolved.
+func defaultConfigPath() string {
+ return filepath.Join(repo.Root(), "apps", "agent", "agent.yaml")
+}
diff --git a/apps/agent/agentcmd/daemon_unix.go b/apps/agent/agentcmd/daemon_unix.go
new file mode 100644
index 0000000..14eb237
--- /dev/null
+++ b/apps/agent/agentcmd/daemon_unix.go
@@ -0,0 +1,37 @@
+//go:build unix
+
+package agentcmd
+
+import (
+ "os"
+ "os/exec"
+ "syscall"
+)
+
+func detachProcess(cmd *exec.Cmd) {
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+}
+
+func signalAlive(pid int) bool {
+ p, err := os.FindProcess(pid)
+ if err != nil {
+ return false
+ }
+ return p.Signal(syscall.Signal(0)) == nil
+}
+
+func signalTerminate(pid int) error {
+ p, err := os.FindProcess(pid)
+ if err != nil {
+ return err
+ }
+ return p.Signal(syscall.SIGTERM)
+}
+
+func signalKill(pid int) error {
+ p, err := os.FindProcess(pid)
+ if err != nil {
+ return err
+ }
+ return p.Signal(syscall.SIGKILL)
+}
diff --git a/apps/agent/agentcmd/daemon_windows.go b/apps/agent/agentcmd/daemon_windows.go
new file mode 100644
index 0000000..ce8e088
--- /dev/null
+++ b/apps/agent/agentcmd/daemon_windows.go
@@ -0,0 +1,46 @@
+//go:build windows
+
+package agentcmd
+
+import (
+ "os"
+ "os/exec"
+ "syscall"
+
+ "golang.org/x/sys/windows"
+)
+
+func detachProcess(cmd *exec.Cmd) {
+ // CREATE_NEW_PROCESS_GROUP so stop can target the child; keep stdio so
+ // stdout/stderr still reach the log file opened by the parent.
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ CreationFlags: windows.CREATE_NEW_PROCESS_GROUP,
+ }
+}
+
+func signalAlive(pid int) bool {
+ // On Windows, FindProcess always succeeds; use OpenProcess exit code instead.
+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
+ if err != nil {
+ return false
+ }
+ defer windows.CloseHandle(h)
+ var code uint32
+ if err := windows.GetExitCodeProcess(h, &code); err != nil {
+ return false
+ }
+ const stillActive = 259 // STILL_ACTIVE
+ return code == stillActive
+}
+
+func signalTerminate(pid int) error {
+ p, err := os.FindProcess(pid)
+ if err != nil {
+ return err
+ }
+ return p.Kill()
+}
+
+func signalKill(pid int) error {
+ return signalTerminate(pid)
+}
diff --git a/apps/agent/agentcmd/update.go b/apps/agent/agentcmd/update.go
new file mode 100644
index 0000000..6b0e04d
--- /dev/null
+++ b/apps/agent/agentcmd/update.go
@@ -0,0 +1,282 @@
+package agentcmd
+
+import (
+ "flag"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "sort"
+ "strings"
+ "time"
+
+ "streamd/apps/agent/internal/config"
+ "streamd/repo"
+)
+
+const (
+ releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
+ defaultChannel = "stable"
+)
+
+// errUpdateDeferred means the binary swap finishes after process exit (Windows self-update).
+var errUpdateDeferred = fmt.Errorf("update deferred until process exit")
+
+func defaultAssetName() string {
+ switch runtime.GOOS {
+ case "linux":
+ switch runtime.GOARCH {
+ case "amd64":
+ return "streamd-linux-amd64"
+ case "arm64":
+ return "streamd-linux-arm64"
+ }
+ case "darwin":
+ switch runtime.GOARCH {
+ case "amd64":
+ return "streamd-darwin-amd64"
+ case "arm64":
+ return "streamd-darwin-arm64"
+ }
+ case "windows":
+ switch runtime.GOARCH {
+ case "amd64":
+ return "streamd-windows-amd64.exe"
+ case "arm64":
+ return "streamd-windows-arm64.exe"
+ }
+ }
+ return ""
+}
+
+func updateURL(base, ref, asset string) string {
+ base = strings.TrimRight(base, "/")
+ return fmt.Sprintf("%s/%s/%s", base, ref, asset)
+}
+
+func updateDaemonCmd(args []string) error {
+ fs := flag.NewFlagSet("update", flag.ExitOnError)
+ cfgPath := fs.String("config", "", "path to agent.yaml")
+ beta := fs.Bool("beta", false, "use beta channel")
+ tag := fs.String("tag", "", "pin to release tag (e.g. v0.2.1)")
+ noRestart := fs.Bool("no-restart", false, "install only; do not start agent")
+ keep := fs.Int("keep", -1, "archived binaries to keep under old/ (-1 = config)")
+ _ = fs.Parse(args)
+
+ path := strings.TrimSpace(*cfgPath)
+ cfg, err := config.Load(path)
+ if err != nil {
+ return err
+ }
+ if path == "" {
+ path = defaultConfigPath()
+ } else if !filepath.IsAbs(path) {
+ if abs, err := filepath.Abs(path); err == nil {
+ path = abs
+ }
+ }
+
+ channel := cfg.Channel
+ if channel == "" {
+ channel = defaultChannel
+ }
+ if *beta {
+ channel = "beta"
+ }
+ ref := channel
+ if strings.TrimSpace(*tag) != "" {
+ ref = strings.TrimSpace(*tag)
+ }
+ asset := cfg.Asset
+ if asset == "" {
+ asset = defaultAssetName()
+ }
+ if asset == "" {
+ return fmt.Errorf("unsupported platform %s/%s — set asset: in agent.yaml", runtime.GOOS, runtime.GOARCH)
+ }
+ keepN := 10
+ if cfg.KeepOld != nil {
+ keepN = *cfg.KeepOld
+ }
+ if *keep >= 0 {
+ keepN = *keep
+ }
+
+ installRoot := repo.Root()
+ url := updateURL(releaseBaseURL, ref, asset)
+ fmt.Printf("agent update: downloading %s\n", url)
+
+ tmp, err := downloadToTemp(installRoot, url)
+ if err != nil {
+ return err
+ }
+ defer os.Remove(tmp)
+
+ if err := smokeTestBinary(tmp); err != nil {
+ return err
+ }
+
+ exe, err := os.Executable()
+ if err != nil {
+ return err
+ }
+ if resolved, err := filepath.EvalSymlinks(exe); err == nil {
+ exe = resolved
+ }
+ target := exe
+ wantName := "streamd"
+ if runtime.GOOS == "windows" {
+ wantName = "streamd.exe"
+ }
+ // Prefer well-known names in the install / Downloads tree.
+ for _, candidate := range []string{
+ filepath.Join(installRoot, wantName),
+ filepath.Join(installRoot, "streamd-windows-amd64.exe"),
+ filepath.Join(installRoot, "streamd-linux-amd64"),
+ filepath.Join(installRoot, "bin", wantName),
+ } {
+ if st, err := os.Stat(candidate); err == nil && !st.IsDir() {
+ target = candidate
+ break
+ }
+ }
+ // If the running exe is already a streamd binary in this tree, prefer it.
+ if strings.Contains(strings.ToLower(filepath.Base(exe)), "streamd") {
+ if st, err := os.Stat(exe); err == nil && !st.IsDir() {
+ target = exe
+ }
+ }
+
+ if _, ok := runningPID(cfg); ok {
+ fmt.Println("agent update: stopping running agent…")
+ if err := stopDaemonCmd([]string{"--config", path}); err != nil {
+ return err
+ }
+ }
+
+ oldDir := filepath.Join(filepath.Dir(target), "old")
+ if err := os.MkdirAll(oldDir, 0o755); err != nil {
+ return err
+ }
+ stamp := time.Now().UTC().Format("20060102T150405Z")
+ archive := filepath.Join(oldDir, "streamd."+stamp)
+ if runtime.GOOS == "windows" {
+ archive += ".exe"
+ }
+ if _, err := os.Stat(archive); err == nil {
+ archive += "." + fmt.Sprint(os.Getpid())
+ }
+
+ if *noRestart {
+ _ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
+ } else {
+ _ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
+ _ = os.Setenv("STREAMD_UPDATE_AGENT_CONFIG", path)
+ }
+ if err := replaceBinary(target, tmp, archive); err != nil {
+ if err == errUpdateDeferred {
+ return nil // helper finishes after exit; treat as success for CLI
+ }
+ return err
+ }
+ fmt.Printf("agent update: archived previous → %s\n", archive)
+ fmt.Printf("agent update: installed %s (%s)\n", target, ref)
+ pruneOldBinaries(oldDir, keepN)
+
+ if *noRestart {
+ fmt.Println("agent update: done (--no-restart). Start with: streamd agent start")
+ return nil
+ }
+ fmt.Println("agent update: starting…")
+ return startDaemonCmd([]string{"--config", path})
+}
+
+func downloadToTemp(dir, url string) (string, error) {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return "", err
+ }
+ f, err := os.CreateTemp(dir, ".streamd-download-*")
+ if err != nil {
+ return "", err
+ }
+ path := f.Name()
+ resp, err := http.Get(url)
+ if err != nil {
+ _ = f.Close()
+ _ = os.Remove(path)
+ return "", err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ _ = f.Close()
+ _ = os.Remove(path)
+ return "", fmt.Errorf("download %s: HTTP %s", url, resp.Status)
+ }
+ n, err := io.Copy(f, resp.Body)
+ closeErr := f.Close()
+ if err != nil {
+ _ = os.Remove(path)
+ return "", err
+ }
+ if closeErr != nil {
+ _ = os.Remove(path)
+ return "", closeErr
+ }
+ if n < 1024 {
+ _ = os.Remove(path)
+ return "", fmt.Errorf("download too small (%d bytes) — check URL %s", n, url)
+ }
+ head, _ := os.ReadFile(path)
+ if len(head) > 32 {
+ h := strings.ToLower(string(head[:32]))
+ if strings.Contains(h, "nul\r\n"+
+ "tasklist /FI \"PID eq %d\" 2>nul | find \"%d\" >nul\r\n"+
+ "if not errorlevel 1 goto wait\r\n"+
+ "move /Y \"%s\" \"%s\"\r\n"+
+ "move /Y \"%s\" \"%s\"\r\n"+
+ "%s"+
+ "del \"%%~f0\"\r\n",
+ pid, pid,
+ escapeCmd(target), escapeCmd(archive),
+ escapeCmd(newPath), escapeCmd(target),
+ startLine,
+ )
+ if err := os.WriteFile(helper, []byte(script), 0o644); err != nil {
+ return err
+ }
+ cmd := exec.Command("cmd.exe", "/C", helper)
+ cmd.Stdout = nil
+ cmd.Stderr = nil
+ detachProcess(cmd)
+ if err := cmd.Start(); err != nil {
+ return fmt.Errorf("start update helper: %w", err)
+ }
+ _ = cmd.Process.Release()
+ fmt.Println("agent update: scheduled file swap after this process exits")
+ fmt.Println("agent update: agent will restart automatically in 1–2s")
+ time.Sleep(300 * time.Millisecond)
+ return errUpdateDeferred
+}
+
+func escapeCmd(p string) string {
+ return p
+}
+
+func sameFile(a, b string) (bool, error) {
+ absA, err := filepath.Abs(a)
+ if err != nil {
+ return false, err
+ }
+ absB, err := filepath.Abs(b)
+ if err != nil {
+ return false, err
+ }
+ return filepath.Clean(absA) == filepath.Clean(absB), nil
+}
+
+func copyFile(src, dst string) error {
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
+ if err != nil {
+ return err
+ }
+ _, copyErr := out.ReadFrom(in)
+ closeErr := out.Close()
+ if copyErr != nil {
+ return copyErr
+ }
+ return closeErr
+}
diff --git a/apps/agent/go.mod b/apps/agent/go.mod
index c3aa50f..c912a7b 100644
--- a/apps/agent/go.mod
+++ b/apps/agent/go.mod
@@ -1,12 +1,12 @@
-module drmdecryption/apps/agent
+module streamd/apps/agent
go 1.25.0
require (
- drmdecryption v0.0.0
github.com/gorilla/websocket v1.5.3
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.34.5
+ streamd v0.0.0
)
require (
@@ -15,11 +15,10 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
- go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
golang.org/x/sys v0.42.0 // indirect
modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.8.0 // indirect
)
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/agent/go.sum b/apps/agent/go.sum
index 5ef9a1c..58f3755 100644
--- a/apps/agent/go.sum
+++ b/apps/agent/go.sum
@@ -1,7 +1,5 @@
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
-github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
-github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -14,8 +12,6 @@ github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdh
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
-go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
-go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -23,8 +19,6 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
-google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
-google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
diff --git a/apps/agent/internal/client/client.go b/apps/agent/internal/client/client.go
index b3050db..ba96c65 100644
--- a/apps/agent/internal/client/client.go
+++ b/apps/agent/internal/client/client.go
@@ -3,42 +3,93 @@ package client
import (
"bytes"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
+ "os"
"strings"
"time"
)
+// Version is reported in the User-Agent so streamd's audit log can tell
+// agent builds apart.
+const Version = "2.0"
+
type Client struct {
- BaseURL string
- Token string
- HTTP *http.Client
- UserAgent string
+ BaseURL string
+ Token string
+ HTTP *http.Client
+ UserAgent string
+ // AgentID is sent as X-Agent-ID so streamd can attribute audit rows to
+ // this agent rather than just to the API key it shares.
+ AgentID string
}
+// ErrUnauthorized is returned when streamd rejects this agent's credential.
+// It is checked by the worker so a bad key does not burn job attempts.
+var ErrUnauthorized = errors.New("unauthorized")
+
func New(baseURL, token string) *Client {
return &Client{
- BaseURL: strings.TrimRight(baseURL, "/"),
- Token: token,
- HTTP: &http.Client{Timeout: 30 * time.Second},
- UserAgent: "drm-agent/1.0",
+ BaseURL: strings.TrimRight(baseURL, "/"),
+ Token: token,
+ HTTP: &http.Client{Timeout: 30 * time.Second},
+ UserAgent: "drm-agent/" + Version,
}
}
+// Stream is one row of GET /api/streams.
+//
+// Note there is no Key field. streamd redacts credentials from this response,
+// and the agent only ever writes keys, never reads them. Decisions that used
+// to be made here by inspecting the key are now made server-side and arrive
+// as NeedsCapture / KeyValid / DRMRequired.
type Stream struct {
ID int64 `json:"id"`
Name string `json:"name"`
Title string `json:"title"`
App string `json:"app"`
Channel string `json:"channel"`
+ Tags string `json:"tags"`
MPD string `json:"mpd"`
- Key string `json:"key"`
Enabled bool `json:"enabled"`
Health string `json:"health"`
LastError string `json:"last_error"`
PlaylistAgeS float64 `json:"playlist_age_s"`
ClaimedBy string `json:"claimed_by"`
+
+ // Credential state, without the credentials.
+ HasKey bool `json:"has_key"`
+ KeyValid bool `json:"key_valid"`
+ DRMRequired bool `json:"drm_required"`
+ // NeedsCapture is streamd's verdict on whether to refresh credentials.
+ // This is the field the poller acts on.
+ NeedsCapture bool `json:"needs_capture"`
+
+ OnDemand bool `json:"on_demand"`
+ Public bool `json:"public"`
+
+ Outputs []Output `json:"outputs"`
+}
+
+// Output is one configured publish format, shown by `agent status`.
+type Output struct {
+ ID string `json:"id"`
+ Label string `json:"label"`
+ Format string `json:"format"`
+ Enabled bool `json:"enabled"`
+}
+
+// EnabledOutputs is a short label list for display, e.g. "HLS, DASH".
+func (s Stream) EnabledOutputs() string {
+ var on []string
+ for _, o := range s.Outputs {
+ if o.Enabled {
+ on = append(on, o.Label)
+ }
+ }
+ return strings.Join(on, ",")
}
type Credentials struct {
@@ -49,11 +100,34 @@ type Credentials struct {
PID string `json:"pid,omitempty"`
}
+// Identity is the answer from GET /api/me.
+type Identity struct {
+ Name string `json:"name"`
+ Role string `json:"role"`
+ ActorKind string `json:"actor_kind"`
+ AgentID string `json:"agent_id,omitempty"`
+}
+
func (c *Client) Health() error {
_, err := c.do(http.MethodGet, "/api/health", nil)
return err
}
+// Me verifies this agent's credential and reports the role it was granted.
+// Called at startup so a missing, wrong or revoked key fails loudly instead
+// of silently failing every poll.
+func (c *Client) Me() (Identity, error) {
+ body, err := c.do(http.MethodGet, "/api/me", nil)
+ if err != nil {
+ return Identity{}, err
+ }
+ var id Identity
+ if err := json.Unmarshal(body, &id); err != nil {
+ return Identity{}, err
+ }
+ return id, nil
+}
+
func (c *Client) ListStreams() ([]Stream, error) {
body, err := c.do(http.MethodGet, "/api/streams", nil)
if err != nil {
@@ -85,6 +159,119 @@ func (c *Client) PostCredentials(id int64, cred Credentials) error {
return err
}
+// Capture event kinds reported back to streamd, so a failing phone capture
+// shows up on the stream's timeline in the dashboard instead of only in this
+// agent's console.
+const (
+ EventCaptureStarted = "capture_started"
+ EventCaptureOK = "capture_ok"
+ EventCaptureFailed = "capture_failed"
+)
+
+// PostEvent records an agent-authored event against a stream. Failures are
+// the caller's to ignore: losing a timeline entry must never fail a capture.
+func (c *Client) PostEvent(streamID int64, kind, message string, detail map[string]any) error {
+ payload := map[string]any{"kind": kind, "message": message}
+ if len(detail) > 0 {
+ payload["detail"] = detail
+ }
+ _, err := c.do(http.MethodPost, fmt.Sprintf("/api/streams/%d/events", streamID), payload)
+ return err
+}
+
+// ModuleInfo is one modules// entry from GET /api/modules.
+type ModuleInfo struct {
+ Name string `json:"name"`
+ HasYAML bool `json:"has_yaml"`
+ YAMLSHA256 string `json:"yaml_sha256,omitempty"`
+ HasPackage bool `json:"has_package"`
+ PackageSHA256 string `json:"package_sha256,omitempty"`
+ Arches []string `json:"arches,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
+}
+
+func (c *Client) ListModules() ([]ModuleInfo, error) {
+ body, err := c.do(http.MethodGet, "/api/modules", nil)
+ if err != nil {
+ return nil, err
+ }
+ var wrap struct {
+ Modules []ModuleInfo `json:"modules"`
+ }
+ if err := json.Unmarshal(body, &wrap); err != nil {
+ return nil, err
+ }
+ return wrap.Modules, nil
+}
+
+// GetModuleYAML downloads raw module.yaml bytes for name.
+func (c *Client) GetModuleYAML(name string) ([]byte, error) {
+ req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/yaml", nil)
+ if err != nil {
+ return nil, err
+ }
+ c.setHeaders(req)
+ resp, err := c.HTTP.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
+ if resp.StatusCode >= 300 {
+ return nil, c.statusError(http.MethodGet, "/api/modules/"+name+"/yaml", resp, body)
+ }
+ return body, nil
+}
+
+// DownloadModulePackage writes the module zip to destPath.
+func (c *Client) DownloadModulePackage(name, destPath string) error {
+ req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/package", nil)
+ if err != nil {
+ return err
+ }
+ c.setHeaders(req)
+ resp, err := c.HTTP.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode >= 300 {
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ return c.statusError(http.MethodGet, "/api/modules/"+name+"/package", resp, body)
+ }
+ tmp := destPath + ".partial"
+ f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
+ if err != nil {
+ return err
+ }
+ _, copyErr := io.Copy(f, io.LimitReader(resp.Body, 100<<20))
+ closeErr := f.Close()
+ if copyErr != nil {
+ _ = os.Remove(tmp)
+ return copyErr
+ }
+ if closeErr != nil {
+ _ = os.Remove(tmp)
+ return closeErr
+ }
+ _ = os.Remove(destPath)
+ return os.Rename(tmp, destPath)
+}
+
+func (c *Client) setHeaders(req *http.Request) {
+ ua := c.UserAgent
+ if ua == "" {
+ ua = "streamd-agent/" + Version
+ }
+ req.Header.Set("User-Agent", ua)
+ if c.Token != "" {
+ req.Header.Set("Authorization", "Bearer "+c.Token)
+ }
+ if c.AgentID != "" {
+ req.Header.Set("X-Agent-ID", c.AgentID)
+ }
+}
+
func (c *Client) do(method, path string, payload any) ([]byte, error) {
var rdr io.Reader
if payload != nil {
@@ -101,18 +288,53 @@ func (c *Client) do(method, path string, payload any) ([]byte, error) {
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
- req.Header.Set("User-Agent", c.UserAgent)
- if c.Token != "" {
- req.Header.Set("Authorization", "Bearer "+c.Token)
- }
+ c.setHeaders(req)
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
- body, _ := io.ReadAll(resp.Body)
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
if resp.StatusCode >= 300 {
- return nil, fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, strings.TrimSpace(string(body)))
+ return nil, c.statusError(method, path, resp, body)
}
return body, nil
}
+
+// statusError turns an HTTP failure into something actionable. A 401 or 403
+// used to surface as a bare status line, which left an operator guessing why
+// a working agent had gone quiet.
+func (c *Client) statusError(method, path string, resp *http.Response, body []byte) error {
+ msg := strings.TrimSpace(string(body))
+ if parsed := errorField(body); parsed != "" {
+ msg = parsed
+ }
+ switch resp.StatusCode {
+ case http.StatusUnauthorized:
+ hint := "streamd rejected this agent's credential"
+ if c.Token == "" {
+ hint = "streamd requires a credential and none is configured"
+ }
+ return fmt.Errorf("%w: %s %s — %s. Set `token:` (or `api_key:`) in apps/agent/agent.yaml, "+
+ "or STREAMD_TOKEN, to an API key created in the streamd dashboard under "+
+ "Settings -> API keys (role: operator). Server said: %s",
+ ErrUnauthorized, method, path, hint, msg)
+ case http.StatusForbidden:
+ return fmt.Errorf("%w: %s %s — this agent's API key lacks the needed role; "+
+ "it must be at least `operator`. Server said: %s", ErrUnauthorized, method, path, msg)
+ case http.StatusTooManyRequests:
+ return fmt.Errorf("%s %s: rate limited by streamd (retry-after %s) — %s",
+ method, path, resp.Header.Get("Retry-After"), msg)
+ }
+ return fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, msg)
+}
+
+func errorField(body []byte) string {
+ var wrap struct {
+ Error string `json:"error"`
+ }
+ if json.Unmarshal(body, &wrap) == nil {
+ return strings.TrimSpace(wrap.Error)
+ }
+ return ""
+}
diff --git a/apps/agent/internal/config/config.go b/apps/agent/internal/config/config.go
index 4e42319..0391f2b 100644
--- a/apps/agent/internal/config/config.go
+++ b/apps/agent/internal/config/config.go
@@ -7,12 +7,16 @@ import (
"gopkg.in/yaml.v3"
- "drmdecryption/repo"
+ "streamd/repo"
)
type Config struct {
- StreamdURL string `yaml:"streamd_url"`
+ StreamdURL string `yaml:"streamd_url"`
+ // Token is this agent's streamd credential. It is now an API key created
+ // in the dashboard (Settings -> API keys, role operator) rather than the
+ // one shared secret; `api_key` is a clearer alias for the same field.
Token string `yaml:"token"`
+ APIKey string `yaml:"api_key"`
PollIntervalSec int `yaml:"poll_interval_sec"`
DataDir string `yaml:"data_dir"`
Workers int `yaml:"workers"`
@@ -23,6 +27,37 @@ type Config struct {
WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch)
UserAgent string `yaml:"user_agent"`
AgentID string `yaml:"agent_id"`
+ // SyncModules pulls modules from streamd into the local cache when missing/stale.
+ SyncModules bool `yaml:"sync_modules"`
+ ModulesDir string `yaml:"modules_dir"` // empty = /modules
+ ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"`
+ ModulesPrune bool `yaml:"modules_prune"` // remove local modules absent from panel
+ // OnDemandPriority lets a capture that streamd pushed — a viewer waking
+ // an on-demand stream, or a scheduled event about to start — jump ahead
+ // of routine refreshes in the queue.
+ OnDemandPriority *bool `yaml:"ondemand_priority"`
+ // JobBackoff enables exponential retry delays after a failed capture
+ // (1m, 2m, 4m, 8m…). Default off — a single agent should retry ASAP.
+ // Set job_backoff: true when several agents share the same streams.
+ JobBackoff *bool `yaml:"job_backoff"`
+ // Daemon / update (streamd agent start|stop|update)
+ LogFile string `yaml:"log_file"` // default agent.log next to config / install root
+ PIDFile string `yaml:"pid_file"` // default agent.pid
+ Channel string `yaml:"channel"` // stable|beta for agent update
+ Asset string `yaml:"asset"` // optional streamd-* asset override
+ KeepOld *int `yaml:"keep_old"` // archived binaries under old/ (default 10)
+}
+
+// PushedCapturesArePriority reports whether pushed captures jump the queue.
+// Defaults to true: somebody is waiting on them.
+func (c Config) PushedCapturesArePriority() bool {
+ return c.OnDemandPriority == nil || *c.OnDemandPriority
+}
+
+// JobBackoffEnabled is the exponential multi-agent retry delay.
+// Defaults to false so a lone agent retries immediately after a failure.
+func (c Config) JobBackoffEnabled() bool {
+ return c.JobBackoff != nil && *c.JobBackoff
}
func (c Config) PollInterval() time.Duration {
@@ -68,9 +103,15 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.StreamdURL == "" {
cfg.StreamdURL = "http://127.0.0.1:8083"
}
+ if cfg.Token == "" {
+ cfg.Token = cfg.APIKey
+ }
if cfg.Token == "" {
cfg.Token = os.Getenv("STREAMD_TOKEN")
}
+ if cfg.Token == "" {
+ cfg.Token = os.Getenv("STREAMD_API_KEY")
+ }
if cfg.PollIntervalSec <= 0 {
cfg.PollIntervalSec = 30
}
@@ -100,5 +141,42 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
cfg.WVD = filepath.Join(root, cfg.WVD)
}
+ if cfg.Python != "" && !filepath.IsAbs(cfg.Python) {
+ cfg.Python = filepath.Join(root, cfg.Python)
+ }
+ if cfg.ModulesDir == "" {
+ cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
+ } else if !filepath.IsAbs(cfg.ModulesDir) {
+ cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir)
+ }
+ if cfg.ModulesSyncIntervalSec <= 0 {
+ cfg.ModulesSyncIntervalSec = 300
+ }
+ if cfg.LogFile == "" {
+ cfg.LogFile = "agent.log"
+ }
+ if !filepath.IsAbs(cfg.LogFile) {
+ cfg.LogFile = filepath.Join(root, cfg.LogFile)
+ }
+ if cfg.PIDFile == "" {
+ cfg.PIDFile = "agent.pid"
+ }
+ if !filepath.IsAbs(cfg.PIDFile) {
+ cfg.PIDFile = filepath.Join(root, cfg.PIDFile)
+ }
+ if cfg.Channel == "" {
+ cfg.Channel = "stable"
+ }
+ if cfg.KeepOld == nil {
+ k := 10
+ cfg.KeepOld = &k
+ }
return cfg
}
+
+func (c Config) ModulesSyncInterval() time.Duration {
+ if c.ModulesSyncIntervalSec <= 0 {
+ return 5 * time.Minute
+ }
+ return time.Duration(c.ModulesSyncIntervalSec) * time.Second
+}
diff --git a/apps/agent/internal/device/pool.go b/apps/agent/internal/device/pool.go
index 1cc2c9f..5d5eab1 100644
--- a/apps/agent/internal/device/pool.go
+++ b/apps/agent/internal/device/pool.go
@@ -4,15 +4,15 @@ import (
"fmt"
"sync"
- "drmdecryption/adb"
+ "streamd/adb"
)
// Pool tracks free/busy ADB devices. Never installs apps.
type Pool struct {
- mu sync.Mutex
- adbBin string
- allow map[string]bool // empty allow = all serials
- busy map[string]string // serial → job label
+ mu sync.Mutex
+ adbBin string
+ allow map[string]bool // empty allow = all serials
+ busy map[string]string // serial → job label
}
func New(adbBin string, allowlist []string) *Pool {
diff --git a/apps/agent/internal/modsync/sync.go b/apps/agent/internal/modsync/sync.go
new file mode 100644
index 0000000..5fa3c0d
--- /dev/null
+++ b/apps/agent/internal/modsync/sync.go
@@ -0,0 +1,377 @@
+// Package modsync pulls provider modules from streamd into a local cache.
+// The panel is the source of truth: agents download package.zip when the
+// package hash changes, and module.yaml alone when only YAML changed.
+package modsync
+
+import (
+ "archive/zip"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "streamd/apps/agent/internal/client"
+ "streamd/modhost"
+ "streamd/repo"
+)
+
+// Syncer keeps the local modules cache aligned with streamd.
+type Syncer struct {
+ API *client.Client
+ ModulesDir string // empty = /modules resolved by caller, or modhost default
+ Interval time.Duration
+ Prune bool // remove local modules absent from the panel
+ Log *log.Logger
+}
+
+func (s *Syncer) modulesDir() string {
+ if strings.TrimSpace(s.ModulesDir) != "" {
+ return s.ModulesDir
+ }
+ return modhost.ModulesDir(repo.Root())
+}
+
+// Once pulls every remote module that is missing or stale locally.
+func (s *Syncer) Once() error {
+ dir := s.modulesDir()
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+
+ remote, err := s.API.ListModules()
+ if err != nil {
+ return err
+ }
+ seen := map[string]struct{}{}
+ for _, m := range remote {
+ seen[m.Name] = struct{}{}
+ if err := s.syncOne(dir, m); err != nil {
+ s.logf("modules sync: %s: %v", m.Name, err)
+ continue
+ }
+ }
+ if s.Prune {
+ s.pruneLocal(dir, seen)
+ }
+ return nil
+}
+
+func (s *Syncer) syncOne(dir string, m client.ModuleInfo) error {
+ modDir := filepath.Join(dir, m.Name)
+ localPkg := localSHA(filepath.Join(modDir, "package.sha256"))
+ localYAML := ""
+ if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
+ sum := sha256.Sum256(raw)
+ localYAML = hex.EncodeToString(sum[:])
+ }
+
+ needPackage := m.HasPackage && (localPkg == "" || !strings.EqualFold(localPkg, m.PackageSHA256))
+ needYAML := m.HasYAML && (localYAML == "" || !strings.EqualFold(localYAML, m.YAMLSHA256))
+
+ if !needPackage && !needYAML {
+ return nil
+ }
+
+ if needPackage {
+ if !m.HasPackage {
+ return fmt.Errorf("panel has no package.zip")
+ }
+ if err := s.pullPackage(modDir, m); err != nil {
+ return err
+ }
+ s.logf("modules sync: pulled package %s", m.Name)
+ // Package extract includes yaml; refresh localYAML check.
+ if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
+ sum := sha256.Sum256(raw)
+ localYAML = hex.EncodeToString(sum[:])
+ needYAML = m.HasYAML && !strings.EqualFold(localYAML, m.YAMLSHA256)
+ } else {
+ needYAML = m.HasYAML
+ }
+ }
+
+ if needYAML {
+ raw, err := s.API.GetModuleYAML(m.Name)
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(modDir, 0o755); err != nil {
+ return err
+ }
+ if err := atomicWrite(filepath.Join(modDir, "module.yaml"), raw, 0o644); err != nil {
+ return err
+ }
+ s.logf("modules sync: updated yaml %s", m.Name)
+ }
+ return nil
+}
+
+func (s *Syncer) pullPackage(modDir string, m client.ModuleInfo) error {
+ if err := os.MkdirAll(modDir, 0o755); err != nil {
+ return err
+ }
+ zipPath := filepath.Join(modDir, "package.zip")
+ if err := s.API.DownloadModulePackage(m.Name, zipPath); err != nil {
+ return err
+ }
+ sum, err := fileSHA256(zipPath)
+ if err != nil {
+ return err
+ }
+ if m.PackageSHA256 != "" && !strings.EqualFold(sum, m.PackageSHA256) {
+ return fmt.Errorf("package sha mismatch: got %s want %s", sum, m.PackageSHA256)
+ }
+
+ extractDir := filepath.Join(modDir, ".extract-tmp")
+ _ = os.RemoveAll(extractDir)
+ if err := os.MkdirAll(extractDir, 0o755); err != nil {
+ return err
+ }
+ defer os.RemoveAll(extractDir)
+
+ if err := unzipSafe(zipPath, extractDir); err != nil {
+ return err
+ }
+ // Flatten a single top-level folder (bbc/...) into extractDir root.
+ if err := flattenSingleRoot(extractDir); err != nil {
+ return err
+ }
+ if err := promoteHostBinary(extractDir, m.Name); err != nil {
+ return err
+ }
+
+ // Move extracted contents into modDir (keep package.zip + sha sidecar).
+ ents, err := os.ReadDir(extractDir)
+ if err != nil {
+ return err
+ }
+ for _, e := range ents {
+ src := filepath.Join(extractDir, e.Name())
+ dst := filepath.Join(modDir, e.Name())
+ _ = os.RemoveAll(dst)
+ if err := os.Rename(src, dst); err != nil {
+ return err
+ }
+ }
+ return atomicWrite(filepath.Join(modDir, "package.sha256"), []byte(sum+"\n"), 0o644)
+}
+
+func (s *Syncer) pruneLocal(dir string, keep map[string]struct{}) {
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ return
+ }
+ for _, e := range ents {
+ if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
+ continue
+ }
+ if _, ok := keep[e.Name()]; ok {
+ continue
+ }
+ path := filepath.Join(dir, e.Name())
+ if err := os.RemoveAll(path); err != nil {
+ s.logf("modules sync: prune %s: %v", e.Name(), err)
+ continue
+ }
+ s.logf("modules sync: pruned %s", e.Name())
+ }
+}
+
+// Loop runs Once immediately, then on Interval until stop closes.
+func (s *Syncer) Loop(stop <-chan struct{}) {
+ interval := s.Interval
+ if interval <= 0 {
+ interval = 5 * time.Minute
+ }
+ _ = s.runLogged()
+ t := time.NewTicker(interval)
+ defer t.Stop()
+ for {
+ select {
+ case <-stop:
+ return
+ case <-t.C:
+ _ = s.runLogged()
+ }
+ }
+}
+
+func (s *Syncer) runLogged() error {
+ if err := s.Once(); err != nil {
+ s.logf("modules sync error: %v", err)
+ return err
+ }
+ return nil
+}
+
+func (s *Syncer) logf(format string, args ...any) {
+ if s.Log != nil {
+ s.Log.Printf(format, args...)
+ return
+ }
+ log.Printf(format, args...)
+}
+
+func localSHA(path string) string {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(b))
+}
+
+func fileSHA256(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+func atomicWrite(path string, data []byte, mode os.FileMode) error {
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, data, mode); err != nil {
+ return err
+ }
+ if err := os.Rename(tmp, path); err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ return nil
+}
+
+func unzipSafe(zipPath, destDir string) error {
+ r, err := zip.OpenReader(zipPath)
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ absDest, err := filepath.Abs(destDir)
+ if err != nil {
+ return err
+ }
+ for _, f := range r.File {
+ name := strings.ReplaceAll(f.Name, "\\", "/")
+ name = strings.TrimPrefix(name, "./")
+ if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
+ continue
+ }
+ if strings.Contains(name, "..") {
+ return fmt.Errorf("zip slip: %s", f.Name)
+ }
+ target := filepath.Join(destDir, filepath.FromSlash(name))
+ absTarget, err := filepath.Abs(target)
+ if err != nil {
+ return err
+ }
+ rel, err := filepath.Rel(absDest, absTarget)
+ if err != nil || strings.HasPrefix(rel, "..") {
+ return fmt.Errorf("zip slip: %s", f.Name)
+ }
+ if f.FileInfo().IsDir() || strings.HasSuffix(name, "/") {
+ if err := os.MkdirAll(target, 0o755); err != nil {
+ return err
+ }
+ continue
+ }
+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+ return err
+ }
+ rc, err := f.Open()
+ if err != nil {
+ return err
+ }
+ mode := os.FileMode(0o644)
+ if f.Mode()&0o111 != 0 {
+ mode = 0o755
+ }
+ out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
+ if err != nil {
+ _ = rc.Close()
+ return err
+ }
+ _, copyErr := io.Copy(out, rc)
+ _ = out.Close()
+ _ = rc.Close()
+ if copyErr != nil {
+ return copyErr
+ }
+ }
+ return nil
+}
+
+func flattenSingleRoot(dir string) error {
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ return err
+ }
+ var dirs []os.DirEntry
+ var files []os.DirEntry
+ for _, e := range ents {
+ if strings.HasPrefix(e.Name(), ".") {
+ continue
+ }
+ if e.IsDir() {
+ dirs = append(dirs, e)
+ } else {
+ files = append(files, e)
+ }
+ }
+ if len(files) > 0 || len(dirs) != 1 {
+ return nil
+ }
+ root := filepath.Join(dir, dirs[0].Name())
+ inner, err := os.ReadDir(root)
+ if err != nil {
+ return err
+ }
+ for _, e := range inner {
+ src := filepath.Join(root, e.Name())
+ dst := filepath.Join(dir, e.Name())
+ if err := os.Rename(src, dst); err != nil {
+ return err
+ }
+ }
+ return os.RemoveAll(root)
+}
+
+func promoteHostBinary(modDir, name string) error {
+ want := name
+ if runtime.GOOS == "windows" {
+ want += ".exe"
+ }
+ dest := filepath.Join(modDir, ".bin", want)
+ if st, err := os.Stat(dest); err == nil && !st.IsDir() {
+ return nil
+ }
+ src := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH, want)
+ in, err := os.Open(src)
+ if err != nil {
+ return nil // soft: host arch may be missing
+ }
+ defer in.Close()
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ return err
+ }
+ out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
+ if err != nil {
+ return err
+ }
+ _, copyErr := io.Copy(out, in)
+ closeErr := out.Close()
+ if copyErr != nil {
+ return copyErr
+ }
+ return closeErr
+}
diff --git a/apps/agent/internal/modsync/sync_test.go b/apps/agent/internal/modsync/sync_test.go
new file mode 100644
index 0000000..0e5c3bd
--- /dev/null
+++ b/apps/agent/internal/modsync/sync_test.go
@@ -0,0 +1,154 @@
+package modsync
+
+import (
+ "archive/zip"
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ "streamd/apps/agent/internal/client"
+)
+
+func TestPullPackageThenYAMLOnly(t *testing.T) {
+ arch := runtime.GOOS + "-" + runtime.GOARCH
+ binName := "demo"
+ if runtime.GOOS == "windows" {
+ binName += ".exe"
+ }
+ zip1 := mustZip(t, map[string][]byte{
+ "module.yaml": []byte("package: a\n"),
+ ".bin/" + arch + "/" + binName: []byte("bin-v1"),
+ })
+ sum1 := sha256.Sum256(zip1)
+ pkgSHA1 := hex.EncodeToString(sum1[:])
+ yaml1SHA := sha256Hex([]byte("package: a\n"))
+
+ zip2 := mustZip(t, map[string][]byte{
+ "module.yaml": []byte("package: a\n"),
+ ".bin/" + arch + "/" + binName: []byte("bin-v2"),
+ })
+ sum2 := sha256.Sum256(zip2)
+ pkgSHA2 := hex.EncodeToString(sum2[:])
+
+ yamlEdited := []byte("package: a\nchannels: {}\n")
+ yamlEditedSHA := sha256Hex(yamlEdited)
+
+ state := struct {
+ pkg []byte
+ pkgSHA string
+ yaml []byte
+ yamlSHA string
+ }{pkg: zip1, pkgSHA: pkgSHA1, yaml: []byte("package: a\n"), yamlSHA: yaml1SHA}
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/api/modules" && r.Method == http.MethodGet:
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "modules": []map[string]any{{
+ "name": "demo",
+ "has_yaml": true,
+ "yaml_sha256": state.yamlSHA,
+ "has_package": true,
+ "package_sha256": state.pkgSHA,
+ }},
+ })
+ case r.URL.Path == "/api/modules/demo/package":
+ w.Header().Set("Content-Type", "application/zip")
+ _, _ = w.Write(state.pkg)
+ case r.URL.Path == "/api/modules/demo/yaml":
+ w.Header().Set("Content-Type", "text/yaml")
+ _, _ = w.Write(state.yaml)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ dir := t.TempDir()
+ api := &client.Client{BaseURL: srv.URL, HTTP: srv.Client()}
+ s := &Syncer{API: api, ModulesDir: dir}
+
+ if err := s.Once(); err != nil {
+ t.Fatalf("first sync: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "demo", "module.yaml")); err != nil {
+ t.Fatal(err)
+ }
+ promoted := filepath.Join(dir, "demo", ".bin", binName)
+ if b, err := os.ReadFile(promoted); err != nil || string(b) != "bin-v1" {
+ t.Fatalf("promoted binary: %v %q", err, b)
+ }
+
+ // YAML-only change on panel.
+ state.yaml = yamlEdited
+ state.yamlSHA = yamlEditedSHA
+ if err := s.Once(); err != nil {
+ t.Fatalf("yaml sync: %v", err)
+ }
+ raw, _ := os.ReadFile(filepath.Join(dir, "demo", "module.yaml"))
+ if !bytes.Equal(raw, yamlEdited) {
+ t.Fatalf("yaml not updated: %s", raw)
+ }
+ if b, _ := os.ReadFile(promoted); string(b) != "bin-v1" {
+ t.Fatalf("binary should be unchanged after yaml-only sync, got %q", b)
+ }
+
+ // Package change.
+ state.pkg = zip2
+ state.pkgSHA = pkgSHA2
+ state.yaml = []byte("package: a\n")
+ state.yamlSHA = yaml1SHA
+ if err := s.Once(); err != nil {
+ t.Fatalf("package sync: %v", err)
+ }
+ if b, _ := os.ReadFile(promoted); string(b) != "bin-v2" {
+ t.Fatalf("binary not updated: %q", b)
+ }
+}
+
+func mustZip(t *testing.T, files map[string][]byte) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ for name, body := range files {
+ w, err := zw.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Write(body); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func sha256Hex(b []byte) string {
+ sum := sha256.Sum256(b)
+ return hex.EncodeToString(sum[:])
+}
+
+func TestUnzipSlip(t *testing.T) {
+ dir := t.TempDir()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ w, _ := zw.Create("../evil")
+ _, _ = w.Write([]byte("x"))
+ _ = zw.Close()
+ zipPath := filepath.Join(dir, "bad.zip")
+ _ = os.WriteFile(zipPath, buf.Bytes(), 0o644)
+ err := unzipSafe(zipPath, filepath.Join(dir, "out"))
+ if err == nil || !strings.Contains(err.Error(), "slip") {
+ t.Fatalf("want zip slip error, got %v", err)
+ }
+}
diff --git a/apps/agent/internal/poller/poller.go b/apps/agent/internal/poller/poller.go
index 870b8df..5195e87 100644
--- a/apps/agent/internal/poller/poller.go
+++ b/apps/agent/internal/poller/poller.go
@@ -6,8 +6,8 @@ import (
"strings"
"time"
- "drmdecryption/apps/agent/internal/client"
- "drmdecryption/apps/agent/internal/queue"
+ "streamd/apps/agent/internal/client"
+ "streamd/apps/agent/internal/queue"
)
type Poller struct {
@@ -51,6 +51,27 @@ func (p *Poller) Once() error {
return nil
}
+// EnqueueNow is the entry point for a capture streamd has pushed over the
+// websocket, for a viewer waking an on-demand stream or a scheduled event
+// about to start. It jumps ahead of routine refreshes because somebody is
+// waiting on it.
+func (p *Poller) EnqueueNow(streamID int64, name, app, channel, reason string) {
+ if reason == "" {
+ reason = "requested"
+ }
+ j, added, err := p.Queue.EnqueueIfIdlePriority(
+ streamID, name, app, channel, reason, p.MaxAttempts, queue.PriorityInteractive)
+ switch {
+ case err != nil:
+ p.logf("push capture for stream %s failed: %v", name, err)
+ case added:
+ p.logf("enqueued job=%d stream=%s reason=%s (pushed by streamd, priority)", j.ID, name, reason)
+ default:
+ // Already queued or running: EnqueueIfIdlePriority promoted it.
+ p.logf("push capture for stream %s: a job is already pending (promoted)", name)
+ }
+}
+
func (p *Poller) Loop(stop <-chan struct{}) {
t := time.NewTicker(p.Interval)
defer t.Stop()
@@ -67,11 +88,24 @@ func (p *Poller) Loop(stop <-chan struct{}) {
}
}
+// needsRefresh decides whether a stream wants fresh credentials.
+//
+// The verdict comes from streamd, not from inspecting the key: credentials are
+// redacted out of the stream list, so a local "is the key empty?" test would
+// see every stream as broken and queue a capture for all of them forever.
+// streamd also knows things this agent does not — whether the stream is clear
+// rather than encrypted, whether it is an idle on-demand stream, and whether
+// it is still inside its start-up window.
func needsRefresh(st client.Stream) string {
- if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
- return "missing_credentials"
+ if !st.NeedsCapture {
+ return ""
}
- if !validKeyPair(st.Key) {
+ switch {
+ case strings.TrimSpace(st.MPD) == "":
+ return "missing_credentials"
+ case st.DRMRequired && !st.HasKey:
+ return "missing_credentials"
+ case st.DRMRequired && !st.KeyValid:
return "invalid_credentials"
}
h := strings.ToLower(strings.TrimSpace(st.Health))
@@ -79,27 +113,44 @@ func needsRefresh(st client.Stream) string {
case "down", "error", "failed":
return "down"
}
- return ""
+ return "stale"
}
-// validKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID ignored).
-func validKeyPair(key string) bool {
- parts := strings.SplitN(strings.TrimSpace(key), ":", 2)
- if len(parts) != 2 {
- return false
- }
- hexOnly := func(s string) string {
- var b strings.Builder
- for _, r := range s {
- switch {
- case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
- b.WriteRune(r)
- }
+// ValidKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID
+// ignored). The authoritative check lives in streamd; this copy exists only
+// to sanity-check what a worker is about to POST.
+func ValidKeyPair(key string) bool {
+ for _, line := range splitKeyLines(key) {
+ kid, k, ok := strings.Cut(line, ":")
+ if !ok || len(hexOnly(kid)) != 32 || len(hexOnly(k)) != 32 {
+ return false
}
- return b.String()
}
- kid, k := hexOnly(parts[0]), hexOnly(parts[1])
- return len(kid) == 32 && len(k) == 32
+ return len(splitKeyLines(key)) > 0
+}
+
+// splitKeyLines mirrors how streamd and the packager split a key field, so a
+// multi-KID capture is not mistaken for a malformed one.
+func splitKeyLines(raw string) []string {
+ raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
+ var out []string
+ for _, line := range strings.Split(raw, "\n") {
+ if line = strings.TrimSpace(line); line != "" {
+ out = append(out, line)
+ }
+ }
+ return out
+}
+
+func hexOnly(s string) string {
+ var b strings.Builder
+ for _, r := range s {
+ switch {
+ case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
}
func (p *Poller) logf(format string, args ...any) {
diff --git a/apps/agent/internal/queue/queue.go b/apps/agent/internal/queue/queue.go
index fbe65c4..04a44b0 100644
--- a/apps/agent/internal/queue/queue.go
+++ b/apps/agent/internal/queue/queue.go
@@ -2,6 +2,7 @@ package queue
import (
"database/sql"
+ "errors"
"fmt"
"os"
"path/filepath"
@@ -100,24 +101,56 @@ func parseTime(s string) time.Time {
return t
}
-// EnqueueIfIdle inserts a job unless one is already queued/running for the stream.
+// Job priorities. ClaimNext orders by priority ascending, so a lower number
+// runs sooner.
+const (
+ // PriorityInteractive is for a capture a viewer or a schedule is actively
+ // waiting on, pushed by streamd over the agent websocket.
+ PriorityInteractive = 10
+ // PriorityRoutine is a background refresh found by polling.
+ PriorityRoutine = 100
+)
+
+// EnqueueIfIdle inserts a routine job unless one is already queued/running
+// for the stream.
func (s *Store) EnqueueIfIdle(streamID int64, name, app, channel, reason string, maxAttempts int) (Job, bool, error) {
- var existing int
+ return s.EnqueueIfIdlePriority(streamID, name, app, channel, reason, maxAttempts, PriorityRoutine)
+}
+
+// EnqueueIfIdlePriority is EnqueueIfIdle with an explicit priority. A job that
+// someone is waiting on is enqueued ahead of routine refreshes; if a routine
+// job for the same stream is already queued, its priority is raised instead of
+// adding a duplicate.
+func (s *Store) EnqueueIfIdlePriority(streamID int64, name, app, channel, reason string, maxAttempts, priority int) (Job, bool, error) {
+ var existingID int64
+ var existingPriority int
err := s.DB.QueryRow(`
-SELECT COUNT(1) FROM jobs WHERE stream_id=? AND status IN ('queued','running')`, streamID).Scan(&existing)
- if err != nil {
- return Job{}, false, err
- }
- if existing > 0 {
+SELECT id, priority FROM jobs
+WHERE stream_id=? AND status IN ('queued','running')
+ORDER BY id LIMIT 1`, streamID).Scan(&existingID, &existingPriority)
+ switch {
+ case err == nil:
+ // Already pending. Promote it when this request is more urgent, and
+ // clear any backoff so it runs now rather than after the delay.
+ if priority < existingPriority {
+ _, _ = s.DB.Exec(
+ `UPDATE jobs SET priority=?, reason=?, not_before='' WHERE id=? AND status='queued'`,
+ priority, reason, existingID)
+ }
return Job{}, false, nil
+ case !errors.Is(err, sql.ErrNoRows):
+ return Job{}, false, err
}
if maxAttempts <= 0 {
maxAttempts = 5
}
+ if priority <= 0 {
+ priority = PriorityRoutine
+ }
res, err := s.DB.Exec(`
INSERT INTO jobs(stream_id,stream_name,app,channel,reason,status,priority,attempts,max_attempts,created_at,not_before)
-VALUES(?,?,?,?,?,'queued',100,0,?,?,?)`,
- streamID, name, app, channel, reason, maxAttempts, now(), now())
+VALUES(?,?,?,?,?,'queued',?,0,?,?,?)`,
+ streamID, name, app, channel, reason, priority, maxAttempts, now(), now())
if err != nil {
return Job{}, false, err
}
@@ -199,17 +232,18 @@ func (s *Store) MarkOK(id int64) error {
return err
}
-// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
+// MarkFailed increments attempts. Re-queues unless maxed out.
// waitingDevice=true keeps status queued without burning an attempt.
-func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
+// backoff is how long to wait before the job is runnable again (0 = immediate).
+func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error {
j, err := s.Get(id)
if err != nil {
return err
}
if waitingDevice {
_, err = s.DB.Exec(`
-UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`,
- msg, id)
+UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
+ msg, now(), id)
return err
}
attempts := j.Attempts + 1
@@ -219,9 +253,8 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
attempts, msg, now(), id)
return err
}
- backoff := time.Duration(1< 15*time.Minute {
- backoff = 15 * time.Minute
+ if backoff < 0 {
+ backoff = 0
}
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
_, err = s.DB.Exec(`
@@ -230,6 +263,29 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
return err
}
+// ExponentialBackoff is the old multi-agent delay: 1m, 2m, 4m, 8m (cap 15m).
+func ExponentialBackoff(attempts int) time.Duration {
+ if attempts < 1 {
+ attempts = 1
+ }
+ d := time.Duration(1< 15*time.Minute {
+ d = 15 * time.Minute
+ }
+ return d
+}
+
+// ClearAllBackoffs makes every queued job runnable now (e.g. agent restart
+// after fixing modules, or when job_backoff is disabled).
+func (s *Store) ClearAllBackoffs() (int, error) {
+ res, err := s.DB.Exec(`UPDATE jobs SET not_before=? WHERE status='queued'`, now())
+ if err != nil {
+ return 0, err
+ }
+ n, _ := res.RowsAffected()
+ return int(n), nil
+}
+
func min(a, b int) int {
if a < b {
return a
diff --git a/apps/agent/internal/worker/worker.go b/apps/agent/internal/worker/worker.go
index aab00e6..c399bd6 100644
--- a/apps/agent/internal/worker/worker.go
+++ b/apps/agent/internal/worker/worker.go
@@ -1,18 +1,20 @@
package worker
import (
+ "errors"
"fmt"
"log"
"strings"
"time"
- "drmdecryption/modhost"
- "drmdecryption/phonecap"
- "drmdecryption/repo"
+ "streamd/modhost"
+ "streamd/phonecap"
+ "streamd/repo"
- "drmdecryption/apps/agent/internal/client"
- "drmdecryption/apps/agent/internal/device"
- "drmdecryption/apps/agent/internal/queue"
+ "streamd/apps/agent/internal/client"
+ "streamd/apps/agent/internal/device"
+ "streamd/apps/agent/internal/poller"
+ "streamd/apps/agent/internal/queue"
)
type Worker struct {
@@ -25,7 +27,10 @@ type Worker struct {
Python string
WVD string
UserAgent string
- Log *log.Logger
+ // JobBackoff enables exponential delays between failed capture attempts.
+ // When false (default), failed jobs are re-queued immediately.
+ JobBackoff bool
+ Log *log.Logger
lastDelayLog time.Time
}
@@ -65,11 +70,18 @@ func (w *Worker) tick() {
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
// Config/environment issues — do not burn attempts or multi-minute backoff.
w.logf("job=%d waiting: %v", job.ID, err)
- _ = w.Queue.MarkFailed(job.ID, err.Error(), true)
+ _ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
return
}
w.logf("job=%d failed: %v", job.ID, err)
- _ = w.Queue.MarkFailed(job.ID, err.Error(), false)
+ w.event(job, client.EventCaptureFailed, err.Error(),
+ map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
+ backoff := time.Duration(0)
+ if w.JobBackoff {
+ backoff = queue.ExponentialBackoff(job.Attempts + 1)
+ w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff)
+ }
+ _ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff)
return
}
_ = w.Queue.MarkOK(job.ID)
@@ -80,6 +92,11 @@ func isAuthErr(err error) bool {
if err == nil {
return false
}
+ // The client now returns a typed error with an actionable message; the
+ // substring check stays as a fallback for errors raised elsewhere.
+ if errors.Is(err, client.ErrUnauthorized) {
+ return true
+ }
s := strings.ToLower(err.Error())
return strings.Contains(s, "401") || strings.Contains(s, "unauthorized")
}
@@ -98,6 +115,10 @@ func (w *Worker) runJob(job queue.Job) error {
return err
}
label := fmt.Sprintf("job-%d:%s", job.ID, job.StreamName)
+ // Tell streamd a capture is under way, so the stream's timeline in the
+ // dashboard shows it rather than just an unexplained "down".
+ w.event(job, client.EventCaptureStarted,
+ fmt.Sprintf("capture started on %s (%s)", w.AgentID, job.Reason), nil)
c, serial, err := w.Pool.Acquire(a.Package(), label)
if err != nil {
return err
@@ -106,8 +127,8 @@ func (w *Worker) runJob(job queue.Job) error {
_ = w.Queue.SetDevice(job.ID, serial)
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
- // Short TTL; /ws/agent heartbeats renew while this process is alive.
- if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
+ // Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
+ if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
return fmt.Errorf("streamd claim: %w", err)
}
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
@@ -127,6 +148,19 @@ func (w *Worker) runJob(job queue.Job) error {
return err
}
+ needsKeys := true
+ if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" {
+ needsKeys = false
+ }
+ hasKey := poller.ValidKeyPair(res.Key)
+ if needsKeys && !hasKey {
+ return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)",
+ trimURL(res.MPD), strings.TrimSpace(res.Key) == "")
+ }
+ if strings.TrimSpace(res.MPD) == "" {
+ return fmt.Errorf("refusing to post credentials without mpd")
+ }
+
cred := client.Credentials{
MPD: res.MPD,
Key: res.Key,
@@ -137,9 +171,41 @@ func (w *Worker) runJob(job queue.Job) error {
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
return fmt.Errorf("post credentials: %w", err)
}
+ w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s",
+ job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD))
+ // Report what was captured, never the key itself.
+ w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
+ "device": serial,
+ "has_key": strings.TrimSpace(res.Key) != "",
+ "key_valid": hasKey,
+ })
return nil
}
+func trimURL(s string) string {
+ s = strings.TrimSpace(s)
+ if len(s) <= 96 {
+ return s
+ }
+ return s[:96] + "…"
+}
+
+// event posts a stream event to streamd. A timeline entry is never worth
+// failing a capture over, so errors are logged and dropped.
+func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {
+ if w.API == nil || job.StreamID == 0 {
+ return
+ }
+ if detail == nil {
+ detail = map[string]any{}
+ }
+ detail["agent_id"] = w.AgentID
+ detail["job_id"] = job.ID
+ if err := w.API.PostEvent(job.StreamID, kind, message, detail); err != nil {
+ w.logf("job=%d: could not report %s to streamd: %v", job.ID, kind, err)
+ }
+}
+
func (w *Worker) logf(format string, args ...any) {
prefix := fmt.Sprintf("worker/%d: ", w.ID)
if w.Log != nil {
diff --git a/apps/agent/internal/wsclient/wsclient.go b/apps/agent/internal/wsclient/wsclient.go
index aec0cd9..b37ac6c 100644
--- a/apps/agent/internal/wsclient/wsclient.go
+++ b/apps/agent/internal/wsclient/wsclient.go
@@ -10,16 +10,42 @@ import (
"time"
"github.com/gorilla/websocket"
+
+ "streamd/apps/agent/internal/client"
)
+// Message is one push from streamd.
+type Message struct {
+ Type string `json:"type"`
+ OK bool `json:"ok"`
+ Error string `json:"error"`
+ Message string `json:"message"`
+ StreamID int64 `json:"stream_id"`
+ StreamName string `json:"stream_name"`
+ App string `json:"app"`
+ Channel string `json:"channel"`
+ Reason string `json:"reason"`
+}
+
// Client keeps a streamd /ws/agent connection alive and sends heartbeats
// so claims auto-renew; on disconnect streamd releases this agent's claims.
+// It also carries pushes from streamd: a capture a viewer or a schedule is
+// waiting on, which would otherwise not be noticed until the next poll.
type Client struct {
BaseURL string
Token string
AgentID string
Log *log.Logger
+ // OnCapture is called when streamd asks for credentials now.
+ OnCapture func(streamID int64, name, app, channel, reason string)
+ // OnStreamChanged is called when a stream was edited, so the agent can
+ // re-poll instead of waiting out its interval.
+ OnStreamChanged func(name, reason string)
+ // OnModulesChanged is called when the panel uploaded/edited/deleted a
+ // module, so the agent can pull without waiting for the sync interval.
+ OnModulesChanged func(name, reason string)
+
stop chan struct{}
}
@@ -47,7 +73,8 @@ func (c *Client) Loop() {
return
default:
}
- if err := c.session(); err != nil {
+ err := c.session()
+ if err != nil {
c.Log.Printf("ws: session ended: %v — retry in %s", err, backoff)
}
select {
@@ -75,18 +102,29 @@ func (c *Client) session() error {
u.Path = "/ws/agent"
q := u.Query()
q.Set("agent_id", c.AgentID)
- if c.Token != "" {
- q.Set("token", c.Token)
- }
+ // The token is deliberately NOT put in the query string. It used to be,
+ // which wrote the shared secret into every reverse proxy access log.
+ // streamd authenticates the handshake from the Authorization header below.
u.RawQuery = q.Encode()
hdr := http.Header{}
if c.Token != "" {
hdr.Set("Authorization", "Bearer "+c.Token)
}
+ if c.AgentID != "" {
+ hdr.Set("X-Agent-ID", c.AgentID)
+ }
+ hdr.Set("User-Agent", "streamd-agent/"+client.Version)
dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
- conn, _, err := dialer.Dial(u.String(), hdr)
+ conn, resp, err := dialer.Dial(u.String(), hdr)
if err != nil {
+ if resp != nil {
+ switch resp.StatusCode {
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return fmt.Errorf("dial: %w (streamd rejected this agent's API key for /ws/agent; "+
+ "it needs at least the operator role)", err)
+ }
+ }
return fmt.Errorf("dial: %w", err)
}
defer conn.Close()
@@ -107,14 +145,11 @@ func (c *Client) session() error {
return
}
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
- var msg map[string]any
- if json.Unmarshal(data, &msg) == nil {
- if t, _ := msg["type"].(string); t == "heartbeat_ack" {
- if ok, _ := msg["ok"].(bool); !ok {
- c.Log.Printf("ws: heartbeat nack: %v", msg["error"])
- }
- }
+ var msg Message
+ if json.Unmarshal(data, &msg) != nil {
+ continue
}
+ c.handle(msg)
}
}()
@@ -139,6 +174,33 @@ func (c *Client) session() error {
}
}
+func (c *Client) handle(msg Message) {
+ switch strings.ToLower(msg.Type) {
+ case "heartbeat_ack":
+ if !msg.OK {
+ c.Log.Printf("ws: heartbeat nack: %s", msg.Error)
+ }
+ case "capture_requested":
+ if msg.StreamID == 0 {
+ return
+ }
+ c.Log.Printf("ws: streamd requested a capture for stream=%s reason=%s",
+ msg.StreamName, msg.Reason)
+ if c.OnCapture != nil {
+ c.OnCapture(msg.StreamID, msg.StreamName, msg.App, msg.Channel, msg.Reason)
+ }
+ case "stream_changed":
+ if c.OnStreamChanged != nil {
+ c.OnStreamChanged(msg.StreamName, msg.Reason)
+ }
+ case "modules_changed":
+ c.Log.Printf("ws: modules changed module=%s reason=%s", msg.StreamName, msg.Reason)
+ if c.OnModulesChanged != nil {
+ c.OnModulesChanged(msg.StreamName, msg.Reason)
+ }
+ }
+}
+
func (c *Client) writeHeartbeat(conn *websocket.Conn) error {
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
return conn.WriteJSON(map[string]string{
diff --git a/apps/capture/README.md b/apps/capture/README.md
index 4274d50..f34b0f7 100644
--- a/apps/capture/README.md
+++ b/apps/capture/README.md
@@ -1,6 +1,6 @@
# capture
-One-shot phone MITM capture, hosted by the single binary as `drm capture`.
+One-shot phone MITM capture, hosted by the single binary as `streamd capture`.
```text
apps/capture/
@@ -8,17 +8,17 @@ apps/capture/
```
```bash
-./bin/drm capture # passive: play anything
-./bin/drm capture --app rte # launch, navigate by hand
-./bin/drm capture --app rte --channel rteone --auto-play \
+./bin/streamd capture # passive: play anything
+./bin/streamd capture --app rte # launch, navigate by hand
+./bin/streamd capture --app rte --channel rteone --auto-play \
--wvd data/device.wvd # fully automated
```
Writes `outputs///` plus `latest/`. App modules are compiled in, so
-there is no modules directory to point at; `drm modules` lists what is available.
+there is no modules directory to point at; `streamd modules` lists what is available.
**Full guide: [docs/capture.md](../../docs/capture.md)** — device setup, flags,
discovering a new app, and troubleshooting.
The catalog lookup that used to be a separate `tg4info` binary is now the
-provider-agnostic `drm catalog` (`apps/cli/catalogcmd`).
+provider-agnostic `streamd catalog` (`apps/cli/catalogcmd`).
diff --git a/apps/capture/capturecmd/capturecmd.go b/apps/capture/capturecmd/capturecmd.go
index 240c54f..c76e01d 100644
--- a/apps/capture/capturecmd/capturecmd.go
+++ b/apps/capture/capturecmd/capturecmd.go
@@ -3,22 +3,25 @@
package capturecmd
import (
+ "encoding/json"
"flag"
"fmt"
+ "os"
+ "path/filepath"
"strings"
"time"
"unicode"
- "drmdecryption/adb"
- "drmdecryption/app"
- "drmdecryption/modcfg"
- "drmdecryption/modhost"
- "drmdecryption/phonecap"
- "drmdecryption/repo"
+ "streamd/adb"
+ "streamd/app"
+ "streamd/modcfg"
+ "streamd/modhost"
+ "streamd/phonecap"
+ "streamd/repo"
)
// Run performs one capture. Providers live under modules// and are built
-// and executed by modhost — they are not linked into drm.exe.
+// and executed by modhost — they are not linked into streamd.
func Run(args []string) error {
args = normalizeArgs(args)
@@ -32,16 +35,17 @@ func Run(args []string) error {
fs := flag.NewFlagSet("capture", flag.ContinueOnError)
appName := fs.String("app", "", "app module under modules//. Empty = passive MITM, no launch/auto-play")
channel := fs.String("channel", "", "channel id for --auto-play")
- autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (implied when --channel is set)")
- waitSec := fs.Int("wait", 180, "seconds to wait for license/mpd capture")
+ allChannels := fs.Bool("all", false, "capture every channel declared by the module (grab-all)")
+ autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (implied when --channel / --all is set)")
+ waitSec := fs.Int("wait", 180, "seconds to wait for license/mpd capture (per channel with --all)")
python := fs.String("python", "", "python for wvkey.py (default: .venv)")
- wvd := fs.String("wvd", "", "path to .wvd device file (required for key fetch)")
+ wvd := fs.String("wvd", "", "path to .wvd device file (required by some apps e.g. c4; MPD-only if omitted)")
userAgent := fs.String("user-agent", "", "optional User-Agent for license requests")
serial := fs.String("serial", "", "adb device serial (default: sole/USB selected device)")
closeApp := fs.Bool("close", true, "force-stop --app when capture finishes (ignored in passive mode)")
- keyMode := fs.String("key-mode", "", "override the app's key mode: modulardrm | raw | none")
+ keyMode := fs.String("key-mode", "", "override the app's key mode: modulardrm | raw | wrap | none")
fs.Usage = func() {
- fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nExample (BBC + NordVPN UK):\n capture --app bbc --channel bbcone --wait 120\n\nFlags:\n", appChoices)
+ fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID | --all] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nExamples:\n capture --app bbc --channel bbcone --wait 120\n capture --app c4 --channel film4 --wvd data/device.wvd\n capture --app c4 --all --wvd data/device.wvd --wait 90\n\nFlags:\n", appChoices)
fs.PrintDefaults()
}
@@ -60,6 +64,9 @@ func Run(args []string) error {
// No --app: passive MITM — the operator plays whatever they want and we dump
// whatever DRM traffic appears.
if strings.TrimSpace(*appName) == "" {
+ if *allChannels {
+ return fmt.Errorf("--all requires --app")
+ }
_, err := phonecap.RunPassive(phonecap.Options{
Client: c,
Python: *python,
@@ -76,7 +83,26 @@ func Run(args []string) error {
if err != nil {
return modhost.FormatUnknown(root, *appName)
}
+ if needsWVD(a) && strings.TrimSpace(*wvd) == "" {
+ return fmt.Errorf("%s requires --wvd PATH (Widevine device file) — encrypted capture cannot be MPD-only", a.Name())
+ }
channelID := strings.TrimSpace(*channel)
+ if *allChannels && channelID != "" {
+ return fmt.Errorf("use either --channel or --all, not both")
+ }
+ if *allChannels {
+ return runAll(root, a, c, phonecap.Options{
+ App: a,
+ Client: c,
+ Python: *python,
+ WVD: *wvd,
+ UserAgent: *userAgent,
+ Wait: time.Duration(*waitSec) * time.Second,
+ CloseApp: *closeApp,
+ KeyMode: *keyMode,
+ ClearProxy: true,
+ })
+ }
// --channel implies interactive auto-play (Explore → channel → Watch live).
doAutoPlay := *autoPlay || channelID != ""
if *autoPlay && channelID == "" {
@@ -102,6 +128,106 @@ func Run(args []string) error {
return err
}
+type channelResult struct {
+ Channel string `json:"channel"`
+ Label string `json:"label"`
+ OK bool `json:"ok"`
+ MPD string `json:"mpd,omitempty"`
+ LicenseURL string `json:"license_url,omitempty"`
+ Key string `json:"key,omitempty"`
+ Path string `json:"path,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+func runAll(root string, a app.App, c *adb.Client, base phonecap.Options) error {
+ chs := a.Channels()
+ if len(chs) == 0 {
+ return fmt.Errorf("no channels configured for %s (%s)", a.Name(), knownChannels(a))
+ }
+ fmt.Printf("[*] Grab-all %s — %d channel(s)\n", a.Name(), len(chs))
+ results := make([]channelResult, 0, len(chs))
+ okN := 0
+ for i, ch := range chs {
+ fmt.Printf("\n======== [%d/%d] %s (%s) ========\n", i+1, len(chs), ch.Label, ch.ID)
+ opt := base
+ opt.Channel = ch.ID
+ opt.NoAutoPlay = false
+ opt.App = a
+ opt.Client = c
+ res, err := phonecap.Run(opt)
+ row := channelResult{
+ Channel: ch.ID,
+ Label: ch.Label,
+ }
+ if err != nil {
+ row.Error = err.Error()
+ fmt.Fprintf(os.Stderr, "[!] %s: %v\n", ch.ID, err)
+ } else {
+ row.OK = res.MPD != ""
+ row.MPD = res.MPD
+ row.LicenseURL = res.Session.LicenseURL
+ row.Key = res.Key
+ row.Path = res.Path
+ if row.OK {
+ okN++
+ } else {
+ row.Error = "no mpd"
+ }
+ }
+ results = append(results, row)
+ if i+1 < len(chs) {
+ // Let iptables / appproxy fully release before the next transparent start.
+ time.Sleep(4 * time.Second)
+ }
+ }
+
+ stamp := time.Now().Format("20060102-150405")
+ batchDir := filepath.Join(root, "outputs", a.Name(), "all-"+stamp)
+ _ = os.MkdirAll(batchDir, 0o755)
+ summaryPath := filepath.Join(batchDir, "SUMMARY.json")
+ if b, err := json.MarshalIndent(results, "", " "); err == nil {
+ _ = os.WriteFile(summaryPath, b, 0o644)
+ }
+ printAllSummary(a.Name(), results, okN, summaryPath)
+ if okN == 0 {
+ return fmt.Errorf("grab-all %s: 0/%d channels captured", a.Name(), len(chs))
+ }
+ if okN < len(chs) {
+ return fmt.Errorf("grab-all %s: %d/%d channels captured (see %s)", a.Name(), okN, len(chs), summaryPath)
+ }
+ return nil
+}
+
+func printAllSummary(appName string, results []channelResult, okN int, summaryPath string) {
+ fmt.Println()
+ fmt.Println("========== GRAB-ALL SUMMARY ==========")
+ fmt.Printf("app: %s ok: %d/%d\n", appName, okN, len(results))
+ fmt.Println("--------------------------------------")
+ fmt.Printf("%-12s %-14s %-6s %s\n", "ID", "LABEL", "OK", "MPD / ERROR")
+ for _, r := range results {
+ status := "no"
+ if r.OK {
+ status = "yes"
+ }
+ detail := r.Error
+ if r.OK {
+ detail = trimURL(r.MPD, 72)
+ }
+ fmt.Printf("%-12s %-14s %-6s %s\n", r.Channel, r.Label, status, detail)
+ }
+ fmt.Println("--------------------------------------")
+ fmt.Println("summary:", summaryPath)
+ fmt.Println("======================================")
+}
+
+func trimURL(s string, n int) string {
+ s = strings.TrimSpace(s)
+ if len(s) <= n {
+ return s
+ }
+ return s[:n] + "…"
+}
+
// normalizeArgs rewrites Unicode dashes Word/Terminal often insert (— – −)
// into ASCII - so `--app` is not silently dropped as a positional token.
func normalizeArgs(args []string) []string {
@@ -130,6 +256,13 @@ func normalizeArgs(args []string) []string {
return out
}
+func needsWVD(a app.App) bool {
+ if rw, ok := a.(app.RequireWVD); ok {
+ return rw.RequireWVD()
+ }
+ return false
+}
+
// knownChannels describes what the operator can pick, or where to declare it when
// the module has no local values file yet.
func knownChannels(a app.App) string {
diff --git a/apps/capture/go.mod b/apps/capture/go.mod
index af6edc7..e575d3d 100644
--- a/apps/capture/go.mod
+++ b/apps/capture/go.mod
@@ -1,13 +1,9 @@
-module drmdecryption/apps/capture
+module streamd/apps/capture
go 1.25.0
-require drmdecryption v0.0.0
+require streamd v0.0.0
-require (
- go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
- golang.org/x/sys v0.42.0 // indirect
- gopkg.in/yaml.v3 v3.0.1 // indirect
-)
+require gopkg.in/yaml.v3 v3.0.1 // indirect
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/capture/go.sum b/apps/capture/go.sum
index 908fb03..a62c313 100644
--- a/apps/capture/go.sum
+++ b/apps/capture/go.sum
@@ -1,11 +1,3 @@
-github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
-github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
-go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
-go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
-golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
-golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
-google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
-google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
diff --git a/apps/cli/capture_args_test.go b/apps/cli/capture_args_test.go
index ef8a084..c533f80 100644
--- a/apps/cli/capture_args_test.go
+++ b/apps/cli/capture_args_test.go
@@ -4,7 +4,7 @@ import (
"strings"
"testing"
- "drmdecryption/apps/capture/capturecmd"
+ "streamd/apps/capture/capturecmd"
)
func TestCaptureRejectsChannelAsApp(t *testing.T) {
diff --git a/apps/cli/catalogcmd/catalogcmd.go b/apps/cli/catalogcmd/catalogcmd.go
index b45ba90..4f5a782 100644
--- a/apps/cli/catalogcmd/catalogcmd.go
+++ b/apps/cli/catalogcmd/catalogcmd.go
@@ -11,9 +11,9 @@ import (
"sort"
"strings"
- "drmdecryption/modhost"
- "drmdecryption/repo"
- "drmdecryption/session"
+ "streamd/modhost"
+ "streamd/repo"
+ "streamd/session"
)
// Run performs a catalog lookup for one channel.
diff --git a/apps/cli/go.mod b/apps/cli/go.mod
index 441ed1e..a3df87f 100644
--- a/apps/cli/go.mod
+++ b/apps/cli/go.mod
@@ -1,13 +1,13 @@
-module drmdecryption/apps/cli
+module streamd/apps/cli
go 1.25.0
require (
- drmdecryption v0.0.0
- drmdecryption/apps/agent v0.0.0
- drmdecryption/apps/capture v0.0.0
- drmdecryption/apps/proxy v0.0.0
- drmdecryption/apps/streamd v0.0.0
+ streamd v0.0.0
+ streamd/apps/agent v0.0.0
+ streamd/apps/capture v0.0.0
+ streamd/apps/proxy v0.0.0
+ streamd/apps/streamd v0.0.0
)
require (
@@ -26,9 +26,9 @@ require (
)
replace (
- drmdecryption => ../pkg
- drmdecryption/apps/agent => ../agent
- drmdecryption/apps/capture => ../capture
- drmdecryption/apps/proxy => ../proxy
- drmdecryption/apps/streamd => ../streamd
+ streamd => ../pkg
+ streamd/apps/agent => ../agent
+ streamd/apps/capture => ../capture
+ streamd/apps/proxy => ../proxy
+ streamd/apps/streamd => ../streamd
)
diff --git a/apps/cli/main.go b/apps/cli/main.go
index 5aab463..802c7fb 100644
--- a/apps/cli/main.go
+++ b/apps/cli/main.go
@@ -1,22 +1,26 @@
-// Command drm is the single entry point for the toolchain: phone capture,
+// Command streamd is the single entry point for the toolchain: phone capture,
// catalog lookups, the always-on agent, the streamd control plane and the
// on-device MITM. Providers live under modules// and are discovered,
// built, and executed by the host — they are not linked into this binary.
package main
import (
+ // The scheduler resolves IANA zone names so a weekly event stays at its
+ // local wall-clock time. Windows ships no zone database, so embed one.
+ _ "time/tzdata"
+
"fmt"
"os"
"strings"
- "drmdecryption/apps/agent/agentcmd"
- "drmdecryption/apps/capture/capturecmd"
- "drmdecryption/apps/cli/catalogcmd"
- "drmdecryption/apps/cli/modulescmd"
- "drmdecryption/apps/proxy/proxyctlcmd"
- "drmdecryption/apps/streamd/servecmd"
- "drmdecryption/bootstrap"
- "drmdecryption/modhost"
+ "streamd/apps/agent/agentcmd"
+ "streamd/apps/capture/capturecmd"
+ "streamd/apps/cli/catalogcmd"
+ "streamd/apps/cli/modulescmd"
+ "streamd/apps/proxy/proxyctlcmd"
+ "streamd/apps/streamd/servecmd"
+ "streamd/bootstrap"
+ "streamd/modhost"
)
func main() {
@@ -35,12 +39,12 @@ func main() {
os.Exit(1)
}
} else if err := modhost.ApplyEnvModulesDir(); err != nil {
- fmt.Fprintln(os.Stderr, "[!] DRM_MODULES_DIR:", err)
+ fmt.Fprintln(os.Stderr, "[!] STREAMD_MODULES_DIR / DRM_MODULES_DIR:", err)
os.Exit(1)
}
// Materialise apps/, bin/, modules/, outputs/, … next to this exe when
- // missing so a lone downloaded drm.exe becomes a GitHub-like install tree.
+ // missing so a lone downloaded streamd.exe becomes a usable install tree.
if cmd != "help" && cmd != "-h" && cmd != "--help" {
if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
@@ -98,18 +102,19 @@ func peelGlobalFlags(args []string) (modulesDir string, rest []string) {
}
func usage() {
- fmt.Fprint(os.Stderr, `drm — DRM capture / restream toolchain
+ fmt.Fprint(os.Stderr, `streamd — capture / restream toolchain
Usage:
- drm [--modules-dir DIR] modules
- drm [--modules-dir DIR] capture --app NAME [--channel ID] [--wvd PATH]
- drm [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
- drm agent run|status|devices|enqueue|cancel [--config …]
- drm serve [--bind …] [--data …] [--token …]
- drm proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
+ streamd [--modules-dir DIR] modules
+ streamd [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--wvd PATH]
+ streamd [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
+ streamd agent run|status|devices|enqueue|cancel [--config …]
+ streamd serve start|stop|restart|status|update|run [flags]
+ streamd serve [--bind …] [--data …] # foreground (same as run)
+ streamd proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
Global flags:
- --modules-dir DIR provider folder (default: /modules, or $DRM_MODULES_DIR)
+ --modules-dir DIR provider folder (default: /modules, or $STREAMD_MODULES_DIR)
Providers live under modules// (Go source + module-publish.yaml).
Local module.yaml holds secrets and is never published; release zips ship
diff --git a/apps/cli/modulescmd/modulescmd.go b/apps/cli/modulescmd/modulescmd.go
index 4f7ee55..5cf2a23 100644
--- a/apps/cli/modulescmd/modulescmd.go
+++ b/apps/cli/modulescmd/modulescmd.go
@@ -9,8 +9,8 @@ import (
"sort"
"text/tabwriter"
- "drmdecryption/modhost"
- "drmdecryption/repo"
+ "streamd/modhost"
+ "streamd/repo"
)
// Run prints external modules under modules/.
diff --git a/apps/modules/README.md b/apps/modules/README.md
index e518fd5..87532fc 100644
--- a/apps/modules/README.md
+++ b/apps/modules/README.md
@@ -4,8 +4,8 @@ One Go package per streaming app. Every module is **compiled into the binary**
there is no plugin loading and no modules directory to point a binary at.
```text
-apps/modules/ Go module: drmdecryption/modules
- go.mod replace drmdecryption => ../pkg
+apps/modules/ Go module: streamd/modules
+ go.mod replace streamd => ../pkg
all/all.go blank-imports every module — the link point
provider/ shared base: values loading, channel aliases, durations
/*.go TRACKED: the app's logic
@@ -37,7 +37,7 @@ Values arrive by **flag → environment → module.yaml → Go default**, and on
mechanical defaults (timeouts, DASH timescales, card geometry) live in code:
```bash
-./bin/drm catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
+./bin/streamd catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
export TG4_POLICY_KEY=BCpkAD... # same thing
```
@@ -46,9 +46,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
1. Create `apps/modules/myapp/` with `config.go` and `myapp.go`
2. Register from `init()`: `appreg.Register(Name, New)` and
`appreg.RegisterFlags(bindFlags)`
-3. Add one line to `all/all.go`: `_ "drmdecryption/modules/myapp"`
+3. Add one line to `all/all.go`: `_ "streamd/modules/myapp"`
4. Create `apps/modules/myapp/module.yaml` with your values
-5. `go -C apps/cli build -o ../../bin/drm .` then `./bin/drm modules`
+5. `go -C apps/cli build -o ../../bin/streamd .` then `./bin/streamd modules`
**Authoring guide: [docs/modules.md](../../docs/modules.md)** — the full contract,
`uiflow` reference, optional capability interfaces, and a checklist.
@@ -59,9 +59,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
## Run
```bash
-./bin/drm modules # what is compiled in
-./bin/drm capture --app rte --channel rteone --auto-play
-./bin/drm capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only
-./bin/drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
-./bin/drm agent run --config apps/agent/agent.yaml
+./bin/streamd modules # what is compiled in
+./bin/streamd capture --app rte --channel rteone --auto-play
+./bin/streamd capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only
+./bin/streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
+./bin/streamd agent run --config apps/agent/agent.yaml
```
diff --git a/apps/modules/all/all.go b/apps/modules/all/all.go
index 33b94a3..9771be3 100644
--- a/apps/modules/all/all.go
+++ b/apps/modules/all/all.go
@@ -4,7 +4,7 @@
package all
import (
- _ "drmdecryption/modules/bbc"
- _ "drmdecryption/modules/rte"
- _ "drmdecryption/modules/tg4"
+ _ "streamd/modules/bbc"
+ _ "streamd/modules/rte"
+ _ "streamd/modules/tg4"
)
diff --git a/apps/modules/all/all_test.go b/apps/modules/all/all_test.go
index fd6113b..f7d2031 100644
--- a/apps/modules/all/all_test.go
+++ b/apps/modules/all/all_test.go
@@ -4,7 +4,7 @@ import (
"flag"
"testing"
- appreg "drmdecryption/app"
+ appreg "streamd/app"
)
// Every module must be constructible with no module.yaml present — a fresh clone
@@ -23,9 +23,9 @@ func TestAllModulesRegisterAndConstruct(t *testing.T) {
t.Errorf("%s: Name() = %q", n, a.Name())
}
switch a.KeyMode() {
- case "raw", "modulardrm", "none":
+ case "raw", "modulardrm", "wrap", "none":
default:
- t.Errorf("%s: KeyMode() = %q, want raw, modulardrm, or none", n, a.KeyMode())
+ t.Errorf("%s: KeyMode() = %q, want raw, modulardrm, wrap, or none", n, a.KeyMode())
}
if a.CAHash() == "" {
t.Errorf("%s: CAHash() empty", n)
@@ -39,6 +39,12 @@ func TestAllModulesRegisterAndConstruct(t *testing.T) {
if a.CaptureHints().RemoteLog == "" {
t.Errorf("%s: CaptureHints has no remote log", n)
}
+ if n == "c4" {
+ rw, ok := a.(appreg.RequireWVD)
+ if !ok || !rw.RequireWVD() {
+ t.Errorf("c4 must RequireWVD() so capture refuses MPD-only runs")
+ }
+ }
}
}
diff --git a/apps/modules/bbc/bbc.go b/apps/modules/bbc/bbc.go
index b20424c..50941de 100644
--- a/apps/modules/bbc/bbc.go
+++ b/apps/modules/bbc/bbc.go
@@ -9,12 +9,12 @@ import (
"os"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
diff --git a/apps/modules/bbc/bbc_test.go b/apps/modules/bbc/bbc_test.go
index 1ea2bca..fff5490 100644
--- a/apps/modules/bbc/bbc_test.go
+++ b/apps/modules/bbc/bbc_test.go
@@ -3,11 +3,11 @@ package bbc
import (
"testing"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modcfg"
+ "streamd/modules/provider"
+ "streamd/mpd"
)
var (
diff --git a/apps/modules/bbc/config.go b/apps/modules/bbc/config.go
index 969ad7d..321ad85 100644
--- a/apps/modules/bbc/config.go
+++ b/apps/modules/bbc/config.go
@@ -4,8 +4,8 @@ import (
"regexp"
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
+ "streamd/modcfg"
+ "streamd/modules/provider"
)
// Name is the module id (--app bbc).
diff --git a/apps/modules/bbc/steps.go b/apps/modules/bbc/steps.go
index b0bdb15..df0e1ee 100644
--- a/apps/modules/bbc/steps.go
+++ b/apps/modules/bbc/steps.go
@@ -6,8 +6,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
// openExplorePage taps the Explore bottom-nav tab and waits for the channel rail.
diff --git a/apps/modules/c4/c4.go b/apps/modules/c4/c4.go
new file mode 100644
index 0000000..f6cea1b
--- /dev/null
+++ b/apps/modules/c4/c4.go
@@ -0,0 +1,148 @@
+// Package c4 is the Channel 4 (All 4) Live TV provider module.
+// Live list rows use content-desc "Select to watch Channel Four" / "E Four" / etc.
+package c4
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
+)
+
+func init() {
+ appreg.Register(Name, New)
+ appreg.RegisterFlags(bindFlags)
+}
+
+func bindFlags(fs *flag.FlagSet) {
+ fs.StringVar(&flags.packageName, Name+".package", "", "override "+Name+" android package id")
+ fs.StringVar(&flags.caHash, Name+".ca-hash", "", "override "+Name+" MITM CA subject hash")
+ fs.StringVar(&flags.proxyBin, Name+".proxy-bin", "", "override "+Name+" on-device MITM binary")
+}
+
+// App is the Channel 4 plugin.
+type App struct {
+ *provider.Base
+ cfg Config
+}
+
+// New constructs the plugin from module.yaml + flags + env.
+func New() (appreg.App, error) {
+ cfg, res, err := loadConfig()
+ if err != nil {
+ return nil, err
+ }
+ labels := make(map[string]string, len(cfg.Channels))
+ for id, ch := range cfg.Channels {
+ labels[id] = ch.Label
+ }
+ return &App{Base: provider.New(Name, cfg.Common, labels, res), cfg: cfg}, nil
+}
+
+// KeyMode: Channel 4 / RedBee needs the phone's JSON license POST (token +
+// challenge). Capture stores that body; wvkey --mode wrap re-issues it.
+func (a *App) KeyMode() string { return "wrap" }
+
+// RequireWVD: C4 live is always encrypted — refuse MPD-only captures.
+func (a *App) RequireWVD() bool { return true }
+
+// CaptureHints: need the DASH MPD and the phone's RedBee license POST body
+// (token + challenge). MPD alone is not enough for keys.
+func (a *App) CaptureHints() capture.Hints {
+ return a.Hints("mpd", "license_body")
+}
+
+// CaptureHintsFor prefers the simulcast path for this live channel so a
+// neighbouring Auto-play / prefetch MPD does not win the Wait score race.
+func (a *App) CaptureHintsFor(channel string) capture.Hints {
+ h := a.CaptureHints()
+ id, err := a.Resolve(channel)
+ if err != nil {
+ id = strings.ToLower(strings.TrimSpace(channel))
+ }
+ prefer := map[string]string{
+ "channel4": "channel(c4)",
+ "e4": "channel(e4)",
+ "more4": "channel(m4)",
+ "film4": "channel(f4)",
+ "fourseven": "channel(4s)",
+ }
+ if p, ok := prefer[id]; ok {
+ h.PreferURLContains = []string{p}
+ }
+ return h
+}
+
+// UseTransparentMITM: UK VPN on-device conflicts with Wi‑Fi http_proxy.
+func (a *App) UseTransparentMITM() bool { return true }
+
+func (a *App) MPDRewriter() mpd.Rewriter { return mpd.Passthrough{} }
+
+func (a *App) Channels() []appreg.Channel {
+ out := make([]appreg.Channel, 0, len(a.cfg.Channels))
+ for _, id := range a.ChannelIDs() {
+ out = append(out, appreg.Channel{ID: id, Label: a.Label(id)})
+ }
+ return out
+}
+
+// Launch cold-starts Channel 4.
+func (a *App) Launch(c *adb.Client) error {
+ c.EnsureAwake()
+ fmt.Printf("[*] Launching %s (%s)…\n", Name, a.Package())
+ c.ForceStop(a.Package())
+ time.Sleep(400 * time.Millisecond)
+ if err := uiflow.MonkeyLaunch(c, a.Package()); err != nil {
+ return err
+ }
+ time.Sleep(time.Duration(a.cfg.Timeouts.LaunchSettle))
+ c.DismissShadeIfFocused()
+ if err := uiflow.WaitUI(c, a.CacheDir(), uiflow.Match{
+ DescContains: a.cfg.UI.LaunchDescContains,
+ TextContains: a.cfg.UI.LaunchDescContains,
+ }, time.Duration(a.cfg.Timeouts.LaunchWaitUI)); err != nil {
+ fmt.Fprintf(os.Stderr, "[!] launch UI wait: %v — continue and play manually\n", err)
+ }
+ return nil
+}
+
+// AutoPlay opens Live TV, scrolls to the channel card, and taps Select to watch.
+func (a *App) AutoPlay(c *adb.Client, channel string) error {
+ id, err := a.Resolve(channel)
+ if err != nil {
+ return err
+ }
+ ch := a.cfg.Channels[id]
+ fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
+ c.DismissShadeIfFocused()
+
+ if err := a.openLiveTab(c); err != nil {
+ return fmt.Errorf("Live TV tab: %w", err)
+ }
+ if err := a.tapChannelCard(c, ch); err != nil {
+ return fmt.Errorf("channel play %s: %w", a.Label(id), err)
+ }
+ return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
+ Timeout: time.Duration(a.cfg.Timeouts.Playback),
+ SoftFail: true,
+ OrDescContains: []string{
+ "Pause",
+ "Unmute",
+ "Cast",
+ },
+ })
+}
+
+func (a *App) VideoSelect() string { return "for=best" }
+func (a *App) AudioSelect() string { return "for=best" }
+func (a *App) RewriterName() string { return "none" }
+func (a *App) LiveWaitSeconds() int { return 2 }
+func (a *App) TSReadyBytes() int64 { return 256 << 10 }
diff --git a/apps/modules/c4/config.go b/apps/modules/c4/config.go
new file mode 100644
index 0000000..8fc767b
--- /dev/null
+++ b/apps/modules/c4/config.go
@@ -0,0 +1,116 @@
+package c4
+
+import (
+ "time"
+
+ "streamd/modcfg"
+ "streamd/modules/provider"
+)
+
+// Name is the module id (--app c4).
+const Name = "c4"
+
+// Channel is one Channel 4 Live TV target.
+type Channel struct {
+ Label string `yaml:"label"`
+ ChipDesc []string `yaml:"chip_desc"`
+ PlayDesc []string `yaml:"play_desc"`
+}
+
+// Config is modules/c4/module.yaml (preferred) or apps/modules/c4/module.yaml.
+type Config struct {
+ provider.Common `yaml:",inline"`
+
+ Channels map[string]Channel `yaml:"channels"`
+ Timeouts Timeouts `yaml:"timeouts"`
+ UI UI `yaml:"ui"`
+}
+
+type Timeouts struct {
+ LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
+ LaunchSettle provider.Duration `yaml:"launch_settle"`
+ LiveNav provider.Duration `yaml:"live_nav"`
+ ChannelFind provider.Duration `yaml:"channel_find"`
+ AfterChannel provider.Duration `yaml:"after_channel"`
+ WatchLive provider.Duration `yaml:"watch_live"`
+ Playback provider.Duration `yaml:"playback"`
+}
+
+type UI struct {
+ LaunchDescContains []string `yaml:"launch_desc_contains"`
+ LiveTab []string `yaml:"live_tab"`
+ LiveTabDescRE []string `yaml:"live_tab_desc_re"`
+ LiveTabTextRE []string `yaml:"live_tab_text_re"`
+ WatchLive []string `yaml:"watch_live"`
+ PlaybackDescContains []string `yaml:"playback_desc_contains"`
+ ChannelScrollMax int `yaml:"channel_scroll_max"`
+}
+
+func (c Config) withDefaults() Config {
+ t := &c.Timeouts
+ t.LaunchWaitUI = provider.Duration(t.LaunchWaitUI.D(30 * time.Second))
+ t.LaunchSettle = provider.Duration(t.LaunchSettle.D(5 * time.Second))
+ t.LiveNav = provider.Duration(t.LiveNav.D(20 * time.Second))
+ t.ChannelFind = provider.Duration(t.ChannelFind.D(45 * time.Second))
+ t.AfterChannel = provider.Duration(t.AfterChannel.D(2 * time.Second))
+ t.WatchLive = provider.Duration(t.WatchLive.D(20 * time.Second))
+ t.Playback = provider.Duration(t.Playback.D(45 * time.Second))
+
+ u := &c.UI
+ if len(u.LaunchDescContains) == 0 {
+ u.LaunchDescContains = []string{"Home", "Live TV", "My Shows", "Downloads", "Search"}
+ }
+ if len(u.LiveTab) == 0 {
+ u.LiveTab = []string{"Live TV"}
+ }
+ if len(u.LiveTabDescRE) == 0 {
+ u.LiveTabDescRE = []string{`(?i)^Live TV$`}
+ }
+ if len(u.LiveTabTextRE) == 0 {
+ u.LiveTabTextRE = []string{`(?i)^Live TV$`}
+ }
+ if len(u.WatchLive) == 0 {
+ u.WatchLive = []string{"Select to watch", "Play Episode", "Restart"}
+ }
+ if len(u.PlaybackDescContains) == 0 {
+ u.PlaybackDescContains = []string{"Pause", "Unmute", "Cast", "Subtitles"}
+ }
+ if u.ChannelScrollMax <= 0 {
+ u.ChannelScrollMax = 10
+ }
+ if c.Package == "" {
+ c.Package = "com.channel4.ondemand"
+ }
+ if c.Channels == nil {
+ c.Channels = map[string]Channel{}
+ }
+ return c
+}
+
+func loadConfig() (Config, modcfg.Result, error) {
+ var cfg Config
+ res, err := modcfg.Load(Name, &cfg)
+ if err != nil {
+ return cfg, res, err
+ }
+ cfg = cfg.withDefaults()
+ if v := modcfg.Env(Name, "package"); v != "" {
+ cfg.Package = v
+ }
+ if flags.packageName != "" {
+ cfg.Package = flags.packageName
+ }
+ if flags.caHash != "" {
+ cfg.CAHash = flags.caHash
+ }
+ if flags.proxyBin != "" {
+ cfg.ProxyBin = flags.proxyBin
+ }
+ return cfg, res, nil
+}
+
+var flags struct {
+ packageName string
+ caHash string
+ proxyBin string
+}
diff --git a/apps/modules/c4/module-publish.yaml b/apps/modules/c4/module-publish.yaml
new file mode 100644
index 0000000..b7d7c23
--- /dev/null
+++ b/apps/modules/c4/module-publish.yaml
@@ -0,0 +1,84 @@
+# Channel 4 (All 4) — published universal values (renamed to module.yaml in release zips).
+# Live cards: content-desc "Select to watch Channel Four" / "E Four" / "More Four" / …
+
+package: com.channel4.ondemand
+proxy_bin: bin/proxy-android-arm64
+
+# SENSITIVE — set in local module.yaml:
+# license_url: "https://c4.eme.lp.aws.redbeemedia.com/wvlicenceproxy-service/widevine/acquire"
+
+# Transparent mode only MITMs open.live by default. Force C4 playlist / license hosts.
+mitm_hosts:
+ - c4assets.com
+ - olsp.live.dash.c4assets.com
+ - stream.c4assets.com
+ - channel4.com
+ - api.channel4.com
+ - c4.eme.lp.aws.redbeemedia.com
+ - redbeemedia.com
+ - all4nav.channel4.com
+
+score:
+ hosts:
+ - c4assets.com
+ - olsp.live.dash.c4assets.com
+ - stream.c4assets.com
+ - channel4.com
+ - api.channel4.com
+ - redbeemedia.com
+ - akamaized.net
+ deny:
+ - google-analytics
+ - googletagmanager
+ - doubleclick
+ - scorecardresearch
+ - facebook.com
+ - crashlytics
+ - appsflyer
+ - optimizely
+
+aliases:
+ c4: channel4
+ four: channel4
+ ch4: channel4
+ channel: channel4
+ e: e4
+ more: more4
+ film: film4
+ "4seven": fourseven
+ seven: fourseven
+
+channels:
+ channel4:
+ label: Channel Four
+ chip_desc: ["(?i)Select to watch\\s+Channel Four"]
+ e4:
+ label: E Four
+ chip_desc: ["(?i)Select to watch\\s+E Four"]
+ more4:
+ label: More Four
+ chip_desc: ["(?i)Select to watch\\s+More Four"]
+ film4:
+ label: Film Four
+ chip_desc: ["(?i)Select to watch\\s+Film Four"]
+ fourseven:
+ label: Four Seven
+ chip_desc: ["(?i)Select to watch\\s+Four Seven"]
+
+ui:
+ launch_desc_contains: ["Home", "Live TV", "My Shows", "Downloads", "Search"]
+ live_tab: ["Live TV"]
+ live_tab_desc_re: ["(?i)^Live TV$"]
+ live_tab_text_re: ["(?i)^Live TV$"]
+ watch_live: ["Select to watch", "Play Episode"]
+ playback_desc_contains: ["Pause", "Unmute", "Cast"]
+ channel_scroll_max: 16
+
+timeouts:
+ launch_wait_ui: 30s
+ launch_settle: 5s
+ live_nav: 20s
+ channel_find: 45s
+ after_channel: 2s
+ watch_live: 20s
+ playback: 45s
diff --git a/apps/modules/c4/steps.go b/apps/modules/c4/steps.go
new file mode 100644
index 0000000..698016c
--- /dev/null
+++ b/apps/modules/c4/steps.go
@@ -0,0 +1,175 @@
+package c4
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+ "time"
+
+ "streamd/adb"
+ "streamd/uiflow"
+)
+
+func (a *App) openLiveTab(c *adb.Client) error {
+ c.DismissShadeIfFocused()
+ if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onLiveTab(nodes) {
+ fmt.Println("[*] already on Live TV")
+ return nil
+ }
+
+ fmt.Println("[*] open Live TV…")
+ descRE := a.cfg.UI.LiveTabDescRE
+ if len(descRE) == 0 {
+ descRE = []string{`(?i)^Live TV$`}
+ }
+ textRE := a.cfg.UI.LiveTabTextRE
+ if len(textRE) == 0 {
+ textRE = []string{`(?i)^Live TV$`}
+ }
+ if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
+ DescRE: descRE,
+ TextRE: textRE,
+ DescContains: a.cfg.UI.LiveTab,
+ TextContains: a.cfg.UI.LiveTab,
+ Pick: uiflow.PickFirst,
+ }, time.Duration(a.cfg.Timeouts.LiveNav)); err != nil {
+ return fmt.Errorf("live tab: %w", err)
+ }
+ time.Sleep(1500 * time.Millisecond)
+
+ deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveNav))
+ for time.Now().Before(deadline) {
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err == nil && a.onLiveTab(nodes) {
+ fmt.Println("[*] Live TV ready")
+ a.disableLiveAutoPlay(c)
+ return nil
+ }
+ time.Sleep(700 * time.Millisecond)
+ }
+ return fmt.Errorf("Live TV did not open")
+}
+
+// disableLiveAutoPlay turns off the Live TV "Auto-play" toggle so the app does
+// not advance to the next channel while we wait for MITM.
+func (a *App) disableLiveAutoPlay(c *adb.Client) {
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err != nil {
+ return
+ }
+ for _, n := range nodes {
+ d := strings.ToLower(strings.TrimSpace(n.Desc))
+ t := strings.ToLower(strings.TrimSpace(n.Text))
+ if d != "auto-play" && t != "auto-play" {
+ continue
+ }
+ if n.Selected || n.Checked {
+ fmt.Println("[*] disable Live Auto-play")
+ _ = c.Tap(n.CX(), n.CY())
+ time.Sleep(500 * time.Millisecond)
+ return
+ }
+ // State may not be exposed — leave alone when already off / unknown.
+ fmt.Println("[*] Live Auto-play control present (left as-is)")
+ return
+ }
+}
+
+func (a *App) onLiveTab(nodes []adb.Node) bool {
+ for _, n := range nodes {
+ d := strings.ToLower(n.Desc)
+ if strings.Contains(d, "select to watch") {
+ return true
+ }
+ if strings.Contains(d, "now showing on") {
+ return true
+ }
+ if strings.EqualFold(n.Desc, "Live TV, heading") || strings.EqualFold(n.Text, "On now") {
+ return true
+ }
+ }
+ return false
+}
+
+// tapChannelCard scrolls the Live list for "Select to watch {Label}" and taps it.
+func (a *App) tapChannelCard(c *adb.Client, ch Channel) error {
+ pats := ch.ChipDesc
+ if len(pats) == 0 {
+ pats = []string{`(?i)Select to watch\s+` + regexp.QuoteMeta(ch.Label)}
+ }
+ chipRE := uiflow.CompileRes(pats)
+ fmt.Printf("[*] find Live card for %s…\n", ch.Label)
+
+ row, err := a.findChannelCard(c, chipRE)
+ if err != nil {
+ return err
+ }
+ fmt.Printf("[*] tap %q @ %d,%d\n", trimDesc(row.Desc, 60), row.CX(), row.CY())
+ if err := c.Tap(row.CX(), row.CY()); err != nil {
+ return err
+ }
+ time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
+ return nil
+}
+
+func (a *App) findChannelCard(c *adb.Client, chipRE []*regexp.Regexp) (*adb.Node, error) {
+ scrollMax := a.cfg.UI.ChannelScrollMax
+ if scrollMax <= 0 {
+ scrollMax = 10
+ }
+ // Prefer starting near the top so Channel Four / E4 are reachable.
+ _ = c.Swipe(540, 1100, 540, 1900, 250)
+ time.Sleep(400 * time.Millisecond)
+
+ for attempt := 0; attempt <= scrollMax; attempt++ {
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err != nil {
+ return nil, err
+ }
+ var best *adb.Node
+ for i := range nodes {
+ n := &nodes[i]
+ hay := n.Desc
+ if hay == "" {
+ hay = n.Text
+ }
+ if hay == "" {
+ continue
+ }
+ // Skip cards clipped into the bottom nav (false taps).
+ if n.Y2 > 2100 || n.CY() > 2050 {
+ continue
+ }
+ for _, p := range chipRE {
+ if !p.MatchString(hay) {
+ continue
+ }
+ // Prefer the explicit "Select to watch" control when present.
+ if strings.Contains(strings.ToLower(hay), "select to watch") {
+ return n, nil
+ }
+ if best == nil {
+ best = n
+ }
+ }
+ }
+ if best != nil {
+ return best, nil
+ }
+ if attempt == scrollMax {
+ break
+ }
+ fmt.Printf("[*] scroll Live list (%d/%d)…\n", attempt+1, scrollMax)
+ _ = c.Swipe(540, 1950, 540, 900, 320)
+ time.Sleep(700 * time.Millisecond)
+ }
+ return nil, fmt.Errorf("channel card not found")
+}
+
+func trimDesc(s string, n int) string {
+ s = strings.TrimSpace(s)
+ if len(s) <= n {
+ return s
+ }
+ return s[:n] + "…"
+}
diff --git a/apps/modules/go.mod b/apps/modules/go.mod
index 6635e2a..1036caa 100644
--- a/apps/modules/go.mod
+++ b/apps/modules/go.mod
@@ -1,9 +1,9 @@
-module drmdecryption/modules
+module streamd/modules
go 1.25.0
-require drmdecryption v0.0.0
+require streamd v0.0.0
require gopkg.in/yaml.v3 v3.0.1 // indirect
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/modules/itv/config.go b/apps/modules/itv/config.go
new file mode 100644
index 0000000..e2f7d96
--- /dev/null
+++ b/apps/modules/itv/config.go
@@ -0,0 +1,116 @@
+package itv
+
+import (
+ "time"
+
+ "streamd/modcfg"
+ "streamd/modules/provider"
+)
+
+// Name is the module id (--app itv).
+const Name = "itv"
+
+// Channel is one live ITVX target.
+type Channel struct {
+ Label string `yaml:"label"`
+ ChipDesc []string `yaml:"chip_desc"`
+ PlayDesc []string `yaml:"play_desc"`
+}
+
+// Config is modules/itv/module.yaml (preferred) or apps/modules/itv/module.yaml.
+type Config struct {
+ provider.Common `yaml:",inline"`
+
+ Channels map[string]Channel `yaml:"channels"`
+ Timeouts Timeouts `yaml:"timeouts"`
+ UI UI `yaml:"ui"`
+}
+
+type Timeouts struct {
+ LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
+ LaunchSettle provider.Duration `yaml:"launch_settle"`
+ LiveNav provider.Duration `yaml:"live_nav"`
+ ChannelFind provider.Duration `yaml:"channel_find"`
+ AfterChannel provider.Duration `yaml:"after_channel"`
+ WatchLive provider.Duration `yaml:"watch_live"`
+ Playback provider.Duration `yaml:"playback"`
+}
+
+type UI struct {
+ LaunchDescContains []string `yaml:"launch_desc_contains"`
+ LiveTab []string `yaml:"live_tab"`
+ LiveTabDescRE []string `yaml:"live_tab_desc_re"`
+ LiveTabTextRE []string `yaml:"live_tab_text_re"`
+ WatchLive []string `yaml:"watch_live"`
+ PlaybackDescContains []string `yaml:"playback_desc_contains"`
+ ChannelScrollMax int `yaml:"channel_scroll_max"`
+}
+
+func (c Config) withDefaults() Config {
+ t := &c.Timeouts
+ t.LaunchWaitUI = provider.Duration(t.LaunchWaitUI.D(30 * time.Second))
+ t.LaunchSettle = provider.Duration(t.LaunchSettle.D(5 * time.Second))
+ t.LiveNav = provider.Duration(t.LiveNav.D(20 * time.Second))
+ t.ChannelFind = provider.Duration(t.ChannelFind.D(45 * time.Second))
+ t.AfterChannel = provider.Duration(t.AfterChannel.D(3 * time.Second))
+ t.WatchLive = provider.Duration(t.WatchLive.D(20 * time.Second))
+ t.Playback = provider.Duration(t.Playback.D(60 * time.Second))
+
+ u := &c.UI
+ if len(u.LaunchDescContains) == 0 {
+ u.LaunchDescContains = []string{"Home", "Live", "Categories", "My List", "ITVX"}
+ }
+ if len(u.LiveTab) == 0 {
+ u.LiveTab = []string{"Lyve", "Live"}
+ }
+ if len(u.LiveTabDescRE) == 0 {
+ u.LiveTabDescRE = []string{"^Lyve$"}
+ }
+ if len(u.LiveTabTextRE) == 0 {
+ u.LiveTabTextRE = []string{"^Live$"}
+ }
+ if len(u.WatchLive) == 0 {
+ u.WatchLive = []string{"WATCH LIVE", "Watch live", "Watch Live"}
+ }
+ if len(u.PlaybackDescContains) == 0 {
+ u.PlaybackDescContains = []string{"Pause", "pause", "Seek", "Player"}
+ }
+ if u.ChannelScrollMax <= 0 {
+ u.ChannelScrollMax = 12
+ }
+ if c.Package == "" {
+ c.Package = "air.ITVMobilePlayer"
+ }
+ if c.Channels == nil {
+ c.Channels = map[string]Channel{}
+ }
+ return c
+}
+
+func loadConfig() (Config, modcfg.Result, error) {
+ var cfg Config
+ res, err := modcfg.Load(Name, &cfg)
+ if err != nil {
+ return cfg, res, err
+ }
+ cfg = cfg.withDefaults()
+ if v := modcfg.Env(Name, "package"); v != "" {
+ cfg.Package = v
+ }
+ if flags.packageName != "" {
+ cfg.Package = flags.packageName
+ }
+ if flags.caHash != "" {
+ cfg.CAHash = flags.caHash
+ }
+ if flags.proxyBin != "" {
+ cfg.ProxyBin = flags.proxyBin
+ }
+ return cfg, res, nil
+}
+
+var flags struct {
+ packageName string
+ caHash string
+ proxyBin string
+}
diff --git a/apps/modules/itv/itv.go b/apps/modules/itv/itv.go
new file mode 100644
index 0000000..bc89ffd
--- /dev/null
+++ b/apps/modules/itv/itv.go
@@ -0,0 +1,124 @@
+// Package itv is a stub ITVX provider module.
+// Launch works; AutoPlay opens the Live tab and taps a channel chip when
+// content-desc matches. Capture scoring targets ITV CDN / license hosts.
+// Full Live navigation and catalog may need tuning against a UK-geo session.
+package itv
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "time"
+
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
+)
+
+func init() {
+ appreg.Register(Name, New)
+ appreg.RegisterFlags(bindFlags)
+}
+
+func bindFlags(fs *flag.FlagSet) {
+ fs.StringVar(&flags.packageName, Name+".package", "", "override "+Name+" android package id")
+ fs.StringVar(&flags.caHash, Name+".ca-hash", "", "override "+Name+" MITM CA subject hash")
+ fs.StringVar(&flags.proxyBin, Name+".proxy-bin", "", "override "+Name+" on-device MITM binary")
+}
+
+// App is the ITVX plugin.
+type App struct {
+ *provider.Base
+ cfg Config
+}
+
+// New constructs the plugin from module.yaml + flags + env.
+func New() (appreg.App, error) {
+ cfg, res, err := loadConfig()
+ if err != nil {
+ return nil, err
+ }
+ labels := make(map[string]string, len(cfg.Channels))
+ for id, ch := range cfg.Channels {
+ labels[id] = ch.Label
+ }
+ return &App{Base: provider.New(Name, cfg.Common, labels, res), cfg: cfg}, nil
+}
+
+// KeyMode: ITVX live typically uses a raw Widevine license response.
+func (a *App) KeyMode() string { return "raw" }
+
+// CaptureHints: transparent MITM yields the DAR MPD URL (+ Irdeto license_url).
+// PSSH is often absent from the outer YoSpace/CSM MPD; require mpd only for now.
+func (a *App) CaptureHints() capture.Hints {
+ return a.Hints("mpd")
+}
+
+// UseTransparentMITM: UK VPN on-device conflicts with Wi‑Fi http_proxy.
+func (a *App) UseTransparentMITM() bool { return true }
+
+// MPDRewriter: passthrough until a DAI rewriter is needed.
+func (a *App) MPDRewriter() mpd.Rewriter { return mpd.Passthrough{} }
+
+func (a *App) Channels() []appreg.Channel {
+ out := make([]appreg.Channel, 0, len(a.cfg.Channels))
+ for _, id := range a.ChannelIDs() {
+ out = append(out, appreg.Channel{ID: id, Label: a.Label(id)})
+ }
+ return out
+}
+
+// Launch cold-starts ITVX.
+func (a *App) Launch(c *adb.Client) error {
+ c.EnsureAwake()
+ fmt.Printf("[*] Launching %s (%s)…\n", Name, a.Package())
+ c.ForceStop(a.Package())
+ time.Sleep(400 * time.Millisecond)
+ if err := uiflow.MonkeyLaunch(c, a.Package()); err != nil {
+ return err
+ }
+ time.Sleep(time.Duration(a.cfg.Timeouts.LaunchSettle))
+ c.DismissShadeIfFocused()
+ if err := uiflow.WaitUI(c, a.CacheDir(), uiflow.Match{
+ DescContains: a.cfg.UI.LaunchDescContains,
+ }, time.Duration(a.cfg.Timeouts.LaunchWaitUI)); err != nil {
+ fmt.Fprintf(os.Stderr, "[!] launch UI wait: %v — continue and play manually\n", err)
+ }
+ return nil
+}
+
+// AutoPlay opens Live, scrolls to the channel row, and taps WATCH LIVE.
+// Failures return an error so batch capture can report which channel broke.
+func (a *App) AutoPlay(c *adb.Client, channel string) error {
+ id, err := a.Resolve(channel)
+ if err != nil {
+ return err
+ }
+ ch := a.cfg.Channels[id]
+ fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
+ c.DismissShadeIfFocused()
+
+ if err := a.openLiveTab(c); err != nil {
+ return fmt.Errorf("Live tab: %w", err)
+ }
+ if err := a.tapChipThenPlay(c, ch); err != nil {
+ return fmt.Errorf("channel play %s: %w", a.Label(id), err)
+ }
+ return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
+ Timeout: time.Duration(a.cfg.Timeouts.Playback),
+ SoftFail: true,
+ OrDescContains: []string{
+ "on full screen",
+ "Unmute",
+ },
+ })
+}
+
+func (a *App) VideoSelect() string { return "for=best" }
+func (a *App) AudioSelect() string { return "for=best" }
+func (a *App) RewriterName() string { return "none" }
+func (a *App) LiveWaitSeconds() int { return 2 }
+func (a *App) TSReadyBytes() int64 { return 256 << 10 }
diff --git a/apps/modules/itv/module-publish.yaml b/apps/modules/itv/module-publish.yaml
new file mode 100644
index 0000000..7065c4d
--- /dev/null
+++ b/apps/modules/itv/module-publish.yaml
@@ -0,0 +1,90 @@
+# ITVX — published universal values (renamed to module.yaml in release zips).
+# Fill secrets in local module.yaml: license_url, origins, kids (never commit that file).
+# Stub: Live UI matchers are best-effort; tune after a UK-geo phone session.
+
+package: air.ITVMobilePlayer
+proxy_bin: bin/proxy-android-arm64
+
+# SENSITIVE — set in local module.yaml:
+# license_url: "https://…"
+
+# Transparent mode only MITMs open.live by default. Force decrypt of ITVX
+# playlist / license / simulcast hosts observed in phone traffic (suffix match).
+# Segment CDNs (akamai.content) stay passthrough so playback is less likely to break.
+mitm_hosts:
+ - play.dar.itv.com
+ - itvpnp.live.ott.irdeto.com
+ - simulcast.itv.com
+ - secure.pes.itv.com
+ - cpt.itv.com
+ - tom.itv.com
+
+score:
+ hosts:
+ - play.dar.itv.com
+ - itvpnp.live.ott.irdeto.com
+ - simulcast.itv.com
+ - content.itv.com
+ - itv.com
+ - itvstatic.com
+ - irdeto.com
+ deny:
+ - google-analytics
+ - googletagmanager
+ - doubleclick
+ - scorecardresearch
+ - facebook.com
+ - crashlytics
+ - launchdarkly
+ - 2cnt.net
+ - appsflyer
+
+aliases:
+ one: itv1
+ itv: itv1
+ two: itv2
+ three: itv3
+ four: itv4
+ be: itvbe
+ citv: itvxkids
+
+channels:
+ itv1:
+ label: ITV1
+ # Live list rows: "Expand ITV1 info button" / "Collapse ITV1 info button"
+ chip_desc: ["(?i)(Expand|Collapse)\\s+ITV1\\s+info button"]
+ play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITV1\\s+on full screen"]
+ itv2:
+ label: ITV2
+ chip_desc: ["(?i)(Expand|Collapse)\\s+ITV2\\s+info button"]
+ play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITV2\\s+on full screen"]
+ itv3:
+ label: ITV3
+ chip_desc: ["(?i)(Expand|Collapse)\\s+ITV3\\s+info button"]
+ play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITV3\\s+on full screen"]
+ itv4:
+ label: ITV4
+ chip_desc: ["(?i)(Expand|Collapse)\\s+ITV4\\s+info button"]
+ play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITV4\\s+on full screen"]
+ itvbe:
+ label: ITVBe
+ chip_desc: ["(?i)(Expand|Collapse)\\s+ITVBe\\s+info button"]
+ play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITVBe\\s+on full screen"]
+
+ui:
+ launch_desc_contains: ["Home", "Lyve", "Live", "Categories", "ITVX"]
+ live_tab: ["Lyve", "Live"]
+ live_tab_desc_re: ["^Lyve$"]
+ live_tab_text_re: ["^Live$"]
+ watch_live: ["WATCH LIVE", "Watch live", "Watch Live"]
+ playback_desc_contains: ["Unmute", "on full screen", "Pause"]
+ channel_scroll_max: 14
+
+timeouts:
+ launch_wait_ui: 30s
+ launch_settle: 5s
+ live_nav: 20s
+ channel_find: 45s
+ after_channel: 3s
+ watch_live: 20s
+ playback: 60s
diff --git a/apps/modules/itv/steps.go b/apps/modules/itv/steps.go
new file mode 100644
index 0000000..4ac6ac6
--- /dev/null
+++ b/apps/modules/itv/steps.go
@@ -0,0 +1,153 @@
+package itv
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+ "time"
+
+ "streamd/adb"
+ "streamd/uiflow"
+)
+
+// openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve";
+// the visible label is still "Live". Prefer the nav item over "Space Live" rows.
+func (a *App) openLiveTab(c *adb.Client) error {
+ c.DismissShadeIfFocused()
+ if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onLiveTab(nodes) {
+ fmt.Println("[*] already on Live tab")
+ return nil
+ }
+
+ fmt.Println("[*] open Live tab…")
+ descRE := a.cfg.UI.LiveTabDescRE
+ if len(descRE) == 0 {
+ descRE = []string{"^Lyve$"}
+ }
+ textRE := a.cfg.UI.LiveTabTextRE
+ if len(textRE) == 0 {
+ textRE = []string{"^Live$"}
+ }
+ if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
+ DescRE: descRE,
+ TextRE: textRE,
+ Pick: uiflow.PickFirst,
+ }, time.Duration(a.cfg.Timeouts.LiveNav)); err != nil {
+ // Fallback: substring match from publish YAML.
+ if err2 := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
+ DescContains: a.cfg.UI.LiveTab,
+ TextContains: a.cfg.UI.LiveTab,
+ Pick: uiflow.PickFirst,
+ }, 8*time.Second); err2 != nil {
+ return fmt.Errorf("live tab: %w", err)
+ }
+ }
+ time.Sleep(1500 * time.Millisecond)
+
+ deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveNav))
+ for time.Now().Before(deadline) {
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err == nil && a.onLiveTab(nodes) {
+ fmt.Println("[*] Live tab ready")
+ return nil
+ }
+ time.Sleep(700 * time.Millisecond)
+ }
+ return fmt.Errorf("Live tab did not open")
+}
+
+func (a *App) onLiveTab(nodes []adb.Node) bool {
+ for _, n := range nodes {
+ d := strings.ToLower(n.Desc)
+ if strings.HasPrefix(d, "expand ") && strings.Contains(d, " info button") {
+ return true
+ }
+ if strings.HasPrefix(d, "collapse ") && strings.Contains(d, " info button") {
+ return true
+ }
+ if strings.HasPrefix(d, "watch ") && strings.Contains(d, " on full screen") {
+ return true
+ }
+ }
+ return false
+}
+
+// tapChipThenPlay scrolls the Live channel list for Expand/Collapse {label}
+// info button, taps the row, then taps WATCH LIVE / Watch {label} on full screen.
+func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
+ pats := ch.ChipDesc
+ if len(pats) == 0 {
+ pats = []string{`(?i)(Expand|Collapse)\s+` + regexp.QuoteMeta(ch.Label) + `\s+info button`}
+ }
+ chipRE := uiflow.CompileRes(pats)
+ fmt.Printf("[*] find Live row for %s…\n", ch.Label)
+
+ row, err := a.findChannelRow(c, chipRE)
+ if err != nil {
+ return err
+ }
+ // Chevron nodes are often not clickable; tap mid-row to the left of the button.
+ x := 540
+ if row.X1 > 0 && row.X1 < 400 {
+ x = row.CX()
+ }
+ y := row.CY()
+ fmt.Printf("[*] tap channel row %q @ %d,%d\n", row.Desc, x, y)
+ if err := c.Tap(x, y); err != nil {
+ return err
+ }
+ time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
+
+ playRE := ch.PlayDesc
+ if len(playRE) == 0 {
+ playRE = []string{
+ `(?i)^WATCH LIVE$`,
+ `(?i)^Watch\s+` + regexp.QuoteMeta(ch.Label) + `\s+on full screen$`,
+ }
+ }
+ fmt.Println("[*] tap Watch live…")
+ // Prefer the list "WATCH LIVE" text button for the selected row.
+ if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
+ TextRE: playRE,
+ DescRE: playRE,
+ Pick: uiflow.PickFirst,
+ }, time.Duration(a.cfg.Timeouts.WatchLive)); err != nil {
+ return fmt.Errorf("watch live: %w", err)
+ }
+ return nil
+}
+
+func (a *App) findChannelRow(c *adb.Client, chipRE []*regexp.Regexp) (*adb.Node, error) {
+ scrollMax := a.cfg.UI.ChannelScrollMax
+ if scrollMax <= 0 {
+ scrollMax = 12
+ }
+ // Prefer scrolling down from the top so ITV1/ITV2 are reachable.
+ _ = c.Swipe(540, 1200, 540, 1900, 250)
+ time.Sleep(400 * time.Millisecond)
+
+ for attempt := 0; attempt <= scrollMax; attempt++ {
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err != nil {
+ return nil, err
+ }
+ for i := range nodes {
+ n := &nodes[i]
+ if n.Desc == "" {
+ continue
+ }
+ for _, p := range chipRE {
+ if p.MatchString(n.Desc) {
+ return n, nil
+ }
+ }
+ }
+ if attempt == scrollMax {
+ break
+ }
+ fmt.Printf("[*] scroll Live list (%d/%d)…\n", attempt+1, scrollMax)
+ _ = c.Swipe(540, 1950, 540, 1100, 320)
+ time.Sleep(700 * time.Millisecond)
+ }
+ return nil, fmt.Errorf("channel row not found")
+}
diff --git a/apps/modules/my5/config.go b/apps/modules/my5/config.go
new file mode 100644
index 0000000..8720d4f
--- /dev/null
+++ b/apps/modules/my5/config.go
@@ -0,0 +1,133 @@
+package my5
+
+import (
+ "time"
+
+ "streamd/modcfg"
+ "streamd/modules/provider"
+)
+
+// Name is the module id (--app my5).
+const Name = "my5"
+
+// Channel is one My5 / Channel 5 Live TV target.
+// Logos in the Live TV rail have no accessibility text, so selection uses
+// logo_index (0-based order in the left channel-logo recycler).
+type Channel struct {
+ Label string `yaml:"label"`
+ LogoIndex int `yaml:"logo_index"`
+ ChipDesc []string `yaml:"chip_desc"` // unused; kept for YAML parity with other modules
+ PlayDesc []string `yaml:"play_desc"`
+}
+
+// Config is modules/my5/module.yaml (preferred) or apps/modules/my5/module.yaml.
+type Config struct {
+ provider.Common `yaml:",inline"`
+
+ Channels map[string]Channel `yaml:"channels"`
+ Timeouts Timeouts `yaml:"timeouts"`
+ UI UI `yaml:"ui"`
+}
+
+type Timeouts struct {
+ LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
+ LaunchSettle provider.Duration `yaml:"launch_settle"`
+ LiveNav provider.Duration `yaml:"live_nav"`
+ ChannelFind provider.Duration `yaml:"channel_find"`
+ AfterChannel provider.Duration `yaml:"after_channel"`
+ WatchLive provider.Duration `yaml:"watch_live"`
+ Playback provider.Duration `yaml:"playback"`
+}
+
+type UI struct {
+ LaunchDescContains []string `yaml:"launch_desc_contains"`
+ LiveTab []string `yaml:"live_tab"`
+ LiveTabDescRE []string `yaml:"live_tab_desc_re"`
+ LiveTabTextRE []string `yaml:"live_tab_text_re"`
+ WatchLive []string `yaml:"watch_live"`
+ PlaybackDescContains []string `yaml:"playback_desc_contains"`
+ ChannelScrollMax int `yaml:"channel_scroll_max"`
+ // LogoMaxX: ImageViews with X1 below this are treated as channel logos.
+ LogoMaxX int `yaml:"logo_max_x"`
+ // LogoMinY / LogoMaxY: vertical band of the logos recycler (excludes player + nav).
+ LogoMinY int `yaml:"logo_min_y"`
+ LogoMaxY int `yaml:"logo_max_y"`
+}
+
+func (c Config) withDefaults() Config {
+ t := &c.Timeouts
+ t.LaunchWaitUI = provider.Duration(t.LaunchWaitUI.D(30 * time.Second))
+ t.LaunchSettle = provider.Duration(t.LaunchSettle.D(5 * time.Second))
+ t.LiveNav = provider.Duration(t.LiveNav.D(20 * time.Second))
+ t.ChannelFind = provider.Duration(t.ChannelFind.D(45 * time.Second))
+ t.AfterChannel = provider.Duration(t.AfterChannel.D(2 * time.Second))
+ t.WatchLive = provider.Duration(t.WatchLive.D(20 * time.Second))
+ t.Playback = provider.Duration(t.Playback.D(45 * time.Second))
+
+ u := &c.UI
+ if len(u.LaunchDescContains) == 0 {
+ u.LaunchDescContains = []string{"Home", "Live TV", "Search", "More", "Milkshake"}
+ }
+ if len(u.LiveTab) == 0 {
+ u.LiveTab = []string{"Live TV"}
+ }
+ if len(u.LiveTabDescRE) == 0 {
+ u.LiveTabDescRE = []string{`(?i)^Live TV$`}
+ }
+ if len(u.LiveTabTextRE) == 0 {
+ u.LiveTabTextRE = []string{`(?i)^Live TV$`}
+ }
+ if len(u.WatchLive) == 0 {
+ u.WatchLive = []string{"Play", "Watch"}
+ }
+ if len(u.PlaybackDescContains) == 0 {
+ u.PlaybackDescContains = []string{"Pause", "Unmute", "Cast", "Subtitles"}
+ }
+ if u.ChannelScrollMax <= 0 {
+ u.ChannelScrollMax = 20
+ }
+ if u.LogoMaxX <= 0 {
+ u.LogoMaxX = 230
+ }
+ if u.LogoMinY <= 0 {
+ u.LogoMinY = 700
+ }
+ if u.LogoMaxY <= 0 {
+ u.LogoMaxY = 2100
+ }
+ if c.Package == "" {
+ c.Package = "com.mobileiq.demand5"
+ }
+ if c.Channels == nil {
+ c.Channels = map[string]Channel{}
+ }
+ return c
+}
+
+func loadConfig() (Config, modcfg.Result, error) {
+ var cfg Config
+ res, err := modcfg.Load(Name, &cfg)
+ if err != nil {
+ return cfg, res, err
+ }
+ cfg = cfg.withDefaults()
+ if v := modcfg.Env(Name, "package"); v != "" {
+ cfg.Package = v
+ }
+ if flags.packageName != "" {
+ cfg.Package = flags.packageName
+ }
+ if flags.caHash != "" {
+ cfg.CAHash = flags.caHash
+ }
+ if flags.proxyBin != "" {
+ cfg.ProxyBin = flags.proxyBin
+ }
+ return cfg, res, nil
+}
+
+var flags struct {
+ packageName string
+ caHash string
+ proxyBin string
+}
diff --git a/apps/modules/my5/module-publish.yaml b/apps/modules/my5/module-publish.yaml
new file mode 100644
index 0000000..cdb0582
--- /dev/null
+++ b/apps/modules/my5/module-publish.yaml
@@ -0,0 +1,118 @@
+# Channel 5 (My5 / "5") — published universal values (renamed to module.yaml in release zips).
+# Live TV left-rail logos have no accessibility text; selection uses logo_index (0-based).
+
+package: com.mobileiq.demand5
+proxy_bin: bin/proxy-android-arm64
+
+# SENSITIVE — set in local module.yaml after capture:
+# license_url: "https://cassie.channel5.com/api/v2/licences/widevine/…"
+
+# Transparent mode only MITMs open.live by default. Force My5 playlist / license hosts.
+mitm_hosts:
+ - channel5.com
+ - corona.channel5.com
+ - cassie.channel5.com
+ - cassie-auth.channel5.com
+ - hwdash.channel5.com
+ - c5apps.channel5.com
+
+score:
+ hosts:
+ - channel5.com
+ - corona.channel5.com
+ - cassie.channel5.com
+ - cassie-auth.channel5.com
+ - hwdash.channel5.com
+ - akamaized.net
+ - akadash
+ deny:
+ - google-analytics
+ - googletagmanager
+ - doubleclick
+ - scorecardresearch
+ - facebook.com
+ - crashlytics
+ - appsflyer
+ - optimizely
+ - kantarmedia
+
+aliases:
+ c5: channel5
+ five: channel5
+ ch5: channel5
+ channel: channel5
+ my5: channel5
+ usa: 5usa
+ star: 5star
+ action: 5action
+ select: 5select
+ cops: 5cops
+ christmas: 5christmas
+ drama: 5drama
+ crime: 5crime
+ interceptors: policeinterceptors
+ pi: policeinterceptors
+
+channels:
+ # Linear Freeview/Freely channels (logo rail order observed on moto g56).
+ channel5:
+ label: Channel 5
+ logo_index: 0
+ 5usa:
+ label: 5USA
+ logo_index: 1
+ 5star:
+ label: 5STAR
+ logo_index: 2
+ 5action:
+ label: 5ACTION
+ logo_index: 3
+ 5select:
+ label: 5SELECT
+ logo_index: 4
+ # FAST / box-set live rails (indices from Live TV scroll; may shift with seasons).
+ policeinterceptors:
+ label: Police Interceptors
+ logo_index: 5
+ 5cops:
+ label: 5 Cops
+ logo_index: 6
+ 5christmas:
+ label: 5 Christmas
+ logo_index: 7
+ 5drama:
+ label: 5 Drama
+ logo_index: 8
+ bargainbrits:
+ label: Bargain Loving Brits
+ logo_index: 9
+ casualty247:
+ label: Casualty 24/7
+ logo_index: 10
+ rogueclaimers:
+ label: Rogue Claimers
+ logo_index: 11
+ 5crime:
+ label: 5 Crime
+ logo_index: 12
+
+ui:
+ launch_desc_contains: ["Home", "Live TV", "Search", "More", "Milkshake"]
+ live_tab: ["Live TV"]
+ live_tab_desc_re: ["(?i)^Live TV$"]
+ live_tab_text_re: ["(?i)^Live TV$"]
+ watch_live: ["Play", "Watch"]
+ playback_desc_contains: ["Pause", "Unmute", "Cast"]
+ channel_scroll_max: 20
+ logo_max_x: 230
+ logo_min_y: 700
+ logo_max_y: 2100
+
+timeouts:
+ launch_wait_ui: 30s
+ launch_settle: 5s
+ live_nav: 20s
+ channel_find: 45s
+ after_channel: 2s
+ watch_live: 20s
+ playback: 45s
diff --git a/apps/modules/my5/my5.go b/apps/modules/my5/my5.go
new file mode 100644
index 0000000..ebd103b
--- /dev/null
+++ b/apps/modules/my5/my5.go
@@ -0,0 +1,160 @@
+// Package my5 is the Channel 5 (My5 / "5") Live TV provider module.
+// Live TV uses a left-rail of channel logos (no content-desc); selection is by logo_index.
+package my5
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
+)
+
+func init() {
+ appreg.Register(Name, New)
+ appreg.RegisterFlags(bindFlags)
+}
+
+func bindFlags(fs *flag.FlagSet) {
+ fs.StringVar(&flags.packageName, Name+".package", "", "override "+Name+" android package id")
+ fs.StringVar(&flags.caHash, Name+".ca-hash", "", "override "+Name+" MITM CA subject hash")
+ fs.StringVar(&flags.proxyBin, Name+".proxy-bin", "", "override "+Name+" on-device MITM binary")
+}
+
+// App is the My5 plugin.
+type App struct {
+ *provider.Base
+ cfg Config
+}
+
+// New constructs the plugin from module.yaml + flags + env.
+func New() (appreg.App, error) {
+ cfg, res, err := loadConfig()
+ if err != nil {
+ return nil, err
+ }
+ labels := make(map[string]string, len(cfg.Channels))
+ for id, ch := range cfg.Channels {
+ labels[id] = ch.Label
+ }
+ return &App{Base: provider.New(Name, cfg.Common, labels, res), cfg: cfg}, nil
+}
+
+// KeyMode: My5 live uses a raw Widevine license response (Cassie).
+func (a *App) KeyMode() string { return "raw" }
+
+// CaptureHints: transparent MITM should yield the DASH MPD (+ license_url).
+func (a *App) CaptureHints() capture.Hints {
+ return a.Hints("mpd")
+}
+
+// CaptureHintsFor prefers URL substrings for this live channel when known.
+func (a *App) CaptureHintsFor(channel string) capture.Hints {
+ h := a.CaptureHints()
+ id, err := a.Resolve(channel)
+ if err != nil {
+ id = strings.ToLower(strings.TrimSpace(channel))
+ }
+ // Prefer patterns filled after first successful captures; safe no-ops until then.
+ prefer := map[string][]string{
+ "channel5": {"channel5", "c5-", "/c5"},
+ "5usa": {"5usa", "usa"},
+ "5star": {"5star", "star"},
+ "5action": {"5action", "action"},
+ "5select": {"5select", "select"},
+ }
+ if p, ok := prefer[id]; ok {
+ h.PreferURLContains = p
+ }
+ return h
+}
+
+// UseTransparentMITM: UK VPN on-device conflicts with Wi‑Fi http_proxy.
+func (a *App) UseTransparentMITM() bool { return true }
+
+func (a *App) MPDRewriter() mpd.Rewriter { return mpd.Passthrough{} }
+
+func (a *App) Channels() []appreg.Channel {
+ out := make([]appreg.Channel, 0, len(a.cfg.Channels))
+ for _, id := range a.ChannelIDs() {
+ out = append(out, appreg.Channel{ID: id, Label: a.Label(id)})
+ }
+ return out
+}
+
+// Launch cold-starts My5 and dismisses common first-run prompts.
+func (a *App) Launch(c *adb.Client) error {
+ c.EnsureAwake()
+ fmt.Printf("[*] Launching %s (%s)…\n", Name, a.Package())
+ c.ForceStop(a.Package())
+ time.Sleep(400 * time.Millisecond)
+ if err := uiflow.MonkeyLaunch(c, a.Package()); err != nil {
+ return err
+ }
+ time.Sleep(time.Duration(a.cfg.Timeouts.LaunchSettle))
+ c.DismissShadeIfFocused()
+ a.dismissOnboarding(c)
+ if err := uiflow.WaitUI(c, a.CacheDir(), uiflow.Match{
+ DescContains: a.cfg.UI.LaunchDescContains,
+ TextContains: a.cfg.UI.LaunchDescContains,
+ }, time.Duration(a.cfg.Timeouts.LaunchWaitUI)); err != nil {
+ fmt.Fprintf(os.Stderr, "[!] launch UI wait: %v — continue and play manually\n", err)
+ }
+ return nil
+}
+
+// AutoPlay opens Live TV, taps the channel logo by index, then the Now EPG cell.
+func (a *App) AutoPlay(c *adb.Client, channel string) error {
+ id, err := a.Resolve(channel)
+ if err != nil {
+ return err
+ }
+ ch := a.cfg.Channels[id]
+ fmt.Printf("[*] Auto-play %s (logo %d)…\n", a.Label(id), ch.LogoIndex)
+ c.EnsureAwake()
+ c.DismissShadeIfFocused()
+ // Capture host normally Launch()s first; still start the app if we landed on the launcher.
+ if !a.appFocused(c) {
+ if err := a.Launch(c); err != nil {
+ return err
+ }
+ }
+ a.dismissOnboarding(c)
+
+ if err := a.openLiveTab(c); err != nil {
+ return fmt.Errorf("Live TV tab: %w", err)
+ }
+ if err := a.tapChannelLogo(c, ch); err != nil {
+ return fmt.Errorf("channel logo %s: %w", a.Label(id), err)
+ }
+ if err := a.tapNowCell(c, ch); err != nil {
+ fmt.Fprintf(os.Stderr, "[!] Now cell tap: %v — relying on embedded player\n", err)
+ }
+ return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
+ Timeout: time.Duration(a.cfg.Timeouts.Playback),
+ SoftFail: true,
+ OrDescContains: []string{
+ "Pause",
+ "Unmute",
+ "Cast",
+ },
+ OrResourceContains: []string{
+ "c5player",
+ "video_view",
+ "video_player",
+ },
+ })
+}
+
+func (a *App) VideoSelect() string { return "for=best" }
+func (a *App) AudioSelect() string { return "for=best" }
+func (a *App) RewriterName() string { return "none" }
+func (a *App) LiveWaitSeconds() int { return 2 }
+func (a *App) TSReadyBytes() int64 { return 256 << 10 }
diff --git a/apps/modules/my5/steps.go b/apps/modules/my5/steps.go
new file mode 100644
index 0000000..f9fd4f7
--- /dev/null
+++ b/apps/modules/my5/steps.go
@@ -0,0 +1,265 @@
+package my5
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "streamd/adb"
+ "streamd/uiflow"
+)
+
+func (a *App) appFocused(c *adb.Client) bool {
+ out, err := c.Shell("dumpsys", "window")
+ if err != nil {
+ return false
+ }
+ pkg := a.Package()
+ for _, line := range strings.Split(out, "\n") {
+ if strings.Contains(line, "mCurrentFocus") && strings.Contains(line, pkg) {
+ return true
+ }
+ }
+ return false
+}
+
+func (a *App) dismissOnboarding(c *adb.Client) {
+ deadline := time.Now().Add(8 * time.Second)
+ for time.Now().Before(deadline) {
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err != nil {
+ return
+ }
+ for _, n := range nodes {
+ t := strings.TrimSpace(n.Text)
+ switch {
+ case strings.EqualFold(t, "Not now"),
+ strings.EqualFold(t, "Just browse"),
+ strings.EqualFold(t, "Skip register"):
+ fmt.Printf("[*] dismiss %q\n", t)
+ _ = c.Tap(n.CX(), n.CY())
+ time.Sleep(800 * time.Millisecond)
+ goto next
+ }
+ }
+ return
+ next:
+ }
+}
+
+func (a *App) openLiveTab(c *adb.Client) error {
+ c.DismissShadeIfFocused()
+ if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onLiveTab(nodes) {
+ fmt.Println("[*] already on Live TV")
+ return nil
+ }
+
+ fmt.Println("[*] open Live TV…")
+ descRE := a.cfg.UI.LiveTabDescRE
+ if len(descRE) == 0 {
+ descRE = []string{`(?i)^Live TV$`}
+ }
+ textRE := a.cfg.UI.LiveTabTextRE
+ if len(textRE) == 0 {
+ textRE = []string{`(?i)^Live TV$`}
+ }
+ if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
+ DescRE: descRE,
+ TextRE: textRE,
+ DescContains: a.cfg.UI.LiveTab,
+ TextContains: a.cfg.UI.LiveTab,
+ Pick: uiflow.PickFirst,
+ }, time.Duration(a.cfg.Timeouts.LiveNav)); err != nil {
+ return fmt.Errorf("live tab: %w", err)
+ }
+ time.Sleep(1500 * time.Millisecond)
+
+ deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveNav))
+ for time.Now().Before(deadline) {
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err == nil && a.onLiveTab(nodes) {
+ fmt.Println("[*] Live TV ready")
+ return nil
+ }
+ time.Sleep(700 * time.Millisecond)
+ }
+ return fmt.Errorf("Live TV did not open")
+}
+
+func (a *App) onLiveTab(nodes []adb.Node) bool {
+ for _, n := range nodes {
+ id := strings.ToLower(n.ResourceID)
+ if strings.Contains(id, "tv_guide_channel_logos") ||
+ strings.Contains(id, "tv_guide_epg") ||
+ strings.Contains(id, "tv_guide_player") ||
+ strings.Contains(id, "tv_guide_navigation") && n.Selected {
+ return true
+ }
+ if strings.EqualFold(n.Text, "Now") && strings.Contains(id, "tv_guide_header_now") {
+ return true
+ }
+ }
+ return false
+}
+
+func (a *App) logoNodes(nodes []adb.Node) []adb.Node {
+ maxX := a.cfg.UI.LogoMaxX
+ minY := a.cfg.UI.LogoMinY
+ maxY := a.cfg.UI.LogoMaxY
+ var out []adb.Node
+ for _, n := range nodes {
+ if !strings.Contains(n.Class, "ImageView") {
+ continue
+ }
+ // Channel logos in the Live rail have empty resource-id; EPG thumbs do not.
+ if strings.TrimSpace(n.ResourceID) != "" {
+ continue
+ }
+ if n.X1 >= maxX || n.Y1 < minY || n.Y1 >= maxY {
+ continue
+ }
+ // Skip tiny icons / nav glyphs.
+ if (n.Y2-n.Y1) < 120 || (n.X2-n.X1) < 120 {
+ continue
+ }
+ if !n.Clickable {
+ continue
+ }
+ out = append(out, n)
+ }
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].Y1 == out[j].Y1 {
+ return out[i].X1 < out[j].X1
+ }
+ return out[i].Y1 < out[j].Y1
+ })
+ return out
+}
+
+// tapChannelLogo scrolls the left logo rail from the top by logo_index rows, then taps.
+func (a *App) tapChannelLogo(c *adb.Client, ch Channel) error {
+ want := ch.LogoIndex
+ if want < 0 {
+ return fmt.Errorf("logo_index must be >= 0")
+ }
+ fmt.Printf("[*] find logo index %d (%s)…\n", want, ch.Label)
+
+ // Scroll to the top of the logo rail.
+ for i := 0; i < 8; i++ {
+ _ = c.Swipe(118, 1000, 118, 1950, 250)
+ time.Sleep(280 * time.Millisecond)
+ }
+ time.Sleep(400 * time.Millisecond)
+
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err != nil {
+ return err
+ }
+ logos := a.logoNodes(nodes)
+ if len(logos) == 0 {
+ return fmt.Errorf("no channel logos visible")
+ }
+ rowH := logos[0].Y2 - logos[0].Y1
+ if rowH < 120 {
+ rowH = 205
+ }
+ // Gap between rows is small; step ≈ row height + ~10px from observed layout.
+ step := rowH + 10
+
+ // Bring target near the top by single-row swipes, then tap it in-view.
+ for i := 0; i < want; i++ {
+ _ = c.Swipe(118, 1200, 118, 1200-step, 220)
+ time.Sleep(350 * time.Millisecond)
+ }
+ time.Sleep(400 * time.Millisecond)
+
+ nodes, err = c.DumpUI(a.CacheDir())
+ if err != nil {
+ return err
+ }
+ logos = a.logoNodes(nodes)
+ if len(logos) == 0 {
+ return fmt.Errorf("no channel logos after scroll to index %d", want)
+ }
+
+ var n adb.Node
+ if want == 0 {
+ n = logos[0]
+ } else {
+ // After want single-row swipes from top, the target is the first fully
+ // visible logo (previous rows scrolled off). Prefer logos[0] when fully
+ // on-screen; otherwise logos[1] if the top one is clipped.
+ n = logos[0]
+ if n.Y1 < a.cfg.UI.LogoMinY+5 && len(logos) > 1 {
+ n = logos[1]
+ }
+ }
+ if n.CY() >= 2050 || n.Y2 > a.cfg.UI.LogoMaxY {
+ return fmt.Errorf("logo index %d clipped into nav", want)
+ }
+ fmt.Printf("[*] tap logo %d @ %d,%d\n", want, n.CX(), n.CY())
+ if err := c.Tap(n.CX(), n.CY()); err != nil {
+ return err
+ }
+ time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
+ return nil
+}
+
+func abs(v int) int {
+ if v < 0 {
+ return -v
+ }
+ return v
+}
+
+// tapNowCell taps the "Now" EPG cell aligned with the selected logo row.
+// After tapChannelLogo scrolls the target to the top of the rail, align to logos[0].
+func (a *App) tapNowCell(c *adb.Client, ch Channel) error {
+ _ = ch
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err != nil {
+ return err
+ }
+ logos := a.logoNodes(nodes)
+ if len(logos) == 0 {
+ return fmt.Errorf("no logos after select")
+ }
+ logo := &logos[0]
+ if logo.Y1 < a.cfg.UI.LogoMinY+5 && len(logos) > 1 {
+ logo = &logos[1]
+ }
+
+ var best *adb.Node
+ bestDist := 1 << 30
+ for i := range nodes {
+ n := &nodes[i]
+ id := strings.ToLower(n.ResourceID)
+ if !strings.Contains(id, "epg_now_view") {
+ continue
+ }
+ d := abs(n.CY() - logo.CY())
+ if d < bestDist {
+ bestDist = d
+ best = n
+ }
+ }
+ if best == nil {
+ // Fallback: tap embedded player surface.
+ for i := range nodes {
+ n := &nodes[i]
+ id := strings.ToLower(n.ResourceID)
+ if strings.Contains(id, "video_view") || strings.Contains(id, "c5player") {
+ fmt.Printf("[*] tap player @ %d,%d\n", n.CX(), n.CY())
+ return c.Tap(n.CX(), n.CY())
+ }
+ }
+ return fmt.Errorf("Now cell not found")
+ }
+ fmt.Printf("[*] tap Now cell @ %d,%d\n", best.CX(), best.CY())
+ if err := c.Tap(best.CX(), best.CY()); err != nil {
+ return err
+ }
+ time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
+ return nil
+}
diff --git a/apps/modules/provider/provider.go b/apps/modules/provider/provider.go
index ab76703..1b0f919 100644
--- a/apps/modules/provider/provider.go
+++ b/apps/modules/provider/provider.go
@@ -10,10 +10,10 @@ import (
"sort"
"strings"
- "drmdecryption/capture"
- "drmdecryption/modcfg"
- "drmdecryption/phonecap"
- "drmdecryption/repo"
+ "streamd/capture"
+ "streamd/modcfg"
+ "streamd/phonecap"
+ "streamd/repo"
)
// Common is the part of a module.yaml that every module has. Modules embed it in
@@ -25,6 +25,9 @@ type Common struct {
CAHash string `yaml:"ca_hash"`
Aliases map[string]string `yaml:"aliases"`
Score capture.ScoreCfg `yaml:"score"`
+ // MitmHosts are forced into transparent MITM via -mitm-host (suffix match).
+ // Transparent mode otherwise passthroughs everything except open.live.bbc.co.uk.
+ MitmHosts []string `yaml:"mitm_hosts"`
}
// Base implements the boilerplate half of app.App.
@@ -54,7 +57,7 @@ func (b *Base) ConfigPath() string { return b.cfg.Path }
func (b *Base) ConfigLoaded() bool { return b.cfg.Loaded }
// ProxyBin resolves the on-device MITM binary. Empty means “auto” (caller uses
-// proxy.FindLocalBin — next to drm.exe, then repo bin/).
+// proxy.FindLocalBin — next to streamd, then repo bin/).
func (b *Base) ProxyBin() string {
if b.common.ProxyBin != "" {
return modcfg.Resolve(b.common.ProxyBin)
@@ -94,6 +97,18 @@ func (b *Base) Score() capture.ScoreCfg {
return capture.DefaultScoreCfg().Merge(b.common.Score)
}
+// MitmHosts returns hosts the transparent MITM must decrypt (empty = BBC open.live only).
+func (b *Base) MitmHosts() []string {
+ out := make([]string, 0, len(b.common.MitmHosts))
+ for _, h := range b.common.MitmHosts {
+ h = strings.TrimSpace(strings.ToLower(h))
+ if h != "" {
+ out = append(out, h)
+ }
+ }
+ return out
+}
+
// Hints returns device-layout hints with this module's scoring applied.
func (b *Base) Hints(require ...string) capture.Hints {
h := capture.DefaultHints()
diff --git a/apps/modules/rte/config.go b/apps/modules/rte/config.go
index c67b99d..f01d3db 100644
--- a/apps/modules/rte/config.go
+++ b/apps/modules/rte/config.go
@@ -3,9 +3,9 @@ package rte
import (
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
+ "streamd/modcfg"
+ "streamd/modules/provider"
+ "streamd/mpd"
)
// Name is the module id (--app rte).
@@ -87,10 +87,12 @@ func (c Config) withDefaults() Config {
t.AfterLiveTab = provider.Duration(t.AfterLiveTab.D(2 * time.Second))
t.AfterChip = provider.Duration(t.AfterChip.D(2 * time.Second))
if len(c.UI.LaunchDescContains) == 0 {
- c.UI.LaunchDescContains = []string{"live tab", "header logo"}
+ c.UI.LaunchDescContains = []string{"live tab", "header logo", "Home tab"}
}
if len(c.UI.LiveTabDescRE) == 0 {
- c.UI.LiveTabDescRE = []string{"Live tab"}
+ // Anchor to the bottom-nav desc ("Live tab, 2 out of 5"). Bare "Live"
+ // also matches home "Watch Live" / "Live Event".
+ c.UI.LiveTabDescRE = []string{"^Live tab"}
}
c.Synthetic = c.Synthetic.WithDefaults()
return c
diff --git a/apps/modules/rte/live_test.go b/apps/modules/rte/live_test.go
index b89e50a..329a1b1 100644
--- a/apps/modules/rte/live_test.go
+++ b/apps/modules/rte/live_test.go
@@ -12,7 +12,7 @@ import (
"strings"
"testing"
- "drmdecryption/mpd"
+ "streamd/mpd"
)
// The rewriter must publish a usable manifest from the KID alone — this is the
diff --git a/apps/modules/rte/module-publish.yaml b/apps/modules/rte/module-publish.yaml
index a70fe79..41cf041 100644
--- a/apps/modules/rte/module-publish.yaml
+++ b/apps/modules/rte/module-publish.yaml
@@ -50,8 +50,9 @@ channels:
# vc12: "…"
ui:
- launch_desc_contains: ["live tab", "header logo", "Live"]
- live_tab_desc_re: ["Live tab", "Live"]
+ # "Live" alone matches home "Watch Live" / "Live Event" — keep anchored to the bottom tab.
+ launch_desc_contains: ["live tab", "header logo", "Home tab"]
+ live_tab_desc_re: ["^Live tab"]
timeouts:
launch_wait_ui: 30s
diff --git a/apps/modules/rte/mpd.go b/apps/modules/rte/mpd.go
index 2d5a31b..6c91a05 100644
--- a/apps/modules/rte/mpd.go
+++ b/apps/modules/rte/mpd.go
@@ -6,7 +6,7 @@ import (
"strings"
"sync"
- "drmdecryption/mpd"
+ "streamd/mpd"
)
func init() {
diff --git a/apps/modules/rte/rte.go b/apps/modules/rte/rte.go
index 04e1326..ec8ec12 100644
--- a/apps/modules/rte/rte.go
+++ b/apps/modules/rte/rte.go
@@ -9,12 +9,12 @@ import (
"fmt"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
@@ -84,7 +84,7 @@ func (a *App) Launch(c *adb.Client) error {
}, time.Duration(a.cfg.Timeouts.LaunchWaitUI))
}
-// AutoPlay navigates to a live channel and waits for playback.
+// AutoPlay opens the Live tab (when needed), taps the channel chip, then Play.
func (a *App) AutoPlay(c *adb.Client, channel string) error {
id, err := a.Resolve(channel)
if err != nil {
@@ -94,13 +94,9 @@ func (a *App) AutoPlay(c *adb.Client, channel string) error {
fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
c.DismissShadeIfFocused()
- if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
- DescRE: a.cfg.UI.LiveTabDescRE,
- }, time.Duration(a.cfg.Timeouts.LiveTab)); err != nil {
- return fmt.Errorf("live tab: %w", err)
+ if err := a.openLiveTab(c); err != nil {
+ return err
}
- time.Sleep(time.Duration(a.cfg.Timeouts.AfterLiveTab))
-
if err := a.tapChipThenPlay(c, ch); err != nil {
return err
}
diff --git a/apps/modules/rte/rte_test.go b/apps/modules/rte/rte_test.go
index eb08cc1..faf3cfd 100644
--- a/apps/modules/rte/rte_test.go
+++ b/apps/modules/rte/rte_test.go
@@ -4,8 +4,8 @@ import (
"strings"
"testing"
- appreg "drmdecryption/app"
- "drmdecryption/mpd"
+ appreg "streamd/app"
+ "streamd/mpd"
)
// Compile-time proof the plugin satisfies every interface the host expects.
diff --git a/apps/modules/rte/steps.go b/apps/modules/rte/steps.go
index 4b92f0b..584e2d1 100644
--- a/apps/modules/rte/steps.go
+++ b/apps/modules/rte/steps.go
@@ -5,13 +5,62 @@ import (
"regexp"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
+// openLiveTab taps the bottom-nav Live tab and waits for channel chips.
+// Home also shows a "Watch Live" label and a "Live Event" row — those must not
+// match. The real control's content-desc is "Live tab, N out of 5".
+func (a *App) openLiveTab(c *adb.Client) error {
+ c.DismissShadeIfFocused()
+ if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onLiveTab(nodes) {
+ fmt.Println("[*] already on Live tab")
+ return nil
+ }
+
+ fmt.Println("[*] open Live tab…")
+ if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
+ DescRE: a.cfg.UI.LiveTabDescRE,
+ Pick: uiflow.PickSmallest,
+ }, time.Duration(a.cfg.Timeouts.LiveTab)); err != nil {
+ return fmt.Errorf("live tab: %w", err)
+ }
+ time.Sleep(time.Duration(a.cfg.Timeouts.AfterLiveTab))
+
+ deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveTab))
+ for time.Now().Before(deadline) {
+ nodes, err := c.DumpUI(a.CacheDir())
+ if err == nil && a.onLiveTab(nodes) {
+ fmt.Println("[*] Live tab ready")
+ return nil
+ }
+ time.Sleep(700 * time.Millisecond)
+ }
+ return fmt.Errorf("Live tab did not open")
+}
+
+// onLiveTab is true when channel chips are on screen. Home often embeds the
+// same chip rail, so this also short-circuits when Play is already reachable
+// without tapping the bottom-nav Live tab.
+func (a *App) onLiveTab(nodes []adb.Node) bool {
+ return a.chipCount(nodes) >= 1
+}
+
+func (a *App) chipCount(nodes []adb.Node) int {
+ n := 0
+ for _, ch := range a.cfg.Channels {
+ pats := uiflow.CompileRes(ch.ChipDesc)
+ if adb.FindSmallest(nodes, pats) != nil {
+ n++
+ }
+ }
+ return n
+}
+
// tapChipThenPlay is this app's navigation idiom: on the Live tab, tap the
// channel chip, then the large hero Play button that appears. If the hero button
-// is already on screen, tap it directly.
+// is already on screen for this channel, tap it directly.
func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
playPats := uiflow.CompileRes(ch.PlayDesc)
chipPats := uiflow.CompileRes(ch.ChipDesc)
@@ -21,18 +70,30 @@ func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
return err
}
if cand := a.findHeroPlay(nodes, playPats); cand != nil {
- fmt.Printf("[*] tap Play @ %d,%d\n", cand.CX(), cand.CY())
- return c.Tap(cand.CX(), cand.CY())
+ x, y := playTapXY(cand)
+ fmt.Printf("[*] tap Play %q @ %d,%d\n", cand.Desc, x, y)
+ return c.Tap(x, y)
}
chip := adb.FindSmallest(nodes, chipPats)
if chip == nil {
- chip, err = c.WaitFor(a.CacheDir(), nil, chipPats, time.Duration(a.cfg.Timeouts.ChipWait))
- if err != nil {
- return fmt.Errorf("chip not found: %w", err)
+ deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.ChipWait))
+ for time.Now().Before(deadline) {
+ nodes, err = c.DumpUI(a.CacheDir())
+ if err == nil {
+ if chip = adb.FindSmallest(nodes, chipPats); chip != nil {
+ break
+ }
+ }
+ time.Sleep(700 * time.Millisecond)
+ }
+ if chip == nil {
+ return fmt.Errorf("chip not found for %s", ch.Label)
}
}
- fmt.Printf("[*] tap chip @ %d,%d\n", chip.CX(), chip.CY())
+ // Chip text nodes are often clickable=false; their centre sits inside a
+ // larger clickable parent, so a centre tap still lands on the parent.
+ fmt.Printf("[*] tap chip %q @ %d,%d\n", chip.Desc, chip.CX(), chip.CY())
_ = c.Tap(chip.CX(), chip.CY())
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChip))
@@ -41,13 +102,14 @@ func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
nodes, err = c.DumpUI(a.CacheDir())
if err == nil {
if cand := a.findHeroPlay(nodes, playPats); cand != nil {
- fmt.Printf("[*] tap Play @ %d,%d\n", cand.CX(), cand.CY())
- return c.Tap(cand.CX(), cand.CY())
+ x, y := playTapXY(cand)
+ fmt.Printf("[*] tap Play %q @ %d,%d\n", cand.Desc, x, y)
+ return c.Tap(x, y)
}
}
time.Sleep(700 * time.Millisecond)
}
- return fmt.Errorf("Play button did not appear")
+ return fmt.Errorf("Play button did not appear for %s", ch.Label)
}
// findHeroPlay accepts a Play match only if it is big enough to be the hero
@@ -59,3 +121,14 @@ func (a *App) findHeroPlay(nodes []adb.Node, playPats []*regexp.Regexp) *adb.Nod
}
return cand
}
+
+// playTapXY aims at the play icon in the upper half of the hero. The geometric
+// centre of the large "Play RTEONE…" node often lands below the hit target and
+// the tap is ignored.
+func playTapXY(n *adb.Node) (int, int) {
+ h := n.Y2 - n.Y1
+ if h < 1 {
+ return n.CX(), n.CY()
+ }
+ return n.CX(), n.Y1 + h*2/5
+}
diff --git a/apps/modules/tg4/catalog.go b/apps/modules/tg4/catalog.go
index a80501d..5afaada 100644
--- a/apps/modules/tg4/catalog.go
+++ b/apps/modules/tg4/catalog.go
@@ -6,9 +6,9 @@ import (
"net/http"
"strings"
- appreg "drmdecryption/app"
- "drmdecryption/brightcove"
- "drmdecryption/session"
+ appreg "streamd/app"
+ "streamd/brightcove"
+ "streamd/session"
)
// playbackConfig is the app's remote config blob. It is decoded generically: the
diff --git a/apps/modules/tg4/config.go b/apps/modules/tg4/config.go
index 2162ed7..3fef619 100644
--- a/apps/modules/tg4/config.go
+++ b/apps/modules/tg4/config.go
@@ -3,9 +3,9 @@ package tg4
import (
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
- "drmdecryption/uiflow"
+ "streamd/modcfg"
+ "streamd/modules/provider"
+ "streamd/uiflow"
)
// Name is the module id (--app tg4).
diff --git a/apps/modules/tg4/keys.go b/apps/modules/tg4/keys.go
index a14db24..5ec6cd1 100644
--- a/apps/modules/tg4/keys.go
+++ b/apps/modules/tg4/keys.go
@@ -5,10 +5,10 @@ import (
"path/filepath"
"strings"
- "drmdecryption/brightcove"
- "drmdecryption/repo"
- "drmdecryption/session"
- "drmdecryption/wvkey"
+ "streamd/brightcove"
+ "streamd/repo"
+ "streamd/session"
+ "streamd/wvkey"
)
// EnrichWithKeys fetches the HLS master, extracts the Widevine PSSH and resolves
diff --git a/apps/modules/tg4/steps.go b/apps/modules/tg4/steps.go
index 3b5040b..b915877 100644
--- a/apps/modules/tg4/steps.go
+++ b/apps/modules/tg4/steps.go
@@ -5,8 +5,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
// openLivePage navigates to the Live page: if a menu entry is visible tap it,
diff --git a/apps/modules/tg4/tg4.go b/apps/modules/tg4/tg4.go
index 8e20653..d1f1a62 100644
--- a/apps/modules/tg4/tg4.go
+++ b/apps/modules/tg4/tg4.go
@@ -10,12 +10,12 @@ import (
"fmt"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
diff --git a/apps/modules/tg4/tg4_test.go b/apps/modules/tg4/tg4_test.go
index cc16fc6..1e16891 100644
--- a/apps/modules/tg4/tg4_test.go
+++ b/apps/modules/tg4/tg4_test.go
@@ -3,9 +3,9 @@ package tg4
import (
"testing"
- appreg "drmdecryption/app"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
+ appreg "streamd/app"
+ "streamd/modcfg"
+ "streamd/modules/provider"
)
// Compile-time proof the plugin satisfies every interface the host expects.
diff --git a/apps/pkg/README.md b/apps/pkg/README.md
index 05a5413..6d17d2b 100644
--- a/apps/pkg/README.md
+++ b/apps/pkg/README.md
@@ -1,10 +1,10 @@
# pkg — shared Go libraries
Imported by `apps/capture`, `apps/agent`, `apps/streamd`, `apps/proxy`, `apps/cli`
-and `apps/modules` as module `drmdecryption` via:
+and `apps/modules` as module `streamd` via:
```go
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
```
## Packages
@@ -34,4 +34,4 @@ provider values live in that module's gitignored `module.yaml`.
go -C apps/pkg test ./...
```
-No binary of its own — everything ships in `bin/drm`, built from `apps/cli`.
+No binary of its own — everything ships in `bin/streamd`, built from `apps/cli`.
diff --git a/apps/pkg/adb/adb.go b/apps/pkg/adb/adb.go
index eb1fa3a..6d1ec85 100644
--- a/apps/pkg/adb/adb.go
+++ b/apps/pkg/adb/adb.go
@@ -219,6 +219,8 @@ type Node struct {
Class string
ResourceID string
Clickable bool
+ Selected bool
+ Checked bool
X1, Y1 int
X2, Y2 int
}
@@ -260,6 +262,8 @@ func parseNodes(xml string) []Node {
Class: attr("class"),
ResourceID: attr("resource-id"),
Clickable: attr("clickable") == "true",
+ Selected: attr("selected") == "true",
+ Checked: attr("checked") == "true",
X1: x1, Y1: y1, X2: x2, Y2: y2,
})
}
diff --git a/apps/pkg/app/app.go b/apps/pkg/app/app.go
index 13617f9..a78b688 100644
--- a/apps/pkg/app/app.go
+++ b/apps/pkg/app/app.go
@@ -6,10 +6,10 @@ import (
"sort"
"sync"
- "drmdecryption/adb"
- "drmdecryption/capture"
- "drmdecryption/mpd"
- "drmdecryption/session"
+ "streamd/adb"
+ "streamd/capture"
+ "streamd/mpd"
+ "streamd/session"
)
// Channel is a named live target inside an app (e.g. rteone).
@@ -83,6 +83,25 @@ type TransparentMITM interface {
UseTransparentMITM() bool
}
+// MitmHostList is implemented by apps that need extra -mitm-host entries in
+// transparent mode (default MITM is only open.live.bbc.co.uk).
+type MitmHostList interface {
+ MitmHosts() []string
+}
+
+// ChannelCaptureHints lets a module bias Wait scoring for a specific channel
+// (e.g. prefer channel(e4) MPD when capturing E4 while neighbours prefetch).
+type ChannelCaptureHints interface {
+ CaptureHintsFor(channel string) capture.Hints
+}
+
+// RequireWVD is implemented by apps that refuse MPD-only captures. When true,
+// `drm capture --app …` must pass --wvd; phonecap will not soft-save a session
+// without keys.
+type RequireWVD interface {
+ RequireWVD() bool
+}
+
var (
mu sync.RWMutex
registry = map[string]func() (App, error){}
diff --git a/apps/pkg/bootstrap/bootstrap.go b/apps/pkg/bootstrap/bootstrap.go
index 1ec264c..52ff36b 100644
--- a/apps/pkg/bootstrap/bootstrap.go
+++ b/apps/pkg/bootstrap/bootstrap.go
@@ -1,4 +1,4 @@
-// Package bootstrap materialises a GitHub-like install tree next to drm.exe
+// Package bootstrap materialises a GitHub-like install tree next to streamd
// so a single downloaded binary can create apps/, bin/, outputs/, etc. on first run.
package bootstrap
@@ -17,7 +17,7 @@ var embedded embed.FS
const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB
// InstallRoot is the directory that should contain apps/, bin/, outputs/.
-// If drm.exe lives in …/bin/, the parent is the root; otherwise the exe directory.
+// If streamd lives in …/bin/, the parent is the root; otherwise the exe directory.
func InstallRoot() (string, error) {
exe, err := os.Executable()
if err != nil {
@@ -91,27 +91,30 @@ func Ensure(root string) (created []string, err error) {
return created, err
}
- // If drm is not already under bin/, copy/link a drm.exe there for 1:1 layout.
- if err := ensureBinDrm(root); err != nil {
+ // If streamd is not already under bin/, copy it there for 1:1 layout.
+ if err := ensureBinHost(root); err != nil {
return created, err
}
return created, nil
}
-func ensureBinDrm(root string) error {
+func ensureBinHost(root string) error {
exe, err := os.Executable()
if err != nil {
return nil
}
exe, _ = filepath.EvalSymlinks(exe)
- dest := filepath.Join(root, "bin", "drm.exe")
- if sameFile(exe, dest) {
+ return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe"))
+}
+
+func copyExeIfMissing(src, dest string) error {
+ if sameFile(src, dest) {
return nil
}
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
return nil
}
- data, err := os.ReadFile(exe)
+ data, err := os.ReadFile(src)
if err != nil {
return err
}
@@ -154,7 +157,7 @@ func EnsureAndLogFor(cmd string) error {
}
proxy := filepath.Join(root, "bin", "proxy-android-arm64")
if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes {
- fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to drm or use a release build that embeds it\n")
+ fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to streamd or use a release build that embeds it\n")
}
// Providers live under modules/; only warn when the command needs them.
needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve"
diff --git a/apps/pkg/bootstrap/embedded/README.md b/apps/pkg/bootstrap/embedded/README.md
index 6773ac9..e4e6cc8 100644
--- a/apps/pkg/bootstrap/embedded/README.md
+++ b/apps/pkg/bootstrap/embedded/README.md
@@ -1,14 +1,14 @@
-# Null DRM
+# Streamd
-Host binary **`drm`** + providers under **`modules/`**.
+Host binary **`streamd`** + providers under **`modules/`**.
## Quick start
-1. Download `drm` (`v*` release) and module zips (`modules-v*` release).
+1. Download `streamd` (`v*` release) and module zips (`modules-v*` release).
2. Unzip providers into `modules//` and edit `module.yaml` (secrets only).
-3. `drm proxy install-ca --reinject`
-4. `drm capture --app bbc --channel bbcone --wait 120`
-5. `drm proxy reset` when finished.
+3. `streamd proxy install-ca --reinject`
+4. `streamd capture --app bbc --channel bbcone --wait 120`
+5. `streamd proxy reset` when finished.
```text
drm modules
@@ -17,6 +17,6 @@ drm catalog --app NAME --channel ID [--keys] [--json]
drm proxy install-ca --reinject | reset | transparent --package PKG
```
-`--modules-dir DIR` or `$DRM_MODULES_DIR` selects another modules folder.
+`--modules-dir DIR` or `$STREAMD_MODULES_DIR` selects another modules folder.
Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official
diff --git a/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod b/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
index c23f9f3..1b7a669 100644
--- a/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
+++ b/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
go 1.25.0
diff --git a/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt b/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt
new file mode 100644
index 0000000..9c8759c
--- /dev/null
+++ b/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt
@@ -0,0 +1,6 @@
+# Dependencies for wvkey.py (the only Python in the project).
+# Install into a venv at the repo root:
+# python -m venv .venv
+# .venv/bin/pip install -r apps/wvkey/requirements.txt
+pywidevine==1.9.0
+requests==2.34.2
diff --git a/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py b/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py
new file mode 100644
index 0000000..87c9e43
--- /dev/null
+++ b/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py
@@ -0,0 +1,367 @@
+#!/usr/bin/env python3
+"""Thin Widevine CDM helper for the Go capture tooling.
+
+Prints a single CONTENT key as KID:KEY on stdout (no banners) when --quiet.
+Exit code 0 on success.
+
+Example:
+ .venv/Scripts/python.exe wvkey.py \\
+ --wvd path/to/device.wvd \\
+ --pssh 'AAAA…' \\
+ --license-url 'https://…' \\
+ --auth 'Basic …' \\
+ --pid 'xxxx' \\
+ --quiet
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+import sys
+from pathlib import Path
+
+import requests
+from pywidevine.cdm import Cdm
+from pywidevine.device import Device
+from pywidevine.pssh import PSSH
+
+
+def fetch_content_keys_modulardrm(
+ *,
+ wvd: Path,
+ pssh_b64: str,
+ auth: str,
+ release_pid: str,
+ license_url: str,
+ user_agent: str,
+) -> list[str]:
+ """RTE / thePlatform ModularDrm (JSON challenge wrapper)."""
+ device = Device.load(str(wvd))
+ cdm = Cdm.from_device(device)
+ session_id = cdm.open()
+ try:
+ challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
+ challenge_b64 = base64.b64encode(challenge).decode("utf-8")
+ payload = {
+ "getWidevineLicense": {
+ "releasePid": release_pid,
+ "widevineChallenge": challenge_b64,
+ }
+ }
+ headers = {
+ "Accept-Encoding": "gzip",
+ "Authorization": auth,
+ "Content-Type": "application/json; charset=utf-8",
+ }
+ if user_agent:
+ headers["User-Agent"] = user_agent
+ response = requests.post(license_url, json=payload, headers=headers, timeout=30)
+ data = response.json()
+ if data.get("isException"):
+ raise RuntimeError(data.get("description") or "license server exception")
+ license_b64 = (
+ data.get("getWidevineLicenseResponse", {}).get("license")
+ or data.get("license")
+ )
+ if not license_b64:
+ raise RuntimeError("no license in response: " + json.dumps(data)[:1500])
+ cdm.parse_license(session_id, base64.b64decode(license_b64))
+ keys = [
+ f"{key.kid.hex}:{key.key.hex()}"
+ for key in cdm.get_keys(session_id)
+ if key.type == "CONTENT"
+ ]
+ finally:
+ cdm.close(session_id)
+ if not keys:
+ raise RuntimeError("no CONTENT keys")
+ return keys
+
+
+def fetch_content_keys_raw(
+ *,
+ wvd: Path,
+ pssh_b64: str,
+ license_url: str,
+ user_agent: str,
+) -> list[str]:
+ """Brightcove / generic Widevine: POST raw challenge, parse raw license body."""
+ device = Device.load(str(wvd))
+ cdm = Cdm.from_device(device)
+ session_id = cdm.open()
+ try:
+ challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
+ headers = {
+ "Content-Type": "application/octet-stream",
+ "Accept": "*/*",
+ }
+ if user_agent:
+ headers["User-Agent"] = user_agent
+ response = requests.post(
+ license_url, data=challenge, headers=headers, timeout=30
+ )
+ if response.status_code >= 400:
+ raise RuntimeError(
+ f"license HTTP {response.status_code}: {response.text[:500]!r}"
+ )
+ body = response.content
+ if not body:
+ raise RuntimeError("empty license response body")
+ # Some servers wrap base64 text; try raw first, then b64.
+ try:
+ cdm.parse_license(session_id, body)
+ except Exception:
+ try:
+ cdm.parse_license(session_id, base64.b64decode(body))
+ except Exception as exc:
+ raise RuntimeError(
+ f"parse_license failed ({len(body)} bytes): {exc}"
+ ) from exc
+ keys = [
+ f"{key.kid.hex}:{key.key.hex()}"
+ for key in cdm.get_keys(session_id)
+ if key.type == "CONTENT"
+ ]
+ finally:
+ cdm.close(session_id)
+ if not keys:
+ raise RuntimeError("no CONTENT keys")
+ return keys
+
+
+_CHALLENGE_KEYS = (
+ "request",
+ "licenseRequest",
+ "license_request",
+ "widevineChallenge",
+ "widevine_challenge",
+ "challenge",
+ "payload",
+ "rawLicenseRequestBase64",
+ "message",
+ "drm_info",
+)
+
+
+def _replace_challenge(obj, challenge_b64: str, challenge_bytes: bytes) -> bool:
+ """Replace the Widevine challenge field inside a captured JSON license body."""
+ if isinstance(obj, dict):
+ for key in _CHALLENGE_KEYS:
+ if key not in obj:
+ continue
+ val = obj[key]
+ if key == "drm_info" and isinstance(val, list):
+ obj[key] = list(challenge_bytes)
+ return True
+ if isinstance(val, str) and len(val) >= 8:
+ obj[key] = challenge_b64
+ return True
+ if isinstance(val, dict) and _replace_challenge(val, challenge_b64, challenge_bytes):
+ return True
+ for val in obj.values():
+ if _replace_challenge(val, challenge_b64, challenge_bytes):
+ return True
+ elif isinstance(obj, list):
+ for item in obj:
+ if _replace_challenge(item, challenge_b64, challenge_bytes):
+ return True
+ return False
+
+
+def _license_bytes_from_response(response: requests.Response) -> bytes:
+ body = response.content
+ if not body:
+ raise RuntimeError("empty license response body")
+ # Prefer JSON wrappers used by RedBee / ModularDrm-style proxies.
+ try:
+ data = response.json()
+ except Exception:
+ data = None
+ if isinstance(data, dict):
+ for path in (
+ ("license",),
+ ("licenseResponse",),
+ ("license_response",),
+ ("payload",),
+ ("message",),
+ ("getWidevineLicenseResponse", "license"),
+ ("status", "license"),
+ ):
+ cur: object = data
+ ok = True
+ for key in path:
+ if not isinstance(cur, dict) or key not in cur:
+ ok = False
+ break
+ cur = cur[key]
+ if ok and isinstance(cur, str) and cur:
+ try:
+ return base64.b64decode(cur)
+ except Exception:
+ return cur.encode("utf-8")
+ # Some LSP responses nest the blob under status.success payload.
+ if data.get("status", {}).get("success") is False:
+ raise RuntimeError("license LSP error: " + json.dumps(data)[:500])
+ return body
+
+
+def fetch_content_keys_wrap(
+ *,
+ wvd: Path,
+ pssh_b64: str,
+ license_url: str,
+ wrap_json: str,
+ user_agent: str,
+) -> list[str]:
+ """Re-POST a captured JSON license body with a fresh local CDM challenge.
+
+ Used by Channel 4 / RedBee (wvlicenceproxy-service) which reject raw
+ octet-stream (HTTP 415) and need the phone's token fields intact.
+ """
+ try:
+ template = json.loads(wrap_json)
+ except Exception as exc:
+ raise RuntimeError(f"wrap-json is not valid JSON: {exc}") from exc
+
+ device = Device.load(str(wvd))
+ cdm = Cdm.from_device(device)
+ session_id = cdm.open()
+ try:
+ challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
+ challenge_b64 = base64.b64encode(challenge).decode("utf-8")
+ if not _replace_challenge(template, challenge_b64, challenge):
+ raise RuntimeError(
+ "wrap-json has no recognisable challenge field "
+ f"(tried {', '.join(_CHALLENGE_KEYS)})"
+ )
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, */*",
+ }
+ if user_agent:
+ headers["User-Agent"] = user_agent
+ response = requests.post(
+ license_url, json=template, headers=headers, timeout=30
+ )
+ if response.status_code >= 400:
+ raise RuntimeError(
+ f"license HTTP {response.status_code}: {response.text[:500]!r}"
+ )
+ license_bytes = _license_bytes_from_response(response)
+ try:
+ cdm.parse_license(session_id, license_bytes)
+ except Exception:
+ try:
+ cdm.parse_license(session_id, base64.b64decode(license_bytes))
+ except Exception as exc:
+ raise RuntimeError(
+ f"parse_license failed ({len(license_bytes)} bytes): {exc}"
+ ) from exc
+ keys = [
+ f"{key.kid.hex}:{key.key.hex()}"
+ for key in cdm.get_keys(session_id)
+ if key.type == "CONTENT"
+ ]
+ finally:
+ cdm.close(session_id)
+ if not keys:
+ raise RuntimeError("no CONTENT keys")
+ return keys
+
+
+def main(argv: list[str] | None = None) -> int:
+ p = argparse.ArgumentParser(description="Widevine CDM helper → KID:KEY")
+ p.add_argument("--wvd", type=Path, required=True, help="Path to .wvd device file")
+ p.add_argument("--pssh", required=True, help="Base64 PSSH box")
+ p.add_argument(
+ "--mode",
+ choices=("modulardrm", "raw", "wrap"),
+ default="modulardrm",
+ help="modulardrm=RTE JSON; raw=octet-stream; wrap=captured JSON body",
+ )
+ p.add_argument("--auth", default="", help="Authorization header (modulardrm)")
+ p.add_argument("--pid", default="", help="releasePid (modulardrm)")
+ p.add_argument(
+ "--wrap-json",
+ default="",
+ help="Captured phone license POST JSON (wrap mode)",
+ )
+ p.add_argument(
+ "--license-url",
+ required=True,
+ help="Widevine license server URL",
+ )
+ p.add_argument(
+ "--user-agent",
+ default="",
+ help="Optional User-Agent for the license request",
+ )
+ p.add_argument(
+ "--quiet",
+ action="store_true",
+ help="Print only KID:KEY lines (for Go tooling)",
+ )
+ p.add_argument(
+ "--all",
+ action="store_true",
+ help="Print every CONTENT key (default: first only)",
+ )
+ args = p.parse_args(argv)
+
+ if not args.wvd.is_file():
+ print(f"[!] missing WVD: {args.wvd}", file=sys.stderr)
+ return 2
+
+ try:
+ if args.mode == "raw":
+ keys = fetch_content_keys_raw(
+ wvd=args.wvd,
+ pssh_b64=args.pssh,
+ license_url=args.license_url,
+ user_agent=args.user_agent,
+ )
+ elif args.mode == "wrap":
+ if not args.wrap_json.strip():
+ print(
+ "[!] --wrap-json required for wrap mode "
+ "(phone must complete a license POST during capture)",
+ file=sys.stderr,
+ )
+ return 2
+ keys = fetch_content_keys_wrap(
+ wvd=args.wvd,
+ pssh_b64=args.pssh,
+ license_url=args.license_url,
+ wrap_json=args.wrap_json,
+ user_agent=args.user_agent,
+ )
+ else:
+ if not args.auth or not args.pid:
+ print("[!] --auth and --pid required for modulardrm mode", file=sys.stderr)
+ return 2
+ keys = fetch_content_keys_modulardrm(
+ wvd=args.wvd,
+ pssh_b64=args.pssh,
+ auth=args.auth,
+ release_pid=args.pid,
+ license_url=args.license_url,
+ user_agent=args.user_agent,
+ )
+ except Exception as exc:
+ print(f"[!] {exc}", file=sys.stderr)
+ return 1
+
+ out = keys if args.all else keys[:1]
+ if not args.quiet:
+ print("[+] Keys:", file=sys.stderr)
+ for pair in out:
+ print(f"--key {pair}", file=sys.stderr)
+ for pair in out:
+ print(pair)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/apps/pkg/bootstrap/embedded/modules/README.md b/apps/pkg/bootstrap/embedded/modules/README.md
index edc20ac..8493f8b 100644
--- a/apps/pkg/bootstrap/embedded/modules/README.md
+++ b/apps/pkg/bootstrap/embedded/modules/README.md
@@ -1,6 +1,6 @@
# External modules
-Each subdirectory is a provider the `drm` host discovers, builds, and runs.
+Each subdirectory is a provider the `streamd` host discovers, builds, and runs.
```
modules/
diff --git a/apps/pkg/bootstrap/embedded/root-go-mod.txt b/apps/pkg/bootstrap/embedded/root-go-mod.txt
index c23f9f3..1b7a669 100644
--- a/apps/pkg/bootstrap/embedded/root-go-mod.txt
+++ b/apps/pkg/bootstrap/embedded/root-go-mod.txt
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
go 1.25.0
diff --git a/apps/pkg/capture/capture.go b/apps/pkg/capture/capture.go
index 35ee985..ef73a54 100644
--- a/apps/pkg/capture/capture.go
+++ b/apps/pkg/capture/capture.go
@@ -9,7 +9,7 @@ import (
"strings"
"time"
- "drmdecryption/adb"
+ "streamd/adb"
)
// Hints tell the waiter which fields / log tags mean a capture is complete.
@@ -24,6 +24,9 @@ type Hints struct {
// Score ranks candidate manifest URLs. Zero value falls back to
// DefaultScoreCfg, which has no provider hosts.
Score ScoreCfg
+ // PreferURLContains boosts MPDs whose URL contains any of these substrings
+ // (e.g. channel(e4) for Channel 4 Live). Used when an app prefetches neighbours.
+ PreferURLContains []string
}
// RemoteCapPaths are the on-device locations the MITM may persist its capture
@@ -59,10 +62,23 @@ func DefaultPassiveHints() Hints {
// score applies the hints' URL scoring, defaulting when unset.
func (h Hints) score(u string) int {
+ var sc int
if len(h.Score.Deny) == 0 && len(h.Score.Hosts) == 0 {
- return DefaultScoreCfg().Score(u)
+ sc = DefaultScoreCfg().Score(u)
+ } else {
+ sc = h.Score.Score(u)
}
- return h.Score.Score(u)
+ if sc <= 0 || len(h.PreferURLContains) == 0 {
+ return sc
+ }
+ low := strings.ToLower(u)
+ for _, p := range h.PreferURLContains {
+ p = strings.ToLower(strings.TrimSpace(p))
+ if p != "" && strings.Contains(low, p) {
+ return sc + 1000
+ }
+ }
+ return sc
}
// Data is the merged capture payload before key fetch.
@@ -70,6 +86,25 @@ type Data map[string]string
func (d Data) Get(k string) string { return d[k] }
+// preferSatisfied is true when no PreferURLContains is set, or the chosen MPD
+// matches one of the preferred substrings.
+func preferSatisfied(cap Data, hints Hints) bool {
+ if len(hints.PreferURLContains) == 0 {
+ return true
+ }
+ mpd := strings.ToLower(strings.TrimSpace(cap["mpd"]))
+ if mpd == "" {
+ return false
+ }
+ for _, p := range hints.PreferURLContains {
+ p = strings.ToLower(strings.TrimSpace(p))
+ if p != "" && strings.Contains(mpd, p) {
+ return true
+ }
+ }
+ return false
+}
+
// Wait pulls device JSON + local mirrored log until required fields exist.
func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout time.Duration) (Data, error) {
deadline := time.Now().Add(timeout)
@@ -104,7 +139,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
enrichFromProxyLog(cap, logText, hints)
if hints.BestEffort {
- if hasUseful(cap, hints) {
+ if hasUseful(cap, hints) && preferSatisfied(cap, hints) {
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
return cap, nil
}
@@ -116,7 +151,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
break
}
}
- if !missing {
+ if !missing && preferSatisfied(cap, hints) {
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
return cap, nil
}
@@ -125,7 +160,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
have := []string{}
keys := hints.Require
if hints.BestEffort {
- keys = []string{"mpd", "license_url", "pssh", "auth", "pid"}
+ keys = []string{"mpd", "license_url", "pssh", "auth", "pid", "license_body"}
}
for _, k := range keys {
if cap[k] != "" {
@@ -225,7 +260,8 @@ func enrichFromProxyLog(cap Data, logText string, hints Hints) {
if sc <= 0 {
return
}
- if sc > bestScore {
+ // Prefer higher score; on a tie keep the later URL (last stream played).
+ if sc > bestScore || (sc == bestScore && sc > 0) {
bestScore = sc
bestMPD = u
}
diff --git a/apps/pkg/go.mod b/apps/pkg/go.mod
index c23f9f3..1b7a669 100644
--- a/apps/pkg/go.mod
+++ b/apps/pkg/go.mod
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
go 1.25.0
diff --git a/apps/pkg/modcfg/modcfg.go b/apps/pkg/modcfg/modcfg.go
index 30b3fa5..5868a55 100644
--- a/apps/pkg/modcfg/modcfg.go
+++ b/apps/pkg/modcfg/modcfg.go
@@ -15,13 +15,14 @@ import (
"path/filepath"
"strings"
- "drmdecryption/modhost"
- "drmdecryption/repo"
+ "streamd/modhost"
+ "streamd/repo"
"gopkg.in/yaml.v3"
)
// Dir returns the directory holding a module's values.
-// Prefers the active modules dir (see modhost / --modules-dir); falls back to
+// Prefers the active modules dir (see modhost / --modules-dir); then the
+// directory beside a panel/release binary (/.bin/); then
// apps/modules// for older checkouts.
func Dir(name string) string {
preferred := filepath.Join(modhost.ModulesDir(""), name)
@@ -31,6 +32,9 @@ func Dir(name string) string {
if modhost.ModulesDirOverride() != "" {
return preferred
}
+ if beside := dirBesideExecutable(name); beside != "" {
+ return beside
+ }
root := repo.Root()
if _, err := os.Stat(filepath.Join(root, "modules")); err == nil {
return filepath.Join(root, "modules", name)
@@ -38,6 +42,43 @@ func Dir(name string) string {
return filepath.Join(root, "apps", "modules", name)
}
+// dirBesideExecutable finds module.yaml next to a panel/release binary layout:
+// /.bin/[.exe]
+// /.bin/-/[.exe]
+func dirBesideExecutable(name string) string {
+ exe, err := os.Executable()
+ if err != nil {
+ return ""
+ }
+ if resolved, err := filepath.EvalSymlinks(exe); err == nil {
+ exe = resolved
+ }
+ base := strings.TrimSuffix(filepath.Base(exe), ".exe")
+ if !strings.EqualFold(base, name) {
+ return ""
+ }
+ binDir := filepath.Dir(exe)
+ candidates := []string{}
+ if strings.EqualFold(filepath.Base(binDir), ".bin") {
+ candidates = append(candidates, filepath.Dir(binDir))
+ }
+ parent := filepath.Dir(binDir)
+ if strings.EqualFold(filepath.Base(parent), ".bin") {
+ candidates = append(candidates, filepath.Dir(parent))
+ }
+ for _, dir := range candidates {
+ if fileExists(filepath.Join(dir, "module.yaml")) || fileExists(filepath.Join(dir, "module-publish.yaml")) {
+ return dir
+ }
+ }
+ return ""
+}
+
+func fileExists(p string) bool {
+ st, err := os.Stat(p)
+ return err == nil && !st.IsDir()
+}
+
// Path returns the preferred values file path (module.yaml).
func Path(name string) string {
return filepath.Join(Dir(name), "module.yaml")
diff --git a/apps/pkg/modhost/discover.go b/apps/pkg/modhost/discover.go
index 93a90de..efecb85 100644
--- a/apps/pkg/modhost/discover.go
+++ b/apps/pkg/modhost/discover.go
@@ -13,7 +13,7 @@ type Module struct {
Dir string // absolute path to modules/
}
-// ModulesDir returns the modules directory (honours --modules-dir / DRM_MODULES_DIR).
+// ModulesDir returns the modules directory (honours --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR).
func ModulesDir(root string) string {
return EffectiveModulesDir(root)
}
diff --git a/apps/pkg/modhost/exec.go b/apps/pkg/modhost/exec.go
index 57d1beb..173e9c5 100644
--- a/apps/pkg/modhost/exec.go
+++ b/apps/pkg/modhost/exec.go
@@ -9,9 +9,39 @@ import (
"strings"
)
+// prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load
+// panel-store module.yaml. Module builds that call EffectiveModulesDir (or
+// ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the
+// panel module.yaml when describe returns no channels.
+func prepareModuleCmd(cmd *exec.Cmd) {
+ ov := ModulesDirOverride()
+ if ov == "" {
+ return
+ }
+ cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"),
+ "STREAMD_MODULES_DIR="+ov)
+}
+
+func withoutEnvKeys(env []string, keys ...string) []string {
+ drop := map[string]struct{}{}
+ for _, k := range keys {
+ drop[strings.ToUpper(k)] = struct{}{}
+ }
+ out := make([]string, 0, len(env))
+ for _, e := range env {
+ key, _, _ := strings.Cut(e, "=")
+ if _, skip := drop[strings.ToUpper(key)]; skip {
+ continue
+ }
+ out = append(out, e)
+ }
+ return out
+}
+
// Run executes the module binary with args, inheriting stdout/stderr.
func Run(bin string, args ...string) error {
cmd := exec.Command(bin, args...)
+ prepareModuleCmd(cmd)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
@@ -24,6 +54,7 @@ func Run(bin string, args ...string) error {
// RunOutput executes the module binary and returns combined stdout.
func RunOutput(bin string, args ...string) (string, error) {
cmd := exec.Command(bin, args...)
+ prepareModuleCmd(cmd)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
@@ -74,5 +105,9 @@ func Load(root, name string) (Module, string, Describe, error) {
if d.Name == "" {
d.Name = m.Name
}
+ // Older panel binaries may not load module.yaml from STREAMD_MODULES_DIR /
+ // exe-adjacent layout, leaving package empty (breaks transparent MITM —
+ // iptables then treats the listen port as the package name).
+ enrichDescribeFromYAML(&d, m.Dir)
return m, bin, d, nil
}
diff --git a/apps/pkg/modhost/exec_test.go b/apps/pkg/modhost/exec_test.go
new file mode 100644
index 0000000..ae7c842
--- /dev/null
+++ b/apps/pkg/modhost/exec_test.go
@@ -0,0 +1,31 @@
+package modhost
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+)
+
+func TestPrepareModuleCmdSetsEnv(t *testing.T) {
+ t.Cleanup(func() { _ = SetModulesDir("") })
+ ov := filepath.Join(t.TempDir(), "modules")
+ if err := os.MkdirAll(ov, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetModulesDir(ov); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command("true")
+ prepareModuleCmd(cmd)
+ found := false
+ for _, e := range cmd.Env {
+ if e == "STREAMD_MODULES_DIR="+ov {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("STREAMD_MODULES_DIR missing in env: %v", cmd.Env)
+ }
+}
diff --git a/apps/pkg/modhost/protocol.go b/apps/pkg/modhost/protocol.go
index 1a498d1..3ac5acc 100644
--- a/apps/pkg/modhost/protocol.go
+++ b/apps/pkg/modhost/protocol.go
@@ -1,8 +1,8 @@
// Package modhost discovers, builds, and runs external provider modules that
-// live under modules// (Go source + module.yaml), outside drm.exe.
+// live under modules// (Go source + module.yaml), outside streamd.
package modhost
-import "drmdecryption/capture"
+import "streamd/capture"
// ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
const ProtocolVersion = 1
@@ -22,12 +22,16 @@ type Describe struct {
KeyMode string `json:"key_mode"`
ProxyBin string `json:"proxy_bin,omitempty"`
CAHash string `json:"ca_hash,omitempty"`
- TransparentMITM bool `json:"transparent_mitm"`
- Rewriter string `json:"rewriter,omitempty"`
- Channels []Channel `json:"channels"`
- Require []string `json:"require,omitempty"`
- Score capture.ScoreCfg `json:"score,omitempty"`
- HasCatalog bool `json:"has_catalog"`
- ValuesPath string `json:"values_path,omitempty"`
- ValuesLoaded bool `json:"values_loaded"`
+ TransparentMITM bool `json:"transparent_mitm"`
+ MitmHosts []string `json:"mitm_hosts,omitempty"`
+ Rewriter string `json:"rewriter,omitempty"`
+ Channels []Channel `json:"channels"`
+ Require []string `json:"require,omitempty"`
+ Score capture.ScoreCfg `json:"score,omitempty"`
+ // ChannelMPDPrefer maps channel id → URL substrings that must win Wait scoring.
+ ChannelMPDPrefer map[string][]string `json:"channel_mpd_prefer,omitempty"`
+ HasCatalog bool `json:"has_catalog"`
+ RequireWVD bool `json:"require_wvd,omitempty"`
+ ValuesPath string `json:"values_path,omitempty"`
+ ValuesLoaded bool `json:"values_loaded"`
}
diff --git a/apps/pkg/modhost/remote_app.go b/apps/pkg/modhost/remote_app.go
index 9a61657..ac113d5 100644
--- a/apps/pkg/modhost/remote_app.go
+++ b/apps/pkg/modhost/remote_app.go
@@ -6,11 +6,11 @@ import (
"path/filepath"
"strings"
- "drmdecryption/adb"
- "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/mpd"
- "drmdecryption/session"
+ "streamd/adb"
+ "streamd/app"
+ "streamd/capture"
+ "streamd/mpd"
+ "streamd/session"
)
// RemoteApp implements app.App by calling an external module binary.
@@ -82,6 +82,41 @@ func (r *RemoteApp) MPDRewriter() mpd.Rewriter {
func (r *RemoteApp) UseTransparentMITM() bool { return r.Desc.TransparentMITM }
+func (r *RemoteApp) RequireWVD() bool { return r.Desc.RequireWVD }
+
+func (r *RemoteApp) MitmHosts() []string {
+ out := make([]string, 0, len(r.Desc.MitmHosts))
+ for _, h := range r.Desc.MitmHosts {
+ h = strings.TrimSpace(strings.ToLower(h))
+ if h != "" {
+ out = append(out, h)
+ }
+ }
+ return out
+}
+
+func (r *RemoteApp) CaptureHintsFor(channel string) capture.Hints {
+ h := r.CaptureHints()
+ if len(r.Desc.ChannelMPDPrefer) == 0 {
+ return h
+ }
+ id := strings.ToLower(strings.TrimSpace(channel))
+ if prefs, ok := r.Desc.ChannelMPDPrefer[id]; ok && len(prefs) > 0 {
+ h.PreferURLContains = append([]string{}, prefs...)
+ return h
+ }
+ // Alias / label fallback: match prefer keys against known channel ids only.
+ for _, ch := range r.Desc.Channels {
+ if strings.EqualFold(ch.ID, id) || strings.EqualFold(ch.Label, id) {
+ if prefs, ok := r.Desc.ChannelMPDPrefer[ch.ID]; ok && len(prefs) > 0 {
+ h.PreferURLContains = append([]string{}, prefs...)
+ }
+ break
+ }
+ }
+ return h
+}
+
func (r *RemoteApp) RewriterName() string {
if r.Desc.Rewriter == "" {
return "none"
@@ -115,10 +150,13 @@ func (r *RemoteApp) ValuesPath() string {
// Ensure RemoteApp satisfies the interfaces capture / catalog use.
var (
- _ app.App = (*RemoteApp)(nil)
- _ app.TransparentMITM = (*RemoteApp)(nil)
- _ app.StreamDefaults = (*RemoteApp)(nil)
- _ app.Catalog = (*RemoteApp)(nil)
+ _ app.App = (*RemoteApp)(nil)
+ _ app.TransparentMITM = (*RemoteApp)(nil)
+ _ app.RequireWVD = (*RemoteApp)(nil)
+ _ app.MitmHostList = (*RemoteApp)(nil)
+ _ app.ChannelCaptureHints = (*RemoteApp)(nil)
+ _ app.StreamDefaults = (*RemoteApp)(nil)
+ _ app.Catalog = (*RemoteApp)(nil)
)
func (r *RemoteApp) VideoSelect() string { return "" }
diff --git a/apps/pkg/modhost/root.go b/apps/pkg/modhost/root.go
index 9133e24..9da5fd3 100644
--- a/apps/pkg/modhost/root.go
+++ b/apps/pkg/modhost/root.go
@@ -3,9 +3,10 @@ package modhost
import (
"os"
"path/filepath"
+ "strings"
"sync"
- "drmdecryption/repo"
+ "streamd/repo"
)
var (
@@ -13,7 +14,7 @@ var (
modulesDirOV string // absolute path override for the modules directory
)
-// SetModulesDir overrides where providers are discovered (drm --modules-dir).
+// SetModulesDir overrides where providers are discovered (streamd --modules-dir).
// Empty clears the override. Relative paths are resolved against the process cwd.
func SetModulesDir(dir string) error {
rootMu.Lock()
@@ -37,24 +38,45 @@ func ModulesDirOverride() string {
return modulesDirOV
}
+// envModulesDir returns STREAMD_MODULES_DIR (preferred) or DRM_MODULES_DIR.
+func envModulesDir() string {
+ v := strings.TrimSpace(os.Getenv("STREAMD_MODULES_DIR"))
+ if v == "" {
+ v = strings.TrimSpace(os.Getenv("DRM_MODULES_DIR"))
+ }
+ if v == "" {
+ return ""
+ }
+ if abs, err := filepath.Abs(v); err == nil {
+ return abs
+ }
+ return v
+}
+
// EffectiveModulesDir is the directory that Discover/Open scan.
-// Prefer --modules-dir / DRM_MODULES_DIR; else /modules.
+// Prefer --modules-dir, then STREAMD_MODULES_DIR / DRM_MODULES_DIR, else /modules.
+// Module binaries read the env here directly so they honour the panel store even
+// when they never call ApplyEnvModulesDir.
func EffectiveModulesDir(root string) string {
if ov := ModulesDirOverride(); ov != "" {
return ov
}
+ if v := envModulesDir(); v != "" {
+ return v
+ }
if root == "" {
root = repo.Root()
}
return filepath.Join(root, "modules")
}
-// ApplyEnvModulesDir sets the override from DRM_MODULES_DIR when no flag was set.
+// ApplyEnvModulesDir sets the override from STREAMD_MODULES_DIR (preferred) or
+// DRM_MODULES_DIR when no flag was set.
func ApplyEnvModulesDir() error {
if ModulesDirOverride() != "" {
return nil
}
- v := os.Getenv("DRM_MODULES_DIR")
+ v := envModulesDir()
if v == "" {
return nil
}
diff --git a/apps/pkg/modhost/root_test.go b/apps/pkg/modhost/root_test.go
new file mode 100644
index 0000000..d653914
--- /dev/null
+++ b/apps/pkg/modhost/root_test.go
@@ -0,0 +1,39 @@
+package modhost
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestEffectiveModulesDirEnv(t *testing.T) {
+ t.Cleanup(func() {
+ _ = SetModulesDir("")
+ _ = os.Unsetenv("STREAMD_MODULES_DIR")
+ _ = os.Unsetenv("DRM_MODULES_DIR")
+ })
+ _ = SetModulesDir("")
+ _ = os.Unsetenv("STREAMD_MODULES_DIR")
+ _ = os.Unsetenv("DRM_MODULES_DIR")
+
+ dir := t.TempDir()
+ t.Setenv("STREAMD_MODULES_DIR", dir)
+ got := EffectiveModulesDir("")
+ want, _ := filepath.Abs(dir)
+ if got != want {
+ t.Fatalf("env modules dir: got %q want %q", got, want)
+ }
+
+ override := filepath.Join(t.TempDir(), "override")
+ if err := os.MkdirAll(override, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetModulesDir(override); err != nil {
+ t.Fatal(err)
+ }
+ got = EffectiveModulesDir("")
+ want, _ = filepath.Abs(override)
+ if got != want {
+ t.Fatalf("flag overrides env: got %q want %q", got, want)
+ }
+}
diff --git a/apps/pkg/modhost/yaml_enrich.go b/apps/pkg/modhost/yaml_enrich.go
new file mode 100644
index 0000000..abb108b
--- /dev/null
+++ b/apps/pkg/modhost/yaml_enrich.go
@@ -0,0 +1,77 @@
+package modhost
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+
+ "gopkg.in/yaml.v3"
+)
+
+// enrichDescribeFromYAML fills gaps left by older module binaries that do not
+// load panel/agent module.yaml (empty package breaks transparent MITM).
+func enrichDescribeFromYAML(d *Describe, modDir string) {
+ if d == nil || strings.TrimSpace(modDir) == "" {
+ return
+ }
+ raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
+ if err != nil {
+ raw, err = os.ReadFile(filepath.Join(modDir, "module-publish.yaml"))
+ if err != nil {
+ return
+ }
+ }
+ var doc struct {
+ Package string `yaml:"package"`
+ LicenseURL string `yaml:"license_url"`
+ KeyMode string `yaml:"key_mode"`
+ ProxyBin string `yaml:"proxy_bin"`
+ CAHash string `yaml:"ca_hash"`
+ TransparentMITM *bool `yaml:"transparent_mitm"`
+ RequireWVD *bool `yaml:"require_wvd"`
+ Rewriter string `yaml:"rewriter"`
+ Channels map[string]struct {
+ Label string `yaml:"label"`
+ } `yaml:"channels"`
+ }
+ if err := yaml.Unmarshal(raw, &doc); err != nil {
+ return
+ }
+ if strings.TrimSpace(d.Package) == "" && strings.TrimSpace(doc.Package) != "" {
+ d.Package = strings.TrimSpace(doc.Package)
+ }
+ if strings.TrimSpace(d.LicenseURL) == "" && strings.TrimSpace(doc.LicenseURL) != "" {
+ d.LicenseURL = strings.TrimSpace(doc.LicenseURL)
+ }
+ if strings.TrimSpace(d.KeyMode) == "" && strings.TrimSpace(doc.KeyMode) != "" {
+ d.KeyMode = strings.TrimSpace(doc.KeyMode)
+ }
+ if strings.TrimSpace(d.ProxyBin) == "" && strings.TrimSpace(doc.ProxyBin) != "" {
+ d.ProxyBin = strings.TrimSpace(doc.ProxyBin)
+ }
+ if strings.TrimSpace(d.CAHash) == "" && strings.TrimSpace(doc.CAHash) != "" {
+ d.CAHash = strings.TrimSpace(doc.CAHash)
+ }
+ if strings.TrimSpace(d.Rewriter) == "" && strings.TrimSpace(doc.Rewriter) != "" {
+ d.Rewriter = strings.TrimSpace(doc.Rewriter)
+ }
+ if !d.TransparentMITM && doc.TransparentMITM != nil {
+ d.TransparentMITM = *doc.TransparentMITM
+ }
+ if !d.RequireWVD && doc.RequireWVD != nil {
+ d.RequireWVD = *doc.RequireWVD
+ }
+ if len(d.Channels) == 0 && len(doc.Channels) > 0 {
+ for id, ch := range doc.Channels {
+ label := strings.TrimSpace(ch.Label)
+ if label == "" {
+ label = id
+ }
+ d.Channels = append(d.Channels, Channel{ID: id, Label: label})
+ }
+ }
+ if !d.ValuesLoaded {
+ d.ValuesLoaded = true
+ d.ValuesPath = filepath.Join(modDir, "module.yaml")
+ }
+}
diff --git a/apps/pkg/mpd/server.go b/apps/pkg/mpd/server.go
index 250b067..8054fdc 100644
--- a/apps/pkg/mpd/server.go
+++ b/apps/pkg/mpd/server.go
@@ -5,6 +5,7 @@ import (
"io"
"net"
"net/http"
+ "net/url"
"strings"
"time"
)
@@ -27,22 +28,28 @@ type Primer interface {
type LocalServer struct {
URL string
Upstream string
- Key string // KID:KEY
+ Key string // KID:KEY (optional for clear streams)
Headers map[string]string
+ Proxy string // optional socks5:// or http:// for upstream fetch
rw Rewriter
kidHint string
ln net.Listener
httpServer *http.Server
+ client *http.Client
}
// StartLocal starts the rewrite proxy. rw must not be nil; pass Passthrough{}
-// to serve upstream unchanged.
-func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (*LocalServer, error) {
+// to serve upstream unchanged. proxyURL may be empty, or socks5:// / http://.
+func StartLocal(upstream, key string, headers map[string]string, rw Rewriter, proxyURL ...string) (*LocalServer, error) {
if rw == nil {
rw = Passthrough{}
}
- s := &LocalServer{Upstream: upstream, Key: key, Headers: headers, rw: rw}
+ proxy := ""
+ if len(proxyURL) > 0 {
+ proxy = strings.TrimSpace(proxyURL[0])
+ }
+ s := &LocalServer{Upstream: upstream, Key: key, Headers: headers, Proxy: proxy, rw: rw}
if key != "" && strings.Contains(key, ":") {
s.kidHint = strings.SplitN(key, ":", 2)[0]
if r, ok := rw.(KIDResolver); ok {
@@ -53,6 +60,11 @@ func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (*
}
}
}
+ client, err := httpClientWithProxy(proxy)
+ if err != nil {
+ return nil, err
+ }
+ s.client = client
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
@@ -66,6 +78,18 @@ func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (*
return s, nil
}
+func httpClientWithProxy(proxyURL string) (*http.Client, error) {
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ if proxyURL != "" {
+ u, err := url.Parse(proxyURL)
+ if err != nil {
+ return nil, fmt.Errorf("proxy URL: %w", err)
+ }
+ transport.Proxy = http.ProxyURL(u)
+ }
+ return &http.Client{Timeout: 20 * time.Second, Transport: transport}, nil
+}
+
func (s *LocalServer) Close() {
if s.httpServer != nil {
_ = s.httpServer.Close()
@@ -82,7 +106,10 @@ func (s *LocalServer) handle(w http.ResponseWriter, r *http.Request) {
for k, v := range s.Headers {
req.Header.Set(k, v)
}
- client := &http.Client{Timeout: 20 * time.Second}
+ client := s.client
+ if client == nil {
+ client = &http.Client{Timeout: 20 * time.Second}
+ }
if resp, err := client.Do(req); err == nil {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
_ = resp.Body.Close()
diff --git a/apps/pkg/phonecap/phonecap.go b/apps/pkg/phonecap/phonecap.go
index bcd9af9..b90bc6d 100644
--- a/apps/pkg/phonecap/phonecap.go
+++ b/apps/pkg/phonecap/phonecap.go
@@ -12,13 +12,13 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/proxy"
- "drmdecryption/repo"
- "drmdecryption/session"
- "drmdecryption/wvkey"
+ "streamd/adb"
+ "streamd/app"
+ "streamd/capture"
+ "streamd/proxy"
+ "streamd/repo"
+ "streamd/session"
+ "streamd/wvkey"
)
// DefaultCAHash is the subject hash of the bundled MITM CA, used when an app
@@ -199,17 +199,28 @@ func Run(opt Options) (res Result, err error) {
proxyBin, caHash := resolveProxy(a, root)
hints := a.CaptureHints()
+ if chHints, ok := a.(app.ChannelCaptureHints); ok && strings.TrimSpace(opt.Channel) != "" {
+ hints = chHints.CaptureHintsFor(opt.Channel)
+ }
useTProxy := false
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
useTProxy = true
}
+ pkgName := strings.TrimSpace(a.Package())
+ if useTProxy && pkgName == "" {
+ return res, fmt.Errorf("module %q has empty package — fix module.yaml package: (or re-pull modules); transparent MITM cannot install iptables UID rules", a.Name())
+ }
if useTProxy {
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
proxy.ClearHTTPProxy(c)
- remoteDir := "/data/local/tmp/capture/" + a.Package()
- if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false); err != nil {
+ remoteDir := "/data/local/tmp/capture/" + pkgName
+ var mitmHosts []string
+ if mh, ok := a.(app.MitmHostList); ok {
+ mitmHosts = mh.MitmHosts()
+ }
+ if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
return res, fmt.Errorf("transparent MITM start: %w", err)
}
defer proxy.StopTransparent(c)
@@ -231,17 +242,6 @@ func Run(opt Options) (res Result, err error) {
proxy.ReinjectCA(c, caHash)
}
- if err := a.Launch(c); err != nil {
- return res, fmt.Errorf("launch: %w", err)
- }
- if !opt.NoAutoPlay {
- if err := a.AutoPlay(c, opt.Channel); err != nil {
- return res, fmt.Errorf("auto-play: %w", err)
- }
- } else {
- fmt.Println("[*] Open the channel on the phone and wait for playback…")
- }
-
_ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755)
serialTag := c.Serial
if serialTag == "" {
@@ -253,80 +253,168 @@ func Run(opt Options) (res Result, err error) {
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
defer close(stop)
- need := hints.Require
- if len(need) == 0 {
- need = []string{"manifest"}
- }
- fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
- fmt.Println(" watch:", localLog)
- capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait)
- if err != nil {
- return res, err
- }
- licenseURL := first(capData.Get("license_url"), a.LicenseURL())
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if keyMode == "" || keyMode == "auto" {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
}
- // Brightcove/HLS: proxy often captures license + master URL but not PSSH.
- // Skip for clear/MPD-only apps (KeyMode none).
- if keyMode != "none" && keyMode != "clear" {
- if strings.TrimSpace(capData.Get("pssh")) == "" && strings.TrimSpace(capData.Get("mpd")) != "" {
- if pssh, err := extractHLSPSSH(capData.Get("mpd")); err == nil && pssh != "" {
- capData["pssh"] = pssh
- } else if err != nil {
- fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
- }
+ needsKeys := keyMode != "none" && keyMode != "clear"
+
+ // DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry
+ // (max 3). Clear / MPD-only apps keep a single wait of opt.Wait.
+ attempts := 1
+ waitPer := opt.Wait
+ if needsKeys {
+ attempts = 3
+ waitPer = 90 * time.Second
+ if opt.Wait > 0 && opt.Wait < waitPer {
+ waitPer = opt.Wait
}
}
- mpdURL := strings.TrimSpace(capData.Get("mpd"))
- // Console: always surface the MPD we will use (BBC clear streams only need this).
- fmt.Println()
- fmt.Println("========== MPD ==========")
- if mpdURL != "" {
- fmt.Println(mpdURL)
- } else {
- fmt.Println("(none)")
+ need := hints.Require
+ if len(need) == 0 {
+ need = []string{"manifest"}
}
- fmt.Println("=========================")
- fmt.Println()
- fmt.Println("[+] Capture:")
- for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh"} {
- v := capData.Get(k)
- if k == "license_url" {
- v = first(v, licenseURL)
+
+ var (
+ capData capture.Data
+ licenseURL string
+ mpdURL string
+ key string
+ lastErr error
+ )
+
+ for attempt := 1; attempt <= attempts; attempt++ {
+ if attempt > 1 {
+ fmt.Printf("[*] Widevine attempt %d/%d — closing app and retrying…\n", attempt, attempts)
+ c.ForceStop(a.Package())
+ time.Sleep(800 * time.Millisecond)
}
- if v == "" {
+
+ // Fresh local mirrors each attempt so we do not reuse a prior MPD/PSSH.
+ _ = os.WriteFile(localLog, nil, 0o644)
+ _ = os.Remove(localCap)
+
+ if err := a.Launch(c); err != nil {
+ lastErr = fmt.Errorf("launch: %w", err)
continue
}
- label := k
- if k == "license_url" {
- label = "license"
+ if !opt.NoAutoPlay {
+ if err := a.AutoPlay(c, opt.Channel); err != nil {
+ lastErr = fmt.Errorf("auto-play: %w", err)
+ c.ForceStop(a.Package())
+ continue
+ }
+ } else {
+ fmt.Println("[*] Open the channel on the phone and wait for playback…")
}
- fmt.Println(" ", label+":", trim(v, 120))
+
+ fmt.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
+ strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
+ fmt.Println(" watch:", localLog)
+ cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
+ if err != nil {
+ lastErr = err
+ fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
+ c.ForceStop(a.Package())
+ continue
+ }
+ capData = cap
+ licenseURL = first(capData.Get("license_url"), a.LicenseURL())
+
+ // Brightcove/HLS: proxy often captures license + master URL but not PSSH.
+ // C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
+ if needsKeys {
+ enrichWidevinePSSH(capData)
+ }
+
+ mpdURL = strings.TrimSpace(capData.Get("mpd"))
+ fmt.Println()
+ fmt.Println("========== MPD ==========")
+ if mpdURL != "" {
+ fmt.Println(mpdURL)
+ } else {
+ fmt.Println("(none)")
+ }
+ fmt.Println("=========================")
+ fmt.Println()
+ fmt.Println("[+] Capture:")
+ for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
+ v := capData.Get(k)
+ if k == "license_url" {
+ v = first(v, licenseURL)
+ }
+ if v == "" {
+ continue
+ }
+ label := k
+ switch k {
+ case "license_url":
+ label = "license"
+ case "license_body":
+ label = "license_body"
+ v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
+ }
+ fmt.Println(" ", label+":", trim(v, 120))
+ }
+
+ if !needsKeys {
+ fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
+ lastErr = nil
+ break
+ }
+
+ k, kerr := fetchKey(opt, root, capData, licenseURL)
+ if kerr != nil {
+ lastErr = kerr
+ // Missing --wvd on a manual grab-all can soft-save MPD-only; agents
+ // always pass WVD so this path is for interactive capture only.
+ softOK := strings.Contains(kerr.Error(), "requires --wvd")
+ if softOK {
+ if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
+ c.ForceStop(a.Package())
+ continue
+ }
+ fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
+ key = ""
+ lastErr = nil
+ break
+ }
+ fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr)
+ c.ForceStop(a.Package())
+ continue
+ }
+ if strings.TrimSpace(k) == "" || !looksLikeKey(k) {
+ lastErr = fmt.Errorf("wvkey returned no usable KID:KEY")
+ fmt.Fprintf(os.Stderr, "[!] %v (attempt %d/%d)\n", lastErr, attempt, attempts)
+ c.ForceStop(a.Package())
+ continue
+ }
+ key = k
+ fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
+ lastErr = nil
+ break
}
- key := ""
- if keyMode == "none" || keyMode == "clear" {
- fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
- } else {
- var kerr error
- key, kerr = fetchKey(opt, root, capData, licenseURL)
- if kerr != nil {
- return res, kerr
+ if lastErr != nil {
+ if needsKeys {
+ return res, fmt.Errorf("widevine capture failed after %d attempt(s): %w", attempts, lastErr)
}
- fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
+ return res, lastErr
+ }
+ if needsKeys && (strings.TrimSpace(key) == "" || !looksLikeKey(key)) {
+ return res, fmt.Errorf("refusing to save capture without Widevine keys (mpd alone is not enough)")
}
sess := session.Session{
- Channel: opt.Channel,
- PSSH: capData.Get("pssh"),
- Auth: capData.Get("auth"),
- PID: capData.Get("pid"),
- Key: key,
- MPD: mpdURL,
- LicenseURL: licenseURL,
+ Channel: opt.Channel,
+ PSSH: capData.Get("pssh"),
+ Auth: capData.Get("auth"),
+ PID: capData.Get("pid"),
+ Key: key,
+ MPD: mpdURL,
+ LicenseURL: licenseURL,
+ LicenseBody: capData.Get("license_body"),
}
path, err := session.Write(root, a.Name(), sess)
if err != nil {
@@ -343,6 +431,62 @@ func Run(opt Options) (res Result, err error) {
return res, nil
}
+func enrichWidevinePSSH(capData capture.Data) {
+ mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
+ curPSSH := strings.TrimSpace(capData.Get("pssh"))
+ needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
+ if !needPSSH || mpdForPSSH == "" {
+ return
+ }
+ if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
+ if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
+ if curPSSH != "" && curPSSH != pssh {
+ fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
+ }
+ capData["pssh"] = pssh
+ } else if err != nil && curPSSH == "" {
+ fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
+ }
+ return
+ }
+ if curPSSH == "" {
+ if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
+ capData["pssh"] = pssh
+ } else if err != nil {
+ fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
+ }
+ }
+}
+
+func looksLikeKey(raw string) bool {
+ raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
+ for _, line := range strings.Split(raw, "\n") {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+ kid, k, ok := strings.Cut(line, ":")
+ if !ok {
+ continue
+ }
+ if len(hexDigits(kid)) == 32 && len(hexDigits(k)) == 32 {
+ return true
+ }
+ }
+ return false
+}
+
+func hexDigits(s string) string {
+ var b strings.Builder
+ for _, r := range s {
+ switch {
+ case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
// ClearProxyLater clears http_proxy (exported for agent defer helpers).
func ClearProxyLater(c *adb.Client) {
proxy.ClearHTTPProxy(c)
@@ -373,22 +517,25 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
if strings.TrimSpace(opt.WVD) == "" {
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
}
- py := opt.Python
- if py == "" {
- py = filepath.Join(root, ".venv", "Scripts", "python.exe")
- if _, err := os.Stat(py); err != nil {
- py = filepath.Join(root, ".venv", "bin", "python")
- }
+ // Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
+ rt, err := wvkey.EnsureRuntime(root)
+ if err != nil {
+ return "", err
+ }
+ py := rt.Python
+ if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
+ py = p
}
wopt := wvkey.Options{
Python: py,
- Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
+ Script: rt.Script,
WVD: opt.WVD,
PSSH: cap.Get("pssh"),
Auth: cap.Get("auth"),
PID: cap.Get("pid"),
LicenseURL: licenseURL,
UserAgent: opt.UserAgent,
+ WrapJSON: cap.Get("license_body"),
}
mode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if mode == "" || mode == "auto" {
@@ -399,6 +546,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
}
}
}
+ // RedBee / wrapped JSON: if the phone posted a license body, prefer wrap
+ // even when the module still says raw (migration safety).
+ if mode == "raw" && strings.TrimSpace(wopt.WrapJSON) != "" {
+ mode = "wrap"
+ }
switch mode {
case "raw":
// Brightcove returns multiple CONTENT keys; NRE needs all of them.
@@ -407,11 +559,22 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
return "", err
}
return strings.Join(keys, "\n"), nil
+ case "wrap":
+ keys, err := wvkey.FetchWrapAll(wopt)
+ if err != nil {
+ return "", err
+ }
+ return strings.Join(keys, "\n"), nil
default:
return wvkey.Fetch(wopt)
}
}
+func fileExistsPath(path string) bool {
+ st, err := os.Stat(path)
+ return err == nil && !st.IsDir()
+}
+
func first(vals ...string) string {
for _, v := range vals {
if strings.TrimSpace(v) != "" {
@@ -449,6 +612,62 @@ func extractHLSPSSH(masterURL string) (string, error) {
return "", fmt.Errorf("no Widevine PSSH in HLS master")
}
+// PlayReady system id fragment inside a base64 PSSH box.
+const playReadyPSSHFrag = "AAAAAmgTweZhAQoarkuZb4IhflQ"
+
+// Widevine system id fragment inside a base64 PSSH box.
+const widevinePSSHFrag = "AAAAA7e+LqXnWSs6jyCfc1R0h7Q"
+
+func isPlayReadyPSSH(b64 string) bool {
+ return strings.Contains(b64, playReadyPSSHFrag) && !strings.Contains(b64, widevinePSSHFrag)
+}
+
+func extractWidevinePSSHFromMPD(mpdURL string) (string, error) {
+ resp, err := http.Get(mpdURL)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != 200 {
+ return "", fmt.Errorf("HTTP %d", resp.StatusCode)
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
+ if err != nil {
+ return "", err
+ }
+ mpd := string(body)
+ lower := strings.ToLower(mpd)
+ const (
+ wvUUID = "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
+ openTag = "")
+ k := strings.Index(lower[i:], closeTag)
+ if j < 0 || k < 0 || k <= j {
+ break
+ }
+ val := strings.TrimSpace(mpd[i+j+1 : i+k])
+ windowStart := i - 400
+ if windowStart < 0 {
+ windowStart = 0
+ }
+ window := lower[windowStart : i+j]
+ if strings.Contains(window, wvUUID) || strings.Contains(val, widevinePSSHFrag) {
+ return val, nil
+ }
+ searchFrom = i + k + len(closeTag)
+ }
+ return "", fmt.Errorf("no Widevine cenc:pssh in MPD")
+}
+
func trim(s string, n int) string {
if len(s) <= n {
return s
diff --git a/apps/pkg/proxy/embed.go b/apps/pkg/proxy/embed.go
index 1c985c4..79d0e20 100644
--- a/apps/pkg/proxy/embed.go
+++ b/apps/pkg/proxy/embed.go
@@ -6,15 +6,15 @@ import (
"os"
"path/filepath"
- "drmdecryption/adb"
- "drmdecryption/repo"
+ "streamd/adb"
+ "streamd/repo"
)
//go:embed embedded/tproxy_iptables.sh
var embeddedTProxyScript []byte
// ensureTProxyScript pushes the iptables helper to the phone.
-// Prefers the source-tree copy; falls back to the copy embedded in drm.exe
+// Prefers the source-tree copy; falls back to the copy embedded in streamd
// so a portable release zip does not need apps/proxy/device/.
func ensureTProxyScript(c *adb.Client) error {
candidates := []string{
diff --git a/apps/pkg/proxy/proxy.go b/apps/pkg/proxy/proxy.go
index df29922..02286d6 100644
--- a/apps/pkg/proxy/proxy.go
+++ b/apps/pkg/proxy/proxy.go
@@ -17,8 +17,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/repo"
+ "streamd/adb"
+ "streamd/repo"
)
const (
@@ -225,7 +225,7 @@ func PushAndStart(c *adb.Client, localBin string, extraArgs ...string) error {
}
// FindLocalBin returns the on-device MITM binary.
-// Search order: next to this drm.exe (release zip layout), then under the repo.
+// Search order: next to this streamd binary (release zip layout), then under the repo.
func FindLocalBin(root string) string {
if root == "" {
root = repo.Root()
@@ -322,11 +322,11 @@ func generateMITMCA(certPath, keyPath string) error {
return err
}
// Unique CN so Android subject_hash_old differs per install (filename HASH.0).
- cn := fmt.Sprintf("Null DRM Capture CA %x", serial.Bytes()[:8])
+ cn := fmt.Sprintf("Streamd Capture CA %x", serial.Bytes()[:8])
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
- Organization: []string{"Null DRM MITM CA"},
+ Organization: []string{"Streamd MITM CA"},
CommonName: cn,
},
NotBefore: time.Now().Add(-time.Hour),
@@ -478,11 +478,17 @@ const (
// StartTransparent pushes appproxy in -transparent mode (no Wi‑Fi http_proxy),
// installs iptables UID REDIRECT for pkg, and writes captures under remoteDir.
-func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool) error {
+// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
+// mode otherwise only MITMs open.live.bbc.co.uk.
+func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error {
+ pkg = strings.TrimSpace(pkg)
+ if pkg == "" {
+ return fmt.Errorf("transparent MITM requires Android package name (module.yaml package: is empty — re-pull/rebuild the module)")
+ }
if port == "" {
port = "8080"
}
- if remoteDir == "" {
+ if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
remoteDir = RemoteCaptureRoot + "/" + pkg
}
stopProxy(c)
@@ -518,6 +524,20 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
_, _ = c.Shell("mkdir", "-p", remoteDir)
_, _ = c.Shell("rm", "-f", remoteDir+"/cap.json", remoteDir+"/traffic.jsonl", remoteDir+"/appproxy.log")
+ mitmFlags := ""
+ seen := map[string]bool{}
+ for _, h := range mitmHosts {
+ h = strings.TrimSpace(strings.ToLower(h))
+ if h == "" || seen[h] || !safeMitmHost(h) {
+ continue
+ }
+ seen[h] = true
+ mitmFlags += " -mitm-host " + h
+ }
+ if mitmFlags != "" {
+ fmt.Printf("[*] Force MITM hosts:%s\n", mitmFlags)
+ }
+
starter := "#!/system/bin/sh\n" +
"mkdir -p '" + remoteDir + "'\n" +
"exec " + RemoteBin +
@@ -529,6 +549,7 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
" -dns 1.1.1.1,1.0.0.1,8.8.8.8" +
" -log-all" +
" -v" +
+ mitmFlags +
"\n"
tmp := filepath.Join(os.TempDir(), "start_appproxy_tproxy.sh")
if err := os.WriteFile(tmp, []byte(starter), 0o755); err != nil {
@@ -597,6 +618,20 @@ func StopTransparent(c *adb.Client) {
fmt.Println("[*] transparent capture stopped")
}
+// safeMitmHost allows only hostname characters so flags stay shell-safe.
+func safeMitmHost(h string) bool {
+ if h == "" || len(h) > 253 {
+ return false
+ }
+ for _, r := range h {
+ if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '.' || r == '-' {
+ continue
+ }
+ return false
+ }
+ return true
+}
+
// ResetOptions controls drm proxy reset.
type ResetOptions struct {
KeepCaptures bool // leave /data/local/tmp/capture/
diff --git a/apps/pkg/repo/root.go b/apps/pkg/repo/root.go
index a03ac8a..c218f43 100644
--- a/apps/pkg/repo/root.go
+++ b/apps/pkg/repo/root.go
@@ -11,7 +11,7 @@ import (
//
// Search order:
// 1. Walk up from the current working directory
-// 2. Walk up from drm.exe (if the exe lives in bin/, start at the parent)
+// 2. Walk up from streamd (if the exe lives in bin/, start at the parent)
func Root() string {
if root := findRoot(wd()); root != "" {
return root
diff --git a/apps/pkg/session/session.go b/apps/pkg/session/session.go
index e5a321c..4000254 100644
--- a/apps/pkg/session/session.go
+++ b/apps/pkg/session/session.go
@@ -22,6 +22,9 @@ type Session struct {
KeyHex string `json:"key_hex,omitempty"`
MPD string `json:"mpd,omitempty"`
LicenseURL string `json:"license_url,omitempty"`
+ // LicenseBody is the phone's JSON license POST (RedBee wrap). Used to
+ // re-issue with a local CDM challenge.
+ LicenseBody string `json:"license_body,omitempty"`
}
// Write creates outputs///session.json (+ field txt files + latest).
@@ -51,11 +54,12 @@ func Write(root, app string, s Session) (string, error) {
return "", err
}
fields := map[string]string{
- "pssh": s.PSSH,
- "auth": s.Auth,
- "pid": s.PID,
- "key": s.Key,
- "mpd": s.MPD,
+ "pssh": s.PSSH,
+ "auth": s.Auth,
+ "pid": s.PID,
+ "key": s.Key,
+ "mpd": s.MPD,
+ "license_body": s.LicenseBody,
}
for name, val := range fields {
if val == "" {
diff --git a/apps/pkg/uiflow/uiflow.go b/apps/pkg/uiflow/uiflow.go
index de8da07..afde843 100644
--- a/apps/pkg/uiflow/uiflow.go
+++ b/apps/pkg/uiflow/uiflow.go
@@ -10,7 +10,7 @@ import (
"strings"
"time"
- "drmdecryption/adb"
+ "streamd/adb"
)
// Pick selects among several matching nodes.
diff --git a/apps/pkg/wvkey/ensure.go b/apps/pkg/wvkey/ensure.go
new file mode 100644
index 0000000..6c7eac6
--- /dev/null
+++ b/apps/pkg/wvkey/ensure.go
@@ -0,0 +1,172 @@
+package wvkey
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+// Runtime is a resolved Python + wvkey.py pair ready for Fetch*.
+type Runtime struct {
+ Python string
+ Script string
+}
+
+// ScriptPath returns /apps/wvkey/wvkey.py.
+func ScriptPath(root string) string {
+ return filepath.Join(root, "apps", "wvkey", "wvkey.py")
+}
+
+// VenvPython returns the platform venv interpreter under root, if present.
+func VenvPython(root string) string {
+ candidates := []string{
+ filepath.Join(root, ".venv", "Scripts", "python.exe"),
+ filepath.Join(root, ".venv", "bin", "python"),
+ filepath.Join(root, ".venv", "bin", "python3"),
+ }
+ for _, c := range candidates {
+ if fileExists(c) {
+ return c
+ }
+ }
+ return ""
+}
+
+// EnsureRuntime makes sure wvkey.py exists and a usable Python with
+// pywidevine is available under root (creating .venv when needed).
+// Works on Windows, Linux, and macOS.
+func EnsureRuntime(root string) (Runtime, error) {
+ var zero Runtime
+ if root == "" {
+ return zero, fmt.Errorf("wvkey: install root required")
+ }
+ script := ScriptPath(root)
+ if !fileExists(script) {
+ return zero, fmt.Errorf("wvkey script missing at %s — re-run streamd so bootstrap can materialise apps/wvkey/", script)
+ }
+ req := filepath.Join(root, "apps", "wvkey", "requirements.txt")
+
+ if py := VenvPython(root); py != "" {
+ if hasPywidevine(py) {
+ return Runtime{Python: py, Script: script}, nil
+ }
+ if err := pipInstall(py, req); err != nil {
+ return zero, err
+ }
+ if !hasPywidevine(py) {
+ return zero, fmt.Errorf("wvkey: installed requirements but pywidevine still missing in %s", py)
+ }
+ return Runtime{Python: py, Script: script}, nil
+ }
+
+ base, err := findSystemPython()
+ if err != nil {
+ return zero, err
+ }
+ venvDir := filepath.Join(root, ".venv")
+ fmt.Fprintf(os.Stderr, "agent: creating Widevine venv at %s …\n", venvDir)
+ if err := createVenv(base, venvDir); err != nil {
+ return zero, err
+ }
+ py := VenvPython(root)
+ if py == "" {
+ return zero, fmt.Errorf("wvkey: venv created at %s but no python binary found", venvDir)
+ }
+ if err := pipInstall(py, req); err != nil {
+ return zero, err
+ }
+ if !hasPywidevine(py) {
+ return zero, fmt.Errorf("wvkey: pywidevine missing after pip install (%s)", py)
+ }
+ fmt.Fprintf(os.Stderr, "agent: Widevine helper ready (%s)\n", py)
+ return Runtime{Python: py, Script: script}, nil
+}
+
+// FindPython prefers an existing install-root venv, then PATH helpers.
+func FindPython(root string) string {
+ if root != "" {
+ if py := VenvPython(root); py != "" {
+ return py
+ }
+ }
+ return findPython()
+}
+
+func fileExists(path string) bool {
+ st, err := os.Stat(path)
+ return err == nil && !st.IsDir()
+}
+
+func hasPywidevine(py string) bool {
+ cmd := exec.Command(py, "-c", "import pywidevine")
+ return cmd.Run() == nil
+}
+
+func pipInstall(py, requirements string) error {
+ if !fileExists(requirements) {
+ return fmt.Errorf("wvkey: requirements missing at %s", requirements)
+ }
+ fmt.Fprintf(os.Stderr, "agent: pip install -r %s …\n", requirements)
+ cmd := exec.Command(py, "-m", "pip", "install", "-r", requirements)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("wvkey: pip install failed: %w\n%s", err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+func createVenv(basePython, venvDir string) error {
+ cmd := exec.Command(basePython, "-m", "venv", venvDir)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("wvkey: python -m venv %s failed: %w\n%s", venvDir, err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+func findSystemPython() (string, error) {
+ var names []string
+ switch runtime.GOOS {
+ case "windows":
+ // Prefer the py launcher (real install) over the Store stub named "python".
+ names = []string{"py", "python3", "python"}
+ default:
+ names = []string{"python3", "python"}
+ }
+ for _, name := range names {
+ if name == "py" {
+ // `py -3` on Windows
+ if p, err := exec.LookPath("py"); err == nil {
+ cmd := exec.Command(p, "-3", "-c", "import sys; print(sys.executable)")
+ out, err := cmd.Output()
+ if err == nil {
+ exe := strings.TrimSpace(string(out))
+ if fileExists(exe) {
+ return exe, nil
+ }
+ }
+ }
+ continue
+ }
+ if p, err := exec.LookPath(name); err == nil {
+ // Skip the WindowsApps Store alias stub when it cannot run -m venv.
+ if runtime.GOOS == "windows" && strings.Contains(strings.ToLower(p), `windowsapps`) {
+ cmd := exec.Command(p, "-c", "import sys; print(sys.executable)")
+ out, err := cmd.Output()
+ if err != nil {
+ continue
+ }
+ exe := strings.TrimSpace(string(out))
+ if !fileExists(exe) || strings.Contains(strings.ToLower(exe), `windowsapps`) {
+ continue
+ }
+ return exe, nil
+ }
+ return p, nil
+ }
+ }
+ return "", fmt.Errorf("wvkey: no system Python found — install Python 3.10+ (Windows/macOS/Linux) so the agent can create .venv for Widevine keys")
+}
diff --git a/apps/pkg/wvkey/wvkey.go b/apps/pkg/wvkey/wvkey.go
index 7516fa2..b5d9a30 100644
--- a/apps/pkg/wvkey/wvkey.go
+++ b/apps/pkg/wvkey/wvkey.go
@@ -19,11 +19,13 @@ type Options struct {
PID string
LicenseURL string
UserAgent string
+ // WrapJSON is a captured phone license POST body (RedBee / wrapped Widevine).
+ WrapJSON string
}
// Fetch runs wvkey.py --quiet (ModularDrm) and returns the first KID:KEY line.
func Fetch(opt Options) (string, error) {
- lines, err := run(opt, false, false)
+ lines, err := run(opt, "modulardrm", false)
if err != nil {
return "", err
}
@@ -35,7 +37,7 @@ func Fetch(opt Options) (string, error) {
// FetchRaw runs wvkey.py --mode raw (Brightcove / octet-stream license).
func FetchRaw(opt Options) (string, error) {
- lines, err := run(opt, true, false)
+ lines, err := run(opt, "raw", false)
if err != nil {
return "", err
}
@@ -47,18 +49,30 @@ func FetchRaw(opt Options) (string, error) {
// FetchRawAll returns every CONTENT key from a raw license response.
func FetchRawAll(opt Options) ([]string, error) {
- return run(opt, true, true)
+ return run(opt, "raw", true)
}
-func run(opt Options, raw, all bool) ([]string, error) {
- py := opt.Python
- if py == "" {
- py = findPython()
- }
+// FetchWrapAll re-POSTs a captured JSON license body with a local CDM challenge.
+func FetchWrapAll(opt Options) ([]string, error) {
+ return run(opt, "wrap", true)
+}
+
+func run(opt Options, mode string, all bool) ([]string, error) {
+ py := resolvePython(opt.Python)
script := opt.Script
if script == "" {
return nil, fmt.Errorf("wvkey script path required")
}
+ if !fileExists(script) {
+ return nil, fmt.Errorf("wvkey script not found: %s", script)
+ }
+ if !fileExists(py) {
+ // Bare names like "python3" are OK via LookPath inside resolvePython;
+ // absolute/relative paths must exist.
+ if filepath.IsAbs(py) || strings.Contains(py, string(os.PathSeparator)) || strings.Contains(py, "/") {
+ return nil, fmt.Errorf("wvkey python not found: %s (run agent once to auto-create .venv, or set python: in agent.yaml)", py)
+ }
+ }
if strings.TrimSpace(opt.WVD) == "" {
return nil, fmt.Errorf("wvkey --wvd path required")
}
@@ -73,12 +87,19 @@ func run(opt Options, raw, all bool) ([]string, error) {
"--wvd", opt.WVD,
"--pssh", opt.PSSH,
"--license-url", opt.LicenseURL,
+ "--mode", mode,
"--quiet",
}
- if raw {
- args = append(args, "--mode", "raw")
- } else {
- args = append(args, "--mode", "modulardrm", "--auth", opt.Auth, "--pid", opt.PID)
+ switch mode {
+ case "raw":
+ // no extra fields
+ case "wrap":
+ if strings.TrimSpace(opt.WrapJSON) == "" {
+ return nil, fmt.Errorf("wvkey wrap mode requires a captured license_body from the phone (playback must start so RedBee gets a token)")
+ }
+ args = append(args, "--wrap-json", opt.WrapJSON)
+ default:
+ args = append(args, "--auth", opt.Auth, "--pid", opt.PID)
}
if all {
args = append(args, "--all")
@@ -106,12 +127,30 @@ func run(opt Options, raw, all bool) ([]string, error) {
return out, nil
}
+// resolvePython uses an explicit path only when the file exists; otherwise
+// discovers a usable interpreter. Passing a missing absolute path used to make
+// exec fail with a confusing "not found in %PATH%" on Windows.
+func resolvePython(explicit string) string {
+ if strings.TrimSpace(explicit) != "" {
+ if st, err := os.Stat(explicit); err == nil && !st.IsDir() {
+ return explicit
+ }
+ if !strings.Contains(explicit, string(os.PathSeparator)) && !strings.Contains(explicit, "/") {
+ if p, err := exec.LookPath(explicit); err == nil {
+ return p
+ }
+ }
+ }
+ return findPython()
+}
+
func findPython() string {
candidates := []string{
filepath.Join(".venv", "Scripts", "python.exe"),
filepath.Join(".venv", "bin", "python"),
"python3",
"python",
+ "py",
}
for _, c := range candidates {
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {
diff --git a/apps/proxy/README.md b/apps/proxy/README.md
index 38f5e83..1641534 100644
--- a/apps/proxy/README.md
+++ b/apps/proxy/README.md
@@ -5,7 +5,7 @@ license URLs, manifests and auth headers.
```text
apps/proxy/
- proxyctlcmd/ host CLI, hosted by bin/drm as `drm proxy`
+ proxyctlcmd/ host CLI, hosted by bin/streamd as `streamd proxy`
device/ linux/arm64 MITM source (module: appproxy)
rteproxy-ca.crt MITM CA (subject hash 6c3578b4)
```
@@ -17,8 +17,8 @@ working.
## Build
```bash
-go -C apps/cli build -o ../../bin/drm . # host CLI
-./bin/drm proxy build # cross-compile the device binary
+go -C apps/cli build -o ../../bin/streamd . # host CLI
+./bin/streamd proxy build # cross-compile the device binary
```
`proxy build` compiles `device/` for linux/arm64 into
@@ -28,20 +28,20 @@ go -C apps/cli build -o ../../bin/drm . # host CLI
```bash
# trust the MITM CA (needs Magisk; mounts into the system store)
-./bin/drm proxy install-ca --reinject
-./bin/drm proxy reinject-ca # mount only, CA already pushed
+./bin/streamd proxy install-ca --reinject
+./bin/streamd proxy reinject-ca # mount only, CA already pushed
# structured capture proxy
-./bin/drm proxy start --install-ca --reinject
-./bin/drm proxy stop
+./bin/streamd proxy start --install-ca --reinject
+./bin/streamd proxy stop
# record everything while you explore an unknown app
-./bin/drm proxy discover --install-ca --reinject
-./bin/drm proxy discover --force-stop # so it inherits the CA mount
+./bin/streamd proxy discover --install-ca --reinject
+./bin/streamd proxy discover --force-stop # so it inherits the CA mount
# pull artifacts without re-running, and release the phone
-./bin/drm proxy pull
-./bin/drm proxy clear-proxy
+./bin/streamd proxy pull
+./bin/streamd proxy clear-proxy
```
Always clear the proxy when done, or the phone keeps pointing at a dead listener.
@@ -53,7 +53,7 @@ phone can stay on NordVPN UK; nothing sets `http_proxy`.
```bash
# leave UK VPN connected on the phone, then:
-./bin/drm proxy transparent --package bbc.iplayer.android --reinject
+./bin/streamd proxy transparent --package bbc.iplayer.android --reinject
# open the app / play — Ctrl+C stops iptables and pulls files
```
@@ -75,7 +75,7 @@ Force-stop the target app once after CA reinject so it inherits the Magisk CA mo
The device binary cannot read an app module's values file, so a module's
manifest-scoring hosts are passed to it as flags (`--match`, `--score-host`,
-`--score-deny`). `drm capture` does this automatically.
+`--score-deny`). `streamd capture` does this automatically.
## Artifacts
diff --git a/apps/proxy/device/main.go b/apps/proxy/device/main.go
index d21fac5..6ebc33a 100644
--- a/apps/proxy/device/main.go
+++ b/apps/proxy/device/main.go
@@ -44,8 +44,11 @@ type capture struct {
LicenseURL string `json:"license_url,omitempty"`
Auth string `json:"auth,omitempty"`
PID string `json:"pid,omitempty"`
+ // LicenseBody is the raw JSON POST body from the phone's license request
+ // (RedBee / wrapped Widevine). Used to re-issue with a local CDM challenge.
+ LicenseBody string `json:"license_body,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
- PSSH string `json:"pssh,omitempty"` // first short Widevine PSSH seen in an MPD body
+ PSSH string `json:"pssh,omitempty"` // Widevine cenc:pssh from an MPD body
}
type licenseBody struct {
@@ -324,6 +327,7 @@ func main() {
if json.Unmarshal(body, &lb) == nil {
pid = lb.GetWidevineLicense.ReleasePID
}
+ bodyStr := string(body)
cap.set(func(c *capture) {
c.LicenseURL = url
if auth != "" {
@@ -332,10 +336,19 @@ func main() {
if pid != "" {
c.PID = pid
}
+ // Keep JSON license wrappers (RedBee / wrapped Widevine) so the
+ // host can swap in a local CDM challenge and re-POST.
+ if len(body) > 0 && (strings.HasPrefix(strings.TrimSpace(bodyStr), "{") ||
+ strings.Contains(strings.ToLower(req.Header.Get("Content-Type")), "json")) {
+ c.LicenseBody = bodyStr
+ }
})
if *verbose {
- log.Printf("[LIC] pid=%s auth=%s", pid, trim(auth, 40))
+ log.Printf("[LIC] pid=%s auth=%s body=%d", pid, trim(auth, 40), len(body))
log.Printf(" %s", trim(url, 120))
+ if len(body) > 0 {
+ log.Printf(" body: %s", trim(bodyStr, 200))
+ }
}
if *logAll {
traffic.write(map[string]any{
@@ -348,7 +361,7 @@ func main() {
"authorization": trim(auth, 200),
"pid": pid,
"body_len": len(body),
- "body_head": trim(string(body), 240),
+ "body_head": trim(bodyStr, 240),
})
}
}
@@ -1205,34 +1218,74 @@ func trim(s string, n int) string {
return s[:n] + "…"
}
-// Prefer the short Widevine PSSH (AAAASnBzc2g…) over the giant PlayReady blob.
+// Prefer a Widevine cenc:pssh (system id edef8ba9-…) over PlayReady / Marlin.
+// Channel 4 MPDs list PlayReady first; taking "any cenc:pssh" yields a useless blob.
func firstShortPSSH(mpd string) string {
- const marker = "AAAASnBzc2g"
- idx := strings.Index(mpd, marker)
- if idx < 0 {
- // any cenc:pssh content
- const open = "")
- k := strings.Index(mpd[i:], "")
+ k := strings.Index(lower[i:], closeTag)
if j < 0 || k < 0 || k <= j {
- return ""
+ break
}
- return strings.TrimSpace(mpd[i+j+1 : i+k])
- }
- end := idx
- for end < len(mpd) {
- c := mpd[end]
- if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=' {
- end++
- continue
+ val := strings.TrimSpace(mpd[i+j+1 : i+k])
+ // Prefer the Widevine ContentProtection block: UUID appears just before
+ // this pssh, or the decoded box itself starts with the Widevine system id.
+ windowStart := i - 400
+ if windowStart < 0 {
+ windowStart = 0
}
- break
+ window := lower[windowStart : i+j]
+ if strings.Contains(window, wvUUID) || strings.Contains(window, wvUUIDBare) || looksLikeWidevinePSSH(val) {
+ return val
+ }
+ searchFrom = i + k + len(closeTag)
}
- return mpd[idx:end]
+ // Fallback: legacy short BBC-style marker, then first cenc:pssh.
+ const marker = "AAAASnBzc2g"
+ if idx := strings.Index(mpd, marker); idx >= 0 {
+ end := idx
+ for end < len(mpd) {
+ c := mpd[end]
+ if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=' {
+ end++
+ continue
+ }
+ break
+ }
+ return mpd[idx:end]
+ }
+ i := strings.Index(lower, openTag)
+ if i < 0 {
+ return ""
+ }
+ j := strings.Index(mpd[i:], ">")
+ k := strings.Index(lower[i:], closeTag)
+ if j < 0 || k < 0 || k <= j {
+ return ""
+ }
+ return strings.TrimSpace(mpd[i+j+1 : i+k])
+}
+
+// looksLikeWidevinePSSH reports whether a base64 PSSH box uses the Widevine system id.
+func looksLikeWidevinePSSH(b64 string) bool {
+ // Widevine system id bytes as they appear after base64 of a typical PSSH header.
+ // Full decode is avoided here to keep the on-device binary dependency-free;
+ // the standard Widevine UUID base64 fragment inside PSSH boxes is stable.
+ const wvFrag = "AAAAA7e+LqXnWSs6jyCfc1R0h7Q" // edef8ba9-79d6-4ace-a3c8-27dcd51d21ed
+ return strings.Contains(b64, wvFrag)
}
func loadOrCreateCA(certPath, keyPath string) (*tls.Certificate, error) {
diff --git a/apps/proxy/device/tproxy_iptables.sh b/apps/proxy/device/tproxy_iptables.sh
index 52a61d6..609e6e9 100644
--- a/apps/proxy/device/tproxy_iptables.sh
+++ b/apps/proxy/device/tproxy_iptables.sh
@@ -19,10 +19,13 @@ uid_for_package() {
echo "$uid"
}
+# -w waits for the xtables lock (needed when grab-all restarts transparent MITM quickly).
+IPT="iptables -w 5"
+
stop_rules() {
- iptables -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true
- iptables -t nat -F "$CHAIN" 2>/dev/null || true
- iptables -t nat -X "$CHAIN" 2>/dev/null || true
+ $IPT -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true
+ $IPT -t nat -F "$CHAIN" 2>/dev/null || true
+ $IPT -t nat -X "$CHAIN" 2>/dev/null || true
echo "STOPPED"
}
@@ -41,17 +44,17 @@ start_rules() {
fi
stop_rules >/dev/null
- iptables -t nat -N "$CHAIN"
+ $IPT -t nat -N "$CHAIN"
# Never redirect the mitm itself (loop).
if [ -n "$proxy_uid" ]; then
- iptables -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN
+ $IPT -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN
fi
# Skip localhost / link-local.
- iptables -t nat -A "$CHAIN" -d 127.0.0.0/8 -j RETURN
- iptables -t nat -A "$CHAIN" -d 10.0.0.0/8 -j RETURN 2>/dev/null || true
+ $IPT -t nat -A "$CHAIN" -d 127.0.0.0/8 -j RETURN
+ $IPT -t nat -A "$CHAIN" -d 10.0.0.0/8 -j RETURN 2>/dev/null || true
# Redirect only the target app's HTTPS.
- iptables -t nat -A "$CHAIN" -p tcp -m owner --uid-owner "$uid" --dport 443 -j REDIRECT --to-ports "$port"
- iptables -t nat -A OUTPUT -j "$CHAIN"
+ $IPT -t nat -A "$CHAIN" -p tcp -m owner --uid-owner "$uid" --dport 443 -j REDIRECT --to-ports "$port"
+ $IPT -t nat -A OUTPUT -j "$CHAIN"
echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}"
}
diff --git a/apps/proxy/go.mod b/apps/proxy/go.mod
index 859bedf..0bea3da 100644
--- a/apps/proxy/go.mod
+++ b/apps/proxy/go.mod
@@ -1,7 +1,7 @@
-module drmdecryption/apps/proxy
+module streamd/apps/proxy
go 1.25.0
-require drmdecryption v0.0.0
+require streamd v0.0.0
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/proxy/proxyctlcmd/proxyctlcmd.go b/apps/proxy/proxyctlcmd/proxyctlcmd.go
index e170465..a39ae31 100644
--- a/apps/proxy/proxyctlcmd/proxyctlcmd.go
+++ b/apps/proxy/proxyctlcmd/proxyctlcmd.go
@@ -18,9 +18,9 @@ import (
"syscall"
"time"
- "drmdecryption/adb"
- "drmdecryption/proxy"
- "drmdecryption/repo"
+ "streamd/adb"
+ "streamd/proxy"
+ "streamd/repo"
)
// Run dispatches a proxy subcommand. args[0] is the subcommand name.
@@ -130,7 +130,7 @@ func buildCmd(args []string) {
if _, err := os.Stat(deviceDir); err != nil {
fmt.Fprintf(os.Stderr, "proxy build needs the full source tree (apps/proxy/device).\n")
- fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to drm.exe instead — no Go build required.\n")
+ fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to streamd instead — no Go build required.\n")
fmt.Fprintf(os.Stderr, "Missing: %s\n", deviceDir)
os.Exit(1)
}
@@ -258,6 +258,14 @@ func clearProxyCmd(args []string) {
proxy.ClearHTTPProxy(c)
}
+type stringList []string
+
+func (s *stringList) String() string { return strings.Join(*s, ",") }
+func (s *stringList) Set(v string) error {
+ *s = append(*s, v)
+ return nil
+}
+
func transparentCmd(args []string) {
fs := flag.NewFlagSet("transparent", flag.ExitOnError)
pkg := fs.String("package", "", "app package to redirect (e.g. bbc.iplayer.android)")
@@ -266,6 +274,8 @@ func transparentCmd(args []string) {
reinject := fs.Bool("reinject", false, "Magisk-reinject CA before start (slow; CA usually already mounted)")
port := fs.String("port", "8080", "transparent listen port on device")
noTail := fs.Bool("no-tail", false, "start only; do not wait / pull on Ctrl+C")
+ var mitmHosts stringList
+ fs.Var(&mitmHosts, "mitm-host", "force MITM for this host (repeatable; e.g. play.dar.itv.com)")
c := clientFrom(fs, args)
if err := c.EnsureDevice(); err != nil {
fatal(err)
@@ -286,7 +296,7 @@ func transparentCmd(args []string) {
remoteDir := "/data/local/tmp/capture/" + *pkg
fmt.Printf("[*] Transparent capture for %s → %s\n", *pkg, remoteDir)
- if err := proxy.StartTransparent(c, local, *pkg, *port, remoteDir, *reinject); err != nil {
+ if err := proxy.StartTransparent(c, local, *pkg, *port, remoteDir, *reinject, mitmHosts...); err != nil {
fatal(err)
}
fmt.Println("[+] running. Leave UK VPN ON. Open the app and play.")
diff --git a/apps/streamd/README.md b/apps/streamd/README.md
index 6aac36e..79994a8 100644
--- a/apps/streamd/README.md
+++ b/apps/streamd/README.md
@@ -1,65 +1,75 @@
# streamd
Control plane: REST API, SQLite, dashboard and media supervisor. Hosted by the
-single binary as `drm serve`.
+single binary as `streamd serve`.
```text
apps/streamd/
servecmd/ the command body, imported by apps/cli
internal/api HTTP handlers
+ internal/auth sessions, API keys, roles
internal/db SQLite store
- internal/ui dashboard (index.html, app.js, app.css)
+ internal/ui dashboard
internal/supervisor downloader + ffmpeg supervision
- internal/ws agent heartbeat
+ internal/ws agent + dashboard websockets
```
## Run
```bash
-./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET
+./bin/streamd serve --bind 127.0.0.1:8083
+# --data is optional: reuses existing .cache/streamd (cwd or next to the binary)
+# or set STREAMD_DATA / pass --data explicitly
```
-Port 8083 by default, to stay clear of anything already on 8080/8081. Media tools
-resolve from flags, then env (`NRE_PATH` / `FFMPEG_PATH` / `MP4DECRYPT_PATH`), then
-`bin/`, then `PATH` — no machine-specific paths are baked in.
+`--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any
+non-loopback address) logs a startup warning — put TLS in front, or keep loopback
+and reverse-proxy. Port 8083 stays clear of anything already on 8080/8081.
-Open `http://HOST:8083/` and put the token in the header box for mutating actions.
+On start, missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE,
+mp4decrypt) unless you pass `--skip-deps`.
-## API
+### Auth
+
+The old shared bearer token is optional and discouraged. Prefer:
+
+1. First-run setup creates an **admin** account (or `--admin-user` / `--admin-pass`).
+2. Sign in at the dashboard (session cookie + CSRF).
+3. Create **API keys** (Settings → API keys) for agents and scripts — roles
+ `admin` / `operator` / `viewer`.
+
+Legacy `--token` / `STREAMD_TOKEN` still works as an admin API key and logs a
+warning so you can migrate.
+
+`GET /api/health` stays readable without a principal (liveness only). Stream list,
+credentials, and mutations need a session or API key.
+
+## API (short)
| Method | Path | Notes |
|---|---|---|
-| GET | `/api/health` | liveness + uptime |
-| GET | `/api/apps` | modules// providers, channels, registered rewriters |
-| GET | `/api/streams` | list + runtime (the agent polls this) |
-| POST | `/api/streams` | create |
+| GET | `/api/health` | liveness (+ deps when authenticated) |
+| GET | `/api/apps` | modules, channels, rewriters |
+| GET | `/api/streams` | list + runtime (agent polls this) |
+| POST | `/api/streams` | create (`enabled` defaults false unless set; use the form checkbox) |
| GET/PATCH/DELETE | `/api/streams/:id` | detail / edit / delete |
| POST | `/api/streams/:id/start\|stop\|restart` | desired state |
-| POST | `/api/streams/:id/credentials` | `{mpd,key,pssh?,auth?,pid?}`, restarts if enabled |
-| POST | `/api/streams/:id/claim` | agent lease (`agent_id`, TTL ~3m) |
-| POST | `/api/streams/:id/claim/release` | release lease |
+| POST | `/api/streams/:id/capture` | ask connected agents to refresh credentials now |
+| POST | `/api/streams/:id/credentials` | `{mpd,key?,…}` — restarts if enabled |
+| POST | `/api/streams/:id/claim` | agent lease |
-Mutating routes need `Authorization: Bearer TOKEN` (or `X-Streamd-Token`, or
-`?token=`). HLS output is served from `--data/www` at `/hls//index.m3u8`.
+HLS output is served from `--data/www` at `/hls//index.m3u8`.
+
+Installation-wide settings (`idle_timeout_s`, `default_on_demand`,
+`default_outputs`, packager knobs) apply when creating a stream that omits those
+fields, or at the next media start for packager knobs.
## No provider knowledge
-The schema has no provider defaults, and the dashboard's app/channel pickers come
-from `/api/apps`. Per-stream downloader settings resolve at start time:
+App/channel pickers come from `/api/apps`. Downloader settings resolve at start:
```text
-stored row -> the stream's app module (app.StreamDefaults) -> neutral defaults
+stored row -> app module (StreamDefaults) -> installation settings -> neutral defaults
```
-The manifest rewriter is a registry lookup on the stream's `rewriter` column, and
-HLS is detected from the manifest shape — not from an app or stream name.
-
-## Status
-
-| Area | State |
-|---|---|
-| serve + SQLite + CRUD UI + claims + credentials | done |
-| `/api/apps` + module-driven defaults | done |
-| Real downloader/ffmpeg workers + playlist health | partial — least exercised path |
-
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
diff --git a/apps/streamd/go.mod b/apps/streamd/go.mod
index 4064060..d3a639e 100644
--- a/apps/streamd/go.mod
+++ b/apps/streamd/go.mod
@@ -1,14 +1,15 @@
-module drmdecryption/apps/streamd
+module streamd/apps/streamd
go 1.25.0
require (
- drmdecryption v0.0.0
github.com/gorilla/websocket v1.5.3
modernc.org/sqlite v1.34.5
+ streamd v0.0.0
+ gopkg.in/yaml.v3 v3.0.1
)
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
require (
github.com/dustin/go-humanize v1.0.1 // indirect
@@ -17,6 +18,7 @@ require (
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.42.0 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.8.0 // indirect
diff --git a/apps/streamd/go.sum b/apps/streamd/go.sum
index 3dff215..077f977 100644
--- a/apps/streamd/go.sum
+++ b/apps/streamd/go.sum
@@ -19,6 +19,9 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
diff --git a/apps/streamd/internal/api/api.go b/apps/streamd/internal/api/api.go
index f355d28..bf83790 100644
--- a/apps/streamd/internal/api/api.go
+++ b/apps/streamd/internal/api/api.go
@@ -4,12 +4,18 @@ import (
"encoding/json"
"errors"
"io"
+ "log/slog"
"net/http"
"strconv"
"strings"
"time"
- "drmdecryption/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/deps"
+ "streamd/apps/streamd/internal/egress"
+ "streamd/apps/streamd/internal/httpx"
+ "streamd/apps/streamd/internal/modstore"
)
type Supervisor interface {
@@ -18,58 +24,109 @@ type Supervisor interface {
Restart(id int64) error
}
+// CaptureRequester asks connected agents to refresh a stream's credentials
+// now, rather than on their next poll. Implemented by the websocket hub.
+type CaptureRequester interface {
+ RequestCapture(st db.Stream, reason string) int
+}
+
+// Viewers reports the live client count per stream, from the HLS gate.
+type Viewers interface {
+ ViewersFor(streamName string) int
+}
+
+// Notifier pushes change notifications to dashboards and agents.
+type Notifier interface {
+ NotifyStreamChanged(name, reason string)
+}
+
+// Scheduler exposes the upcoming schedule for the dashboard.
+type Scheduler interface {
+ Upcoming(limit int) any
+}
+
type Handler struct {
Store *db.Store
- Token string
+ Auth *auth.Store
+ Trust httpx.Trust
Supervisor Supervisor
+ Capture CaptureRequester
+ Viewers Viewers
+ Notifier Notifier
+ Scheduler Scheduler
StartedAt time.Time
+ Deps deps.Status
+ WWWRoot string // data/www — used to report variant playlist health
+ LogRoot string // data/logs — source for the log tail endpoints
+ DataDir string // streamd --data root
+ Modules *modstore.Store
+ // ModulesNotify is set when the hub supports module change pushes.
+ ModulesNotify ModulesNotifier
+ Egress *egress.Manager
+ Log *slog.Logger
}
func (h *Handler) Mount(mux *http.ServeMux) {
mux.HandleFunc("/api/health", h.health)
mux.HandleFunc("/api/streams", h.streams)
mux.HandleFunc("/api/streams/", h.streamAction)
+ mux.HandleFunc("/api/overview", h.overview)
+ h.MountControl(mux)
+ h.MountEgress(mux)
mux.HandleFunc("/api/apps", h.apps)
+ mux.HandleFunc("/api/modules", h.modules)
+ mux.HandleFunc("/api/modules/", h.modules)
}
-func (h *Handler) auth(w http.ResponseWriter, r *http.Request) bool {
- if h.Token == "" {
- return true
+func (h *Handler) logger() *slog.Logger {
+ if h.Log != nil {
+ return h.Log
}
- if r.Method == http.MethodGet {
- return true
- }
- auth := r.Header.Get("Authorization")
- tok := strings.TrimPrefix(auth, "Bearer ")
- if tok == "" {
- tok = r.Header.Get("X-Streamd-Token")
- }
- if tok == "" {
- tok = r.URL.Query().Get("token")
- }
- if tok != h.Token {
- writeErr(w, http.StatusUnauthorized, "unauthorized")
- return false
- }
- return true
+ return slog.Default()
}
+// audit records a mutating request against the caller.
+func (h *Handler) audit(r *http.Request, p *auth.Principal, status int, note string) {
+ if h.Auth == nil {
+ return
+ }
+ h.Auth.AuditRequest(p, h.Trust, r, status, note)
+}
+
+// health is the one route that stays readable without a principal: a reverse
+// proxy and a container orchestrator both need it for liveness checks. It
+// deliberately reveals nothing but liveness and whether the media tools are
+// present — no stream names, no paths.
func (h *Handler) health(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
- writeJSON(w, http.StatusOK, map[string]any{
+ out := map[string]any{
"ok": true,
"service": "streamd",
"uptime_s": time.Since(h.StartedAt).Seconds(),
"started_at": h.StartedAt.UTC().Format(time.RFC3339),
- })
+ }
+ // Tool paths are filesystem layout, so only an authenticated caller gets
+ // them. Anonymous callers still get a usable liveness answer.
+ if p := auth.From(r); p != nil {
+ out["deps"] = h.Deps
+ out["role"] = string(p.Role)
+ } else {
+ out["deps"] = h.Deps.Public()
+ }
+ writeJSON(w, http.StatusOK, out)
}
func (h *Handler) streams(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
+ // Reading the stream list now requires a principal. It used to be
+ // open, and it carries manifest URLs and (before redaction) keys.
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
list, err := h.Store.ListStreams()
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
@@ -78,9 +135,16 @@ func (h *Handler) streams(w http.ResponseWriter, r *http.Request) {
if list == nil {
list = []db.Stream{}
}
+ for i := range list {
+ h.enrich(&list[i])
+ // The list is never a place for credentials, whatever the role:
+ // it is the response the agent polls and the dashboard renders.
+ list[i].Redact()
+ }
writeJSON(w, http.StatusOK, map[string]any{"streams": list})
case http.MethodPost:
- if !h.auth(w, r) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
return
}
var in db.CreateStream
@@ -93,7 +157,11 @@ func (h *Handler) streams(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
- writeJSON(w, http.StatusCreated, st)
+ h.audit(r, p, http.StatusCreated, "created stream "+st.Name)
+ h.logger().Info("stream created", "stream", st.Name, "by", p.Actor())
+ h.enrich(&st)
+ h.notify(st.Name, "created")
+ writeJSON(w, http.StatusCreated, st.Redacted())
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
@@ -121,17 +189,64 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
sub = parts[2]
}
+ switch {
+ case action == "events" && r.Method == http.MethodPost:
+ h.postEvent(w, r, id)
+ return
+ case action == "events" && r.Method == http.MethodGet:
+ h.listEvents(w, r, id)
+ return
+ case action == "metrics" && r.Method == http.MethodGet:
+ h.listMetrics(w, r, id)
+ return
+ case action == "logs" && sub == "stream" && r.Method == http.MethodGet:
+ h.streamLogsSSE(w, r, id)
+ return
+ case action == "logs" && r.Method == http.MethodGet:
+ h.streamLogs(w, r, id)
+ return
+ case action == "schedules":
+ h.streamSchedules(w, r, id)
+ return
+ case action == "duplicate" && r.Method == http.MethodPost:
+ h.duplicate(w, r, id)
+ return
+ case action == "probe" && r.Method == http.MethodPost:
+ h.probe(w, r, id)
+ return
+ }
+
switch {
case action == "" && r.Method == http.MethodGet:
+ p, ok := auth.Guard(w, r, auth.RoleViewer)
+ if !ok {
+ return
+ }
st, err := h.Store.GetStream(id)
if err != nil {
writeErr(w, http.StatusNotFound, "not found")
return
}
- writeJSON(w, http.StatusOK, st)
+ h.enrich(&st)
+ // Credentials come back only for an operator who explicitly asks, and
+ // asking is recorded.
+ reveal := truthy(r.URL.Query().Get("reveal"))
+ if reveal && p.Role.AtLeast(auth.RoleOperator) {
+ h.audit(r, p, http.StatusOK, "revealed credentials for stream "+st.Name)
+ h.logger().Info("credentials revealed", "stream", st.Name, "by", p.Actor())
+ writeJSON(w, http.StatusOK, st)
+ return
+ }
+ if reveal {
+ // Say so rather than silently returning a blank key.
+ writeErr(w, http.StatusForbidden, "role "+string(p.Role)+" cannot reveal credentials (needs operator)")
+ return
+ }
+ writeJSON(w, http.StatusOK, st.Redacted())
case action == "" && (r.Method == http.MethodPatch || r.Method == http.MethodPut):
- if !h.auth(w, r) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
return
}
var in db.PatchStream
@@ -145,8 +260,9 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
- // Editing mpd/key/headers must tear down the live media worker and
- // bring up a fresh instance with the new credentials.
+ h.audit(r, p, http.StatusOK, "edited stream "+st.Name+changeNote(before, st, in))
+ // Editing mpd/key/headers/variants must tear down the live media worker
+ // and bring up a fresh instance with the new credentials.
if h.Supervisor != nil && credentialsChanged(before, st, in) {
if st.Enabled {
_ = h.Supervisor.Restart(id)
@@ -155,12 +271,16 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
}
st, _ = h.Store.GetStream(id)
}
- writeJSON(w, http.StatusOK, st)
+ h.enrich(&st)
+ h.notify(st.Name, "patched")
+ writeJSON(w, http.StatusOK, st.Redacted())
case action == "" && r.Method == http.MethodDelete:
- if !h.auth(w, r) {
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
return
}
+ before, _ := h.Store.GetStream(id)
if h.Supervisor != nil {
_ = h.Supervisor.Stop(id)
}
@@ -168,10 +288,14 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
+ h.audit(r, p, http.StatusOK, "deleted stream "+before.Name)
+ h.logger().Info("stream deleted", "stream", before.Name, "by", p.Actor())
+ h.notify(before.Name, "deleted")
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
case action == "start" && r.Method == http.MethodPost:
- if !h.auth(w, r) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
return
}
st, err := h.Store.SetEnabled(id, true)
@@ -179,6 +303,7 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusNotFound, err.Error())
return
}
+ h.audit(r, p, http.StatusOK, "started stream "+st.Name)
if h.Supervisor != nil {
if err := h.Supervisor.Start(id); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
@@ -186,10 +311,13 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
}
st, _ = h.Store.GetStream(id)
}
- writeJSON(w, http.StatusOK, st)
+ h.enrich(&st)
+ h.notify(st.Name, "started")
+ writeJSON(w, http.StatusOK, st.Redacted())
case action == "stop" && r.Method == http.MethodPost:
- if !h.auth(w, r) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
return
}
if h.Supervisor != nil {
@@ -200,10 +328,14 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusNotFound, err.Error())
return
}
- writeJSON(w, http.StatusOK, st)
+ h.audit(r, p, http.StatusOK, "stopped stream "+st.Name)
+ h.enrich(&st)
+ h.notify(st.Name, "stopped")
+ writeJSON(w, http.StatusOK, st.Redacted())
case action == "restart" && r.Method == http.MethodPost:
- if !h.auth(w, r) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
return
}
st, err := h.Store.SetEnabled(id, true)
@@ -211,6 +343,7 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusNotFound, err.Error())
return
}
+ h.audit(r, p, http.StatusOK, "restarted stream "+st.Name)
if h.Supervisor != nil {
if err := h.Supervisor.Restart(id); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
@@ -218,10 +351,44 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
}
st, _ = h.Store.GetStream(id)
}
- writeJSON(w, http.StatusOK, st)
+ h.enrich(&st)
+ h.notify(st.Name, "restarted")
+ writeJSON(w, http.StatusOK, st.Redacted())
+
+ case action == "capture" && r.Method == http.MethodPost:
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ st, err := h.Store.GetStream(id)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ if h.Capture == nil {
+ writeErr(w, http.StatusServiceUnavailable, "capture push is not available")
+ return
+ }
+ n := h.Capture.RequestCapture(st, "manual")
+ h.audit(r, p, http.StatusOK, "requested capture for stream "+st.Name)
+ h.logger().Info("capture requested", "stream", st.Name, "by", p.Actor(), "agents", n)
+ if n > 0 {
+ h.Store.Eventf(st.ID, db.EventCaptureStarted, db.SevInfo,
+ "manual capture requested (%d agent(s))", n)
+ } else {
+ h.Store.Eventf(st.ID, db.EventCaptureFailed, db.SevWarn,
+ "manual capture requested but no agents are connected")
+ }
+ h.notify(st.Name, "capture")
+ writeJSON(w, http.StatusOK, map[string]any{
+ "ok": true,
+ "stream": st.Name,
+ "agents_notified": n,
+ })
case action == "credentials" && r.Method == http.MethodPost:
- if !h.auth(w, r) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
return
}
var cred db.Credentials
@@ -234,6 +401,10 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
+ // Never log the credential itself, only that it arrived.
+ h.audit(r, p, http.StatusOK, "set credentials for stream "+st.Name+credNote(st))
+ h.logger().Info("credentials updated", "stream", st.Name, "by", p.Actor(),
+ "has_key", st.HasKey, "key_valid", st.KeyValid)
_ = h.Store.ReleaseClaim(id, "")
// Always kill the old media worker; start a fresh one when enabled.
if h.Supervisor != nil {
@@ -244,10 +415,13 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
}
st, _ = h.Store.GetStream(id)
}
- writeJSON(w, http.StatusOK, st)
+ h.enrich(&st)
+ h.notify(st.Name, "credentials")
+ writeJSON(w, http.StatusOK, st.Redacted())
case action == "claim" && sub == "" && r.Method == http.MethodPost:
- if !h.auth(w, r) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
return
}
var body struct {
@@ -265,10 +439,14 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
- writeJSON(w, http.StatusOK, st)
+ _ = p
+ // A claim is high-volume agent bookkeeping, so it is not audited; the
+ // capture events that follow it are.
+ h.enrich(&st)
+ writeJSON(w, http.StatusOK, st.Redacted())
case action == "claim" && sub == "release" && r.Method == http.MethodPost:
- if !h.auth(w, r) {
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
return
}
var body struct {
@@ -286,6 +464,34 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
}
}
+// enrich fills the response-only fields: per-output health, publish links and
+// the live viewer count.
+func (h *Handler) enrich(st *db.Stream) {
+ h.enrichVariantHealth(st)
+ h.enrichLinks(st)
+ if h.Viewers != nil {
+ st.Viewers = h.Viewers.ViewersFor(st.Name)
+ }
+}
+
+// notify pushes a stream change to every connected dashboard and agent so
+// they do not wait for the next poll.
+func (h *Handler) notify(name, reason string) {
+ if h.Notifier == nil || strings.TrimSpace(name) == "" {
+ return
+ }
+ h.Notifier.NotifyStreamChanged(name, reason)
+}
+
+// truthy accepts the spellings a query string realistically carries.
+func truthy(s string) bool {
+ switch strings.ToLower(strings.TrimSpace(s)) {
+ case "1", "true", "yes", "on":
+ return true
+ }
+ return false
+}
+
func readJSON(r *http.Request, dst any) error {
defer r.Body.Close()
b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
@@ -310,8 +516,51 @@ func writeErr(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]any{"error": msg})
}
-// credentialsChanged is true when the patch touched mpd, key, or headers that
-// the live NRE/ffmpeg worker is already using.
+// credNote summarises a credential update for the audit trail without
+// recording any part of the secret.
+func credNote(st db.Stream) string {
+ switch {
+ case !st.HasKey:
+ return " (clear, no key)"
+ case st.KeyValid:
+ return " (key ok)"
+ default:
+ return " (key present but unparseable)"
+ }
+}
+
+// changeNote lists which fields a patch actually touched, for the audit row.
+func changeNote(before, after db.Stream, in db.PatchStream) string {
+ var changed []string
+ add := func(name string, differs bool) {
+ if differs {
+ changed = append(changed, name)
+ }
+ }
+ add("mpd", in.MPD != nil && before.MPD != after.MPD)
+ // Record that the key changed, never what it changed to.
+ add("key", in.Key != nil && before.Key != after.Key)
+ add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON)
+ add("proxy", in.Proxy != nil && before.Proxy != after.Proxy)
+ add("egress", in.Egress != nil && before.Egress != after.Egress)
+ add("variants", before.VariantsJSON != after.VariantsJSON)
+ add("outputs", before.OutputsJSON != after.OutputsJSON)
+ add("settings", before.SettingsJSON != after.SettingsJSON)
+ add("enabled", before.Enabled != after.Enabled)
+ add("on_demand", before.OnDemand != after.OnDemand)
+ add("public", before.Public != after.Public)
+ add("drm_mode", before.DRMMode != after.DRMMode)
+ add("title", in.Title != nil && before.Title != after.Title)
+ add("tags", in.Tags != nil && before.Tags != after.Tags)
+ if len(changed) == 0 {
+ return " (no effective change)"
+ }
+ return " [" + strings.Join(changed, ",") + "]"
+}
+
+// credentialsChanged is true when the patch touched mpd, key, headers, proxy,
+// variants, outputs or packager settings that the live NRE/ffmpeg worker is
+// already using.
func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
if in.MPD != nil && strings.TrimSpace(before.MPD) != strings.TrimSpace(after.MPD) {
return true
@@ -322,5 +571,26 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
if in.HeadersJSON != nil && strings.TrimSpace(before.HeadersJSON) != strings.TrimSpace(after.HeadersJSON) {
return true
}
+ if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) {
+ return true
+ }
+ if in.Egress != nil && strings.TrimSpace(before.Egress) != strings.TrimSpace(after.Egress) {
+ return true
+ }
+ if in.VariantsJSON != nil || len(in.Variants) > 0 {
+ if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) {
+ return true
+ }
+ }
+ // The output set and the packager knobs are both baked into the ffmpeg
+ // command line, so changing either needs a fresh packager.
+ if in.OutputsJSON != nil || len(in.Outputs) > 0 {
+ if strings.TrimSpace(before.OutputsJSON) != strings.TrimSpace(after.OutputsJSON) {
+ return true
+ }
+ }
+ if in.SettingsJSON != nil && strings.TrimSpace(before.SettingsJSON) != strings.TrimSpace(after.SettingsJSON) {
+ return true
+ }
return false
}
diff --git a/apps/streamd/internal/api/apps.go b/apps/streamd/internal/api/apps.go
index e5216e6..53b146d 100644
--- a/apps/streamd/internal/api/apps.go
+++ b/apps/streamd/internal/api/apps.go
@@ -2,10 +2,15 @@ package api
import (
"net/http"
+ "sort"
- "drmdecryption/modhost"
- "drmdecryption/mpd"
- "drmdecryption/repo"
+ "gopkg.in/yaml.v3"
+
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/modstore"
+ "streamd/modhost"
+ "streamd/mpd"
+ "streamd/repo"
)
// appInfo describes one modules// provider to the dashboard, so the UI
@@ -15,6 +20,7 @@ type appInfo struct {
Channels []channelInfo `json:"channels"`
Rewriter string `json:"rewriter"`
HasConfig bool `json:"has_config"`
+ Error string `json:"error,omitempty"`
}
type channelInfo struct {
@@ -22,28 +28,55 @@ type channelInfo struct {
Label string `json:"label"`
}
-// apps answers GET /api/apps: which providers exist under modules/.
+// apps answers GET /api/apps: which providers exist under the panel modules store.
+// A single module that fails to describe is skipped with an error field rather
+// than failing the whole list (bad uploads must not blank the stream pickers).
func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
out := []appInfo{}
- listed, err := modhost.ListAll(repo.Root())
+ mods, err := modhost.Discover(repo.Root())
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
- for _, L := range listed {
- d := L.Desc
+ for _, m := range mods {
+ bin, err := modhost.EnsureBuilt(m)
+ if err != nil {
+ info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
+ h.fillChannelsFromStore(&info, m.Name)
+ out = append(out, info)
+ h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
+ continue
+ }
+ d, err := modhost.RunDescribe(bin)
+ if err != nil {
+ info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
+ h.fillChannelsFromStore(&info, m.Name)
+ out = append(out, info)
+ h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
+ continue
+ }
+ if d.Name == "" {
+ d.Name = m.Name
+ }
info := appInfo{Name: d.Name, Channels: []channelInfo{}, Rewriter: "none"}
for _, ch := range d.Channels {
info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label})
}
- info.HasConfig = len(info.Channels) > 0
if d.Rewriter != "" {
info.Rewriter = d.Rewriter
}
+ // Older module binaries may not see the panel store; fill from module.yaml.
+ if len(info.Channels) == 0 {
+ h.fillChannelsFromStore(&info, m.Name)
+ }
+ info.HasConfig = len(info.Channels) > 0
out = append(out, info)
}
writeJSON(w, http.StatusOK, map[string]any{
@@ -51,3 +84,53 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
"rewriters": mpd.Names(),
})
}
+
+func (h *Handler) fillChannelsFromStore(info *appInfo, name string) {
+ if h == nil || h.Modules == nil || info == nil {
+ return
+ }
+ chans := channelsFromStoreYAML(h.Modules, name)
+ if len(chans) == 0 {
+ return
+ }
+ info.Channels = chans
+ info.HasConfig = true
+ if info.Error != "" {
+ // Soft: yaml channels recovered even though describe failed.
+ info.Error = ""
+ }
+}
+
+// channelsFromStoreYAML reads channels from the panel module.yaml when describe
+// returns none (common with uploaded binaries that resolve values via cwd).
+func channelsFromStoreYAML(store *modstore.Store, name string) []channelInfo {
+ if store == nil {
+ return nil
+ }
+ raw, err := store.ReadYAML(name)
+ if err != nil || len(raw) == 0 {
+ return nil
+ }
+ var doc struct {
+ Channels map[string]struct {
+ Label string `yaml:"label"`
+ } `yaml:"channels"`
+ }
+ if err := yaml.Unmarshal(raw, &doc); err != nil || len(doc.Channels) == 0 {
+ return nil
+ }
+ ids := make([]string, 0, len(doc.Channels))
+ for id := range doc.Channels {
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+ out := make([]channelInfo, 0, len(ids))
+ for _, id := range ids {
+ label := doc.Channels[id].Label
+ if label == "" {
+ label = id
+ }
+ out = append(out, channelInfo{ID: id, Label: label})
+ }
+ return out
+}
diff --git a/apps/streamd/internal/api/apps_test.go b/apps/streamd/internal/api/apps_test.go
new file mode 100644
index 0000000..2ade1ad
--- /dev/null
+++ b/apps/streamd/internal/api/apps_test.go
@@ -0,0 +1,45 @@
+package api
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "streamd/apps/streamd/internal/modstore"
+)
+
+func TestChannelsFromStoreYAML(t *testing.T) {
+ root := t.TempDir()
+ store := modstore.New(root)
+ modDir := filepath.Join(root, "rte")
+ if err := os.MkdirAll(modDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ yaml := []byte(`package: air.RTE
+channels:
+ rteone:
+ label: RTE One
+ rtetwo:
+ label: RTE 2
+`)
+ if err := os.WriteFile(filepath.Join(modDir, "module.yaml"), yaml, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ chans := channelsFromStoreYAML(store, "rte")
+ if len(chans) != 2 {
+ t.Fatalf("got %d channels: %+v", len(chans), chans)
+ }
+ if chans[0].ID != "rteone" || chans[0].Label != "RTE One" {
+ t.Fatalf("first channel: %+v", chans[0])
+ }
+ if chans[1].ID != "rtetwo" {
+ t.Fatalf("second channel: %+v", chans[1])
+ }
+}
+
+func TestChannelsFromStoreYAMLMissing(t *testing.T) {
+ store := modstore.New(t.TempDir())
+ if chans := channelsFromStoreYAML(store, "nope"); chans != nil {
+ t.Fatalf("expected nil, got %+v", chans)
+ }
+}
diff --git a/apps/streamd/internal/api/control.go b/apps/streamd/internal/api/control.go
new file mode 100644
index 0000000..f89db47
--- /dev/null
+++ b/apps/streamd/internal/api/control.go
@@ -0,0 +1,631 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/mpd"
+)
+
+// MountControl adds the bulk, duplicate, probe, settings and schedule routes.
+func (h *Handler) MountControl(mux *http.ServeMux) {
+ mux.HandleFunc("/api/streams/bulk", h.bulk)
+ mux.HandleFunc("/api/settings", h.settings)
+ mux.HandleFunc("/api/schedules", h.schedules)
+ mux.HandleFunc("/api/schedules/", h.scheduleByID)
+}
+
+// ---------- bulk actions ----------
+
+func (h *Handler) bulk(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ var in struct {
+ IDs []int64 `json:"ids"`
+ Action string `json:"action"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ action := strings.ToLower(strings.TrimSpace(in.Action))
+ switch action {
+ case "start", "stop", "restart":
+ default:
+ writeErr(w, http.StatusBadRequest, "action must be start, stop or restart")
+ return
+ }
+ if len(in.IDs) == 0 {
+ writeErr(w, http.StatusBadRequest, "ids required")
+ return
+ }
+ if len(in.IDs) > 200 {
+ writeErr(w, http.StatusBadRequest, "too many ids in one request (max 200)")
+ return
+ }
+
+ type result struct {
+ ID int64 `json:"id"`
+ Name string `json:"name,omitempty"`
+ OK bool `json:"ok"`
+ Error string `json:"error,omitempty"`
+ }
+ results := make([]result, 0, len(in.IDs))
+ okCount := 0
+ for _, id := range in.IDs {
+ res := result{ID: id}
+ st, err := h.Store.GetStream(id)
+ if err != nil {
+ res.Error = "not found"
+ results = append(results, res)
+ continue
+ }
+ res.Name = st.Name
+ // One failure must not abort the rest of the batch: an operator
+ // stopping everything during an incident needs the others to stop.
+ if err := h.applyAction(id, action); err != nil {
+ res.Error = err.Error()
+ } else {
+ res.OK = true
+ okCount++
+ h.notify(st.Name, "bulk_"+action)
+ }
+ results = append(results, res)
+ }
+ h.audit(r, p, http.StatusOK,
+ fmt.Sprintf("bulk %s on %d stream(s), %d succeeded", action, len(in.IDs), okCount))
+ h.logger().Info("bulk action", "action", action, "requested", len(in.IDs), "ok", okCount, "by", p.Actor())
+ writeJSON(w, http.StatusOK, map[string]any{"action": action, "results": results, "ok_count": okCount})
+}
+
+func (h *Handler) applyAction(id int64, action string) error {
+ switch action {
+ case "start":
+ if _, err := h.Store.SetEnabled(id, true); err != nil {
+ return err
+ }
+ if h.Supervisor != nil {
+ return h.Supervisor.Start(id)
+ }
+ case "stop":
+ if h.Supervisor != nil {
+ if err := h.Supervisor.Stop(id); err != nil {
+ return err
+ }
+ }
+ if _, err := h.Store.SetEnabled(id, false); err != nil {
+ return err
+ }
+ case "restart":
+ if _, err := h.Store.SetEnabled(id, true); err != nil {
+ return err
+ }
+ if h.Supervisor != nil {
+ return h.Supervisor.Restart(id)
+ }
+ }
+ return nil
+}
+
+// ---------- duplicate ----------
+
+func (h *Handler) duplicate(w http.ResponseWriter, r *http.Request, id int64) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ src, err := h.Store.GetStream(id)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ var in struct {
+ Name string `json:"name"`
+ Title string `json:"title"`
+ }
+ _ = readJSON(r, &in)
+ name := strings.TrimSpace(in.Name)
+ if name == "" {
+ name = src.Name + "-copy"
+ }
+ title := strings.TrimSpace(in.Title)
+ if title == "" {
+ title = src.Title + " (copy)"
+ }
+ // Everything about how the stream is produced and published is copied.
+ // The copy starts disabled: duplicating a live channel should not quietly
+ // double the transcode load.
+ disabled := false
+ st, err := h.Store.CreateStream(db.CreateStream{
+ Name: name,
+ Title: title,
+ Description: src.Description,
+ Tags: src.Tags,
+ App: src.App,
+ Channel: src.Channel,
+ MPD: src.MPD,
+ Key: src.Key,
+ HeadersJSON: src.HeadersJSON,
+ Proxy: src.Proxy,
+ Egress: src.Egress,
+ VideoSelect: src.VideoSelect,
+ AudioSelect: src.AudioSelect,
+ Rewriter: src.Rewriter,
+ VariantsJSON: src.VariantsJSON,
+ OutputsJSON: src.OutputsJSON,
+ SettingsJSON: src.SettingsJSON,
+ DRMMode: src.DRMMode,
+ OnDemand: &src.OnDemand,
+ IdleTimeoutS: &src.IdleTimeoutS,
+ Public: &src.Public,
+ Enabled: &disabled,
+ })
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusCreated, "duplicated stream "+src.Name+" as "+st.Name)
+ h.Store.Eventf(st.ID, db.EventCreated, db.SevInfo, "duplicated from %s", src.Name)
+ h.enrich(&st)
+ h.notify(st.Name, "duplicated")
+ writeJSON(w, http.StatusCreated, st.Redacted())
+}
+
+// ---------- manifest probe ----------
+
+// probe fetches a stream's manifest through its own proxy and headers and
+// reports what it finds, without starting anything. It answers "is the URL
+// still good, and does it need keys?" without a capture or a transcode.
+func (h *Handler) probe(w http.ResponseWriter, r *http.Request, id int64) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ st, err := h.Store.GetStream(id)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ target := strings.TrimSpace(st.MPD)
+ // Allow probing a candidate URL before saving it.
+ var in struct {
+ MPD string `json:"mpd"`
+ }
+ _ = readJSON(r, &in)
+ if v := strings.TrimSpace(in.MPD); v != "" {
+ target = v
+ }
+ if target == "" {
+ writeErr(w, http.StatusBadRequest, "this stream has no manifest URL to probe")
+ return
+ }
+ u, err := url.Parse(target)
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
+ writeErr(w, http.StatusBadRequest, "manifest must be an http(s) URL")
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
+ defer cancel()
+ res := h.doProbe(ctx, st, target)
+
+ h.audit(r, p, http.StatusOK, fmt.Sprintf("probed stream %s: %s", st.Name, res.Summary))
+ h.Store.Eventf(st.ID, db.EventProbe, severityFor(res.OK), "probe: %s", res.Summary)
+ writeJSON(w, http.StatusOK, res)
+}
+
+func severityFor(ok bool) string {
+ if ok {
+ return db.SevInfo
+ }
+ return db.SevWarn
+}
+
+// probeResult is what the dashboard shows after a probe.
+type probeResult struct {
+ OK bool `json:"ok"`
+ URL string `json:"url"`
+ Status int `json:"status,omitempty"`
+ ContentType string `json:"content_type,omitempty"`
+ Bytes int `json:"bytes,omitempty"`
+ ElapsedMS int64 `json:"elapsed_ms"`
+ Kind string `json:"kind,omitempty"` // dash | hls | unknown
+ Periods int `json:"periods,omitempty"`
+ Representors int `json:"representations,omitempty"`
+ Variants int `json:"variants,omitempty"`
+ Live bool `json:"live"`
+ Encrypted bool `json:"encrypted"`
+ DRMSystems []string `json:"drm_systems,omitempty"`
+ DefaultKID string `json:"default_kid,omitempty"`
+ NeedsKeys bool `json:"needs_keys"`
+ HaveKeys bool `json:"have_keys"`
+ Summary string `json:"summary"`
+ Error string `json:"error,omitempty"`
+}
+
+// drmSystemIDs are the well-known Common Encryption system IDs, so a probe can
+// say which DRM a manifest asks for rather than just "encrypted".
+var drmSystemIDs = map[string]string{
+ "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed": "Widevine",
+ "9a04f079-9840-4286-ab92-e65be0885f95": "PlayReady",
+ "94ce86fb-07ff-4f43-adb8-93d2fa968ca2": "FairPlay",
+ "1077efec-c0b2-4d02-ace3-3c1e52e2fb4b": "ClearKey",
+}
+
+func (h *Handler) doProbe(ctx context.Context, st db.Stream, target string) probeResult {
+ res := probeResult{URL: target, HaveKeys: st.KeyValid}
+ start := time.Now()
+
+ client := &http.Client{Timeout: 20 * time.Second}
+ // Fetch through the stream's effective proxy (explicit or named egress),
+ // so a geo-restricted origin is probed the same way the downloader would.
+ proxy := strings.TrimSpace(st.Proxy)
+ if h.Egress != nil {
+ if p, err := h.Egress.ResolveProxy(st); err == nil {
+ proxy = p
+ } else if strings.TrimSpace(st.Egress) != "" && proxy == "" {
+ res.Error = "egress: " + err.Error()
+ res.Summary = "egress profile could not be brought up"
+ return res
+ }
+ }
+ if proxy != "" {
+ if c, err := httpClientWithProxy(proxy); err == nil {
+ client = c
+ } else {
+ res.Error = "proxy: " + err.Error()
+ res.Summary = "proxy configuration is invalid"
+ return res
+ }
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
+ if err != nil {
+ res.Error = err.Error()
+ res.Summary = "could not build the request"
+ return res
+ }
+ for k, v := range headerMapOf(st.HeadersJSON) {
+ req.Header.Set(k, v)
+ }
+ if req.Header.Get("User-Agent") == "" {
+ req.Header.Set("User-Agent", "streamd-probe/1.0")
+ }
+
+ resp, err := client.Do(req)
+ res.ElapsedMS = time.Since(start).Milliseconds()
+ if err != nil {
+ res.Error = err.Error()
+ res.Summary = "the origin could not be reached"
+ return res
+ }
+ defer resp.Body.Close()
+ res.Status = resp.StatusCode
+ res.ContentType = resp.Header.Get("Content-Type")
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
+ res.Bytes = len(body)
+ res.ElapsedMS = time.Since(start).Milliseconds()
+
+ if resp.StatusCode >= 400 {
+ res.Summary = fmt.Sprintf("origin returned %s", resp.Status)
+ return res
+ }
+ text := string(body)
+ switch {
+ case strings.Contains(text, " 0:
+ fmt.Fprintf(&b, ", encrypted (%s)", strings.Join(res.DRMSystems, ", "))
+ default:
+ b.WriteString(", encrypted")
+ }
+ if res.Encrypted && !res.HaveKeys {
+ b.WriteString(" — no usable key stored")
+ }
+ return b.String()
+}
+
+// httpClientWithProxy builds a client routed through a SOCKS5 or HTTP proxy.
+func httpClientWithProxy(proxyURL string) (*http.Client, error) {
+ u, err := url.Parse(proxyURL)
+ if err != nil {
+ return nil, err
+ }
+ switch u.Scheme {
+ case "http", "https", "socks5", "socks5h":
+ default:
+ return nil, fmt.Errorf("unsupported proxy scheme %q", u.Scheme)
+ }
+ return &http.Client{
+ Timeout: 20 * time.Second,
+ Transport: &http.Transport{Proxy: http.ProxyURL(u)},
+ }, nil
+}
+
+// ---------- settings ----------
+
+func (h *Handler) settings(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ vals, err := h.Store.GetSettings()
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "settings": vals,
+ "effective": h.Store.GlobalPackagerSettings(),
+ })
+ case http.MethodPut, http.MethodPatch:
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
+ return
+ }
+ var in map[string]string
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ // Only known keys, so a typo does not silently become a stored
+ // setting that never takes effect.
+ allowed := map[string]bool{
+ db.SettingHLSTime: true, db.SettingHLSListSize: true,
+ db.SettingLiveWait: true, db.SettingTSReadyBytes: true,
+ db.SettingIdleTimeoutS: true, db.SettingDefaultOutputs: true,
+ db.SettingOnDemand: true,
+ }
+ for k := range in {
+ if !allowed[k] {
+ writeErr(w, http.StatusBadRequest, "unknown setting "+k)
+ return
+ }
+ }
+ if err := h.Store.SetSettings(in); err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusOK, fmt.Sprintf("updated %d global setting(s)", len(in)))
+ vals, _ := h.Store.GetSettings()
+ writeJSON(w, http.StatusOK, map[string]any{
+ "settings": vals,
+ "effective": h.Store.GlobalPackagerSettings(),
+ // These shape the ffmpeg command line, which is built at start
+ // time, so running streams keep their current settings.
+ "note": "applies to each stream the next time it starts",
+ })
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// ---------- schedules ----------
+
+// schedules handles /api/schedules: the cross-stream views.
+func (h *Handler) schedules(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ if truthy(r.URL.Query().Get("upcoming")) {
+ limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
+ list, err := h.Store.UpcomingSchedules(limit)
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"schedules": list})
+ return
+ }
+ list, err := h.Store.ListSchedules(0)
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"schedules": list})
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// scheduleByID handles PATCH and DELETE on one schedule.
+func (h *Handler) scheduleByID(w http.ResponseWriter, r *http.Request) {
+ rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/schedules/"), "/")
+ if rest == "" {
+ h.schedules(w, r)
+ return
+ }
+ if rest == "upcoming" && r.Method == http.MethodGet {
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
+ list, err := h.Store.UpcomingSchedules(limit)
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"schedules": list})
+ return
+ }
+ id, err := strconv.ParseInt(strings.Split(rest, "/")[0], 10, 64)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, "invalid schedule id")
+ return
+ }
+ switch r.Method {
+ case http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ sc, err := h.Store.GetSchedule(id)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, sc)
+ case http.MethodPatch, http.MethodPut:
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ var in struct {
+ db.Schedule
+ Enabled *bool `json:"enabled"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ sc, err := h.Store.PatchSchedule(id, in.Schedule, in.Enabled)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusOK, "edited schedule "+rest+" on stream "+sc.StreamName)
+ writeJSON(w, http.StatusOK, sc)
+ case http.MethodDelete:
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ sc, _ := h.Store.GetSchedule(id)
+ if err := h.Store.DeleteSchedule(id); err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusOK, "deleted schedule "+rest+" on stream "+sc.StreamName)
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// streamSchedules handles /api/streams/:id/schedules.
+func (h *Handler) streamSchedules(w http.ResponseWriter, r *http.Request, id int64) {
+ switch r.Method {
+ case http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ list, err := h.Store.ListSchedules(id)
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"schedules": list})
+ case http.MethodPost:
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ var in db.Schedule
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ in.StreamID = id
+ in.CreatedBy = p.Actor()
+ sc, err := h.Store.CreateSchedule(in)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusCreated,
+ fmt.Sprintf("scheduled %s for stream %s (%s)", sc.Action, sc.StreamName, scheduleLabel(sc)))
+ h.Store.Eventf(id, db.EventUpdated, db.SevInfo,
+ "schedule added: %s %s", sc.Action, scheduleLabel(sc))
+ writeJSON(w, http.StatusCreated, sc)
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+func scheduleLabel(sc db.Schedule) string {
+ if sc.Kind == db.KindWeekly {
+ return fmt.Sprintf("%s at %s %s", db.DaysLabel(sc.DaysMask), sc.TimeOfDay, sc.TZ)
+ }
+ return "once at " + sc.AtUTC
+}
+
+// headerMapOf parses a stream's headers_json for the probe.
+func headerMapOf(headersJSON string) map[string]string {
+ out := map[string]string{}
+ headersJSON = strings.TrimSpace(headersJSON)
+ if headersJSON == "" || headersJSON == "{}" {
+ return out
+ }
+ var m map[string]string
+ if err := json.Unmarshal([]byte(headersJSON), &m); err != nil {
+ return out
+ }
+ for k, v := range m {
+ if k = strings.TrimSpace(k); k != "" {
+ out[k] = strings.TrimSpace(v)
+ }
+ }
+ return out
+}
diff --git a/apps/streamd/internal/api/egress.go b/apps/streamd/internal/api/egress.go
new file mode 100644
index 0000000..bfda8b9
--- /dev/null
+++ b/apps/streamd/internal/api/egress.go
@@ -0,0 +1,254 @@
+package api
+
+import (
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+)
+
+// MountEgress registers /api/egress routes.
+func (h *Handler) MountEgress(mux *http.ServeMux) {
+ mux.HandleFunc("/api/egress", h.egressRoot)
+ mux.HandleFunc("/api/egress/", h.egressAction)
+}
+
+func (h *Handler) egressRoot(w http.ResponseWriter, r *http.Request) {
+ if h.Egress == nil {
+ writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
+ return
+ }
+ switch r.Method {
+ case http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ list, err := h.Store.ListEgressProfiles()
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ for i := range list {
+ h.Egress.Enrich(&list[i])
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"profiles": list})
+ case http.MethodPost:
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
+ return
+ }
+ var in db.CreateEgressProfile
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ prof, err := h.Store.CreateEgressProfile(in)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.Egress.Enrich(&prof)
+ h.audit(r, p, http.StatusOK, "create egress "+prof.Name)
+ writeJSON(w, http.StatusOK, prof)
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+func (h *Handler) egressAction(w http.ResponseWriter, r *http.Request) {
+ if h.Egress == nil {
+ writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
+ return
+ }
+ path := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/egress/"), "/")
+ if path == "" {
+ h.egressRoot(w, r)
+ return
+ }
+ parts := strings.Split(path, "/")
+ name := db.Slug(parts[0])
+ if name == "" {
+ writeErr(w, http.StatusBadRequest, "invalid name")
+ return
+ }
+ action := ""
+ if len(parts) > 1 {
+ action = strings.ToLower(parts[1])
+ }
+
+ switch {
+ case action == "" && r.Method == http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ prof, err := h.Egress.Status(name)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, prof)
+
+ case action == "" && r.Method == http.MethodPut:
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
+ return
+ }
+ h.putEgress(w, r, p, name)
+
+ case action == "" && r.Method == http.MethodDelete:
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
+ return
+ }
+ prof, err := h.Store.GetEgressProfileByName(name)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ _ = h.Egress.Down(name)
+ if err := h.Store.DeleteEgressProfile(prof.ID); err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ _ = h.Egress.RemoveFiles(name)
+ h.audit(r, p, http.StatusOK, "delete egress "+name)
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+
+ case action == "up" && r.Method == http.MethodPost:
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
+ return
+ }
+ if err := h.Egress.EnsureUp(name); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ prof, _ := h.Egress.Status(name)
+ h.audit(r, p, http.StatusOK, "egress up "+name)
+ writeJSON(w, http.StatusOK, prof)
+
+ case action == "down" && r.Method == http.MethodPost:
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
+ return
+ }
+ if err := h.Egress.Down(name); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ prof, _ := h.Egress.Status(name)
+ h.audit(r, p, http.StatusOK, "egress down "+name)
+ writeJSON(w, http.StatusOK, prof)
+
+ case action == "test" && r.Method == http.MethodPost:
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
+ return
+ }
+ out, err := h.Egress.TestDial(name)
+ if err != nil {
+ if out == nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusOK, "egress test "+name+" fail")
+ writeJSON(w, http.StatusOK, out)
+ return
+ }
+ h.audit(r, p, http.StatusOK, "egress test "+name)
+ writeJSON(w, http.StatusOK, out)
+
+ case action == "conf" && r.Method == http.MethodPut:
+ p, ok := auth.Guard(w, r, auth.RoleAdmin)
+ if !ok {
+ return
+ }
+ body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
+ _ = r.Body.Close()
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ contents := string(body)
+ ct := r.Header.Get("Content-Type")
+ if strings.Contains(ct, "json") || strings.HasPrefix(strings.TrimSpace(contents), "{") {
+ var in struct {
+ Conf string `json:"conf"`
+ }
+ if err := json.Unmarshal(body, &in); err != nil || strings.TrimSpace(in.Conf) == "" {
+ writeErr(w, http.StatusBadRequest, "conf required")
+ return
+ }
+ contents = in.Conf
+ }
+ if strings.TrimSpace(contents) == "" {
+ writeErr(w, http.StatusBadRequest, "empty conf")
+ return
+ }
+ if _, err := h.Store.GetEgressProfileByName(name); err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ if err := h.Egress.WriteConf(name, contents); err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ prof, _ := h.Egress.Status(name)
+ h.audit(r, p, http.StatusOK, "egress conf "+name)
+ writeJSON(w, http.StatusOK, prof)
+
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+func (h *Handler) putEgress(w http.ResponseWriter, r *http.Request, p *auth.Principal, name string) {
+ prof, err := h.Store.GetEgressProfileByName(name)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ var in struct {
+ Enabled *bool `json:"enabled"`
+ SocksURL *string `json:"socks_url"`
+ Kind *string `json:"kind"`
+ Conf *string `json:"conf"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ upd, err := h.Store.UpdateEgressProfile(prof.ID, db.UpdateEgressProfile{
+ Enabled: in.Enabled, SocksURL: in.SocksURL, Kind: in.Kind,
+ })
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if in.Conf != nil && strings.TrimSpace(*in.Conf) != "" {
+ if err := h.Egress.WriteConf(name, *in.Conf); err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ }
+ h.Egress.Enrich(&upd)
+ if in.Enabled != nil && *in.Enabled {
+ _ = h.Egress.EnsureUp(name)
+ upd, _ = h.Egress.Status(name)
+ }
+ if in.Enabled != nil && !*in.Enabled {
+ _ = h.Egress.Down(name)
+ upd, _ = h.Egress.Status(name)
+ }
+ h.audit(r, p, http.StatusOK, "update egress "+name)
+ writeJSON(w, http.StatusOK, upd)
+}
diff --git a/apps/streamd/internal/api/events.go b/apps/streamd/internal/api/events.go
new file mode 100644
index 0000000..1817a19
--- /dev/null
+++ b/apps/streamd/internal/api/events.go
@@ -0,0 +1,388 @@
+package api
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/logfile"
+)
+
+// logSources maps a caller-supplied source name to the log file suffix the
+// supervisor writes. It is a fixed allowlist, and the file name is built from
+// the stream's own name, so no part of the path comes from request input.
+var logSources = map[string]string{
+ "nre": "-nre.log",
+ "ffmpeg.out": "-ffmpeg.out.log",
+ "ffmpeg.err": "-ffmpeg.err.log",
+}
+
+// postEvent records an agent-authored event. This is how a failing phone
+// capture reaches the dashboard instead of only the agent's console.
+func (h *Handler) postEvent(w http.ResponseWriter, r *http.Request, id int64) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ st, err := h.Store.GetStream(id)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ var in struct {
+ Kind string `json:"kind"`
+ Severity string `json:"severity"`
+ Message string `json:"message"`
+ Detail map[string]any `json:"detail"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ kind := strings.TrimSpace(in.Kind)
+ if kind == "" {
+ writeErr(w, http.StatusBadRequest, "kind required")
+ return
+ }
+ // Agents may only author their own capture events; everything else on the
+ // timeline is written by streamd itself and must stay trustworthy.
+ if !agentEventKinds[kind] {
+ writeErr(w, http.StatusBadRequest,
+ "kind "+kind+" is not one an agent may report (allowed: capture_started, capture_ok, capture_failed)")
+ return
+ }
+ sev := strings.TrimSpace(in.Severity)
+ if sev == "" {
+ sev = db.SevInfo
+ if kind == db.EventCaptureFailed {
+ sev = db.SevError
+ }
+ }
+ var detail json.RawMessage
+ if len(in.Detail) > 0 {
+ if b, err := json.Marshal(in.Detail); err == nil && len(b) < 8192 {
+ detail = b
+ }
+ }
+ h.Store.AddEvent(db.StreamEvent{
+ StreamID: id,
+ Kind: kind,
+ Severity: sev,
+ Actor: p.Actor(),
+ Message: in.Message,
+ Detail: detail,
+ })
+ h.logger().Info("agent event", "stream", st.Name, "kind", kind, "actor", p.Actor(), "msg", in.Message)
+ if h.Notifier != nil {
+ h.Notifier.NotifyStreamChanged(st.Name, kind)
+ }
+ writeJSON(w, http.StatusCreated, map[string]any{"ok": true})
+}
+
+var agentEventKinds = map[string]bool{
+ db.EventCaptureStarted: true,
+ db.EventCaptureOK: true,
+ db.EventCaptureFailed: true,
+}
+
+func (h *Handler) listEvents(w http.ResponseWriter, r *http.Request, id int64) {
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ // Flush first so a caller sees the effect of what they just did.
+ _ = h.Store.FlushHistory()
+ q := r.URL.Query()
+ limit, _ := strconv.Atoi(q.Get("limit"))
+ list, err := h.Store.ListEvents(id, limit, q.Get("kind"), q.Get("since"))
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"events": list})
+}
+
+func (h *Handler) listMetrics(w http.ResponseWriter, r *http.Request, id int64) {
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ _ = h.Store.FlushHistory()
+ window := parseWindow(r.URL.Query().Get("window"))
+ points, err := h.Store.ListMetrics(id, window)
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ uptime, _ := h.Store.UptimeRatio(id, window)
+ out := map[string]any{"metrics": points, "window_s": int(window.Seconds())}
+ if uptime >= 0 {
+ out["uptime_ratio"] = uptime
+ }
+ writeJSON(w, http.StatusOK, out)
+}
+
+func parseWindow(s string) time.Duration {
+ switch strings.ToLower(strings.TrimSpace(s)) {
+ case "", "1h":
+ return time.Hour
+ case "15m":
+ return 15 * time.Minute
+ case "6h":
+ return 6 * time.Hour
+ case "24h", "1d":
+ return 24 * time.Hour
+ case "7d":
+ return 7 * 24 * time.Hour
+ }
+ if d, err := time.ParseDuration(s); err == nil && d > 0 && d <= 7*24*time.Hour {
+ return d
+ }
+ return time.Hour
+}
+
+// logPath resolves a stream + source + optional variant to a log file path.
+// Returns "" when the source is not on the allowlist.
+func (h *Handler) logPath(st db.Stream, source, variant string) string {
+ suffix, ok := logSources[strings.ToLower(strings.TrimSpace(source))]
+ if !ok || strings.TrimSpace(h.LogRoot) == "" {
+ return ""
+ }
+ base := st.Name
+ // A variant's packager writes to "--ffmpeg.*.log". The
+ // variant id is validated against the stream's own ladder rather than
+ // trusted, so it cannot contribute path characters.
+ if v := strings.TrimSpace(variant); v != "" && v != db.SourceVariantID {
+ known := false
+ for _, spec := range db.ParseVariantsJSON(st.VariantsJSON) {
+ if spec.ID == v {
+ known = true
+ break
+ }
+ }
+ if !known {
+ return ""
+ }
+ base = st.Name + "-" + v
+ }
+ return filepath.Join(h.LogRoot, base+suffix)
+}
+
+func (h *Handler) streamLogs(w http.ResponseWriter, r *http.Request, id int64) {
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
+ return
+ }
+ st, err := h.Store.GetStream(id)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ q := r.URL.Query()
+ source := q.Get("source")
+ if source == "" {
+ source = "nre"
+ }
+ path := h.logPath(st, source, q.Get("variant"))
+ if path == "" {
+ writeErr(w, http.StatusBadRequest, "unknown log source — use one of nre, ffmpeg.out, ffmpeg.err")
+ return
+ }
+ tail, _ := strconv.Atoi(q.Get("tail"))
+ if tail <= 0 {
+ tail = 500
+ }
+ if tail > 5000 {
+ tail = 5000
+ }
+ body, err := logfile.Tail(path, tail)
+ if err != nil {
+ if os.IsNotExist(err) {
+ writeJSON(w, http.StatusOK, map[string]any{
+ "source": source, "lines": "", "exists": false,
+ "note": "no log yet — this stream has not run since streamd started",
+ })
+ return
+ }
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "source": source,
+ "exists": true,
+ "lines": string(body),
+ })
+}
+
+// streamLogsSSE follows a log file and pushes new bytes as they appear, so the
+// dashboard can show a live tail.
+func (h *Handler) streamLogsSSE(w http.ResponseWriter, r *http.Request, id int64) {
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
+ return
+ }
+ st, err := h.Store.GetStream(id)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "not found")
+ return
+ }
+ q := r.URL.Query()
+ source := q.Get("source")
+ if source == "" {
+ source = "nre"
+ }
+ path := h.logPath(st, source, q.Get("variant"))
+ if path == "" {
+ writeErr(w, http.StatusBadRequest, "unknown log source")
+ return
+ }
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ writeErr(w, http.StatusInternalServerError, "streaming unsupported")
+ return
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("Connection", "keep-alive")
+ // Defeat proxy buffering, which would otherwise hold the whole stream.
+ w.Header().Set("X-Accel-Buffering", "no")
+ w.WriteHeader(http.StatusOK)
+
+ send := func(event, data string) bool {
+ for _, line := range strings.Split(strings.TrimRight(data, "\n"), "\n") {
+ if _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, line); err != nil {
+ return false
+ }
+ }
+ flusher.Flush()
+ return true
+ }
+
+ // Start from the tail so the viewer has context, then follow.
+ if initial, err := logfile.Tail(path, 200); err == nil && len(initial) > 0 {
+ if !send("log", string(initial)) {
+ return
+ }
+ }
+ var offset int64
+ if fi, err := os.Stat(path); err == nil {
+ offset = fi.Size()
+ }
+
+ ticker := time.NewTicker(time.Second)
+ defer ticker.Stop()
+ keepalive := time.NewTicker(20 * time.Second)
+ defer keepalive.Stop()
+ ctx := r.Context()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-keepalive.C:
+ if _, err := fmt.Fprint(w, ": keepalive\n\n"); err != nil {
+ return
+ }
+ flusher.Flush()
+ case <-ticker.C:
+ fi, err := os.Stat(path)
+ if err != nil {
+ continue
+ }
+ size := fi.Size()
+ if size < offset {
+ // The file rotated under us; start again from its beginning.
+ offset = 0
+ if !send("note", "-- log rotated --") {
+ return
+ }
+ }
+ if size == offset {
+ continue
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ continue
+ }
+ buf := make([]byte, size-offset)
+ n, err := f.ReadAt(buf, offset)
+ _ = f.Close()
+ if n > 0 {
+ if !send("log", string(buf[:n])) {
+ return
+ }
+ offset += int64(n)
+ }
+ if err != nil && n == 0 {
+ continue
+ }
+ }
+ }
+}
+
+// overview is the dashboard's single round trip: totals, viewer counts and
+// the recent activity feed.
+func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ list, err := h.Store.ListStreams()
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ var running, down, starting, stopped, onDemandIdle, viewers, needCapture int
+ for i := range list {
+ st := &list[i]
+ if h.Viewers != nil {
+ st.Viewers = h.Viewers.ViewersFor(st.Name)
+ viewers += st.Viewers
+ }
+ if st.NeedsCapture {
+ needCapture++
+ }
+ switch st.Health {
+ case "ok":
+ running++
+ case "down":
+ down++
+ case "starting":
+ starting++
+ default:
+ stopped++
+ if st.OnDemand && st.Enabled {
+ onDemandIdle++
+ }
+ }
+ }
+ _ = h.Store.FlushHistory()
+ recent, _ := h.Store.RecentEvents(25)
+ sessions, _ := h.Store.ListRecentSessions(50)
+ if sessions == nil {
+ sessions = []db.StreamSession{}
+ }
+ out := map[string]any{
+ "totals": map[string]any{
+ "streams": len(list),
+ "running": running,
+ "starting": starting,
+ "down": down,
+ "stopped": stopped,
+ "ondemand_idle": onDemandIdle,
+ "viewers": viewers,
+ "needs_capture": needCapture,
+ },
+ "recent_events": recent,
+ "recent_sessions": sessions,
+ }
+ if h.Scheduler != nil {
+ out["upcoming"] = h.Scheduler.Upcoming(10)
+ }
+ writeJSON(w, http.StatusOK, out)
+}
diff --git a/apps/streamd/internal/api/modules.go b/apps/streamd/internal/api/modules.go
new file mode 100644
index 0000000..e5a9de0
--- /dev/null
+++ b/apps/streamd/internal/api/modules.go
@@ -0,0 +1,280 @@
+package api
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/modstore"
+)
+
+// ModulesNotifier pushes module change events to agents and the dashboard.
+type ModulesNotifier interface {
+ NotifyModulesChanged(name, reason string)
+}
+
+func (h *Handler) modStore() *modstore.Store {
+ if h.Modules != nil {
+ return h.Modules
+ }
+ root := filepath.Join(h.DataDir, "modules")
+ return modstore.New(root)
+}
+
+func (h *Handler) notifyModules(name, reason string) {
+ if h.ModulesNotify != nil {
+ h.ModulesNotify.NotifyModulesChanged(name, reason)
+ return
+ }
+ // Hub also implements Notifier; prefer the dedicated method when available.
+ if n, ok := h.Notifier.(ModulesNotifier); ok {
+ n.NotifyModulesChanged(name, reason)
+ }
+}
+
+func (h *Handler) modules(w http.ResponseWriter, r *http.Request) {
+ path := strings.TrimPrefix(r.URL.Path, "/api/modules")
+ path = strings.Trim(path, "/")
+
+ switch {
+ case path == "" && r.Method == http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ h.listModules(w, r)
+ case path == "upload" && r.Method == http.MethodPost:
+ h.uploadModule(w, r)
+ case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
+ h.getModule(w, r, path)
+ case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodPut:
+ h.putModule(w, r, path)
+ case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodDelete:
+ h.deleteModule(w, r, path)
+ case strings.HasSuffix(path, "/yaml") && r.Method == http.MethodGet:
+ name := strings.TrimSuffix(path, "/yaml")
+ name = strings.Trim(name, "/")
+ h.getModuleYAML(w, r, name)
+ case strings.HasSuffix(path, "/package") && r.Method == http.MethodGet:
+ name := strings.TrimSuffix(path, "/package")
+ name = strings.Trim(name, "/")
+ h.getModulePackage(w, r, name)
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+func (h *Handler) listModules(w http.ResponseWriter, r *http.Request) {
+ list, err := h.modStore().List()
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"modules": list})
+}
+
+func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) {
+ if !modstore.NameRe.MatchString(name) {
+ writeErr(w, http.StatusBadRequest, "invalid module name")
+ return
+ }
+ info := h.modStore().Info(name)
+ if !info.HasYAML && !info.HasPackage {
+ writeErr(w, http.StatusNotFound, "module not found")
+ return
+ }
+ out := map[string]any{"module": info}
+ if r.URL.Query().Get("include") == "yaml" {
+ // YAML may hold secrets — operator+.
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
+ return
+ }
+ raw, err := h.modStore().ReadYAML(name)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ out["yaml"] = string(raw)
+ }
+ writeJSON(w, http.StatusOK, out)
+}
+
+func (h *Handler) getModuleYAML(w http.ResponseWriter, r *http.Request, name string) {
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
+ return
+ }
+ if !modstore.NameRe.MatchString(name) {
+ writeErr(w, http.StatusBadRequest, "invalid module name")
+ return
+ }
+ raw, err := h.modStore().ReadYAML(name)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ w.Header().Set("Content-Type", "text/yaml; charset=utf-8")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(raw)
+}
+
+func (h *Handler) getModulePackage(w http.ResponseWriter, r *http.Request, name string) {
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
+ return
+ }
+ if !modstore.NameRe.MatchString(name) {
+ writeErr(w, http.StatusBadRequest, "invalid module name")
+ return
+ }
+ f, _, err := h.modStore().OpenPackage(name)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ defer f.Close()
+ modTime := time.Time{}
+ if st, err := f.Stat(); err == nil {
+ modTime = st.ModTime()
+ }
+ w.Header().Set("Content-Type", "application/zip")
+ w.Header().Set("Content-Disposition", `attachment; filename="`+name+`.zip"`)
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ http.ServeContent(w, r, name+".zip", modTime, f)
+}
+
+func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ if !modstore.NameRe.MatchString(name) {
+ writeErr(w, http.StatusBadRequest, "invalid module name")
+ return
+ }
+
+ body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20))
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ defer r.Body.Close()
+
+ yamlBytes, err := extractModuleYAML(r.Header.Get("Content-Type"), body)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+
+ info, err := h.modStore().WriteYAML(name, yamlBytes)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+
+ h.audit(r, p, http.StatusOK, "updated module.yaml for "+name)
+ h.logger().Info("module.yaml updated", "module", name, "by", p.Actor(), "sha256", info.YAMLSHA256)
+ h.notifyModules(name, "yaml_updated")
+ writeJSON(w, http.StatusOK, map[string]any{
+ "ok": true,
+ "module": info,
+ })
+}
+
+func (h *Handler) deleteModule(w http.ResponseWriter, r *http.Request, name string) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ if !modstore.NameRe.MatchString(name) {
+ writeErr(w, http.StatusBadRequest, "invalid module name")
+ return
+ }
+ if err := h.modStore().Delete(name); err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusOK, "deleted module "+name)
+ h.logger().Info("module deleted", "module", name, "by", p.Actor())
+ h.notifyModules(name, "deleted")
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+func (h *Handler) uploadModule(w http.ResponseWriter, r *http.Request) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ if err := r.ParseMultipartForm(modstore.MaxPackageBytes + (1 << 20)); err != nil {
+ writeErr(w, http.StatusBadRequest, "multipart: "+err.Error())
+ return
+ }
+ name := strings.TrimSpace(r.FormValue("name"))
+ file, hdr, err := r.FormFile("file")
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, "missing file field")
+ return
+ }
+ defer file.Close()
+ if name == "" && hdr != nil {
+ // rte.zip → rte (helps flat release zips before binary inference).
+ base := strings.TrimSuffix(filepath.Base(hdr.Filename), filepath.Ext(hdr.Filename))
+ base = strings.ToLower(strings.TrimSpace(base))
+ if modstore.NameRe.MatchString(base) {
+ name = base
+ }
+ }
+ if hdr.Size > modstore.MaxPackageBytes {
+ writeErr(w, http.StatusBadRequest, "zip too large")
+ return
+ }
+ raw, err := io.ReadAll(io.LimitReader(file, modstore.MaxPackageBytes+1))
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if int64(len(raw)) > modstore.MaxPackageBytes {
+ writeErr(w, http.StatusBadRequest, "zip too large")
+ return
+ }
+ info, err := h.modStore().InstallZip(raw, name)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusOK, "uploaded module package "+info.Name)
+ h.logger().Info("module package uploaded",
+ "module", info.Name, "by", p.Actor(),
+ "package_sha256", info.PackageSHA256, "arches", info.Arches)
+ h.notifyModules(info.Name, "uploaded")
+ writeJSON(w, http.StatusOK, map[string]any{
+ "ok": true,
+ "module": info,
+ })
+}
+
+// extractModuleYAML accepts raw YAML or JSON {"yaml":"..."}.
+func extractModuleYAML(contentType string, body []byte) ([]byte, error) {
+ ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))
+ switch ct {
+ case "application/json", "text/json":
+ var wrap struct {
+ YAML string `json:"yaml"`
+ }
+ if err := json.Unmarshal(body, &wrap); err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(wrap.YAML) == "" {
+ return nil, errors.New("empty yaml field")
+ }
+ return []byte(wrap.YAML), nil
+ default:
+ return body, nil
+ }
+}
diff --git a/apps/streamd/internal/api/variants.go b/apps/streamd/internal/api/variants.go
new file mode 100644
index 0000000..c29db91
--- /dev/null
+++ b/apps/streamd/internal/api/variants.go
@@ -0,0 +1,120 @@
+package api
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+// stalePlaylistS is how old a playlist may get before the output counts as
+// down. It matches the supervisor's own staleness threshold.
+const stalePlaylistS = 45
+
+// enrichVariantHealth updates each variant's health from on-disk HLS playlists.
+func (h *Handler) enrichVariantHealth(st *db.Stream) {
+ if st == nil {
+ return
+ }
+ if len(st.Variants) == 0 {
+ st.Variants = db.AttachVariantStatuses(st.Name, st.VariantsJSON, st.Health, st.PlaylistAgeS)
+ }
+ www := strings.TrimSpace(h.WWWRoot)
+ if www == "" {
+ return
+ }
+ for i := range st.Variants {
+ v := &st.Variants[i]
+ if !v.Enabled {
+ v.Health = "off"
+ continue
+ }
+ if v.IsSource() {
+ v.Health = st.Health
+ v.PlaylistAgeS = st.PlaylistAgeS
+ continue
+ }
+ dirName := db.VariantDir(st.Name, v.ID, v.Height, v.AudioOnly)
+ health, age := h.playlistHealth(filepath.Join(www, dirName, "index.m3u8"), st.Health)
+ v.Health = health
+ v.PlaylistAgeS = age
+ }
+}
+
+// enrichLinks resolves every variant x output endpoint and stats each one, so
+// the dashboard can show that (say) HLS is fine while DASH has died.
+func (h *Handler) enrichLinks(st *db.Stream) {
+ if st == nil {
+ return
+ }
+ links := db.BuildPublishLinks(st.Name, st.VariantsJSON, st.OutputsJSON)
+ www := strings.TrimSpace(h.WWWRoot)
+ // Variant health computed above, to fall back on for outputs with no file
+ // of their own (progressive TS is a live pipe, not a playlist).
+ variantHealth := map[string]string{}
+ for _, v := range st.Variants {
+ variantHealth[v.ID] = v.Health
+ }
+ for i := range links {
+ l := &links[i]
+ if www == "" {
+ continue
+ }
+ if l.Format == db.FormatTS {
+ // No file to stat: the pipe is live exactly when its variant is.
+ if hv, ok := variantHealth[l.VariantID]; ok {
+ l.Health = hv
+ } else {
+ l.Health = st.Health
+ }
+ continue
+ }
+ rel := relFromPlayPath(l.PlayPath)
+ if rel == "" {
+ continue
+ }
+ l.Health, l.PlaylistAgeS = h.playlistHealth(filepath.Join(www, rel), st.Health)
+ }
+ st.Links = links
+}
+
+// playlistHealth reports a playlist's health from its mtime. A missing file
+// while the stream is coming up is "starting", not "down".
+func (h *Handler) playlistHealth(path, streamHealth string) (string, float64) {
+ fi, err := os.Stat(path)
+ if err != nil {
+ if streamHealth == "ok" || streamHealth == "starting" {
+ return "starting", 0
+ }
+ return streamHealth, 0
+ }
+ age := time.Since(fi.ModTime()).Seconds()
+ if age > stalePlaylistS {
+ return "down", age
+ }
+ return "ok", age
+}
+
+// relFromPlayPath turns a /hls/... URL path back into a path relative to the
+// www root. It returns "" for anything that escapes that root.
+func relFromPlayPath(p string) string {
+ const prefix = "/hls/"
+ if !strings.HasPrefix(p, prefix) {
+ return ""
+ }
+ rel := strings.TrimPrefix(p, prefix)
+ // These paths are built by us, but treat them as untrusted anyway: a
+ // stream name is user input and must never climb out of www.
+ clean := filepath.Clean(filepath.FromSlash(rel))
+ if clean == "." || strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) {
+ return ""
+ }
+ for _, seg := range strings.Split(filepath.ToSlash(clean), "/") {
+ if seg == ".." {
+ return ""
+ }
+ }
+ return clean
+}
diff --git a/apps/streamd/internal/auth/auth.go b/apps/streamd/internal/auth/auth.go
new file mode 100644
index 0000000..bc79c1e
--- /dev/null
+++ b/apps/streamd/internal/auth/auth.go
@@ -0,0 +1,174 @@
+// Package auth provides accounts, sessions, API keys and role-based access
+// control for streamd. Password hashing uses crypto/pbkdf2 from the standard
+// library, so no third-party crypto dependency is needed.
+package auth
+
+import (
+ "crypto/pbkdf2"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/hex"
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// Role is an access level. Roles are ordered: viewer < operator < admin.
+type Role string
+
+const (
+ RoleViewer Role = "viewer"
+ RoleOperator Role = "operator"
+ RoleAdmin Role = "admin"
+)
+
+var roleRank = map[Role]int{
+ RoleViewer: 1,
+ RoleOperator: 2,
+ RoleAdmin: 3,
+}
+
+// ParseRole validates a role name, defaulting to viewer for anything unknown.
+func ParseRole(s string) (Role, error) {
+ r := Role(strings.ToLower(strings.TrimSpace(s)))
+ if _, ok := roleRank[r]; !ok {
+ return RoleViewer, fmt.Errorf("unknown role %q (want viewer, operator or admin)", s)
+ }
+ return r, nil
+}
+
+// AtLeast reports whether r grants everything min does.
+func (r Role) AtLeast(min Role) bool {
+ return roleRank[r] >= roleRank[min]
+}
+
+func (r Role) Valid() bool {
+ _, ok := roleRank[r]
+ return ok
+}
+
+// ActorKind distinguishes a logged-in human from a machine credential.
+type ActorKind string
+
+const (
+ ActorUser ActorKind = "user"
+ ActorAPIKey ActorKind = "apikey"
+ ActorSystem ActorKind = "system"
+)
+
+// Principal is the authenticated identity behind a request.
+type Principal struct {
+ Kind ActorKind
+ Role Role
+ // Name is the username or the API key's label, used for audit rows.
+ Name string
+ // UserID is set for session principals only.
+ UserID int64
+ // AgentID is the X-Agent-ID a machine caller volunteered, if any.
+ AgentID string
+ // SessionID is the raw session id for session principals (needed to
+ // resolve the CSRF token); empty for bearer principals.
+ SessionID string
+ // CSRFToken is the token a cookie-authenticated caller must echo back.
+ CSRFToken string
+}
+
+// Actor is the audit-log label for this principal.
+func (p *Principal) Actor() string {
+ if p == nil {
+ return "anonymous"
+ }
+ if p.AgentID != "" && p.Kind == ActorAPIKey {
+ return p.Name + "@" + p.AgentID
+ }
+ return p.Name
+}
+
+// NeedsCSRF is true for ambient (cookie) credentials only. A bearer token is
+// never sent automatically by a browser, so it carries no CSRF risk.
+func (p *Principal) NeedsCSRF() bool {
+ return p != nil && p.Kind == ActorUser && p.SessionID != ""
+}
+
+const (
+ pbkdf2Iterations = 600_000
+ pbkdf2KeyLen = 32
+ saltLen = 16
+ tokenLen = 32
+)
+
+// HashPassword returns an encoded PBKDF2-HMAC-SHA256 hash:
+//
+// pbkdf2-sha256$$$
+func HashPassword(password string) (string, error) {
+ if len(password) < 8 {
+ return "", fmt.Errorf("password must be at least 8 characters")
+ }
+ salt := make([]byte, saltLen)
+ if _, err := rand.Read(salt); err != nil {
+ return "", err
+ }
+ return hashWithSalt(password, salt, pbkdf2Iterations)
+}
+
+func hashWithSalt(password string, salt []byte, iters int) (string, error) {
+ dk, err := pbkdf2.Key(sha256.New, password, salt, iters, pbkdf2KeyLen)
+ if err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("pbkdf2-sha256$%d$%s$%s",
+ iters,
+ base64.RawStdEncoding.EncodeToString(salt),
+ base64.RawStdEncoding.EncodeToString(dk),
+ ), nil
+}
+
+// VerifyPassword checks a password against an encoded hash in constant time.
+// A malformed or empty hash always fails, and never panics.
+func VerifyPassword(encoded, password string) bool {
+ parts := strings.Split(encoded, "$")
+ if len(parts) != 4 || parts[0] != "pbkdf2-sha256" {
+ return false
+ }
+ iters, err := strconv.Atoi(parts[1])
+ if err != nil || iters <= 0 {
+ return false
+ }
+ salt, err := base64.RawStdEncoding.DecodeString(parts[2])
+ if err != nil {
+ return false
+ }
+ want, err := base64.RawStdEncoding.DecodeString(parts[3])
+ if err != nil || len(want) == 0 {
+ return false
+ }
+ got, err := pbkdf2.Key(sha256.New, password, salt, iters, len(want))
+ if err != nil {
+ return false
+ }
+ return subtle.ConstantTimeCompare(got, want) == 1
+}
+
+// NewToken returns a URL-safe random secret and its storage hash. Only the
+// hash is ever persisted, so a database leak does not yield usable credentials.
+func NewToken() (secret, hash string, err error) {
+ b := make([]byte, tokenLen)
+ if _, err := rand.Read(b); err != nil {
+ return "", "", err
+ }
+ secret = base64.RawURLEncoding.EncodeToString(b)
+ return secret, HashToken(secret), nil
+}
+
+// HashToken is the storage form of a session id or API key.
+func HashToken(secret string) string {
+ sum := sha256.Sum256([]byte(secret))
+ return hex.EncodeToString(sum[:])
+}
+
+// SecretEqual compares two secrets in constant time.
+func SecretEqual(a, b string) bool {
+ return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
+}
diff --git a/apps/streamd/internal/auth/auth_test.go b/apps/streamd/internal/auth/auth_test.go
new file mode 100644
index 0000000..cbe85b3
--- /dev/null
+++ b/apps/streamd/internal/auth/auth_test.go
@@ -0,0 +1,548 @@
+package auth
+
+import (
+ "database/sql"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "streamd/apps/streamd/internal/httpx"
+
+ _ "modernc.org/sqlite"
+)
+
+func TestHashPasswordRoundTrip(t *testing.T) {
+ h, err := HashPassword("correct horse battery")
+ if err != nil {
+ t.Fatalf("hash: %v", err)
+ }
+ if !VerifyPassword(h, "correct horse battery") {
+ t.Error("correct password rejected")
+ }
+ if VerifyPassword(h, "correct horse batterz") {
+ t.Error("wrong password accepted")
+ }
+ if VerifyPassword(h, "") {
+ t.Error("empty password accepted")
+ }
+ // Two hashes of the same password must differ (unique salt).
+ h2, _ := HashPassword("correct horse battery")
+ if h == h2 {
+ t.Error("salt is not random: identical hashes")
+ }
+}
+
+func TestHashPasswordRejectsShort(t *testing.T) {
+ if _, err := HashPassword("short"); err == nil {
+ t.Error("expected short password to be rejected")
+ }
+}
+
+func TestVerifyPasswordMalformed(t *testing.T) {
+ for _, bad := range []string{
+ "", "nonsense", "pbkdf2-sha256$", "pbkdf2-sha256$a$b$c",
+ "pbkdf2-sha256$0$c2FsdA$aGFzaA", "bcrypt$1$x$y",
+ "pbkdf2-sha256$1000$!!!$aGFzaA", "pbkdf2-sha256$1000$c2FsdA$",
+ } {
+ if VerifyPassword(bad, "anything") {
+ t.Errorf("malformed hash %q was accepted", bad)
+ }
+ }
+}
+
+func TestRoleOrdering(t *testing.T) {
+ if !RoleAdmin.AtLeast(RoleOperator) || !RoleAdmin.AtLeast(RoleViewer) {
+ t.Error("admin should outrank operator and viewer")
+ }
+ if RoleViewer.AtLeast(RoleOperator) {
+ t.Error("viewer must not satisfy operator")
+ }
+ if RoleOperator.AtLeast(RoleAdmin) {
+ t.Error("operator must not satisfy admin")
+ }
+ if !RoleViewer.AtLeast(RoleViewer) {
+ t.Error("a role should satisfy itself")
+ }
+ if _, err := ParseRole("root"); err == nil {
+ t.Error("unknown role should error")
+ }
+ if r, err := ParseRole(" ADMIN "); err != nil || r != RoleAdmin {
+ t.Errorf("ParseRole should normalise case and space, got %q %v", r, err)
+ }
+}
+
+func TestNewTokenHashing(t *testing.T) {
+ secret, hash, err := NewToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if secret == "" || hash == "" || secret == hash {
+ t.Fatalf("bad token/hash pair: %q %q", secret, hash)
+ }
+ if HashToken(secret) != hash {
+ t.Error("HashToken disagrees with NewToken")
+ }
+ s2, _, _ := NewToken()
+ if s2 == secret {
+ t.Error("tokens are not random")
+ }
+}
+
+func newTestStore(t *testing.T) *Store {
+ t.Helper()
+ // A private temp file rather than :memory:, because the real store runs
+ // with one connection against a file and we want the same semantics.
+ dsn := "file:" + t.TempDir() + "/auth_test.db?_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)"
+ db, err := sql.Open("sqlite", dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { _ = db.Close() })
+ s, err := New(db, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s
+}
+
+func TestUserLifecycle(t *testing.T) {
+ s := newTestStore(t)
+
+ if n, err := s.CountUsers(); err != nil || n != 0 {
+ t.Fatalf("fresh store should have no users, got %d %v", n, err)
+ }
+ u, err := s.CreateUser(" Alice ", "hunter2hunter2", RoleAdmin)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if u.Username != "alice" {
+ t.Errorf("username should be normalised, got %q", u.Username)
+ }
+ if _, err := s.CreateUser("alice", "otherpassword", RoleViewer); err == nil {
+ t.Error("duplicate username should be rejected")
+ }
+
+ if _, err := s.Authenticate("ALICE", "hunter2hunter2"); err != nil {
+ t.Errorf("login should succeed case-insensitively: %v", err)
+ }
+ if _, err := s.Authenticate("alice", "wrong"); err == nil {
+ t.Error("wrong password should fail")
+ }
+ if _, err := s.Authenticate("nobody", "whatever"); err == nil {
+ t.Error("unknown user should fail")
+ }
+
+ // Disabling blocks login.
+ dis := true
+ if _, err := s.UpdateUser(u.ID, nil, &dis); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Authenticate("alice", "hunter2hunter2"); err == nil {
+ t.Error("disabled account should not authenticate")
+ }
+}
+
+func TestSessionLifecycle(t *testing.T) {
+ s := newTestStore(t)
+ u, err := s.CreateUser("bob", "password1234", RoleOperator)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ secret, csrf, err := s.CreateSession(u.ID, time.Hour, "10.0.0.1", "test-agent")
+ if err != nil {
+ t.Fatal(err)
+ }
+ p, err := s.LookupSession(secret, time.Hour)
+ if err != nil {
+ t.Fatalf("lookup: %v", err)
+ }
+ if p.Name != "bob" || p.Role != RoleOperator || p.Kind != ActorUser {
+ t.Errorf("unexpected principal %+v", p)
+ }
+ if p.CSRFToken != csrf {
+ t.Error("CSRF token mismatch")
+ }
+ if !p.NeedsCSRF() {
+ t.Error("session principal must require CSRF")
+ }
+
+ // The raw secret must not be stored.
+ var count int
+ if err := s.DB.QueryRow(`SELECT COUNT(*) FROM sessions WHERE id_hash = ?`, secret).Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 0 {
+ t.Error("raw session secret found in the database")
+ }
+
+ if _, err := s.LookupSession("not-a-session", time.Hour); err == nil {
+ t.Error("bogus session should not resolve")
+ }
+
+ // Changing the password must revoke sessions.
+ if err := s.SetPassword(u.ID, "newpassword12"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.LookupSession(secret, time.Hour); err == nil {
+ t.Error("session should be revoked after a password change")
+ }
+}
+
+func TestSessionExpiry(t *testing.T) {
+ s := newTestStore(t)
+ u, _ := s.CreateUser("carol", "password1234", RoleViewer)
+ secret, _, err := s.CreateSession(u.ID, -time.Hour, "", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // CreateSession clamps a non-positive TTL to the default, so force the row
+ // into the past to exercise the expiry branch.
+ if _, err := s.DB.Exec(`UPDATE sessions SET expires_at = ?`,
+ time.Now().UTC().Add(-time.Minute).Format(time.RFC3339)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.LookupSession(secret, time.Hour); err == nil {
+ t.Error("expired session should not resolve")
+ }
+ if n, err := s.ExpireSessions(); err != nil {
+ t.Fatal(err)
+ } else if n < 0 {
+ t.Error("unexpected negative expiry count")
+ }
+}
+
+func TestAPIKeyLifecycle(t *testing.T) {
+ s := newTestStore(t)
+ k, err := s.CreateAPIKey("phone-agent", RoleOperator)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if k.Secret == "" {
+ t.Fatal("create must return the secret once")
+ }
+ p, err := s.LookupAPIKey(k.Secret)
+ if err != nil {
+ t.Fatalf("lookup: %v", err)
+ }
+ if p.Role != RoleOperator || p.Kind != ActorAPIKey || p.Name != "phone-agent" {
+ t.Errorf("unexpected principal %+v", p)
+ }
+ if p.NeedsCSRF() {
+ t.Error("bearer principals must be exempt from CSRF")
+ }
+
+ // Listing never exposes the secret.
+ list, err := s.ListAPIKeys()
+ if err != nil || len(list) != 1 {
+ t.Fatalf("list: %v %d", err, len(list))
+ }
+ if list[0].Secret != "" {
+ t.Error("list must not expose key secrets")
+ }
+
+ if err := s.RevokeAPIKey(k.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.LookupAPIKey(k.Secret); err == nil {
+ t.Error("revoked key should not authenticate")
+ }
+ if err := s.RevokeAPIKey(k.ID); err == nil {
+ t.Error("revoking twice should report not found")
+ }
+}
+
+func TestLegacyTokenActsAsAdminKey(t *testing.T) {
+ s := newTestStore(t)
+ s.LegacyToken = "SECRET-FROM-ENV"
+ p, err := s.LookupAPIKey("SECRET-FROM-ENV")
+ if err != nil {
+ t.Fatalf("legacy token should resolve: %v", err)
+ }
+ if p.Role != RoleAdmin {
+ t.Errorf("legacy token should be admin, got %q", p.Role)
+ }
+ if _, err := s.LookupAPIKey("SECRET-FROM-EN"); err == nil {
+ t.Error("near-miss token should not resolve")
+ }
+}
+
+func TestAuditBufferFlush(t *testing.T) {
+ s := newTestStore(t)
+ for i := 0; i < 5; i++ {
+ s.Audit(AuditEntry{Actor: "alice", ActorKind: ActorUser, Method: "POST",
+ Path: "/api/streams", Status: 200, Note: "created"})
+ }
+ // Nothing is written until a flush, by design — the DB has a single
+ // connection and must not be hit per request.
+ var n int
+ _ = s.DB.QueryRow(`SELECT COUNT(*) FROM audit_log`).Scan(&n)
+ if n != 0 {
+ t.Errorf("audit rows written before flush: %d", n)
+ }
+ if err := s.FlushAudit(); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.DB.QueryRow(`SELECT COUNT(*) FROM audit_log`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ if n != 5 {
+ t.Errorf("want 5 audit rows after flush, got %d", n)
+ }
+ list, err := s.ListAudit(10, "")
+ if err != nil || len(list) != 5 {
+ t.Fatalf("list audit: %v %d", err, len(list))
+ }
+ if list[0].Actor != "alice" {
+ t.Errorf("unexpected actor %q", list[0].Actor)
+ }
+}
+
+// ---------- middleware ----------
+
+func testMW(t *testing.T) (*Middleware, *Store) {
+ t.Helper()
+ s := newTestStore(t)
+ mw := NewMiddleware(s, httpx.Trust{}, false)
+ return mw, s
+}
+
+// probe is a handler that reports the principal the middleware attached.
+func probe(w http.ResponseWriter, r *http.Request) {
+ p := From(r)
+ if p == nil {
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("anonymous"))
+ return
+ }
+ _, _ = w.Write([]byte(p.Name + ":" + string(p.Role)))
+}
+
+func TestAttachResolvesBearer(t *testing.T) {
+ mw, s := testMW(t)
+ k, _ := s.CreateAPIKey("agent", RoleOperator)
+ h := mw.Attach(http.HandlerFunc(probe))
+
+ req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
+ req.Header.Set("Authorization", "Bearer "+k.Secret)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if got := rec.Body.String(); got != "agent:operator" {
+ t.Errorf("want agent:operator, got %q", got)
+ }
+
+ // X-Streamd-Token is still honoured.
+ req = httptest.NewRequest(http.MethodGet, "/api/streams", nil)
+ req.Header.Set("X-Streamd-Token", k.Secret)
+ rec = httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if got := rec.Body.String(); got != "agent:operator" {
+ t.Errorf("X-Streamd-Token: want agent:operator, got %q", got)
+ }
+}
+
+// The ?token= query parameter used to authenticate. It must not any more: it
+// leaked the shared secret into proxy access logs and Referer headers.
+func TestQueryTokenIsRejected(t *testing.T) {
+ mw, s := testMW(t)
+ k, _ := s.CreateAPIKey("agent", RoleOperator)
+ h := mw.Attach(http.HandlerFunc(probe))
+ req := httptest.NewRequest(http.MethodGet, "/api/streams?token="+k.Secret, nil)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if got := rec.Body.String(); got != "anonymous" {
+ t.Errorf("?token= must not authenticate, got %q", got)
+ }
+}
+
+func TestCSRFRequiredForCookieMutation(t *testing.T) {
+ mw, s := testMW(t)
+ u, _ := s.CreateUser("dave", "password1234", RoleOperator)
+ secret, csrf, err := s.CreateSession(u.ID, time.Hour, "", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ h := mw.Attach(http.HandlerFunc(probe))
+
+ // GET needs no CSRF.
+ req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Errorf("GET with cookie should pass, got %d", rec.Code)
+ }
+
+ // POST without the header is refused.
+ req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
+ rec = httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("POST without CSRF should be 403, got %d", rec.Code)
+ }
+
+ // POST with a wrong header is refused.
+ req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
+ req.Header.Set(CSRFHeader, "wrong")
+ rec = httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("POST with bad CSRF should be 403, got %d", rec.Code)
+ }
+
+ // POST with the right header passes.
+ req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
+ req.Header.Set(CSRFHeader, csrf)
+ rec = httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Errorf("POST with valid CSRF should pass, got %d: %s", rec.Code, rec.Body.String())
+ }
+}
+
+func TestCSRFNotRequiredForBearerMutation(t *testing.T) {
+ mw, s := testMW(t)
+ k, _ := s.CreateAPIKey("agent", RoleOperator)
+ h := mw.Attach(http.HandlerFunc(probe))
+ req := httptest.NewRequest(http.MethodPost, "/api/streams/1/credentials", nil)
+ req.Header.Set("Authorization", "Bearer "+k.Secret)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Errorf("bearer POST should not need CSRF, got %d: %s", rec.Code, rec.Body.String())
+ }
+}
+
+func TestGuardRoles(t *testing.T) {
+ mw, s := testMW(t)
+ k, _ := s.CreateAPIKey("viewer-key", RoleViewer)
+
+ guarded := mw.Attach(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if _, ok := Guard(w, r, RoleOperator); !ok {
+ return
+ }
+ _, _ = w.Write([]byte("allowed"))
+ }))
+
+ // Anonymous → 401.
+ rec := httptest.NewRecorder()
+ guarded.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/streams", nil))
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("anonymous should be 401, got %d", rec.Code)
+ }
+
+ // Under-privileged → 403.
+ req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
+ req.Header.Set("Authorization", "Bearer "+k.Secret)
+ rec = httptest.NewRecorder()
+ guarded.ServeHTTP(rec, req)
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("viewer should be 403 for operator route, got %d", rec.Code)
+ }
+}
+
+func TestLoginThrottleLocksOut(t *testing.T) {
+ mw, s := testMW(t)
+ if _, err := s.CreateUser("erin", "password1234", RoleAdmin); err != nil {
+ t.Fatal(err)
+ }
+ h := NewHandler(s, mw, nil)
+ mux := http.NewServeMux()
+ h.Mount(mux)
+ srv := mw.Attach(mux)
+
+ post := func(body string) int {
+ req := httptest.NewRequest(http.MethodPost, "/api/login", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.RemoteAddr = "203.0.113.9:1234"
+ rec := httptest.NewRecorder()
+ srv.ServeHTTP(rec, req)
+ return rec.Code
+ }
+
+ sawLockout := false
+ for i := 0; i < 12; i++ {
+ if post(`{"username":"erin","password":"wrong"}`) == http.StatusTooManyRequests {
+ sawLockout = true
+ break
+ }
+ }
+ if !sawLockout {
+ t.Error("repeated bad logins should eventually be throttled")
+ }
+ // And the lockout applies to the correct password too, so guessing cannot
+ // be continued by getting lucky.
+ if code := post(`{"username":"erin","password":"password1234"}`); code != http.StatusTooManyRequests {
+ t.Errorf("throttle should also hold off a correct password, got %d", code)
+ }
+}
+
+func TestLoginSucceedsAndSetsCookies(t *testing.T) {
+ mw, s := testMW(t)
+ if _, err := s.CreateUser("frank", "password1234", RoleAdmin); err != nil {
+ t.Fatal(err)
+ }
+ h := NewHandler(s, mw, nil)
+ mux := http.NewServeMux()
+ h.Mount(mux)
+ srv := mw.Attach(mux)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/login", strings.NewReader(`{"username":"frank","password":"password1234"}`))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ srv.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("login failed: %d %s", rec.Code, rec.Body.String())
+ }
+ var sessionCookie, csrfCookie *http.Cookie
+ for _, c := range rec.Result().Cookies() {
+ switch c.Name {
+ case SessionCookie:
+ sessionCookie = c
+ case CSRFCookie:
+ csrfCookie = c
+ }
+ }
+ if sessionCookie == nil || csrfCookie == nil {
+ t.Fatal("login must set both cookies")
+ }
+ if !sessionCookie.HttpOnly {
+ t.Error("session cookie must be HttpOnly")
+ }
+ if csrfCookie.HttpOnly {
+ t.Error("CSRF cookie must be readable by the page script")
+ }
+ if sessionCookie.SameSite != http.SameSiteLaxMode {
+ t.Error("session cookie should be SameSite=Lax")
+ }
+}
+
+func TestLimiterRefills(t *testing.T) {
+ l := NewLimiter(2, 100) // 2 burst, refills fast
+ if !l.Allow("k") || !l.Allow("k") {
+ t.Fatal("burst should allow two")
+ }
+ if l.Allow("k") {
+ t.Error("third call should be denied immediately")
+ }
+ time.Sleep(50 * time.Millisecond)
+ if !l.Allow("k") {
+ t.Error("bucket should refill")
+ }
+ // Distinct keys are independent.
+ if !l.Allow("other") {
+ t.Error("a different key should have its own bucket")
+ }
+ // Empty key is never limited (used for "no IP known").
+ for i := 0; i < 10; i++ {
+ if !l.Allow("") {
+ t.Fatal("empty key should not be limited")
+ }
+ }
+}
diff --git a/apps/streamd/internal/auth/handlers.go b/apps/streamd/internal/auth/handlers.go
new file mode 100644
index 0000000..a86d412
--- /dev/null
+++ b/apps/streamd/internal/auth/handlers.go
@@ -0,0 +1,586 @@
+package auth
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "streamd/apps/streamd/internal/httpx"
+)
+
+// Handler serves the auth routes: login/logout/me, user administration, API
+// keys and the audit log.
+type Handler struct {
+ Store *Store
+ MW *Middleware
+ Log *slog.Logger
+
+ mu sync.Mutex
+ // setupToken gates creation of the very first admin account. It is
+ // generated at startup when the users table is empty and cleared the
+ // moment an account exists.
+ setupToken string
+}
+
+func NewHandler(store *Store, mw *Middleware, lg *slog.Logger) *Handler {
+ if lg == nil {
+ lg = slog.Default()
+ }
+ return &Handler{Store: store, MW: mw, Log: lg}
+}
+
+// SetSetupToken installs the first-run token. Pass "" to disable setup.
+func (h *Handler) SetSetupToken(tok string) {
+ h.mu.Lock()
+ h.setupToken = tok
+ h.mu.Unlock()
+}
+
+func (h *Handler) currentSetupToken() string {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.setupToken
+}
+
+// NeedsSetup reports whether no account exists yet.
+func (h *Handler) NeedsSetup() bool {
+ n, err := h.Store.CountUsers()
+ return err == nil && n == 0
+}
+
+func (h *Handler) Mount(mux *http.ServeMux) {
+ mux.HandleFunc("/api/login", h.login)
+ mux.HandleFunc("/api/logout", h.logout)
+ mux.HandleFunc("/api/me", h.me)
+ mux.HandleFunc("/api/setup", h.setup)
+ mux.HandleFunc("/api/users", h.users)
+ mux.HandleFunc("/api/users/", h.userByID)
+ mux.HandleFunc("/api/apikeys", h.apiKeys)
+ mux.HandleFunc("/api/apikeys/", h.apiKeyByID)
+ mux.HandleFunc("/api/audit", h.audit)
+}
+
+// ---------- session routes ----------
+
+func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ var in struct {
+ Username string `json:"username"`
+ Password string `json:"password"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ ip := h.MW.Trust.ClientIP(r)
+ user := normalizeUsername(in.Username)
+ // Two buckets: one per source address, one per account, so neither a
+ // single host nor a single account can be hammered.
+ keys := []string{"ip:" + ip, "user:" + user}
+ for _, k := range keys {
+ if !h.MW.LoginLimiter.Allow(k) {
+ retry := h.MW.LoginLimiter.RetryAfter(k)
+ w.Header().Set("Retry-After", strconv.Itoa(max(retry, 1)))
+ h.Store.Audit(AuditEntry{Actor: user, ActorKind: ActorUser, IP: ip,
+ Method: r.Method, Path: r.URL.Path, Status: http.StatusTooManyRequests,
+ Note: "login throttled"})
+ writeErr(w, http.StatusTooManyRequests, "too many login attempts — wait and try again")
+ return
+ }
+ }
+
+ u, err := h.Store.Authenticate(in.Username, in.Password)
+ if err != nil {
+ // Burn extra budget on a failure so guessing is expensive.
+ for _, k := range keys {
+ h.MW.LoginLimiter.Penalise(k, 2)
+ }
+ h.Store.Audit(AuditEntry{Actor: user, ActorKind: ActorUser, IP: ip,
+ Method: r.Method, Path: r.URL.Path, Status: http.StatusUnauthorized,
+ Note: "login failed"})
+ h.Log.Info("login failed", "user", user, "ip", ip)
+ writeErr(w, http.StatusUnauthorized, "invalid username or password")
+ return
+ }
+
+ secret, csrf, err := h.Store.CreateSession(u.ID, h.MW.SessionTTL, ip, r.UserAgent())
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ for _, k := range keys {
+ h.MW.LoginLimiter.Reset(k)
+ }
+ h.MW.SetSessionCookies(w, r, secret, csrf)
+ h.Store.Audit(AuditEntry{Actor: u.Username, ActorKind: ActorUser, IP: ip,
+ Method: r.Method, Path: r.URL.Path, Status: http.StatusOK, Note: "login ok"})
+ h.Log.Info("login", "user", u.Username, "role", string(u.Role), "ip", ip)
+ writeJSON(w, http.StatusOK, map[string]any{"user": u, "csrf_token": csrf})
+}
+
+func (h *Handler) logout(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ if secret := SessionSecret(r); secret != "" {
+ _ = h.Store.DeleteSession(secret)
+ }
+ h.MW.ClearSessionCookies(w, r)
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+// me is the agent's and the dashboard's credential preflight: it says who you
+// are, or 401s clearly if your credential is bad or revoked.
+func (h *Handler) me(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ p := From(r)
+ if p == nil {
+ resp := map[string]any{"error": "authentication required"}
+ if h.NeedsSetup() {
+ resp["needs_setup"] = true
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusUnauthorized)
+ _ = json.NewEncoder(w).Encode(resp)
+ return
+ }
+ out := map[string]any{
+ "name": p.Name,
+ "role": string(p.Role),
+ "actor_kind": string(p.Kind),
+ }
+ if p.Kind == ActorUser {
+ out["user_id"] = p.UserID
+ out["csrf_token"] = p.CSRFToken
+ }
+ if p.AgentID != "" {
+ out["agent_id"] = p.AgentID
+ }
+ writeJSON(w, http.StatusOK, out)
+}
+
+// setup creates the first admin account, gated by the one-time token printed
+// to the server log at startup.
+func (h *Handler) setup(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ writeJSON(w, http.StatusOK, map[string]any{"needs_setup": h.NeedsSetup()})
+ case http.MethodPost:
+ if !h.NeedsSetup() {
+ writeErr(w, http.StatusConflict, "setup already complete")
+ return
+ }
+ tok := h.currentSetupToken()
+ if tok == "" {
+ writeErr(w, http.StatusForbidden, "setup is disabled on this server")
+ return
+ }
+ var in struct {
+ SetupToken string `json:"setup_token"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ ip := h.MW.Trust.ClientIP(r)
+ if !h.MW.LoginLimiter.Allow("setup:" + ip) {
+ writeErr(w, http.StatusTooManyRequests, "too many attempts")
+ return
+ }
+ if !SecretEqual(strings.TrimSpace(in.SetupToken), tok) {
+ h.MW.LoginLimiter.Penalise("setup:"+ip, 3)
+ writeErr(w, http.StatusForbidden, "invalid setup token — see the streamd startup log")
+ return
+ }
+ u, err := h.Store.CreateUser(in.Username, in.Password, RoleAdmin)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.SetSetupToken("")
+ secret, csrf, err := h.Store.CreateSession(u.ID, h.MW.SessionTTL, ip, r.UserAgent())
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ h.MW.SetSessionCookies(w, r, secret, csrf)
+ h.Store.Audit(AuditEntry{Actor: u.Username, ActorKind: ActorUser, IP: ip,
+ Method: r.Method, Path: r.URL.Path, Status: http.StatusCreated,
+ Note: "first admin created"})
+ h.Log.Info("first admin account created", "user", u.Username)
+ writeJSON(w, http.StatusCreated, map[string]any{"user": u, "csrf_token": csrf})
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// ---------- users ----------
+
+func (h *Handler) users(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ if _, ok := Guard(w, r, RoleAdmin); !ok {
+ return
+ }
+ list, err := h.Store.ListUsers()
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"users": list})
+ case http.MethodPost:
+ p, ok := Guard(w, r, RoleAdmin)
+ if !ok {
+ return
+ }
+ var in struct {
+ Username string `json:"username"`
+ Password string `json:"password"`
+ Role string `json:"role"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ role, err := ParseRole(in.Role)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ u, err := h.Store.CreateUser(in.Username, in.Password, role)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.auditAction(r, p, http.StatusCreated, "created user "+u.Username+" as "+string(u.Role))
+ writeJSON(w, http.StatusCreated, u)
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+func (h *Handler) userByID(w http.ResponseWriter, r *http.Request) {
+ rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/users/"), "/")
+ if rest == "" {
+ h.users(w, r)
+ return
+ }
+ parts := strings.Split(rest, "/")
+ id, err := strconv.ParseInt(parts[0], 10, 64)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, "invalid user id")
+ return
+ }
+ action := ""
+ if len(parts) > 1 {
+ action = parts[1]
+ }
+
+ // Changing your own password needs only a valid session; everything else
+ // about an account is admin-only.
+ if action == "password" && r.Method == http.MethodPost {
+ p := From(r)
+ if p == nil {
+ writeErr(w, http.StatusUnauthorized, "authentication required")
+ return
+ }
+ self := p.Kind == ActorUser && p.UserID == id
+ if !self && !p.Role.AtLeast(RoleAdmin) {
+ writeErr(w, http.StatusForbidden, "only an admin can change another account's password")
+ return
+ }
+ var in struct {
+ Current string `json:"current_password"`
+ Password string `json:"password"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ // A user changing their own password must prove they know the old one,
+ // so a stolen session cannot be made permanent.
+ if self {
+ if _, err := h.Store.Authenticate(p.Name, in.Current); err != nil {
+ writeErr(w, http.StatusForbidden, "current password is incorrect")
+ return
+ }
+ }
+ if err := h.Store.SetPassword(id, in.Password); err != nil {
+ if errors.Is(err, ErrNotFound) {
+ writeErr(w, http.StatusNotFound, "user not found")
+ return
+ }
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.auditAction(r, p, http.StatusOK, "password changed for user id "+parts[0])
+ // Every session for that user was dropped, including this one if it
+ // was their own, so the dashboard must log in again.
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true, "sessions_revoked": true})
+ return
+ }
+
+ p, ok := Guard(w, r, RoleAdmin)
+ if !ok {
+ return
+ }
+
+ switch {
+ case action == "" && r.Method == http.MethodGet:
+ u, err := h.Store.GetUser(id)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, "user not found")
+ return
+ }
+ writeJSON(w, http.StatusOK, u)
+
+ case action == "" && (r.Method == http.MethodPatch || r.Method == http.MethodPut):
+ var in struct {
+ Role *string `json:"role"`
+ Disabled *bool `json:"disabled"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ var role *Role
+ if in.Role != nil {
+ rr, err := ParseRole(*in.Role)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ role = &rr
+ }
+ // Refuse to strand the installation with no usable admin.
+ demoting := role != nil && *role != RoleAdmin
+ disabling := in.Disabled != nil && *in.Disabled
+ if demoting || disabling {
+ if err := h.ensureAnotherAdmin(id); err != nil {
+ writeErr(w, http.StatusConflict, err.Error())
+ return
+ }
+ }
+ u, err := h.Store.UpdateUser(id, role, in.Disabled)
+ if err != nil {
+ if errors.Is(err, ErrNotFound) {
+ writeErr(w, http.StatusNotFound, "user not found")
+ return
+ }
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.auditAction(r, p, http.StatusOK, "updated user "+u.Username)
+ writeJSON(w, http.StatusOK, u)
+
+ case action == "" && r.Method == http.MethodDelete:
+ if err := h.ensureAnotherAdmin(id); err != nil {
+ writeErr(w, http.StatusConflict, err.Error())
+ return
+ }
+ if err := h.Store.DeleteUser(id); err != nil {
+ if errors.Is(err, ErrNotFound) {
+ writeErr(w, http.StatusNotFound, "user not found")
+ return
+ }
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ h.auditAction(r, p, http.StatusOK, "deleted user id "+parts[0])
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+
+ default:
+ writeErr(w, http.StatusNotFound, "not found")
+ }
+}
+
+// ensureAnotherAdmin fails when id is the last enabled admin.
+func (h *Handler) ensureAnotherAdmin(id int64) error {
+ u, err := h.Store.GetUser(id)
+ if err != nil {
+ return nil // let the caller's own lookup report "not found"
+ }
+ if u.Role != RoleAdmin || u.Disabled {
+ return nil
+ }
+ n, err := h.Store.CountOtherAdmins(id)
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return errors.New("this is the last enabled admin — promote another account first")
+ }
+ return nil
+}
+
+// ---------- api keys ----------
+
+func (h *Handler) apiKeys(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ if _, ok := Guard(w, r, RoleAdmin); !ok {
+ return
+ }
+ list, err := h.Store.ListAPIKeys()
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"api_keys": list})
+ case http.MethodPost:
+ p, ok := Guard(w, r, RoleAdmin)
+ if !ok {
+ return
+ }
+ var in struct {
+ Name string `json:"name"`
+ Role string `json:"role"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if strings.TrimSpace(in.Role) == "" {
+ in.Role = string(RoleOperator)
+ }
+ role, err := ParseRole(in.Role)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ k, err := h.Store.CreateAPIKey(in.Name, role)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.auditAction(r, p, http.StatusCreated, "created api key "+k.Name+" as "+string(k.Role))
+ h.Log.Info("api key created", "name", k.Name, "role", string(k.Role), "by", p.Actor())
+ // The secret appears in this response only, and is never stored.
+ writeJSON(w, http.StatusCreated, k)
+ default:
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+func (h *Handler) apiKeyByID(w http.ResponseWriter, r *http.Request) {
+ rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/apikeys/"), "/")
+ if rest == "" {
+ h.apiKeys(w, r)
+ return
+ }
+ id, err := strconv.ParseInt(strings.Split(rest, "/")[0], 10, 64)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, "invalid key id")
+ return
+ }
+ p, ok := Guard(w, r, RoleAdmin)
+ if !ok {
+ return
+ }
+ if r.Method != http.MethodDelete {
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ if err := h.Store.RevokeAPIKey(id); err != nil {
+ if errors.Is(err, ErrNotFound) {
+ writeErr(w, http.StatusNotFound, "key not found or already revoked")
+ return
+ }
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ h.auditAction(r, p, http.StatusOK, "revoked api key id "+rest)
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+// ---------- audit ----------
+
+func (h *Handler) audit(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ if _, ok := Guard(w, r, RoleAdmin); !ok {
+ return
+ }
+ // Flush first so the caller sees their own just-made changes.
+ _ = h.Store.FlushAudit()
+ limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
+ list, err := h.Store.ListAudit(limit, r.URL.Query().Get("actor"))
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"audit": list})
+}
+
+// AuditRequest records one mutating request against the calling principal.
+func (s *Store) AuditRequest(p *Principal, trust httpx.Trust, r *http.Request, status int, note string) {
+ kind := ActorKind("")
+ if p != nil {
+ kind = p.Kind
+ }
+ s.Audit(AuditEntry{
+ Actor: p.Actor(),
+ ActorKind: kind,
+ IP: trust.ClientIP(r),
+ Method: r.Method,
+ Path: r.URL.Path,
+ Status: status,
+ Note: note,
+ })
+}
+
+func (h *Handler) auditAction(r *http.Request, p *Principal, status int, note string) {
+ h.Store.AuditRequest(p, h.MW.Trust, r, status, note)
+}
+
+// ---------- helpers ----------
+
+func readJSON(r *http.Request, dst any) error {
+ defer r.Body.Close()
+ b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
+ if err != nil {
+ return err
+ }
+ if len(b) == 0 {
+ return errors.New("empty body")
+ }
+ return json.Unmarshal(b, dst)
+}
+
+func writeJSON(w http.ResponseWriter, code int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(code)
+ enc := json.NewEncoder(w)
+ enc.SetIndent("", " ")
+ _ = enc.Encode(v)
+}
+
+func writeErr(w http.ResponseWriter, code int, msg string) {
+ writeJSON(w, code, map[string]any{"error": msg})
+}
+
+// NewSetupToken makes the one-time first-run token.
+func NewSetupToken() string {
+ secret, _, err := NewToken()
+ if err != nil {
+ return "setup-" + strconv.FormatInt(time.Now().UnixNano(), 36)
+ }
+ return secret
+}
diff --git a/apps/streamd/internal/auth/middleware.go b/apps/streamd/internal/auth/middleware.go
new file mode 100644
index 0000000..8d84625
--- /dev/null
+++ b/apps/streamd/internal/auth/middleware.go
@@ -0,0 +1,238 @@
+package auth
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "streamd/apps/streamd/internal/httpx"
+)
+
+const (
+ // SessionCookie holds the session secret. HttpOnly, so page scripts
+ // cannot read it.
+ SessionCookie = "streamd_session"
+ // CSRFCookie mirrors the session's CSRF token for the double-submit
+ // check. Deliberately readable by scripts.
+ CSRFCookie = "streamd_csrf"
+ // CSRFHeader is where the dashboard echoes the token back.
+ CSRFHeader = "X-CSRF-Token"
+)
+
+type ctxKey int
+
+const principalKey ctxKey = 1
+
+// Middleware resolves the principal for each request, enforces CSRF on
+// cookie-authenticated mutations, and rate-limits the API.
+type Middleware struct {
+ Store *Store
+ SessionTTL time.Duration
+ Trust httpx.Trust
+ // CookieSecure forces the Secure attribute even when the request itself
+ // arrived over plain HTTP (the usual case behind a TLS-terminating proxy
+ // that does not set X-Forwarded-Proto).
+ CookieSecure bool
+
+ // APILimiter throttles mutating API calls per client IP.
+ APILimiter *Limiter
+ // LoginLimiter throttles login attempts per IP and per username.
+ LoginLimiter *Limiter
+}
+
+func NewMiddleware(store *Store, trust httpx.Trust, cookieSecure bool) *Middleware {
+ return &Middleware{
+ Store: store,
+ SessionTTL: DefaultSessionTTL,
+ Trust: trust,
+ CookieSecure: cookieSecure,
+ APILimiter: NewLimiter(120, 20),
+ LoginLimiter: NewLimiter(8, 0.2),
+ }
+}
+
+// From returns the principal attached by Attach, or nil when the caller is
+// anonymous.
+func From(r *http.Request) *Principal {
+ p, _ := r.Context().Value(principalKey).(*Principal)
+ return p
+}
+
+// WithPrincipal is exported for tests and for internal callers that need to
+// synthesise an identity.
+func WithPrincipal(ctx context.Context, p *Principal) context.Context {
+ return context.WithValue(ctx, principalKey, p)
+}
+
+// Attach resolves the principal and stores it on the request context. It does
+// not reject anonymous callers — individual routes decide that via Guard — so
+// that the login page and the public media paths keep working.
+func (m *Middleware) Attach(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ p := m.resolve(r)
+ if p != nil {
+ r = r.WithContext(WithPrincipal(r.Context(), p))
+ }
+
+ if isUnsafe(r.Method) {
+ ip := m.Trust.ClientIP(r)
+ // Rate-limit mutations per client. Login has its own tighter
+ // limiter applied in the handler.
+ if strings.HasPrefix(r.URL.Path, "/api/") && !m.APILimiter.Allow(ip) {
+ retry := m.APILimiter.RetryAfter(ip)
+ w.Header().Set("Retry-After", strconv.Itoa(max(retry, 1)))
+ writeJSONError(w, http.StatusTooManyRequests, "too many requests")
+ return
+ }
+ // CSRF applies only to ambient cookie credentials. A bearer token
+ // is never attached automatically by a browser.
+ if p.NeedsCSRF() && !m.csrfOK(r, p) {
+ writeJSONError(w, http.StatusForbidden, "missing or invalid "+CSRFHeader)
+ return
+ }
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func (m *Middleware) resolve(r *http.Request) *Principal {
+ // 1. Session cookie.
+ if c, err := r.Cookie(SessionCookie); err == nil && c.Value != "" {
+ if p, err := m.Store.LookupSession(c.Value, m.SessionTTL); err == nil {
+ return p
+ }
+ }
+ // 2. Bearer token / X-Streamd-Token. Note there is deliberately no
+ // ?token= fallback any more: it leaked the secret into access logs and
+ // referrers. Agents send the header already.
+ secret := bearer(r)
+ if secret == "" {
+ return nil
+ }
+ p, err := m.Store.LookupAPIKey(secret)
+ if err != nil {
+ return nil
+ }
+ p.AgentID = sanitiseAgentID(r.Header.Get("X-Agent-ID"))
+ return p
+}
+
+func bearer(r *http.Request) string {
+ if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" {
+ if len(auth) > 7 && strings.EqualFold(auth[:7], "bearer ") {
+ return strings.TrimSpace(auth[7:])
+ }
+ }
+ return strings.TrimSpace(r.Header.Get("X-Streamd-Token"))
+}
+
+// sanitiseAgentID keeps a volunteered agent label printable and bounded before
+// it reaches an audit row.
+func sanitiseAgentID(s string) string {
+ s = strings.TrimSpace(s)
+ if len(s) > 64 {
+ s = s[:64]
+ }
+ var b strings.Builder
+ for _, r := range s {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9',
+ r == '-', r == '_', r == '.':
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+func (m *Middleware) csrfOK(r *http.Request, p *Principal) bool {
+ sent := strings.TrimSpace(r.Header.Get(CSRFHeader))
+ if sent == "" {
+ return false
+ }
+ return SecretEqual(sent, p.CSRFToken)
+}
+
+func isUnsafe(method string) bool {
+ switch method {
+ case http.MethodGet, http.MethodHead, http.MethodOptions:
+ return false
+ }
+ return true
+}
+
+// Guard enforces a minimum role, writing the error response itself. It returns
+// the principal and false when the request must not proceed.
+func Guard(w http.ResponseWriter, r *http.Request, min Role) (*Principal, bool) {
+ p := From(r)
+ if p == nil {
+ w.Header().Set("WWW-Authenticate", `Bearer realm="streamd"`)
+ writeJSONError(w, http.StatusUnauthorized, "authentication required")
+ return nil, false
+ }
+ if !p.Role.AtLeast(min) {
+ writeJSONError(w, http.StatusForbidden, "role "+string(p.Role)+" cannot perform this action (needs "+string(min)+")")
+ return nil, false
+ }
+ return p, true
+}
+
+// SetSessionCookies issues the session and CSRF cookies after a login.
+func (m *Middleware) SetSessionCookies(w http.ResponseWriter, r *http.Request, secret, csrf string) {
+ secure := m.CookieSecure || m.Trust.IsHTTPS(r)
+ maxAge := int(m.SessionTTL.Seconds())
+ if maxAge <= 0 {
+ maxAge = int(DefaultSessionTTL.Seconds())
+ }
+ http.SetCookie(w, &http.Cookie{
+ Name: SessionCookie,
+ Value: secret,
+ Path: "/",
+ HttpOnly: true,
+ Secure: secure,
+ SameSite: http.SameSiteLaxMode,
+ MaxAge: maxAge,
+ })
+ http.SetCookie(w, &http.Cookie{
+ Name: CSRFCookie,
+ Value: csrf,
+ Path: "/",
+ // Readable on purpose: the dashboard copies it into X-CSRF-Token.
+ HttpOnly: false,
+ Secure: secure,
+ SameSite: http.SameSiteLaxMode,
+ MaxAge: maxAge,
+ })
+}
+
+// ClearSessionCookies expires both cookies on logout.
+func (m *Middleware) ClearSessionCookies(w http.ResponseWriter, r *http.Request) {
+ secure := m.CookieSecure || m.Trust.IsHTTPS(r)
+ for _, name := range []string{SessionCookie, CSRFCookie} {
+ http.SetCookie(w, &http.Cookie{
+ Name: name,
+ Value: "",
+ Path: "/",
+ HttpOnly: name == SessionCookie,
+ Secure: secure,
+ SameSite: http.SameSiteLaxMode,
+ MaxAge: -1,
+ })
+ }
+}
+
+// SessionSecret returns the raw session cookie value, for logout.
+func SessionSecret(r *http.Request) string {
+ if c, err := r.Cookie(SessionCookie); err == nil {
+ return c.Value
+ }
+ return ""
+}
+
+func writeJSONError(w http.ResponseWriter, code int, msg string) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(code)
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": msg})
+}
diff --git a/apps/streamd/internal/auth/ratelimit.go b/apps/streamd/internal/auth/ratelimit.go
new file mode 100644
index 0000000..5b2aa0b
--- /dev/null
+++ b/apps/streamd/internal/auth/ratelimit.go
@@ -0,0 +1,140 @@
+package auth
+
+import (
+ "sync"
+ "time"
+)
+
+// Limiter is a keyed token bucket. Keys are usually a client IP, or an
+// IP+username pair for login attempts.
+type Limiter struct {
+ // Burst is the bucket capacity.
+ Burst float64
+ // PerSecond is the refill rate.
+ PerSecond float64
+
+ mu sync.Mutex
+ buckets map[string]*bucket
+ lastGC time.Time
+}
+
+type bucket struct {
+ tokens float64
+ seen time.Time
+}
+
+func NewLimiter(burst, perSecond float64) *Limiter {
+ if burst <= 0 {
+ burst = 1
+ }
+ if perSecond <= 0 {
+ perSecond = 1
+ }
+ return &Limiter{
+ Burst: burst,
+ PerSecond: perSecond,
+ buckets: map[string]*bucket{},
+ lastGC: time.Now(),
+ }
+}
+
+// Allow consumes a token for key, reporting whether the request may proceed.
+func (l *Limiter) Allow(key string) bool {
+ return l.AllowN(key, 1)
+}
+
+// AllowN consumes n tokens, for operations that should cost more than one.
+func (l *Limiter) AllowN(key string, n float64) bool {
+ if l == nil || key == "" {
+ return true
+ }
+ nowT := time.Now()
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.gcLocked(nowT)
+
+ b, ok := l.buckets[key]
+ if !ok {
+ b = &bucket{tokens: l.Burst, seen: nowT}
+ l.buckets[key] = b
+ }
+ // Refill for the elapsed time, capped at Burst.
+ elapsed := nowT.Sub(b.seen).Seconds()
+ if elapsed > 0 {
+ b.tokens += elapsed * l.PerSecond
+ if b.tokens > l.Burst {
+ b.tokens = l.Burst
+ }
+ }
+ b.seen = nowT
+ if b.tokens < n {
+ return false
+ }
+ b.tokens -= n
+ return true
+}
+
+// Penalise drains a bucket so repeated failures cost more than one attempt.
+func (l *Limiter) Penalise(key string, tokens float64) {
+ if l == nil || key == "" {
+ return
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ b, ok := l.buckets[key]
+ if !ok {
+ b = &bucket{tokens: l.Burst, seen: time.Now()}
+ l.buckets[key] = b
+ }
+ b.tokens -= tokens
+ if b.tokens < -l.Burst {
+ b.tokens = -l.Burst
+ }
+}
+
+// Reset clears a key, used after a successful login.
+func (l *Limiter) Reset(key string) {
+ if l == nil || key == "" {
+ return
+ }
+ l.mu.Lock()
+ delete(l.buckets, key)
+ l.mu.Unlock()
+}
+
+// RetryAfter estimates the seconds until key has a token again.
+func (l *Limiter) RetryAfter(key string) int {
+ if l == nil {
+ return 0
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ b, ok := l.buckets[key]
+ if !ok || b.tokens >= 1 {
+ return 0
+ }
+ need := 1 - b.tokens
+ secs := int(need/l.PerSecond) + 1
+ if secs < 1 {
+ secs = 1
+ }
+ return secs
+}
+
+// gcLocked drops idle buckets so the map cannot grow without bound under a
+// spray of distinct source addresses.
+func (l *Limiter) gcLocked(nowT time.Time) {
+ if nowT.Sub(l.lastGC) < time.Minute {
+ return
+ }
+ l.lastGC = nowT
+ idle := time.Duration(float64(time.Second) * (2 * l.Burst / l.PerSecond))
+ if idle < 5*time.Minute {
+ idle = 5 * time.Minute
+ }
+ for k, b := range l.buckets {
+ if nowT.Sub(b.seen) > idle {
+ delete(l.buckets, k)
+ }
+ }
+}
diff --git a/apps/streamd/internal/auth/store.go b/apps/streamd/internal/auth/store.go
new file mode 100644
index 0000000..bcb0350
--- /dev/null
+++ b/apps/streamd/internal/auth/store.go
@@ -0,0 +1,639 @@
+package auth
+
+import (
+ "database/sql"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+)
+
+// DefaultSessionTTL is how long a login lasts without activity.
+const DefaultSessionTTL = 12 * time.Hour
+
+// ErrNotFound is returned when a user, key or session does not exist.
+var ErrNotFound = errors.New("not found")
+
+// Store owns the auth tables. It shares streamd's single *sql.DB, so every
+// write here serialises with the stream writes — audit rows and key
+// last-used stamps are therefore buffered rather than written per request.
+type Store struct {
+ DB *sql.DB
+
+ // LegacyToken keeps --token / STREAMD_TOKEN working as an implicit admin
+ // API key so existing agents and scripts do not break.
+ LegacyToken string
+
+ mu sync.Mutex
+ // auditBuf accumulates rows between flushes.
+ auditBuf []AuditEntry
+ // keyTouch throttles api_keys.last_used_at writes to one per minute.
+ keyTouch map[int64]time.Time
+}
+
+type User struct {
+ ID int64 `json:"id"`
+ Username string `json:"username"`
+ Role Role `json:"role"`
+ Disabled bool `json:"disabled"`
+ CreatedAt string `json:"created_at"`
+ LastLoginAt string `json:"last_login_at,omitempty"`
+}
+
+type APIKey struct {
+ ID int64 `json:"id"`
+ Name string `json:"name"`
+ Role Role `json:"role"`
+ CreatedAt string `json:"created_at"`
+ LastUsedAt string `json:"last_used_at,omitempty"`
+ RevokedAt string `json:"revoked_at,omitempty"`
+ // Secret is populated only in the response that creates the key; it is
+ // never stored and never shown again.
+ Secret string `json:"secret,omitempty"`
+}
+
+type AuditEntry struct {
+ ID int64 `json:"id"`
+ At string `json:"at"`
+ Actor string `json:"actor"`
+ ActorKind ActorKind `json:"actor_kind"`
+ IP string `json:"ip"`
+ Method string `json:"method"`
+ Path string `json:"path"`
+ Status int `json:"status"`
+ Note string `json:"note,omitempty"`
+}
+
+func New(db *sql.DB, legacyToken string) (*Store, error) {
+ s := &Store{DB: db, LegacyToken: strings.TrimSpace(legacyToken), keyTouch: map[int64]time.Time{}}
+ if err := s.Migrate(); err != nil {
+ return nil, err
+ }
+ return s, nil
+}
+
+func now() string { return time.Now().UTC().Format(time.RFC3339) }
+
+func (s *Store) Migrate() error {
+ _, err := s.DB.Exec(`
+CREATE TABLE IF NOT EXISTS users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT NOT NULL UNIQUE,
+ pass_hash TEXT NOT NULL,
+ role TEXT NOT NULL DEFAULT 'viewer',
+ disabled INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ last_login_at TEXT NOT NULL DEFAULT ''
+);
+
+CREATE TABLE IF NOT EXISTS sessions (
+ id_hash TEXT PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ csrf TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ last_seen_at TEXT NOT NULL DEFAULT '',
+ ip TEXT NOT NULL DEFAULT '',
+ user_agent TEXT NOT NULL DEFAULT ''
+);
+CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
+
+CREATE TABLE IF NOT EXISTS api_keys (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ key_hash TEXT NOT NULL UNIQUE,
+ role TEXT NOT NULL DEFAULT 'operator',
+ created_at TEXT NOT NULL,
+ last_used_at TEXT NOT NULL DEFAULT '',
+ revoked_at TEXT NOT NULL DEFAULT ''
+);
+
+CREATE TABLE IF NOT EXISTS audit_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ at TEXT NOT NULL,
+ actor TEXT NOT NULL DEFAULT '',
+ actor_kind TEXT NOT NULL DEFAULT '',
+ ip TEXT NOT NULL DEFAULT '',
+ method TEXT NOT NULL DEFAULT '',
+ path TEXT NOT NULL DEFAULT '',
+ status INTEGER NOT NULL DEFAULT 0,
+ note TEXT NOT NULL DEFAULT ''
+);
+CREATE INDEX IF NOT EXISTS idx_audit_at ON audit_log(at);
+`)
+ return err
+}
+
+// ---------- users ----------
+
+func (s *Store) CountUsers() (int, error) {
+ var n int
+ err := s.DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
+ return n, err
+}
+
+func normalizeUsername(u string) string {
+ return strings.ToLower(strings.TrimSpace(u))
+}
+
+func (s *Store) CreateUser(username, password string, role Role) (User, error) {
+ username = normalizeUsername(username)
+ if username == "" {
+ return User{}, fmt.Errorf("username required")
+ }
+ if !role.Valid() {
+ return User{}, fmt.Errorf("invalid role %q", role)
+ }
+ hash, err := HashPassword(password)
+ if err != nil {
+ return User{}, err
+ }
+ res, err := s.DB.Exec(`INSERT INTO users(username,pass_hash,role,disabled,created_at) VALUES(?,?,?,0,?)`,
+ username, hash, string(role), now())
+ if err != nil {
+ if strings.Contains(strings.ToLower(err.Error()), "unique") {
+ return User{}, fmt.Errorf("user %q already exists", username)
+ }
+ return User{}, err
+ }
+ id, _ := res.LastInsertId()
+ return s.GetUser(id)
+}
+
+const userSelect = `SELECT id, username, role, disabled, created_at, last_login_at FROM users`
+
+type rowScanner interface{ Scan(...any) error }
+
+func scanUser(row rowScanner) (User, error) {
+ var u User
+ var disabled int
+ var role string
+ if err := row.Scan(&u.ID, &u.Username, &role, &disabled, &u.CreatedAt, &u.LastLoginAt); err != nil {
+ return u, err
+ }
+ u.Role = Role(role)
+ u.Disabled = disabled != 0
+ return u, nil
+}
+
+func (s *Store) GetUser(id int64) (User, error) {
+ u, err := scanUser(s.DB.QueryRow(userSelect+` WHERE id=?`, id))
+ if errors.Is(err, sql.ErrNoRows) {
+ return u, ErrNotFound
+ }
+ return u, err
+}
+
+func (s *Store) ListUsers() ([]User, error) {
+ rows, err := s.DB.Query(userSelect + ` ORDER BY username`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []User{}
+ for rows.Next() {
+ u, err := scanUser(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, u)
+ }
+ return out, rows.Err()
+}
+
+// Authenticate verifies a username and password. It always performs a hash
+// comparison, even for an unknown user, so a missing account and a wrong
+// password take the same time.
+func (s *Store) Authenticate(username, password string) (User, error) {
+ username = normalizeUsername(username)
+ var id int64
+ var hash, role string
+ var disabled int
+ err := s.DB.QueryRow(`SELECT id, pass_hash, role, disabled FROM users WHERE username=?`, username).
+ Scan(&id, &hash, &role, &disabled)
+ if errors.Is(err, sql.ErrNoRows) {
+ // Decoy verify against a well-formed hash to equalise timing.
+ VerifyPassword(decoyHash, password)
+ return User{}, ErrNotFound
+ }
+ if err != nil {
+ return User{}, err
+ }
+ if !VerifyPassword(hash, password) {
+ return User{}, ErrNotFound
+ }
+ if disabled != 0 {
+ return User{}, fmt.Errorf("account disabled")
+ }
+ _, _ = s.DB.Exec(`UPDATE users SET last_login_at=? WHERE id=?`, now(), id)
+ return s.GetUser(id)
+}
+
+// decoyHash is a real PBKDF2 hash of an unguessable value, used only to burn
+// the same CPU on a missing account as on a wrong password.
+var decoyHash = func() string {
+ secret, _, err := NewToken()
+ if err != nil {
+ secret = "streamd-decoy-value"
+ }
+ h, err := hashWithSalt(secret, []byte("streamd-decoy-sa"), pbkdf2Iterations)
+ if err != nil {
+ return ""
+ }
+ return h
+}()
+
+func (s *Store) SetPassword(id int64, password string) error {
+ hash, err := HashPassword(password)
+ if err != nil {
+ return err
+ }
+ res, err := s.DB.Exec(`UPDATE users SET pass_hash=? WHERE id=?`, hash, id)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n == 0 {
+ return ErrNotFound
+ }
+ // Changing a password invalidates every existing session for that user.
+ _, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
+ return nil
+}
+
+func (s *Store) UpdateUser(id int64, role *Role, disabled *bool) (User, error) {
+ cur, err := s.GetUser(id)
+ if err != nil {
+ return User{}, err
+ }
+ if role != nil {
+ if !role.Valid() {
+ return User{}, fmt.Errorf("invalid role %q", *role)
+ }
+ cur.Role = *role
+ }
+ if disabled != nil {
+ cur.Disabled = *disabled
+ }
+ d := 0
+ if cur.Disabled {
+ d = 1
+ }
+ if _, err := s.DB.Exec(`UPDATE users SET role=?, disabled=? WHERE id=?`, string(cur.Role), d, id); err != nil {
+ return User{}, err
+ }
+ if cur.Disabled {
+ _, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
+ }
+ return s.GetUser(id)
+}
+
+func (s *Store) DeleteUser(id int64) error {
+ res, err := s.DB.Exec(`DELETE FROM users WHERE id=?`, id)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n == 0 {
+ return ErrNotFound
+ }
+ _, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
+ return nil
+}
+
+// CountOtherAdmins counts enabled admins other than excludeID. Used to refuse
+// deleting, disabling or demoting the last admin.
+func (s *Store) CountOtherAdmins(excludeID int64) (int, error) {
+ var n int
+ err := s.DB.QueryRow(
+ `SELECT COUNT(*) FROM users WHERE role = 'admin' AND disabled = 0 AND id <> ?`,
+ excludeID).Scan(&n)
+ return n, err
+}
+
+// ---------- sessions ----------
+
+// CreateSession returns the raw session secret and its CSRF token. Only
+// hashes of the secret reach the database.
+func (s *Store) CreateSession(userID int64, ttl time.Duration, ip, ua string) (secret, csrf string, err error) {
+ if ttl <= 0 {
+ ttl = DefaultSessionTTL
+ }
+ secret, hash, err := NewToken()
+ if err != nil {
+ return "", "", err
+ }
+ csrf, _, err = NewToken()
+ if err != nil {
+ return "", "", err
+ }
+ nowT := time.Now().UTC()
+ _, err = s.DB.Exec(`
+INSERT INTO sessions(id_hash,user_id,csrf,created_at,expires_at,last_seen_at,ip,user_agent)
+VALUES(?,?,?,?,?,?,?,?)`,
+ hash, userID, csrf, nowT.Format(time.RFC3339), nowT.Add(ttl).Format(time.RFC3339),
+ nowT.Format(time.RFC3339), ip, truncate(ua, 200))
+ if err != nil {
+ return "", "", err
+ }
+ return secret, csrf, nil
+}
+
+// LookupSession resolves a raw session secret to a principal, sliding the
+// expiry forward on use.
+func (s *Store) LookupSession(secret string, ttl time.Duration) (*Principal, error) {
+ if secret == "" {
+ return nil, ErrNotFound
+ }
+ if ttl <= 0 {
+ ttl = DefaultSessionTTL
+ }
+ hash := HashToken(secret)
+ var userID int64
+ var csrf, expires, username, role string
+ var disabled int
+ err := s.DB.QueryRow(`
+SELECT s.user_id, s.csrf, s.expires_at, u.username, u.role, u.disabled
+FROM sessions s JOIN users u ON u.id = s.user_id
+WHERE s.id_hash = ?`, hash).Scan(&userID, &csrf, &expires, &username, &role, &disabled)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, ErrNotFound
+ }
+ if err != nil {
+ return nil, err
+ }
+ if disabled != 0 {
+ _, _ = s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, hash)
+ return nil, ErrNotFound
+ }
+ if exp, e := time.Parse(time.RFC3339, expires); e == nil && !exp.After(time.Now().UTC()) {
+ _, _ = s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, hash)
+ return nil, ErrNotFound
+ }
+ nowT := time.Now().UTC()
+ _, _ = s.DB.Exec(`UPDATE sessions SET last_seen_at=?, expires_at=? WHERE id_hash=?`,
+ nowT.Format(time.RFC3339), nowT.Add(ttl).Format(time.RFC3339), hash)
+ return &Principal{
+ Kind: ActorUser,
+ Role: Role(role),
+ Name: username,
+ UserID: userID,
+ SessionID: secret,
+ CSRFToken: csrf,
+ }, nil
+}
+
+func (s *Store) DeleteSession(secret string) error {
+ if secret == "" {
+ return nil
+ }
+ _, err := s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, HashToken(secret))
+ return err
+}
+
+// ExpireSessions drops sessions past their expiry. Returns rows removed.
+func (s *Store) ExpireSessions() (int64, error) {
+ res, err := s.DB.Exec(`DELETE FROM sessions WHERE expires_at <> '' AND expires_at < ?`, now())
+ if err != nil {
+ return 0, err
+ }
+ return res.RowsAffected()
+}
+
+// ---------- api keys ----------
+
+func (s *Store) CreateAPIKey(name string, role Role) (APIKey, error) {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return APIKey{}, fmt.Errorf("name required")
+ }
+ if !role.Valid() {
+ return APIKey{}, fmt.Errorf("invalid role %q", role)
+ }
+ secret, hash, err := NewToken()
+ if err != nil {
+ return APIKey{}, err
+ }
+ res, err := s.DB.Exec(`INSERT INTO api_keys(name,key_hash,role,created_at) VALUES(?,?,?,?)`,
+ name, hash, string(role), now())
+ if err != nil {
+ return APIKey{}, err
+ }
+ id, _ := res.LastInsertId()
+ k, err := s.getAPIKey(id)
+ if err != nil {
+ return APIKey{}, err
+ }
+ k.Secret = secret
+ return k, nil
+}
+
+const keySelect = `SELECT id, name, role, created_at, last_used_at, revoked_at FROM api_keys`
+
+func scanKey(row rowScanner) (APIKey, error) {
+ var k APIKey
+ var role string
+ if err := row.Scan(&k.ID, &k.Name, &role, &k.CreatedAt, &k.LastUsedAt, &k.RevokedAt); err != nil {
+ return k, err
+ }
+ k.Role = Role(role)
+ return k, nil
+}
+
+func (s *Store) getAPIKey(id int64) (APIKey, error) {
+ k, err := scanKey(s.DB.QueryRow(keySelect+` WHERE id=?`, id))
+ if errors.Is(err, sql.ErrNoRows) {
+ return k, ErrNotFound
+ }
+ return k, err
+}
+
+func (s *Store) ListAPIKeys() ([]APIKey, error) {
+ rows, err := s.DB.Query(keySelect + ` ORDER BY name`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []APIKey{}
+ for rows.Next() {
+ k, err := scanKey(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, k)
+ }
+ return out, rows.Err()
+}
+
+func (s *Store) RevokeAPIKey(id int64) error {
+ res, err := s.DB.Exec(`UPDATE api_keys SET revoked_at=? WHERE id=? AND revoked_at = ''`, now(), id)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n == 0 {
+ return ErrNotFound
+ }
+ return nil
+}
+
+// LookupAPIKey resolves a bearer secret to a principal. The legacy shared
+// token is accepted first, as an implicit admin key.
+func (s *Store) LookupAPIKey(secret string) (*Principal, error) {
+ if secret == "" {
+ return nil, ErrNotFound
+ }
+ if s.LegacyToken != "" && SecretEqual(secret, s.LegacyToken) {
+ return &Principal{Kind: ActorAPIKey, Role: RoleAdmin, Name: "legacy-token"}, nil
+ }
+ var id int64
+ var name, role, revoked string
+ err := s.DB.QueryRow(`SELECT id, name, role, revoked_at FROM api_keys WHERE key_hash=?`,
+ HashToken(secret)).Scan(&id, &name, &role, &revoked)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, ErrNotFound
+ }
+ if err != nil {
+ return nil, err
+ }
+ if revoked != "" {
+ return nil, ErrNotFound
+ }
+ s.touchKey(id)
+ return &Principal{Kind: ActorAPIKey, Role: Role(role), Name: name}, nil
+}
+
+// touchKey records last_used_at at most once a minute per key, so a polling
+// agent does not serialise a write behind every request.
+func (s *Store) touchKey(id int64) {
+ s.mu.Lock()
+ last, ok := s.keyTouch[id]
+ if ok && time.Since(last) < time.Minute {
+ s.mu.Unlock()
+ return
+ }
+ s.keyTouch[id] = time.Now()
+ s.mu.Unlock()
+ _, _ = s.DB.Exec(`UPDATE api_keys SET last_used_at=? WHERE id=?`, now(), id)
+}
+
+// ---------- audit ----------
+
+// maxAuditBuffer bounds the in-memory audit queue so a wedged flush loop
+// cannot grow without limit.
+const maxAuditBuffer = 10_000
+
+// Audit buffers one audit row. Call FlushAudit to persist.
+func (s *Store) Audit(e AuditEntry) {
+ if e.At == "" {
+ e.At = now()
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if len(s.auditBuf) >= maxAuditBuffer {
+ s.auditBuf = s.auditBuf[1:]
+ }
+ s.auditBuf = append(s.auditBuf, e)
+}
+
+// FlushAudit writes buffered audit rows in one transaction.
+func (s *Store) FlushAudit() error {
+ s.mu.Lock()
+ batch := s.auditBuf
+ s.auditBuf = nil
+ s.mu.Unlock()
+ if len(batch) == 0 {
+ return nil
+ }
+ requeue := func() {
+ s.mu.Lock()
+ s.auditBuf = append(batch, s.auditBuf...)
+ if len(s.auditBuf) > maxAuditBuffer {
+ s.auditBuf = s.auditBuf[len(s.auditBuf)-maxAuditBuffer:]
+ }
+ s.mu.Unlock()
+ }
+ tx, err := s.DB.Begin()
+ if err != nil {
+ requeue()
+ return err
+ }
+ stmt, err := tx.Prepare(`INSERT INTO audit_log(at,actor,actor_kind,ip,method,path,status,note) VALUES(?,?,?,?,?,?,?,?)`)
+ if err != nil {
+ _ = tx.Rollback()
+ requeue()
+ return err
+ }
+ defer stmt.Close()
+ for _, e := range batch {
+ if _, err := stmt.Exec(e.At, e.Actor, string(e.ActorKind), e.IP, e.Method, e.Path, e.Status, truncate(e.Note, 500)); err != nil {
+ _ = tx.Rollback()
+ requeue()
+ return err
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ requeue()
+ return err
+ }
+ return nil
+}
+
+// RunMaintenance flushes audit rows, expires sessions and prunes old audit
+// history until stop is closed.
+func (s *Store) RunMaintenance(stop <-chan struct{}, retain time.Duration) {
+ t := time.NewTicker(5 * time.Second)
+ defer t.Stop()
+ prune := time.NewTicker(1 * time.Hour)
+ defer prune.Stop()
+ for {
+ select {
+ case <-stop:
+ _ = s.FlushAudit()
+ return
+ case <-t.C:
+ _ = s.FlushAudit()
+ _, _ = s.ExpireSessions()
+ case <-prune.C:
+ if retain > 0 {
+ cutoff := time.Now().UTC().Add(-retain).Format(time.RFC3339)
+ _, _ = s.DB.Exec(`DELETE FROM audit_log WHERE at < ?`, cutoff)
+ }
+ }
+ }
+}
+
+func (s *Store) ListAudit(limit int, actor string) ([]AuditEntry, error) {
+ if limit <= 0 || limit > 1000 {
+ limit = 200
+ }
+ q := `SELECT id,at,actor,actor_kind,ip,method,path,status,note FROM audit_log`
+ args := []any{}
+ if strings.TrimSpace(actor) != "" {
+ q += ` WHERE actor = ?`
+ args = append(args, strings.TrimSpace(actor))
+ }
+ q += ` ORDER BY id DESC LIMIT ?`
+ args = append(args, limit)
+ rows, err := s.DB.Query(q, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []AuditEntry{}
+ for rows.Next() {
+ var e AuditEntry
+ var kind string
+ if err := rows.Scan(&e.ID, &e.At, &e.Actor, &kind, &e.IP, &e.Method, &e.Path, &e.Status, &e.Note); err != nil {
+ return nil, err
+ }
+ e.ActorKind = ActorKind(kind)
+ out = append(out, e)
+ }
+ return out, rows.Err()
+}
+
+func truncate(s string, n int) string {
+ if len(s) <= n {
+ return s
+ }
+ return s[:n]
+}
diff --git a/apps/streamd/internal/db/db.go b/apps/streamd/internal/db/db.go
index 90bb690..aa6b3f7 100644
--- a/apps/streamd/internal/db/db.go
+++ b/apps/streamd/internal/db/db.go
@@ -14,23 +14,48 @@ import (
type Store struct {
DB *sql.DB
+ // hist buffers event and metric writes; see events.go.
+ hist history
}
+// DRM mode values for Stream.DRMMode. "auto" infers from whether the stream
+// currently holds a key, so a clear channel is not treated as broken for
+// having none.
+const (
+ DRMAuto = "auto"
+ DRMYes = "yes"
+ DRMNo = "no"
+)
+
+// DefaultIdleTimeoutS is how long an on-demand stream runs with no viewers.
+const DefaultIdleTimeoutS = 300
+
type Stream struct {
- ID int64 `json:"id"`
- Name string `json:"name"`
- Title string `json:"title"`
- App string `json:"app"`
- Channel string `json:"channel"`
- MPD string `json:"mpd"`
- Key string `json:"key"`
- HeadersJSON string `json:"headers_json"`
- VideoSelect string `json:"video_select"`
- AudioSelect string `json:"audio_select"`
- Enabled bool `json:"enabled"`
- Rewriter string `json:"rewriter"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
+ ID int64 `json:"id"`
+ Name string `json:"name"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Tags string `json:"tags"`
+ App string `json:"app"`
+ Channel string `json:"channel"`
+ MPD string `json:"mpd"`
+ Key string `json:"key"`
+ HeadersJSON string `json:"headers_json"`
+ Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
+ Egress string `json:"egress"` // named egress profile (wireguard/socks); used when Proxy empty
+ VideoSelect string `json:"video_select"`
+ AudioSelect string `json:"audio_select"`
+ Enabled bool `json:"enabled"`
+ Rewriter string `json:"rewriter"`
+ VariantsJSON string `json:"variants_json"` // FHD/HD/SD ladder config
+ OutputsJSON string `json:"outputs_json"` // HLS/CMAF/DASH/TS output config
+ SettingsJSON string `json:"settings_json"` // per-stream packager knobs
+ DRMMode string `json:"drm_mode"` // auto | yes | no
+ OnDemand bool `json:"on_demand"`
+ IdleTimeoutS int `json:"idle_timeout_s"`
+ Public bool `json:"public"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
Health string `json:"health,omitempty"`
PID int64 `json:"pid,omitempty"`
@@ -41,40 +66,90 @@ type Stream struct {
LastError string `json:"last_error,omitempty"`
RuntimeAt string `json:"runtime_updated_at,omitempty"`
+ // Variants is filled for API responses (play paths + optional live health).
+ Variants []VariantStatus `json:"variants,omitempty"`
+ // Outputs is the resolved output format list for API responses.
+ Outputs []OutputStatus `json:"outputs,omitempty"`
+ // Links is every playable endpoint (variant x output, plus the ABR
+ // master), filled by the API layer which can see the files on disk.
+ Links []PublishLink `json:"links,omitempty"`
+
ClaimedBy string `json:"claimed_by,omitempty"`
ClaimExp string `json:"claim_expires_at,omitempty"`
+
+ // Derived, never stored. These exist so clients — above all the capture
+ // agent — can reason about credentials without being handed the secrets.
+ HasKey bool `json:"has_key"`
+ HasHeaders bool `json:"has_headers"`
+ HasProxy bool `json:"has_proxy"`
+ HasEgress bool `json:"has_egress"`
+ KeyValid bool `json:"key_valid"`
+ // DRMRequired is DRMMode resolved: whether this stream needs keys at all.
+ DRMRequired bool `json:"drm_required"`
+ // NeedsCapture is the server's verdict on whether the agent should fetch
+ // fresh credentials. The agent must use this rather than inspecting keys,
+ // which are redacted out of API responses.
+ NeedsCapture bool `json:"needs_capture"`
+ // Viewers is the live client count, filled by the HLS gate.
+ Viewers int `json:"viewers,omitempty"`
}
type CreateStream struct {
- Name string `json:"name"`
- Title string `json:"title"`
- App string `json:"app"`
- Channel string `json:"channel"`
- MPD string `json:"mpd"`
- Key string `json:"key"`
- HeadersJSON string `json:"headers_json"`
- VideoSelect string `json:"video_select"`
- AudioSelect string `json:"audio_select"`
- Rewriter string `json:"rewriter"`
- Enabled *bool `json:"enabled"`
+ Name string `json:"name"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Tags string `json:"tags"`
+ App string `json:"app"`
+ Channel string `json:"channel"`
+ MPD string `json:"mpd"`
+ Key string `json:"key"`
+ HeadersJSON string `json:"headers_json"`
+ Proxy string `json:"proxy"`
+ Egress string `json:"egress"`
+ VideoSelect string `json:"video_select"`
+ AudioSelect string `json:"audio_select"`
+ Rewriter string `json:"rewriter"`
+ Enabled *bool `json:"enabled"`
+ VariantsJSON string `json:"variants_json"`
+ Variants []VariantSpec `json:"variants"`
+ OutputsJSON string `json:"outputs_json"`
+ Outputs []OutputSpec `json:"outputs"`
+ SettingsJSON string `json:"settings_json"`
+ DRMMode string `json:"drm_mode"`
+ OnDemand *bool `json:"on_demand"`
+ IdleTimeoutS *int `json:"idle_timeout_s"`
+ Public *bool `json:"public"`
}
type PatchStream struct {
- Title *string `json:"title"`
- App *string `json:"app"`
- Channel *string `json:"channel"`
- MPD *string `json:"mpd"`
- Key *string `json:"key"`
- HeadersJSON *string `json:"headers_json"`
- VideoSelect *string `json:"video_select"`
- AudioSelect *string `json:"audio_select"`
- Rewriter *string `json:"rewriter"`
- Enabled *bool `json:"enabled"`
+ Title *string `json:"title"`
+ Description *string `json:"description"`
+ Tags *string `json:"tags"`
+ App *string `json:"app"`
+ Channel *string `json:"channel"`
+ MPD *string `json:"mpd"`
+ Key *string `json:"key"`
+ HeadersJSON *string `json:"headers_json"`
+ Proxy *string `json:"proxy"`
+ Egress *string `json:"egress"`
+ VideoSelect *string `json:"video_select"`
+ AudioSelect *string `json:"audio_select"`
+ Rewriter *string `json:"rewriter"`
+ Enabled *bool `json:"enabled"`
+ VariantsJSON *string `json:"variants_json"`
+ Variants []VariantSpec `json:"variants"`
+ OutputsJSON *string `json:"outputs_json"`
+ Outputs []OutputSpec `json:"outputs"`
+ SettingsJSON *string `json:"settings_json"`
+ DRMMode *string `json:"drm_mode"`
+ OnDemand *bool `json:"on_demand"`
+ IdleTimeoutS *int `json:"idle_timeout_s"`
+ Public *bool `json:"public"`
}
type Credentials struct {
MPD string `json:"mpd"`
- Key string `json:"key"`
+ Key string `json:"key"` // optional for clear streams
PSSH string `json:"pssh,omitempty"`
Auth string `json:"auth,omitempty"`
PID string `json:"pid,omitempty"`
@@ -114,6 +189,7 @@ CREATE TABLE IF NOT EXISTS streams (
mpd TEXT NOT NULL DEFAULT '',
key_kid_key TEXT NOT NULL DEFAULT '',
headers_json TEXT NOT NULL DEFAULT '{}',
+ proxy TEXT NOT NULL DEFAULT '',
video_select TEXT NOT NULL DEFAULT '',
audio_select TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 0,
@@ -141,7 +217,40 @@ CREATE TABLE IF NOT EXISTS agent_claims (
expires_at TEXT NOT NULL
);
`)
- return err
+ if err != nil {
+ return err
+ }
+ // Columns added after the original schema. SQLite has no "ADD COLUMN IF
+ // NOT EXISTS", so these are best-effort and fail harmlessly when the
+ // column is already there.
+ for _, stmt := range []string{
+ `ALTER TABLE streams ADD COLUMN proxy TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE streams ADD COLUMN variants_json TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE streams ADD COLUMN description TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE streams ADD COLUMN tags TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE streams ADD COLUMN outputs_json TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE streams ADD COLUMN settings_json TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE streams ADD COLUMN drm_mode TEXT NOT NULL DEFAULT 'auto'`,
+ `ALTER TABLE streams ADD COLUMN on_demand INTEGER NOT NULL DEFAULT 0`,
+ `ALTER TABLE streams ADD COLUMN idle_timeout_s INTEGER NOT NULL DEFAULT 300`,
+ `ALTER TABLE streams ADD COLUMN public INTEGER NOT NULL DEFAULT 1`,
+ `ALTER TABLE streams ADD COLUMN egress TEXT NOT NULL DEFAULT ''`,
+ } {
+ _, _ = s.DB.Exec(stmt)
+ }
+ if err := s.migrateHistory(); err != nil {
+ return err
+ }
+ if err := s.migrateSettings(); err != nil {
+ return err
+ }
+ if err := s.migrateSchedules(); err != nil {
+ return err
+ }
+ if err := s.migrateEgress(); err != nil {
+ return err
+ }
+ return s.migrateSessions()
}
func now() string {
@@ -166,18 +275,27 @@ func slug(name string) string {
return out
}
-func (s *Store) ListStreams() ([]Stream, error) {
- rows, err := s.DB.Query(`
-SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
- s.video_select, s.audio_select, s.enabled, s.rewriter, s.created_at, s.updated_at,
+// Slug normalises a name the same way stream and egress profile names are stored.
+func Slug(name string) string { return slug(name) }
+
+const streamSelect = `
+SELECT s.id, s.name, s.title, COALESCE(s.description,''), COALESCE(s.tags,''),
+ s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
+ COALESCE(s.proxy,''), COALESCE(s.egress,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
+ COALESCE(s.variants_json,''), COALESCE(s.outputs_json,''), COALESCE(s.settings_json,''),
+ COALESCE(s.drm_mode,'auto'), COALESCE(s.on_demand,0),
+ COALESCE(s.idle_timeout_s,300), COALESCE(s.public,1),
+ s.created_at, s.updated_at,
COALESCE(r.health,''), COALESCE(r.pid,0), COALESCE(r.play_path,''),
COALESCE(r.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0),
COALESCE(r.last_error,''), COALESCE(r.updated_at,''),
COALESCE(c.agent_id,''), COALESCE(c.expires_at,'')
FROM streams s
LEFT JOIN stream_runtime r ON r.stream_id = s.id
-LEFT JOIN agent_claims c ON c.stream_id = s.id
-ORDER BY s.name`)
+LEFT JOIN agent_claims c ON c.stream_id = s.id`
+
+func (s *Store) ListStreams() ([]Stream, error) {
+ rows, err := s.DB.Query(streamSelect + ` ORDER BY s.name`)
if err != nil {
return nil, err
}
@@ -194,17 +312,13 @@ ORDER BY s.name`)
}
func (s *Store) GetStream(id int64) (Stream, error) {
- row := s.DB.QueryRow(`
-SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
- s.video_select, s.audio_select, s.enabled, s.rewriter, s.created_at, s.updated_at,
- COALESCE(r.health,''), COALESCE(r.pid,0), COALESCE(r.play_path,''),
- COALESCE(r.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0),
- COALESCE(r.last_error,''), COALESCE(r.updated_at,''),
- COALESCE(c.agent_id,''), COALESCE(c.expires_at,'')
-FROM streams s
-LEFT JOIN stream_runtime r ON r.stream_id = s.id
-LEFT JOIN agent_claims c ON c.stream_id = s.id
-WHERE s.id = ?`, id)
+ row := s.DB.QueryRow(streamSelect+` WHERE s.id = ?`, id)
+ return scanStream(row)
+}
+
+// GetStreamByName resolves a stream by its slug name, used by the HLS gate.
+func (s *Store) GetStreamByName(name string) (Stream, error) {
+ row := s.DB.QueryRow(streamSelect+` WHERE s.name = ?`, name)
return scanStream(row)
}
@@ -214,10 +328,14 @@ type rowScanner interface {
func scanStream(row rowScanner) (Stream, error) {
var st Stream
- var enabled int
+ var enabled, onDemand, public int
err := row.Scan(
- &st.ID, &st.Name, &st.Title, &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
- &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.CreatedAt, &st.UpdatedAt,
+ &st.ID, &st.Name, &st.Title, &st.Description, &st.Tags,
+ &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
+ &st.Proxy, &st.Egress, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
+ &st.VariantsJSON, &st.OutputsJSON, &st.SettingsJSON,
+ &st.DRMMode, &onDemand, &st.IdleTimeoutS, &public,
+ &st.CreatedAt, &st.UpdatedAt,
&st.Health, &st.PID, &st.PlayPath, &st.UptimeS, &st.BitrateMbps, &st.PlaylistAgeS,
&st.LastError, &st.RuntimeAt, &st.ClaimedBy, &st.ClaimExp,
)
@@ -225,12 +343,19 @@ func scanStream(row rowScanner) (Stream, error) {
return st, err
}
st.Enabled = enabled != 0
+ st.OnDemand = onDemand != 0
+ st.Public = public != 0
+ if st.IdleTimeoutS <= 0 {
+ st.IdleTimeoutS = DefaultIdleTimeoutS
+ }
if st.Health == "" {
st.Health = "stopped"
}
if st.PlayPath == "" {
st.PlayPath = "/hls/" + st.Name + "/index.m3u8"
}
+ st.Variants = AttachVariantStatuses(st.Name, st.VariantsJSON, st.Health, st.PlaylistAgeS)
+ st.Outputs = AttachOutputStatuses(st.Name, st.OutputsJSON)
// Hide expired claims in API responses (ExpireClaims cleans them shortly after).
if st.ClaimExp != "" {
if exp, e := time.Parse(time.RFC3339, st.ClaimExp); e == nil && !exp.After(time.Now().UTC()) {
@@ -238,9 +363,163 @@ func scanStream(row rowScanner) (Stream, error) {
st.ClaimExp = ""
}
}
+ st.fillDerived()
return st, nil
}
+// fillDerived computes the non-secret flags clients use in place of the
+// credentials themselves.
+func (st *Stream) fillDerived() {
+ st.HasKey = strings.TrimSpace(st.Key) != ""
+ st.KeyValid = ValidKeyPairs(st.Key)
+ hdr := strings.TrimSpace(st.HeadersJSON)
+ st.HasHeaders = hdr != "" && hdr != "{}" && hdr != "null"
+ st.HasProxy = strings.TrimSpace(st.Proxy) != ""
+ st.HasEgress = strings.TrimSpace(st.Egress) != ""
+ switch strings.ToLower(strings.TrimSpace(st.DRMMode)) {
+ case DRMYes:
+ st.DRMRequired = true
+ case DRMNo:
+ st.DRMRequired = false
+ default:
+ // auto: a stream that holds a key is encrypted; one that never had a
+ // key is assumed clear, matching streamd's support for clear content.
+ st.DRMMode = DRMAuto
+ st.DRMRequired = st.HasKey
+ }
+ st.NeedsCapture = st.computeNeedsCapture()
+}
+
+// Redact removes credentials from a Stream destined for an API response.
+// The derived flags survive, so a caller can still tell that a key exists and
+// whether it parses, without being handed the key itself.
+func (st *Stream) Redact() {
+ st.Key = ""
+ st.HeadersJSON = ""
+ st.Proxy = ""
+}
+
+// Redacted returns a copy with credentials stripped.
+func (st Stream) Redacted() Stream {
+ st.Redact()
+ return st
+}
+
+// bootstrapGraceS is how long a stream may sit in "starting" before we treat
+// it as needing fresh credentials. It matches the supervisor's own bootstrap
+// deadline: capturing sooner would restart a stream that is still coming up,
+// which is a slow restart loop.
+const bootstrapGraceS = 180
+
+// computeNeedsCapture reports whether an enabled stream looks down or is
+// missing the credentials it needs.
+func (st Stream) computeNeedsCapture() bool {
+ if !st.Enabled {
+ return false
+ }
+ // No manifest at all: only a capture can supply one.
+ if strings.TrimSpace(st.MPD) == "" {
+ return true
+ }
+ // Encrypted streams need usable keys. Clear streams do not, which is why
+ // this is gated on DRMRequired rather than on the key being empty.
+ if st.DRMRequired && !st.KeyValid {
+ return true
+ }
+ // An on-demand stream that is deliberately idle is not broken. Its
+ // credentials are refreshed when a viewer wakes it.
+ if st.OnDemand && (st.Health == "stopped" || st.Health == "") {
+ return false
+ }
+ switch st.Health {
+ case "down", "stopped", "":
+ return true
+ case "starting":
+ // Give the supervisor its bootstrap window before interfering.
+ return st.UptimeS > bootstrapGraceS
+ }
+ return st.PlaylistAgeS > 30
+}
+
+// ValidKeyPairs reports whether raw holds at least one KID:KEY pair and every
+// pair present is a 32-hex:32-hex pair. Separators may be newlines, commas or
+// semicolons, matching what the supervisor writes to NRE's key file — a
+// multi-KID stream is valid, which a single-pair check would wrongly reject.
+func ValidKeyPairs(raw string) bool {
+ lines := SplitKeyLines(raw)
+ if len(lines) == 0 {
+ return false
+ }
+ for _, line := range lines {
+ kid, key, ok := strings.Cut(line, ":")
+ if !ok {
+ return false
+ }
+ if len(hexOnly(kid)) != 32 || len(hexOnly(key)) != 32 {
+ return false
+ }
+ }
+ return true
+}
+
+// SplitKeyLines normalises a key field into one KID:KEY entry per line.
+func SplitKeyLines(raw string) []string {
+ raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
+ var out []string
+ for _, line := range strings.Split(raw, "\n") {
+ if line = strings.TrimSpace(line); line != "" {
+ out = append(out, line)
+ }
+ }
+ return out
+}
+
+func hexOnly(s string) string {
+ var b strings.Builder
+ for _, r := range s {
+ switch {
+ case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+// AttachVariantStatuses builds the variants array for API responses.
+// Source (FHD) inherits the stream health; scaled variants stay "configured"
+// until the supervisor refreshes them via EnrichVariantHealth.
+func AttachVariantStatuses(streamName, variantsJSON, streamHealth string, playlistAge float64) []VariantStatus {
+ specs := ParseVariantsJSON(variantsJSON)
+ out := make([]VariantStatus, 0, len(specs))
+ for _, v := range specs {
+ vs := VariantStatus{
+ VariantSpec: v,
+ PlayPath: VariantPlayPath(streamName, v.ID, v.Height),
+ }
+ if !v.Enabled {
+ vs.Health = "off"
+ } else if v.Height <= 0 && !v.AudioOnly {
+ vs.Health = streamHealth
+ vs.PlaylistAgeS = playlistAge
+ } else {
+ vs.Health = "pending"
+ }
+ out = append(out, vs)
+ }
+ return out
+}
+
+func normalizeDRMMode(s string) string {
+ switch strings.ToLower(strings.TrimSpace(s)) {
+ case DRMYes:
+ return DRMYes
+ case DRMNo:
+ return DRMNo
+ default:
+ return DRMAuto
+ }
+}
+
func (s *Store) CreateStream(in CreateStream) (Stream, error) {
name := slug(in.Name)
if name == "" {
@@ -252,22 +531,56 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) {
if !json.Valid([]byte(in.HeadersJSON)) {
return Stream{}, fmt.Errorf("headers_json must be valid JSON")
}
+ // Installation-wide defaults for on_demand / idle / outputs when the
+ // caller left those fields unset. Explicit body values still win.
+ s.ApplyCreateDefaults(&in)
// video_select / audio_select / rewriter are left empty on purpose: the
// supervisor resolves them from the stream's app module at start time, so no
// provider's preferences are baked into the schema.
if in.Title == "" {
in.Title = name
}
+ variantsJSON, err := resolveVariantsJSON(in.VariantsJSON, in.Variants, true)
+ if err != nil {
+ return Stream{}, err
+ }
+ outputsJSON, err := resolveOutputsJSON(in.OutputsJSON, in.Outputs, true)
+ if err != nil {
+ return Stream{}, err
+ }
+ settingsJSON := strings.TrimSpace(in.SettingsJSON)
+ if settingsJSON != "" && !json.Valid([]byte(settingsJSON)) {
+ return Stream{}, fmt.Errorf("settings_json must be valid JSON")
+ }
enabled := 0
if in.Enabled != nil && *in.Enabled {
enabled = 1
}
+ onDemand := 0
+ if in.OnDemand != nil && *in.OnDemand {
+ onDemand = 1
+ }
+ // Public by default: that is today's behaviour, and an on-demand stream
+ // that nobody may fetch could never be woken.
+ public := 1
+ if in.Public != nil && !*in.Public {
+ public = 0
+ }
+ idle := DefaultIdleTimeoutS
+ if in.IdleTimeoutS != nil && *in.IdleTimeoutS > 0 {
+ idle = *in.IdleTimeoutS
+ }
ts := now()
res, err := s.DB.Exec(`
-INSERT INTO streams(name,title,app,channel,mpd,key_kid_key,headers_json,video_select,audio_select,enabled,rewriter,created_at,updated_at)
-VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON,
- in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, ts, ts)
+INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,egress,
+ video_select,audio_select,enabled,rewriter,variants_json,outputs_json,
+ settings_json,drm_mode,on_demand,idle_timeout_s,public,created_at,updated_at)
+VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+ name, in.Title, strings.TrimSpace(in.Description), normalizeTags(in.Tags),
+ in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
+ slug(strings.TrimSpace(in.Egress)),
+ in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON,
+ settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts)
if err != nil {
return Stream{}, err
}
@@ -277,6 +590,51 @@ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`,
return s.GetStream(id)
}
+// resolveVariantsJSON normalises the ladder from either the typed list or the
+// raw JSON field. onCreate fills the default ladder when both are empty.
+func resolveVariantsJSON(raw string, list []VariantSpec, onCreate bool) (string, error) {
+ if len(list) > 0 {
+ return EncodeVariantsJSON(list)
+ }
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ if onCreate {
+ return EncodeVariantsJSON(DefaultVariants())
+ }
+ return "", nil
+ }
+ return EncodeVariantsJSON(ParseVariantsJSON(raw))
+}
+
+func resolveOutputsJSON(raw string, list []OutputSpec, onCreate bool) (string, error) {
+ if len(list) > 0 {
+ return EncodeOutputsJSON(list)
+ }
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ if onCreate {
+ return EncodeOutputsJSON(DefaultOutputs())
+ }
+ return "", nil
+ }
+ return EncodeOutputsJSON(ParseOutputsJSON(raw))
+}
+
+// normalizeTags lowercases and de-duplicates a comma-separated tag list.
+func normalizeTags(raw string) string {
+ seen := map[string]bool{}
+ var out []string
+ for _, t := range strings.Split(raw, ",") {
+ t = slug(t)
+ if t == "" || seen[t] {
+ continue
+ }
+ seen[t] = true
+ out = append(out, t)
+ }
+ return strings.Join(out, ",")
+}
+
func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
cur, err := s.GetStream(id)
if err != nil {
@@ -285,6 +643,12 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
if in.Title != nil {
cur.Title = *in.Title
}
+ if in.Description != nil {
+ cur.Description = strings.TrimSpace(*in.Description)
+ }
+ if in.Tags != nil {
+ cur.Tags = normalizeTags(*in.Tags)
+ }
if in.App != nil {
cur.App = *in.App
}
@@ -303,6 +667,12 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
}
cur.HeadersJSON = *in.HeadersJSON
}
+ if in.Proxy != nil {
+ cur.Proxy = strings.TrimSpace(*in.Proxy)
+ }
+ if in.Egress != nil {
+ cur.Egress = slug(strings.TrimSpace(*in.Egress))
+ }
if in.VideoSelect != nil {
cur.VideoSelect = *in.VideoSelect
}
@@ -312,6 +682,51 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
if in.Rewriter != nil {
cur.Rewriter = *in.Rewriter
}
+ if in.DRMMode != nil {
+ cur.DRMMode = normalizeDRMMode(*in.DRMMode)
+ }
+ if in.OnDemand != nil {
+ cur.OnDemand = *in.OnDemand
+ }
+ if in.Public != nil {
+ cur.Public = *in.Public
+ }
+ if in.IdleTimeoutS != nil && *in.IdleTimeoutS > 0 {
+ cur.IdleTimeoutS = *in.IdleTimeoutS
+ }
+ if in.SettingsJSON != nil {
+ v := strings.TrimSpace(*in.SettingsJSON)
+ if v != "" && !json.Valid([]byte(v)) {
+ return Stream{}, fmt.Errorf("settings_json must be valid JSON")
+ }
+ cur.SettingsJSON = v
+ }
+ if len(in.Variants) > 0 || in.VariantsJSON != nil {
+ raw := ""
+ if in.VariantsJSON != nil {
+ raw = *in.VariantsJSON
+ }
+ encoded, err := resolveVariantsJSON(raw, in.Variants, false)
+ if err != nil {
+ return Stream{}, err
+ }
+ if encoded != "" {
+ cur.VariantsJSON = encoded
+ }
+ }
+ if len(in.Outputs) > 0 || in.OutputsJSON != nil {
+ raw := ""
+ if in.OutputsJSON != nil {
+ raw = *in.OutputsJSON
+ }
+ encoded, err := resolveOutputsJSON(raw, in.Outputs, false)
+ if err != nil {
+ return Stream{}, err
+ }
+ if encoded != "" {
+ cur.OutputsJSON = encoded
+ }
+ }
enabled := 0
if cur.Enabled {
enabled = 1
@@ -323,12 +738,24 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
enabled = 0
}
}
+ onDemand := 0
+ if cur.OnDemand {
+ onDemand = 1
+ }
+ public := 0
+ if cur.Public {
+ public = 1
+ }
ts := now()
_, err = s.DB.Exec(`
-UPDATE streams SET title=?, app=?, channel=?, mpd=?, key_kid_key=?, headers_json=?,
- video_select=?, audio_select=?, enabled=?, rewriter=?, updated_at=? WHERE id=?`,
- cur.Title, cur.App, cur.Channel, cur.MPD, cur.Key, cur.HeadersJSON,
- cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, ts, id)
+UPDATE streams SET title=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?,
+ headers_json=?, proxy=?, egress=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
+ variants_json=?, outputs_json=?, settings_json=?, drm_mode=?, on_demand=?,
+ idle_timeout_s=?, public=?, updated_at=? WHERE id=?`,
+ cur.Title, cur.Description, cur.Tags, cur.App, cur.Channel, cur.MPD, cur.Key,
+ cur.HeadersJSON, cur.Proxy, cur.Egress, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
+ cur.VariantsJSON, cur.OutputsJSON, cur.SettingsJSON, cur.DRMMode, onDemand,
+ cur.IdleTimeoutS, public, ts, id)
if err != nil {
return Stream{}, err
}
@@ -362,11 +789,22 @@ ON CONFLICT(stream_id) DO UPDATE SET health=excluded.health, play_path=excluded.
}
func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
- if strings.TrimSpace(cred.MPD) == "" || strings.TrimSpace(cred.Key) == "" {
- return Stream{}, fmt.Errorf("mpd and key required")
+ mpd := strings.TrimSpace(cred.MPD)
+ key := strings.TrimSpace(cred.Key)
+ if mpd == "" {
+ return Stream{}, fmt.Errorf("mpd required")
}
- _, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
- strings.TrimSpace(cred.MPD), strings.TrimSpace(cred.Key), now(), id)
+ st, err := s.GetStream(id)
+ if err != nil {
+ return Stream{}, err
+ }
+ // Encrypted streams must receive usable KID:KEY lines — MPD alone leaves
+ // the packager rainbow-decrypting forever.
+ if st.DRMRequired && !ValidKeyPairs(key) {
+ return Stream{}, fmt.Errorf("key required for DRM stream %q (got mpd but no valid KID:KEY)", st.Name)
+ }
+ _, err = s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
+ mpd, key, now(), id)
if err != nil {
return Stream{}, err
}
@@ -484,21 +922,3 @@ ON CONFLICT(stream_id) DO UPDATE SET
id, p.Health, p.PID, play, p.UptimeS, p.BitrateMbps, p.PlaylistAgeS, p.LastError, now())
return err
}
-
-// NeedsCapture reports whether an enabled stream looks down / missing creds.
-func (st Stream) NeedsCapture() bool {
- if !st.Enabled {
- return false
- }
- if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
- return true
- }
- switch st.Health {
- case "down", "stopped", "starting", "":
- return true
- }
- if st.PlaylistAgeS > 30 {
- return true
- }
- return false
-}
diff --git a/apps/streamd/internal/db/egress.go b/apps/streamd/internal/db/egress.go
new file mode 100644
index 0000000..6371c83
--- /dev/null
+++ b/apps/streamd/internal/db/egress.go
@@ -0,0 +1,226 @@
+package db
+
+import (
+ "database/sql"
+ "fmt"
+ "strings"
+)
+
+const (
+ EgressKindWireGuard = "wireguard"
+ EgressKindSocks = "socks"
+
+ EgressStopped = "stopped"
+ EgressStarting = "starting"
+ EgressUp = "up"
+ EgressDown = "down"
+ EgressError = "error"
+)
+
+// EgressProfile is a named origin-egress path (WireGuard netns or plain SOCKS).
+// Conf blobs live on disk under data/egress//; never in this table.
+type EgressProfile struct {
+ ID int64 `json:"id"`
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ Enabled bool `json:"enabled"`
+ ListenPort int `json:"listen_port"`
+ SocksURL string `json:"socks_url,omitempty"`
+ Status string `json:"status"`
+ LastError string `json:"last_error,omitempty"`
+ EgressIP string `json:"egress_ip,omitempty"`
+ HasConf bool `json:"has_conf"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+func (s *Store) migrateEgress() error {
+ _, err := s.DB.Exec(`
+CREATE TABLE IF NOT EXISTS egress_profiles (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL UNIQUE,
+ kind TEXT NOT NULL DEFAULT 'wireguard',
+ enabled INTEGER NOT NULL DEFAULT 0,
+ listen_port INTEGER NOT NULL DEFAULT 0,
+ socks_url TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL DEFAULT 'stopped',
+ last_error TEXT NOT NULL DEFAULT '',
+ egress_ip TEXT NOT NULL DEFAULT '',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+`)
+ return err
+}
+
+type CreateEgressProfile struct {
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ Enabled *bool `json:"enabled"`
+ SocksURL string `json:"socks_url"`
+}
+
+type UpdateEgressProfile struct {
+ Enabled *bool `json:"enabled"`
+ SocksURL *string `json:"socks_url"`
+ Kind *string `json:"kind"`
+}
+
+func normalizeEgressKind(k string) (string, error) {
+ switch strings.ToLower(strings.TrimSpace(k)) {
+ case "", EgressKindWireGuard:
+ return EgressKindWireGuard, nil
+ case EgressKindSocks:
+ return EgressKindSocks, nil
+ default:
+ return "", fmt.Errorf("kind must be %q or %q", EgressKindWireGuard, EgressKindSocks)
+ }
+}
+
+func (s *Store) ListEgressProfiles() ([]EgressProfile, error) {
+ rows, err := s.DB.Query(`
+SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
+FROM egress_profiles ORDER BY name`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []EgressProfile
+ for rows.Next() {
+ p, err := scanEgress(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, p)
+ }
+ if out == nil {
+ out = []EgressProfile{}
+ }
+ return out, rows.Err()
+}
+
+func (s *Store) GetEgressProfile(id int64) (EgressProfile, error) {
+ row := s.DB.QueryRow(`
+SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
+FROM egress_profiles WHERE id=?`, id)
+ return scanEgress(row)
+}
+
+func (s *Store) GetEgressProfileByName(name string) (EgressProfile, error) {
+ name = slug(name)
+ if name == "" {
+ return EgressProfile{}, fmt.Errorf("name required")
+ }
+ row := s.DB.QueryRow(`
+SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
+FROM egress_profiles WHERE name=?`, name)
+ return scanEgress(row)
+}
+
+func scanEgress(row rowScanner) (EgressProfile, error) {
+ var p EgressProfile
+ var enabled int
+ err := row.Scan(
+ &p.ID, &p.Name, &p.Kind, &enabled, &p.ListenPort, &p.SocksURL,
+ &p.Status, &p.LastError, &p.EgressIP, &p.CreatedAt, &p.UpdatedAt,
+ )
+ if err != nil {
+ return p, err
+ }
+ p.Enabled = enabled != 0
+ if p.Status == "" {
+ p.Status = EgressStopped
+ }
+ return p, nil
+}
+
+func (s *Store) CreateEgressProfile(in CreateEgressProfile) (EgressProfile, error) {
+ name := slug(in.Name)
+ if name == "" {
+ return EgressProfile{}, fmt.Errorf("name required (slug of letters, digits, hyphens)")
+ }
+ kind, err := normalizeEgressKind(in.Kind)
+ if err != nil {
+ return EgressProfile{}, err
+ }
+ socks := strings.TrimSpace(in.SocksURL)
+ if kind == EgressKindSocks && socks == "" {
+ return EgressProfile{}, fmt.Errorf("socks_url required for kind=socks")
+ }
+ enabled := 0
+ if in.Enabled != nil && *in.Enabled {
+ enabled = 1
+ }
+ ts := now()
+ res, err := s.DB.Exec(`
+INSERT INTO egress_profiles(name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at)
+VALUES(?,?,?,0,?,?, '','',?,?)`,
+ name, kind, enabled, socks, EgressStopped, ts, ts)
+ if err != nil {
+ if strings.Contains(strings.ToLower(err.Error()), "unique") {
+ return EgressProfile{}, fmt.Errorf("egress profile %q already exists", name)
+ }
+ return EgressProfile{}, err
+ }
+ id, _ := res.LastInsertId()
+ return s.GetEgressProfile(id)
+}
+
+func (s *Store) UpdateEgressProfile(id int64, in UpdateEgressProfile) (EgressProfile, error) {
+ cur, err := s.GetEgressProfile(id)
+ if err != nil {
+ return EgressProfile{}, err
+ }
+ if in.Enabled != nil {
+ cur.Enabled = *in.Enabled
+ }
+ if in.SocksURL != nil {
+ cur.SocksURL = strings.TrimSpace(*in.SocksURL)
+ }
+ if in.Kind != nil {
+ kind, err := normalizeEgressKind(*in.Kind)
+ if err != nil {
+ return EgressProfile{}, err
+ }
+ cur.Kind = kind
+ }
+ if cur.Kind == EgressKindSocks && cur.SocksURL == "" {
+ return EgressProfile{}, fmt.Errorf("socks_url required for kind=socks")
+ }
+ enabled := 0
+ if cur.Enabled {
+ enabled = 1
+ }
+ ts := now()
+ _, err = s.DB.Exec(`
+UPDATE egress_profiles SET kind=?, enabled=?, socks_url=?, updated_at=? WHERE id=?`,
+ cur.Kind, enabled, cur.SocksURL, ts, id)
+ if err != nil {
+ return EgressProfile{}, err
+ }
+ return s.GetEgressProfile(id)
+}
+
+func (s *Store) DeleteEgressProfile(id int64) error {
+ res, err := s.DB.Exec(`DELETE FROM egress_profiles WHERE id=?`, id)
+ if err != nil {
+ return err
+ }
+ n, _ := res.RowsAffected()
+ if n == 0 {
+ return sql.ErrNoRows
+ }
+ return nil
+}
+
+// SetEgressRuntime updates live status fields without touching config.
+func (s *Store) SetEgressRuntime(id int64, status, lastErr, egressIP string, listenPort int) error {
+ status = strings.TrimSpace(status)
+ if status == "" {
+ status = EgressStopped
+ }
+ _, err := s.DB.Exec(`
+UPDATE egress_profiles SET status=?, last_error=?, egress_ip=?, listen_port=?, updated_at=? WHERE id=?`,
+ status, strings.TrimSpace(lastErr), strings.TrimSpace(egressIP), listenPort, now(), id)
+ return err
+}
diff --git a/apps/streamd/internal/db/egress_test.go b/apps/streamd/internal/db/egress_test.go
new file mode 100644
index 0000000..3b6c9c1
--- /dev/null
+++ b/apps/streamd/internal/db/egress_test.go
@@ -0,0 +1,117 @@
+package db
+
+import (
+ "path/filepath"
+ "testing"
+)
+
+func TestSlugValidation(t *testing.T) {
+ for _, c := range []struct {
+ in, want string
+ }{
+ {"London", "london"},
+ {"dublin-1", "dublin-1"},
+ {" RTE IE ", "rte-ie"},
+ {"!!!", ""},
+ {"Wire_Guard", "wire-guard"},
+ {"a--b", "a-b"},
+ } {
+ if got := Slug(c.in); got != c.want {
+ t.Errorf("Slug(%q) = %q want %q", c.in, got, c.want)
+ }
+ }
+}
+
+func TestEgressCRUD(t *testing.T) {
+ dir := t.TempDir()
+ store, err := Open(filepath.Join(dir, "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ _, err = store.CreateEgressProfile(CreateEgressProfile{Name: "!!!"})
+ if err == nil {
+ t.Fatal("expected empty slug to fail")
+ }
+
+ on := true
+ p, err := store.CreateEgressProfile(CreateEgressProfile{
+ Name: "London", Kind: "wireguard", Enabled: &on,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if p.Name != "london" || p.Kind != EgressKindWireGuard || !p.Enabled {
+ t.Fatalf("create: %+v", p)
+ }
+ if p.Status != EgressStopped {
+ t.Fatalf("status = %q", p.Status)
+ }
+
+ got, err := store.GetEgressProfileByName("LONDON")
+ if err != nil || got.ID != p.ID {
+ t.Fatalf("GetByName: %+v %v", got, err)
+ }
+
+ off := false
+ url := "socks5://127.0.0.1:1080"
+ kind := EgressKindSocks
+ upd, err := store.UpdateEgressProfile(p.ID, UpdateEgressProfile{
+ Enabled: &off, SocksURL: &url, Kind: &kind,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if upd.Enabled || upd.SocksURL != url || upd.Kind != EgressKindSocks {
+ t.Fatalf("update: %+v", upd)
+ }
+
+ if err := store.SetEgressRuntime(p.ID, EgressUp, "", "1.2.3.4", 18080); err != nil {
+ t.Fatal(err)
+ }
+ got, _ = store.GetEgressProfile(p.ID)
+ if got.Status != EgressUp || got.EgressIP != "1.2.3.4" || got.ListenPort != 18080 {
+ t.Fatalf("runtime: %+v", got)
+ }
+
+ list, err := store.ListEgressProfiles()
+ if err != nil || len(list) != 1 {
+ t.Fatalf("list: %v %#v", err, list)
+ }
+
+ if err := store.DeleteEgressProfile(p.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.GetEgressProfile(p.ID); err == nil {
+ t.Fatal("expected missing after delete")
+ }
+}
+
+func TestStreamEgressField(t *testing.T) {
+ dir := t.TempDir()
+ store, err := Open(filepath.Join(dir, "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ st, err := store.CreateStream(CreateStream{Name: "rte1", MPD: "https://x/a.mpd", Egress: "Dublin"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st.Egress != "dublin" || !st.HasEgress || st.HasProxy {
+ t.Fatalf("create egress: %+v has_egress=%v has_proxy=%v", st.Egress, st.HasEgress, st.HasProxy)
+ }
+
+ empty := ""
+ london := "london"
+ st, err = store.PatchStream(st.ID, PatchStream{Egress: &london})
+ if err != nil || st.Egress != "london" {
+ t.Fatalf("patch: %+v %v", st, err)
+ }
+ st, err = store.PatchStream(st.ID, PatchStream{Egress: &empty})
+ if err != nil || st.HasEgress {
+ t.Fatalf("clear egress: %+v %v", st, err)
+ }
+}
diff --git a/apps/streamd/internal/db/events.go b/apps/streamd/internal/db/events.go
new file mode 100644
index 0000000..07bb1e5
--- /dev/null
+++ b/apps/streamd/internal/db/events.go
@@ -0,0 +1,445 @@
+package db
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Event kinds recorded against a stream. Together they are the stream's
+// timeline: who or what acted, and what the supervisor saw happen.
+const (
+ EventCreated = "created"
+ EventUpdated = "updated"
+ EventDeleted = "deleted"
+ EventStarted = "started"
+ EventStopped = "stopped"
+ EventRestarted = "restarted"
+ EventCrashed = "crashed"
+ EventFFRestart = "ff_restart"
+ EventVariantUp = "variant_up"
+ EventVariantDown = "variant_down"
+ EventOnDemandWake = "ondemand_wake"
+ EventIdleStop = "idle_stop"
+ EventScheduledStart = "scheduled_start"
+ EventScheduledStop = "scheduled_stop"
+ EventCredsSet = "creds_set"
+ EventClaimed = "claimed"
+ EventReleased = "released"
+ EventProbe = "probe"
+ EventCaptureStarted = "capture_started"
+ EventCaptureOK = "capture_ok"
+ EventCaptureFailed = "capture_failed"
+)
+
+// Severities.
+const (
+ SevInfo = "info"
+ SevWarn = "warn"
+ SevError = "error"
+)
+
+// ActorSystem is the actor for anything streamd did by itself.
+const ActorSystem = "system"
+
+// StreamEvent is one entry on a stream's timeline.
+type StreamEvent struct {
+ ID int64 `json:"id"`
+ StreamID int64 `json:"stream_id"`
+ StreamName string `json:"stream_name,omitempty"`
+ At string `json:"at"`
+ Kind string `json:"kind"`
+ Severity string `json:"severity"`
+ Actor string `json:"actor"`
+ Message string `json:"message"`
+ // Detail is raw JSON, passed through to the client as-is.
+ Detail json.RawMessage `json:"detail,omitempty"`
+}
+
+// MetricPoint is one health sample for a stream.
+type MetricPoint struct {
+ At string `json:"at"`
+ Health string `json:"health"`
+ BitrateMbps float64 `json:"bitrate_mbps"`
+ PlaylistAgeS float64 `json:"playlist_age_s"`
+ Viewers int `json:"viewers"`
+ // Bucket is 0 for a raw sample and the rollup width in seconds for an
+ // aggregate (60 for the one-minute rollups kept beyond the raw window).
+ Bucket int `json:"bucket,omitempty"`
+}
+
+// Retention windows.
+const (
+ // RawMetricWindow is how long per-tick samples are kept before being
+ // rolled up into one-minute averages.
+ RawMetricWindow = time.Hour
+ // RollupRetention is how long the one-minute rollups are kept.
+ RollupRetention = 7 * 24 * time.Hour
+ // EventRetention is how long a stream's timeline is kept.
+ EventRetention = 90 * 24 * time.Hour
+ rollupBucketS = 60
+)
+
+// history holds the buffered event and metric writes. The store runs on a
+// single database connection shared with every stream write, so neither a
+// 5-second metric tick nor a crash loop may write per occurrence.
+type history struct {
+ mu sync.Mutex
+ events []StreamEvent
+ metrics []bufferedMetric
+}
+
+type bufferedMetric struct {
+ streamID int64
+ point MetricPoint
+}
+
+const maxHistoryBuffer = 20_000
+
+func (s *Store) migrateHistory() error {
+ _, err := s.DB.Exec(`
+CREATE TABLE IF NOT EXISTS stream_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
+ at TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ severity TEXT NOT NULL DEFAULT 'info',
+ actor TEXT NOT NULL DEFAULT '',
+ message TEXT NOT NULL DEFAULT '',
+ detail_json TEXT NOT NULL DEFAULT ''
+);
+CREATE INDEX IF NOT EXISTS idx_events_stream_at ON stream_events(stream_id, id DESC);
+CREATE INDEX IF NOT EXISTS idx_events_at ON stream_events(at);
+
+CREATE TABLE IF NOT EXISTS stream_metrics (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
+ at TEXT NOT NULL,
+ health TEXT NOT NULL DEFAULT '',
+ bitrate_mbps REAL NOT NULL DEFAULT 0,
+ playlist_age_s REAL NOT NULL DEFAULT 0,
+ viewers INTEGER NOT NULL DEFAULT 0,
+ bucket INTEGER NOT NULL DEFAULT 0
+);
+CREATE INDEX IF NOT EXISTS idx_metrics_stream_at ON stream_metrics(stream_id, at);
+`)
+ return err
+}
+
+// AddEvent buffers one timeline entry.
+func (s *Store) AddEvent(e StreamEvent) {
+ if e.StreamID == 0 || e.Kind == "" {
+ return
+ }
+ if e.At == "" {
+ e.At = now()
+ }
+ if e.Severity == "" {
+ e.Severity = SevInfo
+ }
+ if e.Actor == "" {
+ e.Actor = ActorSystem
+ }
+ e.Message = truncateStr(e.Message, 2000)
+ s.hist.mu.Lock()
+ defer s.hist.mu.Unlock()
+ if len(s.hist.events) >= maxHistoryBuffer {
+ s.hist.events = s.hist.events[1:]
+ }
+ s.hist.events = append(s.hist.events, e)
+}
+
+// Eventf is the common case: a system event with a formatted message.
+func (s *Store) Eventf(streamID int64, kind, severity, format string, args ...any) {
+ s.AddEvent(StreamEvent{
+ StreamID: streamID,
+ Kind: kind,
+ Severity: severity,
+ Actor: ActorSystem,
+ Message: fmt.Sprintf(format, args...),
+ })
+}
+
+// AddMetric buffers one health sample.
+func (s *Store) AddMetric(streamID int64, p MetricPoint) {
+ if streamID == 0 {
+ return
+ }
+ if p.At == "" {
+ p.At = now()
+ }
+ s.hist.mu.Lock()
+ defer s.hist.mu.Unlock()
+ if len(s.hist.metrics) >= maxHistoryBuffer {
+ s.hist.metrics = s.hist.metrics[1:]
+ }
+ s.hist.metrics = append(s.hist.metrics, bufferedMetric{streamID: streamID, point: p})
+}
+
+// FlushHistory writes buffered events and metrics in one transaction.
+func (s *Store) FlushHistory() error {
+ s.hist.mu.Lock()
+ events := s.hist.events
+ metrics := s.hist.metrics
+ s.hist.events = nil
+ s.hist.metrics = nil
+ s.hist.mu.Unlock()
+
+ if len(events) == 0 && len(metrics) == 0 {
+ return nil
+ }
+ requeue := func() {
+ s.hist.mu.Lock()
+ s.hist.events = append(events, s.hist.events...)
+ s.hist.metrics = append(metrics, s.hist.metrics...)
+ if len(s.hist.events) > maxHistoryBuffer {
+ s.hist.events = s.hist.events[len(s.hist.events)-maxHistoryBuffer:]
+ }
+ if len(s.hist.metrics) > maxHistoryBuffer {
+ s.hist.metrics = s.hist.metrics[len(s.hist.metrics)-maxHistoryBuffer:]
+ }
+ s.hist.mu.Unlock()
+ }
+
+ tx, err := s.DB.Begin()
+ if err != nil {
+ requeue()
+ return err
+ }
+ if len(events) > 0 {
+ stmt, err := tx.Prepare(`
+INSERT INTO stream_events(stream_id,at,kind,severity,actor,message,detail_json)
+VALUES(?,?,?,?,?,?,?)`)
+ if err != nil {
+ _ = tx.Rollback()
+ requeue()
+ return err
+ }
+ for _, e := range events {
+ // A stream deleted between buffering and flushing takes its
+ // events with it; the foreign key makes that insert fail, which
+ // must not abort the whole batch.
+ _, _ = stmt.Exec(e.StreamID, e.At, e.Kind, e.Severity, e.Actor, e.Message, string(e.Detail))
+ }
+ _ = stmt.Close()
+ }
+ if len(metrics) > 0 {
+ stmt, err := tx.Prepare(`
+INSERT INTO stream_metrics(stream_id,at,health,bitrate_mbps,playlist_age_s,viewers,bucket)
+VALUES(?,?,?,?,?,?,?)`)
+ if err != nil {
+ _ = tx.Rollback()
+ requeue()
+ return err
+ }
+ for _, m := range metrics {
+ _, _ = stmt.Exec(m.streamID, m.point.At, m.point.Health,
+ m.point.BitrateMbps, m.point.PlaylistAgeS, m.point.Viewers, m.point.Bucket)
+ }
+ _ = stmt.Close()
+ }
+ if err := tx.Commit(); err != nil {
+ requeue()
+ return err
+ }
+ return nil
+}
+
+// ListEvents returns a stream's timeline, newest first.
+func (s *Store) ListEvents(streamID int64, limit int, kind, since string) ([]StreamEvent, error) {
+ if limit <= 0 || limit > 1000 {
+ limit = 200
+ }
+ q := `SELECT id,stream_id,at,kind,severity,actor,message,detail_json
+FROM stream_events WHERE stream_id = ?`
+ args := []any{streamID}
+ if k := strings.TrimSpace(kind); k != "" {
+ // Accept a comma-separated kind filter.
+ kinds := strings.Split(k, ",")
+ ph := make([]string, 0, len(kinds))
+ for _, one := range kinds {
+ if one = strings.TrimSpace(one); one != "" {
+ ph = append(ph, "?")
+ args = append(args, one)
+ }
+ }
+ if len(ph) > 0 {
+ q += ` AND kind IN (` + strings.Join(ph, ",") + `)`
+ }
+ }
+ if sv := strings.TrimSpace(since); sv != "" {
+ q += ` AND at >= ?`
+ args = append(args, sv)
+ }
+ q += ` ORDER BY id DESC LIMIT ?`
+ args = append(args, limit)
+ return s.queryEvents(q, args...)
+}
+
+// RecentEvents returns the newest events across every stream, for the
+// dashboard's activity feed.
+func (s *Store) RecentEvents(limit int) ([]StreamEvent, error) {
+ if limit <= 0 || limit > 500 {
+ limit = 50
+ }
+ return s.queryEvents(`
+SELECT e.id, e.stream_id, e.at, e.kind, e.severity, e.actor, e.message, e.detail_json, s.name
+FROM stream_events e LEFT JOIN streams s ON s.id = e.stream_id
+ORDER BY e.id DESC LIMIT ?`, limit)
+}
+
+func (s *Store) queryEvents(q string, args ...any) ([]StreamEvent, error) {
+ rows, err := s.DB.Query(q, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ cols, err := rows.Columns()
+ if err != nil {
+ return nil, err
+ }
+ withName := len(cols) > 8
+ out := []StreamEvent{}
+ for rows.Next() {
+ var e StreamEvent
+ var detail string
+ var name *string
+ dest := []any{&e.ID, &e.StreamID, &e.At, &e.Kind, &e.Severity, &e.Actor, &e.Message, &detail}
+ if withName {
+ dest = append(dest, &name)
+ }
+ if err := rows.Scan(dest...); err != nil {
+ return nil, err
+ }
+ if detail != "" && json.Valid([]byte(detail)) {
+ e.Detail = json.RawMessage(detail)
+ }
+ if name != nil {
+ e.StreamName = *name
+ }
+ out = append(out, e)
+ }
+ return out, rows.Err()
+}
+
+// ListMetrics returns samples for a stream within the window, oldest first.
+func (s *Store) ListMetrics(streamID int64, window time.Duration) ([]MetricPoint, error) {
+ if window <= 0 {
+ window = time.Hour
+ }
+ cutoff := time.Now().UTC().Add(-window).Format(time.RFC3339)
+ rows, err := s.DB.Query(`
+SELECT at,health,bitrate_mbps,playlist_age_s,viewers,bucket
+FROM stream_metrics WHERE stream_id = ? AND at >= ?
+ORDER BY at ASC`, streamID, cutoff)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []MetricPoint{}
+ for rows.Next() {
+ var p MetricPoint
+ if err := rows.Scan(&p.At, &p.Health, &p.BitrateMbps, &p.PlaylistAgeS, &p.Viewers, &p.Bucket); err != nil {
+ return nil, err
+ }
+ out = append(out, p)
+ }
+ return out, rows.Err()
+}
+
+// UptimeRatio is the fraction of samples in the window where the stream was
+// healthy. Returns -1 when there is nothing to judge from.
+func (s *Store) UptimeRatio(streamID int64, window time.Duration) (float64, error) {
+ if window <= 0 {
+ window = 24 * time.Hour
+ }
+ cutoff := time.Now().UTC().Add(-window).Format(time.RFC3339)
+ var total, ok int
+ err := s.DB.QueryRow(`
+SELECT COUNT(*), COALESCE(SUM(CASE WHEN health = 'ok' THEN 1 ELSE 0 END),0)
+FROM stream_metrics WHERE stream_id = ? AND at >= ?`, streamID, cutoff).Scan(&total, &ok)
+ if err != nil {
+ return -1, err
+ }
+ if total == 0 {
+ return -1, nil
+ }
+ return float64(ok) / float64(total), nil
+}
+
+// RollupMetrics collapses raw samples older than RawMetricWindow into
+// one-minute averages, then drops rollups and events past their retention.
+// Keeping every 5-second sample for a week would be millions of rows per
+// stream for no benefit at that zoom level.
+func (s *Store) RollupMetrics() error {
+ rawCutoff := time.Now().UTC().Add(-RawMetricWindow).Format(time.RFC3339)
+ tx, err := s.DB.Begin()
+ if err != nil {
+ return err
+ }
+ // SQLite has no date_trunc, but the timestamps are fixed-width RFC3339
+ // (…THH:MM:SSZ), so truncating to the minute is a substring.
+ if _, err := tx.Exec(`
+INSERT INTO stream_metrics(stream_id,at,health,bitrate_mbps,playlist_age_s,viewers,bucket)
+SELECT stream_id,
+ substr(at, 1, 17) || '00Z',
+ -- the worst health in the minute, so an outage is never averaged away
+ CASE WHEN SUM(CASE WHEN health <> 'ok' THEN 1 ELSE 0 END) > 0 THEN 'degraded' ELSE 'ok' END,
+ AVG(bitrate_mbps), AVG(playlist_age_s), MAX(viewers), ?
+FROM stream_metrics
+WHERE bucket = 0 AND at < ?
+GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
+ _ = tx.Rollback()
+ return err
+ }
+ if _, err := tx.Exec(`DELETE FROM stream_metrics WHERE bucket = 0 AND at < ?`, rawCutoff); err != nil {
+ _ = tx.Rollback()
+ return err
+ }
+ rollupCutoff := time.Now().UTC().Add(-RollupRetention).Format(time.RFC3339)
+ if _, err := tx.Exec(`DELETE FROM stream_metrics WHERE at < ?`, rollupCutoff); err != nil {
+ _ = tx.Rollback()
+ return err
+ }
+ eventCutoff := time.Now().UTC().Add(-EventRetention).Format(time.RFC3339)
+ if _, err := tx.Exec(`DELETE FROM stream_events WHERE at < ?`, eventCutoff); err != nil {
+ _ = tx.Rollback()
+ return err
+ }
+ sessionCutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
+ if _, err := tx.Exec(`
+DELETE FROM stream_sessions
+WHERE ended_at <> '' AND ended_at < ?`, sessionCutoff); err != nil {
+ _ = tx.Rollback()
+ return err
+ }
+ return tx.Commit()
+}
+
+// RunHistoryMaintenance flushes buffered history and prunes on a schedule.
+func (s *Store) RunHistoryMaintenance(stop <-chan struct{}) {
+ flush := time.NewTicker(5 * time.Second)
+ defer flush.Stop()
+ prune := time.NewTicker(15 * time.Minute)
+ defer prune.Stop()
+ for {
+ select {
+ case <-stop:
+ _ = s.FlushHistory()
+ return
+ case <-flush.C:
+ _ = s.FlushHistory()
+ case <-prune.C:
+ _ = s.RollupMetrics()
+ }
+ }
+}
+
+func truncateStr(s string, n int) string {
+ if len(s) <= n {
+ return s
+ }
+ return s[:n]
+}
diff --git a/apps/streamd/internal/db/outputs.go b/apps/streamd/internal/db/outputs.go
new file mode 100644
index 0000000..8905427
--- /dev/null
+++ b/apps/streamd/internal/db/outputs.go
@@ -0,0 +1,285 @@
+package db
+
+import (
+ "encoding/json"
+ "strings"
+)
+
+// Output formats. These are the muxers the packager can be asked to emit for
+// each enabled variant. They are orthogonal to the resolution ladder: the set
+// actually published is variants x outputs.
+const (
+ // FormatHLS is mpegts HLS — the original and only output, kept as the
+ // default so an upgraded install publishes exactly what it did before.
+ FormatHLS = "hls"
+ // FormatCMAF is fMP4/CMAF HLS: init.mp4 plus .m4s segments.
+ FormatCMAF = "hls_fmp4"
+ // FormatDASH is MPEG-DASH.
+ FormatDASH = "dash"
+ // FormatTS is a progressive, endless MPEG-TS stream served from a shared
+ // ring buffer rather than from disk.
+ FormatTS = "mpegts"
+)
+
+// OutputSpec is one configured output format for a stream.
+type OutputSpec struct {
+ ID string `json:"id"`
+ Label string `json:"label"`
+ Format string `json:"format"`
+ Enabled bool `json:"enabled"`
+ // SegmentDuration and ListSize override the stream's packager settings for
+ // this output only. Zero means "inherit".
+ SegmentDuration int `json:"segment_duration,omitempty"`
+ ListSize int `json:"list_size,omitempty"`
+}
+
+// OutputStatus is an OutputSpec as reported by the API.
+type OutputStatus struct {
+ OutputSpec
+}
+
+// PublishLink is one playable endpoint: a variant crossed with an output
+// format, or the ABR master playlist. The dashboard renders one row per link.
+type PublishLink struct {
+ VariantID string `json:"variant_id"`
+ VariantLabel string `json:"variant_label"`
+ OutputID string `json:"output_id"`
+ OutputLabel string `json:"output_label"`
+ Format string `json:"format"`
+ PlayPath string `json:"play_path"`
+ Health string `json:"health,omitempty"`
+ PlaylistAgeS float64 `json:"playlist_age_s,omitempty"`
+ // Master marks the ABR master playlist, which spans every variant.
+ Master bool `json:"master,omitempty"`
+}
+
+// DefaultOutputs is the output set for a new stream: mpegts HLS only. The
+// other formats exist but stay off, so turning one on is always a deliberate
+// act and an upgraded install does not silently start transcoding more.
+func DefaultOutputs() []OutputSpec {
+ return []OutputSpec{
+ {ID: "hls", Label: "HLS", Format: FormatHLS, Enabled: true},
+ {ID: "cmaf", Label: "CMAF", Format: FormatCMAF, Enabled: false},
+ {ID: "dash", Label: "DASH", Format: FormatDASH, Enabled: false},
+ {ID: "ts", Label: "TS", Format: FormatTS, Enabled: false},
+ }
+}
+
+// knownFormats maps a format to its default id and label.
+var knownFormats = map[string]struct{ id, label, container string }{
+ FormatHLS: {"hls", "HLS", "mpegts"},
+ FormatCMAF: {"cmaf", "CMAF", "fmp4"},
+ FormatDASH: {"dash", "DASH", "fmp4"},
+ FormatTS: {"ts", "TS", "mpegts"},
+}
+
+// normalizeFormat maps user input onto a known format, tolerating the shorter
+// aliases the UI and API are likely to send.
+func normalizeFormat(f string) string {
+ switch strings.ToLower(strings.TrimSpace(f)) {
+ case FormatHLS, "m3u8", "hls_mpegts", "hls-ts":
+ return FormatHLS
+ case FormatCMAF, "cmaf", "fmp4", "hls-fmp4":
+ return FormatCMAF
+ case FormatDASH, "mpd":
+ return FormatDASH
+ case FormatTS, "ts", "progressive":
+ return FormatTS
+ }
+ return ""
+}
+
+// ParseOutputsJSON reads outputs_json. Empty or unparseable falls back to the
+// defaults, matching how the variant ladder behaves.
+func ParseOutputsJSON(raw string) []OutputSpec {
+ raw = strings.TrimSpace(raw)
+ if raw == "" || raw == "[]" || raw == "null" {
+ return DefaultOutputs()
+ }
+ var list []OutputSpec
+ if err := json.Unmarshal([]byte(raw), &list); err != nil || len(list) == 0 {
+ return DefaultOutputs()
+ }
+ return NormalizeOutputs(list)
+}
+
+// NormalizeOutputs fills ids and labels, drops unknown formats, de-duplicates
+// by format, and guarantees every known format has an entry so a client can
+// toggle one without having to know the full list.
+func NormalizeOutputs(in []OutputSpec) []OutputSpec {
+ byFormat := map[string]OutputSpec{}
+ for _, o := range in {
+ f := normalizeFormat(o.Format)
+ if f == "" {
+ // Allow a client to identify an output by id alone.
+ f = normalizeFormat(o.ID)
+ }
+ if f == "" {
+ continue
+ }
+ meta := knownFormats[f]
+ o.Format = f
+ if o.ID = slug(o.ID); o.ID == "" {
+ o.ID = meta.id
+ }
+ if strings.TrimSpace(o.Label) == "" {
+ o.Label = meta.label
+ }
+ if o.SegmentDuration < 0 {
+ o.SegmentDuration = 0
+ }
+ if o.ListSize < 0 {
+ o.ListSize = 0
+ }
+ // A later entry for the same format wins, so a partial patch applies
+ // cleanly over the defaults.
+ byFormat[f] = o
+ }
+ out := make([]OutputSpec, 0, len(knownFormats))
+ for _, def := range DefaultOutputs() {
+ if got, ok := byFormat[def.Format]; ok {
+ out = append(out, got)
+ continue
+ }
+ out = append(out, def)
+ }
+ // An output set with nothing enabled would publish nothing at all and
+ // leave the stream unreachable; fall back to HLS.
+ anyOn := false
+ for _, o := range out {
+ if o.Enabled {
+ anyOn = true
+ break
+ }
+ }
+ if !anyOn {
+ for i := range out {
+ if out[i].Format == FormatHLS {
+ out[i].Enabled = true
+ }
+ }
+ }
+ return out
+}
+
+func EncodeOutputsJSON(list []OutputSpec) (string, error) {
+ list = NormalizeOutputs(list)
+ b, err := json.Marshal(list)
+ if err != nil {
+ return "[]", err
+ }
+ return string(b), nil
+}
+
+// EnabledOutputs returns the outputs that should be muxed.
+func EnabledOutputs(list []OutputSpec) []OutputSpec {
+ var out []OutputSpec
+ for _, o := range list {
+ if o.Enabled {
+ out = append(out, o)
+ }
+ }
+ return out
+}
+
+// AttachOutputStatuses builds the outputs array for API responses.
+func AttachOutputStatuses(streamName, outputsJSON string) []OutputStatus {
+ specs := ParseOutputsJSON(outputsJSON)
+ out := make([]OutputStatus, 0, len(specs))
+ for _, o := range specs {
+ out = append(out, OutputStatus{OutputSpec: o})
+ }
+ return out
+}
+
+// VariantDir is the www subdirectory for one variant: the stream name for the
+// source rung, and "-" for every other rung. This is the single
+// definition of that layout; the HLS gate parses it back.
+func VariantDir(streamName, variantID string, height int, audioOnly bool) string {
+ variantID = slug(variantID)
+ if !audioOnly && (height <= 0 || variantID == "" || variantID == SourceVariantID) {
+ return streamName
+ }
+ return streamName + "-" + variantID
+}
+
+// OutputSubPath is the path of an output's playlist relative to its variant
+// directory. The mpegts HLS playlist stays at the root of the directory so
+// existing /hls//index.m3u8 URLs never move.
+func OutputSubPath(format string) string {
+ switch normalizeFormat(format) {
+ case FormatHLS:
+ return "index.m3u8"
+ case FormatCMAF:
+ return "cmaf/index.m3u8"
+ case FormatDASH:
+ return "dash/index.mpd"
+ }
+ return ""
+}
+
+// OutputPlayPath is the URL for one variant x output pair. Progressive TS is
+// served from /live/ because it is a live pipe, not a file on disk.
+func OutputPlayPath(streamName, variantID string, height int, audioOnly bool, format string) string {
+ dir := VariantDir(streamName, variantID, height, audioOnly)
+ if normalizeFormat(format) == FormatTS {
+ return "/live/" + dir + ".ts"
+ }
+ sub := OutputSubPath(format)
+ if sub == "" {
+ return ""
+ }
+ return "/hls/" + dir + "/" + sub
+}
+
+// MasterPlayPath is the ABR master playlist spanning every enabled variant.
+func MasterPlayPath(streamName string) string {
+ return "/hls/" + streamName + "/master.m3u8"
+}
+
+// BuildPublishLinks is the cross product of enabled variants and enabled
+// outputs, with the ABR master first when there is more than one rung to
+// choose between. Health is left empty here and filled by the API layer, which
+// is the part that can see the files on disk.
+func BuildPublishLinks(streamName, variantsJSON, outputsJSON string) []PublishLink {
+ variants := EnabledVariants(ParseVariantsJSON(variantsJSON))
+ outputs := EnabledOutputs(ParseOutputsJSON(outputsJSON))
+ links := make([]PublishLink, 0, len(variants)*len(outputs)+1)
+
+ // The master is only meaningful when HLS is on and there is a real choice.
+ hlsOn := false
+ for _, o := range outputs {
+ if o.Format == FormatHLS || o.Format == FormatCMAF {
+ hlsOn = true
+ break
+ }
+ }
+ if hlsOn && len(variants) > 1 {
+ links = append(links, PublishLink{
+ VariantID: "all",
+ VariantLabel: "ABR",
+ OutputID: "master",
+ OutputLabel: "Master",
+ Format: FormatHLS,
+ PlayPath: MasterPlayPath(streamName),
+ Master: true,
+ })
+ }
+ for _, v := range variants {
+ for _, o := range outputs {
+ p := OutputPlayPath(streamName, v.ID, v.Height, v.AudioOnly, o.Format)
+ if p == "" {
+ continue
+ }
+ links = append(links, PublishLink{
+ VariantID: v.ID,
+ VariantLabel: v.Label,
+ OutputID: o.ID,
+ OutputLabel: o.Label,
+ Format: o.Format,
+ PlayPath: p,
+ })
+ }
+ }
+ return links
+}
diff --git a/apps/streamd/internal/db/schedules.go b/apps/streamd/internal/db/schedules.go
new file mode 100644
index 0000000..ebc478c
--- /dev/null
+++ b/apps/streamd/internal/db/schedules.go
@@ -0,0 +1,459 @@
+package db
+
+import (
+ "database/sql"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
+// Schedule actions and kinds.
+const (
+ ActionStart = "start"
+ ActionStop = "stop"
+
+ KindOnce = "once"
+ KindWeekly = "weekly"
+)
+
+// Schedule is one timed action on a stream: a council meeting at 19:00 every
+// Tuesday, or a one-off match on Saturday.
+type Schedule struct {
+ ID int64 `json:"id"`
+ StreamID int64 `json:"stream_id"`
+ StreamName string `json:"stream_name,omitempty"`
+ Action string `json:"action"`
+ Kind string `json:"kind"`
+ // AtUTC is the moment a "once" schedule fires, RFC3339.
+ AtUTC string `json:"at_utc,omitempty"`
+ // DaysMask is a bitmask of weekdays for a "weekly" schedule, with
+ // Sunday as bit 0 through Saturday as bit 6.
+ DaysMask int `json:"days_mask,omitempty"`
+ // TimeOfDay is "HH:MM" in TZ, for a "weekly" schedule.
+ TimeOfDay string `json:"time_of_day,omitempty"`
+ // TZ is an IANA zone name. Local wall-clock time is what an operator
+ // means by "19:00", so the zone is stored rather than a UTC offset: an
+ // offset would drift by an hour across a DST boundary.
+ TZ string `json:"tz,omitempty"`
+ Enabled bool `json:"enabled"`
+ LastFiredAt string `json:"last_fired_at,omitempty"`
+ NextFireAt string `json:"next_fire_at,omitempty"`
+ CreatedBy string `json:"created_by,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
+ // PrerollFiredFor records the NextFireAt a pre-roll capture was already
+ // requested for, so it happens once per occurrence.
+ PrerollFiredFor string `json:"-"`
+}
+
+func (s *Store) migrateSchedules() error {
+ _, err := s.DB.Exec(`
+CREATE TABLE IF NOT EXISTS schedules (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
+ action TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ at_utc TEXT NOT NULL DEFAULT '',
+ days_mask INTEGER NOT NULL DEFAULT 0,
+ time_of_day TEXT NOT NULL DEFAULT '',
+ tz TEXT NOT NULL DEFAULT 'UTC',
+ enabled INTEGER NOT NULL DEFAULT 1,
+ last_fired_at TEXT NOT NULL DEFAULT '',
+ next_fire_at TEXT NOT NULL DEFAULT '',
+ preroll_fired_for TEXT NOT NULL DEFAULT '',
+ created_by TEXT NOT NULL DEFAULT '',
+ created_at TEXT NOT NULL DEFAULT ''
+);
+CREATE INDEX IF NOT EXISTS idx_schedules_next ON schedules(enabled, next_fire_at);
+CREATE INDEX IF NOT EXISTS idx_schedules_stream ON schedules(stream_id);
+`)
+ return err
+}
+
+// Validate checks a schedule and normalises its fields.
+func (sc *Schedule) Validate() error {
+ sc.Action = strings.ToLower(strings.TrimSpace(sc.Action))
+ switch sc.Action {
+ case ActionStart, ActionStop:
+ default:
+ return fmt.Errorf("action must be %q or %q", ActionStart, ActionStop)
+ }
+ sc.Kind = strings.ToLower(strings.TrimSpace(sc.Kind))
+ if sc.TZ = strings.TrimSpace(sc.TZ); sc.TZ == "" {
+ sc.TZ = "UTC"
+ }
+ if _, err := time.LoadLocation(sc.TZ); err != nil {
+ return fmt.Errorf("unknown timezone %q", sc.TZ)
+ }
+ switch sc.Kind {
+ case KindOnce:
+ t, err := ParseScheduleTime(sc.AtUTC, sc.TZ)
+ if err != nil {
+ return fmt.Errorf("at_utc: %w", err)
+ }
+ sc.AtUTC = t.UTC().Format(time.RFC3339)
+ case KindWeekly:
+ if _, _, err := parseHHMM(sc.TimeOfDay); err != nil {
+ return fmt.Errorf("time_of_day: %w", err)
+ }
+ if sc.DaysMask&0x7F == 0 {
+ return errors.New("days_mask must select at least one weekday")
+ }
+ sc.DaysMask &= 0x7F
+ default:
+ return fmt.Errorf("kind must be %q or %q", KindOnce, KindWeekly)
+ }
+ return nil
+}
+
+// ParseScheduleTime accepts an RFC3339 instant, or a local "YYYY-MM-DD HH:MM"
+// interpreted in tz — which is how a person types a meeting time.
+func ParseScheduleTime(s, tz string) (time.Time, error) {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return time.Time{}, errors.New("a time is required")
+ }
+ if t, err := time.Parse(time.RFC3339, s); err == nil {
+ return t, nil
+ }
+ loc, err := time.LoadLocation(tz)
+ if err != nil {
+ loc = time.UTC
+ }
+ for _, layout := range []string{"2006-01-02 15:04", "2006-01-02T15:04", "2006-01-02 15:04:05"} {
+ if t, err := time.ParseInLocation(layout, s, loc); err == nil {
+ return t, nil
+ }
+ }
+ return time.Time{}, fmt.Errorf("could not parse %q as a time", s)
+}
+
+func parseHHMM(s string) (hour, minute int, err error) {
+ s = strings.TrimSpace(s)
+ t, err := time.Parse("15:04", s)
+ if err != nil {
+ return 0, 0, fmt.Errorf("want HH:MM, got %q", s)
+ }
+ return t.Hour(), t.Minute(), nil
+}
+
+// NextFire computes the next time this schedule should fire, strictly after
+// the given moment. The zero time means "never again".
+func (sc Schedule) NextFire(after time.Time) time.Time {
+ if !sc.Enabled {
+ return time.Time{}
+ }
+ switch sc.Kind {
+ case KindOnce:
+ t, err := time.Parse(time.RFC3339, sc.AtUTC)
+ if err != nil || !t.After(after) {
+ return time.Time{}
+ }
+ return t.UTC()
+ case KindWeekly:
+ hour, minute, err := parseHHMM(sc.TimeOfDay)
+ if err != nil {
+ return time.Time{}
+ }
+ loc, err := time.LoadLocation(sc.TZ)
+ if err != nil {
+ loc = time.UTC
+ }
+ // Walk forward day by day in the target zone. Constructing the time
+ // per local day is what makes this correct across a DST change: the
+ // event stays at 19:00 wall clock rather than drifting an hour.
+ local := after.In(loc)
+ for i := 0; i <= 8; i++ {
+ day := local.AddDate(0, 0, i)
+ if sc.DaysMask&(1< 0 {
+ q += ` WHERE sc.stream_id = ?`
+ args = append(args, streamID)
+ }
+ q += ` ORDER BY sc.next_fire_at = '', sc.next_fire_at, sc.id`
+ rows, err := s.DB.Query(q, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []Schedule{}
+ for rows.Next() {
+ sc, err := scanSchedule(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, sc)
+ }
+ return out, rows.Err()
+}
+
+// UpcomingSchedules lists the soonest pending occurrences across all streams.
+func (s *Store) UpcomingSchedules(limit int) ([]Schedule, error) {
+ if limit <= 0 || limit > 200 {
+ limit = 20
+ }
+ rows, err := s.DB.Query(scheduleSelect+`
+WHERE sc.enabled = 1 AND sc.next_fire_at <> '' AND sc.next_fire_at >= ?
+ORDER BY sc.next_fire_at LIMIT ?`, now(), limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []Schedule{}
+ for rows.Next() {
+ sc, err := scanSchedule(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, sc)
+ }
+ return out, rows.Err()
+}
+
+// DueSchedules returns enabled schedules whose moment has arrived.
+func (s *Store) DueSchedules(at time.Time) ([]Schedule, error) {
+ rows, err := s.DB.Query(scheduleSelect+`
+WHERE sc.enabled = 1 AND sc.next_fire_at <> '' AND sc.next_fire_at <= ?
+ORDER BY sc.next_fire_at`, at.UTC().Format(time.RFC3339))
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []Schedule{}
+ for rows.Next() {
+ sc, err := scanSchedule(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, sc)
+ }
+ return out, rows.Err()
+}
+
+// PendingPreroll returns start schedules firing within the lead time, whose
+// pre-roll has not been requested yet.
+func (s *Store) PendingPreroll(at time.Time, lead time.Duration) ([]Schedule, error) {
+ until := at.Add(lead).UTC().Format(time.RFC3339)
+ rows, err := s.DB.Query(scheduleSelect+`
+WHERE sc.enabled = 1 AND sc.action = 'start' AND sc.next_fire_at <> ''
+ AND sc.next_fire_at <= ? AND sc.next_fire_at > ?
+ AND sc.preroll_fired_for <> sc.next_fire_at
+ORDER BY sc.next_fire_at`, until, at.UTC().Format(time.RFC3339))
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []Schedule{}
+ for rows.Next() {
+ sc, err := scanSchedule(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, sc)
+ }
+ return out, rows.Err()
+}
+
+// MarkPrerolled records that a pre-roll was requested for this occurrence.
+func (s *Store) MarkPrerolled(id int64, forTime string) error {
+ _, err := s.DB.Exec(`UPDATE schedules SET preroll_fired_for=? WHERE id=?`, forTime, id)
+ return err
+}
+
+// MarkFired advances a schedule after it has run. A "once" schedule is
+// disabled, since its moment has passed.
+func (s *Store) MarkFired(sc Schedule, at time.Time) error {
+ next := sc.NextFire(at.Add(time.Second))
+ nextStr := ""
+ if !next.IsZero() {
+ nextStr = next.Format(time.RFC3339)
+ }
+ enabled := 1
+ if sc.Kind == KindOnce || nextStr == "" {
+ enabled = 0
+ }
+ _, err := s.DB.Exec(`
+UPDATE schedules SET last_fired_at=?, next_fire_at=?, enabled=? WHERE id=?`,
+ at.UTC().Format(time.RFC3339), nextStr, enabled, sc.ID)
+ return err
+}
+
+// PatchSchedule updates a schedule and recomputes when it next fires.
+func (s *Store) PatchSchedule(id int64, in Schedule, setEnabled *bool) (Schedule, error) {
+ cur, err := s.GetSchedule(id)
+ if err != nil {
+ return Schedule{}, err
+ }
+ if in.Action != "" {
+ cur.Action = in.Action
+ }
+ if in.Kind != "" {
+ cur.Kind = in.Kind
+ }
+ if in.AtUTC != "" {
+ cur.AtUTC = in.AtUTC
+ }
+ if in.TimeOfDay != "" {
+ cur.TimeOfDay = in.TimeOfDay
+ }
+ if in.TZ != "" {
+ cur.TZ = in.TZ
+ }
+ if in.DaysMask != 0 {
+ cur.DaysMask = in.DaysMask
+ }
+ if setEnabled != nil {
+ cur.Enabled = *setEnabled
+ }
+ if err := cur.Validate(); err != nil {
+ return Schedule{}, err
+ }
+ next := cur.NextFire(time.Now().UTC())
+ nextStr := ""
+ if !next.IsZero() {
+ nextStr = next.Format(time.RFC3339)
+ }
+ en := 0
+ if cur.Enabled {
+ en = 1
+ }
+ _, err = s.DB.Exec(`
+UPDATE schedules SET action=?, kind=?, at_utc=?, days_mask=?, time_of_day=?, tz=?,
+ enabled=?, next_fire_at=?, preroll_fired_for='' WHERE id=?`,
+ cur.Action, cur.Kind, cur.AtUTC, cur.DaysMask, cur.TimeOfDay, cur.TZ,
+ en, nextStr, id)
+ if err != nil {
+ return Schedule{}, err
+ }
+ return s.GetSchedule(id)
+}
+
+func (s *Store) DeleteSchedule(id int64) error {
+ res, err := s.DB.Exec(`DELETE FROM schedules WHERE id=?`, id)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n == 0 {
+ return errors.New("schedule not found")
+ }
+ return nil
+}
+
+// RecomputeNextFire refreshes next_fire_at for every enabled schedule, called
+// at startup so a server that was down over an occurrence does not fire a
+// stale one and then sit with a past timestamp.
+func (s *Store) RecomputeNextFire() error {
+ list, err := s.ListSchedules(0)
+ if err != nil {
+ return err
+ }
+ nowT := time.Now().UTC()
+ for _, sc := range list {
+ if !sc.Enabled {
+ continue
+ }
+ next := sc.NextFire(nowT)
+ nextStr := ""
+ if !next.IsZero() {
+ nextStr = next.Format(time.RFC3339)
+ }
+ enabled := 1
+ if nextStr == "" {
+ // A "once" schedule whose moment has passed is spent.
+ enabled = 0
+ }
+ _, _ = s.DB.Exec(`UPDATE schedules SET next_fire_at=?, enabled=? WHERE id=?`,
+ nextStr, enabled, sc.ID)
+ }
+ return nil
+}
+
+// WeekdayMask builds a days_mask from weekday numbers (0 = Sunday).
+func WeekdayMask(days ...int) int {
+ m := 0
+ for _, d := range days {
+ if d >= 0 && d <= 6 {
+ m |= 1 << uint(d)
+ }
+ }
+ return m
+}
+
+// DaysLabel renders a mask as "Mon,Tue".
+func DaysLabel(mask int) string {
+ names := []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
+ var out []string
+ for i := range names {
+ if mask&(1< 48*time.Hour {
+ t.Errorf("next fire %s is not within two days of %s", got, mon)
+ }
+ // From Tuesday 19:00:01 it must roll to the following week, not fire
+ // again the same evening.
+ justAfter := time.Date(2026, 3, 10, 19, 0, 1, 0, time.UTC)
+ next := sc.NextFire(justAfter)
+ if next.Weekday() != time.Tuesday {
+ t.Errorf("next = %s, want the following Tuesday", next)
+ }
+ if next.Sub(justAfter) < 6*24*time.Hour {
+ t.Errorf("next = %s, should be about a week after %s", next, justAfter)
+ }
+}
+
+// A weekly event is a wall-clock commitment: a 19:00 meeting stays at 19:00
+// local across a DST change. Storing a fixed UTC offset would drift an hour.
+func TestNextFireWeeklyAcrossDST(t *testing.T) {
+ const zone = "Europe/Dublin"
+ loc, err := time.LoadLocation(zone)
+ if err != nil {
+ t.Skipf("zone data unavailable: %v", err)
+ }
+ sc := Schedule{
+ Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00",
+ DaysMask: WeekdayMask(int(time.Sunday)), TZ: zone, Enabled: true,
+ }
+ // Ireland springs forward at 01:00 on Sunday 29 March 2026. Starting on
+ // the 21st puts the first occurrence on 22 March (still GMT) and the
+ // second on 29 March (already IST), so the pair straddles the change.
+ beforeChange := time.Date(2026, 3, 21, 12, 0, 0, 0, loc)
+ first := sc.NextFire(beforeChange)
+ afterChange := sc.NextFire(first.Add(time.Second))
+ if first.In(loc).Day() != 22 || afterChange.In(loc).Day() != 29 {
+ t.Fatalf("test set-up is wrong: occurrences are %s and %s, want 22 and 29 March",
+ first.In(loc), afterChange.In(loc))
+ }
+
+ // Both occurrences must read 19:00 in local time...
+ for _, got := range []time.Time{first, afterChange} {
+ local := got.In(loc)
+ if local.Hour() != 19 || local.Minute() != 0 {
+ t.Errorf("occurrence %s is %02d:%02d local, want 19:00", got, local.Hour(), local.Minute())
+ }
+ }
+ // ...which means their UTC hours differ across the change. That
+ // difference is the proof the zone is being honoured.
+ if first.UTC().Hour() == afterChange.UTC().Hour() {
+ t.Errorf("UTC hour did not shift across the DST boundary (%s vs %s) — "+
+ "the schedule is drifting rather than tracking local time",
+ first.UTC(), afterChange.UTC())
+ }
+}
+
+func TestNextFireWeeklyMultipleDays(t *testing.T) {
+ sc := Schedule{
+ Action: ActionStart, Kind: KindWeekly, TimeOfDay: "08:30",
+ DaysMask: WeekdayMask(int(time.Monday), int(time.Wednesday), int(time.Friday)),
+ TZ: "UTC", Enabled: true,
+ }
+ // From Monday 09:00, the next is Wednesday.
+ from := time.Date(2026, 3, 9, 9, 0, 0, 0, time.UTC)
+ got := sc.NextFire(from)
+ if got.Weekday() != time.Wednesday || got.Hour() != 8 || got.Minute() != 30 {
+ t.Errorf("got %s, want Wednesday 08:30", got)
+ }
+}
+
+func TestScheduleCRUDAndFiring(t *testing.T) {
+ store := newStore(t)
+ st, err := store.CreateStream(CreateStream{Name: "council", MPD: "https://x/a.mpd"})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // A one-off two minutes out.
+ at := time.Now().UTC().Add(2 * time.Minute).Truncate(time.Second)
+ sc, err := store.CreateSchedule(Schedule{
+ StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
+ AtUTC: at.Format(time.RFC3339), CreatedBy: "tester",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if sc.NextFireAt == "" {
+ t.Error("a new schedule should have a next_fire_at")
+ }
+ if sc.StreamName != "council" {
+ t.Errorf("stream name = %q", sc.StreamName)
+ }
+
+ // Not due yet.
+ if due, err := store.DueSchedules(time.Now().UTC()); err != nil || len(due) != 0 {
+ t.Fatalf("should not be due yet: %v %d", err, len(due))
+ }
+ // Due once its moment arrives.
+ due, err := store.DueSchedules(at.Add(time.Second))
+ if err != nil || len(due) != 1 {
+ t.Fatalf("want 1 due, got %d (%v)", len(due), err)
+ }
+
+ // Firing a once-schedule spends it.
+ if err := store.MarkFired(due[0], at); err != nil {
+ t.Fatal(err)
+ }
+ after, err := store.GetSchedule(sc.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if after.Enabled {
+ t.Error("a fired once-schedule should be disabled")
+ }
+ if after.LastFiredAt == "" {
+ t.Error("last_fired_at should be set")
+ }
+ if later, _ := store.DueSchedules(at.Add(time.Hour)); len(later) != 0 {
+ t.Error("a spent schedule must not fire twice")
+ }
+
+ // A weekly schedule keeps going.
+ weekly, err := store.CreateSchedule(Schedule{
+ StreamID: st.ID, Action: ActionStart, Kind: KindWeekly,
+ TimeOfDay: "19:00", DaysMask: WeekdayMask(0, 1, 2, 3, 4, 5, 6), TZ: "UTC",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ firstNext := weekly.NextFireAt
+ firedAt, err := time.Parse(time.RFC3339, firstNext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := store.MarkFired(weekly, firedAt); err != nil {
+ t.Fatal(err)
+ }
+ again, _ := store.GetSchedule(weekly.ID)
+ if !again.Enabled {
+ t.Error("a weekly schedule should stay enabled after firing")
+ }
+ if again.NextFireAt == "" || again.NextFireAt == firstNext {
+ t.Errorf("weekly next_fire_at should have advanced, was %q now %q", firstNext, again.NextFireAt)
+ }
+
+ // Listing and deleting.
+ list, err := store.ListSchedules(st.ID)
+ if err != nil || len(list) != 2 {
+ t.Fatalf("want 2 schedules, got %d (%v)", len(list), err)
+ }
+ if err := store.DeleteSchedule(weekly.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.DeleteSchedule(weekly.ID); err == nil {
+ t.Error("deleting twice should report not found")
+ }
+}
+
+func TestSchedulePrerollOnlyOncePerOccurrence(t *testing.T) {
+ store := newStore(t)
+ st, _ := store.CreateStream(CreateStream{Name: "match", MPD: "https://x/a.mpd"})
+ at := time.Now().UTC().Add(2 * time.Minute)
+ sc, err := store.CreateSchedule(Schedule{
+ StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
+ AtUTC: at.Format(time.RFC3339),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ nowT := time.Now().UTC()
+ pending, err := store.PendingPreroll(nowT, 5*time.Minute)
+ if err != nil || len(pending) != 1 {
+ t.Fatalf("want 1 pre-roll pending, got %d (%v)", len(pending), err)
+ }
+ if err := store.MarkPrerolled(sc.ID, pending[0].NextFireAt); err != nil {
+ t.Fatal(err)
+ }
+ // Already requested: must not ask again every tick.
+ pending, err = store.PendingPreroll(nowT, 5*time.Minute)
+ if err != nil || len(pending) != 0 {
+ t.Fatalf("pre-roll should not repeat, got %d (%v)", len(pending), err)
+ }
+
+ // A stop schedule never pre-rolls: there is nothing to prepare.
+ _, err = store.CreateSchedule(Schedule{
+ StreamID: st.ID, Action: ActionStop, Kind: KindOnce,
+ AtUTC: at.Format(time.RFC3339),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ pending, _ = store.PendingPreroll(nowT, 5*time.Minute)
+ for _, p := range pending {
+ if p.Action == ActionStop {
+ t.Error("a stop schedule should not be pre-rolled")
+ }
+ }
+}
+
+// A server that was down over an occurrence must not fire it late.
+func TestRecomputeNextFireDropsMissedOnce(t *testing.T) {
+ store := newStore(t)
+ st, _ := store.CreateStream(CreateStream{Name: "gone", MPD: "https://x/a.mpd"})
+ past := time.Now().UTC().Add(-2 * time.Hour)
+ sc, err := store.CreateSchedule(Schedule{
+ StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
+ AtUTC: past.Add(time.Hour).Format(time.RFC3339),
+ })
+ if err != nil {
+ // CreateSchedule accepts a past time; NextFire just yields nothing.
+ t.Fatal(err)
+ }
+ if err := store.RecomputeNextFire(); err != nil {
+ t.Fatal(err)
+ }
+ got, _ := store.GetSchedule(sc.ID)
+ if got.Enabled {
+ t.Error("a missed once-schedule should be disabled, not fired late")
+ }
+ if due, _ := store.DueSchedules(time.Now().UTC()); len(due) != 0 {
+ t.Error("a missed schedule must not be due")
+ }
+}
+
+func TestUpcomingSchedulesOrdering(t *testing.T) {
+ store := newStore(t)
+ st, _ := store.CreateStream(CreateStream{Name: "events", MPD: "https://x/a.mpd"})
+ far := time.Now().UTC().Add(3 * time.Hour)
+ near := time.Now().UTC().Add(10 * time.Minute)
+ if _, err := store.CreateSchedule(Schedule{StreamID: st.ID, Action: ActionStart,
+ Kind: KindOnce, AtUTC: far.Format(time.RFC3339)}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.CreateSchedule(Schedule{StreamID: st.ID, Action: ActionStart,
+ Kind: KindOnce, AtUTC: near.Format(time.RFC3339)}); err != nil {
+ t.Fatal(err)
+ }
+ up, err := store.UpcomingSchedules(10)
+ if err != nil || len(up) != 2 {
+ t.Fatalf("want 2 upcoming, got %d (%v)", len(up), err)
+ }
+ if up[0].NextFireAt > up[1].NextFireAt {
+ t.Errorf("upcoming should be soonest first, got %q then %q", up[0].NextFireAt, up[1].NextFireAt)
+ }
+}
+
+// Deleting a stream must take its schedules with it, or the scheduler would
+// keep trying to start something that no longer exists.
+func TestSchedulesCascadeOnStreamDelete(t *testing.T) {
+ store := newStore(t)
+ st, _ := store.CreateStream(CreateStream{Name: "temp", MPD: "https://x/a.mpd"})
+ if _, err := store.CreateSchedule(Schedule{
+ StreamID: st.ID, Action: ActionStart, Kind: KindWeekly,
+ TimeOfDay: "19:00", DaysMask: WeekdayMask(1), TZ: "UTC",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.DeleteStream(st.ID); err != nil {
+ t.Fatal(err)
+ }
+ list, err := store.ListSchedules(st.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(list) != 0 {
+ t.Errorf("schedules outlived their stream: %+v", list)
+ }
+}
+
+func TestDaysLabel(t *testing.T) {
+ if got := DaysLabel(WeekdayMask(1, 3, 5)); got != "Mon,Wed,Fri" {
+ t.Errorf("got %q", got)
+ }
+ if got := DaysLabel(0); got != "" {
+ t.Errorf("empty mask = %q", got)
+ }
+ if got := DaysLabel(WeekdayMask(0, 6)); got != "Sun,Sat" {
+ t.Errorf("got %q", got)
+ }
+}
diff --git a/apps/streamd/internal/db/sessions.go b/apps/streamd/internal/db/sessions.go
new file mode 100644
index 0000000..12a3a96
--- /dev/null
+++ b/apps/streamd/internal/db/sessions.go
@@ -0,0 +1,211 @@
+package db
+
+import (
+ "database/sql"
+ "fmt"
+ "time"
+)
+
+// Session end reasons recorded when a run closes.
+const (
+ SessionStopped = "stopped"
+ SessionNREExit = "nre_exit"
+ SessionOrphaned = "orphaned"
+ SessionTimeout = "timeout"
+)
+
+// SessionRetention is how long closed run history is kept.
+const SessionRetention = 90 * 24 * time.Hour
+
+// StreamSession is one media worker run: start → stop/crash with a duration.
+type StreamSession struct {
+ ID int64 `json:"id"`
+ StreamID int64 `json:"stream_id"`
+ StreamName string `json:"stream_name,omitempty"`
+ StreamTitle string `json:"stream_title,omitempty"`
+ StartedAt string `json:"started_at"`
+ EndedAt string `json:"ended_at,omitempty"`
+ DurationS float64 `json:"duration_s"`
+ EndReason string `json:"end_reason,omitempty"`
+ HealthAtEnd string `json:"health_at_end,omitempty"`
+}
+
+func (s *Store) migrateSessions() error {
+ _, err := s.DB.Exec(`
+CREATE TABLE IF NOT EXISTS stream_sessions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
+ started_at TEXT NOT NULL,
+ ended_at TEXT NOT NULL DEFAULT '',
+ duration_s REAL NOT NULL DEFAULT 0,
+ end_reason TEXT NOT NULL DEFAULT '',
+ health_at_end TEXT NOT NULL DEFAULT ''
+);
+CREATE INDEX IF NOT EXISTS idx_sessions_stream_started ON stream_sessions(stream_id, started_at DESC);
+CREATE INDEX IF NOT EXISTS idx_sessions_ended ON stream_sessions(ended_at DESC);
+CREATE INDEX IF NOT EXISTS idx_sessions_open ON stream_sessions(stream_id, ended_at);
+`)
+ return err
+}
+
+// OpenSession records a new run for streamID. Any previously open row for the
+// same stream is closed as orphaned (e.g. process crash without a clean stop).
+func (s *Store) OpenSession(streamID int64) (int64, error) {
+ if streamID == 0 {
+ return 0, fmt.Errorf("stream id required")
+ }
+ _ = s.CloseOpenSessions(streamID, SessionOrphaned, "stopped")
+ started := now()
+ res, err := s.DB.Exec(`
+INSERT INTO stream_sessions(stream_id, started_at)
+VALUES(?, ?)`, streamID, started)
+ if err != nil {
+ return 0, err
+ }
+ return res.LastInsertId()
+}
+
+// CloseSession ends one open session by id. Already-closed rows are a no-op.
+func (s *Store) CloseSession(id int64, reason, healthAtEnd string) error {
+ if id == 0 {
+ return nil
+ }
+ var started string
+ var ended string
+ err := s.DB.QueryRow(`SELECT started_at, ended_at FROM stream_sessions WHERE id=?`, id).
+ Scan(&started, &ended)
+ if err == sql.ErrNoRows {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if ended != "" {
+ return nil
+ }
+ endedAt := now()
+ dur := durationSeconds(started, endedAt)
+ if reason == "" {
+ reason = SessionStopped
+ }
+ _, err = s.DB.Exec(`
+UPDATE stream_sessions
+SET ended_at=?, duration_s=?, end_reason=?, health_at_end=?
+WHERE id=? AND ended_at=''`,
+ endedAt, dur, reason, healthAtEnd, id)
+ return err
+}
+
+// CloseOpenSessions ends every open session for a stream.
+func (s *Store) CloseOpenSessions(streamID int64, reason, healthAtEnd string) error {
+ if streamID == 0 {
+ return nil
+ }
+ rows, err := s.DB.Query(`
+SELECT id FROM stream_sessions WHERE stream_id=? AND ended_at=''`, streamID)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ var ids []int64
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ return err
+ }
+ ids = append(ids, id)
+ }
+ for _, id := range ids {
+ if err := s.CloseSession(id, reason, healthAtEnd); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// ListRecentSessions returns the newest closed runs across all streams.
+func (s *Store) ListRecentSessions(limit int) ([]StreamSession, error) {
+ if limit <= 0 {
+ limit = 50
+ }
+ if limit > 200 {
+ limit = 200
+ }
+ rows, err := s.DB.Query(`
+SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
+ ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
+FROM stream_sessions ss
+LEFT JOIN streams st ON st.id = ss.stream_id
+WHERE ss.ended_at <> ''
+ORDER BY ss.ended_at DESC, ss.id DESC
+LIMIT ?`, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []StreamSession
+ for rows.Next() {
+ var ss StreamSession
+ if err := rows.Scan(
+ &ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
+ &ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
+ ); err != nil {
+ return nil, err
+ }
+ out = append(out, ss)
+ }
+ return out, rows.Err()
+}
+
+// ListStreamSessions returns recent closed runs for one stream.
+func (s *Store) ListStreamSessions(streamID int64, limit int) ([]StreamSession, error) {
+ if limit <= 0 {
+ limit = 50
+ }
+ rows, err := s.DB.Query(`
+SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
+ ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
+FROM stream_sessions ss
+LEFT JOIN streams st ON st.id = ss.stream_id
+WHERE ss.stream_id=? AND ss.ended_at <> ''
+ORDER BY ss.ended_at DESC, ss.id DESC
+LIMIT ?`, streamID, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []StreamSession
+ for rows.Next() {
+ var ss StreamSession
+ if err := rows.Scan(
+ &ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
+ &ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
+ ); err != nil {
+ return nil, err
+ }
+ out = append(out, ss)
+ }
+ return out, rows.Err()
+}
+
+// PruneSessions drops closed sessions older than SessionRetention.
+func (s *Store) PruneSessions() error {
+ cutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
+ _, err := s.DB.Exec(`
+DELETE FROM stream_sessions
+WHERE ended_at <> '' AND ended_at < ?`, cutoff)
+ return err
+}
+
+func durationSeconds(startedAt, endedAt string) float64 {
+ start, err1 := time.Parse(time.RFC3339, startedAt)
+ end, err2 := time.Parse(time.RFC3339, endedAt)
+ if err1 != nil || err2 != nil {
+ return 0
+ }
+ d := end.Sub(start).Seconds()
+ if d < 0 {
+ return 0
+ }
+ return d
+}
diff --git a/apps/streamd/internal/db/sessions_test.go b/apps/streamd/internal/db/sessions_test.go
new file mode 100644
index 0000000..f6f26b6
--- /dev/null
+++ b/apps/streamd/internal/db/sessions_test.go
@@ -0,0 +1,114 @@
+package db
+
+import (
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestStreamSessionsOpenCloseList(t *testing.T) {
+ store, err := Open(filepath.Join(t.TempDir(), "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ st, err := store.CreateStream(CreateStream{
+ Name: "bbc1", Title: "BBC One", MPD: "https://example.test/a.mpd",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ id1, err := store.OpenSession(st.ID)
+ if err != nil || id1 == 0 {
+ t.Fatalf("OpenSession: id=%d err=%v", id1, err)
+ }
+ time.Sleep(20 * time.Millisecond)
+ if err := store.CloseSession(id1, SessionStopped, "stopped"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Second open should orphan-close nothing (already closed) and create a new row.
+ id2, err := store.OpenSession(st.ID)
+ if err != nil || id2 == 0 || id2 == id1 {
+ t.Fatalf("second OpenSession: id=%d (first=%d) err=%v", id2, id1, err)
+ }
+ if err := store.CloseSession(id2, SessionNREExit, "down"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Idempotent close.
+ if err := store.CloseSession(id2, SessionStopped, "stopped"); err != nil {
+ t.Fatal(err)
+ }
+
+ recent, err := store.ListRecentSessions(10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(recent) != 2 {
+ t.Fatalf("recent len=%d want 2", len(recent))
+ }
+ // Newest ended first.
+ if recent[0].ID != id2 || recent[0].EndReason != SessionNREExit {
+ t.Fatalf("newest = %+v", recent[0])
+ }
+ if recent[1].ID != id1 || recent[1].EndReason != SessionStopped {
+ t.Fatalf("older = %+v", recent[1])
+ }
+ if recent[0].StreamName != "bbc1" || recent[0].DurationS < 0 {
+ t.Fatalf("row fields: %+v", recent[0])
+ }
+
+ per, err := store.ListStreamSessions(st.ID, 5)
+ if err != nil || len(per) != 2 {
+ t.Fatalf("ListStreamSessions: len=%d err=%v", len(per), err)
+ }
+}
+
+func TestOpenSessionClosesOrphan(t *testing.T) {
+ store, err := Open(filepath.Join(t.TempDir(), "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ st, err := store.CreateStream(CreateStream{
+ Name: "rte1", MPD: "https://example.test/b.mpd",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ orphan, err := store.OpenSession(st.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ next, err := store.OpenSession(st.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if next == orphan {
+ t.Fatal("expected a new session id")
+ }
+
+ var ended, reason string
+ if err := store.DB.QueryRow(
+ `SELECT ended_at, end_reason FROM stream_sessions WHERE id=?`, orphan,
+ ).Scan(&ended, &reason); err != nil {
+ t.Fatal(err)
+ }
+ if ended == "" || reason != SessionOrphaned {
+ t.Fatalf("orphan close: ended=%q reason=%q", ended, reason)
+ }
+
+ _ = store.CloseSession(next, SessionStopped, "stopped")
+ recent, err := store.ListRecentSessions(10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(recent) != 2 {
+ t.Fatalf("want 2 closed sessions, got %d", len(recent))
+ }
+}
diff --git a/apps/streamd/internal/db/settings.go b/apps/streamd/internal/db/settings.go
new file mode 100644
index 0000000..1faf555
--- /dev/null
+++ b/apps/streamd/internal/db/settings.go
@@ -0,0 +1,179 @@
+package db
+
+import (
+ "encoding/json"
+ "strconv"
+ "strings"
+)
+
+// Setting keys. These are the installation-wide defaults that sit at the
+// bottom of the resolution chain: stream row -> app module -> these -> the
+// compiled-in defaults.
+const (
+ SettingHLSTime = "hls_time"
+ SettingHLSListSize = "hls_list_size"
+ SettingLiveWait = "live_wait"
+ SettingTSReadyBytes = "ts_ready_bytes"
+ SettingIdleTimeoutS = "idle_timeout_s"
+ SettingDefaultOutputs = "default_outputs"
+ SettingOnDemand = "default_on_demand"
+)
+
+func (s *Store) migrateSettings() error {
+ _, err := s.DB.Exec(`
+CREATE TABLE IF NOT EXISTS settings (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL DEFAULT '',
+ updated_at TEXT NOT NULL DEFAULT ''
+);`)
+ return err
+}
+
+// GetSettings returns every stored setting.
+func (s *Store) GetSettings() (map[string]string, error) {
+ rows, err := s.DB.Query(`SELECT key, value FROM settings`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := map[string]string{}
+ for rows.Next() {
+ var k, v string
+ if err := rows.Scan(&k, &v); err != nil {
+ return nil, err
+ }
+ out[k] = v
+ }
+ return out, rows.Err()
+}
+
+// SetSettings upserts the given keys in one transaction. A key with an empty
+// value is deleted, which returns it to the built-in default.
+func (s *Store) SetSettings(in map[string]string) error {
+ tx, err := s.DB.Begin()
+ if err != nil {
+ return err
+ }
+ for k, v := range in {
+ k = strings.TrimSpace(k)
+ if k == "" {
+ continue
+ }
+ if strings.TrimSpace(v) == "" {
+ if _, err := tx.Exec(`DELETE FROM settings WHERE key=?`, k); err != nil {
+ _ = tx.Rollback()
+ return err
+ }
+ continue
+ }
+ if _, err := tx.Exec(`
+INSERT INTO settings(key,value,updated_at) VALUES(?,?,?)
+ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at`,
+ k, v, now()); err != nil {
+ _ = tx.Rollback()
+ return err
+ }
+ }
+ return tx.Commit()
+}
+
+// PackagerSettings are the knobs that shape the ffmpeg command line. A zero
+// field means "not set at this level", so the next level down applies.
+type PackagerSettings struct {
+ HLSTime int `json:"hls_time,omitempty"`
+ HLSListSize int `json:"hls_list_size,omitempty"`
+ LiveWait int `json:"live_wait,omitempty"`
+ TSReadyBytes int `json:"ts_ready_bytes,omitempty"`
+}
+
+// ParsePackagerSettings reads a stream's settings_json. Unparseable JSON
+// yields the zero value, which simply defers to the levels below.
+func ParsePackagerSettings(raw string) PackagerSettings {
+ var p PackagerSettings
+ raw = strings.TrimSpace(raw)
+ if raw == "" || raw == "null" {
+ return p
+ }
+ _ = json.Unmarshal([]byte(raw), &p)
+ return p.sane()
+}
+
+// sane drops nonsense values rather than passing them to ffmpeg, where a
+// zero segment duration would produce an unplayable stream.
+func (p PackagerSettings) sane() PackagerSettings {
+ if p.HLSTime < 1 || p.HLSTime > 30 {
+ p.HLSTime = 0
+ }
+ if p.HLSListSize < 1 || p.HLSListSize > 500 {
+ p.HLSListSize = 0
+ }
+ if p.LiveWait < 0 || p.LiveWait > 120 {
+ p.LiveWait = 0
+ }
+ if p.TSReadyBytes < 0 || p.TSReadyBytes > (256<<20) {
+ p.TSReadyBytes = 0
+ }
+ return p
+}
+
+// GlobalPackagerSettings reads the installation-wide packager defaults.
+func (s *Store) GlobalPackagerSettings() PackagerSettings {
+ vals, err := s.GetSettings()
+ if err != nil {
+ return PackagerSettings{}
+ }
+ atoi := func(k string) int {
+ n, err := strconv.Atoi(strings.TrimSpace(vals[k]))
+ if err != nil {
+ return 0
+ }
+ return n
+ }
+ return PackagerSettings{
+ HLSTime: atoi(SettingHLSTime),
+ HLSListSize: atoi(SettingHLSListSize),
+ LiveWait: atoi(SettingLiveWait),
+ TSReadyBytes: atoi(SettingTSReadyBytes),
+ }.sane()
+}
+
+// settingTruthy accepts the spellings operators realistically type into the
+// settings form for boolean defaults.
+func settingTruthy(v string) bool {
+ switch strings.ToLower(strings.TrimSpace(v)) {
+ case "1", "true", "yes", "on":
+ return true
+ }
+ return false
+}
+
+// ApplyCreateDefaults fills CreateStream fields that the caller left unset
+// from the installation-wide settings table. Explicit request fields win.
+// Packager knobs (hls_time etc.) are resolved at start time, not at create.
+func (s *Store) ApplyCreateDefaults(in *CreateStream) {
+ if in == nil {
+ return
+ }
+ vals, err := s.GetSettings()
+ if err != nil || len(vals) == 0 {
+ return
+ }
+ if in.OnDemand == nil {
+ if v, ok := vals[SettingOnDemand]; ok && strings.TrimSpace(v) != "" {
+ b := settingTruthy(v)
+ in.OnDemand = &b
+ }
+ }
+ if in.IdleTimeoutS == nil {
+ if v := strings.TrimSpace(vals[SettingIdleTimeoutS]); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ in.IdleTimeoutS = &n
+ }
+ }
+ }
+ if len(in.Outputs) == 0 && strings.TrimSpace(in.OutputsJSON) == "" {
+ if v := strings.TrimSpace(vals[SettingDefaultOutputs]); v != "" {
+ in.OutputsJSON = v
+ }
+ }
+}
diff --git a/apps/streamd/internal/db/settings_test.go b/apps/streamd/internal/db/settings_test.go
new file mode 100644
index 0000000..105b1e5
--- /dev/null
+++ b/apps/streamd/internal/db/settings_test.go
@@ -0,0 +1,57 @@
+package db
+
+import (
+ "path/filepath"
+ "testing"
+)
+
+func TestApplyCreateDefaultsFillsUnsetFields(t *testing.T) {
+ s, err := Open(filepath.Join(t.TempDir(), "d"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = s.Close() })
+
+ if err := s.SetSettings(map[string]string{
+ SettingOnDemand: "true",
+ SettingIdleTimeoutS: "120",
+ SettingDefaultOutputs: `[{"id":"hls","label":"HLS","format":"hls","enabled":true}]`,
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ in := CreateStream{Name: "news"}
+ s.ApplyCreateDefaults(&in)
+ if in.OnDemand == nil || !*in.OnDemand {
+ t.Fatalf("expected on_demand=true from settings, got %+v", in.OnDemand)
+ }
+ if in.IdleTimeoutS == nil || *in.IdleTimeoutS != 120 {
+ t.Fatalf("expected idle_timeout_s=120, got %+v", in.IdleTimeoutS)
+ }
+ if in.OutputsJSON == "" {
+ t.Fatal("expected default_outputs JSON to be copied")
+ }
+}
+
+func TestApplyCreateDefaultsDoesNotOverrideExplicit(t *testing.T) {
+ s, err := Open(filepath.Join(t.TempDir(), "d"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = s.Close() })
+
+ _ = s.SetSettings(map[string]string{
+ SettingOnDemand: "true",
+ SettingIdleTimeoutS: "120",
+ })
+ off := false
+ idle := 600
+ in := CreateStream{Name: "news", OnDemand: &off, IdleTimeoutS: &idle}
+ s.ApplyCreateDefaults(&in)
+ if in.OnDemand == nil || *in.OnDemand {
+ t.Fatal("explicit on_demand=false must win over settings")
+ }
+ if in.IdleTimeoutS == nil || *in.IdleTimeoutS != 600 {
+ t.Fatal("explicit idle_timeout_s must win over settings")
+ }
+}
diff --git a/apps/streamd/internal/db/stream_test.go b/apps/streamd/internal/db/stream_test.go
new file mode 100644
index 0000000..a8a88ba
--- /dev/null
+++ b/apps/streamd/internal/db/stream_test.go
@@ -0,0 +1,170 @@
+package db
+
+import "testing"
+
+const (
+ testKID = "0123456789abcdef0123456789abcdef"
+ testKey = "fedcba9876543210fedcba9876543210"
+)
+
+var goodKey = testKID + ":" + testKey
+
+// withDerived runs the same derivation scanStream does, so these tests
+// exercise exactly what the API serialises.
+func withDerived(st Stream) Stream {
+ st.fillDerived()
+ return st
+}
+
+func TestNeedsCaptureDisabledStreamNever(t *testing.T) {
+ st := withDerived(Stream{Enabled: false, MPD: "", Health: "down"})
+ if st.NeedsCapture {
+ t.Error("a disabled stream must never be queued for capture")
+ }
+}
+
+func TestNeedsCaptureMissingManifest(t *testing.T) {
+ st := withDerived(Stream{Enabled: true, MPD: "", Health: "ok"})
+ if !st.NeedsCapture {
+ t.Error("a stream with no manifest needs a capture")
+ }
+}
+
+// The regression the key redaction would otherwise cause: a healthy encrypted
+// stream must not look like it needs a capture just because the API response
+// no longer carries the key. The server decides, using the derived flags.
+func TestNeedsCaptureHealthyDRMStream(t *testing.T) {
+ st := withDerived(Stream{
+ Enabled: true, MPD: "https://x/manifest.mpd", Key: goodKey,
+ Health: "ok", PlaylistAgeS: 2,
+ })
+ if !st.DRMRequired {
+ t.Error("a stream holding a key should resolve to DRM required")
+ }
+ if !st.KeyValid {
+ t.Error("a well-formed key should be valid")
+ }
+ if st.NeedsCapture {
+ t.Error("a healthy DRM stream must not be queued for capture")
+ }
+ // And after redaction the verdict is unchanged and the key is gone.
+ red := st.Redacted()
+ if red.Key != "" || red.HeadersJSON != "" || red.Proxy != "" {
+ t.Errorf("Redacted left secrets behind: %+v", red)
+ }
+ if red.NeedsCapture != st.NeedsCapture || red.HasKey != true || red.KeyValid != true {
+ t.Error("redaction must preserve the derived flags")
+ }
+}
+
+// A clear stream legitimately has no keys. streamd supports clear content, so
+// this must not spin the capture queue forever — the bug the old
+// "key == empty means capture" rule caused.
+func TestNeedsCaptureClearStreamWithNoKey(t *testing.T) {
+ st := withDerived(Stream{
+ Enabled: true, MPD: "https://x/manifest.mpd", Key: "",
+ DRMMode: DRMNo, Health: "ok", PlaylistAgeS: 2,
+ })
+ if st.DRMRequired {
+ t.Error("drm_mode=no must resolve to DRM not required")
+ }
+ if st.NeedsCapture {
+ t.Error("a healthy clear stream must not be queued for capture")
+ }
+}
+
+// In auto mode a stream that has never held a key is assumed clear.
+func TestNeedsCaptureAutoModeInfersFromKey(t *testing.T) {
+ clear := withDerived(Stream{Enabled: true, MPD: "https://x/a.mpd", Health: "ok"})
+ if clear.DRMRequired {
+ t.Error("auto with no key should infer clear")
+ }
+ if clear.DRMMode != DRMAuto {
+ t.Errorf("auto should be normalised to %q, got %q", DRMAuto, clear.DRMMode)
+ }
+ encrypted := withDerived(Stream{Enabled: true, MPD: "https://x/a.mpd", Key: goodKey, Health: "ok"})
+ if !encrypted.DRMRequired {
+ t.Error("auto with a key should infer DRM")
+ }
+}
+
+func TestNeedsCaptureInvalidKey(t *testing.T) {
+ st := withDerived(Stream{
+ Enabled: true, MPD: "https://x/a.mpd", Key: "garbage",
+ DRMMode: DRMYes, Health: "ok",
+ })
+ if st.KeyValid {
+ t.Error("garbage should not be a valid key")
+ }
+ if !st.NeedsCapture {
+ t.Error("a DRM stream with an unusable key needs a capture")
+ }
+}
+
+// An on-demand stream sitting idle is doing its job, not failing. Treating
+// "stopped" as broken would queue a capture for every idle channel.
+func TestNeedsCaptureOnDemandIdleIsNotBroken(t *testing.T) {
+ st := withDerived(Stream{
+ Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
+ OnDemand: true, Health: "stopped",
+ })
+ if st.NeedsCapture {
+ t.Error("an idle on-demand stream must not be queued for capture")
+ }
+ // The same stream that is not on-demand is genuinely down.
+ always := withDerived(Stream{
+ Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
+ OnDemand: false, Health: "stopped",
+ })
+ if !always.NeedsCapture {
+ t.Error("an always-on stream that is stopped should be refreshed")
+ }
+}
+
+// A stream still inside its bootstrap window must be left alone: capturing
+// would POST credentials and restart it, which is a slow restart loop.
+func TestNeedsCaptureStartingRespectsBootstrapGrace(t *testing.T) {
+ young := withDerived(Stream{
+ Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
+ Health: "starting", UptimeS: 10,
+ })
+ if young.NeedsCapture {
+ t.Error("a stream still starting up must not be restarted by a capture")
+ }
+ stuck := withDerived(Stream{
+ Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
+ Health: "starting", UptimeS: bootstrapGraceS + 1,
+ })
+ if !stuck.NeedsCapture {
+ t.Error("a stream stuck in starting past the grace window needs help")
+ }
+}
+
+func TestNeedsCaptureStalePlaylist(t *testing.T) {
+ st := withDerived(Stream{
+ Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
+ Health: "ok", PlaylistAgeS: 120,
+ })
+ if !st.NeedsCapture {
+ t.Error("a stale playlist should trigger a refresh")
+ }
+}
+
+func TestDerivedHeaderAndProxyFlags(t *testing.T) {
+ for _, c := range []struct {
+ headers string
+ want bool
+ }{
+ {"", false}, {"{}", false}, {"null", false},
+ {`{"Cookie":"x"}`, true},
+ } {
+ st := withDerived(Stream{HeadersJSON: c.headers})
+ if st.HasHeaders != c.want {
+ t.Errorf("HasHeaders(%q) = %v want %v", c.headers, st.HasHeaders, c.want)
+ }
+ }
+ st := withDerived(Stream{Proxy: "socks5://127.0.0.1:1080"})
+ if !st.HasProxy {
+ t.Error("a configured proxy should set HasProxy")
+ }
+}
diff --git a/apps/streamd/internal/db/variants.go b/apps/streamd/internal/db/variants.go
new file mode 100644
index 0000000..d6e025c
--- /dev/null
+++ b/apps/streamd/internal/db/variants.go
@@ -0,0 +1,228 @@
+package db
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+)
+
+// SourceVariantID is the id of the pass-through rung: the source copy
+// published at /hls//index.m3u8.
+const SourceVariantID = "fhd"
+
+// VariantSpec is one configured output ladder rung for a stream.
+// Height 0 (or id "fhd") is the source copy published at /hls//index.m3u8.
+// Other heights are ffmpeg-scaled sibling playlists at /hls/-/index.m3u8.
+// An AudioOnly rung is also height 0 but is a separate, re-encoded rung.
+type VariantSpec struct {
+ ID string `json:"id"`
+ Label string `json:"label"`
+ Enabled bool `json:"enabled"`
+ Height int `json:"height"`
+ VideoBitrate string `json:"video_bitrate,omitempty"`
+ AudioBitrate string `json:"audio_bitrate,omitempty"`
+ // AudioOnly drops video entirely. It is checked before the height-zero
+ // source-rung rule, because an audio rung is height zero too and would
+ // otherwise be rewritten into the source copy.
+ AudioOnly bool `json:"audio_only,omitempty"`
+}
+
+// VariantStatus is VariantSpec plus live play path / health for the API/UI.
+type VariantStatus struct {
+ VariantSpec
+ PlayPath string `json:"play_path"`
+ Health string `json:"health,omitempty"`
+ PlaylistAgeS float64 `json:"playlist_age_s,omitempty"`
+}
+
+// IsSource reports whether this rung is the pass-through copy of the input.
+func (v VariantSpec) IsSource() bool {
+ return !v.AudioOnly && v.Height <= 0
+}
+
+// DefaultVariants returns the FHD + optional HD/SD/audio ladder with only FHD
+// enabled.
+func DefaultVariants() []VariantSpec {
+ return []VariantSpec{
+ {ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0},
+ {ID: "hd", Label: "HD", Enabled: false, Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k"},
+ {ID: "sd", Label: "SD", Enabled: false, Height: 480, VideoBitrate: "1200k", AudioBitrate: "96k"},
+ {ID: "audio", Label: "Audio", Enabled: false, AudioOnly: true, AudioBitrate: "96k"},
+ }
+}
+
+// ParseVariantsJSON reads variants_json from the DB. Empty → defaults (FHD only on).
+func ParseVariantsJSON(raw string) []VariantSpec {
+ raw = strings.TrimSpace(raw)
+ if raw == "" || raw == "[]" || raw == "null" {
+ return DefaultVariants()
+ }
+ var list []VariantSpec
+ if err := json.Unmarshal([]byte(raw), &list); err != nil || len(list) == 0 {
+ return DefaultVariants()
+ }
+ return NormalizeVariants(list)
+}
+
+// NormalizeVariants fills ids/labels/bitrates and ensures a source entry exists.
+func NormalizeVariants(in []VariantSpec) []VariantSpec {
+ out := make([]VariantSpec, 0, len(in))
+ seen := map[string]bool{}
+ hasSource := false
+ for _, v := range in {
+ v.ID = slug(v.ID)
+ // An audio rung is resolved first: it is height zero like the source
+ // copy, and the source rule below would otherwise swallow it.
+ if v.AudioOnly {
+ v.Height = 0
+ if v.ID == "" || v.ID == SourceVariantID {
+ v.ID = "audio"
+ }
+ if v.Label == "" {
+ v.Label = "Audio"
+ }
+ if v.AudioBitrate == "" {
+ v.AudioBitrate = "96k"
+ }
+ v.VideoBitrate = ""
+ if seen[v.ID] {
+ continue
+ }
+ seen[v.ID] = true
+ out = append(out, v)
+ continue
+ }
+ if v.ID == "" {
+ if v.Height <= 0 {
+ v.ID = SourceVariantID
+ } else {
+ v.ID = fmt.Sprintf("%dp", v.Height)
+ }
+ }
+ if seen[v.ID] {
+ continue
+ }
+ seen[v.ID] = true
+ if v.Label == "" {
+ v.Label = strings.ToUpper(v.ID)
+ }
+ if v.Height < 0 {
+ v.Height = 0
+ }
+ if v.Height == 0 {
+ hasSource = true
+ v.ID = SourceVariantID
+ if v.Label == "" || strings.EqualFold(v.Label, SourceVariantID) {
+ v.Label = "FHD"
+ }
+ v.Enabled = true // source copy always published when the stream runs
+ } else {
+ if v.VideoBitrate == "" {
+ switch {
+ case v.Height >= 1080:
+ v.VideoBitrate = "4500k"
+ case v.Height >= 720:
+ v.VideoBitrate = "2800k"
+ case v.Height >= 480:
+ v.VideoBitrate = "1200k"
+ default:
+ v.VideoBitrate = "800k"
+ }
+ }
+ if v.AudioBitrate == "" {
+ if v.Height >= 720 {
+ v.AudioBitrate = "128k"
+ } else {
+ v.AudioBitrate = "96k"
+ }
+ }
+ }
+ out = append(out, v)
+ }
+ if !hasSource {
+ out = append([]VariantSpec{{ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0}}, out...)
+ }
+ return out
+}
+
+// EncodeVariantsJSON stores a normalized ladder.
+func EncodeVariantsJSON(list []VariantSpec) (string, error) {
+ list = NormalizeVariants(list)
+ b, err := json.Marshal(list)
+ if err != nil {
+ return "[]", err
+ }
+ return string(b), nil
+}
+
+// VariantPlayPath is the HLS URL path for one variant of stream name.
+func VariantPlayPath(streamName, variantID string, height int) string {
+ variantID = slug(variantID)
+ if height <= 0 || variantID == "" || variantID == SourceVariantID {
+ return "/hls/" + streamName + "/index.m3u8"
+ }
+ return "/hls/" + streamName + "-" + variantID + "/index.m3u8"
+}
+
+// ScaledVariants returns enabled rungs that need their own encoder: every
+// non-source rung, including audio-only.
+func ScaledVariants(list []VariantSpec) []VariantSpec {
+ var out []VariantSpec
+ for _, v := range list {
+ if v.Enabled && !v.IsSource() {
+ out = append(out, v)
+ }
+ }
+ return out
+}
+
+// EnabledVariants returns every enabled rung, source included.
+func EnabledVariants(list []VariantSpec) []VariantSpec {
+ var out []VariantSpec
+ for _, v := range list {
+ if v.Enabled {
+ out = append(out, v)
+ }
+ }
+ return out
+}
+
+// VariantWidth estimates a rung's pixel width for the ABR master playlist.
+// The packager scales with scale=-2:, so width follows the source
+// aspect; 16:9 is the right assumption for broadcast content and the only
+// thing available before the stream has been probed.
+func VariantWidth(height int) int {
+ if height <= 0 {
+ return 0
+ }
+ w := height * 16 / 9
+ // H.264 needs even dimensions, which is what -2 in the scale filter gives.
+ if w%2 == 1 {
+ w++
+ }
+ return w
+}
+
+// BitrateBps parses an ffmpeg bitrate string such as "2800k" into bits per
+// second, for the BANDWIDTH attribute in the master playlist.
+func BitrateBps(s string) int {
+ s = strings.TrimSpace(strings.ToLower(s))
+ if s == "" {
+ return 0
+ }
+ mult := 1
+ switch {
+ case strings.HasSuffix(s, "k"):
+ mult, s = 1000, strings.TrimSuffix(s, "k")
+ case strings.HasSuffix(s, "m"):
+ mult, s = 1000000, strings.TrimSuffix(s, "m")
+ }
+ n := 0
+ for _, r := range s {
+ if r < '0' || r > '9' {
+ return 0
+ }
+ n = n*10 + int(r-'0')
+ }
+ return n * mult
+}
diff --git a/apps/streamd/internal/db/variants_test.go b/apps/streamd/internal/db/variants_test.go
new file mode 100644
index 0000000..1f21c39
--- /dev/null
+++ b/apps/streamd/internal/db/variants_test.go
@@ -0,0 +1,317 @@
+package db
+
+import "testing"
+
+func TestNormalizeVariantsEnsuresFHD(t *testing.T) {
+ got := NormalizeVariants([]VariantSpec{
+ {ID: "hd", Enabled: true, Height: 720},
+ })
+ if len(got) < 2 {
+ t.Fatalf("len=%d", len(got))
+ }
+ if got[0].ID != "fhd" || got[0].Height != 0 || !got[0].Enabled {
+ t.Fatalf("source = %+v", got[0])
+ }
+ if path := VariantPlayPath("rte-one", "hd", 720); path != "/hls/rte-one-hd/index.m3u8" {
+ t.Fatalf("path=%s", path)
+ }
+ if path := VariantPlayPath("rte-one", "fhd", 0); path != "/hls/rte-one/index.m3u8" {
+ t.Fatalf("fhd path=%s", path)
+ }
+}
+
+func TestParseVariantsJSONDefault(t *testing.T) {
+ got := ParseVariantsJSON("")
+ // The default ladder offers the rungs but turns none of the encoding ones
+ // on, so a new stream costs exactly one pass-through copy.
+ if len(got) != len(DefaultVariants()) {
+ t.Fatalf("default len=%d want %d", len(got), len(DefaultVariants()))
+ }
+ if scaled := ScaledVariants(got); len(scaled) != 0 {
+ t.Fatalf("default should encode nothing, got %v", scaled)
+ }
+ enabled := EnabledVariants(got)
+ if len(enabled) != 1 || !enabled[0].IsSource() {
+ t.Fatalf("default should enable only the source rung, got %+v", enabled)
+ }
+}
+
+// An audio-only rung is height 0, exactly like the source copy. The source
+// rule must not swallow it, or enabling audio would silently overwrite the
+// pass-through rung.
+func TestAudioOnlyRungSurvivesNormalize(t *testing.T) {
+ got := NormalizeVariants([]VariantSpec{
+ {ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0},
+ {ID: "audio", Label: "Audio", Enabled: true, AudioOnly: true},
+ })
+ var source, audio *VariantSpec
+ for i := range got {
+ switch {
+ case got[i].AudioOnly:
+ audio = &got[i]
+ case got[i].IsSource():
+ source = &got[i]
+ }
+ }
+ if source == nil {
+ t.Fatal("source rung disappeared")
+ }
+ if audio == nil {
+ t.Fatal("audio rung was absorbed into the source rung")
+ }
+ if audio.ID == SourceVariantID {
+ t.Errorf("audio rung must not take the source id, got %q", audio.ID)
+ }
+ if audio.VideoBitrate != "" {
+ t.Errorf("audio rung should carry no video bitrate, got %q", audio.VideoBitrate)
+ }
+ if audio.AudioBitrate == "" {
+ t.Error("audio rung should get a default audio bitrate")
+ }
+ // It needs its own encoder, so it must count as scaled.
+ scaled := ScaledVariants(got)
+ foundAudio := false
+ for _, v := range scaled {
+ if v.AudioOnly {
+ foundAudio = true
+ }
+ }
+ if !foundAudio {
+ t.Error("audio rung should be in ScaledVariants (it needs an encoder)")
+ }
+}
+
+// An audio rung sent without an explicit id must not claim the source id.
+func TestAudioOnlyWithoutIDGetsOwnID(t *testing.T) {
+ got := NormalizeVariants([]VariantSpec{{Enabled: true, AudioOnly: true}})
+ var audio, source int
+ for _, v := range got {
+ if v.AudioOnly {
+ audio++
+ if v.ID != "audio" {
+ t.Errorf("want id audio, got %q", v.ID)
+ }
+ }
+ if v.IsSource() {
+ source++
+ }
+ }
+ if audio != 1 || source != 1 {
+ t.Fatalf("want one audio and one source rung, got audio=%d source=%d (%+v)", audio, source, got)
+ }
+}
+
+func TestVariantDirAndOutputPaths(t *testing.T) {
+ cases := []struct {
+ name, id string
+ height int
+ audio bool
+ format string
+ want string
+ }{
+ // The original mpegts HLS URL must never move.
+ {"rte-one", "fhd", 0, false, FormatHLS, "/hls/rte-one/index.m3u8"},
+ {"rte-one", "hd", 720, false, FormatHLS, "/hls/rte-one-hd/index.m3u8"},
+ {"rte-one", "fhd", 0, false, FormatCMAF, "/hls/rte-one/cmaf/index.m3u8"},
+ {"rte-one", "hd", 720, false, FormatCMAF, "/hls/rte-one-hd/cmaf/index.m3u8"},
+ {"rte-one", "fhd", 0, false, FormatDASH, "/hls/rte-one/dash/index.mpd"},
+ {"rte-one", "fhd", 0, false, FormatTS, "/live/rte-one.ts"},
+ {"rte-one", "hd", 720, false, FormatTS, "/live/rte-one-hd.ts"},
+ {"rte-one", "audio", 0, true, FormatHLS, "/hls/rte-one-audio/index.m3u8"},
+ }
+ for _, c := range cases {
+ if got := OutputPlayPath(c.name, c.id, c.height, c.audio, c.format); got != c.want {
+ t.Errorf("OutputPlayPath(%s,%s,%d,%v,%s) = %q want %q",
+ c.name, c.id, c.height, c.audio, c.format, got, c.want)
+ }
+ }
+ // A stream name containing a dash must keep its own directory.
+ if got := VariantDir("city-news", "fhd", 0, false); got != "city-news" {
+ t.Errorf("source dir = %q", got)
+ }
+ if got := VariantDir("city-news", "hd", 720, false); got != "city-news-hd" {
+ t.Errorf("variant dir = %q", got)
+ }
+}
+
+func TestDefaultOutputsOnlyHLS(t *testing.T) {
+ got := ParseOutputsJSON("")
+ on := EnabledOutputs(got)
+ if len(on) != 1 || on[0].Format != FormatHLS {
+ t.Fatalf("default outputs should be mpegts HLS only, got %+v", on)
+ }
+}
+
+func TestNormalizeOutputsKeepsFullSetAndAliases(t *testing.T) {
+ // A client toggling DASH on by id alone should get the whole set back
+ // with DASH enabled and HLS still present.
+ got := NormalizeOutputs([]OutputSpec{
+ {ID: "hls", Format: FormatHLS, Enabled: true},
+ {ID: "dash", Format: "mpd", Enabled: true},
+ {ID: "bogus", Format: "quicktime", Enabled: true},
+ })
+ if len(got) != len(DefaultOutputs()) {
+ t.Fatalf("want the full output set, got %d: %+v", len(got), got)
+ }
+ byFormat := map[string]OutputSpec{}
+ for _, o := range got {
+ byFormat[o.Format] = o
+ }
+ if !byFormat[FormatDASH].Enabled {
+ t.Error("mpd alias should have enabled DASH")
+ }
+ if !byFormat[FormatHLS].Enabled {
+ t.Error("HLS should still be enabled")
+ }
+ if byFormat[FormatCMAF].Enabled {
+ t.Error("CMAF should have stayed off")
+ }
+ for _, o := range got {
+ if o.Label == "" || o.ID == "" {
+ t.Errorf("output missing id/label: %+v", o)
+ }
+ }
+}
+
+// Publishing nothing would make the stream unreachable, so an all-off set
+// falls back to HLS rather than going dark.
+func TestNormalizeOutputsNeverPublishesNothing(t *testing.T) {
+ got := NormalizeOutputs([]OutputSpec{
+ {ID: "hls", Format: FormatHLS, Enabled: false},
+ {ID: "dash", Format: FormatDASH, Enabled: false},
+ })
+ if len(EnabledOutputs(got)) == 0 {
+ t.Fatal("an all-off output set should fall back to HLS")
+ }
+ for _, o := range EnabledOutputs(got) {
+ if o.Format != FormatHLS {
+ t.Errorf("fallback should be HLS, got %q", o.Format)
+ }
+ }
+}
+
+func TestBuildPublishLinks(t *testing.T) {
+ variants, err := EncodeVariantsJSON([]VariantSpec{
+ {ID: SourceVariantID, Enabled: true, Height: 0},
+ {ID: "hd", Enabled: true, Height: 720},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ outputs, err := EncodeOutputsJSON([]OutputSpec{
+ {ID: "hls", Format: FormatHLS, Enabled: true},
+ {ID: "ts", Format: FormatTS, Enabled: true},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ links := BuildPublishLinks("city-news", variants, outputs)
+ // master + 2 variants x 2 outputs
+ if len(links) != 5 {
+ t.Fatalf("want 5 links, got %d: %+v", len(links), links)
+ }
+ if !links[0].Master || links[0].PlayPath != "/hls/city-news/master.m3u8" {
+ t.Errorf("first link should be the ABR master, got %+v", links[0])
+ }
+ seen := map[string]bool{}
+ for _, l := range links {
+ if l.PlayPath == "" {
+ t.Errorf("link with no path: %+v", l)
+ }
+ if seen[l.PlayPath] {
+ t.Errorf("duplicate link path %q", l.PlayPath)
+ }
+ seen[l.PlayPath] = true
+ }
+ for _, want := range []string{
+ "/hls/city-news/index.m3u8",
+ "/hls/city-news-hd/index.m3u8",
+ "/live/city-news.ts",
+ "/live/city-news-hd.ts",
+ } {
+ if !seen[want] {
+ t.Errorf("missing expected link %q", want)
+ }
+ }
+}
+
+// With a single rung there is nothing to switch between, so no master.
+func TestBuildPublishLinksNoMasterForSingleRung(t *testing.T) {
+ variants, _ := EncodeVariantsJSON([]VariantSpec{{ID: SourceVariantID, Enabled: true}})
+ outputs, _ := EncodeOutputsJSON(DefaultOutputs())
+ for _, l := range BuildPublishLinks("solo", variants, outputs) {
+ if l.Master {
+ t.Error("a single-rung stream should not advertise an ABR master")
+ }
+ }
+}
+
+func TestVariantWidthAndBitrate(t *testing.T) {
+ if got := VariantWidth(720); got != 1280 {
+ t.Errorf("720p width = %d want 1280", got)
+ }
+ if got := VariantWidth(1080); got != 1920 {
+ t.Errorf("1080p width = %d want 1920", got)
+ }
+ if got := VariantWidth(0); got != 0 {
+ t.Errorf("source height should give width 0, got %d", got)
+ }
+ if got := VariantWidth(480); got%2 != 0 {
+ t.Errorf("width must be even for H.264, got %d", got)
+ }
+ for in, want := range map[string]int{
+ "2800k": 2800000, "1200K": 1200000, "5M": 5000000,
+ "": 0, "fast": 0, "900": 900,
+ } {
+ if got := BitrateBps(in); got != want {
+ t.Errorf("BitrateBps(%q) = %d want %d", in, got, want)
+ }
+ }
+}
+
+func TestValidKeyPairs(t *testing.T) {
+ const kid = "0123456789abcdef0123456789abcdef"
+ const key = "fedcba9876543210fedcba9876543210"
+ good := []string{
+ kid + ":" + key,
+ kid + ":" + key + "\n" + kid + ":" + key,
+ // Multi-KID separated by commas and semicolons, as the supervisor
+ // accepts. A single-pair check would reject these, which is why the
+ // agent used to re-capture multi-KID streams forever.
+ kid + ":" + key + "," + kid + ":" + key,
+ kid + ":" + key + ";" + kid + ":" + key,
+ " " + kid + ":" + key + " \n\n",
+ }
+ for _, g := range good {
+ if !ValidKeyPairs(g) {
+ t.Errorf("ValidKeyPairs(%q) = false, want true", g)
+ }
+ }
+ bad := []string{
+ "", " ", "notakey", kid, kid + ":", ":" + key,
+ kid + ":deadbeef",
+ kid + ":" + key + "\nbroken",
+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz:" + key,
+ }
+ for _, b := range bad {
+ if ValidKeyPairs(b) {
+ t.Errorf("ValidKeyPairs(%q) = true, want false", b)
+ }
+ }
+}
+
+func TestNormalizeTags(t *testing.T) {
+ for in, want := range map[string]string{
+ "Council, Sports": "council,sports",
+ "council,council": "council",
+ " Live Events ": "live-events",
+ "": "",
+ ",,,": "",
+ "A,b,C": "a,b,c",
+ "Town Hall,town hall": "town-hall",
+ } {
+ if got := normalizeTags(in); got != want {
+ t.Errorf("normalizeTags(%q) = %q want %q", in, got, want)
+ }
+ }
+}
diff --git a/apps/streamd/internal/deps/archive.go b/apps/streamd/internal/deps/archive.go
new file mode 100644
index 0000000..573c34f
--- /dev/null
+++ b/apps/streamd/internal/deps/archive.go
@@ -0,0 +1,153 @@
+package deps
+
+import (
+ "archive/tar"
+ "archive/zip"
+ "compress/gzip"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+// extractNamed finds a file whose base name matches wantName (case-insensitive
+// on Windows) inside archivePath and writes it to destPath.
+func extractNamed(archivePath, _ /*binDir*/, wantName, destPath string) error {
+ lower := strings.ToLower(archivePath)
+ switch {
+ case strings.HasSuffix(lower, ".zip"):
+ return extractZipNamed(archivePath, wantName, destPath)
+ case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
+ return extractTarGZNamed(archivePath, wantName, destPath)
+ case strings.HasSuffix(lower, ".tar.xz"):
+ return extractTarXZNamed(archivePath, wantName, destPath)
+ default:
+ return fmt.Errorf("unsupported archive type: %s", archivePath)
+ }
+}
+
+func nameMatch(base, want string) bool {
+ return strings.EqualFold(filepath.Base(base), want)
+}
+
+func extractZipNamed(archivePath, wantName, destPath string) error {
+ r, err := zip.OpenReader(archivePath)
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ for _, f := range r.File {
+ if f.FileInfo().IsDir() {
+ continue
+ }
+ if !nameMatch(f.Name, wantName) {
+ continue
+ }
+ rc, err := f.Open()
+ if err != nil {
+ return err
+ }
+ err = writeFile(destPath, rc)
+ _ = rc.Close()
+ return err
+ }
+ return fmt.Errorf("%s not found in %s", wantName, filepath.Base(archivePath))
+}
+
+func extractTarGZNamed(archivePath, wantName, destPath string) error {
+ f, err := os.Open(archivePath)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ gz, err := gzip.NewReader(f)
+ if err != nil {
+ return err
+ }
+ defer gz.Close()
+ return readTarNamed(gz, wantName, destPath, filepath.Base(archivePath))
+}
+
+// extractTarXZNamed shells out to tar when available (linux/mac; Git Bash on Windows).
+func extractTarXZNamed(archivePath, wantName, destPath string) error {
+ tmp, err := os.MkdirTemp("", "ffmpeg-xz-*")
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(tmp)
+
+ tarBin, err := exec.LookPath("tar")
+ if err != nil {
+ return fmt.Errorf("tar required to extract .tar.xz (install tar or place %s in bin/): %w", wantName, err)
+ }
+ cmd := exec.Command(tarBin, "-xJf", archivePath, "-C", tmp)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("tar extract: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+ var found string
+ _ = filepath.Walk(tmp, func(path string, info os.FileInfo, err error) error {
+ if err != nil || info.IsDir() {
+ return nil
+ }
+ if nameMatch(path, wantName) {
+ found = path
+ return io.EOF
+ }
+ return nil
+ })
+ if found == "" {
+ return fmt.Errorf("%s not found in %s", wantName, filepath.Base(archivePath))
+ }
+ in, err := os.Open(found)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ return writeFile(destPath, in)
+}
+
+func readTarNamed(r io.Reader, wantName, destPath, archiveBase string) error {
+ tr := tar.NewReader(r)
+ for {
+ hdr, err := tr.Next()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ if hdr.Typeflag != tar.TypeReg {
+ continue
+ }
+ if !nameMatch(hdr.Name, wantName) {
+ continue
+ }
+ return writeFile(destPath, tr)
+ }
+ return fmt.Errorf("%s not found in %s", wantName, archiveBase)
+}
+
+func writeFile(dest string, r io.Reader) error {
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ return err
+ }
+ tmp := dest + ".partial"
+ f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
+ if err != nil {
+ return err
+ }
+ _, copyErr := io.Copy(f, r)
+ closeErr := f.Close()
+ if copyErr != nil {
+ _ = os.Remove(tmp)
+ return copyErr
+ }
+ if closeErr != nil {
+ _ = os.Remove(tmp)
+ return closeErr
+ }
+ _ = os.Remove(dest)
+ return os.Rename(tmp, dest)
+}
diff --git a/apps/streamd/internal/deps/deps.go b/apps/streamd/internal/deps/deps.go
new file mode 100644
index 0000000..9b449c5
--- /dev/null
+++ b/apps/streamd/internal/deps/deps.go
@@ -0,0 +1,247 @@
+// Package deps ensures media tools (ffmpeg, N_m3u8DL-RE, mp4decrypt) exist
+// under bin/ next to the install, downloading static builds when missing.
+package deps
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "streamd/repo"
+)
+
+// Status is the resolved path for each tool after Ensure.
+type Status struct {
+ BinDir string `json:"bin_dir"`
+ FFmpeg string `json:"ffmpeg"`
+ NRE string `json:"nre"`
+ MP4Decrypt string `json:"mp4decrypt"`
+ Notes []string `json:"notes,omitempty"`
+}
+
+// Public is Status with filesystem paths reduced to presence flags, for the
+// unauthenticated part of /api/health. Absolute install paths are useful to an
+// operator and useful to an attacker, so anonymous callers get neither.
+func (s Status) Public() map[string]any {
+ have := func(p string) bool { return strings.TrimSpace(p) != "" }
+ return map[string]any{
+ "ffmpeg": have(s.FFmpeg),
+ "nre": have(s.NRE),
+ "mp4decrypt": have(s.MP4Decrypt),
+ }
+}
+
+// Options controls Ensure.
+type Options struct {
+ // BinDir overrides where binaries are installed. Empty → /bin
+ // or the directory containing the running executable.
+ BinDir string
+ // SkipDownload only resolves existing paths (flags/env/bin/PATH).
+ SkipDownload bool
+ Log *log.Logger
+}
+
+func (o Options) logf(format string, args ...any) {
+ if o.Log != nil {
+ o.Log.Printf(format, args...)
+ } else {
+ log.Printf(format, args...)
+ }
+}
+
+// Ensure resolves ffmpeg, N_m3u8DL-RE and mp4decrypt, downloading into BinDir
+// when missing (unless SkipDownload). Returns paths suitable for the supervisor.
+func Ensure(o Options, preferNRE, preferFFmpeg, preferDecrypt string) (Status, error) {
+ st := Status{}
+ binDir := o.BinDir
+ if binDir == "" {
+ binDir = defaultBinDir()
+ }
+ if err := os.MkdirAll(binDir, 0o755); err != nil {
+ return st, err
+ }
+ st.BinDir = binDir
+
+ var notes []string
+ ff, err := resolveOrFetch(o, "ffmpeg", preferFFmpeg, binDir, ffmpegCandidates(binDir), fetchFFmpeg)
+ if err != nil {
+ notes = append(notes, "ffmpeg: "+err.Error())
+ o.logf("[!] deps: ffmpeg: %v", err)
+ } else {
+ st.FFmpeg = ff
+ o.logf("[+] deps: ffmpeg → %s", ff)
+ }
+
+ nre, err := resolveOrFetch(o, "N_m3u8DL-RE", preferNRE, binDir, nreCandidates(binDir), fetchNRE)
+ if err != nil {
+ notes = append(notes, "N_m3u8DL-RE: "+err.Error())
+ o.logf("[!] deps: N_m3u8DL-RE: %v", err)
+ } else {
+ st.NRE = nre
+ o.logf("[+] deps: N_m3u8DL-RE → %s", nre)
+ }
+
+ dec, err := resolveOrFetch(o, "mp4decrypt", preferDecrypt, binDir, decryptCandidates(binDir), fetchMP4Decrypt)
+ if err != nil {
+ notes = append(notes, "mp4decrypt: "+err.Error())
+ o.logf("[!] deps: mp4decrypt: %v", err)
+ } else {
+ st.MP4Decrypt = dec
+ o.logf("[+] deps: mp4decrypt → %s", dec)
+ }
+
+ st.Notes = notes
+ // Serve can start even if a tool is missing; stream start will fail clearly.
+ return st, nil
+}
+
+func defaultBinDir() string {
+ root := repo.Root()
+ if root != "" {
+ return filepath.Join(root, "bin")
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ return "bin"
+ }
+ if resolved, err := filepath.EvalSymlinks(exe); err == nil {
+ exe = resolved
+ }
+ dir := filepath.Dir(exe)
+ if strings.EqualFold(filepath.Base(dir), "bin") {
+ return dir
+ }
+ return filepath.Join(dir, "bin")
+}
+
+type fetchFunc func(binDir string, logf func(string, ...any)) (string, error)
+
+func resolveOrFetch(o Options, label, prefer, binDir string, candidates []string, fetch fetchFunc) (string, error) {
+ if p := firstExisting(prefer); p != "" {
+ return p, nil
+ }
+ for _, c := range candidates {
+ if p := firstExisting(c); p != "" {
+ return p, nil
+ }
+ }
+ if o.SkipDownload {
+ return "", fmt.Errorf("%s not found (auto-download disabled)", label)
+ }
+ o.logf("[*] deps: %s missing → downloading into %s …", label, binDir)
+ return fetch(binDir, o.logf)
+}
+
+func firstExisting(paths ...string) string {
+ for _, p := range paths {
+ p = strings.TrimSpace(p)
+ if p == "" {
+ continue
+ }
+ if filepath.IsAbs(p) || strings.ContainsAny(p, `/\`) {
+ if st, err := os.Stat(p); err == nil && !st.IsDir() {
+ return p
+ }
+ continue
+ }
+ if abs, err := exec.LookPath(p); err == nil {
+ return abs
+ }
+ }
+ return ""
+}
+
+func ffmpegCandidates(binDir string) []string {
+ name := "ffmpeg"
+ if runtime.GOOS == "windows" {
+ name = "ffmpeg.exe"
+ }
+ return []string{
+ os.Getenv("FFMPEG_PATH"),
+ os.Getenv("FFMPEG"),
+ filepath.Join(binDir, name),
+ name,
+ }
+}
+
+func nreCandidates(binDir string) []string {
+ names := []string{"N_m3u8DL-RE"}
+ if runtime.GOOS == "windows" {
+ names = []string{"N_m3u8DL-RE.exe", "N_m3u8DL-RE"}
+ }
+ out := []string{os.Getenv("NRE_PATH"), os.Getenv("N_M3U8DL_RE")}
+ for _, n := range names {
+ out = append(out, filepath.Join(binDir, n), n)
+ }
+ return out
+}
+
+func decryptCandidates(binDir string) []string {
+ name := "mp4decrypt"
+ if runtime.GOOS == "windows" {
+ name = "mp4decrypt.exe"
+ }
+ return []string{
+ os.Getenv("MP4DECRYPT_PATH"),
+ os.Getenv("MP4DECRYPT"),
+ filepath.Join(binDir, name),
+ name,
+ }
+}
+
+func httpGet(url string) (*http.Response, error) {
+ client := &http.Client{Timeout: 10 * time.Minute}
+ req, err := http.NewRequest(http.MethodGet, url, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("User-Agent", "streamd/1.0")
+ return client.Do(req)
+}
+
+func downloadTo(url, dest string, logf func(string, ...any)) error {
+ logf("[*] deps: GET %s", url)
+ resp, err := httpGet(url)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("download %s: HTTP %s", url, resp.Status)
+ }
+ tmp := dest + ".partial"
+ f, err := os.Create(tmp)
+ if err != nil {
+ return err
+ }
+ n, copyErr := io.Copy(f, resp.Body)
+ closeErr := f.Close()
+ if copyErr != nil {
+ _ = os.Remove(tmp)
+ return copyErr
+ }
+ if closeErr != nil {
+ _ = os.Remove(tmp)
+ return closeErr
+ }
+ if err := os.Rename(tmp, dest); err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ logf("[+] deps: saved %s (%d bytes)", dest, n)
+ return nil
+}
+
+func chmodX(path string) {
+ if runtime.GOOS == "windows" {
+ return
+ }
+ _ = os.Chmod(path, 0o755)
+}
diff --git a/apps/streamd/internal/deps/fetch_ffmpeg.go b/apps/streamd/internal/deps/fetch_ffmpeg.go
new file mode 100644
index 0000000..e1393a2
--- /dev/null
+++ b/apps/streamd/internal/deps/fetch_ffmpeg.go
@@ -0,0 +1,64 @@
+package deps
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+)
+
+// BtbN static GPL builds (linked from ffmpeg.org). No official BtbN macOS
+// builds — on darwin we leave a clear note to use Homebrew.
+func fetchFFmpeg(binDir string, logf func(string, ...any)) (string, error) {
+ url, archiveName, err := ffmpegURL()
+ if err != nil {
+ return "", err
+ }
+ archivePath := filepath.Join(binDir, archiveName)
+ if err := downloadTo(url, archivePath, logf); err != nil {
+ return "", err
+ }
+ defer func() { _ = os.Remove(archivePath) }()
+
+ want := "ffmpeg"
+ if runtime.GOOS == "windows" {
+ want = "ffmpeg.exe"
+ }
+ dest := filepath.Join(binDir, want)
+ if err := extractNamed(archivePath, binDir, want, dest); err != nil {
+ return "", err
+ }
+ chmodX(dest)
+
+ // Best-effort ffprobe alongside ffmpeg.
+ probeWant := "ffprobe"
+ if runtime.GOOS == "windows" {
+ probeWant = "ffprobe.exe"
+ }
+ probeDest := filepath.Join(binDir, probeWant)
+ _ = extractNamed(archivePath, binDir, probeWant, probeDest)
+ chmodX(probeDest)
+
+ return dest, nil
+}
+
+func ffmpegURL() (url, archiveName string, err error) {
+ switch runtime.GOOS + "/" + runtime.GOARCH {
+ case "windows/amd64":
+ return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip",
+ "ffmpeg-win64-gpl.zip", nil
+ case "windows/arm64":
+ return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-winarm64-gpl.zip",
+ "ffmpeg-winarm64-gpl.zip", nil
+ case "linux/amd64":
+ return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz",
+ "ffmpeg-linux64-gpl.tar.xz", nil
+ case "linux/arm64":
+ return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm64-gpl.tar.xz",
+ "ffmpeg-linuxarm64-gpl.tar.xz", nil
+ case "darwin/amd64", "darwin/arm64":
+ return "", "", fmt.Errorf("no static ffmpeg auto-build for macOS; install with: brew install ffmpeg")
+ default:
+ return "", "", fmt.Errorf("unsupported platform %s/%s for ffmpeg auto-download", runtime.GOOS, runtime.GOARCH)
+ }
+}
diff --git a/apps/streamd/internal/deps/fetch_mp4decrypt.go b/apps/streamd/internal/deps/fetch_mp4decrypt.go
new file mode 100644
index 0000000..f662115
--- /dev/null
+++ b/apps/streamd/internal/deps/fetch_mp4decrypt.go
@@ -0,0 +1,50 @@
+package deps
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+)
+
+// Official Bento4 SDK binaries from bento4.com (v1.6.0-641).
+// linux/arm64 and windows/arm64 are not published there — clear error.
+func fetchMP4Decrypt(binDir string, logf func(string, ...any)) (string, error) {
+ url, archiveName, err := bento4URL()
+ if err != nil {
+ return "", err
+ }
+ archivePath := filepath.Join(binDir, archiveName)
+ if err := downloadTo(url, archivePath, logf); err != nil {
+ return "", err
+ }
+ defer func() { _ = os.Remove(archivePath) }()
+
+ want := "mp4decrypt"
+ if runtime.GOOS == "windows" {
+ want = "mp4decrypt.exe"
+ }
+ dest := filepath.Join(binDir, want)
+ if err := extractNamed(archivePath, binDir, want, dest); err != nil {
+ return "", err
+ }
+ chmodX(dest)
+ return dest, nil
+}
+
+func bento4URL() (url, archiveName string, err error) {
+ const base = "https://www.bok.net/Bento4/binaries/"
+ switch runtime.GOOS + "/" + runtime.GOARCH {
+ case "windows/amd64":
+ name := "Bento4-SDK-1-6-0-641.x86_64-microsoft-win32.zip"
+ return base + name, name, nil
+ case "linux/amd64":
+ name := "Bento4-SDK-1-6-0-641.x86_64-unknown-linux.zip"
+ return base + name, name, nil
+ case "darwin/amd64", "darwin/arm64":
+ name := "Bento4-SDK-1-6-0-641.universal-apple-macosx.zip"
+ return base + name, name, nil
+ default:
+ return "", "", fmt.Errorf("no Bento4 binary for %s/%s (place mp4decrypt in bin/ manually)", runtime.GOOS, runtime.GOARCH)
+ }
+}
diff --git a/apps/streamd/internal/deps/fetch_nre.go b/apps/streamd/internal/deps/fetch_nre.go
new file mode 100644
index 0000000..2c282b9
--- /dev/null
+++ b/apps/streamd/internal/deps/fetch_nre.go
@@ -0,0 +1,71 @@
+package deps
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+)
+
+const nreTag = "v0.6.0-beta"
+const nreBase = "https://github.com/nilaoda/N_m3u8DL-RE/releases/download/" + nreTag + "/"
+
+func fetchNRE(binDir string, logf func(string, ...any)) (string, error) {
+ url, archiveName, binName, err := nreURL()
+ if err != nil {
+ return "", err
+ }
+ archivePath := filepath.Join(binDir, archiveName)
+ if err := downloadTo(url, archivePath, logf); err != nil {
+ return "", err
+ }
+ defer func() { _ = os.Remove(archivePath) }()
+
+ dest := filepath.Join(binDir, binName)
+ if err := extractNamed(archivePath, binDir, binName, dest); err != nil {
+ // Some archives nest the binary or use a slightly different name.
+ if err2 := extractNamed(archivePath, binDir, "N_m3u8DL-RE", dest); err2 != nil {
+ if runtime.GOOS == "windows" {
+ if err3 := extractNamed(archivePath, binDir, "N_m3u8DL-RE.exe", dest); err3 != nil {
+ return "", err
+ }
+ } else {
+ return "", err
+ }
+ }
+ }
+ chmodX(dest)
+ return dest, nil
+}
+
+func nreURL() (url, archiveName, binName string, err error) {
+ binName = "N_m3u8DL-RE"
+ if runtime.GOOS == "windows" {
+ binName = "N_m3u8DL-RE.exe"
+ }
+ switch runtime.GOOS + "/" + runtime.GOARCH {
+ case "windows/amd64":
+ name := "N_m3u8DL-RE_v0.6.0-beta_win-x64_20260629.zip"
+ return nreBase + name, name, binName, nil
+ case "windows/arm64":
+ name := "N_m3u8DL-RE_v0.6.0-beta_win-arm64_20260629.zip"
+ return nreBase + name, name, binName, nil
+ case "windows/386":
+ name := "N_m3u8DL-RE_v0.6.0-beta_win-NT6.0-x86_20260629.zip"
+ return nreBase + name, name, binName, nil
+ case "linux/amd64":
+ name := "N_m3u8DL-RE_v0.6.0-beta_linux-x64_20260629.tar.gz"
+ return nreBase + name, name, binName, nil
+ case "linux/arm64":
+ name := "N_m3u8DL-RE_v0.6.0-beta_linux-arm64_20260629.tar.gz"
+ return nreBase + name, name, binName, nil
+ case "darwin/amd64":
+ name := "N_m3u8DL-RE_v0.6.0-beta_osx-x64_20260629.tar.gz"
+ return nreBase + name, name, binName, nil
+ case "darwin/arm64":
+ name := "N_m3u8DL-RE_v0.6.0-beta_osx-arm64_20260629.tar.gz"
+ return nreBase + name, name, binName, nil
+ default:
+ return "", "", "", fmt.Errorf("unsupported platform %s/%s for N_m3u8DL-RE auto-download", runtime.GOOS, runtime.GOARCH)
+ }
+}
diff --git a/apps/streamd/internal/egress/conf.go b/apps/streamd/internal/egress/conf.go
new file mode 100644
index 0000000..7e4356b
--- /dev/null
+++ b/apps/streamd/internal/egress/conf.go
@@ -0,0 +1,80 @@
+package egress
+
+import (
+ "bufio"
+ "strings"
+)
+
+// wgInterfaceAddrs extracts Address= values from the [Interface] section of a
+// wg-quick style conf. Private keys are never returned or logged.
+func wgInterfaceAddrs(conf string) []string {
+ var addrs []string
+ section := ""
+ sc := bufio.NewScanner(strings.NewReader(conf))
+ for sc.Scan() {
+ line := strings.TrimSpace(sc.Text())
+ if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
+ continue
+ }
+ if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
+ section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
+ continue
+ }
+ if section != "interface" {
+ continue
+ }
+ key, val, ok := strings.Cut(line, "=")
+ if !ok {
+ continue
+ }
+ if strings.EqualFold(strings.TrimSpace(key), "Address") {
+ for _, part := range strings.Split(val, ",") {
+ if a := strings.TrimSpace(part); a != "" {
+ addrs = append(addrs, a)
+ }
+ }
+ }
+ }
+ return addrs
+}
+
+// wgSetconfBody strips wg-quick-only keys so the result is valid for `wg setconf`.
+func wgSetconfBody(conf string) string {
+ var b strings.Builder
+ section := ""
+ sc := bufio.NewScanner(strings.NewReader(conf))
+ for sc.Scan() {
+ raw := sc.Text()
+ line := strings.TrimSpace(raw)
+ if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
+ continue
+ }
+ if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
+ section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
+ b.WriteString(line)
+ b.WriteByte('\n')
+ continue
+ }
+ key, _, ok := strings.Cut(line, "=")
+ if !ok {
+ continue
+ }
+ k := strings.ToLower(strings.TrimSpace(key))
+ if section == "interface" {
+ switch k {
+ case "privatekey", "listenport", "fwmark":
+ b.WriteString(line)
+ b.WriteByte('\n')
+ }
+ continue
+ }
+ if section == "peer" {
+ switch k {
+ case "publickey", "presharedkey", "allowedips", "endpoint", "persistentkeepalive":
+ b.WriteString(line)
+ b.WriteByte('\n')
+ }
+ }
+ }
+ return b.String()
+}
diff --git a/apps/streamd/internal/egress/manager.go b/apps/streamd/internal/egress/manager.go
new file mode 100644
index 0000000..d7a8967
--- /dev/null
+++ b/apps/streamd/internal/egress/manager.go
@@ -0,0 +1,418 @@
+package egress
+
+import (
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+const (
+ baseListenPort = 18080
+ socksPortInNS = 1080
+)
+
+// Manager brings named egress profiles up and resolves a stream's origin proxy.
+type Manager struct {
+ DataDir string
+ Store *db.Store
+ Log *slog.Logger
+ SocksBin string // microsocks or gost; looked up if empty
+
+ mu sync.Mutex
+ running map[string]*runState // by profile name
+}
+
+type runState struct {
+ name string
+ listenPort int
+ nsIP string // veth IP inside netns, e.g. 10.255.N.2
+ socksCmd *exec.Cmd
+ forwardLn net.Listener
+ stopFwd chan struct{}
+}
+
+// New builds a Manager. SocksBin may be empty (auto LookPath).
+func New(dataDir string, store *db.Store, log *slog.Logger, socksBin string) *Manager {
+ if log == nil {
+ log = slog.Default()
+ }
+ return &Manager{
+ DataDir: dataDir,
+ Store: store,
+ Log: log,
+ SocksBin: socksBin,
+ running: map[string]*runState{},
+ }
+}
+
+// WarnMissingDeps logs once when WireGuard host tools are absent. Safe to call
+// on every platform; non-Linux hosts skip the check.
+func (m *Manager) WarnMissingDeps() {
+ if runtime.GOOS != "linux" {
+ return
+ }
+ for _, bin := range []string{"ip", "wg"} {
+ if _, err := exec.LookPath(bin); err != nil {
+ m.logger().Warn("egress: tool missing from PATH (WireGuard profiles need it)",
+ "bin", bin)
+ }
+ }
+ if _, err := m.findSocksBin(); err != nil {
+ m.logger().Warn("egress: microsocks or gost missing from PATH (WireGuard profiles need a SOCKS forwarder in the netns)")
+ }
+}
+
+func (m *Manager) logger() *slog.Logger {
+ if m.Log != nil {
+ return m.Log
+ }
+ return slog.Default()
+}
+
+func (m *Manager) profileDir(name string) string {
+ return filepath.Join(m.DataDir, "egress", db.Slug(name))
+}
+
+func (m *Manager) confPath(name string) string {
+ return filepath.Join(m.profileDir(name), "wg.conf")
+}
+
+// HasConf reports whether a WireGuard conf file exists for name.
+func (m *Manager) HasConf(name string) bool {
+ st, err := os.Stat(m.confPath(name))
+ return err == nil && st.Size() > 0
+}
+
+// WriteConf stores a WireGuard conf on disk (0600). Does not log contents.
+func (m *Manager) WriteConf(name, contents string) error {
+ name = db.Slug(name)
+ if name == "" {
+ return fmt.Errorf("name required")
+ }
+ dir := m.profileDir(name)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+ path := m.confPath(name)
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, []byte(contents), 0o600); err != nil {
+ return err
+ }
+ return os.Rename(tmp, path)
+}
+
+// ReadConf returns the raw conf for admin use. Callers must not log it.
+func (m *Manager) ReadConf(name string) (string, error) {
+ b, err := os.ReadFile(m.confPath(name))
+ if err != nil {
+ return "", err
+ }
+ return string(b), nil
+}
+
+// RemoveFiles deletes on-disk conf for a profile (after DB delete).
+func (m *Manager) RemoveFiles(name string) error {
+ name = db.Slug(name)
+ if name == "" {
+ return nil
+ }
+ return os.RemoveAll(m.profileDir(name))
+}
+
+// Enrich fills HasConf on profiles (conf is never stored in the DB).
+func (m *Manager) Enrich(p *db.EgressProfile) {
+ if p == nil {
+ return
+ }
+ if p.Kind == db.EgressKindWireGuard {
+ p.HasConf = m.HasConf(p.Name)
+ }
+}
+
+// ResolveProxy returns the SOCKS/HTTP proxy URL a stream should use for origin
+// fetch. Order: explicit stream.Proxy, then named egress profile, else empty.
+func (m *Manager) ResolveProxy(st db.Stream) (string, error) {
+ if p := strings.TrimSpace(st.Proxy); p != "" {
+ return p, nil
+ }
+ name := strings.TrimSpace(st.Egress)
+ if name == "" {
+ return "", nil
+ }
+ if err := m.EnsureUp(name); err != nil {
+ return "", err
+ }
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return "", err
+ }
+ switch p.Kind {
+ case db.EgressKindSocks:
+ u := strings.TrimSpace(p.SocksURL)
+ if u == "" {
+ return "", fmt.Errorf("egress %q has no socks_url", p.Name)
+ }
+ return u, nil
+ default:
+ if p.ListenPort <= 0 {
+ return "", fmt.Errorf("egress %q is up but has no listen port", p.Name)
+ }
+ return fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort), nil
+ }
+}
+
+// StartEnabled brings up every profile marked enabled.
+func (m *Manager) StartEnabled() {
+ list, err := m.Store.ListEgressProfiles()
+ if err != nil {
+ m.logger().Error("list egress profiles", "err", err)
+ return
+ }
+ for _, p := range list {
+ if !p.Enabled {
+ continue
+ }
+ if err := m.EnsureUp(p.Name); err != nil {
+ m.logger().Warn("egress start", "name", p.Name, "err", err)
+ }
+ }
+}
+
+// StopAll tears down every running profile.
+func (m *Manager) StopAll() {
+ m.mu.Lock()
+ names := make([]string, 0, len(m.running))
+ for n := range m.running {
+ names = append(names, n)
+ }
+ m.mu.Unlock()
+ for _, n := range names {
+ _ = m.Down(n)
+ }
+}
+
+// Status returns the DB row for a profile (with HasConf filled).
+func (m *Manager) Status(name string) (db.EgressProfile, error) {
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return p, err
+ }
+ m.Enrich(&p)
+ return p, nil
+}
+
+// EnsureUp brings a profile to a usable SOCKS endpoint.
+func (m *Manager) EnsureUp(name string) error {
+ name = db.Slug(name)
+ if name == "" {
+ return fmt.Errorf("egress name required")
+ }
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return fmt.Errorf("egress profile %q: %w", name, err)
+ }
+
+ m.mu.Lock()
+ if rs, ok := m.running[name]; ok && rs != nil {
+ m.mu.Unlock()
+ return nil
+ }
+ m.mu.Unlock()
+
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressStarting, "", p.EgressIP, p.ListenPort)
+
+ switch p.Kind {
+ case db.EgressKindSocks:
+ u := strings.TrimSpace(p.SocksURL)
+ if u == "" {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, "socks_url required", "", 0)
+ return fmt.Errorf("egress %q: socks_url required", name)
+ }
+ m.mu.Lock()
+ m.running[name] = &runState{name: name}
+ m.mu.Unlock()
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", "", 0)
+ return nil
+ case db.EgressKindWireGuard:
+ if runtime.GOOS != "linux" {
+ msg := "wireguard egress requires Linux"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+ }
+ return m.ensureWireGuardUp(p)
+ default:
+ msg := fmt.Sprintf("unknown egress kind %q", p.Kind)
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+ }
+}
+
+// Down stops a profile's local SOCKS / netns.
+func (m *Manager) Down(name string) error {
+ name = db.Slug(name)
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return err
+ }
+
+ m.mu.Lock()
+ rs := m.running[name]
+ delete(m.running, name)
+ m.mu.Unlock()
+
+ if rs != nil {
+ m.stopRun(rs)
+ }
+ if p.Kind == db.EgressKindWireGuard && runtime.GOOS == "linux" {
+ if err := m.teardownWireGuard(name, p.ID); err != nil {
+ m.logger().Warn("egress teardown", "name", name, "err", err)
+ }
+ }
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressStopped, "", "", 0)
+ return nil
+}
+
+func (m *Manager) stopRun(rs *runState) {
+ if rs.stopFwd != nil {
+ close(rs.stopFwd)
+ rs.stopFwd = nil
+ }
+ if rs.forwardLn != nil {
+ _ = rs.forwardLn.Close()
+ rs.forwardLn = nil
+ }
+ if rs.socksCmd != nil && rs.socksCmd.Process != nil {
+ _ = rs.socksCmd.Process.Kill()
+ _, _ = rs.socksCmd.Process.Wait()
+ rs.socksCmd = nil
+ }
+}
+
+func (m *Manager) findSocksBin() (string, error) {
+ if m.SocksBin != "" {
+ return m.SocksBin, nil
+ }
+ for _, n := range []string{"microsocks", "gost"} {
+ if p, err := exec.LookPath(n); err == nil {
+ m.SocksBin = p
+ return p, nil
+ }
+ }
+ return "", fmt.Errorf("microsocks (or gost) not found on PATH")
+}
+
+func (m *Manager) allocListenPort(id int64) int {
+ return baseListenPort + int(id%1000)
+}
+
+func (m *Manager) vethAddrs(id int64) (hostIP, nsIP, subnet string) {
+ // Unique /30-ish /24 host pair per profile id (1..254).
+ n := int(id % 200)
+ if n <= 0 {
+ n = 1
+ }
+ hostIP = fmt.Sprintf("10.255.%d.1", n)
+ nsIP = fmt.Sprintf("10.255.%d.2", n)
+ subnet = fmt.Sprintf("10.255.%d.0/24", n)
+ return hostIP, nsIP, subnet
+}
+
+func (m *Manager) startLocalForward(listenPort int, destHost string, destPort int) (net.Listener, chan struct{}, error) {
+ ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", listenPort))
+ if err != nil {
+ return nil, nil, err
+ }
+ stop := make(chan struct{})
+ go func() {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ select {
+ case <-stop:
+ return
+ default:
+ return
+ }
+ }
+ go proxyTCP(c, fmt.Sprintf("%s:%d", destHost, destPort))
+ }
+ }()
+ return ln, stop, nil
+}
+
+func proxyTCP(client net.Conn, addr string) {
+ defer client.Close()
+ _ = client.SetDeadline(time.Now().Add(60 * time.Second))
+ upstream, err := net.DialTimeout("tcp", addr, 15*time.Second)
+ if err != nil {
+ return
+ }
+ defer upstream.Close()
+ _ = client.SetDeadline(time.Time{})
+ _ = upstream.SetDeadline(time.Time{})
+ done := make(chan struct{}, 2)
+ go func() { _, _ = io.Copy(upstream, client); done <- struct{}{} }()
+ go func() { _, _ = io.Copy(client, upstream); done <- struct{}{} }()
+ <-done
+}
+
+// TestDial tries a short TCP connect through the resolved SOCKS endpoint of a
+// profile (after EnsureUp). Used by POST /api/egress/:name/test.
+func (m *Manager) TestDial(name string) (map[string]any, error) {
+ if err := m.EnsureUp(name); err != nil {
+ return nil, err
+ }
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return nil, err
+ }
+ var proxyURL string
+ switch p.Kind {
+ case db.EgressKindSocks:
+ proxyURL = strings.TrimSpace(p.SocksURL)
+ default:
+ if p.ListenPort <= 0 {
+ return nil, fmt.Errorf("no listen port")
+ }
+ proxyURL = fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort)
+ }
+ out := map[string]any{
+ "ok": true,
+ "name": p.Name,
+ "kind": p.Kind,
+ "proxy_url": proxyURL,
+ "status": p.Status,
+ "egress_ip": p.EgressIP,
+ }
+ // Dial the local SOCKS port to confirm it accepts TCP.
+ hostPort := ""
+ if p.Kind == db.EgressKindWireGuard && p.ListenPort > 0 {
+ hostPort = fmt.Sprintf("127.0.0.1:%d", p.ListenPort)
+ } else if u := strings.TrimPrefix(strings.TrimPrefix(proxyURL, "socks5://"), "socks5h://"); u != proxyURL {
+ if i := strings.LastIndex(u, "@"); i >= 0 {
+ u = u[i+1:]
+ }
+ hostPort = u
+ }
+ if hostPort != "" {
+ c, err := net.DialTimeout("tcp", hostPort, 5*time.Second)
+ if err != nil {
+ out["ok"] = false
+ out["error"] = err.Error()
+ return out, fmt.Errorf("socks dial: %w", err)
+ }
+ _ = c.Close()
+ out["socks_reachable"] = true
+ }
+ return out, nil
+}
diff --git a/apps/streamd/internal/egress/manager_test.go b/apps/streamd/internal/egress/manager_test.go
new file mode 100644
index 0000000..b355237
--- /dev/null
+++ b/apps/streamd/internal/egress/manager_test.go
@@ -0,0 +1,100 @@
+package egress
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+func TestResolveProxyOrder(t *testing.T) {
+ dir := t.TempDir()
+ store, err := db.Open(filepath.Join(dir, "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ m := New(filepath.Join(dir, "data"), store, nil, "")
+
+ // Neither proxy nor egress.
+ got, err := m.ResolveProxy(db.Stream{Name: "a"})
+ if err != nil || got != "" {
+ t.Fatalf("empty: got %q err %v", got, err)
+ }
+
+ // Explicit proxy wins over egress.
+ got, err = m.ResolveProxy(db.Stream{
+ Proxy: "socks5://127.0.0.1:9999",
+ Egress: "london",
+ })
+ if err != nil || got != "socks5://127.0.0.1:9999" {
+ t.Fatalf("proxy wins: got %q err %v", got, err)
+ }
+
+ on := true
+ _, err = store.CreateEgressProfile(db.CreateEgressProfile{
+ Name: "dublin",
+ Kind: db.EgressKindSocks,
+ Enabled: &on,
+ SocksURL: "socks5://10.0.0.5:1080",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ got, err = m.ResolveProxy(db.Stream{Egress: "dublin"})
+ if err != nil || got != "socks5://10.0.0.5:1080" {
+ t.Fatalf("egress socks: got %q err %v", got, err)
+ }
+
+ // Missing profile.
+ _, err = m.ResolveProxy(db.Stream{Egress: "missing"})
+ if err == nil {
+ t.Fatal("expected error for missing profile")
+ }
+
+ // WireGuard on non-Linux must fail EnsureUp (covered when GOOS != linux).
+ _, err = store.CreateEgressProfile(db.CreateEgressProfile{
+ Name: "london", Kind: db.EgressKindWireGuard, Enabled: &on,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = m.ResolveProxy(db.Stream{Egress: "london"})
+ // On Linux without conf/tools this also errors; on Windows always errors.
+ if err == nil {
+ t.Fatal("expected wireguard EnsureUp to fail without a working tunnel")
+ }
+}
+
+func TestWgConfParse(t *testing.T) {
+ conf := `[Interface]
+PrivateKey = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEE=
+Address = 10.64.0.2/32
+Address = fd00::2/128
+DNS = 1.1.1.1
+
+[Peer]
+PublicKey = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBEE=
+AllowedIPs = 0.0.0.0/0, ::/0
+Endpoint = 203.0.113.1:51820
+`
+ addrs := wgInterfaceAddrs(conf)
+ if len(addrs) != 2 || addrs[0] != "10.64.0.2/32" || addrs[1] != "fd00::2/128" {
+ t.Fatalf("addrs: %#v", addrs)
+ }
+ body := wgSetconfBody(conf)
+ lower := strings.ToLower(body)
+ if strings.Contains(lower, "address") || strings.Contains(lower, "dns") {
+ t.Fatalf("setconf body still has wg-quick keys:\n%s", body)
+ }
+ if !strings.Contains(body, "PrivateKey") || !strings.Contains(body, "PublicKey") {
+ t.Fatalf("setconf missing keys:\n%s", body)
+ }
+ addrs = wgInterfaceAddrs("[Interface]\nAddress = 10.1.0.2/32, 10.1.0.3/32\n")
+ if len(addrs) != 2 {
+ t.Fatalf("combined: %#v", addrs)
+ }
+}
diff --git a/apps/streamd/internal/egress/wg_linux.go b/apps/streamd/internal/egress/wg_linux.go
new file mode 100644
index 0000000..a26c3a3
--- /dev/null
+++ b/apps/streamd/internal/egress/wg_linux.go
@@ -0,0 +1,302 @@
+//go:build linux
+
+package egress
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
+ name := p.Name
+ confPath := m.confPath(name)
+ raw, err := os.ReadFile(confPath)
+ if err != nil {
+ msg := "wg.conf missing; upload a WireGuard conf first"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("egress %q: %s", name, msg)
+ }
+ addrs := wgInterfaceAddrs(string(raw))
+ if len(addrs) == 0 {
+ msg := "wg.conf has no Interface Address="
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("egress %q: %s", name, msg)
+ }
+ socksBin, err := m.findSocksBin()
+ if err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ if _, err := exec.LookPath("ip"); err != nil {
+ msg := "ip (iproute2) not found on PATH"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+ }
+ if _, err := exec.LookPath("wg"); err != nil {
+ msg := "wg (wireguard-tools) not found on PATH"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+ }
+
+ listenPort := p.ListenPort
+ if listenPort <= 0 {
+ listenPort = m.allocListenPort(p.ID)
+ }
+ hostIP, nsIP, _ := m.vethAddrs(p.ID)
+ nsName := netnsName(name)
+ wgDev := wgDevName(name)
+ hostVeth := hostVethName(name)
+ nsVeth := "hv0"
+
+ // Tear down any leftover state before bringing up.
+ _ = m.teardownWireGuard(name, p.ID)
+
+ run := func(args ...string) error {
+ cmd := exec.Command(args[0], args[1:]...)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %w (%s)", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ }
+ return nil
+ }
+ nsExec := func(args ...string) error {
+ full := append([]string{"ip", "netns", "exec", nsName}, args...)
+ return run(full...)
+ }
+
+ if err := run("ip", "netns", "add", nsName); err != nil {
+ // Already exists is fine after a partial teardown.
+ if !strings.Contains(err.Error(), "File exists") {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ }
+ // DNS inside the netns: host /etc/resolv.conf often points at
+ // 127.0.0.53 (systemd-resolved), which is unreachable from the ns.
+ // ip netns exec bind-mounts /etc/netns//resolv.conf over /etc/resolv.conf.
+ if err := writeNetnsResolv(nsName); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ // Loopback inside ns.
+ _ = nsExec("ip", "link", "set", "lo", "up")
+
+ if err := run("ip", "link", "add", wgDev, "type", "wireguard"); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ if err := run("ip", "link", "set", wgDev, "netns", nsName); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = run("ip", "link", "del", wgDev)
+ return err
+ }
+
+ setconfPath := filepath.Join(m.profileDir(name), "wg.setconf")
+ body := wgSetconfBody(string(raw))
+ if err := os.WriteFile(setconfPath, []byte(body), 0o600); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ if err := nsExec("wg", "setconf", wgDev, setconfPath); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ for _, a := range addrs {
+ if err := nsExec("ip", "address", "add", a, "dev", wgDev); err != nil {
+ // "File exists" after restart is fine.
+ if !strings.Contains(err.Error(), "File exists") {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ }
+ }
+ if err := nsExec("ip", "link", "set", wgDev, "up"); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ // Default route only inside the netns — never the host table.
+ _ = nsExec("ip", "route", "replace", "default", "dev", wgDev)
+
+ if err := run("ip", "link", "add", hostVeth, "type", "veth", "peer", "name", nsVeth); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := run("ip", "link", "set", nsVeth, "netns", nsName); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := run("ip", "addr", "add", hostIP+"/24", "dev", hostVeth); err != nil && !strings.Contains(err.Error(), "File exists") {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := run("ip", "link", "set", hostVeth, "up"); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := nsExec("ip", "addr", "add", nsIP+"/24", "dev", nsVeth); err != nil && !strings.Contains(err.Error(), "File exists") {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := nsExec("ip", "link", "set", nsVeth, "up"); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+
+ socksCmd, err := m.startSocksInNS(nsName, socksBin, nsIP)
+ if err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+
+ ln, stopFwd, err := m.startLocalForward(listenPort, nsIP, socksPortInNS)
+ if err != nil {
+ _ = socksCmd.Process.Kill()
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+
+ rs := &runState{
+ name: name,
+ listenPort: listenPort,
+ nsIP: nsIP,
+ socksCmd: socksCmd,
+ forwardLn: ln,
+ stopFwd: stopFwd,
+ }
+ m.mu.Lock()
+ m.running[name] = rs
+ m.mu.Unlock()
+
+ egressIP := probeEgressIP(nsName)
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", egressIP, listenPort)
+ m.logger().Info("egress up", "name", name, "listen", listenPort, "ns", nsName, "egress_ip", egressIP)
+ return nil
+}
+
+func (m *Manager) startSocksInNS(nsName, socksBin, bindIP string) (*exec.Cmd, error) {
+ base := filepath.Base(socksBin)
+ var cmd *exec.Cmd
+ switch {
+ case strings.Contains(base, "gost"):
+ cmd = exec.Command("ip", "netns", "exec", nsName, socksBin,
+ "-L", fmt.Sprintf("socks5://%s:%d", bindIP, socksPortInNS))
+ default:
+ // microsocks
+ cmd = exec.Command("ip", "netns", "exec", nsName, socksBin,
+ "-i", bindIP, "-p", fmt.Sprintf("%d", socksPortInNS))
+ }
+ cmd.Stdout = nil
+ cmd.Stderr = nil
+ if err := cmd.Start(); err != nil {
+ return nil, fmt.Errorf("start socks in netns: %w", err)
+ }
+ // Brief wait so a crash-on-start is visible.
+ time.Sleep(200 * time.Millisecond)
+ if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
+ return nil, fmt.Errorf("socks exited immediately")
+ }
+ return cmd, nil
+}
+
+func (m *Manager) teardownWireGuard(name string, _ int64) error {
+ nsName := netnsName(name)
+ wgDev := wgDevName(name)
+ hostVeth := hostVethName(name)
+
+ runQuiet := func(args ...string) {
+ _ = exec.Command(args[0], args[1:]...).Run()
+ }
+ runQuiet("ip", "netns", "exec", nsName, "ip", "link", "del", wgDev)
+ runQuiet("ip", "link", "del", hostVeth)
+ runQuiet("ip", "link", "del", wgDev) // if still in init ns
+ runQuiet("ip", "netns", "del", nsName)
+ _ = os.Remove(filepath.Join(m.profileDir(name), "wg.setconf"))
+ _ = os.RemoveAll(filepath.Join("/etc/netns", nsName))
+ return nil
+}
+
+// writeNetnsResolv installs public resolvers for processes inside the netns
+// (microsocks, curl probe). Without this, SOCKS5 hostname connects fail with
+// error 0x01 when the host uses systemd-resolved's 127.0.0.53 stub.
+func writeNetnsResolv(nsName string) error {
+ dir := filepath.Join("/etc/netns", nsName)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return fmt.Errorf("netns resolv dir: %w", err)
+ }
+ body := "# streamd egress — public DNS (host 127.0.0.53 is unreachable in netns)\n" +
+ "nameserver 1.1.1.1\n" +
+ "nameserver 1.0.0.1\n" +
+ "nameserver 8.8.8.8\n"
+ path := filepath.Join(dir, "resolv.conf")
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ return fmt.Errorf("netns resolv.conf: %w", err)
+ }
+ return nil
+}
+
+func netnsName(name string) string {
+ return "streamd-" + name
+}
+
+func wgDevName(name string) string {
+ // IFNAMSIZ is 15.
+ s := "wg-" + name
+ if len(s) > 15 {
+ s = s[:15]
+ }
+ return s
+}
+
+func hostVethName(name string) string {
+ s := "sv-" + name
+ if len(s) > 15 {
+ s = s[:15]
+ }
+ return s
+}
+
+func probeEgressIP(nsName string) string {
+ // Best-effort: ask a public echo over the ns default route.
+ for _, url := range []string{
+ "https://api.ipify.org",
+ "https://ifconfig.me/ip",
+ "https://1.1.1.1/cdn-cgi/trace", // fallback parse below if needed
+ } {
+ cmd := exec.Command("ip", "netns", "exec", nsName,
+ "curl", "-4", "-fsS", "--max-time", "5", url)
+ out, err := cmd.Output()
+ if err != nil {
+ continue
+ }
+ s := strings.TrimSpace(string(out))
+ if strings.Contains(url, "cdn-cgi/trace") {
+ for _, line := range strings.Split(s, "\n") {
+ if strings.HasPrefix(line, "ip=") {
+ return strings.TrimPrefix(line, "ip=")
+ }
+ }
+ continue
+ }
+ if s != "" && !strings.Contains(s, " ") {
+ return s
+ }
+ }
+ return ""
+}
diff --git a/apps/streamd/internal/egress/wg_stub.go b/apps/streamd/internal/egress/wg_stub.go
new file mode 100644
index 0000000..065d686
--- /dev/null
+++ b/apps/streamd/internal/egress/wg_stub.go
@@ -0,0 +1,19 @@
+//go:build !linux
+
+package egress
+
+import (
+ "fmt"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
+ msg := "wireguard egress requires Linux"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+}
+
+func (m *Manager) teardownWireGuard(name string, id int64) error {
+ return nil
+}
diff --git a/apps/streamd/internal/hlsgate/hlsgate.go b/apps/streamd/internal/hlsgate/hlsgate.go
new file mode 100644
index 0000000..264ece4
--- /dev/null
+++ b/apps/streamd/internal/hlsgate/hlsgate.go
@@ -0,0 +1,675 @@
+// Package hlsgate serves the published media and, for streams marked
+// on-demand, starts them when a viewer first asks for a playlist.
+//
+// It replaces a plain http.FileServer over data/www, which could only serve
+// what was already running, listed directories, and told nobody anything about
+// who was watching.
+package hlsgate
+
+import (
+ "errors"
+ "log/slog"
+ "net/http"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/httpx"
+ "streamd/apps/streamd/internal/tsfanout"
+)
+
+// Supervisor is the subset of the media supervisor the gate needs.
+type Supervisor interface {
+ Start(id int64) error
+ Stop(id int64) error
+ Running(id int64) bool
+}
+
+// CaptureRequester asks connected agents for fresh credentials now.
+type CaptureRequester interface {
+ RequestCapture(st db.Stream, reason string) int
+}
+
+// Defaults.
+const (
+ // DefaultWait is how long a viewer's request is held while a stream
+ // starts. Long enough for ffmpeg to produce a first segment, short enough
+ // that a browser does not give up on its own.
+ DefaultWait = 30 * time.Second
+ // DefaultCaptureWait applies when credentials must be captured first,
+ // which involves a real phone and takes far longer.
+ DefaultCaptureWait = 120 * time.Second
+ // viewerWindow is how long a client counts as watching after its last
+ // request. A player fetches a segment every few seconds, so a minute is
+ // generous without being stale.
+ viewerWindow = 60 * time.Second
+ idleCheckTick = 30 * time.Second
+ pollInterval = 250 * time.Millisecond
+)
+
+// Config is the gate's settings. It is separate from Gate so it can be passed
+// by value without copying the gate's mutex.
+type Config struct {
+ Store *db.Store
+ WWWRoot string
+ Sup Supervisor
+ Fanout *tsfanout.Set
+ Capture CaptureRequester
+ Trust httpx.Trust
+ Log *slog.Logger
+
+ // Wait and CaptureWait bound how long a request is held.
+ Wait time.Duration
+ CaptureWait time.Duration
+}
+
+type Gate struct {
+ Config
+
+ mu sync.Mutex
+ tracks map[string]*track
+ waking map[int64]*wake
+
+ // wakeLimiter bounds how often an anonymous caller can trigger a start.
+ // Waking a stream spawns processes, so it is the one unauthenticated
+ // action here with real cost.
+ wakeLimiter *auth.Limiter
+}
+
+// track is the live request picture for one stream.
+type track struct {
+ lastRequest time.Time
+ requests int64
+ // clients maps a client address to its last request time, giving a
+ // distinct-viewer count over the window rather than a request count.
+ clients map[string]time.Time
+}
+
+// wake is the single-flight state for one stream being started.
+type wake struct {
+ done chan struct{}
+ err error
+ started time.Time
+}
+
+func New(cfg Config) *Gate {
+ out := &Gate{Config: cfg}
+ if out.Wait <= 0 {
+ out.Wait = DefaultWait
+ }
+ if out.CaptureWait <= 0 {
+ out.CaptureWait = DefaultCaptureWait
+ }
+ if out.Log == nil {
+ out.Log = slog.Default()
+ }
+ out.tracks = map[string]*track{}
+ out.waking = map[int64]*wake{}
+ // Eight wakes per client, refilling slowly: enough for a person opening a
+ // few channels, not enough to be used as a process-spawning amplifier.
+ out.wakeLimiter = auth.NewLimiter(8, 0.1)
+ return out
+}
+
+func (g *Gate) Mount(mux *http.ServeMux) {
+ mux.Handle("/hls/", http.HandlerFunc(g.serveHLS))
+ mux.Handle("/live/", http.HandlerFunc(g.serveLive))
+}
+
+// target is a resolved request: which stream, which rung, which file.
+type target struct {
+ stream db.Stream
+ variant db.VariantSpec
+ // dir is the www subdirectory, i.e. the stream or variant directory name.
+ dir string
+ // rel is the file path within dir ("index.m3u8", "cmaf/index.m3u8", ...).
+ rel string
+ // isPlaylist marks the requests that may wake a stream.
+ isPlaylist bool
+}
+
+var errNotFound = errors.New("no such stream")
+
+// resolve maps a www directory name onto a stream and rung.
+//
+// The layout is "" for the source rung and "-" for the
+// others, and a stream name may itself contain a dash — so an exact match is
+// tried first, and only then a split at the last dash whose suffix is a real
+// rung of the stream that remains.
+func (g *Gate) resolve(dir string) (db.Stream, db.VariantSpec, error) {
+ if dir == "" {
+ return db.Stream{}, db.VariantSpec{}, errNotFound
+ }
+ if st, err := g.Store.GetStreamByName(dir); err == nil {
+ return st, sourceRung(st), nil
+ }
+ // Try progressively earlier dashes, so "a-b-hd" resolves against a stream
+ // called "a-b" even though "a" also exists.
+ for i := strings.LastIndex(dir, "-"); i > 0; i = strings.LastIndex(dir[:i], "-") {
+ name, variantID := dir[:i], dir[i+1:]
+ st, err := g.Store.GetStreamByName(name)
+ if err != nil {
+ continue
+ }
+ for _, v := range db.ParseVariantsJSON(st.VariantsJSON) {
+ if v.ID == variantID {
+ return st, v, nil
+ }
+ }
+ }
+ return db.Stream{}, db.VariantSpec{}, errNotFound
+}
+
+func sourceRung(st db.Stream) db.VariantSpec {
+ for _, v := range db.ParseVariantsJSON(st.VariantsJSON) {
+ if v.IsSource() {
+ return v
+ }
+ }
+ return db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true}
+}
+
+// serveHLS handles /hls//.
+func (g *Gate) serveHLS(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ rest := strings.TrimPrefix(r.URL.Path, "/hls/")
+ // A trailing slash or a bare /hls/ used to produce a directory listing,
+ // which enumerated every stream on the server.
+ if rest == "" || strings.HasSuffix(rest, "/") {
+ http.NotFound(w, r)
+ return
+ }
+ dir, rel, ok := strings.Cut(rest, "/")
+ if !ok || rel == "" {
+ http.NotFound(w, r)
+ return
+ }
+ st, variant, err := g.resolve(dir)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ // Reject anything that tries to climb out of the stream's directory
+ // before it is ever joined to a filesystem path.
+ clean := path.Clean("/" + rel)
+ if clean == "/" || strings.Contains(clean, "..") {
+ http.NotFound(w, r)
+ return
+ }
+ rel = strings.TrimPrefix(clean, "/")
+
+ t := target{
+ stream: st,
+ variant: variant,
+ dir: dir,
+ rel: rel,
+ isPlaylist: isPlaylist(rel),
+ }
+ if !g.authorise(w, r, st) {
+ return
+ }
+ g.note(st.Name, g.Trust.ClientIP(r))
+
+ full := filepath.Join(g.WWWRoot, filepath.FromSlash(dir), filepath.FromSlash(rel))
+ if _, err := os.Stat(full); err != nil {
+ // Only a playlist request may wake a stream. A segment request for a
+ // stream that is not running is simply a 404: starting a stream would
+ // not produce that particular segment anyway.
+ if !t.isPlaylist || !g.shouldWake(st) {
+ http.NotFound(w, r)
+ return
+ }
+ if !g.waitForStart(w, r, t, full) {
+ return
+ }
+ }
+ g.serveFile(w, r, full, rel)
+}
+
+// serveLive handles /live/.ts, the progressive MPEG-TS output.
+func (g *Gate) serveLive(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ name := strings.TrimPrefix(r.URL.Path, "/live/")
+ if !strings.HasSuffix(name, ".ts") {
+ http.NotFound(w, r)
+ return
+ }
+ dir := strings.TrimSuffix(name, ".ts")
+ if dir == "" || strings.ContainsAny(dir, "/\\") {
+ http.NotFound(w, r)
+ return
+ }
+ st, _, err := g.resolve(dir)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ if !tsEnabled(st) {
+ http.Error(w, "this stream does not publish a progressive MPEG-TS output", http.StatusNotFound)
+ return
+ }
+ if !g.authorise(w, r, st) {
+ return
+ }
+ g.note(st.Name, g.Trust.ClientIP(r))
+
+ ring, ok := g.Fanout.Get(dir)
+ if !ok {
+ // Nothing is publishing yet: wake it if we may, then wait for a ring.
+ if !g.shouldWake(st) {
+ http.Error(w, "stream is not running", http.StatusServiceUnavailable)
+ return
+ }
+ if !g.wakeAndWaitRing(w, r, st, dir) {
+ return
+ }
+ ring, ok = g.Fanout.Get(dir)
+ if !ok {
+ g.retryLater(w, "stream did not start in time")
+ return
+ }
+ }
+
+ if r.Method == http.MethodHead {
+ w.Header().Set("Content-Type", "video/mp2t")
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+
+ reader := ring.NewReader()
+ defer reader.Close()
+
+ h := w.Header()
+ h.Set("Content-Type", "video/mp2t")
+ h.Set("Cache-Control", "no-store")
+ // Defeat proxy buffering, or the viewer waits for a buffer to fill.
+ h.Set("X-Accel-Buffering", "no")
+ w.WriteHeader(http.StatusOK)
+
+ flusher, _ := w.(http.Flusher)
+ buf := make([]byte, 64<<10)
+ ctx := r.Context()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ n, err := reader.Read(buf)
+ if n > 0 {
+ if _, werr := w.Write(buf[:n]); werr != nil {
+ return
+ }
+ if flusher != nil {
+ flusher.Flush()
+ }
+ // A request that is actively pulling bytes is a live viewer, but
+ // re-noting on every chunk would be pointless work; the ring's
+ // own reader count covers the fine grain.
+ }
+ if err != nil {
+ if errors.Is(err, tsfanout.ErrLagged) {
+ g.Log.Info("dropped a progressive-TS client that fell behind",
+ "stream", st.Name, "ip", g.Trust.ClientIP(r))
+ }
+ return
+ }
+ }
+}
+
+func tsEnabled(st db.Stream) bool {
+ for _, o := range db.EnabledOutputs(db.ParseOutputsJSON(st.OutputsJSON)) {
+ if o.Format == db.FormatTS {
+ return true
+ }
+ }
+ return false
+}
+
+func isPlaylist(rel string) bool {
+ l := strings.ToLower(rel)
+ return strings.HasSuffix(l, ".m3u8") || strings.HasSuffix(l, ".mpd")
+}
+
+// authorise enforces the per-stream public flag. A public stream is readable
+// by anyone, which is what makes on-demand work; a private one needs a
+// principal.
+func (g *Gate) authorise(w http.ResponseWriter, r *http.Request, st db.Stream) bool {
+ if st.Public {
+ return true
+ }
+ if p := auth.From(r); p != nil {
+ return true
+ }
+ w.Header().Set("WWW-Authenticate", `Bearer realm="streamd"`)
+ http.Error(w, "this stream is not public", http.StatusUnauthorized)
+ return false
+}
+
+// shouldWake reports whether this request may start the stream.
+// Deliberately NOT conditioned on the stream being stopped: when twenty
+// viewers arrive together, the first one starts it and the rest must wait for
+// the same playlist. Checking Running() here meant everyone after the first
+// got a 404 while the stream was still starting. startOnce is what makes sure
+// only one start actually happens.
+func (g *Gate) shouldWake(st db.Stream) bool {
+ if !st.OnDemand || !st.Enabled {
+ return false
+ }
+ // Nothing to start from: no manifest, and no agent able to fetch one.
+ if strings.TrimSpace(st.MPD) == "" && !st.NeedsCapture {
+ return false
+ }
+ return true
+}
+
+// waitForStart holds the request while the stream comes up. Returns true when
+// the file now exists and may be served.
+func (g *Gate) waitForStart(w http.ResponseWriter, r *http.Request, t target, full string) bool {
+ ip := g.Trust.ClientIP(r)
+ if !g.wakeLimiter.Allow(ip) {
+ g.retryLater(w, "too many start requests from this client")
+ return false
+ }
+ st := t.stream
+ deadline := g.Wait
+ // Credentials have to be captured first, which involves a real phone and
+ // is far slower than starting a packager.
+ if st.NeedsCapture {
+ deadline = g.CaptureWait
+ }
+ if err := g.startOnce(st); err != nil {
+ g.Log.Error("on-demand start failed", "stream", st.Name, "err", err)
+ g.retryLater(w, "stream could not be started")
+ return false
+ }
+
+ ctx := r.Context()
+ give := time.Now().Add(deadline)
+ for time.Now().Before(give) {
+ select {
+ case <-ctx.Done():
+ // The viewer gave up; the stream stays up for the idle timeout so
+ // their retry is instant.
+ return false
+ case <-time.After(pollInterval):
+ }
+ if fi, err := os.Stat(full); err == nil && fi.Size() > 0 {
+ // A playlist exists; make sure it lists at least one segment, or
+ // the player gets an empty playlist and stops.
+ if !t.isPlaylist || playlistHasSegment(full) {
+ g.note(st.Name, ip)
+ return true
+ }
+ }
+ }
+ g.retryLater(w, "stream is still starting")
+ return false
+}
+
+// wakeAndWaitRing starts a stream and waits for its progressive-TS ring.
+func (g *Gate) wakeAndWaitRing(w http.ResponseWriter, r *http.Request, st db.Stream, dir string) bool {
+ ip := g.Trust.ClientIP(r)
+ if !g.wakeLimiter.Allow(ip) {
+ g.retryLater(w, "too many start requests from this client")
+ return false
+ }
+ deadline := g.Wait
+ if st.NeedsCapture {
+ deadline = g.CaptureWait
+ }
+ if err := g.startOnce(st); err != nil {
+ g.retryLater(w, "stream could not be started")
+ return false
+ }
+ ctx := r.Context()
+ give := time.Now().Add(deadline)
+ for time.Now().Before(give) {
+ select {
+ case <-ctx.Done():
+ return false
+ case <-time.After(pollInterval):
+ }
+ if _, ok := g.Fanout.Get(dir); ok {
+ return true
+ }
+ }
+ g.retryLater(w, "stream is still starting")
+ return false
+}
+
+// startOnce starts a stream under a per-stream single flight, so twenty
+// viewers arriving together produce one start, not twenty.
+func (g *Gate) startOnce(st db.Stream) error {
+ g.mu.Lock()
+ if wk, ok := g.waking[st.ID]; ok {
+ g.mu.Unlock()
+ // Someone else is already starting it; wait for their result.
+ <-wk.done
+ return wk.err
+ }
+ if g.Sup.Running(st.ID) {
+ // Already up, or already coming up from an earlier request: there is
+ // nothing to start, only a playlist to wait for. Calling Start again
+ // would restart a healthy stream and cut off its current viewers.
+ g.noteLocked(st.Name, "")
+ g.mu.Unlock()
+ return nil
+ }
+ wk := &wake{done: make(chan struct{}), started: time.Now()}
+ g.waking[st.ID] = wk
+ // Count the wake as activity straight away, so the idle sweep cannot stop
+ // the stream before the first viewer has been served.
+ g.noteLocked(st.Name, "")
+ g.mu.Unlock()
+
+ g.Log.Info("waking on-demand stream", "stream", st.Name, "needs_capture", st.NeedsCapture)
+ g.Store.AddEvent(db.StreamEvent{
+ StreamID: st.ID, Kind: db.EventOnDemandWake, Severity: db.SevInfo,
+ Message: "a viewer requested this stream, starting it",
+ })
+ // Credentials may be stale. Ask any connected agent to refresh now rather
+ // than on its next poll, with a viewer already waiting.
+ if st.NeedsCapture && g.Capture != nil {
+ if n := g.Capture.RequestCapture(st, "ondemand_wake"); n > 0 {
+ g.Log.Info("asked agents for fresh credentials", "stream", st.Name, "agents", n)
+ }
+ }
+
+ err := g.Sup.Start(st.ID)
+
+ g.mu.Lock()
+ wk.err = err
+ delete(g.waking, st.ID)
+ g.mu.Unlock()
+ close(wk.done)
+ return err
+}
+
+// playlistHasSegment reports whether a media playlist lists at least one
+// segment. A freshly created but empty playlist makes a player give up.
+func playlistHasSegment(p string) bool {
+ b, err := os.ReadFile(p)
+ if err != nil {
+ return false
+ }
+ body := string(b)
+ if strings.HasSuffix(strings.ToLower(p), ".mpd") {
+ // A DASH manifest is self-describing; its presence is enough.
+ return strings.Contains(body, " 1 {
+ for k, seen := range t.clients {
+ if nowT.Sub(seen) > viewerWindow {
+ delete(t.clients, k)
+ }
+ }
+ }
+ }
+}
+
+// ViewersFor is the number of distinct clients seen in the last minute, plus
+// any progressive-TS readers currently attached.
+func (g *Gate) ViewersFor(name string) int {
+ g.mu.Lock()
+ t, ok := g.tracks[name]
+ n := 0
+ if ok {
+ nowT := time.Now()
+ for _, seen := range t.clients {
+ if nowT.Sub(seen) <= viewerWindow {
+ n++
+ }
+ }
+ }
+ g.mu.Unlock()
+ if g.Fanout != nil {
+ n += g.Fanout.Readers(name)
+ }
+ return n
+}
+
+// RunIdleLoop stops on-demand streams nobody is watching.
+func (g *Gate) RunIdleLoop(stop <-chan struct{}) {
+ t := time.NewTicker(idleCheckTick)
+ defer t.Stop()
+ for {
+ select {
+ case <-stop:
+ return
+ case <-t.C:
+ g.sweepIdle()
+ }
+ }
+}
+
+func (g *Gate) sweepIdle() {
+ list, err := g.Store.ListStreams()
+ if err != nil {
+ return
+ }
+ for _, st := range list {
+ if !st.OnDemand || !g.Sup.Running(st.ID) {
+ continue
+ }
+ idle := time.Duration(st.IdleTimeoutS) * time.Second
+ if idle <= 0 {
+ idle = db.DefaultIdleTimeoutS * time.Second
+ }
+ // A progressive-TS client holds an open connection rather than
+ // polling, so it would otherwise look idle the whole time it watched.
+ if g.Fanout != nil && g.Fanout.Readers(st.Name) > 0 {
+ g.note(st.Name, "")
+ continue
+ }
+ g.mu.Lock()
+ t, seen := g.tracks[st.Name]
+ var last time.Time
+ if seen {
+ last = t.lastRequest
+ }
+ g.mu.Unlock()
+ if !seen || last.IsZero() {
+ // Running but never requested through the gate: it was started by
+ // hand or by a schedule, so leave it alone.
+ continue
+ }
+ if time.Since(last) < idle {
+ continue
+ }
+ g.Log.Info("stopping idle on-demand stream",
+ "stream", st.Name, "idle_s", int(time.Since(last).Seconds()))
+ g.Store.AddEvent(db.StreamEvent{
+ StreamID: st.ID, Kind: db.EventIdleStop, Severity: db.SevInfo,
+ Message: "no viewers for " + idle.String() + ", stopping until the next request",
+ })
+ if err := g.Sup.Stop(st.ID); err != nil {
+ g.Log.Error("idle stop failed", "stream", st.Name, "err", err)
+ continue
+ }
+ g.mu.Lock()
+ delete(g.tracks, st.Name)
+ g.mu.Unlock()
+ }
+}
diff --git a/apps/streamd/internal/hlsgate/hlsgate_test.go b/apps/streamd/internal/hlsgate/hlsgate_test.go
new file mode 100644
index 0000000..8fe07ad
--- /dev/null
+++ b/apps/streamd/internal/hlsgate/hlsgate_test.go
@@ -0,0 +1,642 @@
+package hlsgate
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/tsfanout"
+)
+
+// fakeSup records what the gate asked for, and can pretend a stream comes up.
+type fakeSup struct {
+ mu sync.Mutex
+ starts int32
+ stops int32
+ running map[int64]bool
+ onStart func(id int64)
+ startErr error
+}
+
+func newFakeSup() *fakeSup {
+ return &fakeSup{running: map[int64]bool{}}
+}
+
+func (f *fakeSup) Start(id int64) error {
+ atomic.AddInt32(&f.starts, 1)
+ if f.startErr != nil {
+ return f.startErr
+ }
+ f.mu.Lock()
+ f.running[id] = true
+ cb := f.onStart
+ f.mu.Unlock()
+ if cb != nil {
+ cb(id)
+ }
+ return nil
+}
+
+func (f *fakeSup) Stop(id int64) error {
+ atomic.AddInt32(&f.stops, 1)
+ f.mu.Lock()
+ f.running[id] = false
+ f.mu.Unlock()
+ return nil
+}
+
+func (f *fakeSup) Running(id int64) bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.running[id]
+}
+
+type fakeCapture struct{ n int32 }
+
+func (c *fakeCapture) RequestCapture(st db.Stream, reason string) int {
+ atomic.AddInt32(&c.n, 1)
+ return 1
+}
+
+func newTestGate(t *testing.T) (*Gate, *db.Store, *fakeSup, string) {
+ t.Helper()
+ dir := t.TempDir()
+ store, err := db.Open(filepath.Join(dir, "db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+ www := filepath.Join(dir, "www")
+ if err := os.MkdirAll(www, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ sup := newFakeSup()
+ g := New(Config{
+ Store: store,
+ WWWRoot: www,
+ Sup: sup,
+ Fanout: tsfanout.NewSet(1 << 16),
+ Wait: 2 * time.Second,
+ })
+ return g, store, sup, www
+}
+
+func mkStream(t *testing.T, store *db.Store, in db.CreateStream) db.Stream {
+ t.Helper()
+ st, err := store.CreateStream(in)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return st
+}
+
+func writeFile(t *testing.T, path, body string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+const livePlaylist = "#EXTM3U\n#EXT-X-VERSION:3\n#EXTINF:4.0,\nseg_00001.ts\n"
+
+// ---------- path resolution ----------
+
+// A stream name may contain a dash, so "city-news-hd" must resolve as the
+// "hd" rung of "city-news", while "city-news" resolves as its own source rung.
+func TestResolveStreamNamesContainingDashes(t *testing.T) {
+ g, store, _, _ := newTestGate(t)
+ variants, err := db.EncodeVariantsJSON([]db.VariantSpec{
+ {ID: db.SourceVariantID, Enabled: true},
+ {ID: "hd", Enabled: true, Height: 720},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ mkStream(t, store, db.CreateStream{Name: "city-news", VariantsJSON: variants})
+ mkStream(t, store, db.CreateStream{Name: "city", VariantsJSON: variants})
+ // A stream whose literal name ends in -hd must win over being read as a
+ // rung of another stream.
+ mkStream(t, store, db.CreateStream{Name: "sport-hd"})
+
+ cases := []struct {
+ dir string
+ wantStream string
+ wantVariant string
+ }{
+ {"city-news", "city-news", db.SourceVariantID},
+ {"city-news-hd", "city-news", "hd"},
+ {"city", "city", db.SourceVariantID},
+ {"city-hd", "city", "hd"},
+ {"sport-hd", "sport-hd", db.SourceVariantID},
+ }
+ for _, c := range cases {
+ st, v, err := g.resolve(c.dir)
+ if err != nil {
+ t.Errorf("resolve(%q) failed: %v", c.dir, err)
+ continue
+ }
+ if st.Name != c.wantStream || v.ID != c.wantVariant {
+ t.Errorf("resolve(%q) = %s/%s, want %s/%s",
+ c.dir, st.Name, v.ID, c.wantStream, c.wantVariant)
+ }
+ }
+ for _, bad := range []string{"", "nope", "city-news-4k", "city-news-hd-extra"} {
+ if _, _, err := g.resolve(bad); err == nil {
+ t.Errorf("resolve(%q) should have failed", bad)
+ }
+ }
+}
+
+// ---------- traversal ----------
+
+func TestPathTraversalRejected(t *testing.T) {
+ g, store, _, www := newTestGate(t)
+ mkStream(t, store, db.CreateStream{Name: "news"})
+ // A secret outside the media root, as a credible target.
+ writeFile(t, filepath.Join(filepath.Dir(www), "streamd.db"), "SECRET")
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+
+ srv := httptest.NewServer(http.HandlerFunc(g.serveHLS))
+ defer srv.Close()
+
+ for _, p := range []string{
+ "/hls/news/../../streamd.db",
+ "/hls/news/..%2f..%2fstreamd.db",
+ "/hls/news/%2e%2e/%2e%2e/streamd.db",
+ "/hls/news/....//....//streamd.db",
+ "/hls/../streamd.db",
+ } {
+ req, err := http.NewRequest(http.MethodGet, srv.URL+p, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := http.DefaultTransport.RoundTrip(req)
+ if err != nil {
+ continue
+ }
+ body := make([]byte, 64)
+ n, _ := resp.Body.Read(body)
+ _ = resp.Body.Close()
+ if resp.StatusCode == http.StatusOK && string(body[:n]) == "SECRET" {
+ t.Errorf("traversal succeeded for %q", p)
+ }
+ }
+}
+
+func TestDirectoryListingRefused(t *testing.T) {
+ g, store, _, www := newTestGate(t)
+ mkStream(t, store, db.CreateStream{Name: "news"})
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+
+ for _, p := range []string{"/hls/", "/hls/news/", "/hls/news"} {
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, p, nil))
+ if rec.Code == http.StatusOK {
+ t.Errorf("%s returned 200; a listing would enumerate every stream", p)
+ }
+ }
+}
+
+// ---------- serving ----------
+
+func TestServesExistingPlaylistWithCacheHeaders(t *testing.T) {
+ g, store, _, www := newTestGate(t)
+ mkStream(t, store, db.CreateStream{Name: "news"})
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+ writeFile(t, filepath.Join(www, "news", "seg_00001.ts"), "mediabytes")
+
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("playlist: %d %s", rec.Code, rec.Body.String())
+ }
+ if ct := rec.Header().Get("Content-Type"); ct != "application/vnd.apple.mpegurl" {
+ t.Errorf("playlist content type = %q", ct)
+ }
+ // A live playlist must not be cached, or viewers stick on a stale window.
+ if cc := rec.Header().Get("Cache-Control"); cc == "" || !contains(cc, "no-cache") {
+ t.Errorf("playlist cache-control = %q, want no-cache", cc)
+ }
+
+ rec = httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/seg_00001.ts", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("segment: %d", rec.Code)
+ }
+ // A segment never changes under its name, so it is cacheable forever.
+ if cc := rec.Header().Get("Cache-Control"); !contains(cc, "immutable") {
+ t.Errorf("segment cache-control = %q, want immutable", cc)
+ }
+}
+
+func contains(h, needle string) bool {
+ return len(h) >= len(needle) && (h == needle || indexOf(h, needle) >= 0)
+}
+
+func indexOf(h, needle string) int {
+ for i := 0; i+len(needle) <= len(h); i++ {
+ if h[i:i+len(needle)] == needle {
+ return i
+ }
+ }
+ return -1
+}
+
+// ---------- on-demand wake ----------
+
+func TestWakeStartsStreamAndServesOnceReady(t *testing.T) {
+ g, store, sup, www := newTestGate(t)
+ on := true
+ st := mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
+ })
+ // The supervisor "starts" by producing a playlist, as the real one does.
+ sup.onStart = func(id int64) {
+ go func() {
+ time.Sleep(150 * time.Millisecond)
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+ }()
+ }
+
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("want the request held until ready, got %d %s", rec.Code, rec.Body.String())
+ }
+ if got := atomic.LoadInt32(&sup.starts); got != 1 {
+ t.Errorf("starts = %d, want 1", got)
+ }
+ // The wake must be on the stream's timeline.
+ _ = store.FlushHistory()
+ events, err := store.ListEvents(st.ID, 20, db.EventOnDemandWake, "")
+ if err != nil || len(events) == 0 {
+ t.Errorf("expected an ondemand_wake event, got %v (%v)", events, err)
+ }
+}
+
+// Twenty viewers arriving together must produce one start, not twenty.
+func TestWakeIsSingleFlight(t *testing.T) {
+ g, store, sup, www := newTestGate(t)
+ on := true
+ mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
+ })
+ var once sync.Once
+ sup.onStart = func(id int64) {
+ once.Do(func() {
+ go func() {
+ time.Sleep(200 * time.Millisecond)
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+ }()
+ })
+ }
+
+ const clients = 20
+ var wg sync.WaitGroup
+ codes := make([]int, clients)
+ for i := 0; i < clients; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
+ // Distinct client addresses, so the per-IP wake limiter does not
+ // mask the single-flight behaviour being tested.
+ req.RemoteAddr = fmt.Sprintf("10.0.0.%d:1234", i+1)
+ g.serveHLS(rec, req)
+ codes[i] = rec.Code
+ }(i)
+ }
+ wg.Wait()
+
+ if got := atomic.LoadInt32(&sup.starts); got != 1 {
+ t.Errorf("concurrent wakes started the stream %d times, want exactly 1", got)
+ }
+ for i, c := range codes {
+ if c != http.StatusOK {
+ t.Errorf("client %d got %d, want 200", i, c)
+ }
+ }
+}
+
+func TestWakeTimesOutWithRetryAfter(t *testing.T) {
+ g, store, sup, _ := newTestGate(t)
+ g.Wait = 300 * time.Millisecond
+ on := true
+ mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
+ })
+ // Starts, but never produces media.
+ sup.onStart = func(id int64) {}
+
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Errorf("want 503 when the stream does not come up, got %d", rec.Code)
+ }
+ if ra := rec.Header().Get("Retry-After"); ra == "" {
+ t.Error("a 503 should carry Retry-After so players back off sensibly")
+ }
+}
+
+// A stream that is not marked on-demand must never be started by a request.
+func TestNonOnDemandStreamIsNotWoken(t *testing.T) {
+ g, store, sup, _ := newTestGate(t)
+ yes := true
+ no := false
+ mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &no, Enabled: &yes,
+ })
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("want 404, got %d", rec.Code)
+ }
+ if got := atomic.LoadInt32(&sup.starts); got != 0 {
+ t.Errorf("a non-on-demand stream was started %d times", got)
+ }
+}
+
+// Only a playlist may wake a stream. Starting one to serve a specific old
+// segment would not produce that segment anyway.
+func TestSegmentRequestDoesNotWake(t *testing.T) {
+ g, store, sup, _ := newTestGate(t)
+ on := true
+ mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
+ })
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/seg_00042.ts", nil))
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("want 404 for a segment on a stopped stream, got %d", rec.Code)
+ }
+ if got := atomic.LoadInt32(&sup.starts); got != 0 {
+ t.Errorf("a segment request woke the stream %d times", got)
+ }
+}
+
+// An empty playlist makes a player give up, so the gate must keep waiting
+// until a segment is listed.
+func TestWakeWaitsForASegmentNotJustAFile(t *testing.T) {
+ g, store, sup, www := newTestGate(t)
+ g.Wait = 2 * time.Second
+ on := true
+ mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
+ })
+ sup.onStart = func(id int64) {
+ go func() {
+ // First an empty playlist, as ffmpeg briefly writes...
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), "#EXTM3U\n#EXT-X-VERSION:3\n")
+ time.Sleep(300 * time.Millisecond)
+ // ...then one with a segment.
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+ }()
+ }
+ start := time.Now()
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("got %d", rec.Code)
+ }
+ if time.Since(start) < 250*time.Millisecond {
+ t.Error("served an empty playlist instead of waiting for a segment")
+ }
+ if !contains(rec.Body.String(), "#EXTINF") {
+ t.Error("served playlist has no segment")
+ }
+}
+
+// A woken stream with stale credentials must trigger a capture push, not wait
+// for the agent's next poll.
+func TestWakeRequestsCaptureWhenCredentialsAreStale(t *testing.T) {
+ g, store, sup, _ := newTestGate(t)
+ capReq := &fakeCapture{}
+ g.Capture = capReq
+ g.Wait = 200 * time.Millisecond
+ // needs_capture switches the gate to the longer CaptureWait deadline, so
+ // that is the one this test has to shorten.
+ g.CaptureWait = 300 * time.Millisecond
+ on := true
+ // Enabled, on-demand, DRM required but no key: needs_capture is true.
+ mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
+ DRMMode: db.DRMYes,
+ })
+ sup.onStart = func(id int64) {}
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
+ if got := atomic.LoadInt32(&capReq.n); got != 1 {
+ t.Errorf("capture requests = %d, want 1", got)
+ }
+ _ = rec
+}
+
+// ---------- access control ----------
+
+func TestPrivateStreamNeedsAPrincipal(t *testing.T) {
+ g, store, _, www := newTestGate(t)
+ no := false
+ mkStream(t, store, db.CreateStream{Name: "internal", Public: &no})
+ writeFile(t, filepath.Join(www, "internal", "index.m3u8"), livePlaylist)
+
+ rec := httptest.NewRecorder()
+ g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/internal/index.m3u8", nil))
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("a private stream should need auth, got %d", rec.Code)
+ }
+
+ // With a principal attached it is served.
+ req := httptest.NewRequest(http.MethodGet, "/hls/internal/index.m3u8", nil)
+ req = req.WithContext(auth.WithPrincipal(req.Context(),
+ &auth.Principal{Kind: auth.ActorUser, Role: auth.RoleViewer, Name: "op"}))
+ rec = httptest.NewRecorder()
+ g.serveHLS(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Errorf("an authenticated request should be served, got %d", rec.Code)
+ }
+}
+
+// ---------- viewers ----------
+
+func TestViewerCountIsDistinctClientsNotRequests(t *testing.T) {
+ g, store, _, www := newTestGate(t)
+ mkStream(t, store, db.CreateStream{Name: "news"})
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+
+ // One client, many requests: still one viewer.
+ for i := 0; i < 10; i++ {
+ req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
+ req.RemoteAddr = "198.51.100.7:4000"
+ g.serveHLS(httptest.NewRecorder(), req)
+ }
+ if got := g.ViewersFor("news"); got != 1 {
+ t.Errorf("viewers = %d after 10 requests from one client, want 1", got)
+ }
+
+ // Three clients: three viewers.
+ for _, ip := range []string{"198.51.100.8:1", "198.51.100.9:1"} {
+ req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
+ req.RemoteAddr = ip
+ g.serveHLS(httptest.NewRecorder(), req)
+ }
+ if got := g.ViewersFor("news"); got != 3 {
+ t.Errorf("viewers = %d, want 3", got)
+ }
+ if got := g.ViewersFor("nosuchstream"); got != 0 {
+ t.Errorf("unknown stream viewers = %d, want 0", got)
+ }
+}
+
+// ---------- idle stop ----------
+
+func TestIdleSweepStopsUnwatchedOnDemandStream(t *testing.T) {
+ g, store, sup, www := newTestGate(t)
+ on := true
+ idle := 1 // one second
+ st := mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd",
+ OnDemand: &on, Enabled: &on, IdleTimeoutS: &idle,
+ })
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+ sup.running[st.ID] = true
+
+ // A viewer arrives, so it is not idle yet.
+ req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
+ req.RemoteAddr = "203.0.113.5:9"
+ g.serveHLS(httptest.NewRecorder(), req)
+
+ g.sweepIdle()
+ if got := atomic.LoadInt32(&sup.stops); got != 0 {
+ t.Fatalf("stopped a stream that was just requested (%d stops)", got)
+ }
+
+ // Let the idle window pass.
+ time.Sleep(1100 * time.Millisecond)
+ g.sweepIdle()
+ if got := atomic.LoadInt32(&sup.stops); got != 1 {
+ t.Errorf("stops = %d, want 1 after the idle window", got)
+ }
+ _ = store.FlushHistory()
+ events, _ := store.ListEvents(st.ID, 20, db.EventIdleStop, "")
+ if len(events) == 0 {
+ t.Error("expected an idle_stop event on the timeline")
+ }
+}
+
+// A stream started by hand or by a schedule must not be stopped by the idle
+// sweep just because nobody has pulled it through the gate.
+func TestIdleSweepLeavesManuallyStartedStreams(t *testing.T) {
+ g, store, sup, _ := newTestGate(t)
+ on := true
+ idle := 1
+ st := mkStream(t, store, db.CreateStream{
+ Name: "council", MPD: "https://origin.test/a.mpd",
+ OnDemand: &on, Enabled: &on, IdleTimeoutS: &idle,
+ })
+ sup.running[st.ID] = true
+ time.Sleep(1100 * time.Millisecond)
+ g.sweepIdle()
+ if got := atomic.LoadInt32(&sup.stops); got != 0 {
+ t.Errorf("stopped a stream that was never requested through the gate (%d stops)", got)
+ }
+}
+
+// An always-on stream is never stopped for being idle.
+func TestIdleSweepIgnoresAlwaysOnStreams(t *testing.T) {
+ g, store, sup, www := newTestGate(t)
+ yes := true
+ no := false
+ idle := 1
+ st := mkStream(t, store, db.CreateStream{
+ Name: "news", MPD: "https://origin.test/a.mpd",
+ OnDemand: &no, Enabled: &yes, IdleTimeoutS: &idle,
+ })
+ writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
+ sup.running[st.ID] = true
+ req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
+ req.RemoteAddr = "203.0.113.6:9"
+ g.serveHLS(httptest.NewRecorder(), req)
+ time.Sleep(1100 * time.Millisecond)
+ g.sweepIdle()
+ if got := atomic.LoadInt32(&sup.stops); got != 0 {
+ t.Errorf("an always-on stream was idle-stopped (%d stops)", got)
+ }
+}
+
+// ---------- progressive TS ----------
+
+func TestLiveTSRequiresTheOutputToBeEnabled(t *testing.T) {
+ g, store, _, _ := newTestGate(t)
+ // Default outputs are HLS only, so /live/ must refuse.
+ mkStream(t, store, db.CreateStream{Name: "news"})
+ rec := httptest.NewRecorder()
+ g.serveLive(rec, httptest.NewRequest(http.MethodGet, "/live/news.ts", nil))
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("want 404 when the TS output is off, got %d", rec.Code)
+ }
+}
+
+func TestLiveTSServesFromTheRing(t *testing.T) {
+ g, store, _, _ := newTestGate(t)
+ outputs, err := db.EncodeOutputsJSON([]db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ {ID: "ts", Format: db.FormatTS, Enabled: true},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ mkStream(t, store, db.CreateStream{Name: "news", OutputsJSON: outputs})
+
+ ring := g.Fanout.Create("news")
+ // A PAT packet so a joining reader has a decodable starting point.
+ pkt := make([]byte, 188)
+ pkt[0] = 0x47
+ pkt[3] = 0x10
+ for i := 4; i < 188; i++ {
+ pkt[i] = 0xAB
+ }
+ _, _ = ring.Write(pkt)
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/live/news.ts", nil)
+ // Close the ring shortly so the handler returns rather than streaming
+ // forever.
+ go func() {
+ time.Sleep(100 * time.Millisecond)
+ _ = ring.Close()
+ }()
+ g.serveLive(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("got %d: %s", rec.Code, rec.Body.String())
+ }
+ if ct := rec.Header().Get("Content-Type"); ct != "video/mp2t" {
+ t.Errorf("content type = %q, want video/mp2t", ct)
+ }
+ if rec.Body.Len() == 0 {
+ t.Error("no media was written to the client")
+ }
+}
+
+func TestLiveTSRejectsOddPaths(t *testing.T) {
+ g, store, _, _ := newTestGate(t)
+ mkStream(t, store, db.CreateStream{Name: "news"})
+ for _, p := range []string{"/live/", "/live/news", "/live/news.m3u8", "/live/../x.ts", "/live/a/b.ts"} {
+ rec := httptest.NewRecorder()
+ g.serveLive(rec, httptest.NewRequest(http.MethodGet, p, nil))
+ if rec.Code == http.StatusOK {
+ t.Errorf("%s returned 200", p)
+ }
+ }
+}
diff --git a/apps/streamd/internal/httpx/httpx.go b/apps/streamd/internal/httpx/httpx.go
new file mode 100644
index 0000000..df9c958
--- /dev/null
+++ b/apps/streamd/internal/httpx/httpx.go
@@ -0,0 +1,257 @@
+// Package httpx holds the transport-level middleware streamd wraps around its
+// mux: real-client-IP resolution behind a trusted reverse proxy, security
+// headers, a strict CORS policy and an access log.
+package httpx
+
+import (
+ "log/slog"
+ "net"
+ "net/http"
+ "strings"
+ "time"
+)
+
+// ParseCIDRs turns a comma-separated list of CIDRs or bare IPs into networks.
+// Bare IPs become single-host networks, so --trusted-proxies 10.0.0.5 works.
+func ParseCIDRs(list string) ([]*net.IPNet, error) {
+ var out []*net.IPNet
+ for _, raw := range strings.Split(list, ",") {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ continue
+ }
+ if _, n, err := net.ParseCIDR(raw); err == nil {
+ out = append(out, n)
+ continue
+ }
+ ip := net.ParseIP(raw)
+ if ip == nil {
+ return nil, &net.ParseError{Type: "CIDR or IP address", Text: raw}
+ }
+ bits := 32
+ if ip.To4() == nil {
+ bits = 128
+ }
+ out = append(out, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
+ }
+ return out, nil
+}
+
+// Trust decides whether forwarded headers may be believed.
+type Trust struct {
+ Proxies []*net.IPNet
+}
+
+func (t Trust) trusted(ip net.IP) bool {
+ if ip == nil {
+ return false
+ }
+ for _, n := range t.Proxies {
+ if n.Contains(ip) {
+ return true
+ }
+ }
+ return false
+}
+
+// ClientIP returns the caller's address. X-Forwarded-For is honoured only when
+// the immediate peer is a configured trusted proxy; otherwise the peer address
+// wins, so a stranger cannot spoof their IP to dodge a rate limit.
+func (t Trust) ClientIP(r *http.Request) string {
+ peer := peerIP(r)
+ if !t.trusted(net.ParseIP(peer)) {
+ return peer
+ }
+ // Right-most entry is the one our trusted proxy appended; walk from the
+ // right to the first address that is not itself a trusted proxy.
+ xff := r.Header.Get("X-Forwarded-For")
+ parts := strings.Split(xff, ",")
+ for i := len(parts) - 1; i >= 0; i-- {
+ cand := strings.TrimSpace(parts[i])
+ if cand == "" {
+ continue
+ }
+ ip := net.ParseIP(cand)
+ if ip == nil {
+ continue
+ }
+ if !t.trusted(ip) {
+ return ip.String()
+ }
+ }
+ if real := strings.TrimSpace(r.Header.Get("X-Real-IP")); real != "" {
+ if ip := net.ParseIP(real); ip != nil {
+ return ip.String()
+ }
+ }
+ return peer
+}
+
+// IsHTTPS reports whether the original client request used TLS, trusting
+// X-Forwarded-Proto only from a trusted proxy.
+func (t Trust) IsHTTPS(r *http.Request) bool {
+ if r.TLS != nil {
+ return true
+ }
+ if !t.trusted(net.ParseIP(peerIP(r))) {
+ return false
+ }
+ proto := strings.ToLower(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")))
+ // A proxy chain may append, e.g. "https, http".
+ if i := strings.IndexByte(proto, ','); i >= 0 {
+ proto = strings.TrimSpace(proto[:i])
+ }
+ return proto == "https"
+}
+
+func peerIP(r *http.Request) string {
+ host, _, err := net.SplitHostPort(r.RemoteAddr)
+ if err != nil {
+ return strings.TrimSpace(r.RemoteAddr)
+ }
+ return host
+}
+
+// SecurityHeaders sets conservative defaults on every response. The CSP is
+// default-src 'self' throughout, which is why hls.js is vendored into the
+// embedded assets rather than loaded from a CDN.
+func SecurityHeaders(trust Trust, next http.Handler) http.Handler {
+ const csp = "default-src 'self'; " +
+ "script-src 'self'; " +
+ "style-src 'self' 'unsafe-inline'; " +
+ "img-src 'self' data:; " +
+ "media-src 'self' blob:; " +
+ "connect-src 'self' ws: wss:; " +
+ "font-src 'self'; " +
+ "object-src 'none'; " +
+ "base-uri 'none'; " +
+ "form-action 'self'; " +
+ "frame-ancestors 'none'"
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ // Media responses are served to players and must stay cacheable and
+ // embeddable; the policy above is for the dashboard documents.
+ if !isMediaPath(r.URL.Path) {
+ h.Set("Content-Security-Policy", csp)
+ h.Set("X-Frame-Options", "DENY")
+ h.Set("Referrer-Policy", "no-referrer")
+ h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
+ }
+ h.Set("X-Content-Type-Options", "nosniff")
+ if trust.IsHTTPS(r) {
+ h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func isMediaPath(p string) bool {
+ return strings.HasPrefix(p, "/hls/") || strings.HasPrefix(p, "/live/")
+}
+
+// CORS echoes an Origin only when it is explicitly allowed. With no allowed
+// origins configured the API is same-origin only, which is the default.
+func CORS(allowed []string, next http.Handler) http.Handler {
+ allow := map[string]bool{}
+ wildcardMedia := false
+ for _, o := range allowed {
+ o = strings.TrimRight(strings.TrimSpace(o), "/")
+ if o == "" {
+ continue
+ }
+ if o == "*" {
+ wildcardMedia = true
+ continue
+ }
+ allow[strings.ToLower(o)] = true
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ origin := strings.TrimRight(strings.TrimSpace(r.Header.Get("Origin")), "/")
+ if origin != "" {
+ switch {
+ case allow[strings.ToLower(origin)]:
+ w.Header().Set("Access-Control-Allow-Origin", origin)
+ w.Header().Set("Access-Control-Allow-Credentials", "true")
+ w.Header().Add("Vary", "Origin")
+ case wildcardMedia && isMediaPath(r.URL.Path):
+ // A wildcard is only ever honoured for media, never for the
+ // API, so credentials can never be read cross-origin.
+ w.Header().Set("Access-Control-Allow-Origin", "*")
+ }
+ w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Streamd-Token, X-CSRF-Token, X-Agent-ID")
+ w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS")
+ w.Header().Set("Access-Control-Max-Age", "600")
+ }
+ if r.Method == http.MethodOptions {
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+// StatusRecorder captures the response status and byte count for logging and
+// for the audit trail.
+type StatusRecorder struct {
+ http.ResponseWriter
+ Status int
+ Bytes int64
+}
+
+func (s *StatusRecorder) WriteHeader(code int) {
+ if s.Status == 0 {
+ s.Status = code
+ }
+ s.ResponseWriter.WriteHeader(code)
+}
+
+func (s *StatusRecorder) Write(b []byte) (int, error) {
+ if s.Status == 0 {
+ s.Status = http.StatusOK
+ }
+ n, err := s.ResponseWriter.Write(b)
+ s.Bytes += int64(n)
+ return n, err
+}
+
+// Flush forwards to the underlying writer so SSE and progressive TS keep
+// streaming through this wrapper.
+func (s *StatusRecorder) Flush() {
+ if f, ok := s.ResponseWriter.(http.Flusher); ok {
+ f.Flush()
+ }
+}
+
+// Unwrap lets http.ResponseController reach the real writer (needed for
+// per-write deadlines on long-lived streaming responses).
+func (s *StatusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
+
+// AccessLog logs one line per request at debug level, and at info level for
+// 5xx responses so failures are visible without enabling debug.
+func AccessLog(lg *slog.Logger, trust Trust, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Media and websocket traffic is far too chatty for a per-request log.
+ if isMediaPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/ws/") {
+ next.ServeHTTP(w, r)
+ return
+ }
+ start := time.Now()
+ rec := &StatusRecorder{ResponseWriter: w}
+ next.ServeHTTP(rec, r)
+ if rec.Status == 0 {
+ rec.Status = http.StatusOK
+ }
+ lvl := slog.LevelDebug
+ if rec.Status >= 500 {
+ lvl = slog.LevelInfo
+ }
+ lg.Log(r.Context(), lvl, "http",
+ "method", r.Method,
+ "path", r.URL.Path,
+ "status", rec.Status,
+ "bytes", rec.Bytes,
+ "dur_ms", time.Since(start).Milliseconds(),
+ "ip", trust.ClientIP(r),
+ )
+ })
+}
diff --git a/apps/streamd/internal/logfile/logfile.go b/apps/streamd/internal/logfile/logfile.go
new file mode 100644
index 0000000..b9bd4e4
--- /dev/null
+++ b/apps/streamd/internal/logfile/logfile.go
@@ -0,0 +1,239 @@
+// Package logfile provides a size-capped rotating writer for the per-stream
+// downloader and packager logs.
+//
+// It replaces two patterns that both lost information: the N_m3u8DL-RE log was
+// opened with O_TRUNC on every start, which erased the evidence from the crash
+// you were about to investigate, and the ffmpeg logs were opened O_APPEND with
+// no bound, which grew without limit on a long-running stream.
+package logfile
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// Defaults for a per-stream log.
+const (
+ DefaultMaxBytes = 8 << 20 // 8 MiB per generation
+ DefaultGenerations = 3 // name.log, name.log.1, name.log.2
+)
+
+// Writer is an io.WriteCloser that rotates when the file passes MaxBytes.
+// It is safe for concurrent use, and for being handed to an exec.Cmd as
+// Stdout and Stderr at the same time.
+type Writer struct {
+ path string
+ maxBytes int64
+ generations int
+
+ mu sync.Mutex
+ f *os.File
+ size int64
+}
+
+// Open opens path for appending, rotating it if it is already over the cap.
+// maxBytes and generations fall back to the defaults when not positive.
+func Open(path string, maxBytes int64, generations int) (*Writer, error) {
+ if maxBytes <= 0 {
+ maxBytes = DefaultMaxBytes
+ }
+ if generations <= 0 {
+ generations = DefaultGenerations
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return nil, err
+ }
+ w := &Writer{path: path, maxBytes: maxBytes, generations: generations}
+ if err := w.reopen(); err != nil {
+ return nil, err
+ }
+ return w, nil
+}
+
+// OpenWithBanner opens the log and writes a start marker, so one file can hold
+// several runs and still be readable. This is what replaces truncating.
+func OpenWithBanner(path string, maxBytes int64, generations int, what string) (*Writer, error) {
+ w, err := Open(path, maxBytes, generations)
+ if err != nil {
+ return nil, err
+ }
+ _, _ = fmt.Fprintf(w, "\n==== %s start %s ====\n", what, time.Now().UTC().Format(time.RFC3339))
+ return w, nil
+}
+
+// OpenCmdLog prepares a rotating append log and returns the live *os.File for
+// exec.Cmd Stdout/Stderr. Go only inherits a real FD for *os.File; any other
+// io.Writer becomes a pipe, and N_m3u8DL-RE's Spectre progress UI crashes on
+// pipe-backed consoles (ArgumentException in LiveRenderable.RemoveRange).
+//
+// The caller owns the file and must Close it. Mid-run size rotation is skipped
+// (rotation still happens at open when the prior file is already over the cap).
+func OpenCmdLog(path string, maxBytes int64, generations int, what string) (*os.File, error) {
+ w, err := OpenWithBanner(path, maxBytes, generations, what)
+ if err != nil {
+ return nil, err
+ }
+ return w.DetachFile()
+}
+
+// DetachFile transfers ownership of the underlying *os.File to the caller.
+// The Writer becomes inert; do not Write or Close it afterward.
+func (w *Writer) DetachFile() (*os.File, error) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.f == nil {
+ return nil, os.ErrClosed
+ }
+ f := w.f
+ w.f = nil
+ return f, nil
+}
+
+func (w *Writer) reopen() error {
+ f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+ if err != nil {
+ return err
+ }
+ w.f = f
+ if st, err := f.Stat(); err == nil {
+ w.size = st.Size()
+ } else {
+ w.size = 0
+ }
+ return nil
+}
+
+func (w *Writer) Write(p []byte) (int, error) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.f == nil {
+ return 0, os.ErrClosed
+ }
+ // Rotate before the write that would cross the cap, so a generation never
+ // greatly exceeds MaxBytes.
+ if w.size > 0 && w.size+int64(len(p)) > w.maxBytes {
+ if err := w.rotateLocked(); err != nil {
+ // Rotation failing (a Windows file lock, say) must not lose the
+ // log line: keep writing to the current file.
+ _, _ = fmt.Fprintf(w.f, "==== rotate failed: %v ====\n", err)
+ }
+ }
+ n, err := w.f.Write(p)
+ w.size += int64(n)
+ return n, err
+}
+
+// rotateLocked shifts name.log.N-1 -> name.log.N and starts a fresh file.
+func (w *Writer) rotateLocked() error {
+ if err := w.f.Close(); err != nil {
+ // Still try to rotate; reopen below will surface a real problem.
+ _ = err
+ }
+ // Drop the oldest, then walk down so each generation moves up one.
+ oldest := fmt.Sprintf("%s.%d", w.path, w.generations-1)
+ _ = os.Remove(oldest)
+ for i := w.generations - 2; i >= 1; i-- {
+ from := fmt.Sprintf("%s.%d", w.path, i)
+ to := fmt.Sprintf("%s.%d", w.path, i+1)
+ if _, err := os.Stat(from); err == nil {
+ _ = os.Rename(from, to)
+ }
+ }
+ if w.generations > 1 {
+ if err := os.Rename(w.path, w.path+".1"); err != nil && !os.IsNotExist(err) {
+ // Could not move the live file; reopen it and carry on appending.
+ if rerr := w.reopen(); rerr != nil {
+ return rerr
+ }
+ return err
+ }
+ } else {
+ _ = os.Remove(w.path)
+ }
+ return w.reopen()
+}
+
+func (w *Writer) Close() error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.f == nil {
+ return nil
+ }
+ err := w.f.Close()
+ w.f = nil
+ return err
+}
+
+// Path is the live file's path.
+func (w *Writer) Path() string { return w.path }
+
+// Tail returns the last n lines of path. Reads from the end rather than
+// loading the file, so an 8 MiB log is cheap to tail.
+func Tail(path string, lines int) ([]byte, error) {
+ if lines <= 0 {
+ lines = 200
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ st, err := f.Stat()
+ if err != nil {
+ return nil, err
+ }
+ size := st.Size()
+ if size == 0 {
+ return nil, nil
+ }
+
+ const chunk = 64 << 10
+ var (
+ buf []byte
+ newlines int
+ pos = size
+ )
+ for pos > 0 && newlines <= lines {
+ readSize := int64(chunk)
+ if pos < readSize {
+ readSize = pos
+ }
+ pos -= readSize
+ part := make([]byte, readSize)
+ if _, err := f.ReadAt(part, pos); err != nil {
+ return nil, err
+ }
+ for _, b := range part {
+ if b == '\n' {
+ newlines++
+ }
+ }
+ buf = append(part, buf...)
+ // Guard against a single enormous line eating memory.
+ if int64(len(buf)) > 8<<20 {
+ break
+ }
+ }
+
+ // Trim to the requested number of trailing lines.
+ count := 0
+ for i := len(buf) - 1; i >= 0; i-- {
+ if buf[i] != '\n' {
+ continue
+ }
+ // Ignore a trailing newline at the very end of the file.
+ if i == len(buf)-1 {
+ continue
+ }
+ // The content after the Nth newline from the end is exactly N lines,
+ // so stop on the Nth, not past it.
+ count++
+ if count == lines {
+ return buf[i+1:], nil
+ }
+ }
+ return buf, nil
+}
diff --git a/apps/streamd/internal/logfile/logfile_test.go b/apps/streamd/internal/logfile/logfile_test.go
new file mode 100644
index 0000000..2bd5c78
--- /dev/null
+++ b/apps/streamd/internal/logfile/logfile_test.go
@@ -0,0 +1,192 @@
+package logfile
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestRotatesAtSizeCap(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "stream-nre.log")
+ w, err := Open(path, 1024, 3)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer w.Close()
+
+ line := strings.Repeat("x", 100) + "\n"
+ for i := 0; i < 50; i++ {
+ if _, err := w.Write([]byte(line)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The live file must stay near the cap, not grow to 5 KiB.
+ st, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st.Size() > 1024+int64(len(line)) {
+ t.Errorf("live log is %d bytes, cap is 1024", st.Size())
+ }
+ // Generations exist, and no more than were asked for.
+ if _, err := os.Stat(path + ".1"); err != nil {
+ t.Errorf("expected a rotated generation: %v", err)
+ }
+ if _, err := os.Stat(path + ".3"); err == nil {
+ t.Error("generation 3 should not exist with generations=3 (0,1,2)")
+ }
+}
+
+func TestGenerationCountRespected(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "x.log")
+ w, err := Open(path, 200, 2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer w.Close()
+ for i := 0; i < 40; i++ {
+ _, _ = w.Write([]byte(strings.Repeat("y", 50) + "\n"))
+ }
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // generations=2 means x.log and x.log.1 only.
+ if len(ents) > 2 {
+ var names []string
+ for _, e := range ents {
+ names = append(names, e.Name())
+ }
+ t.Errorf("want at most 2 files, got %v", names)
+ }
+}
+
+// Reopening must append, not truncate: a restart has to leave the previous
+// run's output in place, which is the whole point of this package.
+func TestReopenAppendsAndBannerMarksRuns(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "run.log")
+
+ w1, err := OpenWithBanner(path, 1<<20, 3, "nre")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = w1.Write([]byte("first run output\n"))
+ _ = w1.Close()
+
+ w2, err := OpenWithBanner(path, 1<<20, 3, "nre")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = w2.Write([]byte("second run output\n"))
+ _ = w2.Close()
+
+ b, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := string(b)
+ if !strings.Contains(body, "first run output") {
+ t.Error("the previous run's output was lost — this is the O_TRUNC bug")
+ }
+ if !strings.Contains(body, "second run output") {
+ t.Error("the new run's output is missing")
+ }
+ if n := strings.Count(body, "==== nre start "); n != 2 {
+ t.Errorf("want 2 start banners, got %d", n)
+ }
+}
+
+func TestTail(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "t.log")
+ var buf bytes.Buffer
+ for i := 0; i < 500; i++ {
+ fmt.Fprintf(&buf, "line %d\n", i)
+ }
+ if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ out, err := Tail(path, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lines := strings.Split(strings.TrimRight(string(out), "\n"), "\n")
+ if len(lines) != 10 {
+ t.Fatalf("want 10 lines, got %d: %q", len(lines), string(out))
+ }
+ if lines[9] != "line 499" {
+ t.Errorf("last line = %q, want %q", lines[9], "line 499")
+ }
+ if lines[0] != "line 490" {
+ t.Errorf("first line = %q, want %q", lines[0], "line 490")
+ }
+
+ // Asking for more lines than exist returns the whole file.
+ out, err = Tail(path, 10000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(out, buf.Bytes()) {
+ t.Error("tail of a short file should return all of it")
+ }
+}
+
+func TestTailEmptyAndMissing(t *testing.T) {
+ dir := t.TempDir()
+ empty := filepath.Join(dir, "empty.log")
+ if err := os.WriteFile(empty, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if out, err := Tail(empty, 10); err != nil || len(out) != 0 {
+ t.Errorf("empty file: got %q %v", out, err)
+ }
+ if _, err := Tail(filepath.Join(dir, "nope.log"), 10); err == nil {
+ t.Error("a missing file should error")
+ }
+}
+
+func TestWriteAfterCloseDoesNotPanic(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "c.log")
+ w, err := Open(path, 1<<20, 2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = w.Close()
+ if _, err := w.Write([]byte("x")); err == nil {
+ t.Error("writing to a closed writer should error, not panic")
+ }
+ // Double close is harmless.
+ if err := w.Close(); err != nil {
+ t.Errorf("second Close should be a no-op, got %v", err)
+ }
+}
+
+func TestConcurrentWrites(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "p.log")
+ // An exec.Cmd gets this same writer as both Stdout and Stderr, so
+ // concurrent writes are the normal case, not an edge case.
+ w, err := Open(path, 4096, 3)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer w.Close()
+ done := make(chan struct{})
+ for g := 0; g < 4; g++ {
+ go func(g int) {
+ defer func() { done <- struct{}{} }()
+ for i := 0; i < 100; i++ {
+ _, _ = w.Write([]byte(fmt.Sprintf("writer %d line %d\n", g, i)))
+ }
+ }(g)
+ }
+ for i := 0; i < 4; i++ {
+ <-done
+ }
+}
diff --git a/apps/streamd/internal/modstore/modstore.go b/apps/streamd/internal/modstore/modstore.go
new file mode 100644
index 0000000..b6acdff
--- /dev/null
+++ b/apps/streamd/internal/modstore/modstore.go
@@ -0,0 +1,650 @@
+// Package modstore keeps provider modules under the streamd data directory.
+// Operators upload release-style zips; agents pull package.zip + module.yaml.
+package modstore
+
+import (
+ "archive/zip"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "sort"
+ "strings"
+ "time"
+)
+
+const (
+ MaxPackageBytes = 100 << 20 // 100 MiB
+ manifestName = "manifest.json"
+ packageName = "package.zip"
+ yamlName = "module.yaml"
+)
+
+var NameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
+
+// archDirRe matches .bin/-/ folder names (never a module name).
+var archDirRe = regexp.MustCompile(`^[a-z0-9]+-(amd64|arm64|386|arm)$`)
+
+// Info is one module's metadata for the API and agent sync.
+type Info struct {
+ Name string `json:"name"`
+ HasYAML bool `json:"has_yaml"`
+ YAMLSHA256 string `json:"yaml_sha256,omitempty"`
+ HasPackage bool `json:"has_package"`
+ PackageSHA256 string `json:"package_sha256,omitempty"`
+ Arches []string `json:"arches,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
+ UploadedAt string `json:"uploaded_at,omitempty"`
+ YAMLUpdatedAt string `json:"yaml_updated_at,omitempty"`
+}
+
+type Manifest struct {
+ Name string `json:"name"`
+ YAMLSHA256 string `json:"yaml_sha256,omitempty"`
+ PackageSHA256 string `json:"package_sha256,omitempty"`
+ Arches []string `json:"arches,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
+ UploadedAt string `json:"uploaded_at,omitempty"`
+ YAMLUpdatedAt string `json:"yaml_updated_at,omitempty"`
+}
+
+// Store is the on-disk module library under /modules.
+type Store struct {
+ Root string
+}
+
+func New(root string) *Store {
+ return &Store{Root: root}
+}
+
+func (s *Store) modulesDir() string {
+ return s.Root
+}
+
+func (s *Store) modDir(name string) string {
+ return filepath.Join(s.Root, name)
+}
+
+func (s *Store) Ensure() error {
+ return os.MkdirAll(s.Root, 0o755)
+}
+
+// List returns every module directory under the store.
+func (s *Store) List() ([]Info, error) {
+ ents, err := os.ReadDir(s.Root)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return []Info{}, nil
+ }
+ return nil, err
+ }
+ out := make([]Info, 0, len(ents))
+ for _, e := range ents {
+ if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
+ continue
+ }
+ if !NameRe.MatchString(e.Name()) {
+ continue
+ }
+ out = append(out, s.Info(e.Name()))
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
+ return out, nil
+}
+
+// Info loads manifest + checks for yaml/package files.
+func (s *Store) Info(name string) Info {
+ info := Info{Name: name}
+ if !NameRe.MatchString(name) {
+ return info
+ }
+ dir := s.modDir(name)
+ m, err := s.readManifest(dir)
+ if err == nil {
+ info.YAMLSHA256 = m.YAMLSHA256
+ info.PackageSHA256 = m.PackageSHA256
+ info.Arches = append([]string(nil), m.Arches...)
+ info.SizeBytes = m.SizeBytes
+ info.UploadedAt = m.UploadedAt
+ info.YAMLUpdatedAt = m.YAMLUpdatedAt
+ info.HasYAML = m.YAMLSHA256 != ""
+ info.HasPackage = m.PackageSHA256 != ""
+ }
+ // Prefer live file hashes when present so a hand-edited yaml still shows.
+ if b, err := os.ReadFile(filepath.Join(dir, yamlName)); err == nil {
+ info.HasYAML = true
+ sum := sha256.Sum256(b)
+ info.YAMLSHA256 = hex.EncodeToString(sum[:])
+ }
+ if st, err := os.Stat(filepath.Join(dir, packageName)); err == nil && !st.IsDir() {
+ info.HasPackage = true
+ if info.PackageSHA256 == "" {
+ if sum, err := fileSHA256(filepath.Join(dir, packageName)); err == nil {
+ info.PackageSHA256 = sum
+ }
+ }
+ if info.SizeBytes == 0 {
+ info.SizeBytes = st.Size()
+ }
+ }
+ return info
+}
+
+// ReadYAML returns module.yaml bytes.
+func (s *Store) ReadYAML(name string) ([]byte, error) {
+ if !NameRe.MatchString(name) {
+ return nil, fmt.Errorf("invalid module name")
+ }
+ b, err := os.ReadFile(filepath.Join(s.modDir(name), yamlName))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, fmt.Errorf("module %s: no module.yaml", name)
+ }
+ return nil, err
+ }
+ return b, nil
+}
+
+// WriteYAML atomically replaces module.yaml and updates the manifest.
+func (s *Store) WriteYAML(name string, yamlBytes []byte) (Info, error) {
+ if !NameRe.MatchString(name) {
+ return Info{}, fmt.Errorf("invalid module name")
+ }
+ if len(strings.TrimSpace(string(yamlBytes))) == 0 {
+ return Info{}, fmt.Errorf("empty module.yaml")
+ }
+ dir := s.modDir(name)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return Info{}, err
+ }
+ dest := filepath.Join(dir, yamlName)
+ if err := atomicWrite(dest, yamlBytes, 0o644); err != nil {
+ return Info{}, err
+ }
+ sum := sha256.Sum256(yamlBytes)
+ now := time.Now().UTC().Format(time.RFC3339)
+ m, _ := s.readManifest(dir)
+ m.Name = name
+ m.YAMLSHA256 = hex.EncodeToString(sum[:])
+ m.YAMLUpdatedAt = now
+ if m.UploadedAt == "" {
+ m.UploadedAt = now
+ }
+ if err := s.writeManifest(dir, m); err != nil {
+ return Info{}, err
+ }
+ return s.Info(name), nil
+}
+
+// OpenPackage returns a ReadCloser for package.zip plus size.
+func (s *Store) OpenPackage(name string) (*os.File, int64, error) {
+ if !NameRe.MatchString(name) {
+ return nil, 0, fmt.Errorf("invalid module name")
+ }
+ path := filepath.Join(s.modDir(name), packageName)
+ f, err := os.Open(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, 0, fmt.Errorf("module %s: no package.zip", name)
+ }
+ return nil, 0, err
+ }
+ st, err := f.Stat()
+ if err != nil {
+ _ = f.Close()
+ return nil, 0, err
+ }
+ return f, st.Size(), nil
+}
+
+// Delete removes the module directory.
+func (s *Store) Delete(name string) error {
+ if !NameRe.MatchString(name) {
+ return fmt.Errorf("invalid module name")
+ }
+ dir := s.modDir(name)
+ if _, err := os.Stat(dir); err != nil {
+ if os.IsNotExist(err) {
+ return fmt.Errorf("module %s not found", name)
+ }
+ return err
+ }
+ return os.RemoveAll(dir)
+}
+
+// InstallZip stores zipBytes as package.zip, extracts into the module dir,
+// promotes the host-arch binary, and writes the manifest.
+// nameHint may be empty; the zip layout is used to infer the name.
+func (s *Store) InstallZip(zipBytes []byte, nameHint string) (Info, error) {
+ if len(zipBytes) == 0 {
+ return Info{}, fmt.Errorf("empty zip")
+ }
+ if int64(len(zipBytes)) > MaxPackageBytes {
+ return Info{}, fmt.Errorf("zip exceeds %d byte limit", MaxPackageBytes)
+ }
+
+ name, entries, err := inspectZip(zipBytes, nameHint)
+ if err != nil {
+ return Info{}, err
+ }
+ if !NameRe.MatchString(name) {
+ return Info{}, fmt.Errorf("invalid module name %q", name)
+ }
+
+ if err := s.Ensure(); err != nil {
+ return Info{}, err
+ }
+ dir := s.modDir(name)
+ tmpDir, err := os.MkdirTemp(s.Root, "."+name+".tmp-*")
+ if err != nil {
+ return Info{}, err
+ }
+ defer os.RemoveAll(tmpDir)
+
+ if err := extractZipEntries(zipBytes, entries, tmpDir); err != nil {
+ return Info{}, err
+ }
+ if err := promoteHostBinary(tmpDir, name); err != nil {
+ return Info{}, err
+ }
+ yamlPath := filepath.Join(tmpDir, yamlName)
+ if _, err := os.Stat(yamlPath); err != nil {
+ return Info{}, fmt.Errorf("zip missing module.yaml")
+ }
+ arches := detectArches(tmpDir, name)
+ pkgSum := sha256.Sum256(zipBytes)
+ yamlRaw, err := os.ReadFile(yamlPath)
+ if err != nil {
+ return Info{}, err
+ }
+ yamlSum := sha256.Sum256(yamlRaw)
+ now := time.Now().UTC().Format(time.RFC3339)
+ m := Manifest{
+ Name: name,
+ YAMLSHA256: hex.EncodeToString(yamlSum[:]),
+ PackageSHA256: hex.EncodeToString(pkgSum[:]),
+ Arches: arches,
+ SizeBytes: int64(len(zipBytes)),
+ UploadedAt: now,
+ YAMLUpdatedAt: now,
+ }
+ if err := s.writeManifest(tmpDir, m); err != nil {
+ return Info{}, err
+ }
+ if err := atomicWrite(filepath.Join(tmpDir, packageName), zipBytes, 0o644); err != nil {
+ return Info{}, err
+ }
+
+ // Replace the live module dir.
+ backup := dir + ".bak"
+ _ = os.RemoveAll(backup)
+ if _, err := os.Stat(dir); err == nil {
+ if err := os.Rename(dir, backup); err != nil {
+ return Info{}, err
+ }
+ }
+ if err := os.Rename(tmpDir, dir); err != nil {
+ _ = os.Rename(backup, dir)
+ return Info{}, err
+ }
+ _ = os.RemoveAll(backup)
+ return s.Info(name), nil
+}
+
+type zipEntry struct {
+ // Rel is the path relative to the module root inside the zip (forward slashes).
+ Rel string
+ File *zip.File
+}
+
+func inspectZip(zipBytes []byte, nameHint string) (name string, entries []zipEntry, err error) {
+ zr, err := zip.NewReader(newBytesReaderAt(zipBytes), int64(len(zipBytes)))
+ if err != nil {
+ return "", nil, fmt.Errorf("open zip: %w", err)
+ }
+ return inspectZipReader(zr, nameHint)
+}
+
+type bytesReaderAt struct{ b []byte }
+
+func newBytesReaderAt(b []byte) *bytesReaderAt { return &bytesReaderAt{b: b} }
+
+func (r *bytesReaderAt) ReadAt(p []byte, off int64) (int, error) {
+ if off < 0 {
+ return 0, errors.New("negative offset")
+ }
+ if off >= int64(len(r.b)) {
+ return 0, io.EOF
+ }
+ n := copy(p, r.b[off:])
+ if n < len(p) {
+ return n, io.EOF
+ }
+ return n, nil
+}
+
+func inspectZipReader(zr *zip.Reader, nameHint string) (string, []zipEntry, error) {
+ hint := strings.TrimSpace(nameHint)
+ if hint != "" && !NameRe.MatchString(hint) {
+ return "", nil, fmt.Errorf("invalid module name %q", hint)
+ }
+
+ prefix := ""
+ topDirs := map[string]struct{}{}
+ hasRootFile := false
+
+ for _, f := range zr.File {
+ name := strings.ReplaceAll(f.Name, "\\", "/")
+ name = strings.TrimPrefix(name, "./")
+ if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
+ continue
+ }
+ parts := strings.Split(name, "/")
+ if len(parts) > 0 && parts[0] != "" {
+ if f.FileInfo().IsDir() || len(parts) > 1 {
+ topDirs[parts[0]] = struct{}{}
+ }
+ if len(parts) == 1 && !f.FileInfo().IsDir() {
+ hasRootFile = true
+ }
+ }
+ }
+
+ switch {
+ case hint != "":
+ prefix = ""
+ // If every entry is under hint/, strip it.
+ allUnder := true
+ for _, f := range zr.File {
+ n := strings.ReplaceAll(f.Name, "\\", "/")
+ n = strings.TrimPrefix(n, "./")
+ if n == "" || strings.HasPrefix(n, "__MACOSX/") {
+ continue
+ }
+ if n != hint && !strings.HasPrefix(n, hint+"/") {
+ allUnder = false
+ break
+ }
+ }
+ if allUnder {
+ prefix = hint + "/"
+ }
+ case hasRootFile:
+ // Flat zip: module.yaml at root. Name must be provided or inferred from binary.
+ prefix = ""
+ case len(topDirs) == 1:
+ for d := range topDirs {
+ prefix = d + "/"
+ if hint == "" {
+ hint = d
+ }
+ }
+ default:
+ return "", nil, fmt.Errorf("cannot infer module name from zip; pass name= or use a single top-level folder")
+ }
+
+ if hint == "" {
+ hint = inferNameFromBinEntries(zr, prefix)
+ }
+ if hint == "" {
+ return "", nil, fmt.Errorf("cannot infer module name from zip; pass name=")
+ }
+ if !NameRe.MatchString(hint) {
+ return "", nil, fmt.Errorf("invalid module name %q", hint)
+ }
+
+ var entries []zipEntry
+ for _, f := range zr.File {
+ n := strings.ReplaceAll(f.Name, "\\", "/")
+ n = strings.TrimPrefix(n, "./")
+ if n == "" || strings.HasPrefix(n, "__MACOSX/") || strings.HasSuffix(n, ".DS_Store") {
+ continue
+ }
+ rel := n
+ if prefix != "" {
+ if !strings.HasPrefix(n, prefix) {
+ continue
+ }
+ rel = strings.TrimPrefix(n, prefix)
+ }
+ if rel == "" {
+ continue
+ }
+ if strings.Contains(rel, "..") {
+ return "", nil, fmt.Errorf("zip slip: %s", f.Name)
+ }
+ entries = append(entries, zipEntry{Rel: rel, File: f})
+ }
+ if len(entries) == 0 {
+ return "", nil, fmt.Errorf("zip has no files for module %s", hint)
+ }
+ return hint, entries, nil
+}
+
+func extractZipEntries(zipBytes []byte, entries []zipEntry, destDir string) error {
+ _ = zipBytes // entries already hold openable *zip.File from the same buffer
+ for _, e := range entries {
+ target := filepath.Join(destDir, filepath.FromSlash(e.Rel))
+ // Zip-slip: ensure target stays under destDir.
+ if !isUnder(destDir, target) {
+ return fmt.Errorf("zip slip: %s", e.Rel)
+ }
+ if e.File.FileInfo().IsDir() || strings.HasSuffix(e.Rel, "/") {
+ if err := os.MkdirAll(target, 0o755); err != nil {
+ return err
+ }
+ continue
+ }
+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+ return err
+ }
+ rc, err := e.File.Open()
+ if err != nil {
+ return err
+ }
+ mode := e.File.Mode()
+ if mode&0o111 != 0 {
+ mode = 0o755
+ } else {
+ mode = 0o644
+ }
+ err = copyToFile(target, rc, mode)
+ _ = rc.Close()
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// inferNameFromBinEntries picks the module binary basename from
+// .bin//[.exe] or .bin/[.exe]. Directory entries and
+// arch folder names (linux-amd64, darwin-arm64, …) are skipped — those used
+// to be mistaken for the module name on flat release zips.
+func inferNameFromBinEntries(zr *zip.Reader, prefix string) string {
+ var fallback string
+ for _, f := range zr.File {
+ if f.FileInfo().IsDir() {
+ continue
+ }
+ n := strings.ReplaceAll(f.Name, "\\", "/")
+ n = strings.TrimPrefix(n, "./")
+ if prefix != "" {
+ if !strings.HasPrefix(n, prefix) {
+ continue
+ }
+ n = strings.TrimPrefix(n, prefix)
+ }
+ n = strings.TrimSuffix(n, "/")
+ if !strings.HasPrefix(n, ".bin/") {
+ continue
+ }
+ rel := strings.TrimPrefix(n, ".bin/")
+ parts := strings.Split(rel, "/")
+ base := parts[len(parts)-1]
+ base = strings.TrimSuffix(base, ".exe")
+ if !NameRe.MatchString(base) || archDirRe.MatchString(base) {
+ continue
+ }
+ // Prefer .bin//
+ if len(parts) >= 2 && archDirRe.MatchString(parts[0]) {
+ return base
+ }
+ // .bin/
+ if len(parts) == 1 && fallback == "" {
+ fallback = base
+ }
+ }
+ return fallback
+}
+
+func isUnder(root, path string) bool {
+ absRoot, err1 := filepath.Abs(root)
+ absPath, err2 := filepath.Abs(path)
+ if err1 != nil || err2 != nil {
+ return false
+ }
+ rel, err := filepath.Rel(absRoot, absPath)
+ if err != nil {
+ return false
+ }
+ return rel == "." || (!strings.HasPrefix(rel, "..") && !filepath.IsAbs(rel))
+}
+
+func copyToFile(dest string, r io.Reader, mode os.FileMode) error {
+ tmp := dest + ".partial"
+ f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
+ if err != nil {
+ return err
+ }
+ _, copyErr := io.Copy(f, r)
+ closeErr := f.Close()
+ if copyErr != nil {
+ _ = os.Remove(tmp)
+ return copyErr
+ }
+ if closeErr != nil {
+ _ = os.Remove(tmp)
+ return closeErr
+ }
+ _ = os.Remove(dest)
+ return os.Rename(tmp, dest)
+}
+
+func promoteHostBinary(modDir, name string) error {
+ want := name
+ if runtime.GOOS == "windows" {
+ want += ".exe"
+ }
+ dest := filepath.Join(modDir, ".bin", want)
+ if fileExists(dest) {
+ return nil
+ }
+ archDir := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH)
+ src := filepath.Join(archDir, want)
+ if !fileExists(src) {
+ // Soft: describe may fail later; zip install still succeeds.
+ return nil
+ }
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ return err
+ }
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ return copyToFile(dest, in, 0o755)
+}
+
+func detectArches(modDir, name string) []string {
+ binRoot := filepath.Join(modDir, ".bin")
+ ents, err := os.ReadDir(binRoot)
+ if err != nil {
+ return nil
+ }
+ seen := map[string]struct{}{}
+ var arches []string
+ add := func(a string) {
+ if _, ok := seen[a]; ok {
+ return
+ }
+ seen[a] = struct{}{}
+ arches = append(arches, a)
+ }
+ for _, e := range ents {
+ if e.IsDir() {
+ sub := e.Name() // e.g. windows-amd64
+ if strings.Contains(sub, "-") {
+ add(sub)
+ }
+ continue
+ }
+ base := strings.TrimSuffix(e.Name(), ".exe")
+ if base == name {
+ add(runtime.GOOS + "-" + runtime.GOARCH)
+ }
+ }
+ sort.Strings(arches)
+ return arches
+}
+
+func (s *Store) readManifest(dir string) (Manifest, error) {
+ var m Manifest
+ b, err := os.ReadFile(filepath.Join(dir, manifestName))
+ if err != nil {
+ return m, err
+ }
+ if err := json.Unmarshal(b, &m); err != nil {
+ return m, err
+ }
+ return m, nil
+}
+
+func (s *Store) writeManifest(dir string, m Manifest) error {
+ b, err := json.MarshalIndent(m, "", " ")
+ if err != nil {
+ return err
+ }
+ b = append(b, '\n')
+ return atomicWrite(filepath.Join(dir, manifestName), b, 0o644)
+}
+
+func atomicWrite(path string, data []byte, mode os.FileMode) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, data, mode); err != nil {
+ return err
+ }
+ if err := os.Rename(tmp, path); err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ return nil
+}
+
+func fileSHA256(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+func fileExists(p string) bool {
+ st, err := os.Stat(p)
+ return err == nil && !st.IsDir()
+}
diff --git a/apps/streamd/internal/modstore/modstore_test.go b/apps/streamd/internal/modstore/modstore_test.go
new file mode 100644
index 0000000..bcd841c
--- /dev/null
+++ b/apps/streamd/internal/modstore/modstore_test.go
@@ -0,0 +1,170 @@
+package modstore
+
+import (
+ "archive/zip"
+ "bytes"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+func makeZip(t *testing.T, files map[string][]byte) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ for name, body := range files {
+ w, err := zw.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Write(body); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func TestInstallZipInfersNameNotArchDir(t *testing.T) {
+ // Flat release zips list .bin/darwin-arm64/ before the binary; that arch
+ // folder must not become the module name.
+ root := t.TempDir()
+ s := New(root)
+ zipBytes := makeZip(t, map[string][]byte{
+ "module.yaml": []byte("package: air.RTE\nchannels:\n rteone: {label: One}\n"),
+ ".bin/": nil, // directory markers via path only
+ ".bin/darwin-arm64/rte": []byte("mac-bin"),
+ ".bin/linux-amd64/rte": []byte("linux-bin"),
+ ".bin/windows-amd64/rte.exe": []byte("win-bin"),
+ })
+ info, err := s.InstallZip(zipBytes, "")
+ if err != nil {
+ t.Fatalf("InstallZip: %v", err)
+ }
+ if info.Name != "rte" {
+ t.Fatalf("inferred name=%q want rte", info.Name)
+ }
+}
+
+func TestInstallZipFlatAndYAMLOnly(t *testing.T) {
+ root := t.TempDir()
+ s := New(root)
+
+ arch := runtime.GOOS + "-" + runtime.GOARCH
+ binName := "demo"
+ if runtime.GOOS == "windows" {
+ binName += ".exe"
+ }
+ zipBytes := makeZip(t, map[string][]byte{
+ "module.yaml": []byte("package: com.example\nchannels: {}\n"),
+ ".bin/" + arch + "/" + binName: []byte("fake-binary"),
+ ".bin/linux-amd64/demo": []byte("linux-bin"),
+ })
+
+ info, err := s.InstallZip(zipBytes, "demo")
+ if err != nil {
+ t.Fatalf("InstallZip: %v", err)
+ }
+ if info.Name != "demo" || !info.HasYAML || !info.HasPackage {
+ t.Fatalf("info = %+v", info)
+ }
+ if info.PackageSHA256 == "" || info.YAMLSHA256 == "" {
+ t.Fatalf("missing hashes: %+v", info)
+ }
+ pkgHash := info.PackageSHA256
+ yamlHash := info.YAMLSHA256
+
+ // Host binary should be promoted.
+ promoted := filepath.Join(root, "demo", ".bin", binName)
+ if !fileExists(promoted) {
+ t.Fatalf("expected promoted binary at %s", promoted)
+ }
+
+ // YAML-only update must not change package hash.
+ info2, err := s.WriteYAML("demo", []byte("package: com.example\nchannels:\n one: {label: One}\n"))
+ if err != nil {
+ t.Fatalf("WriteYAML: %v", err)
+ }
+ if info2.PackageSHA256 != pkgHash {
+ t.Fatalf("package hash changed on yaml edit: %s -> %s", pkgHash, info2.PackageSHA256)
+ }
+ if info2.YAMLSHA256 == yamlHash {
+ t.Fatal("yaml hash should change after edit")
+ }
+
+ raw, err := s.ReadYAML("demo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), "one:") {
+ t.Fatalf("yaml not updated: %s", raw)
+ }
+
+ f, size, err := s.OpenPackage("demo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ if size != int64(len(zipBytes)) {
+ t.Fatalf("package size %d want %d", size, len(zipBytes))
+ }
+}
+
+func TestInstallZipTopLevelFolder(t *testing.T) {
+ root := t.TempDir()
+ s := New(root)
+ zipBytes := makeZip(t, map[string][]byte{
+ "bbc/module.yaml": []byte("package: bbc.iplayer.android\n"),
+ "bbc/.bin/linux-amd64/bbc": []byte("bin"),
+ "bbc/.bin/windows-amd64/bbc.exe": []byte("winbin"),
+ })
+ info, err := s.InstallZip(zipBytes, "")
+ if err != nil {
+ t.Fatalf("InstallZip: %v", err)
+ }
+ if info.Name != "bbc" {
+ t.Fatalf("name=%q", info.Name)
+ }
+ list, err := s.List()
+ if err != nil || len(list) != 1 || list[0].Name != "bbc" {
+ t.Fatalf("list=%v err=%v", list, err)
+ }
+}
+
+func TestZipSlipRejected(t *testing.T) {
+ root := t.TempDir()
+ s := New(root)
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ w, err := zw.Create("../evil.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = w.Write([]byte("x"))
+ _ = zw.Close()
+ _, err = s.InstallZip(buf.Bytes(), "demo")
+ if err == nil {
+ t.Fatal("expected zip-slip error")
+ }
+}
+
+func TestDelete(t *testing.T) {
+ root := t.TempDir()
+ s := New(root)
+ zipBytes := makeZip(t, map[string][]byte{
+ "module.yaml": []byte("package: x\n"),
+ })
+ if _, err := s.InstallZip(zipBytes, "xmod"); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.Delete("xmod"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(root, "xmod")); !os.IsNotExist(err) {
+ t.Fatalf("dir still present: %v", err)
+ }
+}
diff --git a/apps/streamd/internal/scheduler/scheduler.go b/apps/streamd/internal/scheduler/scheduler.go
new file mode 100644
index 0000000..fa0b2e2
--- /dev/null
+++ b/apps/streamd/internal/scheduler/scheduler.go
@@ -0,0 +1,178 @@
+// Package scheduler starts and stops streams at planned times, so a council
+// meeting or a match can be set up in advance instead of started by hand.
+package scheduler
+
+import (
+ "log/slog"
+ "time"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+// Supervisor is the subset of the media supervisor the scheduler needs.
+type Supervisor interface {
+ Start(id int64) error
+ Stop(id int64) error
+ Running(id int64) bool
+}
+
+// CaptureRequester asks connected agents for fresh credentials now.
+type CaptureRequester interface {
+ RequestCapture(st db.Stream, reason string) int
+}
+
+const (
+ tick = 15 * time.Second
+ // DefaultPreroll is how far ahead of a scheduled start credentials are
+ // refreshed. A 19:00 meeting is no use if the keys expired at noon, and a
+ // phone capture takes minutes.
+ DefaultPreroll = 5 * time.Minute
+)
+
+type Scheduler struct {
+ Store *db.Store
+ Sup Supervisor
+ Capture CaptureRequester
+ Log *slog.Logger
+ Preroll time.Duration
+}
+
+func New(store *db.Store, sup Supervisor, capture CaptureRequester, lg *slog.Logger, preroll time.Duration) *Scheduler {
+ if lg == nil {
+ lg = slog.Default()
+ }
+ if preroll <= 0 {
+ preroll = DefaultPreroll
+ }
+ return &Scheduler{Store: store, Sup: sup, Capture: capture, Log: lg, Preroll: preroll}
+}
+
+// Run drives the scheduler until stop is closed.
+func (s *Scheduler) Run(stop <-chan struct{}) {
+ // A server that was down over an occurrence must not fire it late; recompute
+ // every next_fire_at against the current time first.
+ if err := s.Store.RecomputeNextFire(); err != nil {
+ s.Log.Error("recompute schedule times", "err", err)
+ }
+ t := time.NewTicker(tick)
+ defer t.Stop()
+ for {
+ select {
+ case <-stop:
+ return
+ case <-t.C:
+ s.step(time.Now().UTC())
+ }
+ }
+}
+
+// step fires everything due and requests pre-roll captures.
+func (s *Scheduler) step(now time.Time) {
+ s.preroll(now)
+
+ due, err := s.Store.DueSchedules(now)
+ if err != nil {
+ s.Log.Error("list due schedules", "err", err)
+ return
+ }
+ for _, sc := range due {
+ st, err := s.Store.GetStream(sc.StreamID)
+ if err != nil {
+ // The stream is gone; the schedule row went with it via the
+ // foreign key, so nothing to do.
+ continue
+ }
+ s.fire(sc, st, now)
+ if err := s.Store.MarkFired(sc, now); err != nil {
+ s.Log.Error("advance schedule", "schedule", sc.ID, "err", err)
+ }
+ }
+}
+
+func (s *Scheduler) fire(sc db.Schedule, st db.Stream, now time.Time) {
+ switch sc.Action {
+ case db.ActionStart:
+ if s.Sup.Running(st.ID) {
+ s.Log.Info("scheduled start skipped: already running", "stream", st.Name)
+ s.Store.AddEvent(db.StreamEvent{
+ StreamID: st.ID, Kind: db.EventScheduledStart, Severity: db.SevInfo,
+ Actor: db.ActorSystem, Message: "scheduled start: already running",
+ })
+ return
+ }
+ s.Log.Info("scheduled start", "stream", st.Name, "schedule", sc.ID)
+ s.Store.AddEvent(db.StreamEvent{
+ StreamID: st.ID, Kind: db.EventScheduledStart, Severity: db.SevInfo,
+ Actor: db.ActorSystem, Message: "scheduled start",
+ })
+ // Enable it too, or a manual stop earlier in the day would leave the
+ // scheduled event unable to come up.
+ if _, err := s.Store.SetEnabled(st.ID, true); err != nil {
+ s.Log.Error("scheduled enable failed", "stream", st.Name, "err", err)
+ }
+ if err := s.Sup.Start(st.ID); err != nil {
+ s.Log.Error("scheduled start failed", "stream", st.Name, "err", err)
+ s.Store.Eventf(st.ID, db.EventScheduledStart, db.SevError,
+ "scheduled start failed: %v", err)
+ }
+
+ case db.ActionStop:
+ s.Log.Info("scheduled stop", "stream", st.Name, "schedule", sc.ID)
+ s.Store.AddEvent(db.StreamEvent{
+ StreamID: st.ID, Kind: db.EventScheduledStop, Severity: db.SevInfo,
+ Actor: db.ActorSystem, Message: "scheduled stop",
+ })
+ if err := s.Sup.Stop(st.ID); err != nil {
+ s.Log.Error("scheduled stop failed", "stream", st.Name, "err", err)
+ }
+ if _, err := s.Store.SetEnabled(st.ID, false); err != nil {
+ s.Log.Error("scheduled disable failed", "stream", st.Name, "err", err)
+ }
+ }
+}
+
+// preroll asks for fresh credentials shortly before a scheduled start, so the
+// event does not begin with a capture still in flight.
+func (s *Scheduler) preroll(now time.Time) {
+ if s.Capture == nil {
+ return
+ }
+ pending, err := s.Store.PendingPreroll(now, s.Preroll)
+ if err != nil {
+ s.Log.Error("list pre-roll schedules", "err", err)
+ return
+ }
+ for _, sc := range pending {
+ st, err := s.Store.GetStream(sc.StreamID)
+ if err != nil {
+ continue
+ }
+ // Mark it either way: a stream with good credentials needs no capture,
+ // and re-checking it every 15s until the event would be pointless.
+ _ = s.Store.MarkPrerolled(sc.ID, sc.NextFireAt)
+ if !st.NeedsCapture {
+ continue
+ }
+ if n := s.Capture.RequestCapture(st, "schedule_preroll"); n > 0 {
+ s.Log.Info("pre-roll capture requested",
+ "stream", st.Name, "fires_at", sc.NextFireAt, "agents", n)
+ s.Store.Eventf(st.ID, db.EventCaptureStarted, db.SevInfo,
+ "pre-roll: asked %d agent(s) for fresh credentials before the scheduled start", n)
+ } else {
+ s.Log.Warn("pre-roll needed but no agent is connected",
+ "stream", st.Name, "fires_at", sc.NextFireAt)
+ s.Store.Eventf(st.ID, db.EventCaptureFailed, db.SevWarn,
+ "pre-roll: credentials are stale and no agent is connected")
+ }
+ }
+}
+
+// Upcoming is the dashboard's view of what is scheduled next. It returns `any`
+// to keep the api package free of a dependency on this one.
+func (s *Scheduler) Upcoming(limit int) any {
+ list, err := s.Store.UpcomingSchedules(limit)
+ if err != nil {
+ return []db.Schedule{}
+ }
+ return list
+}
diff --git a/apps/streamd/internal/supervisor/appdefaults.go b/apps/streamd/internal/supervisor/appdefaults.go
index 5e1847e..dd0440a 100644
--- a/apps/streamd/internal/supervisor/appdefaults.go
+++ b/apps/streamd/internal/supervisor/appdefaults.go
@@ -3,21 +3,25 @@ package supervisor
import (
"strings"
- "drmdecryption/app"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/modhost"
- "drmdecryption/repo"
+ "streamd/app"
+ "streamd/apps/streamd/internal/db"
+ "streamd/modhost"
+ "streamd/repo"
)
-// streamSettings are the downloader knobs for one stream. They come from the
-// stream's app module when it declares them, so the supervisor never has to
-// guess from an app name or a stream name.
+// streamSettings are the downloader and packager knobs for one stream. They
+// come from the stream row first, then the stream's app module, then the
+// installation-wide settings, then neutral defaults — so the supervisor never
+// has to guess from an app name or a stream name.
type streamSettings struct {
VideoSelect string
AudioSelect string
Rewriter string
LiveWait int
TSReadyBytes int64
+ // HLSTime and HLSListSize shape every output's segmenting.
+ HLSTime int
+ HLSListSize int
// IsHLS drives packaging choices that depend on the manifest format.
IsHLS bool
}
@@ -31,15 +35,20 @@ const (
hlsLiveWait = 6
)
-// settingsFor resolves a stream's downloader settings: the app module's
-// declarations first, then the stream row, then neutral defaults.
-func settingsFor(st db.Stream) streamSettings {
+// settingsFor resolves a stream's settings. globals is the installation-wide
+// layer, read from the settings table; pass the zero value when there is none.
+func settingsFor(st db.Stream, globals db.PackagerSettings) streamSettings {
+ // Per-stream overrides win over everything.
+ own := db.ParsePackagerSettings(st.SettingsJSON)
+
s := streamSettings{
VideoSelect: strings.TrimSpace(st.VideoSelect),
AudioSelect: strings.TrimSpace(st.AudioSelect),
Rewriter: strings.TrimSpace(st.Rewriter),
- LiveWait: defaultLiveWait,
- TSReadyBytes: defaultTSReadyBytes,
+ LiveWait: own.LiveWait,
+ TSReadyBytes: int64(own.TSReadyBytes),
+ HLSTime: own.HLSTime,
+ HLSListSize: own.HLSListSize,
IsHLS: isHLS(st),
}
if sd := streamDefaultsFor(st.App); sd != nil {
@@ -52,21 +61,53 @@ func settingsFor(st db.Stream) streamSettings {
if s.Rewriter == "" {
s.Rewriter = sd.RewriterName()
}
- if n := sd.LiveWaitSeconds(); n > 0 {
- s.LiveWait = n
+ if s.LiveWait == 0 {
+ if n := sd.LiveWaitSeconds(); n > 0 {
+ s.LiveWait = n
+ }
}
- if n := sd.TSReadyBytes(); n > 0 {
- s.TSReadyBytes = n
+ if s.TSReadyBytes == 0 {
+ if n := sd.TSReadyBytes(); n > 0 {
+ s.TSReadyBytes = n
+ }
}
}
+ // Installation-wide settings.
+ if s.LiveWait == 0 {
+ s.LiveWait = globals.LiveWait
+ }
+ if s.TSReadyBytes == 0 {
+ s.TSReadyBytes = int64(globals.TSReadyBytes)
+ }
+ if s.HLSTime == 0 {
+ s.HLSTime = globals.HLSTime
+ }
+ if s.HLSListSize == 0 {
+ s.HLSListSize = globals.HLSListSize
+ }
+ // An HLS source needs a longer wait and a bigger buffer before probing,
+ // but only when nothing more specific asked otherwise.
if s.IsHLS {
- if s.LiveWait == defaultLiveWait {
+ if s.LiveWait == 0 {
s.LiveWait = hlsLiveWait
}
- if s.TSReadyBytes == defaultTSReadyBytes {
+ if s.TSReadyBytes == 0 {
s.TSReadyBytes = hlsTSReadyBytes
}
}
+ // Neutral defaults.
+ if s.LiveWait == 0 {
+ s.LiveWait = defaultLiveWait
+ }
+ if s.TSReadyBytes == 0 {
+ s.TSReadyBytes = defaultTSReadyBytes
+ }
+ if s.HLSTime == 0 {
+ s.HLSTime = defaultHLSTime
+ }
+ if s.HLSListSize == 0 {
+ s.HLSListSize = defaultHLSListSize
+ }
if s.VideoSelect == "" {
s.VideoSelect = "for=best"
}
diff --git a/apps/streamd/internal/supervisor/appdefaults_test.go b/apps/streamd/internal/supervisor/appdefaults_test.go
index eda8448..ee1feca 100644
--- a/apps/streamd/internal/supervisor/appdefaults_test.go
+++ b/apps/streamd/internal/supervisor/appdefaults_test.go
@@ -3,11 +3,11 @@ package supervisor
import (
"testing"
- "drmdecryption/adb"
- "drmdecryption/app"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/capture"
- "drmdecryption/mpd"
+ "streamd/adb"
+ "streamd/app"
+ "streamd/apps/streamd/internal/db"
+ "streamd/capture"
+ "streamd/mpd"
)
// fakeApp stands in for a compiled-in app module: the supervisor must take its
@@ -44,7 +44,7 @@ func register(t *testing.T, f *fakeApp) {
func TestSettingsComeFromTheAppModule(t *testing.T) {
register(t, &fakeApp{name: "fakedash", rewriter: "fakedash", liveWait: 3, tsBytes: 111})
- got := settingsFor(db.Stream{App: "fakedash", MPD: "https://origin.test/manifest.mpd"})
+ got := settingsFor(db.Stream{App: "fakedash", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
if got.Rewriter != "fakedash" {
t.Errorf("rewriter = %q, want fakedash", got.Rewriter)
}
@@ -67,7 +67,7 @@ func TestStoredSettingsOverrideTheModule(t *testing.T) {
MPD: "https://origin.test/manifest.mpd",
VideoSelect: "res=1920x1080:for=best",
Rewriter: "none",
- })
+ }, db.PackagerSettings{})
if got.VideoSelect != "res=1920x1080:for=best" {
t.Errorf("video select = %q, want the stored value", got.VideoSelect)
}
@@ -78,7 +78,7 @@ func TestStoredSettingsOverrideTheModule(t *testing.T) {
// An unknown app must not inherit any provider's preferences.
func TestUnknownAppGetsNeutralDefaults(t *testing.T) {
- got := settingsFor(db.Stream{App: "nosuchapp", MPD: "https://origin.test/manifest.mpd"})
+ got := settingsFor(db.Stream{App: "nosuchapp", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
if got.VideoSelect != "for=best" || got.AudioSelect != "for=best" {
t.Errorf("selectors = %q / %q, want for=best", got.VideoSelect, got.AudioSelect)
}
@@ -93,7 +93,7 @@ func TestUnknownAppGetsNeutralDefaults(t *testing.T) {
// HLS gets more buffering and a longer live wait, by manifest shape and not by
// matching a stream name.
func TestHLSDetectionByManifestShape(t *testing.T) {
- got := settingsFor(db.Stream{App: "", MPD: "https://cdn.test/x/playlist-hls-dvr.m3u8"})
+ got := settingsFor(db.Stream{App: "", MPD: "https://cdn.test/x/playlist-hls-dvr.m3u8"}, db.PackagerSettings{})
if !got.IsHLS {
t.Fatal("an .m3u8 manifest should be detected as HLS")
}
@@ -104,7 +104,7 @@ func TestHLSDetectionByManifestShape(t *testing.T) {
t.Errorf("tsReadyBytes = %d, want %d", got.TSReadyBytes, hlsTSReadyBytes)
}
// The old code keyed this off stream names like "tg4"/"cula"/"plus".
- named := settingsFor(db.Stream{Name: "tg4-ioi", MPD: "https://origin.test/manifest.mpd"})
+ named := settingsFor(db.Stream{Name: "tg4-ioi", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
if named.TSReadyBytes != defaultTSReadyBytes {
t.Error("buffering must not be chosen by stream name any more")
}
@@ -113,7 +113,7 @@ func TestHLSDetectionByManifestShape(t *testing.T) {
// A module's rewriter is only used if it registered one under that name.
func TestRewriterLookupGatesTheRewrite(t *testing.T) {
register(t, &fakeApp{name: "fakeunregistered", rewriter: "fakeunregistered"})
- cfg := settingsFor(db.Stream{App: "fakeunregistered", MPD: "https://origin.test/manifest.mpd"})
+ cfg := settingsFor(db.Stream{App: "fakeunregistered", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
if _, needed := mpd.Lookup(cfg.Rewriter); needed {
t.Error("an unregistered rewriter name must not trigger a rewrite")
}
@@ -127,3 +127,63 @@ type stubRewriter struct{}
func (stubRewriter) Name() string { return "fakeunregistered" }
func (stubRewriter) Rewrite(in []byte, _ string) ([]byte, error) { return in, nil }
+
+// The resolution chain is: stream row, then app module, then the
+// installation-wide settings, then the compiled-in defaults.
+func TestGlobalSettingsSitBelowTheModule(t *testing.T) {
+ globals := db.PackagerSettings{HLSTime: 6, HLSListSize: 30, LiveWait: 9, TSReadyBytes: 999}
+
+ // Nothing more specific: the global layer applies.
+ got := settingsFor(db.Stream{MPD: "https://origin.test/manifest.mpd"}, globals)
+ if got.HLSTime != 6 || got.HLSListSize != 30 {
+ t.Errorf("hls_time=%d list_size=%d, want the global values", got.HLSTime, got.HLSListSize)
+ }
+ if got.LiveWait != 9 || got.TSReadyBytes != 999 {
+ t.Errorf("liveWait=%d tsReady=%d, want the global values", got.LiveWait, got.TSReadyBytes)
+ }
+
+ // A module declaration beats the global layer.
+ register(t, &fakeApp{name: "fakeglobals", rewriter: "none", liveWait: 4, tsBytes: 222})
+ got = settingsFor(db.Stream{App: "fakeglobals", MPD: "https://origin.test/manifest.mpd"}, globals)
+ if got.LiveWait != 4 || got.TSReadyBytes != 222 {
+ t.Errorf("liveWait=%d tsReady=%d, want the module values", got.LiveWait, got.TSReadyBytes)
+ }
+ // ...but the global packager knobs still apply, since no module declares them.
+ if got.HLSTime != 6 {
+ t.Errorf("hls_time = %d, want the global 6", got.HLSTime)
+ }
+}
+
+// A per-stream settings_json override beats everything else.
+func TestPerStreamSettingsWinOverAllLayers(t *testing.T) {
+ register(t, &fakeApp{name: "fakeperstream", rewriter: "none", liveWait: 4, tsBytes: 222})
+ globals := db.PackagerSettings{HLSTime: 6, HLSListSize: 30, LiveWait: 9}
+ got := settingsFor(db.Stream{
+ App: "fakeperstream",
+ MPD: "https://origin.test/manifest.mpd",
+ SettingsJSON: `{"hls_time":2,"hls_list_size":8,"live_wait":1}`,
+ }, globals)
+ if got.HLSTime != 2 || got.HLSListSize != 8 || got.LiveWait != 1 {
+ t.Errorf("got hls_time=%d list_size=%d live_wait=%d, want the per-stream 2/8/1",
+ got.HLSTime, got.HLSListSize, got.LiveWait)
+ }
+}
+
+// Nonsense in settings_json must be ignored rather than handed to ffmpeg,
+// where a zero segment duration would produce an unplayable stream.
+func TestInsaneSettingsAreIgnored(t *testing.T) {
+ for _, raw := range []string{
+ `{"hls_time":0}`, `{"hls_time":-5}`, `{"hls_time":9999}`,
+ `{"hls_list_size":0}`, `not json at all`, ``,
+ } {
+ got := settingsFor(db.Stream{
+ MPD: "https://origin.test/manifest.mpd", SettingsJSON: raw,
+ }, db.PackagerSettings{})
+ if got.HLSTime != defaultHLSTime {
+ t.Errorf("settings_json %q gave hls_time=%d, want the default %d", raw, got.HLSTime, defaultHLSTime)
+ }
+ if got.HLSListSize != defaultHLSListSize {
+ t.Errorf("settings_json %q gave list_size=%d, want the default %d", raw, got.HLSListSize, defaultHLSListSize)
+ }
+ }
+}
diff --git a/apps/streamd/internal/supervisor/ffmpeg_integration_test.go b/apps/streamd/internal/supervisor/ffmpeg_integration_test.go
new file mode 100644
index 0000000..c333c44
--- /dev/null
+++ b/apps/streamd/internal/supervisor/ffmpeg_integration_test.go
@@ -0,0 +1,218 @@
+package supervisor
+
+import (
+ "bytes"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+// These tests run the real ffmpeg against the real generated command line.
+// The unit tests prove the arguments look right; only ffmpeg can prove it
+// accepts them — tee's escaping rules in particular are easy to get subtly
+// wrong in a way no amount of string assertion would catch.
+//
+// Skipped when ffmpeg is not installed, and under -short.
+
+func ffmpegPath(t *testing.T) string {
+ t.Helper()
+ if testing.Short() {
+ t.Skip("skipping ffmpeg integration test in short mode")
+ }
+ for _, cand := range []string{os.Getenv("FFMPEG_PATH"), "ffmpeg"} {
+ if cand == "" {
+ continue
+ }
+ if p, err := exec.LookPath(cand); err == nil {
+ return p
+ }
+ }
+ t.Skip("ffmpeg not found on PATH; skipping integration test")
+ return ""
+}
+
+// makeTestTS renders a few seconds of synthetic audio and video to an MPEG-TS
+// file, standing in for what the downloader produces.
+func makeTestTS(t *testing.T, ff, dir string, seconds int) string {
+ t.Helper()
+ out := filepath.Join(dir, "source.ts")
+ cmd := exec.Command(ff,
+ "-hide_banner", "-loglevel", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc2=size=640x360:rate=25",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000",
+ "-t", strconv.Itoa(seconds),
+ "-c:v", "libx264", "-preset", "ultrafast", "-g", "25", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", "-b:a", "96k",
+ "-f", "mpegts", out,
+ )
+ if b, err := cmd.CombinedOutput(); err != nil {
+ t.Skipf("could not render a test source (%v): %s", err, b)
+ }
+ return out
+}
+
+// runPlan runs one variant's full generated command against src and returns
+// the process's CPU time.
+func runPlan(t *testing.T, ff, src, wwwDir string, spec db.VariantSpec, outputs []db.OutputSpec) (time.Duration, string) {
+ t.Helper()
+ if err := os.MkdirAll(wwwDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cfg := streamSettings{HLSTime: 2, HLSListSize: 5}
+ plan := buildOutputPlan(outputs, wwwDir, cfg, spec)
+ for _, d := range plan.Dirs {
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The real supervisor passes "-follow 1" to track a growing file; here the
+ // source is complete, so read it once and exit.
+ args := []string{"-hide_banner", "-loglevel", "error", "-y", "-i", src}
+ args = append(args, variantCodecArgs(spec)...)
+ args = append(args, plan.Args...)
+
+ cmd := exec.Command(ff, args...)
+ // Capture stderr explicitly rather than with CombinedOutput: when the TS
+ // output is on, stdout carries media and cannot also collect diagnostics.
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ if plan.WantsTS {
+ sink, err := os.Create(filepath.Join(wwwDir, "pipe.ts"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer sink.Close()
+ cmd.Stdout = sink
+ }
+ err := cmd.Run()
+ out := stderr.String()
+ if err != nil {
+ t.Fatalf("ffmpeg rejected the generated command: %v\nargs: %q\nstderr: %s", err, args, out)
+ }
+ var cpu time.Duration
+ if cmd.ProcessState != nil {
+ cpu = cmd.ProcessState.UserTime() + cmd.ProcessState.SystemTime()
+ }
+ return cpu, out
+}
+
+// A single HLS output must work: this is the command streamd has always run.
+func TestFFmpegAcceptsSingleHLSOutput(t *testing.T) {
+ ff := ffmpegPath(t)
+ dir := t.TempDir()
+ src := makeTestTS(t, ff, dir, 4)
+ www := filepath.Join(dir, "www", "news")
+ _, _ = runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ })
+ mustExist(t, filepath.Join(www, "index.m3u8"))
+ mustGlob(t, filepath.Join(www, "seg_*.ts"))
+}
+
+// The real test of the tee spec: ffmpeg must accept it and every output must
+// actually be written.
+func TestFFmpegAcceptsTeeWithEveryFormat(t *testing.T) {
+ ff := ffmpegPath(t)
+ dir := t.TempDir()
+ src := makeTestTS(t, ff, dir, 4)
+ www := filepath.Join(dir, "www", "news")
+ _, out := runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ {ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
+ {ID: "dash", Format: db.FormatDASH, Enabled: true},
+ {ID: "ts", Format: db.FormatTS, Enabled: true},
+ })
+ // onfail=ignore means a broken leg is silent, so check the files rather
+ // than trusting the exit status.
+ mustExist(t, filepath.Join(www, "index.m3u8"))
+ mustGlob(t, filepath.Join(www, "seg_*.ts"))
+ mustExist(t, filepath.Join(www, "cmaf", "index.m3u8"))
+ mustGlob(t, filepath.Join(www, "cmaf", "*.m4s"))
+ mustExist(t, filepath.Join(www, "cmaf", "init.mp4"))
+ mustExist(t, filepath.Join(www, "dash", "index.mpd"))
+ mustNonEmpty(t, filepath.Join(www, "pipe.ts"))
+ if strings.Contains(strings.ToLower(out), "invalid argument") {
+ t.Errorf("ffmpeg complained about the tee spec: %s", out)
+ }
+}
+
+// A path with a drive letter and a space is where tee escaping actually bites.
+func TestFFmpegAcceptsTeeWithAwkwardPath(t *testing.T) {
+ ff := ffmpegPath(t)
+ dir := t.TempDir()
+ src := makeTestTS(t, ff, dir, 3)
+ // A space in a directory name, which is ordinary on Windows.
+ www := filepath.Join(dir, "www root", "city news")
+ _, _ = runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ {ID: "dash", Format: db.FormatDASH, Enabled: true},
+ })
+ mustExist(t, filepath.Join(www, "index.m3u8"))
+ mustExist(t, filepath.Join(www, "dash", "index.mpd"))
+}
+
+// The headline efficiency claim: adding formats to a transcoded rung must
+// share one encode. Three formats through tee should cost far less than three
+// times a single format — if it is ~3x, the encoder is running per output.
+func TestTeeEncodesOnceNotPerOutput(t *testing.T) {
+ ff := ffmpegPath(t)
+ dir := t.TempDir()
+ // Long enough that encoding dominates process start-up cost.
+ src := makeTestTS(t, ff, dir, 8)
+ hd := db.VariantSpec{ID: "hd", Label: "HD", Enabled: true, Height: 720,
+ VideoBitrate: "2800k", AudioBitrate: "128k"}
+
+ oneCPU, _ := runPlan(t, ff, src, filepath.Join(dir, "one"), hd, []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ })
+ threeCPU, _ := runPlan(t, ff, src, filepath.Join(dir, "three"), hd, []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ {ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
+ {ID: "dash", Format: db.FormatDASH, Enabled: true},
+ })
+ if oneCPU <= 0 || threeCPU <= 0 {
+ t.Skipf("no CPU accounting available (one=%v three=%v)", oneCPU, threeCPU)
+ }
+ ratio := float64(threeCPU) / float64(oneCPU)
+ t.Logf("CPU: 1 format = %v, 3 formats = %v (ratio %.2fx)", oneCPU, threeCPU, ratio)
+ // Muxing three times instead of once is not free, but it is nothing like
+ // encoding three times. Anything approaching 3x means tee is not in use.
+ if ratio > 2.0 {
+ t.Errorf("3 formats cost %.2fx the CPU of 1 — the encoder appears to be running "+
+ "per output rather than once through tee", ratio)
+ }
+}
+
+func mustExist(t *testing.T, path string) {
+ t.Helper()
+ st, err := os.Stat(path)
+ if err != nil {
+ t.Errorf("expected %s to exist: %v", path, err)
+ return
+ }
+ if st.Size() == 0 {
+ t.Errorf("%s is empty", path)
+ }
+}
+
+func mustNonEmpty(t *testing.T, path string) {
+ t.Helper()
+ st, err := os.Stat(path)
+ if err != nil || st.Size() == 0 {
+ t.Errorf("expected %s to have content (err=%v)", path, err)
+ }
+}
+
+func mustGlob(t *testing.T, pattern string) {
+ t.Helper()
+ m, err := filepath.Glob(pattern)
+ if err != nil || len(m) == 0 {
+ t.Errorf("expected files matching %s (err=%v)", pattern, err)
+ }
+}
diff --git a/apps/streamd/internal/supervisor/media.go b/apps/streamd/internal/supervisor/media.go
index b616146..8f7e8e8 100644
--- a/apps/streamd/internal/supervisor/media.go
+++ b/apps/streamd/internal/supervisor/media.go
@@ -4,80 +4,126 @@ import (
"encoding/json"
"fmt"
"io"
- "log"
+ "log/slog"
"os"
"os/exec"
"path/filepath"
- "runtime"
"strconv"
"strings"
"sync"
"time"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/mpd"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/logfile"
+ "streamd/apps/streamd/internal/tsfanout"
+ "streamd/mpd"
)
-// Media runs N_m3u8DL-RE + ffmpeg HLS packager per stream into DataDir/www//.
+// Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into
+// DataDir/www// and, when the progressive TS output is on, into a
+// shared in-memory ring.
type Media struct {
Store *db.Store
DataDir string
NRE string
FFmpeg string
MP4Decrypt string
- Log *log.Logger
+ Log *slog.Logger
+ // Fanout holds the live progressive-TS rings, when that output is on.
+ Fanout *tsfanout.Set
+ // Notifier pushes health changes to the dashboard. Optional.
+ Notifier Notifier
+ // ViewersFn reports the live client count for a stream, for the metrics
+ // series. Optional.
+ ViewersFn func(streamName string) int
+ // ProxyResolver resolves stream.Proxy / stream.Egress to a SOCKS/HTTP URL.
+ ProxyResolver ProxyResolver
mu sync.Mutex
procs map[int64]*streamProc
stopMon chan struct{}
}
+// ProxyResolver turns a stream row into an origin-fetch proxy URL.
+type ProxyResolver interface {
+ ResolveProxy(st db.Stream) (string, error)
+}
+
+// Notifier is the subset of the websocket hub the supervisor needs.
+type Notifier interface {
+ NotifyRuntime(name, health string)
+ NotifyStreamChanged(name, reason string)
+}
+
type streamProc struct {
- id int64
- name string
- nre *exec.Cmd
- ffmpeg *exec.Cmd
- started time.Time
- workDir string
- wwwDir string
- tsPath string
- hlsIndex string
- nreLog *os.File
- ffOutLog *os.File
- ffErrLog *os.File
- stopping bool
- mpdProxy *mpd.LocalServer
- nreDead bool
- ffDead bool
+ id int64
+ name string
+ nre *exec.Cmd
+ ffmpeg *exec.Cmd
+ started time.Time
+ sessionID int64 // stream_sessions row opened when NRE starts
+ workDir string
+ wwwDir string
+ tsPath string
+ hlsIndex string
+ nreLogFile *os.File // per-stream NRE log (banner + append)
+ nrePTY io.Closer // Linux PTY master; nil on Windows / fallback
+ ffOutLog *logfile.Writer
+ ffErrLog *logfile.Writer
+ stopping bool
+ mpdProxy *mpd.LocalServer
+ nreDead bool
+ ffDead bool
+ variants []*variantProc
+ variantSpecs []db.VariantSpec
+ outputSpecs []db.OutputSpec
+ cfg streamSettings
// tsReadyBytes is how much muxed output to buffer before probing, from the
// stream's app module.
tsReadyBytes int64
+ // lastHealth lets the supervisor report only health transitions.
+ lastHealth string
+ // lastTSSize / lastTSAt back the bitrate estimate.
+ lastTSSize int64
+ lastTSAt time.Time
}
// Options for constructing the media supervisor.
type Options struct {
- Store *db.Store
- DataDir string
- NRE string
- FFmpeg string
- MP4Decrypt string
- Log *log.Logger
+ Store *db.Store
+ DataDir string
+ NRE string
+ FFmpeg string
+ MP4Decrypt string
+ Log *slog.Logger
+ Fanout *tsfanout.Set
+ Notifier Notifier
+ ViewersFn func(streamName string) int
+ ProxyResolver ProxyResolver
}
func NewMedia(opt Options) *Media {
lg := opt.Log
if lg == nil {
- lg = log.Default()
+ lg = slog.Default()
+ }
+ fan := opt.Fanout
+ if fan == nil {
+ fan = tsfanout.NewSet(tsfanout.DefaultBufferBytes)
}
m := &Media{
- Store: opt.Store,
- DataDir: opt.DataDir,
- NRE: opt.NRE,
- FFmpeg: opt.FFmpeg,
- MP4Decrypt: opt.MP4Decrypt,
- Log: lg,
- procs: map[int64]*streamProc{},
- stopMon: make(chan struct{}),
+ Store: opt.Store,
+ DataDir: opt.DataDir,
+ NRE: opt.NRE,
+ FFmpeg: opt.FFmpeg,
+ MP4Decrypt: opt.MP4Decrypt,
+ Log: lg,
+ Fanout: fan,
+ Notifier: opt.Notifier,
+ ViewersFn: opt.ViewersFn,
+ ProxyResolver: opt.ProxyResolver,
+ procs: map[int64]*streamProc{},
+ stopMon: make(chan struct{}),
}
go m.monitorLoop()
return m
@@ -96,34 +142,40 @@ func (m *Media) Close() {
}
}
+// Running reports whether a stream currently has a live worker. The HLS gate
+// uses this to decide whether a request needs to wake the stream.
+func (m *Media) Running(id int64) bool {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ sp, ok := m.procs[id]
+ return ok && !sp.stopping
+}
+
+func (m *Media) logsDir() string { return filepath.Join(m.DataDir, "logs") }
+
+func (m *Media) effectiveProxy(st db.Stream) (string, error) {
+ if m.ProxyResolver != nil {
+ return m.ProxyResolver.ResolveProxy(st)
+ }
+ return strings.TrimSpace(st.Proxy), nil
+}
+
func (m *Media) Start(id int64) error {
st, err := m.Store.GetStream(id)
if err != nil {
return err
}
- if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
- _ = m.Store.SetRuntime(id, db.RuntimePatch{
- Health: "down",
- PlayPath: "/hls/" + st.Name + "/index.m3u8",
- LastError: "missing mpd/key - capture required",
- })
- return fmt.Errorf("missing mpd/key")
+ if strings.TrimSpace(st.MPD) == "" {
+ m.fail(id, st.Name, "missing mpd — paste a manifest URL (keys optional for clear streams)")
+ return fmt.Errorf("missing mpd")
}
mpdURL := strings.TrimSpace(st.MPD)
if !strings.HasPrefix(strings.ToLower(mpdURL), "http://") && !strings.HasPrefix(strings.ToLower(mpdURL), "https://") {
- _ = m.Store.SetRuntime(id, db.RuntimePatch{
- Health: "down",
- PlayPath: "/hls/" + st.Name + "/index.m3u8",
- LastError: "mpd must be an http(s) URL",
- })
+ m.fail(id, st.Name, "mpd must be an http(s) URL")
return fmt.Errorf("invalid mpd url")
}
if m.NRE == "" || m.FFmpeg == "" {
- _ = m.Store.SetRuntime(id, db.RuntimePatch{
- Health: "down",
- PlayPath: "/hls/" + st.Name + "/index.m3u8",
- LastError: "NRE or ffmpeg binary not configured",
- })
+ m.fail(id, st.Name, "NRE or ffmpeg binary not configured")
return fmt.Errorf("NRE or ffmpeg not configured")
}
@@ -141,60 +193,64 @@ func (m *Media) Start(id int64) error {
workDir := filepath.Join(m.DataDir, "work", st.Name)
wwwDir := filepath.Join(m.DataDir, "www", st.Name)
+ variantSpecs := db.ParseVariantsJSON(st.VariantsJSON)
+ outputSpecs := db.ParseOutputsJSON(st.OutputsJSON)
// Fresh dirs each start — leftover decrypted segments make NRE File.Move fail.
_ = os.RemoveAll(wwwDir)
_ = os.RemoveAll(workDir)
- for _, d := range []string{workDir, wwwDir, filepath.Join(m.DataDir, "logs")} {
+ for _, v := range db.ScaledVariants(variantSpecs) {
+ _ = os.RemoveAll(filepath.Join(m.DataDir, "www", db.VariantDir(st.Name, v.ID, v.Height, v.AudioOnly)))
+ }
+ for _, d := range []string{workDir, wwwDir, m.logsDir()} {
if err := os.MkdirAll(d, 0o755); err != nil {
return err
}
}
keysFile := filepath.Join(workDir, "keys.txt")
- keysBody := normalizeKeysFile(st.Key)
- if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil {
- return err
+ hasKeys := strings.TrimSpace(st.Key) != ""
+ if hasKeys {
+ keysBody := normalizeKeysFile(st.Key)
+ // 0600: this file holds the content keys.
+ if err := os.WriteFile(keysFile, []byte(keysBody), 0o600); err != nil {
+ return err
+ }
}
saveName := st.Name
- tsPath := filepath.Join(workDir, saveName+".ts")
- _ = os.Remove(tsPath)
-
headers := headerMap(st.HeadersJSON)
+ cfg := settingsFor(st, m.Store.GlobalPackagerSettings())
+ originProxy, err := m.effectiveProxy(st)
+ if err != nil {
+ m.fail(id, st.Name, "egress: "+err.Error())
+ return err
+ }
manifestURL := st.MPD
- cfg := settingsFor(st)
var mpdProxy *mpd.LocalServer
// The rewriter is named by the stream row or its app module and looked up in
// the mpd registry, so streamd needs no knowledge of any provider.
if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS {
- srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw)
+ srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, originProxy)
if err != nil {
- _ = m.Store.SetRuntime(id, db.RuntimePatch{
- Health: "down", PlayPath: "/hls/" + st.Name + "/index.m3u8",
- LastError: "mpd rewrite server: " + err.Error(),
- })
+ m.fail(id, st.Name, "mpd rewrite server: "+err.Error())
return err
}
mpdProxy = srv
manifestURL = srv.URL
- m.logf("stream %s: rewritten MPD %s", st.Name, manifestURL)
+ m.Log.Info("rewritten MPD in use", "stream", st.Name, "url", manifestURL)
}
// Ad-stitched manifest rewrite + live pipe mux.
nreTmp := filepath.Join(workDir, "nre")
_ = os.MkdirAll(nreTmp, 0o755)
- tsPath = filepath.Join(nreTmp, saveName+".ts")
+ tsPath := filepath.Join(nreTmp, saveName+".ts")
_ = os.Remove(tsPath)
liveWait := strconv.Itoa(cfg.LiveWait)
nreArgs := []string{
manifestURL,
- // Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
- // always feed every KID:KEY via --key-text-file.
- "--key-text-file", keysFile,
"--live-real-time-merge",
"--live-pipe-mux",
- "--mp4-real-time-decryption",
"--live-wait-time", liveWait,
"--ffmpeg-binary-path", m.FFmpeg,
"--save-name", saveName,
@@ -202,7 +258,24 @@ func (m *Media) Start(id int64) error {
"--tmp-dir", nreTmp,
"--no-ansi-color",
"--log-level", "ERROR",
- "-ss", "0",
+ // Drop every subtitle track. Live pipe-mux to TS does not need them, and
+ // an extra Spectre progress row makes redirected-console crashes more
+ // likely (NRE forces ANSI UI when stdout is a log file).
+ "-ds", "for=all",
+ }
+ if hasKeys {
+ // Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
+ // always feed every KID:KEY via --key-text-file.
+ nreArgs = append(nreArgs,
+ "--key-text-file", keysFile,
+ "--mp4-real-time-decryption",
+ )
+ }
+ if proxy := strings.TrimSpace(originProxy); proxy != "" {
+ // NRE prefers --custom-proxy over the system proxy when both are set.
+ // The proxy may carry credentials, so it is not logged.
+ nreArgs = append(nreArgs, "--custom-proxy", proxy)
+ m.Log.Info("origin proxy in use", "stream", st.Name)
}
// A synthetic manifest publishes exactly one video + audio pair, and an HLS
// master's variants rarely match a resolution/language filter, so in both
@@ -212,7 +285,7 @@ func (m *Media) Start(id int64) error {
} else {
nreArgs = append(nreArgs, "-sv", cfg.VideoSelect, "-sa", cfg.AudioSelect)
}
- if m.MP4Decrypt != "" {
+ if hasKeys && m.MP4Decrypt != "" {
nreArgs = append(nreArgs,
"--decryption-engine", "MP4DECRYPT",
"--decryption-binary-path", m.MP4Decrypt,
@@ -224,21 +297,25 @@ func (m *Media) Start(id int64) error {
nreArgs = append(nreArgs, "-H", h)
}
}
- _ = keysFile // kept on disk for debugging
- nreLogPath := filepath.Join(m.DataDir, "logs", st.Name+"-nre.log")
- nreLog, err := os.OpenFile(nreLogPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
+ // Banner + rotate-on-open keep prior runs readable. On Linux, NRE runs under
+ // a PTY (see startNRELogged): plain file/pipe redirects force Spectre live UI
+ // with WindowWidth 0 and crash ProgressRefreshThread.
+ nreLogFile, err := logfile.OpenCmdLog(
+ filepath.Join(m.logsDir(), st.Name+"-nre.log"),
+ logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre")
if err != nil {
return err
}
nreCmd := exec.Command(m.NRE, nreArgs...)
- nreCmd.Stdout = nreLog
- nreCmd.Stderr = nreLog
hideWindow(nreCmd)
// NRE (v0.6) resolves mp4decrypt via PATH / sibling of its .exe, and often
// ignores --decryption-binary-path for MP4DECRYPT. Match legacy: prepend
// dirs and best-effort copy beside NRE.
nreEnv := os.Environ()
+ nreEnv = setEnvDefault(nreEnv, "COLUMNS", "120")
+ nreEnv = setEnvDefault(nreEnv, "LINES", "40")
+ nreEnv = setEnvDefault(nreEnv, "TERM", "xterm")
pathPrepend := []string{}
if m.MP4Decrypt != "" {
pathPrepend = append(pathPrepend, filepath.Dir(m.MP4Decrypt))
@@ -255,28 +332,41 @@ func (m *Media) Start(id int64) error {
nreEnv = prependPathEnv(nreEnv, strings.Join(pathPrepend, sep))
}
nreCmd.Env = nreEnv
- if err := nreCmd.Start(); err != nil {
- _ = nreLog.Close()
+ nrePTY, keepLogFD, err := startNRELogged(nreCmd, nreLogFile)
+ if err != nil {
+ if keepLogFD {
+ _ = nreLogFile.Close()
+ }
if mpdProxy != nil {
mpdProxy.Close()
}
- _ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "down", LastError: err.Error(), PlayPath: "/hls/" + st.Name + "/index.m3u8"})
+ m.fail(id, st.Name, err.Error())
return err
}
- m.logf("stream %s: NRE pid=%d", st.Name, nreCmd.Process.Pid)
+ ownedLog := nreLogFile
+ if !keepLogFD {
+ ownedLog = nil
+ }
+ m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
+ sessionID, _ := m.Store.OpenSession(id)
sp := &streamProc{
- id: id,
- name: st.Name,
- nre: nreCmd,
- started: time.Now(),
- workDir: workDir,
- wwwDir: wwwDir,
- tsPath: tsPath,
- hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
- nreLog: nreLog,
- mpdProxy: mpdProxy,
+ id: id,
+ name: st.Name,
+ nre: nreCmd,
+ started: time.Now(),
+ sessionID: sessionID,
+ workDir: workDir,
+ wwwDir: wwwDir,
+ tsPath: tsPath,
+ hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
+ nreLogFile: ownedLog,
+ nrePTY: nrePTY,
+ mpdProxy: mpdProxy,
+ variantSpecs: variantSpecs,
+ outputSpecs: outputSpecs,
+ cfg: cfg,
tsReadyBytes: cfg.TSReadyBytes,
}
@@ -284,6 +374,12 @@ func (m *Media) Start(id int64) error {
m.procs[id] = sp
m.mu.Unlock()
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: id, Kind: db.EventStarted, Severity: db.SevInfo,
+ Message: fmt.Sprintf("downloader started (pid %d), publishing %s",
+ nreCmd.Process.Pid, outputSummary(outputSpecs)),
+ })
+
go func() {
_ = nreCmd.Wait()
m.mu.Lock()
@@ -297,6 +393,34 @@ func (m *Media) Start(id int64) error {
return nil
}
+// fail records a start-up failure in one place: runtime row, timeline, log and
+// dashboard push.
+func (m *Media) fail(id int64, name, msg string) {
+ _ = m.Store.SetRuntime(id, db.RuntimePatch{
+ Health: "down",
+ PlayPath: "/hls/" + name + "/index.m3u8",
+ LastError: msg,
+ })
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: id, Kind: db.EventCrashed, Severity: db.SevError, Message: msg,
+ })
+ m.Log.Error("stream failed to start", "stream", name, "err", msg)
+ if m.Notifier != nil {
+ m.Notifier.NotifyRuntime(name, "down")
+ }
+}
+
+func outputSummary(outputs []db.OutputSpec) string {
+ var on []string
+ for _, o := range db.EnabledOutputs(outputs) {
+ on = append(on, o.Label)
+ }
+ if len(on) == 0 {
+ return "nothing"
+ }
+ return strings.Join(on, "+")
+}
+
func (m *Media) bootstrapHLS(sp *streamProc) {
deadline := time.Now().Add(3 * time.Minute)
nreDir := filepath.Dir(sp.tsPath)
@@ -323,8 +447,13 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + sp.name + "/index.m3u8",
- LastError: "NRE exited before TS was ready — see logs/" + sp.name + "-nre.log",
+ LastError: "NRE exited before TS was ready — see data/logs/" + sp.name + "-nre.log",
})
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
+ Message: "downloader exited before any media arrived — see data/logs/" + sp.name + "-nre.log",
+ })
+ m.closeSession(sp, db.SessionNREExit, "down")
m.cleanupProc(sp.id)
return
}
@@ -336,16 +465,26 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
PlayPath: "/hls/" + sp.name + "/index.m3u8",
LastError: "timed out waiting for growing TS",
})
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
+ Message: "timed out waiting for the downloader to produce media",
+ })
_ = m.Stop(sp.id)
return
}
- if err := m.startFFmpegHLS(sp); err != nil {
+ if err := m.startPackager(sp); err != nil {
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
Health: "down", LastError: err.Error(), PlayPath: "/hls/" + sp.name + "/index.m3u8",
})
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
+ Message: "packager failed to start: " + err.Error(),
+ })
return
}
+ m.startVariantPackagers(sp, sp.variantSpecs)
+ m.writeMasterPlaylist(sp)
pid := int64(0)
if sp.nre != nil && sp.nre.Process != nil {
pid = int64(sp.nre.Process.Pid)
@@ -357,46 +496,67 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
})
}
-func (m *Media) startFFmpegHLS(sp *streamProc) error {
- ffOut := filepath.Join(m.DataDir, "logs", sp.name+"-ffmpeg.out.log")
- ffErr := filepath.Join(m.DataDir, "logs", sp.name+"-ffmpeg.err.log")
- outF, err := os.OpenFile(ffOut, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+// startPackager runs the ffmpeg that publishes the source rung's outputs.
+// The source rung is a stream copy, so additional output formats here are
+// nearly free; the tee muxer still keeps it to one process.
+func (m *Media) startPackager(sp *streamProc) error {
+ sourceSpec := db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true, Height: 0}
+ plan := buildOutputPlan(sp.outputSpecs, sp.wwwDir, sp.cfg, sourceSpec)
+ // ffmpeg will not create an output's directory, and under tee's
+ // onfail=ignore a missing one fails that output silently.
+ for _, d := range plan.Dirs {
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ return err
+ }
+ }
+
+ args := append(inputArgs(sp.tsPath), variantCodecArgs(sourceSpec)...)
+ args = append(args, plan.Args...)
+
+ errLog, err := logfile.OpenWithBanner(
+ filepath.Join(m.logsDir(), sp.name+"-ffmpeg.err.log"),
+ logfile.DefaultMaxBytes, logfile.DefaultGenerations, "ffmpeg")
if err != nil {
return err
}
- errF, err := os.OpenFile(ffErr, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
- if err != nil {
- _ = outF.Close()
- return err
+ ffCmd := exec.Command(m.FFmpeg, args...)
+ ffCmd.Stderr = errLog
+
+ var outLog *logfile.Writer
+ if plan.WantsTS {
+ // stdout carries the live media, so it cannot also be a log file.
+ // ffmpeg writes diagnostics to stderr, so nothing is lost.
+ ring := m.Fanout.Create(sp.name)
+ pipe, err := ffCmd.StdoutPipe()
+ if err != nil {
+ _ = errLog.Close()
+ return err
+ }
+ go func() {
+ _, _ = io.Copy(ring, pipe)
+ _ = ring.Close()
+ }()
+ } else {
+ outLog, err = logfile.Open(
+ filepath.Join(m.logsDir(), sp.name+"-ffmpeg.out.log"),
+ logfile.DefaultMaxBytes, logfile.DefaultGenerations)
+ if err != nil {
+ _ = errLog.Close()
+ return err
+ }
+ ffCmd.Stdout = outLog
}
- ffArgs := []string{
- "-hide_banner", "-loglevel", "warning", "-y",
- "-follow", "1",
- // Large probe: early pipe-mux bytes often lack clean audio config.
- "-analyzeduration", "20M",
- "-probesize", "10M",
- "-fflags", "+genpts",
- "-i", sp.tsPath,
- "-map", "0",
- "-c", "copy",
- "-f", "hls",
- "-hls_time", "4",
- "-hls_list_size", "15",
- "-hls_flags", "delete_segments+append_list+omit_endlist+independent_segments",
- "-hls_segment_type", "mpegts",
- "-hls_segment_filename", filepath.Join(sp.wwwDir, "seg_%05d.ts"),
- sp.hlsIndex,
- }
- ffCmd := exec.Command(m.FFmpeg, ffArgs...)
- ffCmd.Stdout = outF
- ffCmd.Stderr = errF
+
hideWindow(ffCmd)
if err := ffCmd.Start(); err != nil {
- _ = outF.Close()
- _ = errF.Close()
+ _ = errLog.Close()
+ if outLog != nil {
+ _ = outLog.Close()
+ }
return err
}
- m.logf("stream %s: ffmpeg HLS pid=%d → %s", sp.name, ffCmd.Process.Pid, sp.hlsIndex)
+ m.Log.Info("packager started", "stream", sp.name, "pid", ffCmd.Process.Pid,
+ "outputs", outputSummary(sp.outputSpecs))
m.mu.Lock()
if cur, ok := m.procs[sp.id]; ok && !cur.stopping {
@@ -407,14 +567,16 @@ func (m *Media) startFFmpegHLS(sp *streamProc) error {
_ = cur.ffErrLog.Close()
}
cur.ffmpeg = ffCmd
- cur.ffOutLog = outF
- cur.ffErrLog = errF
+ cur.ffOutLog = outLog
+ cur.ffErrLog = errLog
cur.ffDead = false
} else {
m.mu.Unlock()
_ = killProcess(ffCmd)
- _ = outF.Close()
- _ = errF.Close()
+ _ = errLog.Close()
+ if outLog != nil {
+ _ = outLog.Close()
+ }
return fmt.Errorf("stream stopped before ffmpeg attach")
}
m.mu.Unlock()
@@ -443,9 +605,12 @@ func (m *Media) Stop(id int64) error {
if st.Name != "" {
name = st.Name
}
+ _ = m.Store.CloseOpenSessions(id, db.SessionStopped, "stopped")
_ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "stopped", PlayPath: "/hls/" + name + "/index.m3u8"})
return nil
}
+ m.closeSession(sp, db.SessionStopped, "stopped")
+ m.stopAllVariants(sp)
nrePID, ffPID := 0, 0
if sp.ffmpeg != nil && sp.ffmpeg.Process != nil {
ffPID = sp.ffmpeg.Process.Pid
@@ -459,21 +624,42 @@ func (m *Media) Stop(id int64) error {
sp.mpdProxy.Close()
sp.mpdProxy = nil
}
+ // Drops every progressive-TS client of this stream and its variants.
+ m.Fanout.RemovePrefix(sp.name)
waitPIDsGone([]int{nrePID, ffPID}, 5*time.Second)
m.cleanupProc(id)
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "stopped",
PlayPath: "/hls/" + sp.name + "/index.m3u8",
})
- m.logf("stream %s: stopped", sp.name)
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: id, Kind: db.EventStopped, Severity: db.SevInfo, Message: "worker stopped",
+ })
+ m.Log.Info("stream stopped", "stream", sp.name)
+ if m.Notifier != nil {
+ m.Notifier.NotifyRuntime(sp.name, "stopped")
+ }
return nil
}
+// closeSession ends the open stream_sessions row for this process, if any.
+func (m *Media) closeSession(sp *streamProc, reason, health string) {
+ if sp == nil || sp.sessionID == 0 {
+ return
+ }
+ _ = m.Store.CloseSession(sp.sessionID, reason, health)
+ sp.sessionID = 0
+}
+
func (m *Media) Restart(id int64) error {
- m.logf("stream id=%d: hard restart (kill worker, fresh start)", id)
+ m.Log.Info("hard restart", "stream_id", id)
_ = m.Stop(id)
// Give Windows time to release file locks on work/www before Start wipes them.
time.Sleep(1 * time.Second)
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: id, Kind: db.EventRestarted, Severity: db.SevInfo,
+ Message: "restarting worker",
+ })
return m.Start(id)
}
@@ -484,14 +670,18 @@ func (m *Media) cleanupProc(id int64) {
if !ok {
return
}
- if sp.nreLog != nil {
- _ = sp.nreLog.Close()
+ if sp.nrePTY != nil {
+ _ = sp.nrePTY.Close()
+ sp.nrePTY = nil
}
- if sp.ffOutLog != nil {
- _ = sp.ffOutLog.Close()
+ if sp.nreLogFile != nil {
+ _ = sp.nreLogFile.Close()
+ sp.nreLogFile = nil
}
- if sp.ffErrLog != nil {
- _ = sp.ffErrLog.Close()
+ for _, w := range []*logfile.Writer{sp.ffOutLog, sp.ffErrLog} {
+ if w != nil {
+ _ = w.Close()
+ }
}
delete(m.procs, id)
}
@@ -540,8 +730,15 @@ func (m *Media) refreshHealth(id int64) {
if nreDead {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime,
- LastError: "NRE process exited — see logs/" + sp.name + "-nre.log",
+ LastError: "NRE process exited — see data/logs/" + sp.name + "-nre.log",
})
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: id, Kind: db.EventCrashed, Severity: db.SevError,
+ Message: fmt.Sprintf("downloader exited after %.0fs — see data/logs/%s-nre.log", uptime, sp.name),
+ })
+ m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
+ m.closeSession(sp, db.SessionNREExit, "down")
+ m.report(sp, "down")
m.cleanupProc(id)
return
}
@@ -552,6 +749,7 @@ func (m *Media) refreshHealth(id int64) {
Health: "starting", PID: pid, PlayPath: playPath, UptimeS: uptime,
LastError: "waiting for HLS playlist",
})
+ m.sample(sp, "starting", 0, 0)
if ffDead {
// restart ffmpeg packager if TS still growing
go m.restartFFmpeg(sp)
@@ -565,13 +763,86 @@ func (m *Media) refreshHealth(id int64) {
health = "down"
lastErr = fmt.Sprintf("playlist stale (%.0fs)", age)
}
+ bitrate := m.estimateBitrate(sp)
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: health, PID: pid, PlayPath: playPath, UptimeS: uptime,
- PlaylistAgeS: age, LastError: lastErr,
+ PlaylistAgeS: age, LastError: lastErr, BitrateMbps: bitrate,
})
+ m.sample(sp, health, bitrate, age)
+ m.report(sp, health)
if ffDead && health != "down" {
go m.restartFFmpeg(sp)
}
+ go m.restartDeadVariants(sp)
+}
+
+// report pushes a health change to the dashboard, only on a transition, so an
+// idle stream does not generate traffic every five seconds.
+func (m *Media) report(sp *streamProc, health string) {
+ m.mu.Lock()
+ cur, ok := m.procs[sp.id]
+ if !ok {
+ m.mu.Unlock()
+ return
+ }
+ prev := cur.lastHealth
+ changed := prev != health
+ cur.lastHealth = health
+ m.mu.Unlock()
+ if !changed {
+ return
+ }
+ if prev != "" {
+ sev := db.SevInfo
+ if health == "down" {
+ sev = db.SevError
+ }
+ m.Store.Eventf(sp.id, db.EventVariantUp, sev, "health %s to %s", prev, health)
+ }
+ if m.Notifier != nil {
+ m.Notifier.NotifyRuntime(sp.name, health)
+ }
+}
+
+// sample records one point on the stream's health series.
+func (m *Media) sample(sp *streamProc, health string, bitrate, age float64) {
+ viewers := 0
+ if m.ViewersFn != nil {
+ viewers = m.ViewersFn(sp.name)
+ }
+ m.Store.AddMetric(sp.id, db.MetricPoint{
+ Health: health,
+ BitrateMbps: bitrate,
+ PlaylistAgeS: age,
+ Viewers: viewers,
+ })
+}
+
+// estimateBitrate derives Mbps from how fast the muxed TS is growing, which is
+// all the dashboard sparkline needs.
+func (m *Media) estimateBitrate(sp *streamProc) float64 {
+ fi, err := os.Stat(sp.tsPath)
+ if err != nil {
+ return 0
+ }
+ size := fi.Size()
+ nowT := time.Now()
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ cur, ok := m.procs[sp.id]
+ if !ok {
+ return 0
+ }
+ prevSize, prevAt := cur.lastTSSize, cur.lastTSAt
+ cur.lastTSSize, cur.lastTSAt = size, nowT
+ if prevAt.IsZero() || size <= prevSize {
+ return 0
+ }
+ elapsed := nowT.Sub(prevAt).Seconds()
+ if elapsed <= 0 {
+ return 0
+ }
+ return float64(size-prevSize) * 8 / elapsed / 1e6
}
func (m *Media) restartFFmpeg(sp *streamProc) {
@@ -598,19 +869,28 @@ func (m *Media) restartFFmpeg(sp *streamProc) {
m.mu.Unlock()
return
}
- m.logf("stream %s: restarting ffmpeg HLS packager", sp.name)
- if err := m.startFFmpegHLS(sp); err != nil {
- m.logf("stream %s: ffmpeg restart failed: %v", sp.name, err)
+ m.Log.Warn("restarting packager", "stream", sp.name)
+ m.Store.AddEvent(db.StreamEvent{
+ StreamID: sp.id, Kind: db.EventFFRestart, Severity: db.SevWarn,
+ Message: "packager exited; restarting it",
+ })
+ if err := m.startPackager(sp); err != nil {
+ m.Log.Error("packager restart failed", "stream", sp.name, "err", err)
m.mu.Lock()
if cur, ok := m.procs[sp.id]; ok {
cur.ffDead = true
}
m.mu.Unlock()
+ return
}
-}
-
-func (m *Media) logf(format string, args ...any) {
- m.Log.Printf("supervisor: "+format, args...)
+ m.mu.Lock()
+ specs := sp.variantSpecs
+ if cur, ok := m.procs[sp.id]; ok {
+ specs = cur.variantSpecs
+ }
+ m.mu.Unlock()
+ m.startVariantPackagers(sp, specs)
+ m.writeMasterPlaylist(sp)
}
func headerMap(headersJSON string) map[string]string {
@@ -645,37 +925,26 @@ func headerFlags(headersJSON string) []string {
// normalizeKeysFile turns a DB key field (one or many KID:KEY lines, or
// comma/semicolon separated) into an NRE --key-text-file body.
func normalizeKeysFile(raw string) string {
- raw = strings.ReplaceAll(raw, ",", "\n")
- raw = strings.ReplaceAll(raw, ";", "\n")
- var lines []string
+ var out []string
seen := map[string]bool{}
- for _, line := range strings.Split(raw, "\n") {
- line = strings.TrimSpace(line)
- if line == "" || strings.Count(line, ":") != 1 {
- continue
- }
- if seen[line] {
+ for _, line := range db.SplitKeyLines(raw) {
+ if strings.Count(line, ":") != 1 || seen[line] {
continue
}
seen[line] = true
- lines = append(lines, line)
+ out = append(out, line)
}
- if len(lines) == 0 {
+ if len(out) == 0 {
return strings.TrimSpace(raw) + "\n"
}
- return strings.Join(lines, "\n") + "\n"
+ return strings.Join(out, "\n") + "\n"
}
func killProcess(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
- pid := cmd.Process.Pid
- if runtime.GOOS == "windows" {
- _ = exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
- return nil
- }
- return cmd.Process.Kill()
+ return killProcessTree(cmd)
}
func prependPathEnv(env []string, prefix string) []string {
@@ -698,6 +967,20 @@ func prependPathEnv(env []string, prefix string) []string {
return out
}
+// setEnvDefault sets KEY=value when KEY is missing or empty in env.
+func setEnvDefault(env []string, key, value string) []string {
+ prefix := key + "="
+ for i, e := range env {
+ if strings.HasPrefix(e, prefix) {
+ if strings.TrimSpace(e[len(prefix):]) == "" {
+ env[i] = prefix + value
+ }
+ return env
+ }
+ }
+ return append(env, prefix+value)
+}
+
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
@@ -715,8 +998,6 @@ func copyFile(src, dst string) error {
return out.Close()
}
-// findGrowingTS locates NRE's live-pipe-mux output. Depending on version/flags
-// it may be saveName.ts or saveName..ts (e.g. test.en.ts).
func waitPIDsGone(pids []int, timeout time.Duration) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
@@ -737,10 +1018,8 @@ func waitPIDsGone(pids []int, timeout time.Duration) {
}
}
-func findGrowingTS(dir, saveName string) string {
- return findGrowingTSMin(dir, saveName, 256*1024)
-}
-
+// findGrowingTSMin locates NRE's live-pipe-mux output. Depending on
+// version/flags it may be saveName.ts or saveName..ts (e.g. test.en.ts).
func findGrowingTSMin(dir, saveName string, minSize int64) string {
if minSize <= 0 {
minSize = 256 * 1024
diff --git a/apps/streamd/internal/supervisor/outputs.go b/apps/streamd/internal/supervisor/outputs.go
new file mode 100644
index 0000000..0a2457e
--- /dev/null
+++ b/apps/streamd/internal/supervisor/outputs.go
@@ -0,0 +1,299 @@
+package supervisor
+
+import (
+ "fmt"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+// Packager defaults. These were literals in the ffmpeg command line before
+// they became per-stream settings.
+const (
+ defaultHLSTime = 4
+ defaultHLSListSize = 15
+ hlsFlags = "delete_segments+append_list+omit_endlist+independent_segments"
+)
+
+// outputPlan is the resolved publishing plan for one variant.
+type outputPlan struct {
+ // Args are the ffmpeg output arguments, appended after the input.
+ Args []string
+ // WantsTS is true when one of the outputs is the progressive MPEG-TS
+ // pipe, which means the process's stdout is media and must not also be
+ // used for logging.
+ WantsTS bool
+ // Dirs must exist before ffmpeg starts: it will not create them, and
+ // under tee's onfail=ignore a missing one fails that output silently.
+ Dirs []string
+ // Playlists maps an output format to the file it writes, for health
+ // checks and the master playlist.
+ Playlists map[string]string
+}
+
+// buildOutputPlan turns a variant's enabled outputs into ffmpeg arguments.
+//
+// With a single output it emits a plain "-f ... ", which keeps
+// the common HLS-only case the same shape streamd has always run. With
+// several it emits one tee muxer, so the frames are encoded once and muxed N
+// times — listing several plain outputs would instead run the encoder once per
+// output, roughly tripling CPU for a 720p rung publishing HLS+CMAF+DASH.
+func buildOutputPlan(outputs []db.OutputSpec, wwwDir string, cfg streamSettings, spec db.VariantSpec) outputPlan {
+ plan := outputPlan{Playlists: map[string]string{}}
+ enabled := db.EnabledOutputs(outputs)
+ if len(enabled) == 0 {
+ // Never publish nothing: that would leave the stream unreachable.
+ enabled = []db.OutputSpec{{ID: "hls", Format: db.FormatHLS, Enabled: true}}
+ }
+ // The source rung is a stream copy from the downloader's MPEG-TS. Copying
+ // that into an fMP4 container needs two fixes that re-encoding would not:
+ // the AAC has to be converted from ADTS to ASC, and the H.264 codec tag
+ // carried from TS is rejected by the MP4 muxer. Both were found by running
+ // the real ffmpeg; see ffmpeg_integration_test.go.
+ copying := spec.IsSource()
+
+ type target struct {
+ format string
+ options []kv
+ url string
+ // fmp4 marks an output whose container is ISO-BMFF.
+ fmp4 bool
+ }
+ var targets []target
+
+ for _, o := range enabled {
+ segDur := o.SegmentDuration
+ if segDur <= 0 {
+ segDur = cfg.HLSTime
+ }
+ listSize := o.ListSize
+ if listSize <= 0 {
+ listSize = cfg.HLSListSize
+ }
+ switch o.Format {
+ case db.FormatHLS:
+ index := filepath.Join(wwwDir, "index.m3u8")
+ targets = append(targets, target{
+ format: "hls",
+ options: []kv{
+ {"hls_time", strconv.Itoa(segDur)},
+ {"hls_list_size", strconv.Itoa(listSize)},
+ {"hls_flags", hlsFlags},
+ {"hls_segment_type", "mpegts"},
+ {"hls_segment_filename", filepath.Join(wwwDir, "seg_%05d.ts")},
+ },
+ url: index,
+ })
+ plan.Playlists[db.FormatHLS] = index
+
+ case db.FormatCMAF:
+ dir := filepath.Join(wwwDir, "cmaf")
+ index := filepath.Join(dir, "index.m3u8")
+ targets = append(targets, target{
+ format: "hls",
+ fmp4: true,
+ options: []kv{
+ {"hls_time", strconv.Itoa(segDur)},
+ {"hls_list_size", strconv.Itoa(listSize)},
+ {"hls_flags", hlsFlags},
+ {"hls_segment_type", "fmp4"},
+ {"hls_fmp4_init_filename", "init.mp4"},
+ {"hls_segment_filename", filepath.Join(dir, "seg_%05d.m4s")},
+ },
+ url: index,
+ })
+ plan.Dirs = append(plan.Dirs, dir)
+ plan.Playlists[db.FormatCMAF] = index
+
+ case db.FormatDASH:
+ dir := filepath.Join(wwwDir, "dash")
+ index := filepath.Join(dir, "index.mpd")
+ targets = append(targets, target{
+ format: "dash",
+ fmp4: true,
+ options: []kv{
+ {"seg_duration", strconv.Itoa(segDur)},
+ {"window_size", strconv.Itoa(listSize)},
+ {"extra_window_size", "2"},
+ {"use_template", "1"},
+ {"use_timeline", "1"},
+ {"streaming", "1"},
+ },
+ url: index,
+ })
+ plan.Dirs = append(plan.Dirs, dir)
+ plan.Playlists[db.FormatDASH] = index
+
+ case db.FormatTS:
+ targets = append(targets, target{format: "mpegts", url: "pipe:1"})
+ plan.WantsTS = true
+ }
+ }
+
+ // An fMP4 output from a copied source needs an MP4-compatible codec tag.
+ // This is a stream option rather than a muxer option, so it applies to the
+ // whole output; it is harmless to the MPEG-TS legs, which ignore it.
+ var pre []string
+ needsFMP4Fixes := false
+ for _, t := range targets {
+ if t.fmp4 {
+ needsFMP4Fixes = true
+ break
+ }
+ }
+ if copying && needsFMP4Fixes {
+ pre = append(pre, "-tag:v", "avc1", "-tag:a", "mp4a")
+ }
+
+ if len(targets) == 1 {
+ t := targets[0]
+ args := append([]string{}, pre...)
+ // With one output there is no tee, so a bitstream filter is set the
+ // ordinary way.
+ if copying && t.fmp4 {
+ args = append(args, "-bsf:a", "aac_adtstoasc")
+ }
+ args = append(args, "-f", t.format)
+ for _, o := range t.options {
+ args = append(args, "-"+o.k, o.v)
+ }
+ plan.Args = append(args, t.url)
+ return plan
+ }
+
+ // Several outputs: one tee, one encode.
+ specs := make([]string, 0, len(targets))
+ for _, t := range targets {
+ opts := make([]string, 0, len(t.options)+3)
+ opts = append(opts, "f="+t.format)
+ // onfail=ignore on every leg is essential. Without it, a reader
+ // disconnecting from the progressive TS pipe, or a full disk under one
+ // output directory, tears down the whole ffmpeg process and takes the
+ // healthy outputs with it.
+ opts = append(opts, "onfail=ignore")
+ // The ADTS-to-ASC conversion has to be per-leg: applying it globally
+ // would also rewrite the audio going into the MPEG-TS outputs, which
+ // need ADTS.
+ if copying && t.fmp4 {
+ opts = append(opts, "bsfs/a=aac_adtstoasc")
+ }
+ for _, o := range t.options {
+ opts = append(opts, teeEscapeKey(o.k)+"="+teeEscapeValue(o.v))
+ }
+ specs = append(specs, "["+strings.Join(opts, ":")+"]"+teeEscapeURL(t.url))
+ }
+ plan.Args = append(pre, "-f", "tee", strings.Join(specs, "|"))
+ return plan
+}
+
+type kv struct{ k, v string }
+
+// teeEscapeKey escapes a tee option name. Names are fixed identifiers, so
+// this only guards against a stray separator reaching the parser.
+func teeEscapeKey(s string) string {
+ return strings.NewReplacer(
+ `\`, `\\`,
+ `:`, `\:`,
+ `|`, `\|`,
+ `[`, `\[`,
+ `]`, `\]`,
+ `=`, `\=`,
+ ).Replace(s)
+}
+
+// teeEscapeValue escapes a tee option value.
+//
+// This needs two layers at once, which is not obvious and was established by
+// testing against the real ffmpeg (see ffmpeg_integration_test.go): the value
+// is wrapped in single quotes AND its colons are backslash-escaped. Quoting
+// alone is not enough, and escaping alone is not enough.
+//
+// A Windows path is what makes it matter. Unescaped,
+// "hls_segment_filename=C:/data/seg.ts" is split at the drive letter, ffmpeg
+// rejects that slave, and under onfail=ignore the output silently never
+// appears — a failure mode that looks like "CMAF just doesn't work".
+func teeEscapeValue(s string) string {
+ // Forward slashes throughout: a backslash is itself an escape character
+ // here, so a Windows path written with them is a second problem.
+ s = filepath.ToSlash(s)
+ // A literal single quote cannot appear inside a single-quoted run: close
+ // the quote, emit an escaped one, reopen.
+ s = strings.ReplaceAll(s, `'`, `'\''`)
+ s = strings.ReplaceAll(s, `:`, `\:`)
+ return `'` + s + `'`
+}
+
+// teeEscapeURL escapes the destination URL of one tee output. The URL runs
+// from after "]" to the next unescaped "|", so only the separator and bracket
+// characters need escaping — a colon is safe here, and escaping it would
+// corrupt the path.
+func teeEscapeURL(s string) string {
+ s = filepath.ToSlash(s)
+ return strings.NewReplacer(
+ `|`, `\|`,
+ `[`, `\[`,
+ `]`, `\]`,
+ ).Replace(s)
+}
+
+// variantCodecArgs builds the encoder arguments for one rung. The source rung
+// is a stream copy; a scaled rung re-encodes; an audio-only rung drops video.
+func variantCodecArgs(v db.VariantSpec) []string {
+ if v.IsSource() {
+ return []string{"-map", "0", "-c", "copy"}
+ }
+ if v.AudioOnly {
+ abr := v.AudioBitrate
+ if abr == "" {
+ abr = "96k"
+ }
+ return []string{
+ "-map", "0:a:0?",
+ "-vn",
+ "-c:a", "aac",
+ "-b:a", abr,
+ "-ac", "2",
+ }
+ }
+ vbr := v.VideoBitrate
+ if vbr == "" {
+ vbr = "2800k"
+ }
+ abr := v.AudioBitrate
+ if abr == "" {
+ abr = "128k"
+ }
+ return []string{
+ "-map", "0:v:0",
+ "-map", "0:a:0?",
+ "-vf", fmt.Sprintf("scale=-2:%d", v.Height),
+ "-c:v", "libx264",
+ "-preset", "veryfast",
+ "-tune", "zerolatency",
+ "-b:v", vbr,
+ "-maxrate", vbr,
+ "-bufsize", doubleBitrate(vbr),
+ "-g", "48",
+ "-keyint_min", "48",
+ "-sc_threshold", "0",
+ "-c:a", "aac",
+ "-b:a", abr,
+ "-ac", "2",
+ }
+}
+
+// inputArgs are the demuxer options for reading the growing TS the downloader
+// is writing. The large probe is deliberate: the first bytes of a pipe-mux
+// often lack a clean audio configuration.
+func inputArgs(tsPath string) []string {
+ return []string{
+ "-hide_banner", "-loglevel", "warning", "-y",
+ "-follow", "1",
+ "-analyzeduration", "20M",
+ "-probesize", "10M",
+ "-fflags", "+genpts",
+ "-i", tsPath,
+ }
+}
diff --git a/apps/streamd/internal/supervisor/outputs_test.go b/apps/streamd/internal/supervisor/outputs_test.go
new file mode 100644
index 0000000..c4e6a92
--- /dev/null
+++ b/apps/streamd/internal/supervisor/outputs_test.go
@@ -0,0 +1,389 @@
+package supervisor
+
+import (
+ "strings"
+ "testing"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+// quote and backslash as values, so the test source stays readable where it
+// asserts on ffmpeg's escaping.
+const (
+ q = "'"
+ bs = `\`
+)
+
+func testCfg() streamSettings {
+ return streamSettings{HLSTime: defaultHLSTime, HLSListSize: defaultHLSListSize}
+}
+
+func only(format string) []db.OutputSpec {
+ return []db.OutputSpec{{ID: "x", Format: format, Enabled: true}}
+}
+
+func sourceSpecForTest() db.VariantSpec {
+ return db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true, Height: 0}
+}
+
+func normalize(s string) string { return strings.ReplaceAll(s, `\`, "/") }
+
+// findFormat returns the muxer named by -f, without assuming a position: a
+// stream-copied rung publishing fMP4 carries -tag options first.
+func findFormat(args []string) string {
+ for i := 0; i < len(args)-1; i++ {
+ if args[i] == "-f" {
+ return args[i+1]
+ }
+ }
+ return ""
+}
+
+// teeSpec returns the single tee specification argument.
+func teeSpec(t *testing.T, args []string) string {
+ t.Helper()
+ for i := 0; i < len(args)-1; i++ {
+ if args[i] == "-f" && args[i+1] == "tee" {
+ if i+2 >= len(args) {
+ t.Fatalf("-f tee with no spec: %v", args)
+ }
+ return args[i+2]
+ }
+ }
+ t.Fatalf("no tee muxer in %v", args)
+ return ""
+}
+
+// With a single mpegts HLS output the command must stay the plain form
+// streamd has always run. media.go is the least-exercised code in the project,
+// so the common path deliberately does not change shape.
+func TestSingleHLSOutputMatchesTheOriginalCommand(t *testing.T) {
+ plan := buildOutputPlan(only(db.FormatHLS), "/data/www/news", testCfg(), sourceSpecForTest())
+ want := []string{
+ "-f", "hls",
+ "-hls_time", "4",
+ "-hls_list_size", "15",
+ "-hls_flags", "delete_segments+append_list+omit_endlist+independent_segments",
+ "-hls_segment_type", "mpegts",
+ "-hls_segment_filename", "/data/www/news/seg_%05d.ts",
+ "/data/www/news/index.m3u8",
+ }
+ if len(plan.Args) != len(want) {
+ t.Fatalf("arg count %d, want %d\ngot: %v\nwant: %v", len(plan.Args), len(want), plan.Args, want)
+ }
+ for i := range want {
+ // Separators are normalised, since filepath.Join is platform-specific.
+ if normalize(plan.Args[i]) != normalize(want[i]) {
+ t.Errorf("arg %d = %q, want %q", i, plan.Args[i], want[i])
+ }
+ }
+ if plan.WantsTS {
+ t.Error("an HLS-only plan must not claim stdout")
+ }
+ for _, a := range plan.Args {
+ if a == "tee" {
+ t.Error("a single output must not use the tee muxer")
+ }
+ }
+}
+
+func TestSingleOutputPerFormat(t *testing.T) {
+ cases := []struct {
+ format string
+ wantMux string
+ wantPath string
+ }{
+ {db.FormatHLS, "hls", "/data/www/news/index.m3u8"},
+ {db.FormatCMAF, "hls", "/data/www/news/cmaf/index.m3u8"},
+ {db.FormatDASH, "dash", "/data/www/news/dash/index.mpd"},
+ {db.FormatTS, "mpegts", "pipe:1"},
+ }
+ for _, c := range cases {
+ plan := buildOutputPlan(only(c.format), "/data/www/news", testCfg(), sourceSpecForTest())
+ if mux := findFormat(plan.Args); mux != c.wantMux {
+ t.Errorf("%s: muxer = %q, want %s (args %v)", c.format, mux, c.wantMux, plan.Args)
+ }
+ if last := normalize(plan.Args[len(plan.Args)-1]); last != c.wantPath {
+ t.Errorf("%s: output = %q, want %q", c.format, last, c.wantPath)
+ }
+ if (c.format == db.FormatTS) != plan.WantsTS {
+ t.Errorf("%s: WantsTS = %v", c.format, plan.WantsTS)
+ }
+ }
+}
+
+// The headline requirement: several outputs must share ONE encode via tee. If
+// this regresses into several plain outputs, ffmpeg runs the encoder once per
+// format and CPU triples for a transcoded rung.
+func TestMultipleOutputsUseOneTee(t *testing.T) {
+ outputs := []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ {ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
+ {ID: "dash", Format: db.FormatDASH, Enabled: true},
+ {ID: "ts", Format: db.FormatTS, Enabled: true},
+ }
+ plan := buildOutputPlan(outputs, "/data/www/news", testCfg(), sourceSpecForTest())
+ spec := teeSpec(t, plan.Args)
+
+ fCount := 0
+ for _, a := range plan.Args {
+ if a == "-f" {
+ fCount++
+ }
+ }
+ if fCount != 1 {
+ t.Errorf("want a single -f (the tee), got %d: %v", fCount, plan.Args)
+ }
+
+ legs := strings.Split(spec, "|")
+ if len(legs) != 4 {
+ t.Fatalf("want 4 tee legs, got %d: %s", len(legs), spec)
+ }
+ // Every leg must carry onfail=ignore: without it one dead output (a
+ // disconnected TS reader, a full disk) kills the whole process and takes
+ // the healthy outputs with it.
+ for i, leg := range legs {
+ if !strings.Contains(leg, "onfail=ignore") {
+ t.Errorf("leg %d has no onfail=ignore: %s", i, leg)
+ }
+ if !strings.HasPrefix(leg, "[") || !strings.Contains(leg, "]") {
+ t.Errorf("leg %d is not a bracketed tee spec: %s", i, leg)
+ }
+ }
+ if n := strings.Count(spec, "f=hls"); n != 2 {
+ t.Errorf("want two hls legs (mpegts + fmp4), got %d", n)
+ }
+ if !strings.Contains(spec, "f=dash") || !strings.Contains(spec, "f=mpegts") {
+ t.Errorf("missing a format in the tee spec: %s", spec)
+ }
+ if !plan.WantsTS {
+ t.Error("a plan including the TS output must claim stdout")
+ }
+ // CMAF and DASH write into subdirectories ffmpeg will not create.
+ if len(plan.Dirs) != 2 {
+ t.Errorf("want 2 directories to pre-create, got %v", plan.Dirs)
+ }
+}
+
+// Windows paths contain a colon, which is also the tee option separator.
+// Unescaped, hls_segment_filename=C:/... is split at the drive letter, that
+// slave is rejected, and under onfail=ignore the output silently never
+// appears.
+func TestTeeEscapesColonsInPaths(t *testing.T) {
+ outputs := []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ {ID: "dash", Format: db.FormatDASH, Enabled: true},
+ }
+ plan := buildOutputPlan(outputs, `C:\data\www\city news`, testCfg(), sourceSpecForTest())
+ spec := teeSpec(t, plan.Args)
+
+ if strings.Contains(spec, "hls_segment_filename=C:") {
+ t.Errorf("drive-letter colon is unescaped in the option value: %s", spec)
+ }
+ // Real ffmpeg needs BOTH: the value quoted and its colon escaped.
+ if !strings.Contains(spec, "hls_segment_filename="+q+"C"+bs+":") {
+ t.Errorf("want the value quoted with its colon escaped, got: %s", spec)
+ }
+ // A space is fine: this is one argv element, not a shell word.
+ if !strings.Contains(spec, "city news") {
+ t.Errorf("path with a space was mangled: %s", spec)
+ }
+ // The URL after ] keeps its colon, which is not special there.
+ if !strings.Contains(spec, "]C:/data/www/city news/index.m3u8") {
+ t.Errorf("output URL should keep its drive colon: %s", spec)
+ }
+}
+
+func TestTeeEscapeKey(t *testing.T) {
+ for in, want := range map[string]string{
+ "plain": "plain",
+ "a:b": "a" + bs + ":b",
+ "a|b": "a" + bs + "|b",
+ "a[b]": "a" + bs + "[b" + bs + "]",
+ "k=v": "k" + bs + "=v",
+ "bsfs/a": "bsfs/a",
+ } {
+ if got := teeEscapeKey(in); got != want {
+ t.Errorf("teeEscapeKey(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestTeeEscapeValue(t *testing.T) {
+ // Both layers, in this order: quote the whole value, escape its colons.
+ // Established against the real ffmpeg; neither alone is accepted.
+ if got := teeEscapeValue("C:/data/seg_%05d.ts"); got != q+"C"+bs+":/data/seg_%05d.ts"+q {
+ t.Errorf("got %q", got)
+ }
+ // Backslashes become forward slashes rather than being doubled, because a
+ // backslash is itself an escape character in a tee spec.
+ if got := teeEscapeValue(`C:\data\x.ts`); got != q+"C"+bs+":/data/x.ts"+q {
+ t.Errorf("got %q", got)
+ }
+ // A space needs nothing special once the value is quoted.
+ if got := teeEscapeValue("/srv/city news/seg.ts"); got != q+"/srv/city news/seg.ts"+q {
+ t.Errorf("got %q", got)
+ }
+ // A plain value is quoted too, which is harmless and keeps one rule.
+ if got := teeEscapeValue("mpegts"); got != q+"mpegts"+q {
+ t.Errorf("got %q", got)
+ }
+ // A literal quote must not end the quoted run.
+ if got := teeEscapeValue("/srv/o" + q + "brien/seg.ts"); !strings.Contains(got, q+bs+q) {
+ t.Errorf("apostrophe was not escaped: %q", got)
+ }
+}
+
+func TestTeeEscapeURL(t *testing.T) {
+ // Backslashes become forward slashes, and only the separator characters
+ // are escaped — a colon must survive untouched in a URL.
+ if got := teeEscapeURL(`C:\data\x.m3u8`); got != "C:/data/x.m3u8" {
+ t.Errorf("got %q", got)
+ }
+ if got := teeEscapeURL("a|b"); got != "a"+bs+"|b" {
+ t.Errorf("pipe must be escaped in a URL, got %q", got)
+ }
+ if got := teeEscapeURL("pipe:1"); got != "pipe:1" {
+ t.Errorf("pipe:1 must pass through unchanged, got %q", got)
+ }
+}
+
+// A copied source rung into an fMP4 container needs the ADTS-to-ASC filter on
+// that leg only, plus an MP4 codec tag. A re-encoded rung needs neither,
+// because ffmpeg then produces the right bitstream for each muxer itself.
+func TestFMP4CopyFixesOnlyWhenCopying(t *testing.T) {
+ outputs := []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ {ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
+ }
+ src := buildOutputPlan(outputs, "/w", testCfg(), sourceSpecForTest())
+ if !strings.Contains(strings.Join(src.Args, " "), "-tag:v avc1") {
+ t.Error("a copied rung publishing fMP4 needs an MP4 codec tag")
+ }
+ for _, leg := range strings.Split(teeSpec(t, src.Args), "|") {
+ isFMP4 := strings.Contains(leg, "fmp4")
+ hasBSF := strings.Contains(leg, "aac_adtstoasc")
+ if isFMP4 != hasBSF {
+ t.Errorf("aac_adtstoasc belongs on the fMP4 leg and only there: %s", leg)
+ }
+ }
+
+ hd := db.VariantSpec{ID: "hd", Enabled: true, Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k"}
+ enc := strings.Join(buildOutputPlan(outputs, "/w", testCfg(), hd).Args, " ")
+ if strings.Contains(enc, "-tag:v avc1") {
+ t.Error("a re-encoded rung should not need a codec tag override")
+ }
+ if strings.Contains(enc, "aac_adtstoasc") {
+ t.Error("a re-encoded rung should not need the ADTS filter")
+ }
+}
+
+// A single fMP4 output has no tee, so the bitstream filter is set the
+// ordinary way.
+func TestSingleFMP4OutputUsesPlainBSF(t *testing.T) {
+ plan := buildOutputPlan(only(db.FormatCMAF), "/w", testCfg(), sourceSpecForTest())
+ joined := strings.Join(plan.Args, " ")
+ if !strings.Contains(joined, "-bsf:a aac_adtstoasc") {
+ t.Errorf("want a plain -bsf:a, got %s", joined)
+ }
+ if strings.Contains(joined, "bsfs/a") {
+ t.Errorf("tee syntax leaked into a single-output command: %s", joined)
+ }
+}
+
+// Publishing nothing would leave the stream unreachable.
+func TestNoEnabledOutputsFallsBackToHLS(t *testing.T) {
+ plan := buildOutputPlan([]db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: false},
+ }, "/data/www/news", testCfg(), sourceSpecForTest())
+ if findFormat(plan.Args) != "hls" {
+ t.Errorf("want an HLS fallback, got %v", plan.Args)
+ }
+}
+
+func TestPerOutputSegmentOverrides(t *testing.T) {
+ outputs := []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true, SegmentDuration: 2, ListSize: 6},
+ }
+ plan := buildOutputPlan(outputs, "/data/www/news", testCfg(), sourceSpecForTest())
+ joined := strings.Join(plan.Args, " ")
+ if !strings.Contains(joined, "-hls_time 2") || !strings.Contains(joined, "-hls_list_size 6") {
+ t.Errorf("per-output overrides were ignored: %s", joined)
+ }
+ // An output that does not override inherits the stream's settings.
+ cfg := testCfg()
+ cfg.HLSTime, cfg.HLSListSize = 8, 40
+ plan = buildOutputPlan(only(db.FormatHLS), "/data/www/news", cfg, sourceSpecForTest())
+ joined = strings.Join(plan.Args, " ")
+ if !strings.Contains(joined, "-hls_time 8") || !strings.Contains(joined, "-hls_list_size 40") {
+ t.Errorf("stream settings were not inherited: %s", joined)
+ }
+}
+
+func TestVariantCodecArgs(t *testing.T) {
+ // The source rung is a pass-through copy: no encoder at all.
+ src := strings.Join(variantCodecArgs(sourceSpecForTest()), " ")
+ if !strings.Contains(src, "-c copy") {
+ t.Errorf("source rung must stream-copy, got %q", src)
+ }
+ if strings.Contains(src, "libx264") {
+ t.Error("source rung must not re-encode")
+ }
+
+ // A scaled rung encodes video and audio.
+ hd := strings.Join(variantCodecArgs(db.VariantSpec{
+ ID: "hd", Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k",
+ }), " ")
+ for _, want := range []string{"scale=-2:720", "libx264", "-b:v 2800k", "-b:a 128k", "-bufsize 5600k"} {
+ if !strings.Contains(hd, want) {
+ t.Errorf("scaled rung missing %q in %q", want, hd)
+ }
+ }
+
+ // An audio-only rung drops video entirely.
+ au := strings.Join(variantCodecArgs(db.VariantSpec{
+ ID: "audio", AudioOnly: true, AudioBitrate: "96k",
+ }), " ")
+ if !strings.Contains(au, "-vn") {
+ t.Errorf("audio rung must pass -vn, got %q", au)
+ }
+ if strings.Contains(au, "libx264") || strings.Contains(au, "scale=") {
+ t.Errorf("audio rung must not touch video, got %q", au)
+ }
+ if !strings.Contains(au, "-b:a 96k") {
+ t.Errorf("audio rung missing its bitrate, got %q", au)
+ }
+}
+
+func TestDoubleBitrate(t *testing.T) {
+ for in, want := range map[string]string{
+ "2800k": "5600k",
+ "1200k": "2400k",
+ "5M": "10000k",
+ "": "5600k",
+ "junk": "5600k",
+ } {
+ if got := doubleBitrate(in); got != want {
+ t.Errorf("doubleBitrate(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestPlaylistsRecorded(t *testing.T) {
+ outputs := []db.OutputSpec{
+ {ID: "hls", Format: db.FormatHLS, Enabled: true},
+ {ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
+ {ID: "dash", Format: db.FormatDASH, Enabled: true},
+ {ID: "ts", Format: db.FormatTS, Enabled: true},
+ }
+ plan := buildOutputPlan(outputs, "/w", testCfg(), sourceSpecForTest())
+ for _, f := range []string{db.FormatHLS, db.FormatCMAF, db.FormatDASH} {
+ if plan.Playlists[f] == "" {
+ t.Errorf("no playlist recorded for %s", f)
+ }
+ }
+ // The progressive TS has no file on disk, so no playlist entry.
+ if plan.Playlists[db.FormatTS] != "" {
+ t.Error("the TS output should not record a playlist file")
+ }
+}
diff --git a/apps/streamd/internal/supervisor/proc_unix.go b/apps/streamd/internal/supervisor/proc_unix.go
index 266175f..832f76d 100644
--- a/apps/streamd/internal/supervisor/proc_unix.go
+++ b/apps/streamd/internal/supervisor/proc_unix.go
@@ -3,13 +3,27 @@
package supervisor
import (
+ "io"
"os"
"os/exec"
+ "strings"
"syscall"
)
func hideWindow(cmd *exec.Cmd) {}
+func killProcessTree(cmd *exec.Cmd) error {
+ if cmd == nil || cmd.Process == nil {
+ return nil
+ }
+ pid := cmd.Process.Pid
+ // Negative PID signals the process group (script PTY wrapper + NRE).
+ if err := syscall.Kill(-pid, syscall.SIGKILL); err == nil {
+ return nil
+ }
+ return cmd.Process.Kill()
+}
+
func processDead(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {
@@ -18,3 +32,63 @@ func processDead(pid int) bool {
err = p.Signal(syscall.Signal(0))
return err != nil
}
+
+// startNRELogged starts NRE under a PTY so Spectre.Console sees a real terminal.
+// Plain file/pipe redirects make N_m3u8DL-RE force ANSI UI with WindowWidth 0,
+// which crashes ProgressRefreshThread (ArgumentException/RemoveRange).
+//
+// Uses util-linux `script` when available (PTY + typescript log). Falls back to
+// attaching logFile as Stdout/Stderr. keepLogFD is false when script took over
+// the log path (caller must not Close logFile again).
+func startNRELogged(cmd *exec.Cmd, logFile *os.File) (pty io.Closer, keepLogFD bool, err error) {
+ scriptPath, err := exec.LookPath("script")
+ if err != nil {
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+ if err := cmd.Start(); err != nil {
+ return nil, true, err
+ }
+ return nopCloser{}, true, nil
+ }
+
+ logPath := logFile.Name()
+ _ = logFile.Sync()
+ _ = logFile.Close()
+
+ inner := shellJoin(append([]string{cmd.Path}, cmd.Args[1:]...)...)
+ // -q quiet header, -a append (keep prior runs), -f flush so log tails live.
+ wrapped := exec.Command(scriptPath, "-q", "-a", "-f", "-c", inner, logPath)
+ wrapped.Env = cmd.Env
+ wrapped.Dir = cmd.Dir
+ if cmd.SysProcAttr != nil {
+ wrapped.SysProcAttr = cmd.SysProcAttr
+ } else {
+ wrapped.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ // Own process group so Stop can signal the whole tree (script + NRE).
+ wrapped.SysProcAttr.Setpgid = true
+ *cmd = *wrapped
+ if err := cmd.Start(); err != nil {
+ return nil, false, err
+ }
+ return nopCloser{}, false, nil
+}
+
+func shellJoin(argv ...string) string {
+ parts := make([]string, len(argv))
+ for i, a := range argv {
+ parts[i] = shellQuote(a)
+ }
+ return strings.Join(parts, " ")
+}
+
+func shellQuote(s string) string {
+ if s == "" {
+ return "''"
+ }
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+type nopCloser struct{}
+
+func (nopCloser) Close() error { return nil }
diff --git a/apps/streamd/internal/supervisor/proc_windows.go b/apps/streamd/internal/supervisor/proc_windows.go
index 4de3aff..bc95f5a 100644
--- a/apps/streamd/internal/supervisor/proc_windows.go
+++ b/apps/streamd/internal/supervisor/proc_windows.go
@@ -3,8 +3,10 @@
package supervisor
import (
+ "io"
"os"
"os/exec"
+ "strconv"
"syscall"
)
@@ -15,6 +17,29 @@ func hideWindow(cmd *exec.Cmd) {
}
}
+func killProcessTree(cmd *exec.Cmd) error {
+ if cmd == nil || cmd.Process == nil {
+ return nil
+ }
+ pid := cmd.Process.Pid
+ return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
+}
+
+// startNRELogged attaches logFile as Stdout/Stderr. Windows CREATE_NO_WINDOW
+// avoids the Spectre pipe-width crash that hits Linux daemons.
+func startNRELogged(cmd *exec.Cmd, logFile *os.File) (io.Closer, bool, error) {
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+ if err := cmd.Start(); err != nil {
+ return nil, true, err
+ }
+ return nopCloser{}, true, nil
+}
+
+type nopCloser struct{}
+
+func (nopCloser) Close() error { return nil }
+
func processDead(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {
diff --git a/apps/streamd/internal/supervisor/stub.go b/apps/streamd/internal/supervisor/stub.go
index a847894..609c0ee 100644
--- a/apps/streamd/internal/supervisor/stub.go
+++ b/apps/streamd/internal/supervisor/stub.go
@@ -5,7 +5,7 @@ import (
"sync"
"time"
- "drmdecryption/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/db"
)
// Stub marks streams as starting/stopped without spawning media workers.
@@ -27,13 +27,13 @@ func (s *Stub) Start(id int64) error {
if err != nil {
return err
}
- if st.MPD == "" || st.Key == "" {
+ if st.MPD == "" {
_, err = s.Store.DB.Exec(`
INSERT INTO stream_runtime(stream_id,health,play_path,last_error,updated_at)
VALUES(?,?,?,?,?)
ON CONFLICT(stream_id) DO UPDATE SET health=excluded.health, last_error=excluded.last_error, updated_at=excluded.updated_at`,
- id, "down", "/hls/"+st.Name+"/index.m3u8", "missing mpd/key - capture required", time.Now().UTC().Format(time.RFC3339))
- return err
+ id, "down", "/hls/"+st.Name+"/index.m3u8", "missing mpd", time.Now().UTC().Format(time.RFC3339))
+ return fmt.Errorf("missing mpd")
}
pid := 10000 + int(id)
s.pids[id] = pid
diff --git a/apps/streamd/internal/supervisor/variants.go b/apps/streamd/internal/supervisor/variants.go
new file mode 100644
index 0000000..ebf925d
--- /dev/null
+++ b/apps/streamd/internal/supervisor/variants.go
@@ -0,0 +1,330 @@
+package supervisor
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/logfile"
+)
+
+type variantProc struct {
+ spec db.VariantSpec
+ wwwDir string
+ index string
+ cmd *exec.Cmd
+ outLog *logfile.Writer
+ errLog *logfile.Writer
+ dead bool
+}
+
+func (m *Media) startVariantPackagers(sp *streamProc, specs []db.VariantSpec) {
+ scaled := db.ScaledVariants(specs)
+ if len(scaled) == 0 {
+ return
+ }
+ m.mu.Lock()
+ cur, ok := m.procs[sp.id]
+ if !ok || cur.stopping {
+ m.mu.Unlock()
+ return
+ }
+ // Drop any previous variant workers before spawning new ones.
+ old := cur.variants
+ cur.variants = nil
+ m.mu.Unlock()
+ for _, vp := range old {
+ m.stopVariant(vp)
+ }
+
+ var started []*variantProc
+ for _, spec := range scaled {
+ vp, err := m.spawnVariantFFmpeg(sp, spec)
+ if err != nil {
+ m.Log.Error("variant packager failed to start",
+ "stream", sp.name, "variant", spec.ID, "err", err)
+ m.Store.Eventf(sp.id, db.EventVariantDown, db.SevError,
+ "variant %s failed to start: %v", spec.ID, err)
+ continue
+ }
+ started = append(started, vp)
+ m.Log.Info("variant packager started", "stream", sp.name, "variant", spec.ID,
+ "height", spec.Height, "audio_only", spec.AudioOnly,
+ "pid", vp.cmd.Process.Pid, "index", vp.index)
+ }
+
+ m.mu.Lock()
+ if cur, ok := m.procs[sp.id]; ok && !cur.stopping {
+ cur.variants = started
+ } else {
+ m.mu.Unlock()
+ for _, vp := range started {
+ m.stopVariant(vp)
+ }
+ return
+ }
+ m.mu.Unlock()
+}
+
+func (m *Media) spawnVariantFFmpeg(sp *streamProc, spec db.VariantSpec) (*variantProc, error) {
+ dirName := db.VariantDir(sp.name, spec.ID, spec.Height, spec.AudioOnly)
+ wwwDir := filepath.Join(m.DataDir, "www", dirName)
+ _ = os.RemoveAll(wwwDir)
+ if err := os.MkdirAll(wwwDir, 0o755); err != nil {
+ return nil, err
+ }
+
+ plan := buildOutputPlan(sp.outputSpecs, wwwDir, sp.cfg, spec)
+ for _, d := range plan.Dirs {
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ return nil, err
+ }
+ }
+
+ // One encoder, N muxers: the codec args appear once and the tee fans the
+ // encoded frames out. Listing several plain outputs instead would run
+ // libx264 once per format.
+ args := append(inputArgs(sp.tsPath), variantCodecArgs(spec)...)
+ args = append(args, plan.Args...)
+
+ errLog, err := logfile.OpenWithBanner(
+ filepath.Join(m.logsDir(), dirName+"-ffmpeg.err.log"),
+ logfile.DefaultMaxBytes, logfile.DefaultGenerations, "ffmpeg")
+ if err != nil {
+ return nil, err
+ }
+
+ ffCmd := exec.Command(m.FFmpeg, args...)
+ ffCmd.Stderr = errLog
+
+ var outLog *logfile.Writer
+ if plan.WantsTS {
+ // stdout is this variant's live TS, fanned out to its own ring.
+ ring := m.Fanout.Create(dirName)
+ pipe, err := ffCmd.StdoutPipe()
+ if err != nil {
+ _ = errLog.Close()
+ return nil, err
+ }
+ go func() {
+ _, _ = io.Copy(ring, pipe)
+ _ = ring.Close()
+ }()
+ } else {
+ outLog, err = logfile.Open(
+ filepath.Join(m.logsDir(), dirName+"-ffmpeg.out.log"),
+ logfile.DefaultMaxBytes, logfile.DefaultGenerations)
+ if err != nil {
+ _ = errLog.Close()
+ return nil, err
+ }
+ ffCmd.Stdout = outLog
+ }
+
+ hideWindow(ffCmd)
+ if err := ffCmd.Start(); err != nil {
+ _ = errLog.Close()
+ if outLog != nil {
+ _ = outLog.Close()
+ }
+ return nil, err
+ }
+
+ vp := &variantProc{
+ spec: spec,
+ wwwDir: wwwDir,
+ index: filepath.Join(wwwDir, "index.m3u8"),
+ cmd: ffCmd,
+ outLog: outLog,
+ errLog: errLog,
+ }
+ go func() {
+ _ = ffCmd.Wait()
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if cur, ok := m.procs[sp.id]; ok {
+ for _, v := range cur.variants {
+ if v == vp {
+ v.dead = true
+ }
+ }
+ }
+ }()
+ return vp, nil
+}
+
+// doubleBitrate is the -bufsize that pairs with a -maxrate.
+func doubleBitrate(b string) string {
+ n := db.BitrateBps(b)
+ if n <= 0 {
+ return "5600k"
+ }
+ return fmt.Sprintf("%dk", n*2/1000)
+}
+
+func (m *Media) stopVariant(vp *variantProc) {
+ if vp == nil {
+ return
+ }
+ if vp.cmd != nil && vp.cmd.Process != nil {
+ _ = killProcess(vp.cmd)
+ }
+ for _, w := range []*logfile.Writer{vp.outLog, vp.errLog} {
+ if w != nil {
+ _ = w.Close()
+ }
+ }
+}
+
+func (m *Media) stopAllVariants(sp *streamProc) {
+ m.mu.Lock()
+ list := sp.variants
+ sp.variants = nil
+ m.mu.Unlock()
+ for _, vp := range list {
+ m.stopVariant(vp)
+ }
+}
+
+func (m *Media) restartDeadVariants(sp *streamProc) {
+ m.mu.Lock()
+ cur, ok := m.procs[sp.id]
+ if !ok || cur.stopping {
+ m.mu.Unlock()
+ return
+ }
+ var dead []*variantProc
+ var alive []*variantProc
+ for _, vp := range cur.variants {
+ if vp.dead {
+ dead = append(dead, vp)
+ } else {
+ alive = append(alive, vp)
+ }
+ }
+ cur.variants = alive
+ m.mu.Unlock()
+
+ for _, vp := range dead {
+ m.stopVariant(vp)
+ m.Store.Eventf(sp.id, db.EventVariantDown, db.SevWarn,
+ "variant %s exited; restarting it", vp.spec.ID)
+ fresh, err := m.spawnVariantFFmpeg(sp, vp.spec)
+ if err != nil {
+ m.Log.Error("variant restart failed", "stream", sp.name, "variant", vp.spec.ID, "err", err)
+ continue
+ }
+ m.mu.Lock()
+ if cur, ok := m.procs[sp.id]; ok && !cur.stopping {
+ cur.variants = append(cur.variants, fresh)
+ } else {
+ m.mu.Unlock()
+ m.stopVariant(fresh)
+ return
+ }
+ m.mu.Unlock()
+ m.Log.Info("variant restarted", "stream", sp.name, "variant", vp.spec.ID)
+ m.Store.Eventf(sp.id, db.EventVariantUp, db.SevInfo, "variant %s back up", vp.spec.ID)
+ }
+}
+
+// writeMasterPlaylist publishes the ABR master listing every enabled rung.
+//
+// streamd writes this itself rather than asking ffmpeg to: each rung is a
+// separate process writing its own playlist, so nothing but the supervisor
+// knows the whole ladder. Without a master, the rung playlists are independent
+// URLs and no player can switch between them.
+func (m *Media) writeMasterPlaylist(sp *streamProc) {
+ enabled := db.EnabledVariants(sp.variantSpecs)
+ // With one rung there is nothing to switch between.
+ if len(enabled) < 2 {
+ return
+ }
+ // Only meaningful when an HLS-family output is actually published.
+ hls := false
+ for _, o := range db.EnabledOutputs(sp.outputSpecs) {
+ if o.Format == db.FormatHLS || o.Format == db.FormatCMAF {
+ hls = true
+ break
+ }
+ }
+ if !hls {
+ return
+ }
+
+ bw := make(map[string]int, len(enabled))
+ for _, v := range enabled {
+ bw[v.ID] = m.variantBandwidth(sp, v)
+ }
+ // Highest bandwidth first is conventional, and gives a player a sensible
+ // default before it has measured the connection.
+ sort.SliceStable(enabled, func(i, j int) bool {
+ return bw[enabled[i].ID] > bw[enabled[j].ID]
+ })
+
+ var b strings.Builder
+ b.WriteString("#EXTM3U\n#EXT-X-VERSION:3\n")
+ b.WriteString("## generated by streamd - do not edit\n")
+ for _, v := range enabled {
+ dir := db.VariantDir(sp.name, v.ID, v.Height, v.AudioOnly)
+ // Relative to the master's own directory, so the playlist keeps
+ // working behind whatever path prefix a reverse proxy adds.
+ rel := "index.m3u8"
+ if dir != sp.name {
+ rel = "../" + dir + "/index.m3u8"
+ }
+ switch {
+ case v.AudioOnly:
+ fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d,CODECS=\"mp4a.40.2\"\n%s\n", bw[v.ID], rel)
+ case v.Height > 0:
+ fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d,RESOLUTION=%dx%d\n%s\n",
+ bw[v.ID], db.VariantWidth(v.Height), v.Height, rel)
+ default:
+ // The source rung's real resolution is whatever the origin sends,
+ // so advertise it by bandwidth alone rather than by a guess.
+ fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d\n%s\n", bw[v.ID], rel)
+ }
+ }
+
+ path := filepath.Join(sp.wwwDir, "master.m3u8")
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, []byte(b.String()), 0o644); err != nil {
+ m.Log.Error("write master playlist", "stream", sp.name, "err", err)
+ return
+ }
+ // Rename so a player never reads a half-written master.
+ if err := os.Rename(tmp, path); err != nil {
+ _ = os.Remove(tmp)
+ m.Log.Error("publish master playlist", "stream", sp.name, "err", err)
+ return
+ }
+ m.Log.Info("master playlist published", "stream", sp.name, "rungs", len(enabled))
+}
+
+// variantBandwidth estimates a rung's peak bitrate for the master playlist.
+// A scaled rung is capped by its configured bitrates; the source rung has none,
+// so the measured value is used with a conservative estimate standing in until
+// the stream has actually run.
+func (m *Media) variantBandwidth(sp *streamProc, v db.VariantSpec) int {
+ if v.AudioOnly {
+ if bps := db.BitrateBps(v.AudioBitrate); bps > 0 {
+ return bps
+ }
+ return 96000
+ }
+ if v.Height > 0 {
+ if bps := db.BitrateBps(v.VideoBitrate) + db.BitrateBps(v.AudioBitrate); bps > 0 {
+ return bps
+ }
+ return 2800000
+ }
+ if st, err := m.Store.GetStream(sp.id); err == nil && st.BitrateMbps > 0.1 {
+ return int(st.BitrateMbps * 1e6)
+ }
+ return 6000000
+}
diff --git a/apps/streamd/internal/tsfanout/tsfanout.go b/apps/streamd/internal/tsfanout/tsfanout.go
new file mode 100644
index 0000000..468cd2e
--- /dev/null
+++ b/apps/streamd/internal/tsfanout/tsfanout.go
@@ -0,0 +1,333 @@
+// Package tsfanout serves one live MPEG-TS pipe to many HTTP clients.
+//
+// The packager writes a single progressive mpegts stream to its stdout; this
+// package buffers the most recent few seconds of it and hands each client a
+// copy from a decodable starting point. The cost is one encoder regardless of
+// how many people are watching, rather than an ffmpeg per viewer.
+package tsfanout
+
+import (
+ "errors"
+ "io"
+ "sync"
+)
+
+// TS constants. An MPEG-TS stream is a continuous grid of 188-byte packets,
+// each starting with the sync byte 0x47.
+const (
+ packetSize = 188
+ syncByte = 0x47
+ // pidPAT is the Program Association Table. A client that starts here
+ // learns the stream's structure and can begin decoding; starting at an
+ // arbitrary byte produces garbage.
+ pidPAT = 0
+)
+
+// DefaultBufferBytes is a few seconds of a typical broadcast bitrate.
+const DefaultBufferBytes = 8 << 20
+
+// ErrLagged is returned to a client that fell so far behind that the bytes it
+// still needed have been overwritten. Such a client is dropped rather than
+// allowed to hold the buffer hostage or grow memory.
+var ErrLagged = errors.New("client fell behind the live buffer")
+
+// ErrClosed is returned once the source has ended.
+var ErrClosed = errors.New("stream closed")
+
+// Ring is a fixed-size circular buffer of the live stream, with absolute byte
+// offsets so each reader can track its own position.
+type Ring struct {
+ mu sync.Mutex
+ cond *sync.Cond
+
+ buf []byte
+ // written is the total number of bytes ever written, i.e. the absolute
+ // offset just past the newest byte.
+ written int64
+ closed bool
+
+ // joinAt is the absolute offset of the most recent PAT packet, which is
+ // where a new client should start.
+ joinAt int64
+ // aligned tracks whether we have locked onto the 188-byte packet grid,
+ // and carry holds a partial trailing packet between writes.
+ aligned bool
+ carry []byte
+ // carryAt is the absolute offset of carry[0].
+ carryAt int64
+
+ readers int
+}
+
+func New(size int) *Ring {
+ if size < 4*packetSize {
+ size = DefaultBufferBytes
+ }
+ // Whole packets keep the arithmetic honest.
+ size -= size % packetSize
+ r := &Ring{buf: make([]byte, size)}
+ r.cond = sync.NewCond(&r.mu)
+ return r
+}
+
+// Write implements io.Writer and is wired to the packager's stdout.
+func (r *Ring) Write(p []byte) (int, error) {
+ if len(p) == 0 {
+ return 0, nil
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.closed {
+ return 0, ErrClosed
+ }
+ total := len(p)
+ r.scanLocked(p)
+ for len(p) > 0 {
+ off := int(r.written % int64(len(r.buf)))
+ n := copy(r.buf[off:], p)
+ r.written += int64(n)
+ p = p[n:]
+ }
+ r.cond.Broadcast()
+ return total, nil
+}
+
+// scanLocked walks the incoming bytes on the packet grid and records where the
+// newest PAT begins. It keeps a carry so packets split across writes are still
+// seen whole.
+func (r *Ring) scanLocked(p []byte) {
+ // Absolute offset of p[0].
+ base := r.written
+
+ var data []byte
+ var dataAt int64
+ if len(r.carry) > 0 {
+ data = append(r.carry, p...)
+ dataAt = r.carryAt
+ } else {
+ data = p
+ dataAt = base
+ }
+
+ i := 0
+ for {
+ if !r.aligned {
+ // Look for a sync byte with another one a packet later, which is
+ // strong evidence of real alignment rather than a stray 0x47.
+ found := -1
+ for j := i; j+packetSize < len(data); j++ {
+ if data[j] == syncByte && data[j+packetSize] == syncByte {
+ found = j
+ break
+ }
+ }
+ if found < 0 {
+ break
+ }
+ i = found
+ r.aligned = true
+ }
+ if i+packetSize > len(data) {
+ break
+ }
+ if data[i] != syncByte {
+ // Lost the grid; re-acquire from the next byte.
+ r.aligned = false
+ i++
+ continue
+ }
+ pid := (int(data[i+1]&0x1F) << 8) | int(data[i+2])
+ if pid == pidPAT {
+ r.joinAt = dataAt + int64(i)
+ }
+ i += packetSize
+ }
+
+ // Keep whatever is left of the last partial packet.
+ if rest := len(data) - i; rest > 0 && rest < packetSize {
+ r.carry = append(r.carry[:0], data[i:]...)
+ r.carryAt = dataAt + int64(i)
+ } else {
+ r.carry = r.carry[:0]
+ r.carryAt = 0
+ }
+}
+
+// Close ends the stream and wakes every reader.
+func (r *Ring) Close() error {
+ r.mu.Lock()
+ r.closed = true
+ r.cond.Broadcast()
+ r.mu.Unlock()
+ return nil
+}
+
+// Closed reports whether the source has ended.
+func (r *Ring) Closed() bool {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.closed
+}
+
+// Readers is the current client count.
+func (r *Ring) Readers() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.readers
+}
+
+// Reader is one client's view of the ring.
+type Reader struct {
+ ring *Ring
+ pos int64
+ done bool
+}
+
+// NewReader joins the stream at the most recent decodable point.
+func (r *Ring) NewReader() *Reader {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ start := r.joinAt
+ // Nothing useful seen yet, or the PAT has already been overwritten: start
+ // from the oldest byte still held.
+ oldest := r.oldestLocked()
+ if start < oldest {
+ start = oldest
+ }
+ r.readers++
+ return &Reader{ring: r, pos: start}
+}
+
+func (r *Ring) oldestLocked() int64 {
+ if r.written <= int64(len(r.buf)) {
+ return 0
+ }
+ return r.written - int64(len(r.buf))
+}
+
+// Read blocks until bytes are available, the client has lagged, or the stream
+// ends.
+func (rd *Reader) Read(p []byte) (int, error) {
+ ring := rd.ring
+ ring.mu.Lock()
+ defer ring.mu.Unlock()
+ for {
+ if rd.pos < ring.oldestLocked() {
+ return 0, ErrLagged
+ }
+ if avail := ring.written - rd.pos; avail > 0 {
+ n := int64(len(p))
+ if avail < n {
+ n = avail
+ }
+ // Do not read past the end of the circular array in one go.
+ off := int(rd.pos % int64(len(ring.buf)))
+ if tail := int64(len(ring.buf) - off); n > tail {
+ n = tail
+ }
+ copy(p[:n], ring.buf[off:off+int(n)])
+ rd.pos += n
+ return int(n), nil
+ }
+ if ring.closed {
+ return 0, io.EOF
+ }
+ ring.cond.Wait()
+ }
+}
+
+// Close releases the reader.
+func (rd *Reader) Close() error {
+ if rd.done {
+ return nil
+ }
+ rd.done = true
+ rd.ring.mu.Lock()
+ rd.ring.readers--
+ rd.ring.mu.Unlock()
+ return nil
+}
+
+// Set tracks one ring per publish target (a stream's variant), so the HTTP
+// layer can look one up by name.
+type Set struct {
+ mu sync.Mutex
+ rings map[string]*Ring
+ size int
+}
+
+func NewSet(bufferBytes int) *Set {
+ if bufferBytes <= 0 {
+ bufferBytes = DefaultBufferBytes
+ }
+ return &Set{rings: map[string]*Ring{}, size: bufferBytes}
+}
+
+// Create replaces any existing ring for key and returns the new one. The old
+// ring is closed, which drops its readers — they will reconnect.
+func (s *Set) Create(key string) *Ring {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if old, ok := s.rings[key]; ok {
+ _ = old.Close()
+ }
+ r := New(s.size)
+ s.rings[key] = r
+ return r
+}
+
+// Get returns the live ring for key, if any.
+func (s *Set) Get(key string) (*Ring, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ r, ok := s.rings[key]
+ if ok && r.Closed() {
+ return nil, false
+ }
+ return r, ok
+}
+
+// Remove closes and forgets the ring for key.
+func (s *Set) Remove(key string) {
+ s.mu.Lock()
+ r, ok := s.rings[key]
+ delete(s.rings, key)
+ s.mu.Unlock()
+ if ok {
+ _ = r.Close()
+ }
+}
+
+// RemovePrefix drops every ring whose key starts with prefix, used when a
+// stream and all its variants stop.
+func (s *Set) RemovePrefix(prefix string) {
+ s.mu.Lock()
+ var doomed []*Ring
+ for k, r := range s.rings {
+ if k == prefix || (len(k) > len(prefix) && k[:len(prefix)] == prefix) {
+ doomed = append(doomed, r)
+ delete(s.rings, k)
+ }
+ }
+ s.mu.Unlock()
+ for _, r := range doomed {
+ _ = r.Close()
+ }
+}
+
+// Readers totals the clients across every ring whose key starts with prefix.
+func (s *Set) Readers(prefix string) int {
+ s.mu.Lock()
+ rings := make([]*Ring, 0, len(s.rings))
+ for k, r := range s.rings {
+ if k == prefix || (len(k) > len(prefix) && k[:len(prefix)] == prefix) {
+ rings = append(rings, r)
+ }
+ }
+ s.mu.Unlock()
+ total := 0
+ for _, r := range rings {
+ total += r.Readers()
+ }
+ return total
+}
diff --git a/apps/streamd/internal/tsfanout/tsfanout_test.go b/apps/streamd/internal/tsfanout/tsfanout_test.go
new file mode 100644
index 0000000..5a3549f
--- /dev/null
+++ b/apps/streamd/internal/tsfanout/tsfanout_test.go
@@ -0,0 +1,304 @@
+package tsfanout
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "testing"
+ "time"
+)
+
+// tsPacket builds one 188-byte TS packet for the given PID.
+func tsPacket(pid int, fill byte) []byte {
+ p := make([]byte, packetSize)
+ p[0] = syncByte
+ p[1] = byte(pid>>8) & 0x1F
+ p[2] = byte(pid & 0xFF)
+ p[3] = 0x10
+ for i := 4; i < packetSize; i++ {
+ p[i] = fill
+ }
+ return p
+}
+
+// tsStream builds a stream whose every n-th packet is a PAT, as ffmpeg's
+// mpegts muxer emits.
+func tsStream(packets int, patEvery int) []byte {
+ var b bytes.Buffer
+ for i := 0; i < packets; i++ {
+ if patEvery > 0 && i%patEvery == 0 {
+ b.Write(tsPacket(pidPAT, byte(i)))
+ continue
+ }
+ b.Write(tsPacket(0x100, byte(i)))
+ }
+ return b.Bytes()
+}
+
+func TestWriteReturnsFullLength(t *testing.T) {
+ r := New(DefaultBufferBytes)
+ data := tsStream(10, 5)
+ n, err := r.Write(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n != len(data) {
+ t.Errorf("Write returned %d, want %d — an io.Writer that under-reports breaks io.Copy", n, len(data))
+ }
+}
+
+// A client joining mid-stream must start at a PAT packet, or its decoder has
+// no idea what it is looking at.
+func TestReaderJoinsAtPATBoundary(t *testing.T) {
+ r := New(64 * packetSize)
+ // PAT every 5 packets.
+ r.Write(tsStream(20, 5))
+
+ rd := r.NewReader()
+ defer rd.Close()
+ buf := make([]byte, packetSize)
+ if _, err := io.ReadFull(rd, buf); err != nil {
+ t.Fatal(err)
+ }
+ if buf[0] != syncByte {
+ t.Fatalf("reader did not start on a packet boundary: first byte %#x", buf[0])
+ }
+ pid := (int(buf[1]&0x1F) << 8) | int(buf[2])
+ if pid != pidPAT {
+ t.Errorf("reader started at PID %d, want the PAT (%d)", pid, pidPAT)
+ }
+}
+
+// Even when the writes are chopped at arbitrary, non-packet-aligned sizes, the
+// scanner must still find the grid. A pipe gives no alignment guarantees.
+func TestPATDetectionAcrossSplitWrites(t *testing.T) {
+ r := New(64 * packetSize)
+ data := tsStream(20, 5)
+ // Deliberately awkward chunk size, coprime with 188.
+ for i := 0; i < len(data); i += 77 {
+ end := i + 77
+ if end > len(data) {
+ end = len(data)
+ }
+ if _, err := r.Write(data[i:end]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ rd := r.NewReader()
+ defer rd.Close()
+ buf := make([]byte, packetSize)
+ if _, err := io.ReadFull(rd, buf); err != nil {
+ t.Fatal(err)
+ }
+ pid := (int(buf[1]&0x1F) << 8) | int(buf[2])
+ if buf[0] != syncByte || pid != pidPAT {
+ t.Errorf("split writes broke PAT detection: sync=%#x pid=%d", buf[0], pid)
+ }
+}
+
+func TestReaderStreamsSubsequentWrites(t *testing.T) {
+ r := New(64 * packetSize)
+ r.Write(tsStream(5, 5))
+ rd := r.NewReader()
+ defer rd.Close()
+
+ // Drain what is buffered.
+ buf := make([]byte, 5*packetSize)
+ if _, err := io.ReadFull(rd, buf); err != nil {
+ t.Fatal(err)
+ }
+
+ // A read with nothing available must block, then return new data.
+ type res struct {
+ n int
+ err error
+ }
+ ch := make(chan res, 1)
+ go func() {
+ b := make([]byte, packetSize)
+ n, err := rd.Read(b)
+ ch <- res{n, err}
+ }()
+ select {
+ case got := <-ch:
+ t.Fatalf("Read returned early (%d, %v) instead of waiting for data", got.n, got.err)
+ case <-time.After(50 * time.Millisecond):
+ }
+ r.Write(tsPacket(0x100, 9))
+ select {
+ case got := <-ch:
+ if got.err != nil || got.n == 0 {
+ t.Fatalf("Read after write: %d %v", got.n, got.err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("Read did not wake after a write")
+ }
+}
+
+// A stalled client must be dropped, not allowed to stall the writer or grow
+// memory. This is the backpressure decision that keeps one slow viewer from
+// affecting the stream.
+func TestLaggedReaderIsDropped(t *testing.T) {
+ size := 8 * packetSize
+ r := New(size)
+ r.Write(tsStream(4, 4))
+ rd := r.NewReader()
+ defer rd.Close()
+
+ // Overwrite the whole buffer several times without the reader consuming.
+ for i := 0; i < 5; i++ {
+ r.Write(tsStream(8, 8))
+ }
+ buf := make([]byte, packetSize)
+ _, err := rd.Read(buf)
+ if !errors.Is(err, ErrLagged) {
+ t.Errorf("want ErrLagged for a stalled client, got %v", err)
+ }
+}
+
+func TestMultipleReadersGetSameBytes(t *testing.T) {
+ r := New(64 * packetSize)
+ // Three clients, one source: the whole point of the package.
+ a, b, c := r.NewReader(), r.NewReader(), r.NewReader()
+ defer a.Close()
+ defer b.Close()
+ defer c.Close()
+ if got := r.Readers(); got != 3 {
+ t.Fatalf("Readers() = %d, want 3", got)
+ }
+
+ data := tsStream(10, 5)
+ r.Write(data)
+ read := func(rd *Reader) []byte {
+ out := make([]byte, 10*packetSize)
+ if _, err := io.ReadFull(rd, out); err != nil {
+ t.Fatalf("read: %v", err)
+ }
+ return out
+ }
+ ra, rb, rc := read(a), read(b), read(c)
+ if !bytes.Equal(ra, rb) || !bytes.Equal(rb, rc) {
+ t.Error("readers received different bytes from the same source")
+ }
+
+ // Closing one must not disturb the others.
+ _ = a.Close()
+ if got := r.Readers(); got != 2 {
+ t.Errorf("after one close, Readers() = %d, want 2", got)
+ }
+ r.Write(tsPacket(0x100, 1))
+ one := make([]byte, packetSize)
+ if _, err := io.ReadFull(b, one); err != nil {
+ t.Errorf("surviving reader broke after another closed: %v", err)
+ }
+}
+
+func TestCloseEndsReaders(t *testing.T) {
+ r := New(64 * packetSize)
+ rd := r.NewReader()
+ defer rd.Close()
+ done := make(chan error, 1)
+ go func() {
+ b := make([]byte, packetSize)
+ _, err := rd.Read(b)
+ done <- err
+ }()
+ time.Sleep(20 * time.Millisecond)
+ _ = r.Close()
+ select {
+ case err := <-done:
+ if !errors.Is(err, io.EOF) {
+ t.Errorf("want io.EOF after Close, got %v", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("Close did not wake a blocked reader")
+ }
+ if _, err := r.Write([]byte("x")); !errors.Is(err, ErrClosed) {
+ t.Errorf("write after close should fail, got %v", err)
+ }
+}
+
+// The ring must wrap correctly: reading across the seam has to produce the
+// bytes that were written, not a torn copy.
+func TestRingWrapsCorrectly(t *testing.T) {
+ size := 16 * packetSize
+ r := New(size)
+ rd := r.NewReader()
+ defer rd.Close()
+
+ // Write and drain repeatedly so the write position passes the end of the
+ // array several times.
+ var want, got bytes.Buffer
+ for round := 0; round < 10; round++ {
+ chunk := tsStream(6, 6)
+ r.Write(chunk)
+ want.Write(chunk)
+ buf := make([]byte, len(chunk))
+ if _, err := io.ReadFull(rd, buf); err != nil {
+ t.Fatalf("round %d: %v", round, err)
+ }
+ got.Write(buf)
+ }
+ if !bytes.Equal(want.Bytes(), got.Bytes()) {
+ t.Error("data read across the ring wrap does not match what was written")
+ }
+}
+
+func TestSetLifecycle(t *testing.T) {
+ s := NewSet(16 * packetSize)
+ if _, ok := s.Get("city-news"); ok {
+ t.Error("empty set should not resolve a key")
+ }
+ r := s.Create("city-news")
+ if got, ok := s.Get("city-news"); !ok || got != r {
+ t.Error("Create then Get should return the same ring")
+ }
+
+ // Creating again replaces and closes the old ring, so its readers drop.
+ rd := r.NewReader()
+ defer rd.Close()
+ r2 := s.Create("city-news")
+ if r2 == r {
+ t.Error("Create should replace the existing ring")
+ }
+ if !r.Closed() {
+ t.Error("the replaced ring should be closed")
+ }
+
+ // Prefix removal covers a stream and all of its variants at once.
+ s.Create("city-news-hd")
+ s.Create("other")
+ s.RemovePrefix("city-news")
+ if _, ok := s.Get("city-news"); ok {
+ t.Error("city-news should be gone")
+ }
+ if _, ok := s.Get("city-news-hd"); ok {
+ t.Error("city-news-hd should be gone")
+ }
+ if _, ok := s.Get("other"); !ok {
+ t.Error("unrelated key should survive RemovePrefix")
+ }
+}
+
+func TestSetReadersCountsAcrossVariants(t *testing.T) {
+ s := NewSet(16 * packetSize)
+ a := s.Create("news")
+ b := s.Create("news-hd")
+ r1, r2, r3 := a.NewReader(), b.NewReader(), b.NewReader()
+ defer r1.Close()
+ defer r2.Close()
+ defer r3.Close()
+ if got := s.Readers("news"); got != 3 {
+ t.Errorf("Readers(news) = %d, want 3 across both variants", got)
+ }
+}
+
+// A closed ring must not be handed out as live.
+func TestGetSkipsClosedRing(t *testing.T) {
+ s := NewSet(16 * packetSize)
+ r := s.Create("x")
+ _ = r.Close()
+ if _, ok := s.Get("x"); ok {
+ t.Error("Get should not return a closed ring")
+ }
+}
diff --git a/apps/streamd/internal/ui/app.css b/apps/streamd/internal/ui/app.css
deleted file mode 100644
index 778d890..0000000
--- a/apps/streamd/internal/ui/app.css
+++ /dev/null
@@ -1,106 +0,0 @@
-:root {
- --bg: #0f1115;
- --card: #171a21;
- --border: #2a303c;
- --text: #e8eaed;
- --muted: #9aa0a6;
- --accent: #7aa2ff;
- --ok: #3dd68c;
- --degraded: #f5a524;
- --down: #f07178;
- --stopped: #6b7280;
-}
-* { box-sizing: border-box; }
-body {
- margin: 0;
- font: 14px/1.45 system-ui, Segoe UI, sans-serif;
- background: var(--bg);
- color: var(--text);
-}
-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 12px 20px;
- border-bottom: 1px solid var(--border);
-}
-h1 { margin: 0; font-size: 18px; font-weight: 600; }
-h2 { margin: 0 0 12px; font-size: 15px; font-weight: 600; }
-.header-right { display: flex; gap: 16px; align-items: center; }
-.muted { color: var(--muted); }
-.card {
- margin: 16px 20px;
- padding: 16px;
- background: var(--card);
- border: 1px solid var(--border);
- border-radius: 8px;
-}
-.grid {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 10px 14px;
-}
-.span2 { grid-column: span 2; }
-label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--muted); }
-input, select, button, textarea {
- font: inherit;
- color: var(--text);
- background: #0c0e12;
- border: 1px solid var(--border);
- border-radius: 6px;
- padding: 7px 9px;
-}
-textarea {
- font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
- font-size: 12px;
- line-height: 1.4;
- resize: vertical;
- min-height: 4.5em;
- white-space: pre;
-}
-button {
- background: #243044;
- border-color: #334155;
- cursor: pointer;
-}
-button:hover { border-color: var(--accent); }
-button.ghost { background: transparent; }
-button.danger { border-color: #7f1d1d; color: #fecaca; }
-.actions { display: flex; gap: 8px; align-items: end; }
-.token-box input { width: 180px; }
-.row-between { display: flex; justify-content: space-between; align-items: center; }
-.table-wrap { overflow-x: auto; }
-table { width: 100%; border-collapse: collapse; }
-th, td { text-align: left; padding: 8px 6px; border-bottom: 1px solid var(--border); vertical-align: middle; }
-th { color: var(--muted); font-weight: 500; font-size: 12px; }
-.pill {
- display: inline-block;
- padding: 2px 8px;
- border-radius: 999px;
- font-size: 12px;
- background: #222;
-}
-.pill.ok { color: var(--ok); }
-.pill.degraded { color: var(--degraded); }
-.pill.down, .pill.starting { color: var(--down); }
-.pill.stopped { color: var(--stopped); }
-.pill.claim { color: #c4b5fd; background: #1f1635; }
-.row-actions { display: flex; flex-wrap: wrap; gap: 6px; }
-.row-actions button { padding: 4px 8px; font-size: 12px; }
-.msg { min-height: 1.2em; margin: 8px 0 0; }
-.msg.err { color: var(--down); }
-a { color: var(--accent); }
-dialog {
- border: 1px solid var(--border);
- background: var(--card);
- color: var(--text);
- border-radius: 8px;
- padding: 16px;
- min-width: min(560px, 92vw);
-}
-dialog::backdrop { background: rgba(0,0,0,.55); }
-@media (max-width: 720px) {
- .grid { grid-template-columns: 1fr; }
- .span2 { grid-column: span 1; }
- header { flex-direction: column; align-items: flex-start; gap: 8px; }
-}
diff --git a/apps/streamd/internal/ui/app.js b/apps/streamd/internal/ui/app.js
deleted file mode 100644
index d42c50e..0000000
--- a/apps/streamd/internal/ui/app.js
+++ /dev/null
@@ -1,286 +0,0 @@
-(() => {
- const tokenEl = document.getElementById("token");
- const rowsEl = document.getElementById("rows");
- const listMsg = document.getElementById("list-msg");
- const formMsg = document.getElementById("form-msg");
- const uptimeEl = document.getElementById("uptime");
- const agentsEl = document.getElementById("agents-status");
- const dlg = document.getElementById("edit-dlg");
- const editForm = document.getElementById("edit-form");
-
- tokenEl.value = localStorage.getItem("streamd_token") || "";
- tokenEl.addEventListener("change", () => {
- localStorage.setItem("streamd_token", tokenEl.value.trim());
- connectUIWS();
- });
-
- function token() {
- return tokenEl.value.trim();
- }
-
- function headers(json) {
- const h = {};
- if (json) h["Content-Type"] = "application/json";
- const t = token();
- if (t) h["Authorization"] = "Bearer " + t;
- return h;
- }
-
- async function api(path, opts = {}) {
- const res = await fetch(path, opts);
- const text = await res.text();
- let data = null;
- try { data = text ? JSON.parse(text) : null; } catch { data = { raw: text }; }
- if (!res.ok) {
- const msg = (data && data.error) || res.statusText || "request failed";
- throw new Error(msg);
- }
- return data;
- }
-
- function age(s) {
- if (s == null || s === 0) return "—";
- return Number(s).toFixed(1) + "s";
- }
-
- function claimLabel(s) {
- if (!s.claimed_by) return '—';
- let exp = "";
- if (s.claim_expires_at) {
- const ms = Date.parse(s.claim_expires_at) - Date.now();
- if (!Number.isNaN(ms)) {
- exp = ms > 0 ? ` (${Math.ceil(ms / 1000)}s)` : " (expired)";
- }
- }
- return `${esc(s.claimed_by)}${esc(exp)}`;
- }
-
- function render(streams) {
- if (!streams.length) {
- rowsEl.innerHTML = "";
- listMsg.textContent = "No streams yet. Add one above.";
- return;
- }
- listMsg.textContent = streams.length + " stream(s)";
- rowsEl.innerHTML = streams.map((s) => {
- const need = !s.mpd || !s.key ? " needs capture" : "";
- return `
- | ${esc(s.name)} ${esc(s.title || "")}${need} |
- ${esc(s.app)} / ${esc(s.channel)} |
- ${esc(s.health || "stopped")} |
- ${claimLabel(s)} |
- ${age(s.playlist_age_s)} |
- hls |
-
-
-
-
-
- ${s.claimed_by ? `` : ""}
-
- |
-
`;
- }).join("");
- }
-
- function esc(v) {
- return String(v ?? "").replace(/[&<>"']/g, (c) => ({
- "&": "&", "<": "<", ">": ">", '"': """, "'": "'"
- }[c]));
- }
-
- function renderAgents(list) {
- if (!agentsEl) return;
- if (!list || !list.length) {
- agentsEl.textContent = "agents: none connected";
- return;
- }
- agentsEl.textContent = "agents: " + list.map((a) => a.agent_id).join(", ");
- }
-
- async function refresh() {
- try {
- const [health, list, agents] = await Promise.all([
- api("/api/health"),
- api("/api/streams"),
- api("/api/agents").catch(() => ({ agents: [] })),
- ]);
- uptimeEl.textContent = "up " + Math.floor(health.uptime_s || 0) + "s";
- render(list.streams || []);
- renderAgents(agents.agents || []);
- listMsg.classList.remove("err");
- } catch (e) {
- listMsg.textContent = e.message;
- listMsg.classList.add("err");
- }
- }
-
- // App/channel pickers come from the binary's compiled-in modules, so the UI
- // never hardcodes a provider.
- const appSel = document.getElementById("app-select");
- const chanSel = document.getElementById("channel-select");
- let apps = [];
-
- function fillChannels() {
- const a = apps.find((x) => x.name === appSel.value);
- chanSel.innerHTML = "";
- if (!a || !a.channels.length) {
- const o = document.createElement("option");
- o.value = "";
- o.textContent = a ? "(no module.yaml — no channels)" : "(no apps)";
- chanSel.appendChild(o);
- return;
- }
- for (const ch of a.channels) {
- const o = document.createElement("option");
- o.value = ch.id;
- o.textContent = ch.label && ch.label !== ch.id ? ch.id + " — " + ch.label : ch.id;
- chanSel.appendChild(o);
- }
- }
-
- async function loadApps() {
- try {
- const data = await api("/api/apps");
- apps = data.apps || [];
- } catch (e) {
- apps = [];
- }
- appSel.innerHTML = "";
- if (!apps.length) {
- const o = document.createElement("option");
- o.value = "";
- o.textContent = "(no app modules compiled in)";
- appSel.appendChild(o);
- }
- for (const a of apps) {
- const o = document.createElement("option");
- o.value = a.name;
- o.textContent = a.name;
- appSel.appendChild(o);
- }
- fillChannels();
- }
-
- appSel.addEventListener("change", fillChannels);
- loadApps();
-
- document.getElementById("refresh").addEventListener("click", refresh);
-
- document.getElementById("create-form").addEventListener("submit", async (ev) => {
- ev.preventDefault();
- formMsg.textContent = "";
- formMsg.classList.remove("err");
- const fd = new FormData(ev.target);
- const body = Object.fromEntries(fd.entries());
- try {
- await api("/api/streams", {
- method: "POST",
- headers: headers(true),
- body: JSON.stringify(body),
- });
- ev.target.reset();
- ev.target.headers_json.value = "{}";
- fillChannels();
- formMsg.textContent = "Created.";
- refresh();
- } catch (e) {
- formMsg.textContent = e.message;
- formMsg.classList.add("err");
- }
- });
-
- rowsEl.addEventListener("click", async (ev) => {
- const btn = ev.target.closest("button[data-act]");
- if (!btn) return;
- const id = btn.dataset.id;
- const act = btn.dataset.act;
- try {
- if (act === "delete") {
- if (!confirm("Delete stream #" + id + "?")) return;
- await api("/api/streams/" + id, { method: "DELETE", headers: headers(false) });
- } else if (act === "unclaim") {
- await api("/api/streams/" + id + "/claim/release", {
- method: "POST",
- headers: headers(true),
- body: JSON.stringify({ agent_id: "" }),
- });
- } else if (act === "edit") {
- const st = await api("/api/streams/" + id);
- editForm.id.value = st.id;
- editForm.title.value = st.title || "";
- editForm.channel.value = st.channel || "";
- editForm.mpd.value = st.mpd || "";
- editForm.key.value = st.key || "";
- editForm.headers_json.value = st.headers_json || "{}";
- dlg.showModal();
- return;
- } else {
- await api("/api/streams/" + id + "/" + act, {
- method: "POST",
- headers: headers(false),
- });
- }
- refresh();
- } catch (e) {
- listMsg.textContent = e.message;
- listMsg.classList.add("err");
- }
- });
-
- document.getElementById("edit-cancel").addEventListener("click", () => dlg.close());
-
- editForm.addEventListener("submit", async (ev) => {
- ev.preventDefault();
- const id = editForm.id.value;
- const body = {
- title: editForm.title.value,
- channel: editForm.channel.value,
- mpd: editForm.mpd.value,
- key: editForm.key.value,
- headers_json: editForm.headers_json.value,
- };
- try {
- await api("/api/streams/" + id, {
- method: "PATCH",
- headers: headers(true),
- body: JSON.stringify(body),
- });
- dlg.close();
- refresh();
- } catch (e) {
- alert(e.message);
- }
- });
-
- let uiWS = null;
- let uiWSTimer = null;
- function connectUIWS() {
- if (uiWS) {
- try { uiWS.close(); } catch {}
- uiWS = null;
- }
- const proto = location.protocol === "https:" ? "wss:" : "ws:";
- const ws = new WebSocket(proto + "//" + location.host + "/ws/ui");
- uiWS = ws;
- ws.onmessage = (ev) => {
- try {
- const msg = JSON.parse(ev.data);
- if (msg.type === "agents" || msg.type === "agent_online" || msg.type === "agent_offline") {
- renderAgents(msg.agents || []);
- }
- if (msg.type === "claims_changed" || msg.type === "agent_offline") {
- refresh();
- }
- } catch {}
- };
- ws.onclose = () => {
- clearTimeout(uiWSTimer);
- uiWSTimer = setTimeout(connectUIWS, 3000);
- };
- }
-
- refresh();
- connectUIWS();
- setInterval(refresh, 5000);
-})();
diff --git a/apps/streamd/internal/ui/index.html b/apps/streamd/internal/ui/index.html
index 6418772..c425196 100644
--- a/apps/streamd/internal/ui/index.html
+++ b/apps/streamd/internal/ui/index.html
@@ -4,81 +4,106 @@
streamd
+
+
-
+
+
+
+
+
-
-
-
Streams
-
- agents: —
-
-
-
-
-
-
-
- | name |
- app / channel |
- health |
- claim |
- age |
- play |
- actions |
-
-
-
-
-
- Loading…
-
+
-