From 066e018749a778e2c08f661b443560593cca1ee6 Mon Sep 17 00:00:00 2001 From: 404errordeveloper Date: Fri, 9 Oct 2026 20:57:43 +0200 Subject: [PATCH] =?UTF-8?q?=EF=BB=BFstreamd:=20preview=20quality=20picker,?= =?UTF-8?q?=20dashboard=20polish,=20C4=20wrap=20keys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Preview player can select FHD/HD/SD (or ABR master) from publish links - Embed dashboard screenshots in README; Linux streamd+agent setup guide - C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH - Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate --- .forgejo/workflows/modules-release.yml | 2 + README.md | 48 +- apps/agent/README.md | 21 +- apps/agent/agent.yaml | 13 +- apps/agent/agentcmd/agentcmd.go | 46 +- apps/agent/internal/client/client.go | 181 +++- apps/agent/internal/config/config.go | 28 +- apps/agent/internal/device/pool.go | 8 +- apps/agent/internal/poller/poller.go | 91 +- apps/agent/internal/queue/queue.go | 51 +- apps/agent/internal/worker/worker.go | 35 + apps/agent/internal/wsclient/wsclient.go | 78 +- apps/capture/capturecmd/capturecmd.go | 143 ++- apps/cli/main.go | 6 +- apps/modules/all/all_test.go | 10 +- apps/modules/c4/c4.go | 148 ++++ apps/modules/c4/config.go | 116 +++ apps/modules/c4/module-publish.yaml | 84 ++ apps/modules/c4/steps.go | 175 ++++ apps/modules/my5/config.go | 133 +++ apps/modules/my5/module-publish.yaml | 118 +++ apps/modules/my5/my5.go | 160 ++++ apps/modules/my5/steps.go | 265 ++++++ apps/pkg/adb/adb.go | 4 + apps/pkg/app/app.go | 13 + apps/pkg/capture/capture.go | 48 +- apps/pkg/modhost/protocol.go | 21 +- apps/pkg/modhost/remote_app.go | 36 +- apps/pkg/phonecap/phonecap.go | 137 ++- apps/pkg/session/session.go | 14 +- apps/pkg/wvkey/wvkey.go | 30 +- apps/proxy/device/main.go | 99 ++- apps/proxy/device/tproxy_iptables.sh | 21 +- apps/streamd/README.md | 72 +- apps/streamd/internal/api/api.go | 328 ++++++- apps/streamd/internal/api/apps.go | 4 + apps/streamd/internal/api/control.go | 620 +++++++++++++ apps/streamd/internal/api/events.go | 383 ++++++++ apps/streamd/internal/api/modules.go | 14 +- apps/streamd/internal/api/variants.go | 94 +- apps/streamd/internal/auth/auth.go | 174 ++++ apps/streamd/internal/auth/auth_test.go | 548 ++++++++++++ apps/streamd/internal/auth/handlers.go | 586 +++++++++++++ apps/streamd/internal/auth/middleware.go | 238 +++++ apps/streamd/internal/auth/ratelimit.go | 140 +++ apps/streamd/internal/auth/store.go | 639 ++++++++++++++ apps/streamd/internal/db/db.go | 490 +++++++++-- apps/streamd/internal/db/events.go | 438 ++++++++++ apps/streamd/internal/db/outputs.go | 285 ++++++ apps/streamd/internal/db/schedules.go | 459 ++++++++++ apps/streamd/internal/db/schedules_test.go | 370 ++++++++ apps/streamd/internal/db/settings.go | 179 ++++ apps/streamd/internal/db/settings_test.go | 57 ++ apps/streamd/internal/db/stream_test.go | 170 ++++ apps/streamd/internal/db/variants.go | 109 ++- apps/streamd/internal/db/variants_test.go | 295 ++++++- apps/streamd/internal/deps/deps.go | 20 +- apps/streamd/internal/hlsgate/hlsgate.go | 675 +++++++++++++++ apps/streamd/internal/hlsgate/hlsgate_test.go | 642 ++++++++++++++ apps/streamd/internal/httpx/httpx.go | 257 ++++++ apps/streamd/internal/logfile/logfile.go | 211 +++++ apps/streamd/internal/logfile/logfile_test.go | 192 +++++ apps/streamd/internal/scheduler/scheduler.go | 178 ++++ .../internal/supervisor/appdefaults.go | 69 +- .../internal/supervisor/appdefaults_test.go | 72 +- .../supervisor/ffmpeg_integration_test.go | 218 +++++ apps/streamd/internal/supervisor/media.go | 444 +++++++--- apps/streamd/internal/supervisor/outputs.go | 299 +++++++ .../internal/supervisor/outputs_test.go | 389 +++++++++ apps/streamd/internal/supervisor/variants.go | 255 ++++-- apps/streamd/internal/tsfanout/tsfanout.go | 333 +++++++ .../internal/tsfanout/tsfanout_test.go | 304 +++++++ apps/streamd/internal/ui/app.css | 211 ----- apps/streamd/internal/ui/app.js | 440 ---------- apps/streamd/internal/ui/index.html | 202 ++--- apps/streamd/internal/ui/static/app.css | 645 ++++++++++++++ apps/streamd/internal/ui/static/js/api.js | 134 +++ apps/streamd/internal/ui/static/js/app.js | 331 +++++++ .../internal/ui/static/js/components.js | 375 ++++++++ apps/streamd/internal/ui/static/js/store.js | 200 +++++ apps/streamd/internal/ui/static/js/util.js | 350 ++++++++ .../internal/ui/static/js/views/admin.js | 562 ++++++++++++ .../internal/ui/static/js/views/dashboard.js | 180 ++++ .../ui/static/js/views/stream-form.js | 263 ++++++ .../internal/ui/static/js/views/stream.js | 816 ++++++++++++++++++ .../internal/ui/static/js/views/streams.js | 292 +++++++ .../internal/ui/static/vendor/README.md | 13 + .../internal/ui/static/vendor/hls.min.js | 2 + apps/streamd/internal/ui/ui.go | 33 +- apps/streamd/internal/ws/hub.go | 229 ++++- apps/streamd/servecmd/servecmd.go | 343 +++++--- apps/wvkey/README.md | 9 + apps/wvkey/wvkey.py | 164 +++- docs/README.md | 1 + docs/images/streamd/dashboard.jpg | Bin 0 -> 68132 bytes docs/images/streamd/people-keys.jpg | Bin 0 -> 36618 bytes docs/images/streamd/stream-detail.jpg | Bin 0 -> 63459 bytes docs/images/streamd/streams.jpg | Bin 0 -> 82750 bytes docs/streamd-server-setup.md | 477 ++++++++++ docs/streamd.md | 43 +- modules/README.md | 3 +- modules/c4/go.mod | 15 + modules/c4/go.sum | 4 + modules/c4/main.go | 171 ++++ modules/c4/module-publish.yaml | 84 ++ modules/my5/go.mod | 15 + modules/my5/go.sum | 4 + modules/my5/main.go | 169 ++++ modules/my5/module-publish.yaml | 118 +++ scripts/build-modules-release.ps1 | 4 +- scripts/build-modules-release.sh | 4 +- scripts/notify-telegram.ps1 | 2 +- scripts/notify-telegram.sh | 2 +- 113 files changed, 19002 insertions(+), 1541 deletions(-) create mode 100644 apps/modules/c4/c4.go create mode 100644 apps/modules/c4/config.go create mode 100644 apps/modules/c4/module-publish.yaml create mode 100644 apps/modules/c4/steps.go create mode 100644 apps/modules/my5/config.go create mode 100644 apps/modules/my5/module-publish.yaml create mode 100644 apps/modules/my5/my5.go create mode 100644 apps/modules/my5/steps.go create mode 100644 apps/streamd/internal/api/control.go create mode 100644 apps/streamd/internal/api/events.go create mode 100644 apps/streamd/internal/auth/auth.go create mode 100644 apps/streamd/internal/auth/auth_test.go create mode 100644 apps/streamd/internal/auth/handlers.go create mode 100644 apps/streamd/internal/auth/middleware.go create mode 100644 apps/streamd/internal/auth/ratelimit.go create mode 100644 apps/streamd/internal/auth/store.go create mode 100644 apps/streamd/internal/db/events.go create mode 100644 apps/streamd/internal/db/outputs.go create mode 100644 apps/streamd/internal/db/schedules.go create mode 100644 apps/streamd/internal/db/schedules_test.go create mode 100644 apps/streamd/internal/db/settings.go create mode 100644 apps/streamd/internal/db/settings_test.go create mode 100644 apps/streamd/internal/db/stream_test.go create mode 100644 apps/streamd/internal/hlsgate/hlsgate.go create mode 100644 apps/streamd/internal/hlsgate/hlsgate_test.go create mode 100644 apps/streamd/internal/httpx/httpx.go create mode 100644 apps/streamd/internal/logfile/logfile.go create mode 100644 apps/streamd/internal/logfile/logfile_test.go create mode 100644 apps/streamd/internal/scheduler/scheduler.go create mode 100644 apps/streamd/internal/supervisor/ffmpeg_integration_test.go create mode 100644 apps/streamd/internal/supervisor/outputs.go create mode 100644 apps/streamd/internal/supervisor/outputs_test.go create mode 100644 apps/streamd/internal/tsfanout/tsfanout.go create mode 100644 apps/streamd/internal/tsfanout/tsfanout_test.go delete mode 100644 apps/streamd/internal/ui/app.css delete mode 100644 apps/streamd/internal/ui/app.js create mode 100644 apps/streamd/internal/ui/static/app.css create mode 100644 apps/streamd/internal/ui/static/js/api.js create mode 100644 apps/streamd/internal/ui/static/js/app.js create mode 100644 apps/streamd/internal/ui/static/js/components.js create mode 100644 apps/streamd/internal/ui/static/js/store.js create mode 100644 apps/streamd/internal/ui/static/js/util.js create mode 100644 apps/streamd/internal/ui/static/js/views/admin.js create mode 100644 apps/streamd/internal/ui/static/js/views/dashboard.js create mode 100644 apps/streamd/internal/ui/static/js/views/stream-form.js create mode 100644 apps/streamd/internal/ui/static/js/views/stream.js create mode 100644 apps/streamd/internal/ui/static/js/views/streams.js create mode 100644 apps/streamd/internal/ui/static/vendor/README.md create mode 100644 apps/streamd/internal/ui/static/vendor/hls.min.js create mode 100644 docs/images/streamd/dashboard.jpg create mode 100644 docs/images/streamd/people-keys.jpg create mode 100644 docs/images/streamd/stream-detail.jpg create mode 100644 docs/images/streamd/streams.jpg create mode 100644 docs/streamd-server-setup.md create mode 100644 modules/c4/go.mod create mode 100644 modules/c4/go.sum create mode 100644 modules/c4/main.go create mode 100644 modules/c4/module-publish.yaml create mode 100644 modules/my5/go.mod create mode 100644 modules/my5/go.sum create mode 100644 modules/my5/main.go create mode 100644 modules/my5/module-publish.yaml diff --git a/.forgejo/workflows/modules-release.yml b/.forgejo/workflows/modules-release.yml index 872e8af..418c1bc 100644 --- a/.forgejo/workflows/modules-release.yml +++ b/.forgejo/workflows/modules-release.yml @@ -55,6 +55,8 @@ jobs: | `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//` (e.g. `bbc.zip` → `modules/bbc/`). diff --git a/README.md b/README.md index 9df626b..d1e3c77 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Next-generation open-source DRM decryption for Android streaming apps.** -Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, …), pull manifests +Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, Channel 4, …), pull manifests and licenses through a transparent MITM, and restream. One host binary — **`drm`** — plus drop-in providers under **`modules/`**. @@ -24,6 +24,39 @@ traffic. | 🇮🇪 `rte` | RTÉ Player | Irish egress; ModularDRM keys | | 🟢 `tg4` | TG4 | Catalog + phone capture | | 🟣 `itv` | ITVX | Transparent MITM; UK VPN; Live list autoplay | +| 🟧 `c4` | Channel 4 | Transparent MITM; UK VPN; Live TV grab-all | + +--- + +## 🖥️ streamd dashboard + +Run `drm serve`, open the panel in a browser, manage streams and API keys: + +

+ streamd Dashboard — overview, live Channel 4, HLS link +

+ +

Dashboard — health, live streams, and play links

+ +

+ streamd Streams list +

+ +

Streams — list, filters, start / stop / restart

+ +

+ streamd stream detail with in-browser player +

+ +

Stream detail — credentials, variants, and preview player

+ +

+ streamd People and API keys +

+ +

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) --- @@ -33,7 +66,7 @@ traffic. From the latest **`v*`** release grab your host binary (e.g. `drm-windows-amd64.exe`) and `proxy-android-arm64`. From a **`modules-v*`** release grab the zips you need -(`bbc.zip`, `rte.zip`, `tg4.zip`, `itv.zip`). +(`bbc.zip`, `rte.zip`, `tg4.zip`, `itv.zip`, `c4.zip`, `my5.zip`). ```text Null-DRM/ @@ -87,6 +120,13 @@ drm capture --app bbc --channel s4c --wait 120 # ITVX (UK VPN; Live tab autoplay) drm capture --app itv --channel itv1 --wait 90 +# Channel 4 — one channel, or every Live channel +drm capture --app c4 --channel channel4 --wait 90 +drm capture --app c4 --all --wait 90 + +# Grab every channel for any module +drm 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 @@ -135,8 +175,8 @@ drm agent run|status|devices|enqueue|cancel [--config …] | `module-publish.yaml` | git only | Universal package, channels, UI | | `module.yaml` | zips yes / git no | Secrets + overlays; release zips ship publish renamed | -Release module assets are `bbc.zip` / `rte.zip` / `tg4.zip` / `itv.zip` with -`module.yaml` only (no `module-publish.yaml` inside the zip). +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). --- diff --git a/apps/agent/README.md b/apps/agent/README.md index f68f9d1..44fe6ae 100644 --- a/apps/agent/README.md +++ b/apps/agent/README.md @@ -26,10 +26,11 @@ 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/drm serve --bind 127.0.0.1:8083 --data .cache/streamd -# terminal 2 — agent -export STREAMD_TOKEN=SECRET +# terminal 2 — agent (operator API key from streamd Settings → API keys) +export STREAMD_API_KEY=ndk_… +# or legacy: export STREAMD_TOKEN=… ./bin/drm agent run --config apps/agent/agent.yaml ``` @@ -40,14 +41,18 @@ export STREAMD_TOKEN=SECRET ./bin/drm 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. +App modules are discovered under `modules/`. 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`. + +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. diff --git a/apps/agent/agent.yaml b/apps/agent/agent.yaml index 2d73a7c..0bf5550 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://185.18.221.132:8083 -# Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials, modules). -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 @@ -15,6 +18,8 @@ devices: [] # empty = all adb "device" serials; never install sync_modules: true # modules_dir: modules # optional override (default: repo modules/) # modules_sync_interval_sec: 300 -# wvd: data/device.wvd # path to .wvd (required for key fetch) +# Required for key fetch. Relative paths resolve from the repo root +# (DRM-Decryption/), not from C:\Users\admin\Programming\. +wvd: # user_agent: "" # optional license-request User-Agent diff --git a/apps/agent/agentcmd/agentcmd.go b/apps/agent/agentcmd/agentcmd.go index fff2c42..a104e32 100644 --- a/apps/agent/agentcmd/agentcmd.go +++ b/apps/agent/agentcmd/agentcmd.go @@ -82,6 +82,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 { @@ -92,10 +100,22 @@ 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) q := openQueue(cfg) defer q.Close() @@ -129,6 +149,28 @@ func runCmd(sub string, args []string) { } 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) + } + }() + } go ws.Loop() for i := 0; i < cfg.Workers; i++ { @@ -211,7 +253,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/internal/client/client.go b/apps/agent/internal/client/client.go index 077ca75..0ddaa5c 100644 --- a/apps/agent/internal/client/client.go +++ b/apps/agent/internal/client/client.go @@ -3,6 +3,7 @@ package client import ( "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -10,35 +11,84 @@ import ( "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 +99,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 +158,26 @@ 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"` @@ -113,22 +206,33 @@ func (c *Client) PutModuleYAML(name string, yamlBytes []byte) error { return err } req.Header.Set("Content-Type", "text/yaml") - 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 err } defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if resp.StatusCode >= 300 { - return fmt.Errorf("PUT /api/modules/%s: %s — %s", name, resp.Status, strings.TrimSpace(string(body))) + return c.statusError(http.MethodPut, "/api/modules/"+name, resp, body) } return nil } +func (c *Client) setHeaders(req *http.Request) { + ua := c.UserAgent + if ua == "" { + ua = "drm-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 { @@ -145,18 +249,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 725d104..2239f5a 100644 --- a/apps/agent/internal/config/config.go +++ b/apps/agent/internal/config/config.go @@ -11,8 +11,12 @@ import ( ) 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"` @@ -24,9 +28,19 @@ type Config struct { UserAgent string `yaml:"user_agent"` AgentID string `yaml:"agent_id"` // SyncModules pushes local modules//module.yaml to streamd when missing/stale. - SyncModules bool `yaml:"sync_modules"` - ModulesDir string `yaml:"modules_dir"` // empty = repo modules/ - ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"` + SyncModules bool `yaml:"sync_modules"` + ModulesDir string `yaml:"modules_dir"` // empty = repo modules/ + ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"` + // 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"` +} + +// 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 } func (c Config) PollInterval() time.Duration { @@ -72,9 +86,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 } diff --git a/apps/agent/internal/device/pool.go b/apps/agent/internal/device/pool.go index 1cc2c9f..a9800b4 100644 --- a/apps/agent/internal/device/pool.go +++ b/apps/agent/internal/device/pool.go @@ -9,10 +9,10 @@ import ( // 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/poller/poller.go b/apps/agent/internal/poller/poller.go index 870b8df..2014717 100644 --- a/apps/agent/internal/poller/poller.go +++ b/apps/agent/internal/poller/poller.go @@ -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..40411bb 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 } diff --git a/apps/agent/internal/worker/worker.go b/apps/agent/internal/worker/worker.go index aab00e6..ea009f4 100644 --- a/apps/agent/internal/worker/worker.go +++ b/apps/agent/internal/worker/worker.go @@ -1,6 +1,7 @@ package worker import ( + "errors" "fmt" "log" "strings" @@ -12,6 +13,7 @@ import ( "drmdecryption/apps/agent/internal/client" "drmdecryption/apps/agent/internal/device" + "drmdecryption/apps/agent/internal/poller" "drmdecryption/apps/agent/internal/queue" ) @@ -69,6 +71,8 @@ func (w *Worker) tick() { return } w.logf("job=%d failed: %v", job.ID, err) + w.event(job, client.EventCaptureFailed, err.Error(), + map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts}) _ = w.Queue.MarkFailed(job.ID, err.Error(), false) return } @@ -80,6 +84,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 +107,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 @@ -137,9 +150,31 @@ 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) } + // 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": poller.ValidKeyPair(res.Key), + }) return nil } +// 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..05400c7 100644 --- a/apps/agent/internal/wsclient/wsclient.go +++ b/apps/agent/internal/wsclient/wsclient.go @@ -10,16 +10,39 @@ import ( "time" "github.com/gorilla/websocket" + + "drmdecryption/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) + stop chan struct{} } @@ -47,7 +70,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 +99,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", "drm-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 +142,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 +171,28 @@ 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) + } + } +} + 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/capturecmd/capturecmd.go b/apps/capture/capturecmd/capturecmd.go index 240c54f..8c93c66 100644 --- a/apps/capture/capturecmd/capturecmd.go +++ b/apps/capture/capturecmd/capturecmd.go @@ -3,8 +3,11 @@ package capturecmd import ( + "encoding/json" "flag" "fmt" + "os" + "path/filepath" "strings" "time" "unicode" @@ -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/cli/main.go b/apps/cli/main.go index 5aab463..3db10b7 100644 --- a/apps/cli/main.go +++ b/apps/cli/main.go @@ -5,6 +5,10 @@ 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" @@ -102,7 +106,7 @@ func usage() { Usage: drm [--modules-dir DIR] modules - drm [--modules-dir DIR] capture --app NAME [--channel ID] [--wvd PATH] + drm [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--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 …] diff --git a/apps/modules/all/all_test.go b/apps/modules/all/all_test.go index fd6113b..9639faa 100644 --- a/apps/modules/all/all_test.go +++ b/apps/modules/all/all_test.go @@ -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/c4/c4.go b/apps/modules/c4/c4.go new file mode 100644 index 0000000..4757ef6 --- /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" + + "drmdecryption/adb" + appreg "drmdecryption/app" + "drmdecryption/capture" + "drmdecryption/modules/provider" + "drmdecryption/mpd" + "drmdecryption/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..fd8d192 --- /dev/null +++ b/apps/modules/c4/config.go @@ -0,0 +1,116 @@ +package c4 + +import ( + "time" + + "drmdecryption/modcfg" + "drmdecryption/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..fd60461 --- /dev/null +++ b/apps/modules/c4/steps.go @@ -0,0 +1,175 @@ +package c4 + +import ( + "fmt" + "regexp" + "strings" + "time" + + "drmdecryption/adb" + "drmdecryption/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/my5/config.go b/apps/modules/my5/config.go new file mode 100644 index 0000000..9b7e6e8 --- /dev/null +++ b/apps/modules/my5/config.go @@ -0,0 +1,133 @@ +package my5 + +import ( + "time" + + "drmdecryption/modcfg" + "drmdecryption/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..94c46de --- /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" + + "drmdecryption/adb" + appreg "drmdecryption/app" + "drmdecryption/capture" + "drmdecryption/modules/provider" + "drmdecryption/mpd" + "drmdecryption/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..9c6c996 --- /dev/null +++ b/apps/modules/my5/steps.go @@ -0,0 +1,265 @@ +package my5 + +import ( + "fmt" + "sort" + "strings" + "time" + + "drmdecryption/adb" + "drmdecryption/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/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 819a558..3a180b7 100644 --- a/apps/pkg/app/app.go +++ b/apps/pkg/app/app.go @@ -89,6 +89,19 @@ 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/capture/capture.go b/apps/pkg/capture/capture.go index 35ee985..f4e30e4 100644 --- a/apps/pkg/capture/capture.go +++ b/apps/pkg/capture/capture.go @@ -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/modhost/protocol.go b/apps/pkg/modhost/protocol.go index 2eaad7f..4fbade8 100644 --- a/apps/pkg/modhost/protocol.go +++ b/apps/pkg/modhost/protocol.go @@ -22,13 +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"` - 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"` - 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 e617241..6932567 100644 --- a/apps/pkg/modhost/remote_app.go +++ b/apps/pkg/modhost/remote_app.go @@ -82,6 +82,8 @@ 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 { @@ -93,6 +95,28 @@ func (r *RemoteApp) MitmHosts() []string { 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" @@ -126,11 +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.MitmHostList = (*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/phonecap/phonecap.go b/apps/pkg/phonecap/phonecap.go index e8ae111..776335c 100644 --- a/apps/pkg/phonecap/phonecap.go +++ b/apps/pkg/phonecap/phonecap.go @@ -199,6 +199,9 @@ 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 @@ -253,6 +256,9 @@ func Run(opt Options) (res Result, err error) { } localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log") localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json") + // Fresh local mirrors each run so grab-all does not reuse a prior channel's MPD. + _ = os.WriteFile(localLog, nil, 0o644) + _ = os.Remove(localCap) stop := make(chan struct{}) go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop) defer close(stop) @@ -273,13 +279,28 @@ func Run(opt Options) (res Result, err error) { keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode())) } // Brightcove/HLS: proxy often captures license + master URL but not PSSH. + // C4 MPDs list PlayReady before Widevine — replace a PlayReady blob. // 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) + mpdForPSSH := strings.TrimSpace(capData.Get("mpd")) + curPSSH := strings.TrimSpace(capData.Get("pssh")) + needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH) + if needPSSH && mpdForPSSH != "" { + 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) + } + } else 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) + } } } } @@ -296,7 +317,7 @@ func Run(opt Options) (res Result, err error) { fmt.Println("=========================") fmt.Println() fmt.Println("[+] Capture:") - for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh"} { + for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} { v := capData.Get(k) if k == "license_url" { v = first(v, licenseURL) @@ -305,8 +326,12 @@ func Run(opt Options) (res Result, err error) { continue } label := k - if k == "license_url" { + 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)) } @@ -318,19 +343,31 @@ func Run(opt Options) (res Result, err error) { var kerr error key, kerr = fetchKey(opt, root, capData, licenseURL) if kerr != nil { - return res, kerr + // Allow MPD-only sessions when no .wvd was passed (grab-all / first pass), + // unless the app requires keys (e.g. c4). + softOK := strings.Contains(kerr.Error(), "requires --wvd") + if softOK { + if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() { + return res, kerr + } + fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr) + } else { + return res, kerr + } + } else { + fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | ")) } - fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | ")) } 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 { @@ -393,6 +430,7 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st 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" { @@ -403,6 +441,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. @@ -411,6 +454,12 @@ 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) } @@ -453,6 +502,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/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/wvkey/wvkey.go b/apps/pkg/wvkey/wvkey.go index 7516fa2..48ec924 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,10 +49,15 @@ 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) { +// 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 := opt.Python if py == "" { py = findPython() @@ -73,12 +80,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") 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/streamd/README.md b/apps/streamd/README.md index 6dd642a..7efabc8 100644 --- a/apps/streamd/README.md +++ b/apps/streamd/README.md @@ -7,61 +7,67 @@ single binary as `drm serve`. 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/drm serve --bind 127.0.0.1:8083 --data .cache/streamd ``` -Port 8083 by default, to stay clear of anything already on 8080/8081. On start, -missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE, mp4decrypt) -unless you pass `--skip-deps`. Flags / env still win when set. +`--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. -Add a stream with an `.mpd` URL; Widevine keys are optional for clear content. -Optional per-stream SOCKS5/HTTP `proxy` routes origin fetches (geo egress). +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?}` — key optional; 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/internal/api/api.go b/apps/streamd/internal/api/api.go index 718dfe9..0ae4089 100644 --- a/apps/streamd/internal/api/api.go +++ b/apps/streamd/internal/api/api.go @@ -4,13 +4,16 @@ import ( "encoding/json" "errors" "io" + "log/slog" "net/http" "strconv" "strings" "time" + "drmdecryption/apps/streamd/internal/auth" "drmdecryption/apps/streamd/internal/db" "drmdecryption/apps/streamd/internal/deps" + "drmdecryption/apps/streamd/internal/httpx" ) type Supervisor interface { @@ -19,63 +22,103 @@ 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 + 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) 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), - "deps": h.Deps, - }) + } + // 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()) @@ -85,11 +128,15 @@ func (h *Handler) streams(w http.ResponseWriter, r *http.Request) { list = []db.Stream{} } for i := range list { - h.enrichVariantHealth(&list[i]) + 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 @@ -102,8 +149,11 @@ func (h *Handler) streams(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, err.Error()) return } - h.enrichVariantHealth(&st) - 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") } @@ -131,18 +181,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 } - h.enrichVariantHealth(&st) - 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 @@ -156,6 +252,7 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, err.Error()) return } + 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) { @@ -166,13 +263,16 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) { } st, _ = h.Store.GetStream(id) } - h.enrichVariantHealth(&st) - 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) } @@ -180,10 +280,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) @@ -191,6 +295,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()) @@ -198,10 +303,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 { @@ -212,10 +320,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) @@ -223,6 +335,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()) @@ -230,10 +343,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 @@ -246,6 +393,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 { @@ -256,10 +407,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 { @@ -277,10 +431,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 { @@ -298,6 +456,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)) @@ -322,8 +508,50 @@ func writeErr(w http.ResponseWriter, code int, msg string) { writeJSON(w, code, map[string]any{"error": msg}) } +// 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("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, -// or variants that the live NRE/ffmpeg worker is already using. +// 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 @@ -342,5 +570,15 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool { 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..179290a 100644 --- a/apps/streamd/internal/api/apps.go +++ b/apps/streamd/internal/api/apps.go @@ -3,6 +3,7 @@ package api import ( "net/http" + "drmdecryption/apps/streamd/internal/auth" "drmdecryption/modhost" "drmdecryption/mpd" "drmdecryption/repo" @@ -28,6 +29,9 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) { 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()) if err != nil { diff --git a/apps/streamd/internal/api/control.go b/apps/streamd/internal/api/control.go new file mode 100644 index 0000000..7cb3723 --- /dev/null +++ b/apps/streamd/internal/api/control.go @@ -0,0 +1,620 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "drmdecryption/apps/streamd/internal/auth" + "drmdecryption/apps/streamd/internal/db" + "drmdecryption/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, + 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 own proxy, so a geo-restricted origin is + // probed the same way the downloader would reach it. + if proxy := strings.TrimSpace(st.Proxy); 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/events.go b/apps/streamd/internal/api/events.go new file mode 100644 index 0000000..8943dbf --- /dev/null +++ b/apps/streamd/internal/api/events.go @@ -0,0 +1,383 @@ +package api + +import ( + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "drmdecryption/apps/streamd/internal/auth" + "drmdecryption/apps/streamd/internal/db" + "drmdecryption/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) + 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, + } + 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 index 066e661..b04a480 100644 --- a/apps/streamd/internal/api/modules.go +++ b/apps/streamd/internal/api/modules.go @@ -12,6 +12,7 @@ import ( "regexp" "strings" + "drmdecryption/apps/streamd/internal/auth" "drmdecryption/modhost" "drmdecryption/repo" ) @@ -29,6 +30,12 @@ func (h *Handler) modules(w http.ResponseWriter, r *http.Request) { path := strings.TrimPrefix(r.URL.Path, "/api/modules") path = strings.Trim(path, "/") + // Module metadata describes the provider plugins installed on this host, + // so even reading it needs a principal. + if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { + return + } + switch { case path == "" && r.Method == http.MethodGet: h.listModules(w, r) @@ -74,7 +81,10 @@ func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) } func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) { - if !h.auth(w, r) { + // Writing a module.yaml changes how streams are captured on this host: + // operator, and recorded. + p, ok := auth.Guard(w, r, auth.RoleOperator) + if !ok { return } if !moduleNameRe.MatchString(name) { @@ -117,6 +127,8 @@ func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) } info := moduleYAMLInfo(modDir, name) + h.audit(r, p, http.StatusOK, "uploaded module.yaml for "+name) + h.logger().Info("module.yaml updated", "module", name, "by", p.Actor(), "sha256", info.YAMLSHA256) writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "module": info, diff --git a/apps/streamd/internal/api/variants.go b/apps/streamd/internal/api/variants.go index ead583c..69da377 100644 --- a/apps/streamd/internal/api/variants.go +++ b/apps/streamd/internal/api/variants.go @@ -9,6 +9,10 @@ import ( "drmdecryption/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 { @@ -27,28 +31,90 @@ func (h *Handler) enrichVariantHealth(st *db.Stream) { v.Health = "off" continue } - if v.Height <= 0 { + if v.IsSource() { v.Health = st.Health v.PlaylistAgeS = st.PlaylistAgeS continue } - dirName := st.Name + "-" + v.ID - index := filepath.Join(www, dirName, "index.m3u8") - fi, err := os.Stat(index) - if err != nil { - if st.Health == "ok" || st.Health == "starting" { - v.Health = "starting" + 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 { - v.Health = st.Health + l.Health = st.Health } continue } - age := time.Since(fi.ModTime()).Seconds() - v.PlaylistAgeS = age - if age > 45 { - v.Health = "down" - } else { - v.Health = "ok" + 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..b4a7df4 --- /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" + + "drmdecryption/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..40290d0 --- /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" + + "drmdecryption/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..db2e5a1 --- /dev/null +++ b/apps/streamd/internal/auth/middleware.go @@ -0,0 +1,238 @@ +package auth + +import ( + "context" + "encoding/json" + "net/http" + "strconv" + "strings" + "time" + + "drmdecryption/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 1a42064..522e009 100644 --- a/apps/streamd/internal/db/db.go +++ b/apps/streamd/internal/db/db.go @@ -14,12 +14,28 @@ 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"` + Description string `json:"description"` + Tags string `json:"tags"` App string `json:"app"` Channel string `json:"channel"` MPD string `json:"mpd"` @@ -31,6 +47,12 @@ type Stream struct { 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"` @@ -45,42 +67,80 @@ type Stream struct { // 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"` + 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"` - Proxy string `json:"proxy"` - 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"` + 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"` + 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"` - Proxy *string `json:"proxy"` - 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"` + 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"` + 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 { @@ -156,10 +216,30 @@ CREATE TABLE IF NOT EXISTS agent_claims ( if err != nil { return err } - // Older DBs created before proxy / variants existed. - _, _ = s.DB.Exec(`ALTER TABLE streams ADD COLUMN proxy TEXT NOT NULL DEFAULT ''`) - _, _ = s.DB.Exec(`ALTER TABLE streams ADD COLUMN variants_json TEXT NOT NULL DEFAULT ''`) - return nil + // 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`, + } { + _, _ = s.DB.Exec(stmt) + } + if err := s.migrateHistory(); err != nil { + return err + } + if err := s.migrateSettings(); err != nil { + return err + } + return s.migrateSchedules() } func now() string { @@ -185,9 +265,13 @@ func slug(name string) string { } const streamSelect = ` -SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json, +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,''), s.video_select, s.audio_select, s.enabled, s.rewriter, - COALESCE(s.variants_json,''), s.created_at, s.updated_at, + 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,''), @@ -218,16 +302,25 @@ func (s *Store) GetStream(id int64) (Stream, error) { 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) +} + type rowScanner interface { Scan(dest ...any) error } 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.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.VariantsJSON, + &st.ID, &st.Name, &st.Title, &st.Description, &st.Tags, + &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON, + &st.Proxy, &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, @@ -236,6 +329,11 @@ 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" } @@ -243,6 +341,7 @@ func scanStream(row rowScanner) (Stream, error) { 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()) { @@ -250,9 +349,127 @@ 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) != "" + 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. @@ -266,7 +483,7 @@ func AttachVariantStatuses(streamName, variantsJSON, streamHealth string, playli } if !v.Enabled { vs.Health = "off" - } else if v.Height <= 0 { + } else if v.Height <= 0 && !v.AudioOnly { vs.Health = streamHealth vs.PlaylistAgeS = playlistAge } else { @@ -277,6 +494,17 @@ func AttachVariantStatuses(streamName, variantsJSON, streamHealth string, playli 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 == "" { @@ -288,38 +516,55 @@ 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 := strings.TrimSpace(in.VariantsJSON) - if len(in.Variants) > 0 { - encoded, err := EncodeVariantsJSON(in.Variants) - if err != nil { - return Stream{}, err - } - variantsJSON = encoded - } else if variantsJSON == "" { - variantsJSON, _ = EncodeVariantsJSON(DefaultVariants()) - } else { - encoded, err := EncodeVariantsJSON(ParseVariantsJSON(variantsJSON)) - if err != nil { - return Stream{}, err - } - variantsJSON = encoded + 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,proxy,video_select,audio_select,enabled,rewriter,variants_json,created_at,updated_at) -VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, - name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy), - in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, ts, ts) +INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy, + 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), + in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON, + settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts) if err != nil { return Stream{}, err } @@ -329,6 +574,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 { @@ -337,6 +627,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 } @@ -367,18 +663,50 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) { if in.Rewriter != nil { cur.Rewriter = *in.Rewriter } - if len(in.Variants) > 0 { - encoded, err := EncodeVariantsJSON(in.Variants) + 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 } - cur.VariantsJSON = encoded - } else if in.VariantsJSON != nil { - encoded, err := EncodeVariantsJSON(ParseVariantsJSON(*in.VariantsJSON)) + 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 } - cur.VariantsJSON = encoded + if encoded != "" { + cur.OutputsJSON = encoded + } } enabled := 0 if cur.Enabled { @@ -391,12 +719,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=?, proxy=?, - video_select=?, audio_select=?, enabled=?, rewriter=?, variants_json=?, updated_at=? WHERE id=?`, - cur.Title, cur.App, cur.Channel, cur.MPD, cur.Key, cur.HeadersJSON, cur.Proxy, - cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, cur.VariantsJSON, ts, id) +UPDATE streams SET title=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?, + headers_json=?, proxy=?, 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.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 } @@ -554,21 +894,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/events.go b/apps/streamd/internal/db/events.go new file mode 100644 index 0000000..426285d --- /dev/null +++ b/apps/streamd/internal/db/events.go @@ -0,0 +1,438 @@ +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 + } + 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/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 index e7099ee..d6e025c 100644 --- a/apps/streamd/internal/db/variants.go +++ b/apps/streamd/internal/db/variants.go @@ -6,9 +6,14 @@ import ( "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"` @@ -16,6 +21,10 @@ type VariantSpec struct { 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. @@ -26,12 +35,19 @@ type VariantStatus struct { PlaylistAgeS float64 `json:"playlist_age_s,omitempty"` } -// DefaultVariants returns the FHD + optional HD/SD ladder with only FHD enabled. +// 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: "fhd", Label: "FHD", Enabled: true, Height: 0}, + {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"}, } } @@ -48,16 +64,37 @@ func ParseVariantsJSON(raw string) []VariantSpec { return NormalizeVariants(list) } -// NormalizeVariants fills ids/labels/bitrates and ensures an FHD/source entry exists. +// 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 = "fhd" + v.ID = SourceVariantID } else { v.ID = fmt.Sprintf("%dp", v.Height) } @@ -74,8 +111,8 @@ func NormalizeVariants(in []VariantSpec) []VariantSpec { } if v.Height == 0 { hasSource = true - v.ID = "fhd" - if v.Label == "" || strings.EqualFold(v.Label, "fhd") { + 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 @@ -103,7 +140,7 @@ func NormalizeVariants(in []VariantSpec) []VariantSpec { out = append(out, v) } if !hasSource { - out = append([]VariantSpec{{ID: "fhd", Label: "FHD", Enabled: true, Height: 0}}, out...) + out = append([]VariantSpec{{ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0}}, out...) } return out } @@ -121,19 +158,71 @@ func EncodeVariantsJSON(list []VariantSpec) (string, error) { // 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 == "fhd" { + if height <= 0 || variantID == "" || variantID == SourceVariantID { return "/hls/" + streamName + "/index.m3u8" } return "/hls/" + streamName + "-" + variantID + "/index.m3u8" } -// ScaledVariants returns enabled non-source (transcode) variants. +// 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.Height > 0 { + 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 index 6ce40ce..1f21c39 100644 --- a/apps/streamd/internal/db/variants_test.go +++ b/apps/streamd/internal/db/variants_test.go @@ -22,11 +22,296 @@ func TestNormalizeVariantsEnsuresFHD(t *testing.T) { func TestParseVariantsJSONDefault(t *testing.T) { got := ParseVariantsJSON("") - if len(got) != 3 { - t.Fatalf("default len=%d", len(got)) + // 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())) } - scaled := ScaledVariants(got) - if len(scaled) != 0 { - t.Fatalf("default scaled=%v", scaled) + 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/deps.go b/apps/streamd/internal/deps/deps.go index 9a2d02f..7ee72b9 100644 --- a/apps/streamd/internal/deps/deps.go +++ b/apps/streamd/internal/deps/deps.go @@ -19,13 +19,25 @@ import ( // 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"` + 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 diff --git a/apps/streamd/internal/hlsgate/hlsgate.go b/apps/streamd/internal/hlsgate/hlsgate.go new file mode 100644 index 0000000..0005dbd --- /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" + + "drmdecryption/apps/streamd/internal/auth" + "drmdecryption/apps/streamd/internal/db" + "drmdecryption/apps/streamd/internal/httpx" + "drmdecryption/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..01c318b --- /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" + + "drmdecryption/apps/streamd/internal/auth" + "drmdecryption/apps/streamd/internal/db" + "drmdecryption/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..a4598f8 --- /dev/null +++ b/apps/streamd/internal/logfile/logfile.go @@ -0,0 +1,211 @@ +// 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 +} + +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/scheduler/scheduler.go b/apps/streamd/internal/scheduler/scheduler.go new file mode 100644 index 0000000..c8c40cf --- /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" + + "drmdecryption/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..24725bd 100644 --- a/apps/streamd/internal/supervisor/appdefaults.go +++ b/apps/streamd/internal/supervisor/appdefaults.go @@ -9,15 +9,19 @@ import ( "drmdecryption/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..f41eb39 100644 --- a/apps/streamd/internal/supervisor/appdefaults_test.go +++ b/apps/streamd/internal/supervisor/appdefaults_test.go @@ -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..dcbcf8b --- /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" + + "drmdecryption/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 7ec9133..cc14d53 100644 --- a/apps/streamd/internal/supervisor/media.go +++ b/apps/streamd/internal/supervisor/media.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" "io" - "log" + "log/slog" "os" "os/exec" "path/filepath" @@ -15,45 +15,69 @@ import ( "time" "drmdecryption/apps/streamd/internal/db" + "drmdecryption/apps/streamd/internal/logfile" + "drmdecryption/apps/streamd/internal/tsfanout" "drmdecryption/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 mu sync.Mutex procs map[int64]*streamProc stopMon chan struct{} } +// 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 - variants []*variantProc + id int64 + name string + nre *exec.Cmd + ffmpeg *exec.Cmd + started time.Time + workDir string + wwwDir string + tsPath string + hlsIndex string + nreLog *logfile.Writer + 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. @@ -63,13 +87,20 @@ type Options struct { NRE string FFmpeg string MP4Decrypt string - Log *log.Logger + Log *slog.Logger + Fanout *tsfanout.Set + Notifier Notifier + ViewersFn func(streamName string) int } 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, @@ -78,6 +109,9 @@ func NewMedia(opt Options) *Media { FFmpeg: opt.FFmpeg, MP4Decrypt: opt.MP4Decrypt, Log: lg, + Fanout: fan, + Notifier: opt.Notifier, + ViewersFn: opt.ViewersFn, procs: map[int64]*streamProc{}, stopMon: make(chan struct{}), } @@ -98,34 +132,33 @@ 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) Start(id int64) error { st, err := m.Store.GetStream(id) if err != nil { return err } if strings.TrimSpace(st.MPD) == "" { - _ = m.Store.SetRuntime(id, db.RuntimePatch{ - Health: "down", - PlayPath: "/hls/" + st.Name + "/index.m3u8", - LastError: "missing mpd — paste a manifest URL (keys optional for clear streams)", - }) + 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") } @@ -144,13 +177,14 @@ 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 _, v := range db.ScaledVariants(variantSpecs) { - _ = os.RemoveAll(filepath.Join(m.DataDir, "www", st.Name+"-"+v.ID)) + _ = os.RemoveAll(filepath.Join(m.DataDir, "www", db.VariantDir(st.Name, v.ID, v.Height, v.AudioOnly))) } - for _, d := range []string{workDir, wwwDir, filepath.Join(m.DataDir, "logs")} { + for _, d := range []string{workDir, wwwDir, m.logsDir()} { if err := os.MkdirAll(d, 0o755); err != nil { return err } @@ -160,39 +194,34 @@ func (m *Media) Start(id int64) error { hasKeys := strings.TrimSpace(st.Key) != "" if hasKeys { keysBody := normalizeKeysFile(st.Key) - if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil { + // 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()) 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, st.Proxy) 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) @@ -219,8 +248,9 @@ func (m *Media) Start(id int64) error { } if proxy := strings.TrimSpace(st.Proxy); 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.logf("stream %s: origin proxy %s", st.Name, 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 @@ -242,10 +272,13 @@ 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) + // A rotating log opened with a start banner, rather than truncated. The + // previous run's output is exactly what you need when working out why + // this run is happening. + nreLog, err := logfile.OpenWithBanner( + filepath.Join(m.logsDir(), st.Name+"-nre.log"), + logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre") if err != nil { return err } @@ -278,10 +311,10 @@ func (m *Media) Start(id int64) error { 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) + m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid) sp := &streamProc{ id: id, @@ -296,6 +329,8 @@ func (m *Media) Start(id int64) error { mpdProxy: mpdProxy, variantSpecs: variantSpecs, + outputSpecs: outputSpecs, + cfg: cfg, tsReadyBytes: cfg.TSReadyBytes, } @@ -303,6 +338,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() @@ -316,6 +357,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) @@ -344,6 +413,10 @@ func (m *Media) bootstrapHLS(sp *streamProc) { PlayPath: "/hls/" + sp.name + "/index.m3u8", LastError: "NRE exited before TS was ready — see 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 logs/" + sp.name + "-nre.log", + }) m.cleanupProc(sp.id) return } @@ -355,17 +428,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) @@ -377,46 +459,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 { @@ -427,14 +530,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() @@ -480,21 +585,33 @@ 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 } 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) } @@ -505,14 +622,10 @@ func (m *Media) cleanupProc(id int64) { if !ok { return } - if sp.nreLog != nil { - _ = sp.nreLog.Close() - } - if sp.ffOutLog != nil { - _ = sp.ffOutLog.Close() - } - if sp.ffErrLog != nil { - _ = sp.ffErrLog.Close() + for _, w := range []*logfile.Writer{sp.nreLog, sp.ffOutLog, sp.ffErrLog} { + if w != nil { + _ = w.Close() + } } delete(m.procs, id) } @@ -563,6 +676,12 @@ func (m *Media) refreshHealth(id int64) { Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime, LastError: "NRE process exited — see 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 logs/%s-nre.log", uptime, sp.name), + }) + m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime)) + m.report(sp, "down") m.cleanupProc(id) return } @@ -573,6 +692,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) @@ -586,16 +706,88 @@ 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) { m.mu.Lock() cur, ok := m.procs[sp.id] @@ -620,9 +812,13 @@ 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 @@ -637,10 +833,7 @@ func (m *Media) restartFFmpeg(sp *streamProc) { } m.mu.Unlock() m.startVariantPackagers(sp, specs) -} - -func (m *Media) logf(format string, args ...any) { - m.Log.Printf("supervisor: "+format, args...) + m.writeMasterPlaylist(sp) } func headerMap(headersJSON string) map[string]string { @@ -675,25 +868,19 @@ 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 { @@ -702,8 +889,7 @@ func killProcess(cmd *exec.Cmd) error { } pid := cmd.Process.Pid if runtime.GOOS == "windows" { - _ = exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run() - return nil + return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run() } return cmd.Process.Kill() } @@ -745,8 +931,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) { @@ -767,10 +951,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..12d443f --- /dev/null +++ b/apps/streamd/internal/supervisor/outputs.go @@ -0,0 +1,299 @@ +package supervisor + +import ( + "fmt" + "path/filepath" + "strconv" + "strings" + + "drmdecryption/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..76c4000 --- /dev/null +++ b/apps/streamd/internal/supervisor/outputs_test.go @@ -0,0 +1,389 @@ +package supervisor + +import ( + "strings" + "testing" + + "drmdecryption/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/variants.go b/apps/streamd/internal/supervisor/variants.go index bb58b43..324786d 100644 --- a/apps/streamd/internal/supervisor/variants.go +++ b/apps/streamd/internal/supervisor/variants.go @@ -2,12 +2,15 @@ package supervisor import ( "fmt" + "io" "os" "os/exec" "path/filepath" + "sort" "strings" "drmdecryption/apps/streamd/internal/db" + "drmdecryption/apps/streamd/internal/logfile" ) type variantProc struct { @@ -15,8 +18,8 @@ type variantProc struct { wwwDir string index string cmd *exec.Cmd - outLog *os.File - errLog *os.File + outLog *logfile.Writer + errLog *logfile.Writer dead bool } @@ -43,12 +46,16 @@ func (m *Media) startVariantPackagers(sp *streamProc, specs []db.VariantSpec) { for _, spec := range scaled { vp, err := m.spawnVariantFFmpeg(sp, spec) if err != nil { - m.logf("stream %s variant %s: %v", sp.name, spec.ID, err) + 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.logf("stream %s: variant %s (%dp) pid=%d → %s", - sp.name, spec.ID, spec.Height, vp.cmd.Process.Pid, vp.index) + 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() @@ -65,84 +72,76 @@ func (m *Media) startVariantPackagers(sp *streamProc, specs []db.VariantSpec) { } func (m *Media) spawnVariantFFmpeg(sp *streamProc, spec db.VariantSpec) (*variantProc, error) { - dirName := sp.name + "-" + spec.ID + 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 } - index := filepath.Join(wwwDir, "index.m3u8") - outPath := filepath.Join(m.DataDir, "logs", dirName+"-ffmpeg.out.log") - errPath := filepath.Join(m.DataDir, "logs", dirName+"-ffmpeg.err.log") - outF, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) + 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 } - errF, err := os.OpenFile(errPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) - if err != nil { - _ = outF.Close() - 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 } - vBitrate := spec.VideoBitrate - if vBitrate == "" { - vBitrate = "2800k" - } - aBitrate := spec.AudioBitrate - if aBitrate == "" { - aBitrate = "128k" - } - scale := fmt.Sprintf("scale=-2:%d", spec.Height) - - ffArgs := []string{ - "-hide_banner", "-loglevel", "warning", "-y", - "-follow", "1", - "-analyzeduration", "20M", - "-probesize", "10M", - "-fflags", "+genpts", - "-i", sp.tsPath, - "-map", "0:v:0", - "-map", "0:a:0?", - "-vf", scale, - "-c:v", "libx264", - "-preset", "veryfast", - "-tune", "zerolatency", - "-b:v", vBitrate, - "-maxrate", vBitrate, - "-bufsize", doubleBitrate(vBitrate), - "-g", "48", - "-keyint_min", "48", - "-sc_threshold", "0", - "-c:a", "aac", - "-b:a", aBitrate, - "-ac", "2", - "-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(wwwDir, "seg_%05d.ts"), - index, - } - - 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 nil, err } vp := &variantProc{ spec: spec, wwwDir: wwwDir, - index: index, + index: filepath.Join(wwwDir, "index.m3u8"), cmd: ffCmd, - outLog: outF, - errLog: errF, + outLog: outLog, + errLog: errLog, } go func() { _ = ffCmd.Wait() @@ -159,24 +158,13 @@ func (m *Media) spawnVariantFFmpeg(sp *streamProc, spec db.VariantSpec) (*varian return vp, nil } +// doubleBitrate is the -bufsize that pairs with a -maxrate. func doubleBitrate(b string) string { - b = strings.TrimSpace(b) - if b == "" { + n := db.BitrateBps(b) + if n <= 0 { return "5600k" } - num := 0 - unit := "" - for i, r := range b { - if r < '0' || r > '9' { - unit = b[i:] - break - } - num = num*10 + int(r-'0') - } - if num <= 0 { - return "5600k" - } - return fmt.Sprintf("%d%s", num*2, unit) + return fmt.Sprintf("%dk", n*2/1000) } func (m *Media) stopVariant(vp *variantProc) { @@ -186,11 +174,10 @@ func (m *Media) stopVariant(vp *variantProc) { if vp.cmd != nil && vp.cmd.Process != nil { _ = killProcess(vp.cmd) } - if vp.outLog != nil { - _ = vp.outLog.Close() - } - if vp.errLog != nil { - _ = vp.errLog.Close() + for _, w := range []*logfile.Writer{vp.outLog, vp.errLog} { + if w != nil { + _ = w.Close() + } } } @@ -225,9 +212,11 @@ func (m *Media) restartDeadVariants(sp *streamProc) { 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.logf("stream %s variant %s restart: %v", sp.name, vp.spec.ID, err) + m.Log.Error("variant restart failed", "stream", sp.name, "variant", vp.spec.ID, "err", err) continue } m.mu.Lock() @@ -239,7 +228,103 @@ func (m *Media) restartDeadVariants(sp *streamProc) { return } m.mu.Unlock() - m.logf("stream %s: restarted variant %s", sp.name, vp.spec.ID) + 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 2e2091d..0000000 --- a/apps/streamd/internal/ui/app.css +++ /dev/null @@ -1,211 +0,0 @@ -:root { - --bg: #0f1115; - --card: #171a21; - --border: #2a303c; - --text: #e8eaed; - --muted: #9aa0a6; - --accent: #7aa2ff; - --ok: #3dd68c; - --degraded: #f5a524; - --down: #f07178; - --stopped: #6b7280; - --chip: #1c2230; -} -* { 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; flex-wrap: wrap; } -.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; } -button.tiny { - padding: 3px 8px; - font-size: 11px; - line-height: 1.2; -} -.actions { display: flex; gap: 8px; align-items: end; } -.token-box input { width: 180px; } -.row-between { display: flex; justify-content: space-between; align-items: center; gap: 12px; } -.table-wrap { overflow-x: auto; } -table { width: 100%; border-collapse: collapse; } -th, td { text-align: left; padding: 10px 6px; border-bottom: 1px solid var(--border); vertical-align: top; } -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, .pill.pending { color: var(--down); } -.pill.stopped, .pill.off { color: var(--stopped); } -.pill.claim { color: #c4b5fd; background: #1f1635; } -.row-actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } -.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); } -code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; } - -.variants-field { - border: 1px solid var(--border); - border-radius: 8px; - padding: 12px; - margin: 0; -} -.variants-field legend { - padding: 0 6px; - color: var(--text); - font-size: 12px; - font-weight: 600; -} -.hint { margin: 0 0 10px; color: var(--muted); font-size: 12px; } -.variant-toggles { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 8px; -} -.variant-card { - display: grid; - grid-template-columns: auto 1fr; - grid-template-rows: auto auto; - column-gap: 8px; - row-gap: 2px; - align-items: center; - padding: 10px 12px; - border: 1px solid var(--border); - border-radius: 8px; - background: #12151c; - cursor: pointer; - color: var(--text); -} -.variant-card input { - grid-row: 1 / span 2; - width: 16px; - height: 16px; - accent-color: var(--accent); -} -.variant-card .v-title { font-weight: 600; font-size: 13px; color: var(--text); } -.variant-card .v-meta { font-size: 11px; color: var(--muted); } -.variant-card.on, -.variant-card:has(input:checked) { - border-color: #3b82f6; - background: #152033; - box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.25); -} -.variant-card.locked { - opacity: 0.92; - cursor: default; -} - -.link-stack { display: flex; flex-direction: column; gap: 6px; min-width: 180px; } -.link-row { - display: flex; - align-items: center; - gap: 6px; - flex-wrap: wrap; - padding: 6px 8px; - background: var(--chip); - border: 1px solid var(--border); - border-radius: 8px; -} -.link-row .v-label { - font-size: 11px; - font-weight: 700; - letter-spacing: 0.02em; - min-width: 2.4em; - color: var(--accent); -} -.link-row .v-path { - flex: 1; - min-width: 0; - font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; - font-size: 11px; - color: var(--muted); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.link-row .pill { margin-left: auto; } - -.toast { - position: fixed; - right: 16px; - bottom: 16px; - background: #1e293b; - border: 1px solid #334155; - color: var(--text); - padding: 10px 14px; - border-radius: 8px; - box-shadow: 0 8px 24px rgba(0,0,0,.35); - z-index: 50; - font-size: 13px; -} -.toast.show { display: block; } - -dialog { - border: 1px solid var(--border); - background: var(--card); - color: var(--text); - border-radius: 8px; - padding: 16px; - min-width: min(640px, 94vw); -} -dialog::backdrop { background: rgba(0,0,0,.55); } -@media (max-width: 720px) { - .grid { grid-template-columns: 1fr; } - .span2 { grid-column: span 1; } - .variant-toggles { grid-template-columns: 1fr; } - 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 b46ebb4..0000000 --- a/apps/streamd/internal/ui/app.js +++ /dev/null @@ -1,440 +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"); - const toastEl = document.getElementById("toast"); - - 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 absURL(path) { - if (!path) return ""; - try { return new URL(path, location.origin).href; } catch { return path; } - } - - let toastTimer = null; - function toast(msg) { - if (!toastEl) return; - toastEl.hidden = false; - toastEl.classList.add("show"); - toastEl.textContent = msg; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { - toastEl.hidden = true; - toastEl.classList.remove("show"); - }, 1800); - } - - async function copyText(text) { - if (!text) return; - try { - await navigator.clipboard.writeText(text); - toast("Copied m3u8 link"); - } catch { - const ta = document.createElement("textarea"); - ta.value = text; - ta.style.position = "fixed"; - ta.style.left = "-9999px"; - document.body.appendChild(ta); - ta.select(); - try { document.execCommand("copy"); toast("Copied m3u8 link"); } - catch { toast("Copy failed"); } - ta.remove(); - } - } - - 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 enabledVariants(s) { - const list = Array.isArray(s.variants) ? s.variants : []; - const enabled = list.filter((v) => v && v.enabled !== false && v.health !== "off"); - if (enabled.length) return enabled; - return [{ - id: "fhd", - label: "FHD", - enabled: true, - height: 0, - play_path: s.play_path || ("/hls/" + s.name + "/index.m3u8"), - health: s.health || "stopped", - playlist_age_s: s.playlist_age_s, - }]; - } - - function linksCell(s) { - const vars = enabledVariants(s); - return ``; - } - - 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 ? " needs MPD" : ""; - 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)} - ${linksCell(s)} - - - - - - ${s.claimed_by ? `` : ""} - - - `; - }).join(""); - } - - function esc(v) { - return String(v ?? "").replace(/[&<>"']/g, (c) => ({ - "&": "&", "<": "<", ">": ">", '"': """, "'": "'" - }[c])); - } - - function readVariantToggles(root) { - const cards = root.querySelectorAll(".variant-card input[data-id]"); - const out = []; - cards.forEach((input) => { - const id = input.dataset.id; - const height = Number(input.dataset.height || 0); - const enabled = id === "fhd" ? true : !!input.checked; - const item = { - id, - label: id.toUpperCase(), - enabled, - height: id === "fhd" ? 0 : height, - }; - if (height > 0) { - item.video_bitrate = input.dataset.vbr || ""; - item.audio_bitrate = input.dataset.abr || ""; - } - out.push(item); - }); - return out; - } - - function setVariantToggles(root, variants) { - const byId = {}; - (variants || []).forEach((v) => { byId[v.id] = v; }); - root.querySelectorAll(".variant-card input[data-id]").forEach((input) => { - const id = input.dataset.id; - if (id === "fhd") { - input.checked = true; - return; - } - const v = byId[id]; - input.checked = !!(v && v.enabled); - const card = input.closest(".variant-card"); - if (card) card.classList.toggle("on", input.checked); - }); - } - - function wireVariantCards(root) { - root.querySelectorAll(".variant-card").forEach((card) => { - const input = card.querySelector("input[type=checkbox]"); - if (!input || input.disabled) { - card.classList.add("on"); - return; - } - const sync = () => card.classList.toggle("on", input.checked); - input.addEventListener("change", sync); - sync(); - }); - } - - wireVariantCards(document.getElementById("create-variants")); - wireVariantCards(document.getElementById("edit-variants")); - - 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(", "); - } - - const depsEl = document.getElementById("deps-status"); - - function renderDeps(d) { - if (!depsEl || !d) return; - const bit = (label, path) => (path ? label + "✓" : label + "✗"); - depsEl.textContent = [ - bit("ffmpeg", d.ffmpeg), - bit("nre", d.nre), - bit("mp4decrypt", d.mp4decrypt), - ].join(" · "); - depsEl.title = [ - "bin: " + (d.bin_dir || ""), - "ffmpeg: " + (d.ffmpeg || "(missing)"), - "nre: " + (d.nre || "(missing)"), - "mp4decrypt: " + (d.mp4decrypt || "(missing)"), - ...(d.notes || []), - ].join("\n"); - } - - 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"; - renderDeps(health.deps); - render(list.streams || []); - renderAgents(agents.agents || []); - listMsg.classList.remove("err"); - } catch (e) { - listMsg.textContent = e.message; - listMsg.classList.add("err"); - } - } - - 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()); - body.variants = readVariantToggles(document.getElementById("create-variants")); - try { - await api("/api/streams", { - method: "POST", - headers: headers(true), - body: JSON.stringify(body), - }); - ev.target.reset(); - ev.target.headers_json.value = "{}"; - setVariantToggles(document.getElementById("create-variants"), [ - { id: "fhd", enabled: true }, - { id: "hd", enabled: false }, - { id: "sd", enabled: false }, - ]); - 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 act = btn.dataset.act; - if (act === "copy-link") { - copyText(btn.dataset.url || ""); - return; - } - const id = btn.dataset.id; - 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 || ""; - if (editForm.proxy) editForm.proxy.value = st.proxy || ""; - editForm.headers_json.value = st.headers_json || "{}"; - setVariantToggles(document.getElementById("edit-variants"), st.variants || []); - 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, - proxy: editForm.proxy ? editForm.proxy.value : "", - headers_json: editForm.headers_json.value, - variants: readVariantToggles(document.getElementById("edit-variants")), - }; - 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 c500223..4121147 100644 --- a/apps/streamd/internal/ui/index.html +++ b/apps/streamd/internal/ui/index.html @@ -4,128 +4,102 @@ streamd + + -
-

streamd

-
- - - -
-
- -
-

Add stream

-
- - - - - - - - -
- Output variants -

FHD is the source copy. Enable HD / SD to also publish scaled HLS playlists as separate streams.

-
- - - + +
-
- -
-
-

-
- -
-
-

Streams

-
- agents: — - -
-
-
- - - - - - - - - - - - - -
nameapp / channelhealthclaimagelinksactions
-
-

Loading…

-
- - -
-

Edit stream

- - - - - - - -
- Output variants -

Each enabled rung publishes its own m3u8. FHD stays the source; HD/SD are live-transcoded.

-
- - - +
+ Tools + —
-
-
- -
+ + +
+
+ +

Dashboard

+
+ Live + + +
+ + + +
+
+
+
+ + + +
+ +
+ + + - - - + diff --git a/apps/streamd/internal/ui/static/app.css b/apps/streamd/internal/ui/static/app.css new file mode 100644 index 0000000..93593d0 --- /dev/null +++ b/apps/streamd/internal/ui/static/app.css @@ -0,0 +1,645 @@ +/* streamd dashboard — signal amber on charcoal. + Tokens redefine for dark; components only use var(--…). */ + +:root { + color-scheme: light dark; + + --bg: #f4f2ee; + --bg-elev: #ffffff; + --bg-sunken: #ebe7e0; + --sidebar: #1a1814; + --sidebar-text: #cfc6b8; + --sidebar-active: #2a2620; + --border: #ddd6cb; + --border-strong: #c9bfb0; + --text: #16140f; + --text-dim: #6a6358; + --accent: #c47a12; + --accent-soft: #f8ecda; + --accent-ink: #ffffff; + --ok: #0f7b4f; + --ok-soft: #dcf5e8; + --warn: #9a6200; + --warn-soft: #fdf0d5; + --down: #b4232a; + --down-soft: #fde4e4; + --idle: #6a6358; + --idle-soft: #ebe7e0; + --shadow: 0 1px 2px rgba(40, 30, 16, .05), 0 6px 18px -6px rgba(40, 30, 16, .12); + --radius: 10px; + --radius-sm: 7px; + --mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; + --ease: 180ms ease; +} + +/* Charcoal dark: page and sidebar differ so the shell still reads. */ +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #141210; + --bg-elev: #1c1a17; + --bg-sunken: #0f0e0c; + --sidebar: #0c0b0a; + --sidebar-text: #cfc6b8; + --sidebar-active: #24201c; + --border: #2e2a24; + --border-strong: #3d372f; + --text: #f2ebe0; + --text-dim: #a89f90; + --accent: #e8a23a; + --accent-soft: #2a2010; + --accent-ink: #1a1408; + --ok: #3dd68c; + --ok-soft: #163024; + --warn: #e6b84d; + --warn-soft: #2a220c; + --down: #f07178; + --down-soft: #2e1414; + --idle: #a89f90; + --idle-soft: #24201c; + --shadow: 0 1px 0 rgba(255, 255, 255, .04) inset, 0 8px 24px rgba(0, 0, 0, .35); + } +} +:root[data-theme="dark"] { + --bg: #141210; + --bg-elev: #1c1a17; + --bg-sunken: #0f0e0c; + --sidebar: #0c0b0a; + --sidebar-text: #cfc6b8; + --sidebar-active: #24201c; + --border: #2e2a24; + --border-strong: #3d372f; + --text: #f2ebe0; + --text-dim: #a89f90; + --accent: #e8a23a; + --accent-soft: #2a2010; + --accent-ink: #1a1408; + --ok: #3dd68c; + --ok-soft: #163024; + --warn: #e6b84d; + --warn-soft: #2a220c; + --down: #f07178; + --down-soft: #2e1414; + --idle: #a89f90; + --idle-soft: #24201c; + --shadow: 0 1px 0 rgba(255, 255, 255, .04) inset, 0 8px 24px rgba(0, 0, 0, .35); +} + +* { box-sizing: border-box; } + +html, body { height: 100%; } + +body { + margin: 0; + font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + background: var(--bg); + color: var(--text); + -webkit-font-smoothing: antialiased; +} + +h1, h2, h3 { margin: 0; font-weight: 600; letter-spacing: -0.01em; } +h1 { font-size: 21px; } +h2 { font-size: 15px; } +h3 { font-size: 13px; font-weight: 600; } +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +.mono { font-family: var(--mono); font-size: 12px; } +.muted { color: var(--text-dim); } +.hint { color: var(--text-dim); font-size: 12px; margin: 2px 0 0; } +.spacer { flex: 1; } +.only-mobile { display: none; } +.sr-only { + position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; + overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; +} + +/* ---------- layout ---------- */ + +#app { + display: grid; + grid-template-columns: 232px 1fr; + min-height: 100vh; +} +/* Explicit display rules beat the UA [hidden] stylesheet; force hide. */ +#app[hidden], +#gate[hidden], +.stack[hidden], +[hidden] { + display: none !important; +} + +#sidebar { + background: var(--sidebar); + color: var(--sidebar-text); + display: flex; + flex-direction: column; + padding: 14px 10px; + gap: 14px; + position: sticky; + top: 0; + height: 100vh; +} + +.brand { + display: flex; + align-items: center; + gap: 9px; + padding: 2px 8px 8px; +} +.brand-name { font-weight: 600; color: #fff; font-size: 15px; letter-spacing: -0.01em; } +.logo { + width: 22px; height: 22px; border-radius: 6px; flex: 0 0 auto; + background: var(--accent); + position: relative; +} +.logo::after { + content: ""; position: absolute; left: 8px; top: 6px; + border-left: 7px solid var(--accent-ink); + border-top: 5px solid transparent; + border-bottom: 5px solid transparent; +} +.logo.big { width: 34px; height: 34px; border-radius: 9px; } +.logo.big::after { left: 12px; top: 9px; border-left-width: 11px; border-top-width: 8px; border-bottom-width: 8px; } + +#nav { display: flex; flex-direction: column; gap: 2px; } +#nav a { + display: flex; align-items: center; gap: 10px; + padding: 8px 10px; + border-radius: var(--radius-sm); + color: var(--sidebar-text); + font-size: 13.5px; +} +#nav a:hover { background: var(--sidebar-active); text-decoration: none; color: #fff; } +#nav a.active { background: var(--sidebar-active); color: #fff; font-weight: 600; } +#nav a .ico { + width: 16px; height: 16px; flex: 0 0 auto; + display: inline-flex; align-items: center; justify-content: center; + opacity: .85; +} +#nav a .ico svg { width: 16px; height: 16px; display: block; } +#nav a[hidden] { display: none; } + +.sidebar-foot { margin-top: auto; display: flex; flex-direction: column; gap: 6px; } +.chip { + padding: 6px 8px; border-radius: 6px; + background: rgba(255, 255, 255, .05); + color: var(--sidebar-text); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + font-size: 11px; +} +.chip .chip-label { + display: block; font-size: 10px; font-weight: 600; + color: rgba(255,255,255,.45); letter-spacing: .02em; margin-bottom: 1px; +} +.chip .chip-val { font-family: var(--mono); font-size: 11px; } + +#main { display: flex; flex-direction: column; min-width: 0; } + +#topbar { + display: flex; align-items: center; gap: 12px; + padding: 12px 20px; + background: var(--bg-elev); + border-bottom: 1px solid var(--border); + position: sticky; top: 0; z-index: 20; +} +#page-title { font-size: 21px; font-weight: 600; letter-spacing: -0.02em; } +.who { display: flex; align-items: center; gap: 8px; } +.conn { + display: inline-flex; align-items: center; gap: 6px; + font-size: 12px; padding: 4px 10px; border-radius: 999px; + background: var(--ok-soft); color: var(--ok); font-weight: 600; +} +.conn::before { + content: ""; width: 7px; height: 7px; border-radius: 50%; + background: currentColor; box-shadow: 0 0 0 3px color-mix(in srgb, currentColor 25%, transparent); +} +.conn.off { background: var(--down-soft); color: var(--down); } +.conn.warn { background: var(--warn-soft); color: var(--warn); } +#uptime { + font-size: 12px; color: var(--text-dim); + font-variant-numeric: tabular-nums; +} +#theme-btn { + display: inline-flex; align-items: center; gap: 6px; + font-size: 12px; font-weight: 500; color: var(--text-dim); + border: 1px solid var(--border); border-radius: var(--radius-sm); + background: transparent; padding: 5px 10px; +} +#theme-btn:hover { background: var(--bg-sunken); color: var(--text); filter: none; } + +#view { padding: 20px; min-width: 0; } +#view:focus { outline: none; } +#view.view-enter { animation: view-in var(--ease) both; } +@keyframes view-in { + from { opacity: 0; } + to { opacity: 1; } +} +.stack { display: flex; flex-direction: column; gap: 16px; } + +/* ---------- cards ---------- */ + +.card { + background: var(--bg-elev); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow); + padding: 16px; +} +.card > h2 { margin-bottom: 12px; } +.card-head { + display: flex; align-items: center; gap: 12px; flex-wrap: wrap; + margin-bottom: 12px; +} +.card-head h2 { margin: 0; } + +/* ---------- stat tiles ---------- */ + +.tile-band { display: flex; flex-direction: column; gap: 8px; } +.tile-band-label { + font-size: 11px; font-weight: 600; color: var(--text-dim); + text-transform: uppercase; letter-spacing: .04em; +} +.tiles { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); + gap: 12px; +} +.tile { + background: var(--bg-elev); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 13px 15px; + box-shadow: var(--shadow); +} +.tile .k { font-size: 11.5px; color: var(--text-dim); text-transform: uppercase; letter-spacing: .04em; } +.tile .v { font-size: 26px; font-weight: 600; line-height: 1.15; margin-top: 3px; font-variant-numeric: tabular-nums; } +.tile.ok .v { color: var(--ok); } +.tile.down .v { color: var(--down); } +.tile.warn .v { color: var(--warn); } +.tile.alarm { + border-color: color-mix(in srgb, var(--down) 35%, var(--border)); +} +.tile.alarm.down { background: color-mix(in srgb, var(--down-soft) 55%, var(--bg-elev)); } +.tile.alarm.warn { background: color-mix(in srgb, var(--warn-soft) 55%, var(--bg-elev)); } + +/* ---------- forms ---------- */ + +label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--text-dim); } +label > span.lbl { font-size: 12px; } +input, select, textarea, button { + font: inherit; + color: var(--text); + background: var(--bg-elev); + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + padding: 7px 9px; +} +input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; +} +input[type=checkbox] { width: 16px; height: 16px; accent-color: var(--accent); padding: 0; } +textarea { font-family: var(--mono); font-size: 12px; resize: vertical; min-height: 4.2em; white-space: pre; } +input:disabled, select:disabled, textarea:disabled { opacity: .55; } + +button { + cursor: pointer; + background: var(--accent); + border-color: transparent; + color: var(--accent-ink); + font-weight: 600; + font-size: 13px; + padding: 7px 13px; + transition: background var(--ease), border-color var(--ease), color var(--ease), transform 80ms ease; +} +button:hover { background: color-mix(in srgb, var(--accent) 88%, #000); } +button:active:not(:disabled) { transform: translateY(1px); } +button.ghost { + background: transparent; color: var(--text); border-color: var(--border-strong); font-weight: 500; +} +button.ghost:hover { background: var(--bg-sunken); } +button.danger { background: transparent; color: var(--down); border-color: var(--down); } +button.danger:hover { background: var(--down-soft); } +button.sm { padding: 4px 9px; font-size: 12px; } +button.tiny { padding: 2px 7px; font-size: 11px; font-weight: 500; } +button:disabled, button[aria-busy="true"] { opacity: .55; cursor: not-allowed; transform: none; } +button[aria-busy="true"] { position: relative; } +.icon-btn { + background: transparent; border-color: transparent; color: var(--text-dim); + padding: 5px 8px; font-size: 15px; +} +.icon-btn:hover { background: var(--bg-sunken); color: var(--text); } + +.grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); + gap: 11px 14px; +} +.span2 { grid-column: 1 / -1; } +.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.row.end { justify-content: flex-end; } +.inline-check { flex-direction: row; align-items: center; gap: 7px; color: var(--text); font-size: 13px; } + +fieldset { + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 12px; + margin: 0; +} +legend { padding: 0 6px; font-size: 12px; font-weight: 600; color: var(--text); } + +.msg { min-height: 1.2em; margin: 6px 0 0; font-size: 13px; } +.msg.err { color: var(--down); } +.msg.ok { color: var(--ok); } + +/* ---------- pills ---------- */ + +.pill { + display: inline-block; + padding: 2px 8px; + border-radius: 999px; + font-size: 11.5px; + font-weight: 600; + white-space: nowrap; + background: var(--idle-soft); + color: var(--idle); +} +.pill.ok { background: var(--ok-soft); color: var(--ok); } +.pill.starting, .pill.pending { background: var(--warn-soft); color: var(--warn); } +.pill.down, .pill.error { background: var(--down-soft); color: var(--down); } +.pill.stopped, .pill.off { background: var(--idle-soft); color: var(--idle); } +.pill.role { background: var(--accent-soft); color: var(--accent); } +.pill.tag { background: var(--bg-sunken); color: var(--text-dim); font-weight: 500; } + +/* ---------- tables ---------- */ + +.table-wrap { overflow-x: auto; margin: 0 -16px -16px; padding: 0 16px 4px; } +table { width: 100%; border-collapse: collapse; font-size: 13px; } +th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid var(--border); vertical-align: middle; } +th { + color: var(--text-dim); font-weight: 600; font-size: 11.5px; + text-transform: uppercase; letter-spacing: .03em; + position: sticky; top: 0; background: var(--bg-elev); z-index: 1; +} +th.sortable { cursor: pointer; user-select: none; } +th.sortable:hover { color: var(--text); } +th .arrow { opacity: .5; font-size: 9px; } +tbody tr:hover { background: var(--bg-sunken); } +tbody tr:last-child td { border-bottom: none; } +td.actions { white-space: nowrap; } +td.actions .row { gap: 5px; } +.name-cell strong { font-size: 13.5px; } +.name-cell a { color: var(--text); } +.name-cell a:hover { color: var(--accent); } +.sub { color: var(--text-dim); font-size: 11.5px; margin-top: 1px; } +.empty { padding: 28px 8px; text-align: center; color: var(--text-dim); } + +/* ---------- publish links ---------- */ + +.links { display: flex; flex-direction: column; gap: 5px; min-width: 200px; } +.links.compact { min-width: 0; max-width: 280px; } +.link-row { + display: flex; align-items: center; gap: 7px; + padding: 5px 7px; + background: var(--bg-sunken); + border: 1px solid var(--border); + border-radius: var(--radius-sm); +} +.link-row .lab { + font-size: 10.5px; font-weight: 700; letter-spacing: .03em; + color: var(--accent); min-width: 52px; +} +.link-row.master .lab { color: var(--ok); } +.link-row .path { + flex: 1; min-width: 0; + font-family: var(--mono); font-size: 11px; color: var(--text-dim); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +button.copied { color: var(--ok); border-color: var(--ok); } + +/* ---------- sparkline ---------- */ + +.spark { display: block; width: 100%; height: 44px; } +.spark .line { fill: none; stroke: var(--accent); stroke-width: 1.5; } +.spark .area { fill: var(--accent); opacity: .12; } +.spark .zero { stroke: var(--border-strong); stroke-width: 1; stroke-dasharray: 2 3; } + +/* ---------- timeline ---------- */ + +.timeline { display: flex; flex-direction: column; gap: 0; } +.ev { + display: grid; + grid-template-columns: 74px 110px 1fr; + gap: 10px; + padding: 7px 0; + border-bottom: 1px solid var(--border); + font-size: 12.5px; + align-items: baseline; +} +.ev:last-child { border-bottom: none; } +.ev .at { font-family: var(--mono); font-size: 11px; color: var(--text-dim); } +.ev .msg { word-break: break-word; } +.ev .msg .who { color: var(--text-dim); font-size: 11px; } +.ev.error .msg { color: var(--down); } +.ev.warn .msg { color: var(--warn); } + +/* ---------- log viewer ---------- */ + +.logbox { + background: var(--bg-sunken); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 10px 12px; + font-family: var(--mono); + font-size: 11.5px; + line-height: 1.45; + white-space: pre-wrap; + word-break: break-word; + max-height: 420px; + overflow: auto; + margin: 0; +} + +/* ---------- player ---------- */ + +.player-wrap { background: #000; border-radius: var(--radius-sm); overflow: hidden; } +.preview-player .preview-controls { flex-wrap: wrap; gap: 8px; align-items: center; } +.preview-player select.sm { + min-width: 10rem; + padding: 4px 8px; + font: inherit; + color: var(--text); + background: var(--surface-2, var(--panel)); + border: 1px solid var(--border); + border-radius: var(--radius-sm); +} +video { width: 100%; max-height: 420px; display: block; background: #000; } + +/* ---------- variant / output editors ---------- */ + +.vrow, .orow { + display: grid; + grid-template-columns: auto 1fr 90px 100px 100px auto; + gap: 8px; + align-items: center; + padding: 8px 0; + border-bottom: 1px solid var(--border); +} +.orow { grid-template-columns: auto 1fr 110px 110px; } +.vrow:last-of-type, .orow:last-of-type { border-bottom: none; } +.vrow input[type=text], .vrow input[type=number], .orow input[type=number] { padding: 5px 7px; font-size: 12px; } +.vrow .vname { font-weight: 600; font-size: 13px; } +.vrow .locked-note, .orow .fmt { font-size: 11px; color: var(--text-dim); } +.col-head { + display: grid; + grid-template-columns: auto 1fr 90px 100px 100px auto; + gap: 8px; + font-size: 10.5px; text-transform: uppercase; letter-spacing: .03em; + color: var(--text-dim); + padding-bottom: 5px; + border-bottom: 1px solid var(--border); +} +.col-head.out { grid-template-columns: auto 1fr 110px 110px; } + +/* ---------- auth gate ---------- */ + +#gate { + min-height: 100vh; + display: grid; + place-items: center; + padding: 20px; + background: var(--bg); +} +.auth-card { + width: 100%; max-width: 370px; + background: var(--bg-elev); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow); + padding: 26px; + display: flex; flex-direction: column; gap: 13px; +} +.auth-card h2 { margin: 0; } +.auth-sub { margin: -4px 0 0; color: var(--text-dim); font-size: 13px; } +.auth-card button[type=submit] { margin-top: 4px; padding: 9px; } + +/* ---------- toast & modal ---------- */ + +#toast-stack { + position: fixed; right: 16px; bottom: 16px; z-index: 100; + display: flex; flex-direction: column-reverse; gap: 8px; + max-width: min(420px, calc(100vw - 32px)); + pointer-events: none; +} +.toast { + background: var(--sidebar); color: #fff; + padding: 10px 15px; + border-radius: var(--radius-sm); + box-shadow: var(--shadow); + font-size: 13px; + pointer-events: auto; + animation: toast-in var(--ease) both; +} +.toast.out { animation: toast-out var(--ease) both; } +.toast.err { background: var(--down); } +@keyframes toast-in { + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: none; } +} +@keyframes toast-out { + from { opacity: 1; transform: none; } + to { opacity: 0; transform: translateY(8px); } +} + +dialog { + border: 1px solid var(--border); + background: var(--bg-elev); + color: var(--text); + border-radius: var(--radius); + padding: 20px; + width: min(560px, calc(100vw - 32px)); + box-shadow: var(--shadow); +} +dialog::backdrop { background: rgba(0, 0, 0, .6); backdrop-filter: blur(2px); } + +/* ---------- tabs / wizard / skeleton ---------- */ + +.tabs { + display: flex; gap: 2px; + border-bottom: 1px solid var(--border); + margin: 0 0 16px; +} +.tabs a, .tabs button { + background: transparent; border: none; border-bottom: 2px solid transparent; + border-radius: 0; color: var(--text-dim); font-weight: 500; + padding: 8px 14px; margin-bottom: -1px; +} +.tabs a:hover, .tabs button:hover { color: var(--text); background: transparent; text-decoration: none; } +.tabs a.active, .tabs button.active { + color: var(--text); border-bottom-color: var(--accent); font-weight: 600; +} + +.wizard-steps { + display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; +} +.wizard-steps .step { + font-size: 12px; color: var(--text-dim); padding: 4px 10px; + border-radius: 999px; border: 1px solid var(--border); + background: transparent; font-weight: 500; transform: none; +} +.wizard-steps .step:hover { background: var(--bg-sunken); color: var(--text); } +.wizard-steps .step.on { color: var(--accent-ink); background: var(--accent); border-color: transparent; font-weight: 600; } +.wizard-steps .step.on:hover { background: var(--accent); color: var(--accent-ink); } +.wizard-steps .step.done { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 40%, var(--border)); } +.wizard-foot { + position: sticky; bottom: 0; z-index: 5; + display: flex; gap: 8px; align-items: center; justify-content: flex-end; + margin: 20px -20px -20px; padding: 14px 20px; + background: color-mix(in srgb, var(--bg-elev) 92%, transparent); + border-top: 1px solid var(--border); + backdrop-filter: blur(6px); +} + +.skeleton { + background: linear-gradient(90deg, var(--bg-sunken) 25%, var(--border) 50%, var(--bg-sunken) 75%); + background-size: 200% 100%; + animation: shimmer 1.2s ease-in-out infinite; + border-radius: var(--radius-sm); + min-height: 1em; +} +@keyframes shimmer { + 0% { background-position: 200% 0; } + 100% { background-position: -200% 0; } +} + +.flag-more { + font-size: 11px; color: var(--text-dim); padding: 2px 6px; + border-radius: 999px; background: var(--bg-sunken); +} + +/* ---------- responsive ---------- */ + +@media (max-width: 900px) { + .only-mobile { display: inline-flex; } + #app { grid-template-columns: 1fr; } + #sidebar { + position: fixed; inset: 0 auto 0 0; width: 258px; z-index: 50; + transform: translateX(-100%); + transition: transform .18s ease; + } + #app.nav-open #sidebar { transform: none; } + #app.nav-open::after { + content: ""; position: fixed; inset: 0; z-index: 40; + background: rgba(0, 0, 0, .55); + } + #view { padding: 16px; } + #topbar { padding: 10px 16px; } + .who #who-name { display: none; } + .vrow, .col-head { grid-template-columns: auto 1fr 1fr; } + .vrow > .del { grid-column: 3; justify-self: end; } + .col-head { display: none; } + .table-wrap { margin: 0 -16px -16px; padding: 0 16px 4px; } +} + +@media (prefers-reduced-motion: reduce) { + * { transition: none !important; animation: none !important; } +} diff --git a/apps/streamd/internal/ui/static/js/api.js b/apps/streamd/internal/ui/static/js/api.js new file mode 100644 index 0000000..5115566 --- /dev/null +++ b/apps/streamd/internal/ui/static/js/api.js @@ -0,0 +1,134 @@ +// API client. Carries the CSRF token on mutations and routes a 401 back to +// the sign-in screen rather than leaving a half-dead page. + +let csrfToken = ""; +const onUnauthorized = []; + +export function setCSRF(token) { + csrfToken = token || ""; +} + +export function getCSRF() { + return csrfToken; +} + +/** Register a callback for when the session turns out to be gone. */ +export function onAuthLost(fn) { + onUnauthorized.push(fn); +} + +export class ApiError extends Error { + constructor(message, status, body) { + super(message); + this.name = "ApiError"; + this.status = status; + this.body = body; + } +} + +async function request(method, path, body, opts = {}) { + const headers = {}; + let payload; + if (body !== undefined && body !== null) { + headers["Content-Type"] = "application/json"; + payload = JSON.stringify(body); + } + // The session cookie is HttpOnly, so the double-submit token is what proves + // this request came from the dashboard and not from another origin. + if (method !== "GET" && method !== "HEAD" && csrfToken) { + headers["X-CSRF-Token"] = csrfToken; + } + const res = await fetch(path, { + method, + headers, + body: payload, + credentials: "same-origin", + signal: opts.signal, + }); + + const text = await res.text(); + let data = null; + if (text) { + try { + data = JSON.parse(text); + } catch { + data = { raw: text }; + } + } + + if (res.status === 401) { + // allow401 lets boot/login/setup read the JSON body (e.g. needs_setup) + // without treating it as a hard failure or kicking the session. + if (opts.allow401) return data; + for (const fn of onUnauthorized) fn(data); + throw new ApiError((data && data.error) || "not signed in", 401, data); + } + if (!res.ok) { + const msg = (data && data.error) || res.statusText || `request failed (${res.status})`; + throw new ApiError(msg, res.status, data); + } + return data; +} + +export const api = { + get: (p, opts) => request("GET", p, null, opts), + post: (p, b, opts) => request("POST", p, b ?? {}, opts), + patch: (p, b, opts) => request("PATCH", p, b ?? {}, opts), + put: (p, b, opts) => request("PUT", p, b ?? {}, opts), + del: (p, opts) => request("DELETE", p, null, opts), + + // --- session --- + me: () => request("GET", "/api/me", null, { allow401: true }), + login: (username, password) => request("POST", "/api/login", { username, password }, { allow401: true }), + setup: (setup_token, username, password) => + request("POST", "/api/setup", { setup_token, username, password }, { allow401: true }), + logout: () => request("POST", "/api/logout", {}), + setupState: () => request("GET", "/api/setup", null, { allow401: true }), + + // --- streams --- + health: () => request("GET", "/api/health", null, { allow401: true }), + overview: () => api.get("/api/overview"), + streams: () => api.get("/api/streams"), + stream: (id, reveal) => api.get(`/api/streams/${id}${reveal ? "?reveal=1" : ""}`), + createStream: (body) => api.post("/api/streams", body), + patchStream: (id, body) => api.patch(`/api/streams/${id}`, body), + deleteStream: (id) => api.del(`/api/streams/${id}`), + action: (id, what) => api.post(`/api/streams/${id}/${what}`), + bulk: (ids, action) => api.post("/api/streams/bulk", { ids, action }), + duplicate: (id, body) => api.post(`/api/streams/${id}/duplicate`, body), + probe: (id, mpd) => api.post(`/api/streams/${id}/probe`, mpd ? { mpd } : {}), + capture: (id) => api.post(`/api/streams/${id}/capture`), + credentials: (id, body) => api.post(`/api/streams/${id}/credentials`, body), + + // --- history --- + events: (id, limit = 100) => api.get(`/api/streams/${id}/events?limit=${limit}`), + metrics: (id, window = "1h") => api.get(`/api/streams/${id}/metrics?window=${encodeURIComponent(window)}`), + logs: (id, source, variant) => { + const q = new URLSearchParams({ source, tail: "600" }); + if (variant) q.set("variant", variant); + return api.get(`/api/streams/${id}/logs?${q}`); + }, + + // --- schedules --- + schedules: (id) => api.get(`/api/streams/${id}/schedules`), + allSchedules: () => api.get("/api/schedules"), + upcoming: (limit = 10) => api.get(`/api/schedules?upcoming=1&limit=${limit}`), + createSchedule: (id, body) => api.post(`/api/streams/${id}/schedules`, body), + patchSchedule: (sid, body) => api.patch(`/api/schedules/${sid}`, body), + deleteSchedule: (sid) => api.del(`/api/schedules/${sid}`), + + // --- admin --- + settings: () => api.get("/api/settings"), + saveSettings: (body) => api.put("/api/settings", body), + users: () => api.get("/api/users"), + createUser: (body) => api.post("/api/users", body), + patchUser: (id, body) => api.patch(`/api/users/${id}`, body), + deleteUser: (id) => api.del(`/api/users/${id}`), + setPassword: (id, body) => api.post(`/api/users/${id}/password`, body), + apiKeys: () => api.get("/api/apikeys"), + createKey: (body) => api.post("/api/apikeys", body), + revokeKey: (id) => api.del(`/api/apikeys/${id}`), + audit: (limit = 200) => api.get(`/api/audit?limit=${limit}`), + agents: () => api.get("/api/agents"), + apps: () => api.get("/api/apps"), +}; diff --git a/apps/streamd/internal/ui/static/js/app.js b/apps/streamd/internal/ui/static/js/app.js new file mode 100644 index 0000000..befb1b2 --- /dev/null +++ b/apps/streamd/internal/ui/static/js/app.js @@ -0,0 +1,331 @@ +// Application shell: sign-in gate, hash router, chrome. + +import { api, setCSRF, onAuthLost } from "./api.js"; +import { state, subscribe, connect, disconnect, refresh, setMe, isAdmin } from "./store.js"; +import { $, $$, el, clear, setText, toast, fmtSeconds } from "./util.js"; +import { dashboard } from "./views/dashboard.js"; +import { streams } from "./views/streams.js"; +import { streamView } from "./views/stream.js"; +import { scheduleView, settingsView, peopleView, auditView } from "./views/admin.js"; + +const app = $("#app"); +const gate = $("#gate"); +const viewRoot = $("#view"); + +let teardown = null; + +// ---------- theme ---------- + +function showingDark() { + const cur = document.documentElement.dataset.theme; + if (cur) return cur === "dark"; + return window.matchMedia("(prefers-color-scheme: dark)").matches; +} + +function paintThemeLabel() { + const label = $("#theme-btn-label"); + if (!label) return; + // Button names the mode you will switch *to*. + setText(label, showingDark() ? "Light" : "Dark"); +} + +function initTheme() { + const saved = localStorage.getItem("streamd.theme"); + if (saved === "light" || saved === "dark") { + document.documentElement.dataset.theme = saved; + } + paintThemeLabel(); + $("#theme-btn").addEventListener("click", () => { + const next = showingDark() ? "light" : "dark"; + document.documentElement.dataset.theme = next; + paintThemeLabel(); + try { + localStorage.setItem("streamd.theme", next); + } catch { + // Private browsing; the choice simply will not persist. + } + }); +} + +// ---------- routes ---------- + +const ROUTES = [ + { path: /^\/?$/, title: "Dashboard", nav: "/", mount: (root) => dashboard(root) }, + { path: /^\/streams$/, title: "Streams", nav: "/streams", mount: (root) => streams(root) }, + { + path: /^\/streams\/new$/, title: "Add stream", nav: "/streams", + mount: (root) => import("./views/stream-form.js").then((m) => m.streamCreate(root)), + }, + { + path: /^\/stream\/(\d+)(?:\/(live|config|debug))?$/, title: "Stream", nav: "/streams", + mount: (root, m) => streamView(root, Number(m[1]), m[2] || "live"), + }, + { path: /^\/schedule$/, title: "Schedule", nav: "/schedule", mount: (root) => scheduleView(root) }, + { path: /^\/settings$/, title: "Settings", nav: "/settings", admin: true, mount: (root) => settingsView(root) }, + { path: /^\/people$/, title: "People & keys", nav: "/people", admin: true, mount: (root) => peopleView(root) }, + { path: /^\/audit$/, title: "Audit log", nav: "/audit", admin: true, mount: (root) => auditView(root) }, +]; + +function currentPath() { + const h = location.hash.replace(/^#/, ""); + return h || "/"; +} + +function route() { + const path = currentPath(); + if (teardown) { + try { + teardown(); + } catch (err) { + console.error("view teardown failed", err); + } + teardown = null; + } + clear(viewRoot); + + for (const r of ROUTES) { + const m = path.match(r.path); + if (!m) continue; + if (r.admin && !isAdmin()) { + viewRoot.append(el("div.card", + el("h2", { text: "Not available" }), + el("p.hint", { text: "This page is administrator-only." }), + )); + setText($("#page-title"), "Not available"); + return; + } + setText($("#page-title"), r.title); + document.title = `${r.title} · streamd`; + markNav(r.nav); + viewRoot.classList.remove("view-enter"); + void viewRoot.offsetWidth; + viewRoot.classList.add("view-enter"); + try { + const mounted = r.mount(viewRoot, m); + // Mount may return a teardown, or a Promise thereof (lazy create page). + if (mounted && typeof mounted.then === "function") { + mounted.then((fn) => { teardown = fn || null; }).catch((err) => { + console.error(err); + viewRoot.append(el("div.card", el("p.msg.err", { text: `This page failed to render: ${err.message}` }))); + }); + } else { + teardown = mounted || null; + } + } catch (err) { + console.error(err); + viewRoot.append(el("div.card", el("p.msg.err", { text: `This page failed to render: ${err.message}` }))); + } + app.classList.remove("nav-open"); + viewRoot.focus({ preventScroll: true }); + return; + } + + setText($("#page-title"), "Not found"); + markNav(""); + viewRoot.append(el("div.card", + el("h2", { text: "Not found" }), + el("p", el("a", { href: "#/", text: "Back to the dashboard" })), + )); +} + +function markNav(nav) { + for (const a of $$("#nav a")) { + a.classList.toggle("active", a.dataset.nav === nav); + } +} + +// ---------- chrome ---------- + +function paintChrome() { + const me = state.me || {}; + setText($("#who-name"), me.name || ""); + const role = $("#who-role"); + setText(role, me.role || ""); + role.className = `pill role`; + + for (const a of $$("#nav a[data-admin]")) a.hidden = !isAdmin(); + + const conn = $("#conn"); + const live = !!state.connected; + setText(conn, live ? "Live" : "Reconnecting"); + conn.classList.toggle("off", !live); + conn.classList.toggle("warn", !live); + conn.title = live ? "WebSocket connected" : "WebSocket reconnecting — data may be stale"; + + setText($("#uptime"), state.uptimeS ? `up ${fmtSeconds(state.uptimeS)}` : ""); + + const agents = state.agents || []; + const agentVal = $("#agent-chip .chip-val") || $("#agent-chip"); + const agentIds = agents.map((a) => a.agent_id); + setText(agentVal, agents.length ? agentIds.join(", ") : "none"); + $("#agent-chip").title = agents.length + ? agentIds.join("\n") + : "No capture agents connected"; + + const d = state.deps; + if (d) { + const mark = (ok) => (ok ? "✓" : "✗"); + // /api/health gives paths to a signed-in caller and booleans otherwise. + const has = (v) => (typeof v === "boolean" ? v : !!v); + const chip = $("#deps-chip"); + const val = chip.querySelector(".chip-val") || chip; + setText(val, `ffmpeg${mark(has(d.ffmpeg))} nre${mark(has(d.nre))} mp4decrypt${mark(has(d.mp4decrypt))}`); + chip.title = [ + `ffmpeg: ${d.ffmpeg || "missing"}`, + `N_m3u8DL-RE: ${d.nre || "missing"}`, + `mp4decrypt: ${d.mp4decrypt || "missing"}`, + d.bin_dir ? `bin: ${d.bin_dir}` : "", + ].filter(Boolean).join("\n"); + } + + if (state.lastError) toastOnce(state.lastError); +} + +let lastToast = ""; +function toastOnce(msg) { + if (msg === lastToast) return; + lastToast = msg; + toast(msg, true); + setTimeout(() => (lastToast = ""), 8000); +} + +// ---------- sign-in ---------- + +function showGate(opts = {}) { + disconnect(); + app.hidden = true; + gate.hidden = false; + const form = $("#login-form"); + const setupRow = $("#setup-row"); + const needsSetup = !!opts.needsSetup; + setupRow.hidden = !needsSetup; + setupRow.querySelector("input").required = needsSetup; + setText($("#gate-title"), needsSetup ? "Create the first administrator" : "Sign in to streamd"); + setText($("#gate-note"), needsSetup + ? "No accounts exist yet. Paste the one-time setup token from the streamd startup log." + : ""); + setText($("#gate-submit"), needsSetup ? "Create account" : "Sign in"); + setText($("#gate-msg"), opts.message || ""); + $("#gate-msg").classList.toggle("err", !!opts.message); + form.dataset.mode = needsSetup ? "setup" : "login"; + (needsSetup ? setupRow.querySelector("input") : form.username).focus(); +} + +function showApp() { + gate.hidden = true; + app.hidden = false; + connect(); + route(); +} + +async function submitGate(ev) { + ev.preventDefault(); + const form = ev.target; + const msg = $("#gate-msg"); + setText(msg, ""); + msg.classList.remove("err"); + const btn = $("#gate-submit"); + btn.disabled = true; + try { + const username = form.username.value.trim(); + const password = form.password.value; + let res; + if (form.dataset.mode === "setup") { + res = await api.setup(form.setup_token.value.trim(), username, password); + } else { + res = await api.login(username, password); + } + if (!res || res.error) { + throw new Error((res && res.error) || "sign-in failed"); + } + setCSRF(res.csrf_token || ""); + // Prefer /api/me (includes csrf). If the Set-Cookie round-trip is slow or + // blocked, fall back to the login/setup payload so the UI still advances. + let me = await api.me(); + if (!me || !me.role) { + if (res.user) { + me = { + name: res.user.username || username, + role: res.user.role || "admin", + actor_kind: "user", + user_id: res.user.id, + csrf_token: res.csrf_token, + }; + } else if (res.role || res.name) { + me = res; + } + } + if (!me || !me.role) { + throw new Error( + "Account was created/accepted, but the browser session cookie was not established. " + + "Allow cookies for this origin, then hard-refresh and sign in.", + ); + } + setMe(me); + form.reset(); + showApp(); + await refresh("signed-in"); + } catch (err) { + setText(msg, err.message || String(err)); + msg.classList.add("err"); + } finally { + btn.disabled = false; + } +} + +async function logout() { + try { + await api.logout(); + } catch { + // Signing out locally matters more than the request succeeding. + } + setCSRF(""); + setMe(null); + showGate({ message: "Signed out." }); +} + +// ---------- boot ---------- + +async function boot() { + initTheme(); + subscribe(paintChrome); + window.addEventListener("hashchange", route); + $("#login-form").addEventListener("submit", submitGate); + $("#logout-btn").addEventListener("click", logout); + $("#nav-open").addEventListener("click", () => app.classList.add("nav-open")); + $("#nav-close").addEventListener("click", () => app.classList.remove("nav-open")); + app.addEventListener("click", (ev) => { + // Tapping the scrim closes the mobile drawer. + if (app.classList.contains("nav-open") && !ev.target.closest("#sidebar") && !ev.target.closest("#nav-open")) { + app.classList.remove("nav-open"); + } + }); + document.addEventListener("keydown", (ev) => { + if (ev.key === "Escape") app.classList.remove("nav-open"); + }); + + // A session that expires while the page is open sends the viewer back to + // sign-in rather than leaving a page full of failing requests. + onAuthLost(() => { + setMe(null); + showGate({ message: "Your session expired. Sign in again." }); + }); + + try { + const me = await api.me(); + if (me && me.role) { + setCSRF(me.csrf_token || ""); + setMe(me); + await refresh("boot"); + showApp(); + return; + } + // allow401 returns the 401 JSON body instead of throwing. + showGate({ needsSetup: !!(me && me.needs_setup) }); + } catch (err) { + const needsSetup = !!(err.body && err.body.needs_setup); + showGate({ needsSetup }); + } +} + +boot(); diff --git a/apps/streamd/internal/ui/static/js/components.js b/apps/streamd/internal/ui/static/js/components.js new file mode 100644 index 0000000..b4aeb7a --- /dev/null +++ b/apps/streamd/internal/ui/static/js/components.js @@ -0,0 +1,375 @@ +// Shared pieces used by more than one view. + +import { el, pill, copyText, absURL, fmtAge, fmtDateTime, clear, append } from "./util.js"; + +/** A list of copyable publish endpoints, one row per variant x format. */ +export function publishLinks(stream, opts = {}) { + const links = Array.isArray(stream.links) ? stream.links : []; + const box = el(`div.links${opts.compact ? ".compact" : ""}`); + if (!links.length) { + // A stream with no resolved links still has its canonical HLS path. + const path = stream.play_path || `/hls/${stream.name}/index.m3u8`; + box.append(linkRow({ output_label: "HLS", variant_label: "", play_path: path, health: stream.health }, opts)); + return box; + } + const shown = opts.limit ? links.slice(0, opts.limit) : links; + for (const l of shown) box.append(linkRow(l, opts)); + if (opts.limit && links.length > opts.limit) { + box.append(el("div.hint", { text: `+${links.length - opts.limit} more` })); + } + return box; +} + +function linkRow(l, opts = {}) { + const url = absURL(l.play_path); + const label = l.master + ? "MASTER" + : [l.variant_label, l.output_label].filter(Boolean).join(" · "); + const copyBtn = el("button.tiny.ghost", { + text: "Copy", + title: `Copy ${url}`, + onclick: (ev) => copyText(url, label ? `${label} link` : "link", ev.currentTarget), + }); + return el(`div.link-row${l.master ? ".master" : ""}`, + el("span.lab", { text: label || "HLS" }), + el("span.path", { text: l.play_path, title: url }), + !opts.compact && l.health ? pill(l.health) : null, + copyBtn, + ); +} + +/** + * Editor for the output ladder: any number of rungs at any height and + * bitrate, which replaces the three hardcoded checkboxes. + */ +export function variantEditor(variants) { + const rows = el("div"); + const wrap = el("fieldset", + el("legend", { text: "Quality ladder" }), + el("p.hint", { + text: "The source rung is always published as a straight copy. Each extra rung is " + + "re-encoded, so every one you enable costs CPU.", + }), + el("div.col-head", + el("span", { text: "On" }), el("span", { text: "Name" }), + el("span", { text: "Height" }), el("span", { text: "Video" }), + el("span", { text: "Audio" }), el("span", { text: "" }), + ), + rows, + el("div.row", { style: { marginTop: "10px" } }, + el("button.ghost.sm", { + type: "button", + text: "+ Add rung", + onclick: () => rows.append(variantRow({ + id: "", label: "", enabled: true, height: 480, + video_bitrate: "1200k", audio_bitrate: "96k", + })), + }), + el("button.ghost.sm", { + type: "button", + text: "+ Add audio-only", + onclick: () => rows.append(variantRow({ + id: "audio", label: "Audio", enabled: true, height: 0, + audio_only: true, audio_bitrate: "96k", + })), + }), + ), + ); + + const list = (variants && variants.length ? variants : [{ id: "fhd", label: "FHD", enabled: true, height: 0 }]); + for (const v of list) rows.append(variantRow(v)); + + wrap.readValue = () => Array.from(rows.children) + .map((r) => r.readValue()) + .filter((v) => v && (v.audio_only || v.height > 0 || v.id === "fhd")); + return wrap; +} + +function variantRow(v) { + const isSource = !v.audio_only && (!v.height || v.height <= 0) && (v.id === "fhd" || !v.id); + const on = el("input", { type: "checkbox", checked: isSource || v.enabled !== false, disabled: isSource }); + const name = el("input", { + type: "text", value: v.label || (v.id || "").toUpperCase(), placeholder: "HD", + disabled: isSource, maxlength: "24", + }); + const height = el("input", { + type: "number", value: v.height || 0, min: "0", max: "4320", step: "2", + disabled: isSource || v.audio_only, + }); + const vbr = el("input", { + type: "text", value: v.video_bitrate || "", placeholder: "2800k", + disabled: isSource || v.audio_only, + }); + const abr = el("input", { type: "text", value: v.audio_bitrate || "", placeholder: "128k", disabled: isSource }); + + const row = el("div.vrow", + on, + isSource + ? el("div", el("div.vname", { text: v.label || "FHD" }), el("div.locked-note", { text: "source · copy" })) + : name, + isSource ? el("span.locked-note", { text: "as source" }) : height, + isSource ? el("span.locked-note", { text: "copy" }) : (v.audio_only ? el("span.locked-note", { text: "none" }) : vbr), + abr, + isSource + ? el("span") + : el("button.tiny.danger.del", { type: "button", text: "Remove", onclick: () => row.remove() }), + ); + + row.readValue = () => { + if (isSource) return { id: "fhd", label: "FHD", enabled: true, height: 0 }; + const h = v.audio_only ? 0 : Math.max(0, parseInt(height.value, 10) || 0); + const label = name.value.trim() || (v.audio_only ? "Audio" : `${h}p`); + return { + id: (v.id || label).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""), + label, + enabled: on.checked, + height: h, + audio_only: !!v.audio_only, + video_bitrate: v.audio_only ? "" : vbr.value.trim(), + audio_bitrate: abr.value.trim(), + }; + }; + return row; +} + +/** Editor for which formats a stream publishes. */ +export function outputEditor(outputs) { + const rows = el("div"); + const wrap = el("fieldset", + el("legend", { text: "Publish formats" }), + el("p.hint", { + text: "Every enabled rung is published in each enabled format. The formats share " + + "one encode per rung, so adding a format is far cheaper than adding a rung.", + }), + el("div.col-head.out", + el("span", { text: "On" }), el("span", { text: "Format" }), + el("span", { text: "Segment s" }), el("span", { text: "Playlist len" }), + ), + rows, + ); + const list = outputs && outputs.length ? outputs : [ + { id: "hls", label: "HLS", format: "hls", enabled: true }, + { id: "cmaf", label: "CMAF", format: "hls_fmp4", enabled: false }, + { id: "dash", label: "DASH", format: "dash", enabled: false }, + { id: "ts", label: "TS", format: "mpegts", enabled: false }, + ]; + for (const o of list) rows.append(outputRow(o)); + wrap.readValue = () => Array.from(rows.children).map((r) => r.readValue()); + return wrap; +} + +const FORMAT_BLURB = { + hls: "index.m3u8 — MPEG-TS HLS, the broadest player support", + hls_fmp4: "cmaf/index.m3u8 — fMP4 segments, better on Safari", + dash: "dash/index.mpd — MPEG-DASH", + mpegts: "/live/.ts — one endless URL, opens in VLC", +}; + +function outputRow(o) { + const on = el("input", { type: "checkbox", checked: !!o.enabled }); + const seg = el("input", { type: "number", min: "0", max: "30", value: o.segment_duration || "", placeholder: "inherit" }); + const len = el("input", { type: "number", min: "0", max: "500", value: o.list_size || "", placeholder: "inherit" }); + const row = el("div.orow", + on, + el("div", + el("div", { text: o.label || o.id }), + el("div.fmt", { text: FORMAT_BLURB[o.format] || o.format }), + ), + seg, + len, + ); + row.readValue = () => ({ + id: o.id, + label: o.label, + format: o.format, + enabled: on.checked, + segment_duration: parseInt(seg.value, 10) || 0, + list_size: parseInt(len.value, 10) || 0, + }); + return row; +} + +/** + * An HLS preview player using the vendored hls.js, with native fallback. + * + * @param {string|object} playPathOrOpts + * string path, or { path, choices: [{ label, play_path }] } so the operator + * can pick FHD / HD / SD (or ABR master) before hitting Play preview. + */ +export function player(playPathOrOpts) { + const opts = typeof playPathOrOpts === "string" + ? { path: playPathOrOpts, choices: [] } + : (playPathOrOpts || {}); + let playPath = opts.path || ""; + const choices = Array.isArray(opts.choices) ? opts.choices.filter((c) => c && c.play_path) : []; + if (!playPath && choices.length) playPath = choices[0].play_path; + + const video = el("video", { controls: true, playsinline: true, muted: true, preload: "none" }); + const note = el("p.hint"); + const pathHint = el("p.hint.mono"); + setPathHint(playPath); + + let quality = null; + if (choices.length > 1) { + quality = el("select.sm", { + title: "Preview quality", + onchange: () => { + playPath = quality.value; + setPathHint(playPath); + // If already playing, switch source immediately. + if (hls || video.src) start(); + }, + }); + for (const c of choices) { + quality.append(el("option", { + value: c.play_path, + text: c.label || c.play_path, + selected: c.play_path === playPath, + })); + } + } + + const wrap = el("div.preview-player", + el("div.player-wrap", video), + el("div.row.preview-controls", { style: { marginTop: "8px" } }, + quality + ? el("label.row", { style: { gap: "6px", alignItems: "center" } }, + el("span.muted", { text: "Quality" }), + quality, + ) + : null, + el("button.sm", { type: "button", text: "Play preview", onclick: start }), + el("button.ghost.sm", { type: "button", text: "Stop", onclick: stop }), + note, + ), + pathHint, + ); + let hls = null; + + function setPathHint(path) { + pathHint.textContent = path ? `Playing ${path}` : ""; + } + + async function start() { + stop(); + if (quality) playPath = quality.value; + if (!playPath) { + note.textContent = "no playlist to play"; + return; + } + setPathHint(playPath); + const url = absURL(playPath); + // Safari plays HLS natively; everywhere else needs hls.js, which is + // served from this host so the page CSP can stay default-src 'self'. + if (video.canPlayType("application/vnd.apple.mpegurl")) { + video.src = url; + note.textContent = "native HLS"; + video.play().catch((e) => (note.textContent = e.message)); + return; + } + note.textContent = "loading player…"; + try { + const mod = await import("/static/vendor/hls.min.js"); + const Hls = mod.default || window.Hls; + if (!Hls || !Hls.isSupported()) { + note.textContent = "this browser cannot play HLS — use the copied link in VLC"; + return; + } + hls = new Hls({ lowLatencyMode: false, enableWorker: true }); + hls.on(Hls.Events.ERROR, (_e, data) => { + if (data && data.fatal) note.textContent = `player error: ${data.details || data.type}`; + }); + hls.loadSource(url); + hls.attachMedia(video); + note.textContent = "hls.js"; + video.play().catch(() => { + note.textContent = "ready — press play"; + }); + } catch (err) { + note.textContent = `could not load the player: ${err.message}`; + } + } + + function stop() { + if (hls) { + hls.destroy(); + hls = null; + } + video.removeAttribute("src"); + video.load(); + note.textContent = ""; + } + + wrap.stop = stop; + return wrap; +} + +/** Build preview quality choices from a stream's publish links (HLS/CMAF). */ +export function previewChoices(stream) { + const links = Array.isArray(stream && stream.links) ? stream.links : []; + const out = []; + const seen = new Set(); + for (const l of links) { + if (!l || !l.play_path) continue; + const fmt = String(l.format || "").toLowerCase(); + // Prefer MPEG-TS HLS and fMP4 HLS; skip DASH/TS fanout for in-browser preview. + if (fmt && fmt !== "hls" && fmt !== "hls_fmp4" && fmt !== "cmaf") continue; + if (seen.has(l.play_path)) continue; + seen.add(l.play_path); + const label = l.master + ? "ABR master" + : [l.variant_label || l.variant_id, l.output_label].filter(Boolean).join(" · ") || l.play_path; + out.push({ label, play_path: l.play_path, master: !!l.master }); + } + if (!out.length) { + const path = (stream && stream.play_path) || (stream && stream.name ? `/hls/${stream.name}/index.m3u8` : ""); + if (path) out.push({ label: "Source", play_path: path }); + } + return out; +} + +/** A stream's event timeline. */ +export function timeline(events) { + const box = el("div.timeline"); + if (!events || !events.length) { + box.append(el("div.empty", { text: "Nothing recorded yet." })); + return box; + } + for (const e of events) { + const sev = e.severity === "error" ? "error" : e.severity === "warn" ? "warn" : "info"; + box.append(el(`div.ev.${sev}`, + el("span.at", { text: fmtDateTime(e.at), title: e.at }), + pill(e.kind), + el("span.msg", + el("span", { text: e.message || "" }), + e.actor && e.actor !== "system" ? el("span.who", { text: ` — ${e.actor}` }) : null, + ), + )); + } + return box; +} + +/** A tag strip. */ +export function tagList(tags) { + const row = el("span.row", { style: { gap: "4px" } }); + for (const t of String(tags || "").split(",").filter(Boolean)) { + row.append(pill(t, "tag")); + } + return row; +} + +/** Health summary for a stream row, including the staleness age. */ +export function healthCell(s) { + return el("div", + pill(s.health || "stopped"), + s.last_error ? el("div.sub", { text: s.last_error, title: s.last_error }) : null, + s.playlist_age_s ? el("div.sub", { text: `playlist ${fmtAge(s.playlist_age_s)} old` }) : null, + ); +} + +/** Replace a container's children with new nodes. */ +export function replace(node, ...children) { + clear(node); + append(node, children); + return node; +} diff --git a/apps/streamd/internal/ui/static/js/store.js b/apps/streamd/internal/ui/static/js/store.js new file mode 100644 index 0000000..d23eba6 --- /dev/null +++ b/apps/streamd/internal/ui/static/js/store.js @@ -0,0 +1,200 @@ +// Client state, kept fresh by a websocket with a polling fallback. +// +// The old dashboard re-fetched everything on a five second timer. Here the +// server pushes health and change deltas, and the timer is only a safety net +// for when the socket is down. + +import { api } from "./api.js"; + +const listeners = new Set(); + +export const state = { + me: null, + streams: [], + overview: null, + agents: [], + deps: null, + uptimeS: 0, + connected: false, + lastError: "", +}; + +export function subscribe(fn) { + listeners.add(fn); + return () => listeners.delete(fn); +} + +function emit(reason) { + for (const fn of listeners) { + try { + fn(state, reason); + } catch (err) { + console.error("subscriber failed", err); + } + } +} + +export function streamById(id) { + return state.streams.find((s) => String(s.id) === String(id)) || null; +} + +let inflight = null; + +/** Refresh the stream list and headline numbers. */ +export async function refresh(reason = "poll") { + // Coalesce: a websocket burst must not become a burst of requests. + if (inflight) return inflight; + inflight = (async () => { + try { + const [overview, streams, health] = await Promise.all([ + api.overview().catch(() => null), + api.streams(), + api.health().catch(() => null), + ]); + state.streams = streams.streams || []; + if (overview) state.overview = overview; + if (health) { + state.uptimeS = health.uptime_s || 0; + if (health.deps) state.deps = health.deps; + } + state.lastError = ""; + } catch (err) { + state.lastError = err.message || String(err); + } finally { + inflight = null; + emit(reason); + } + })(); + return inflight; +} + +export function setMe(me) { + state.me = me; + emit("me"); +} + +export function isAdmin() { + return state.me && state.me.role === "admin"; +} + +export function canEdit() { + return state.me && (state.me.role === "admin" || state.me.role === "operator"); +} + +// ---------- websocket ---------- + +let ws = null; +let reconnectTimer = null; +let backoff = 1000; +let pollTimer = null; +let stopped = false; + +const scheduleRefresh = (() => { + let t = null; + return (reason) => { + // Several pushes often arrive together (a restart touches health and the + // stream row); one refresh shortly after covers them all. + clearTimeout(t); + t = setTimeout(() => refresh(reason), 220); + }; +})(); + +export function connect() { + stopped = false; + openSocket(); + startPolling(); +} + +export function disconnect() { + stopped = true; + clearTimeout(reconnectTimer); + clearInterval(pollTimer); + pollTimer = null; + if (ws) { + try { + ws.close(); + } catch { + /* already closing */ + } + ws = null; + } + state.connected = false; +} + +function startPolling() { + clearInterval(pollTimer); + // Slow when pushed to, brisk when the socket is down. + pollTimer = setInterval(() => { + if (!state.connected) refresh("poll-fallback"); + else refresh("poll-slow"); + }, 15000); +} + +function openSocket() { + if (stopped) return; + if (ws) { + try { + ws.close(); + } catch { + /* ignore */ + } + } + const proto = location.protocol === "https:" ? "wss:" : "ws:"; + let sock; + try { + sock = new WebSocket(`${proto}//${location.host}/ws/ui`); + } catch { + scheduleReconnect(); + return; + } + ws = sock; + + sock.onopen = () => { + state.connected = true; + backoff = 1000; + emit("ws-open"); + }; + + sock.onmessage = (ev) => { + let msg; + try { + msg = JSON.parse(ev.data); + } catch { + return; + } + switch (msg.type) { + case "agents": + case "agent_online": + case "agent_offline": + state.agents = msg.agents || []; + emit("agents"); + if (msg.type !== "agents") scheduleRefresh("agent-change"); + break; + case "runtime": + case "streams_changed": + case "claims_changed": + scheduleRefresh(msg.type); + break; + default: + break; + } + }; + + sock.onclose = () => { + if (ws === sock) ws = null; + state.connected = false; + emit("ws-close"); + scheduleReconnect(); + }; + + sock.onerror = () => { + // onclose follows, which is where the reconnect is scheduled. + }; +} + +function scheduleReconnect() { + if (stopped) return; + clearTimeout(reconnectTimer); + reconnectTimer = setTimeout(openSocket, backoff); + backoff = Math.min(backoff * 2, 20000); +} diff --git a/apps/streamd/internal/ui/static/js/util.js b/apps/streamd/internal/ui/static/js/util.js new file mode 100644 index 0000000..ccceae2 --- /dev/null +++ b/apps/streamd/internal/ui/static/js/util.js @@ -0,0 +1,350 @@ +// DOM and formatting helpers. +// +// Everything here builds nodes and sets textContent rather than assembling +// HTML strings. A stream title, a log line and an error message all come from +// outside, and node building makes it impossible for them to become markup. + +/** + * el("div.card", {title: "x"}, child, ...) -> HTMLElement + * The tag accepts a CSS-like shorthand: "span.pill.ok" or "#id.cls". + */ +export function el(spec, attrs, ...children) { + let tag = "div"; + const classes = []; + let id = ""; + const m = String(spec).match(/^([a-zA-Z][a-zA-Z0-9-]*)?((?:[.#][^.#]+)*)$/); + if (m) { + if (m[1]) tag = m[1]; + for (const part of (m[2] || "").match(/[.#][^.#]+/g) || []) { + if (part[0] === ".") classes.push(part.slice(1)); + else id = part.slice(1); + } + } + const node = document.createElement(tag); + if (classes.length) node.className = classes.join(" "); + if (id) node.id = id; + + if (attrs && (typeof attrs !== "object" || attrs instanceof Node || Array.isArray(attrs))) { + children.unshift(attrs); + attrs = null; + } + for (const [k, v] of Object.entries(attrs || {})) { + if (v === null || v === undefined || v === false) continue; + if (k === "class") node.className = v; + else if (k === "text") node.textContent = v; + else if (k === "html") throw new Error("el(): raw html is not allowed"); + else if (k === "dataset") Object.assign(node.dataset, v); + else if (k === "style" && typeof v === "object") Object.assign(node.style, v); + else if (k.startsWith("on") && typeof v === "function") node.addEventListener(k.slice(2), v); + else if (v === true) node.setAttribute(k, ""); + else node.setAttribute(k, v); + } + append(node, children); + return node; +} + +export function append(node, children) { + for (const c of children.flat(4)) { + if (c === null || c === undefined || c === false || c === "") continue; + node.append(c instanceof Node ? c : document.createTextNode(String(c))); + } + return node; +} + +export function clear(node) { + while (node.firstChild) node.removeChild(node.firstChild); + return node; +} + +export function $(sel, root = document) { + return root.querySelector(sel); +} + +export function $$(sel, root = document) { + return Array.from(root.querySelectorAll(sel)); +} + +/** pill("ok") -> a status chip. */ +export function pill(text, extraClass) { + const cls = String(text || "unknown").toLowerCase().replace(/[^a-z0-9]+/g, "-"); + return el(`span.pill.${cls}${extraClass ? "." + extraClass : ""}`, { text: text || "unknown" }); +} + +// ---------- formatting ---------- + +export function fmtSeconds(s) { + s = Math.max(0, Math.round(Number(s) || 0)); + if (s < 60) return `${s}s`; + const m = Math.floor(s / 60); + if (m < 60) return `${m}m ${s % 60}s`; + const h = Math.floor(m / 60); + if (h < 24) return `${h}h ${m % 60}m`; + return `${Math.floor(h / 24)}d ${h % 24}h`; +} + +export function fmtAge(s) { + if (s === null || s === undefined || s === 0) return "—"; + const n = Number(s); + if (!isFinite(n)) return "—"; + return n < 10 ? `${n.toFixed(1)}s` : `${Math.round(n)}s`; +} + +export function fmtBitrate(mbps) { + const n = Number(mbps) || 0; + if (n <= 0) return "—"; + return n < 10 ? `${n.toFixed(2)} Mb/s` : `${n.toFixed(1)} Mb/s`; +} + +export function fmtTime(iso) { + if (!iso) return "—"; + const d = new Date(iso); + if (isNaN(d)) return "—"; + return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }); +} + +export function fmtDateTime(iso) { + if (!iso) return "—"; + const d = new Date(iso); + if (isNaN(d)) return "—"; + return d.toLocaleString([], { + month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", + }); +} + +/** fmtRelative("2026-01-01T...") -> "in 4m" / "6m ago" */ +export function fmtRelative(iso) { + if (!iso) return "—"; + const d = new Date(iso); + if (isNaN(d)) return "—"; + const diff = d.getTime() - Date.now(); + const abs = Math.abs(diff); + const mins = Math.round(abs / 60000); + let label; + if (abs < 45000) label = "now"; + else if (mins < 60) label = `${mins}m`; + else if (mins < 60 * 24) label = `${Math.round(mins / 60)}h`; + else label = `${Math.round(mins / 1440)}d`; + if (label === "now") return "now"; + return diff > 0 ? `in ${label}` : `${label} ago`; +} + +export function absURL(path) { + if (!path) return ""; + try { + return new URL(path, location.origin).href; + } catch { + return path; + } +} + +// ---------- interaction ---------- + +const TOAST_MAX = 3; + +export function toast(msg, isError) { + const stack = $("#toast-stack"); + if (!stack) return; + const node = el(`div.toast${isError ? ".err" : ""}`, { + role: isError ? "alert" : "status", + text: String(msg), + }); + stack.append(node); + while (stack.children.length > TOAST_MAX) { + stack.firstElementChild.remove(); + } + const ms = isError ? 5200 : 2400; + setTimeout(() => { + node.classList.add("out"); + setTimeout(() => node.remove(), 200); + }, ms); +} + +/** Mark a button busy for the duration of an async fn. */ +export async function withBusy(btn, fn) { + if (!btn) return fn(); + const prev = btn.getAttribute("aria-busy") === "true"; + if (prev) return; + btn.setAttribute("aria-busy", "true"); + btn.disabled = true; + try { + return await fn(); + } finally { + btn.removeAttribute("aria-busy"); + btn.disabled = false; + } +} + +/** Flip a copy button label to "Copied" briefly; still toasts as fallback. */ +export function markCopied(btn, ms = 1200) { + if (!btn) return; + const prev = btn.dataset.prevLabel || btn.textContent; + btn.dataset.prevLabel = prev; + btn.textContent = "Copied"; + btn.classList.add("copied"); + clearTimeout(Number(btn.dataset.copyTimer || 0)); + btn.dataset.copyTimer = String(setTimeout(() => { + btn.textContent = btn.dataset.prevLabel || "Copy"; + btn.classList.remove("copied"); + }, ms)); +} + +export async function copyText(text, label = "link", btn) { + if (!text) return; + const ok = async () => { + if (btn) markCopied(btn); + else toast(`Copied ${label}`); + }; + try { + await navigator.clipboard.writeText(text); + await ok(); + return; + } catch { + // Clipboard API needs a secure context; plain HTTP behind a proxy is a + // normal deployment, so fall back rather than failing. + } + const ta = el("textarea", { style: { position: "fixed", left: "-9999px" } }); + ta.value = text; + document.body.append(ta); + ta.select(); + try { + document.execCommand("copy"); + await ok(); + } catch { + toast("Could not copy — select the text instead", true); + } + ta.remove(); +} + +/** Open a modal built from nodes. Returns a close function. */ +export function openModal(...children) { + const dlg = $("#modal"); + const body = $("#modal-body"); + // Always rebuild body here. Do not clear on the dialog "close" event: callers + // often close() then immediately openModal() again (e.g. create API key → + // show secret), and an async close handler would wipe the new content. + clear(body); + append(body, children); + const close = () => { + if (dlg.open) dlg.close(); + }; + if (!dlg.open) dlg.showModal(); + return close; +} + +/** A yes/no dialog that resolves to a boolean. */ +export function confirmDialog(title, detail, confirmLabel = "Confirm", danger = true) { + return new Promise((resolve) => { + let settled = false; + const done = (v) => { + if (settled) return; + settled = true; + close(); + resolve(v); + }; + const close = openModal( + el("h2", { text: title }), + detail ? el("p.hint", { text: detail }) : null, + el("div.row.end", { style: { marginTop: "16px" } }, + el("button.ghost", { text: "Cancel", onclick: () => done(false) }), + el(danger ? "button.danger" : "button", { text: confirmLabel, onclick: () => done(true) }), + ), + ); + $("#modal").addEventListener("close", () => done(false), { once: true }); + }); +} + +/** Debounce for filter inputs. */ +export function debounce(fn, ms = 180) { + let t = null; + return (...args) => { + clearTimeout(t); + t = setTimeout(() => fn(...args), ms); + }; +} + +// ---------- sparkline ---------- + +/** + * sparkline(points, pick) -> inline SVG. + * Drawn by hand rather than with a chart library: one series, no axes, and no + * reason to ship a dependency for it. + */ +export function sparkline(points, pick, opts = {}) { + const w = opts.width || 240; + const h = opts.height || 44; + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("class", "spark"); + svg.setAttribute("viewBox", `0 0 ${w} ${h}`); + svg.setAttribute("preserveAspectRatio", "none"); + svg.setAttribute("role", "img"); + + const vals = (points || []).map(pick).map((v) => (isFinite(v) ? Number(v) : 0)); + if (vals.length < 2) { + svg.setAttribute("aria-label", "not enough data yet"); + const t = document.createElementNS(svg.namespaceURI, "text"); + t.setAttribute("x", 4); + t.setAttribute("y", h / 2 + 4); + t.setAttribute("fill", "currentColor"); + t.setAttribute("font-size", "10"); + t.setAttribute("opacity", ".55"); + t.textContent = "collecting…"; + svg.append(t); + return svg; + } + const max = Math.max(...vals, opts.min || 0.0001); + const stepX = w / (vals.length - 1); + const y = (v) => h - 2 - (v / max) * (h - 6); + const pts = vals.map((v, i) => `${(i * stepX).toFixed(2)},${y(v).toFixed(2)}`); + + const area = document.createElementNS(svg.namespaceURI, "path"); + area.setAttribute("class", "area"); + area.setAttribute("d", `M0,${h} L${pts.join(" L")} L${w},${h} Z`); + const line = document.createElementNS(svg.namespaceURI, "polyline"); + line.setAttribute("class", "line"); + line.setAttribute("points", pts.join(" ")); + svg.append(area, line); + svg.setAttribute("aria-label", `${opts.label || "series"}, latest ${vals[vals.length - 1]}, peak ${max}`); + return svg; +} + +// ---------- keyed list rendering ---------- + +/** + * Reconcile a list of rows into a parent by key. + * + * The old dashboard rebuilt the whole table with innerHTML every five + * seconds, which threw away focus, scroll position, text selection and any + * open menu. This updates in place instead: existing rows are patched, new + * ones inserted, departed ones removed. + */ +export function reconcile(parent, items, keyOf, create, update) { + const existing = new Map(); + for (const node of Array.from(parent.children)) { + const k = node.dataset.key; + if (k !== undefined) existing.set(k, node); + else node.remove(); + } + let prev = null; + for (const item of items) { + const key = String(keyOf(item)); + let node = existing.get(key); + if (node) { + existing.delete(key); + update(node, item); + } else { + node = create(item); + node.dataset.key = key; + } + // Place it after the previous row, moving it only when out of order. + const want = prev ? prev.nextSibling : parent.firstChild; + if (node !== want) parent.insertBefore(node, want); + prev = node; + } + for (const node of existing.values()) node.remove(); +} + +/** Set textContent only when it differs, so selections survive updates. */ +export function setText(node, text) { + const s = text === null || text === undefined ? "" : String(text); + if (node.textContent !== s) node.textContent = s; +} diff --git a/apps/streamd/internal/ui/static/js/views/admin.js b/apps/streamd/internal/ui/static/js/views/admin.js new file mode 100644 index 0000000..c718430 --- /dev/null +++ b/apps/streamd/internal/ui/static/js/views/admin.js @@ -0,0 +1,562 @@ +// Schedule overview, global settings, people and keys, and the audit log. + +import { + el, pill, toast, confirmDialog, fmtDateTime, fmtRelative, copyText, clear, append, openModal, setText, +} from "../util.js"; +import { state, isAdmin, canEdit, refresh } from "../store.js"; +import { api } from "../api.js"; +import { daysLabel } from "./dashboard.js"; +import { openScheduleDialog } from "./stream.js"; + +// ---------- schedule overview ---------- + +export function scheduleView(root) { + const body = el("tbody"); + const pick = el("select"); + root.append(el("div.stack", + el("div.card", + el("div.card-head", + el("h2", { text: "All schedules" }), + el("span.spacer"), + canEdit() ? el("div.row", + pick, + el("button.sm", { + text: "+ Add schedule", + onclick: () => { + if (!pick.value) { + toast("Pick a stream first", true); + return; + } + openScheduleDialog(Number(pick.value), load); + }, + }), + ) : null, + ), + el("p.hint", { + text: "A scheduled start enables the stream and brings it up; a scheduled stop takes it down. " + + "Credentials are refreshed a few minutes beforehand.", + }), + el("div.table-wrap", el("table", + el("thead", el("tr", + el("th", { text: "Stream" }), el("th", { text: "Action" }), + el("th", { text: "When" }), el("th", { text: "Next" }), + el("th", { text: "Last fired" }), el("th", { text: "" }), + )), + body, + )), + ), + )); + + function fillStreams() { + const want = (state.streams || []).map((s) => `${s.id}:${s.name}`).join("|"); + if (pick.dataset.opts === want) return; + pick.dataset.opts = want; + clear(pick); + append(pick, [ + el("option", { value: "", text: "Choose a stream…" }), + ...(state.streams || []).map((s) => el("option", { value: s.id, text: s.title || s.name })), + ]); + } + + async function load() { + fillStreams(); + try { + const d = await api.allSchedules(); + const list = d.schedules || []; + clear(body); + if (!list.length) { + body.append(el("tr", el("td.empty", { colspan: "6", text: "Nothing scheduled yet." }))); + return; + } + for (const sc of list) { + body.append(el("tr", + el("td", el("a", { href: `#/stream/${sc.stream_id}`, text: sc.stream_name || `#${sc.stream_id}` })), + el("td", pill(sc.action)), + el("td", + el("div", { text: sc.kind === "weekly" ? `${daysLabel(sc.days_mask)} at ${sc.time_of_day}` : "once" }), + el("div.sub", { text: sc.kind === "weekly" ? sc.tz : fmtDateTime(sc.at_utc) }), + ), + el("td", + el("div", { text: sc.enabled ? fmtRelative(sc.next_fire_at) : "disabled" }), + el("div.sub", { text: sc.enabled ? fmtDateTime(sc.next_fire_at) : "" }), + ), + el("td", { text: sc.last_fired_at ? fmtDateTime(sc.last_fired_at) : "—" }), + el("td.actions", canEdit() ? el("div.row", + el("button.tiny.ghost", { + text: sc.enabled ? "Disable" : "Enable", + onclick: async () => { + try { + await api.patchSchedule(sc.id, { enabled: !sc.enabled }); + load(); + } catch (err) { + toast(err.message, true); + } + }, + }), + el("button.tiny.danger", { + text: "Delete", + onclick: async () => { + if (!(await confirmDialog("Delete this schedule?", "", "Delete"))) return; + try { + await api.deleteSchedule(sc.id); + load(); + } catch (err) { + toast(err.message, true); + } + }, + }), + ) : null), + )); + } + } catch (err) { + clear(body); + body.append(el("tr", el("td.empty", { colspan: "6", text: err.message }))); + } + } + + load(); + refresh("schedule"); + return () => {}; +} + +// ---------- settings ---------- + +export function settingsView(root) { + const wrap = el("div.stack"); + root.append(wrap); + + async function load() { + clear(wrap); + if (!isAdmin()) { + wrap.append(el("div.card", el("p", { text: "Settings are administrator-only." }))); + return; + } + let data; + try { + data = await api.settings(); + } catch (err) { + wrap.append(el("div.card", el("p.msg.err", { text: err.message }))); + return; + } + const vals = data.settings || {}; + const field = (key, label, hint, attrs = {}) => { + const input = el("input", { value: vals[key] || "", placeholder: "default", ...attrs }); + input.dataset.key = key; + return el("label", el("span.lbl", { text: label }), input, hint ? el("small.hint", { text: hint }) : null); + }; + + const form = el("form", + el("div.grid", + field("hls_time", "Segment seconds", "Shorter means lower latency and more requests.", + { type: "number", min: "1", max: "30" }), + field("hls_list_size", "Playlist length", "How many segments stay in a live playlist.", + { type: "number", min: "1", max: "500" }), + field("live_wait", "Downloader live wait", "Seconds the downloader waits before starting.", + { type: "number", min: "0", max: "120" }), + field("ts_ready_bytes", "Buffer before packaging", "Bytes of muxed media to collect before probing.", + { type: "number", min: "0" }), + field("idle_timeout_s", "Default idle timeout", "Applied to new streams when create omits idle_timeout_s.", + { type: "number", min: "30", max: "86400" }), + field("default_on_demand", "Default on-demand", "true/false — applied when create omits on_demand."), + field("default_outputs", "Default outputs JSON", "JSON array of output specs for new streams that omit outputs."), + ), + el("p.hint", { + text: "Blank means the built-in default. Packager knobs apply the next time a stream starts. " + + "On-demand / idle / outputs defaults apply when a new stream is created without those fields.", + }), + el("div.row.end", { style: { marginTop: "14px" } }, el("button", { type: "submit", text: "Save settings" })), + ); + form.addEventListener("submit", async (ev) => { + ev.preventDefault(); + const body = {}; + for (const input of form.querySelectorAll("input[data-key]")) { + body[input.dataset.key] = input.value.trim(); + } + try { + await api.saveSettings(body); + toast("Settings saved — applies at each stream's next start"); + load(); + } catch (err) { + toast(err.message, true); + } + }); + + const eff = data.effective || {}; + wrap.append( + el("div.card", el("div.card-head", el("h2", { text: "Packaging defaults" })), form), + el("div.card", + el("div.card-head", el("h2", { text: "In effect now" })), + el("div.grid", + ...Object.entries(eff).map(([k, v]) => + el("div", el("div.k.muted", { text: k }), el("div.mono", { text: String(v || "built-in default") }))), + ), + ), + ); + } + + load(); + return () => {}; +} + +// ---------- people and API keys ---------- + +export function peopleView(root) { + const usersBox = el("div"); + const keysBox = el("div"); + root.append(el("div.stack", + el("div.card", + el("div.card-head", + el("h2", { text: "People" }), + el("span.spacer"), + el("button.sm", { text: "+ Add person", onclick: () => openUserDialog(loadUsers) }), + ), + el("p.hint", { + text: "Administrators manage people, keys and settings. Operators run and edit streams. " + + "Viewers can look but not touch, and never see credentials.", + }), + usersBox, + ), + el("div.card", + el("div.card-head", + el("h2", { text: "API keys" }), + el("span.spacer"), + el("button.sm", { text: "+ New key", onclick: () => openKeyDialog(loadKeys) }), + ), + el("p.hint", { + text: "Machine credentials, one per capture agent. The secret is shown once, " + + "on creation, and only its hash is stored.", + }), + keysBox, + ), + )); + + if (!isAdmin()) { + clear(usersBox); + usersBox.append(el("p", { text: "Administrator-only." })); + return () => {}; + } + + async function loadUsers() { + try { + const d = await api.users(); + const body = el("tbody"); + for (const u of d.users || []) { + const self = state.me && state.me.user_id === u.id; + body.append(el("tr", + el("td", + el("div", { text: u.username }), + self ? el("div.sub", { text: "that is you" }) : null, + ), + el("td", pill(u.role, "role")), + el("td", u.disabled ? pill("disabled") : pill("active", "ok")), + el("td", { text: u.last_login_at ? fmtDateTime(u.last_login_at) : "never" }), + el("td.actions", el("div.row", + el("select", { + onchange: async (e) => { + try { + await api.patchUser(u.id, { role: e.target.value }); + toast("Role updated"); + loadUsers(); + } catch (err) { + toast(err.message, true); + loadUsers(); + } + }, + }, ...["viewer", "operator", "admin"].map((r) => + el("option", { value: r, text: r, selected: u.role === r }))), + el("button.tiny.ghost", { + text: u.disabled ? "Enable" : "Disable", + onclick: async () => { + try { + await api.patchUser(u.id, { disabled: !u.disabled }); + loadUsers(); + } catch (err) { + toast(err.message, true); + } + }, + }), + el("button.tiny.ghost", { text: "Password", onclick: () => openPasswordDialog(u, self) }), + el("button.tiny.danger", { + text: "Remove", + onclick: async () => { + if (!(await confirmDialog(`Remove ${u.username}?`, + "Their sessions end immediately.", "Remove"))) return; + try { + await api.deleteUser(u.id); + toast("Removed"); + loadUsers(); + } catch (err) { + toast(err.message, true); + } + }, + }), + )), + )); + } + usersBox.replaceChildren(el("div.table-wrap", el("table", + el("thead", el("tr", + el("th", { text: "Username" }), el("th", { text: "Role" }), el("th", { text: "Status" }), + el("th", { text: "Last signed in" }), el("th", { text: "" }), + )), + body, + ))); + } catch (err) { + usersBox.replaceChildren(el("p.msg.err", { text: err.message })); + } + } + + async function loadKeys() { + try { + const d = await api.apiKeys(); + const body = el("tbody"); + for (const k of d.api_keys || []) { + body.append(el("tr", + el("td", { text: k.name }), + el("td", pill(k.role, "role")), + el("td", k.revoked_at ? pill("revoked") : pill("active", "ok")), + el("td", { text: k.last_used_at ? fmtDateTime(k.last_used_at) : "never" }), + el("td.actions", k.revoked_at ? null : el("button.tiny.danger", { + text: "Revoke", + onclick: async () => { + if (!(await confirmDialog(`Revoke "${k.name}"?`, + "Any agent using it stops working immediately.", "Revoke"))) return; + try { + await api.revokeKey(k.id); + toast("Revoked"); + loadKeys(); + } catch (err) { + toast(err.message, true); + } + }, + })), + )); + } + if (!(d.api_keys || []).length) { + body.append(el("tr", el("td.empty", { colspan: "5", text: "No API keys yet." }))); + } + keysBox.replaceChildren(el("div.table-wrap", el("table", + el("thead", el("tr", + el("th", { text: "Name" }), el("th", { text: "Role" }), el("th", { text: "Status" }), + el("th", { text: "Last used" }), el("th", { text: "" }), + )), + body, + ))); + } catch (err) { + keysBox.replaceChildren(el("p.msg.err", { text: err.message })); + } + } + + loadUsers(); + loadKeys(); + return () => {}; +} + +function openUserDialog(onDone) { + const username = el("input", { required: true, autocomplete: "off" }); + const password = el("input", { type: "password", required: true, minlength: "8", autocomplete: "new-password" }); + const role = el("select", ...["operator", "viewer", "admin"].map((r) => el("option", { value: r, text: r }))); + const msg = el("p.msg"); + const form = el("form", + el("h2", { text: "Add person" }), + el("div.stack", { style: { marginTop: "12px" } }, + el("label", el("span.lbl", { text: "Username" }), username), + el("label", el("span.lbl", { text: "Password" }), password, + el("small.hint", { text: "At least 8 characters." })), + el("label", el("span.lbl", { text: "Role" }), role), + ), + msg, + el("div.row.end", { style: { marginTop: "14px" } }, + el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }), + el("button", { type: "submit", text: "Add" }), + ), + ); + form.addEventListener("submit", async (ev) => { + ev.preventDefault(); + try { + await api.createUser({ username: username.value.trim(), password: password.value, role: role.value }); + close(); + toast("Added"); + if (onDone) onDone(); + } catch (err) { + msg.textContent = err.message; + msg.classList.add("err"); + } + }); + const close = openModal(form); + username.focus(); +} + +function openPasswordDialog(user, self) { + const current = el("input", { type: "password", autocomplete: "current-password" }); + const next = el("input", { type: "password", required: true, minlength: "8", autocomplete: "new-password" }); + const msg = el("p.msg"); + const form = el("form", + el("h2", { text: `Change password for ${user.username}` }), + el("p.hint", { + text: self + ? "You will be signed out, because changing a password ends every session for the account." + : "Their sessions end immediately.", + }), + el("div.stack", { style: { marginTop: "12px" } }, + self ? el("label", el("span.lbl", { text: "Current password" }), current) : null, + el("label", el("span.lbl", { text: "New password" }), next), + ), + msg, + el("div.row.end", { style: { marginTop: "14px" } }, + el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }), + el("button", { type: "submit", text: "Change" }), + ), + ); + form.addEventListener("submit", async (ev) => { + ev.preventDefault(); + try { + await api.setPassword(user.id, { current_password: current.value, password: next.value }); + close(); + if (self) { + toast("Password changed — sign in again"); + setTimeout(() => location.reload(), 900); + } else { + toast("Password changed"); + } + } catch (err) { + msg.textContent = err.message; + msg.classList.add("err"); + } + }); + const close = openModal(form); +} + +function openKeyDialog(onDone) { + const name = el("input", { required: true, placeholder: "phone-agent-01" }); + const role = el("select", ...["operator", "viewer", "admin"].map((r) => el("option", { value: r, text: r }))); + const msg = el("p.msg"); + const form = el("form", + el("h2", { text: "New API key" }), + el("p.hint", { text: "A capture agent needs the operator role." }), + el("div.stack", { style: { marginTop: "12px" } }, + el("label", el("span.lbl", { text: "Name" }), name), + el("label", el("span.lbl", { text: "Role" }), role), + ), + msg, + el("div.row.end", { style: { marginTop: "14px" } }, + el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }), + el("button", { type: "submit", text: "Create" }), + ), + ); + form.addEventListener("submit", async (ev) => { + ev.preventDefault(); + try { + const k = await api.createKey({ name: name.value.trim(), role: role.value }); + // Replace this dialog in place — do not close() first. Closing raced the + // next openModal and wiped the secret box empty. + showSecret(k); + if (onDone) onDone(); + } catch (err) { + msg.textContent = err.message; + msg.classList.add("err"); + } + }); + const close = openModal(form); + name.focus(); +} + +function showSecret(key) { + const value = (key && (key.secret || key.token || key.key)) || ""; + if (!value) { + openModal( + el("h2", { text: "Key created, but secret missing" }), + el("p.msg.err", { + text: "The server did not return the one-time secret. Check the streamd version, then revoke this key and create another.", + }), + el("div.row.end", { style: { marginTop: "14px" } }, + el("button", { text: "Close", onclick: () => document.getElementById("modal").close() })), + ); + return; + } + const secret = el("pre.logbox", { text: value, style: { maxHeight: "none" } }); + const close = openModal( + el("h2", { text: `Key "${key.name || "agent"}" created` }), + el("p.hint", { + text: "Copy it now. Only a hash is stored, so this is the one and only time it is shown.", + }), + secret, + el("p.hint", { text: "In apps/agent/agent.yaml set: api_key: " }), + el("div.row.end", { style: { marginTop: "14px" } }, + el("button.ghost", { text: "Copy", onclick: () => copyText(value, "API key") }), + el("button", { text: "Done", onclick: () => close() }), + ), + ); +} + +// ---------- audit log ---------- + +export function auditView(root) { + const body = el("tbody"); + const filter = el("input", { type: "search", placeholder: "Filter by actor…" }); + root.append(el("div.card", + el("div.card-head", + el("h2", { text: "Audit log" }), + el("span.spacer"), + filter, + el("button.ghost.sm", { text: "Reload", onclick: () => load() }), + ), + el("p.hint", { text: "Every change, who made it, and from where. Login attempts included." }), + el("div.table-wrap", el("table", + el("thead", el("tr", + el("th", { text: "When" }), el("th", { text: "Actor" }), el("th", { text: "Action" }), + el("th", { text: "Status" }), el("th", { text: "From" }), + )), + body, + )), + )); + + let rows = []; + + function paint() { + const q = filter.value.trim().toLowerCase(); + const list = q ? rows.filter((e) => String(e.actor || "").toLowerCase().includes(q)) : rows; + clear(body); + if (!list.length) { + body.append(el("tr", el("td.empty", { colspan: "5", text: "Nothing recorded." }))); + return; + } + for (const e of list) { + const bad = e.status >= 400; + body.append(el("tr", + el("td.mono", { text: fmtDateTime(e.at), title: e.at }), + el("td", + el("div", { text: e.actor || "anonymous" }), + el("div.sub", { text: e.actor_kind || "" }), + ), + el("td", + el("div", { text: e.note || `${e.method} ${e.path}` }), + el("div.sub.mono", { text: `${e.method} ${e.path}` }), + ), + el("td", pill(String(e.status), bad ? "down" : "ok")), + el("td.mono", { text: e.ip || "—" }), + )); + } + } + + async function load() { + if (!isAdmin()) { + clear(body); + body.append(el("tr", el("td.empty", { colspan: "5", text: "Administrator-only." }))); + return; + } + try { + const d = await api.audit(300); + rows = d.audit || []; + paint(); + } catch (err) { + clear(body); + body.append(el("tr", el("td.empty", { colspan: "5", text: err.message }))); + } + } + + filter.addEventListener("input", paint); + load(); + return () => {}; +} + +export { setText }; diff --git a/apps/streamd/internal/ui/static/js/views/dashboard.js b/apps/streamd/internal/ui/static/js/views/dashboard.js new file mode 100644 index 0000000..f88e65d --- /dev/null +++ b/apps/streamd/internal/ui/static/js/views/dashboard.js @@ -0,0 +1,180 @@ +// Dashboard: the headline numbers, what is scheduled next, and recent events. + +import { el, pill, fmtRelative, fmtDateTime, setText, reconcile } from "../util.js"; +import { state, subscribe, refresh } from "../store.js"; +import { timeline } from "../components.js"; + +export function dashboard(root) { + const alarmTiles = el("div.tiles"); + const trafficTiles = el("div.tiles"); + const upcomingBody = el("tbody"); + const feed = el("div"); + const attention = el("div.stack"); + + root.append(el("div.stack", + el("div.tile-band", + el("div.tile-band-label", { text: "Alarms" }), + alarmTiles, + ), + el("div.tile-band", + el("div.tile-band-label", { text: "Traffic" }), + trafficTiles, + ), + el("div.card", + el("div.card-head", el("h2", { text: "Needs attention" })), + attention, + ), + el("div.card", + el("div.card-head", + el("h2", { text: "Coming up" }), + el("span.spacer"), + el("a", { href: "#/schedule", text: "Manage schedule" }), + ), + el("div.table-wrap", + el("table", + el("thead", el("tr", + el("th", { text: "When" }), + el("th", { text: "Stream" }), + el("th", { text: "Action" }), + el("th", { text: "Repeats" }), + )), + upcomingBody, + ), + ), + ), + el("div.card", + el("div.card-head", el("h2", { text: "Recent activity" })), + feed, + ), + )); + + function paint() { + const t = (state.overview && state.overview.totals) || {}; + const streams = state.streams || []; + const counts = { + streams: t.streams ?? streams.length, + running: t.running ?? streams.filter((s) => s.health === "ok").length, + down: t.down ?? streams.filter((s) => s.health === "down").length, + starting: t.starting ?? streams.filter((s) => s.health === "starting").length, + idle: t.ondemand_idle ?? 0, + viewers: t.viewers ?? 0, + capture: t.needs_capture ?? 0, + }; + + reconcile(alarmTiles, + [ + { k: "down", label: "Down", v: counts.down, cls: counts.down ? "down alarm" : "" }, + { k: "capture", label: "Need credentials", v: counts.capture, cls: counts.capture ? "warn alarm" : "" }, + { k: "starting", label: "Starting", v: counts.starting, cls: counts.starting ? "warn alarm" : "" }, + ], + (d) => d.k, + (d) => el(`div.tile${d.cls ? "." + d.cls.split(" ").join(".") : ""}`, + el("div.k", { text: d.label }), + el("div.v", { text: String(d.v) }), + ), + (node, d) => { + node.className = `tile${d.cls ? " " + d.cls : ""}`; + setText(node.querySelector(".v"), String(d.v)); + }, + ); + + reconcile(trafficTiles, + [ + { k: "live", label: "Live now", v: counts.running, cls: counts.running ? "ok" : "" }, + { k: "viewers", label: "Viewers", v: counts.viewers, cls: "" }, + { k: "idle", label: "On-demand idle", v: counts.idle, cls: "" }, + { k: "total", label: "Streams", v: counts.streams, cls: "" }, + ], + (d) => d.k, + (d) => el(`div.tile${d.cls ? "." + d.cls.split(" ").join(".") : ""}`, + el("div.k", { text: d.label }), + el("div.v", { text: String(d.v) }), + ), + (node, d) => { + node.className = `tile${d.cls ? " " + d.cls : ""}`; + setText(node.querySelector(".v"), String(d.v)); + }, + ); + + // Needs attention: anything down, or enabled but missing credentials. + const problems = streams.filter( + (s) => s.health === "down" || (s.enabled && s.needs_capture), + ); + if (!problems.length) { + reconcile(attention, [{ id: "none" }], (x) => x.id, + () => el("div.empty", + el("p", { text: "Everything looks healthy." }), + el("p", el("a", { href: "#/streams", text: "View all streams" })), + ), () => {}); + } else { + reconcile(attention, problems, (s) => s.id, + (s) => el("div.row", + el("a", { href: `#/stream/${s.id}`, text: s.title || s.name, class: "grow" }), + el("span.spacer"), + el("span.sub.reason"), + el("span.st"), + ), + (node, s) => { + const a = node.querySelector("a"); + a.href = `#/stream/${s.id}`; + setText(a, s.title || s.name); + setText(node.querySelector(".reason"), + s.needs_capture ? "needs fresh credentials" : (s.last_error || "")); + const st = node.querySelector(".st"); + st.replaceChildren(pill(s.health || "stopped")); + }, + ); + } + + const upcoming = (state.overview && state.overview.upcoming) || []; + if (!upcoming.length) { + reconcile(upcomingBody, [{ id: "none" }], (x) => x.id, + () => el("tr", el("td.empty", { colspan: "4", text: "Nothing scheduled." })), () => {}); + } else { + reconcile(upcomingBody, upcoming, (s) => s.id, + () => el("tr", el("td.when"), el("td.who"), el("td.act"), el("td.rep")), + (tr, s) => { + const when = tr.querySelector(".when"); + when.replaceChildren( + el("div", { text: fmtRelative(s.next_fire_at) }), + el("div.sub", { text: fmtDateTime(s.next_fire_at) }), + ); + const who = tr.querySelector(".who"); + who.replaceChildren(el("a", { + href: `#/stream/${s.stream_id}`, text: s.stream_name || `#${s.stream_id}`, + })); + tr.querySelector(".act").replaceChildren(pill(s.action)); + setText(tr.querySelector(".rep"), + s.kind === "weekly" ? `${daysLabel(s.days_mask)} ${s.time_of_day} ${s.tz}` : "once"); + }, + ); + } + + const events = (state.overview && state.overview.recent_events) || []; + feed.replaceChildren(timeline(events.map((e) => ({ + ...e, + message: e.stream_name ? `${e.stream_name}: ${e.message}` : e.message, + })))); + } + + const off = subscribe(paint); + paint(); + refresh("dashboard"); + // Keep the relative times honest without a full refetch. + const tick = setInterval(paint, 30000); + return () => { + off(); + clearInterval(tick); + }; +} + +const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + +export function daysLabel(mask) { + const bits = Number(mask) || 0; + if (!bits) return "—"; + if (bits === 0x7f) return "every day"; + const days = []; + for (let i = 0; i < 7; i++) if (bits & (1 << i)) days.push(DAY_NAMES[i]); + return days.join(", "); +} diff --git a/apps/streamd/internal/ui/static/js/views/stream-form.js b/apps/streamd/internal/ui/static/js/views/stream-form.js new file mode 100644 index 0000000..b3142aa --- /dev/null +++ b/apps/streamd/internal/ui/static/js/views/stream-form.js @@ -0,0 +1,263 @@ +// Stepped full-page create flow: Basics → Source → Outputs → Review. + +import { + el, clear, append, toast, setText, withBusy, +} from "../util.js"; +import { api } from "../api.js"; +import { refresh, canEdit } from "../store.js"; +import { variantEditor, outputEditor } from "../components.js"; + +const STEPS = ["Basics", "Source", "Outputs", "Review"]; + +export function streamCreate(root) { + if (!canEdit()) { + root.append(el("div.card", + el("h2", { text: "Not available" }), + el("p.hint", { text: "Operators and admins can create streams." }), + )); + return; + } + + let step = 0; + let apps = []; + + const name = el("input", { name: "name", required: true, placeholder: "city-news", maxlength: "64" }); + const title = el("input", { name: "title", placeholder: "City News" }); + const appSel = el("select", { onchange: fillChannels }, + el("option", { value: "", text: "(none)" })); + const chanSel = el("select"); + const tags = el("input", { placeholder: "council, sports" }); + const onDemand = el("input", { type: "checkbox" }); + const enabled = el("input", { type: "checkbox", checked: true }); + const isPublic = el("input", { type: "checkbox", checked: true }); + + const mpd = el("input", { placeholder: "https://…/manifest.mpd" }); + const key = el("textarea", { rows: "3", placeholder: "KID:KEY per line — leave empty for clear streams", spellcheck: "false" }); + const proxy = el("input", { placeholder: "socks5://127.0.0.1:1080 (optional)" }); + const headers = el("input", { value: "{}" }); + const idle = el("input", { type: "number", value: "300", min: "30", max: "86400" }); + const drm = el("select", + el("option", { value: "auto", text: "Auto — infer from the key" }), + el("option", { value: "yes", text: "Encrypted — keys required" }), + el("option", { value: "no", text: "Clear — no keys needed" }), + ); + const rewriter = el("select", + el("option", { value: "", text: "Inherit from module / none" }), + ); + const videoSel = el("input", { placeholder: "for=best (blank = module default)" }); + const audioSel = el("input", { placeholder: "for=best (blank = module default)" }); + const variants = variantEditor(null); + const outputs = outputEditor(null); + + const stepNav = el("div.wizard-steps"); + const panel = el("div"); + const msg = el("p.msg"); + const backBtn = el("button.ghost", { type: "button", text: "Back", onclick: () => go(step - 1) }); + const nextBtn = el("button", { type: "button", text: "Next", onclick: () => go(step + 1) }); + const skipBtn = el("button.ghost", { + type: "button", + text: "Use defaults → Review", + onclick: () => go(3), + }); + const createBtn = el("button", { type: "button", text: "Create stream", onclick: (ev) => submit(ev.currentTarget) }); + const cancelBtn = el("button.ghost", { + type: "button", text: "Cancel", + onclick: () => { location.hash = "#/streams"; }, + }); + const footLeft = el("div.row"); + const footRight = el("div.row"); + + root.append(el("div.card", + el("div.card-head", + el("h2", { text: "Add stream" }), + el("span.spacer"), + el("a", { href: "#/streams", text: "Back to list" }), + ), + stepNav, + panel, + msg, + el("div.wizard-foot", footLeft, el("span.spacer"), footRight), + )); + + function fillChannels() { + clear(chanSel); + const a = apps.find((x) => x.name === appSel.value); + if (!a || !a.channels || !a.channels.length) { + chanSel.append(el("option", { value: "", text: a ? "(module declares no channels)" : "(none)" })); + return; + } + append(chanSel, a.channels.map((c) => + el("option", { value: c.id, text: c.label && c.label !== c.id ? `${c.id} — ${c.label}` : c.id }))); + } + + function body() { + return { + name: name.value.trim(), + title: title.value.trim(), + app: appSel.value, + channel: chanSel.value, + mpd: mpd.value.trim(), + key: key.value.trim(), + proxy: proxy.value.trim(), + headers_json: headers.value.trim() || "{}", + tags: tags.value, + drm_mode: drm.value, + rewriter: rewriter.value, + video_select: videoSel.value.trim(), + audio_select: audioSel.value.trim(), + enabled: enabled.checked, + on_demand: onDemand.checked, + public: isPublic.checked, + idle_timeout_s: parseInt(idle.value, 10) || 300, + variants: variants.readValue(), + outputs: outputs.readValue(), + }; + } + + function validateStep(i) { + setText(msg, ""); + msg.classList.remove("err"); + if (i === 0) { + if (!name.value.trim()) { + setText(msg, "Name is required."); + msg.classList.add("err"); + return false; + } + } + if (i === 1) { + try { + JSON.parse(headers.value || "{}"); + } catch { + setText(msg, "Headers must be valid JSON."); + msg.classList.add("err"); + return false; + } + } + return true; + } + + function go(i) { + if (i > step && !validateStep(step)) return; + step = Math.max(0, Math.min(STEPS.length - 1, i)); + paint(); + } + + function paintSteps() { + clear(stepNav); + append(stepNav, STEPS.map((label, i) => + el(`button.step${i === step ? ".on" : ""}${i < step ? ".done" : ""}`, { + type: "button", + text: `${i + 1}. ${label}`, + onclick: () => { + if (i <= step || validateStep(step)) go(i); + }, + }))); + } + + function paintPanel() { + clear(panel); + if (step === 0) { + panel.append(el("div.grid", + el("label", el("span.lbl", { text: "Name (URL slug)" }), name), + el("label", el("span.lbl", { text: "Title" }), title), + el("label", el("span.lbl", { text: "App module" }), appSel), + el("label", el("span.lbl", { text: "Channel" }), chanSel), + el("label", el("span.lbl", { text: "Tags" }), tags), + el("label.inline-check", enabled, el("span", { text: "Enabled (required for on-demand wake)" })), + el("label.inline-check", onDemand, el("span", { text: "Start on demand, stop when idle" })), + el("label.inline-check", isPublic, el("span", { text: "Publicly fetchable" })), + )); + } else if (step === 1) { + panel.append(el("div.grid", + el("label.span2", el("span.lbl", { text: "Manifest URL" }), mpd), + el("label.span2", el("span.lbl", { text: "Keys" }), key), + el("label", el("span.lbl", { text: "Origin proxy" }), proxy), + el("label", el("span.lbl", { text: "Headers JSON" }), headers), + el("label", el("span.lbl", { text: "Encryption" }), drm), + el("label", el("span.lbl", { text: "Rewriter" }), rewriter), + el("label", el("span.lbl", { text: "Video select" }), videoSel), + el("label", el("span.lbl", { text: "Audio select" }), audioSel), + el("label", el("span.lbl", { text: "Idle timeout (s)" }), idle), + )); + } else if (step === 2) { + panel.append(el("div.stack", variants, outputs)); + } else { + const b = body(); + panel.append(el("div.stack", + el("p.hint", { text: "Confirm and create. You can edit everything later on the stream page." }), + el("div.card", { style: { boxShadow: "none" } }, + row("Name", b.name), + row("Title", b.title || "—"), + row("Module", b.app ? `${b.app} / ${b.channel || "—"}` : "—"), + row("Manifest", b.mpd || "(from module / capture)"), + row("Encryption", b.drm_mode), + row("On-demand", b.on_demand ? "yes" : "no"), + row("Public", b.public ? "yes" : "no"), + row("Variants", String((b.variants || []).filter((v) => v.enabled).length) + " enabled"), + row("Outputs", String((b.outputs || []).filter((o) => o.enabled).length) + " enabled"), + ), + )); + } + } + + function row(k, v) { + return el("div.row", { style: { justifyContent: "space-between", padding: "4px 0" } }, + el("span.muted", { text: k }), + el("span.mono", { text: v }), + ); + } + + function paintFoot() { + clear(footLeft); + clear(footRight); + footLeft.append(cancelBtn); + if (step === 0 && (appSel.value || name.value)) footLeft.append(skipBtn); + if (step > 0) footRight.append(backBtn); + if (step < STEPS.length - 1) footRight.append(nextBtn); + else footRight.append(createBtn); + } + + function paint() { + paintSteps(); + paintPanel(); + paintFoot(); + if (step === 0) name.focus(); + } + + async function submit(btn) { + if (!validateStep(0) || !validateStep(1)) { + go(0); + return; + } + await withBusy(btn, async () => { + try { + const st = await api.createStream(body()); + toast(`Created ${st.name}`); + await refresh("create"); + location.hash = `#/stream/${st.id}`; + } catch (err) { + setText(msg, err.message); + msg.classList.add("err"); + } + }); + } + + (async () => { + try { + const d = await api.apps(); + apps = d.apps || []; + clear(appSel); + appSel.append(el("option", { value: "", text: "(none)" })); + append(appSel, apps.map((a) => el("option", { value: a.name, text: a.name }))); + fillChannels(); + for (const n of d.rewriters || []) { + rewriter.append(el("option", { value: n, text: n })); + } + } catch { + // Module list is optional. + } + paint(); + })(); + + paint(); +} diff --git a/apps/streamd/internal/ui/static/js/views/stream.js b/apps/streamd/internal/ui/static/js/views/stream.js new file mode 100644 index 0000000..a6633b2 --- /dev/null +++ b/apps/streamd/internal/ui/static/js/views/stream.js @@ -0,0 +1,816 @@ +// One stream: everything about it on a single page. + +import { + el, pill, setText, toast, confirmDialog, sparkline, fmtBitrate, fmtSeconds, + fmtAge, fmtDateTime, fmtRelative, copyText, absURL, clear, append, openModal, +} from "../util.js"; +import { state, subscribe, refresh, canEdit, isAdmin, streamById } from "../store.js"; +import { api } from "../api.js"; +import { publishLinks, variantEditor, outputEditor, player, previewChoices, timeline } from "../components.js"; +import { daysLabel } from "./dashboard.js"; + +export function streamView(root, id, tab = "live") { + const activeTab = ["live", "config", "debug"].includes(tab) ? tab : "live"; + const titleRow = el("div.card-head"); + const statRow = el("div.tiles"); + const linksBox = el("div"); + const playerBox = el("div"); + const chartBox = el("div.stack"); + const eventsBox = el("div"); + const logBox = el("div"); + const schedBox = el("div"); + const configBox = el("div"); + + const livePanel = el("div.stack", + el("div.card", + el("div.card-head", el("h2", { text: "Publish endpoints" })), + linksBox, + ), + el("div.card", + el("div.card-head", el("h2", { text: "Preview" })), + playerBox, + ), + ); + const configPanel = el("div.stack", + el("div.card", + el("div.card-head", + el("h2", { text: "Configuration" }), + el("span.spacer"), + isAdmin() ? el("button.danger.sm", { text: "Delete stream", onclick: () => remove() }) : null, + ), + configBox, + ), + el("div.card", + el("div.card-head", el("h2", { text: "Schedule" })), + schedBox, + ), + ); + const debugPanel = el("div.stack", + el("div.card", + el("div.card-head", el("h2", { text: "Health" })), + chartBox, + ), + el("div.card", + el("div.card-head", el("h2", { text: "Timeline" })), + eventsBox, + ), + el("div.card", + el("div.card-head", el("h2", { text: "Logs" })), + logBox, + ), + ); + + const tabNav = el("nav.tabs", + el("a", { + href: `#/stream/${id}`, + class: activeTab === "live" ? "active" : "", + text: "Live", + }), + el("a", { + href: `#/stream/${id}/config`, + class: activeTab === "config" ? "active" : "", + text: "Config", + }), + el("a", { + href: `#/stream/${id}/debug`, + class: activeTab === "debug" ? "active" : "", + text: "Debug", + }), + ); + + livePanel.hidden = activeTab !== "live"; + configPanel.hidden = activeTab !== "config"; + debugPanel.hidden = activeTab !== "debug"; + + root.append(el("div.stack", + el("div.card", titleRow, statRow), + tabNav, + livePanel, + configPanel, + debugPanel, + )); + + let currentPlayer = null; + let detail = null; + + function paintHeader() { + const s = detail || streamById(id); + if (!s) { + clear(titleRow); + titleRow.append(el("h2", { text: "Stream not found" })); + return; + } + clear(titleRow); + append(titleRow, [ + el("div", + el("h2", { text: s.title || s.name }), + el("div.sub.mono", { text: s.name }), + ), + pill(s.health || "stopped"), + s.enabled === false ? pill("out of service", "off") : null, + s.on_demand ? pill("on-demand", "tag") : null, + s.public === false ? pill("private", "tag") : null, + el("span.spacer"), + canEdit() ? el("div.row", + el("button.sm", { text: "Start", onclick: () => act("start") }), + el("button.ghost.sm", { text: "Stop", onclick: () => act("stop") }), + el("button.ghost.sm", { text: "Restart", onclick: () => act("restart") }), + el("button.ghost.sm", { + text: "Refresh keys", + title: "Ask connected agents to capture fresh credentials now", + onclick: requestCapture, + }), + el("button.ghost.sm", { text: "Probe", title: "Fetch the manifest without starting anything", onclick: probe }), + el("button.ghost.sm", { text: "Duplicate", onclick: duplicate }), + ) : null, + ]); + + clear(statRow); + append(statRow, [ + tile("Viewers", s.viewers ? String(s.viewers) : "0"), + tile("Bitrate", fmtBitrate(s.bitrate_mbps)), + tile("Uptime", s.uptime_s ? fmtSeconds(s.uptime_s) : "—"), + tile("Playlist age", fmtAge(s.playlist_age_s)), + tile("Credentials", s.needs_capture ? "stale" : (s.drm_required ? (s.key_valid ? "ok" : "missing") : "not needed"), + s.needs_capture ? "warn" : ""), + tile("PID", s.pid ? String(s.pid) : "—"), + ]); + if (s.last_error) { + statRow.append(el("div.tile.down", + el("div.k", { text: "Last error" }), + el("div", { text: s.last_error, style: { fontSize: "12px", marginTop: "4px" } }), + )); + } + linksBox.replaceChildren(publishLinks(s)); + + // Rebuild the preview when the published ladder changes (new FHD/HD/SD + // links), so the quality picker stays in sync with Publish endpoints. + const choices = previewChoices(s); + const choiceKey = choices.map((c) => c.play_path).join("|"); + if (!currentPlayer || currentPlayer._choiceKey !== choiceKey) { + if (currentPlayer && currentPlayer.stop) currentPlayer.stop(); + const preferred = choices.find((c) => c.master) || choices[0]; + currentPlayer = player({ + path: preferred ? preferred.play_path : (s.play_path || `/hls/${s.name}/index.m3u8`), + choices, + }); + currentPlayer._choiceKey = choiceKey; + playerBox.replaceChildren( + currentPlayer, + el("p.hint", { + text: choices.length > 1 + ? "Pick FHD / HD / SD (or ABR master), then Play preview. Copy any publish link for VLC or ffplay." + : "Play preview uses the source playlist. Copy a publish link for VLC or ffplay.", + }), + ); + } + } + + function tile(label, value, cls) { + return el(`div.tile${cls ? "." + cls : ""}`, + el("div.k", { text: label }), + el("div.v", { text: String(value), style: { fontSize: "18px" } }), + ); + } + + async function loadDetail() { + try { + detail = await api.stream(id); + paintHeader(); + paintConfig(); + } catch (err) { + clear(titleRow); + titleRow.append(el("h2", { text: "Stream not found" }), el("p.hint", { text: err.message })); + } + } + + async function loadMetrics(window = "1h") { + try { + const d = await api.metrics(id, window); + const points = d.metrics || []; + clear(chartBox); + const picker = el("div.row", + el("span.muted", { text: "Window" }), + ...["15m", "1h", "6h", "24h", "7d"].map((w) => + el(`button.tiny${w === window ? "" : ".ghost"}`, { + text: w, onclick: () => loadMetrics(w), + })), + el("span.spacer"), + d.uptime_ratio !== undefined + ? el("span.muted", { text: `healthy ${(d.uptime_ratio * 100).toFixed(1)}% of this window` }) + : null, + ); + append(chartBox, [ + picker, + el("div", + el("h3.muted", { text: "Bitrate (Mb/s)" }), + sparkline(points, (p) => p.bitrate_mbps, { label: "bitrate" }), + ), + el("div", + el("h3.muted", { text: "Viewers" }), + sparkline(points, (p) => p.viewers, { label: "viewers", min: 1 }), + ), + el("div", + el("h3.muted", { text: "Playlist age (s)" }), + sparkline(points, (p) => p.playlist_age_s, { label: "playlist age", min: 10 }), + ), + points.length < 2 + ? el("p.hint", { text: "Health samples are recorded every 5 seconds while the stream runs." }) + : null, + ]); + } catch (err) { + chartBox.replaceChildren(el("p.msg.err", { text: err.message })); + } + } + + async function loadEvents() { + try { + const d = await api.events(id, 120); + eventsBox.replaceChildren(timeline(d.events || [])); + } catch (err) { + eventsBox.replaceChildren(el("p.msg.err", { text: err.message })); + } + } + + let logSource = "nre"; + let logVariant = ""; + let sse = null; + + function paintLogs() { + clear(logBox); + if (!canEdit()) { + logBox.append(el("p.hint", { text: "Logs are available to operators." })); + return; + } + const pre = el("pre.logbox", { text: "loading…" }); + const follow = el("input", { type: "checkbox" }); + const variants = ((detail && detail.variants) || []).filter((v) => v.enabled && v.id !== "fhd"); + const varSel = el("select", { + onchange: (e) => { + logVariant = e.target.value; + load(); + }, + }, + el("option", { value: "", text: "source rung" }), + ...variants.map((v) => el("option", { value: v.id, text: v.label || v.id, selected: logVariant === v.id })), + ); + append(logBox, [ + el("div.row", + el("span.muted", { text: "Source" }), + ...[["nre", "downloader"], ["ffmpeg.err", "packager (stderr)"], ["ffmpeg.out", "packager (stdout)"]] + .map(([val, label]) => + el(`button.tiny${val === logSource ? "" : ".ghost"}`, { + text: label, + onclick: () => { + logSource = val; + paintLogs(); + }, + })), + varSel, + el("span.spacer"), + el("label.inline-check", follow, el("span", { text: "Follow" })), + el("button.tiny.ghost", { text: "Reload", onclick: () => load() }), + ), + pre, + ]); + + follow.addEventListener("change", () => (follow.checked ? startFollow() : stopFollow())); + + async function load() { + stopFollow(); + follow.checked = false; + try { + const d = await api.logs(id, logSource, logVariant); + setText(pre, d.exists ? (d.lines || "(empty)") : (d.note || "no log yet")); + pre.scrollTop = pre.scrollHeight; + } catch (err) { + setText(pre, err.message); + } + } + + function startFollow() { + stopFollow(); + const q = new URLSearchParams({ source: logSource }); + if (logVariant) q.set("variant", logVariant); + sse = new EventSource(`/api/streams/${id}/logs/stream?${q}`); + sse.addEventListener("log", (ev) => { + const atBottom = pre.scrollHeight - pre.scrollTop - pre.clientHeight < 40; + pre.append(document.createTextNode(ev.data + "\n")); + // Bound what the page holds; a busy stream would grow without limit. + if (pre.childNodes.length > 4000) pre.removeChild(pre.firstChild); + if (atBottom) pre.scrollTop = pre.scrollHeight; + }); + sse.addEventListener("note", (ev) => { + pre.append(document.createTextNode(`\n${ev.data}\n`)); + }); + sse.onerror = () => { + stopFollow(); + follow.checked = false; + toast("Live log tail disconnected", true); + }; + } + + function stopFollow() { + if (sse) { + sse.close(); + sse = null; + } + } + + load(); + } + + async function loadSchedules() { + try { + const d = await api.schedules(id); + const list = d.schedules || []; + clear(schedBox); + if (!list.length) schedBox.append(el("div.empty", { text: "Nothing scheduled for this stream." })); + else { + const body = el("tbody"); + for (const sc of list) { + body.append(el("tr", + el("td", pill(sc.action)), + el("td", + el("div", { text: sc.kind === "weekly" ? `${daysLabel(sc.days_mask)} at ${sc.time_of_day}` : "once" }), + el("div.sub", { text: sc.kind === "weekly" ? sc.tz : fmtDateTime(sc.at_utc) }), + ), + el("td", + el("div", { text: sc.enabled ? fmtRelative(sc.next_fire_at) : "disabled" }), + el("div.sub", { text: sc.enabled ? fmtDateTime(sc.next_fire_at) : "" }), + ), + el("td", { text: sc.last_fired_at ? fmtDateTime(sc.last_fired_at) : "—" }), + el("td.actions", canEdit() ? el("div.row", + el("button.tiny.ghost", { + text: sc.enabled ? "Disable" : "Enable", + onclick: async () => { + try { + await api.patchSchedule(sc.id, { enabled: !sc.enabled }); + loadSchedules(); + } catch (err) { + toast(err.message, true); + } + }, + }), + el("button.tiny.danger", { + text: "Delete", + onclick: async () => { + if (!(await confirmDialog("Delete this schedule?", "", "Delete"))) return; + try { + await api.deleteSchedule(sc.id); + loadSchedules(); + } catch (err) { + toast(err.message, true); + } + }, + }), + ) : null), + )); + } + schedBox.append(el("div.table-wrap", el("table", + el("thead", el("tr", + el("th", { text: "Action" }), el("th", { text: "When" }), + el("th", { text: "Next" }), el("th", { text: "Last fired" }), el("th", { text: "" }), + )), + body, + ))); + } + if (canEdit()) { + schedBox.append(el("div.row", { style: { marginTop: "12px" } }, + el("button.sm", { text: "+ Add schedule", onclick: () => openScheduleDialog(id, loadSchedules) }), + el("span.hint", { + text: "Credentials are refreshed a few minutes before a scheduled start.", + }), + )); + } + } catch (err) { + schedBox.replaceChildren(el("p.msg.err", { text: err.message })); + } + } + + function paintConfig() { + const s = detail; + if (!s) return; + clear(configBox); + if (!canEdit()) { + configBox.append(el("p.hint", { text: "Configuration is editable by operators." })); + return; + } + + const title = el("input", { value: s.title || "" }); + const desc = el("input", { value: s.description || "" }); + const tags = el("input", { value: s.tags || "" }); + const mpd = el("input", { value: s.mpd || "" }); + const key = el("textarea", { rows: "3", placeholder: s.has_key ? "unchanged — type to replace" : "none", spellcheck: "false" }); + const proxy = el("input", { placeholder: s.has_proxy ? "unchanged — type to replace" : "none" }); + const headers = el("input", { placeholder: s.has_headers ? "unchanged — type to replace" : "{}" }); + const drm = el("select", + ...[["auto", "Auto — infer from the key"], ["yes", "Encrypted — keys required"], ["no", "Clear — no keys needed"]] + .map(([v, t]) => el("option", { value: v, text: t, selected: (s.drm_mode || "auto") === v })), + ); + const onDemand = el("input", { type: "checkbox", checked: !!s.on_demand }); + const isPublic = el("input", { type: "checkbox", checked: s.public !== false }); + const idle = el("input", { type: "number", value: s.idle_timeout_s || 300, min: "30", max: "86400" }); + const enabled = el("input", { type: "checkbox", checked: !!s.enabled }); + const hlsTime = el("input", { type: "number", min: "1", max: "30", placeholder: "inherit" }); + const listSize = el("input", { type: "number", min: "1", max: "500", placeholder: "inherit" }); + const videoSel = el("input", { value: s.video_select || "", placeholder: "for=best (blank = module default)" }); + const audioSel = el("input", { value: s.audio_select || "", placeholder: "for=best (blank = module default)" }); + const appSel = el("select"); + const chanSel = el("select"); + const rewriter = el("select", + el("option", { value: "", text: "Inherit from module / none", selected: !s.rewriter }), + ); + try { + const ps = JSON.parse(s.settings_json || "{}"); + if (ps.hls_time) hlsTime.value = ps.hls_time; + if (ps.hls_list_size) listSize.value = ps.hls_list_size; + } catch { + // settings_json is operator-entered; a bad value just means no override. + } + const variants = variantEditor(s.variants); + const outputs = outputEditor(s.outputs); + const msg = el("p.msg"); + + function fillChannels(apps) { + clear(chanSel); + const a = (apps || []).find((x) => x.name === appSel.value); + if (a && a.channels && a.channels.length) { + append(chanSel, a.channels.map((c) => + el("option", { + value: c.id, + text: c.label && c.label !== c.id ? `${c.id} — ${c.label}` : c.id, + selected: s.channel === c.id, + }))); + if (s.channel && !a.channels.some((c) => c.id === s.channel)) { + chanSel.append(el("option", { value: s.channel, text: `${s.channel} (stored)`, selected: true })); + } + return; + } + chanSel.append(el("option", { + value: "", text: a ? "(module declares no channels)" : "(none)", selected: !s.channel, + })); + if (s.channel) { + chanSel.append(el("option", { value: s.channel, text: `${s.channel} (stored)`, selected: true })); + } + } + + // Load module/channel/rewriter pickers asynchronously; paint the rest now. + (async () => { + let apps = []; + let rewriters = []; + try { + const d = await api.apps(); + apps = d.apps || []; + rewriters = d.rewriters || []; + } catch { + // Pickers stay empty; free-text overrides still work via stored values. + } + clear(appSel); + append(appSel, [ + el("option", { value: "", text: "(none)", selected: !s.app }), + ...apps.map((a) => el("option", { value: a.name, text: a.name, selected: s.app === a.name })), + ]); + if (s.app && !apps.some((a) => a.name === s.app)) { + appSel.append(el("option", { value: s.app, text: `${s.app} (stored)`, selected: true })); + } + appSel.onchange = () => fillChannels(apps); + fillChannels(apps); + for (const n of rewriters) { + rewriter.append(el("option", { value: n, text: n, selected: s.rewriter === n })); + } + if (s.rewriter && !rewriters.includes(s.rewriter)) { + rewriter.append(el("option", { value: s.rewriter, text: `${s.rewriter} (stored)`, selected: true })); + } + })(); + + const revealBtn = el("button.ghost.sm", { + type: "button", + text: "Reveal stored credentials", + onclick: async () => { + try { + const full = await api.stream(id, true); + key.value = full.key || ""; + proxy.value = full.proxy || ""; + headers.value = full.headers_json || "{}"; + revealBtn.remove(); + toast("Revealed — this was recorded in the audit log"); + } catch (err) { + toast(err.message, true); + } + }, + }); + + const form = el("form", + el("div.grid", + el("label", el("span.lbl", { text: "Title" }), title), + el("label", el("span.lbl", { text: "Tags" }), tags), + el("label.span2", el("span.lbl", { text: "Description" }), desc), + el("label", el("span.lbl", { text: "App module" }), appSel), + el("label", el("span.lbl", { text: "Channel" }), chanSel), + el("label", el("span.lbl", { text: "Rewriter" }), rewriter), + el("label", el("span.lbl", { text: "Encryption" }), drm), + el("label", el("span.lbl", { text: "Video select" }), videoSel), + el("label", el("span.lbl", { text: "Audio select" }), audioSel), + el("label.span2", el("span.lbl", { text: "Manifest URL" }), mpd), + el("label.span2", el("span.lbl", { text: "Keys" }), key), + el("label", el("span.lbl", { text: "Origin proxy" }), proxy), + el("label", el("span.lbl", { text: "Headers JSON" }), headers), + el("label", el("span.lbl", { text: "Idle timeout (s)" }), idle), + el("label", el("span.lbl", { text: "Segment seconds" }), hlsTime), + el("label", el("span.lbl", { text: "Playlist length" }), listSize), + el("label.inline-check", enabled, el("span", { text: "Enabled" })), + el("label.inline-check", onDemand, el("span", { text: "Start on demand" })), + el("label.inline-check", isPublic, el("span", { text: "Publicly fetchable" })), + ), + el("div.row", { style: { marginTop: "8px" } }, revealBtn, + el("span.hint", { text: "Credentials are never sent to the browser unless you ask." })), + el("div.stack", { style: { marginTop: "14px" } }, variants, outputs), + msg, + el("div.row.end", { style: { marginTop: "14px" } }, + el("button", { type: "submit", text: "Save changes" }), + ), + ); + + form.addEventListener("submit", async (ev) => { + ev.preventDefault(); + msg.textContent = ""; + msg.classList.remove("err"); + const body = { + title: title.value, + description: desc.value, + tags: tags.value, + app: appSel.value, + channel: chanSel.value, + rewriter: rewriter.value, + video_select: videoSel.value.trim(), + audio_select: audioSel.value.trim(), + mpd: mpd.value.trim(), + drm_mode: drm.value, + enabled: enabled.checked, + on_demand: onDemand.checked, + public: isPublic.checked, + idle_timeout_s: parseInt(idle.value, 10) || 300, + variants: variants.readValue(), + outputs: outputs.readValue(), + settings_json: JSON.stringify({ + hls_time: parseInt(hlsTime.value, 10) || 0, + hls_list_size: parseInt(listSize.value, 10) || 0, + }), + }; + // Only send a credential when it was actually typed, so saving the form + // does not wipe a key the browser was never given. + if (key.value.trim()) body.key = key.value.trim(); + if (proxy.value.trim()) body.proxy = proxy.value.trim(); + if (headers.value.trim()) { + try { + JSON.parse(headers.value); + } catch { + msg.textContent = "Headers must be valid JSON."; + msg.classList.add("err"); + return; + } + body.headers_json = headers.value.trim(); + } + try { + await api.patchStream(id, body); + toast("Saved"); + await loadDetail(); + await refresh("save"); + loadEvents(); + } catch (err) { + msg.textContent = err.message; + msg.classList.add("err"); + } + }); + + configBox.append(form); + } + + async function requestCapture() { + try { + const res = await api.capture(id); + const n = res.agents_notified || 0; + if (n > 0) toast(`Asked ${n} agent(s) to refresh credentials`); + else toast("No agents connected — capture was queued for when one appears", true); + loadEvents(); + await refresh("capture"); + } catch (err) { + toast(err.message, true); + } + } + + async function act(what) { + const s = detail || streamById(id); + if (what === "stop" && s && s.health === "ok") { + if (!(await confirmDialog(`Stop ${s.title || s.name}?`, "Anyone watching will be disconnected.", "Stop"))) return; + } + try { + await api.action(id, what); + toast(what); + await loadDetail(); + await refresh("action"); + loadEvents(); + } catch (err) { + toast(err.message, true); + } + } + + async function probe() { + toast("Probing the origin…"); + try { + const r = await api.probe(id); + openModal( + el("h2", { text: r.ok ? "Manifest looks good" : "Probe failed" }), + el("p", { text: r.summary || r.error || "" }), + el("div.grid", { style: { marginTop: "12px" } }, + kv("Status", r.status || "—"), + kv("Kind", r.kind || "—"), + kv("Round trip", `${r.elapsed_ms} ms`), + kv("Size", `${r.bytes || 0} bytes`), + kv("Live", r.live ? "yes" : "no"), + kv("Encrypted", r.encrypted ? (r.drm_systems || []).join(", ") || "yes" : "no"), + r.default_kid ? kv("Default KID", r.default_kid) : null, + kv("Keys stored", r.have_keys ? "yes" : "no"), + ), + r.error ? el("p.msg.err", { text: r.error }) : null, + el("div.row.end", { style: { marginTop: "14px" } }, + el("button", { text: "Close", onclick: () => document.getElementById("modal").close() })), + ); + loadEvents(); + } catch (err) { + toast(err.message, true); + } + } + + function kv(k, v) { + return el("div", el("div.k.muted", { text: k }), el("div.mono", { text: String(v) })); + } + + async function duplicate() { + const s = detail || streamById(id); + const name = el("input", { value: `${s.name}-copy` }); + const form = el("form", + el("h2", { text: "Duplicate stream" }), + el("p.hint", { text: "Everything is copied, including credentials. The copy starts disabled." }), + el("label", { style: { marginTop: "10px" } }, el("span.lbl", { text: "New name" }), name), + el("div.row.end", { style: { marginTop: "14px" } }, + el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }), + el("button", { type: "submit", text: "Duplicate" }), + ), + ); + form.addEventListener("submit", async (ev) => { + ev.preventDefault(); + try { + const copy = await api.duplicate(id, { name: name.value.trim() }); + close(); + await refresh("duplicate"); + location.hash = `#/stream/${copy.id}`; + } catch (err) { + toast(err.message, true); + } + }); + const close = openModal(form); + } + + async function remove() { + const s = detail || streamById(id); + if (!(await confirmDialog(`Delete ${s.name}?`, + "The stream, its history and its schedules are removed. This cannot be undone.", + "Delete permanently"))) return; + try { + await api.deleteStream(id); + toast("Deleted"); + await refresh("delete"); + location.hash = "#/streams"; + } catch (err) { + toast(err.message, true); + } + } + + const off = subscribe(() => paintHeader()); + loadDetail(); + if (activeTab === "live" || activeTab === "debug") { + loadMetrics("1h"); + loadEvents(); + } + if (activeTab === "config") loadSchedules(); + if (activeTab === "debug") paintLogs(); + // Prefetch sibling tab data so switching feels instant after first visit. + if (activeTab === "live") { + loadSchedules(); + } + if (activeTab === "config") { + loadEvents(); + } + const tick = setInterval(() => { + if (activeTab === "debug" || activeTab === "live") { + loadMetrics(currentWindow()); + loadEvents(); + } + }, 30000); + let lastWindow = "1h"; + function currentWindow() { + return lastWindow; + } + + return () => { + off(); + clearInterval(tick); + if (sse) sse.close(); + if (currentPlayer) currentPlayer.stop(); + }; +} + +/** Dialog for adding a schedule to a stream. */ +export function openScheduleDialog(streamID, onDone) { + const action = el("select", + el("option", { value: "start", text: "Start the stream" }), + el("option", { value: "stop", text: "Stop the stream" }), + ); + const kind = el("select", { onchange: sync }, + el("option", { value: "weekly", text: "Every week" }), + el("option", { value: "once", text: "Once" }), + ); + const time = el("input", { type: "time", value: "19:00", required: true }); + const at = el("input", { type: "datetime-local" }); + const tz = el("select"); + // Intl gives the browser's own zone; offer it first since it is almost + // always the one an operator means. + const localZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + for (const z of Array.from(new Set([localZone, "UTC", "Europe/Dublin", "Europe/London"]))) { + tz.append(el("option", { value: z, text: z, selected: z === localZone })); + } + const days = [0, 1, 2, 3, 4, 5, 6].map((d) => el("input", { type: "checkbox", checked: d >= 1 && d <= 5 })); + const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + const dayRow = el("div.row", ...days.map((cb, i) => + el("label.inline-check", cb, el("span", { text: dayNames[i] })))); + const weeklyRows = el("div.stack", + el("label", el("span.lbl", { text: "Time of day" }), time), + el("label", el("span.lbl", { text: "Days" }), dayRow), + ); + const onceRow = el("label", el("span.lbl", { text: "Date and time" }), at); + const msg = el("p.msg"); + + function sync() { + weeklyRows.hidden = kind.value !== "weekly"; + onceRow.hidden = kind.value !== "once"; + } + + const form = el("form", + el("h2", { text: "Add schedule" }), + el("div.stack", { style: { marginTop: "12px" } }, + el("label", el("span.lbl", { text: "Action" }), action), + el("label", el("span.lbl", { text: "Repeat" }), kind), + weeklyRows, + onceRow, + el("label", el("span.lbl", { text: "Timezone" }), tz), + ), + el("p.hint", { text: "Times are local to the chosen zone, so an event stays put across a clock change." }), + msg, + el("div.row.end", { style: { marginTop: "14px" } }, + el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }), + el("button", { type: "submit", text: "Add" }), + ), + ); + sync(); + + form.addEventListener("submit", async (ev) => { + ev.preventDefault(); + msg.textContent = ""; + msg.classList.remove("err"); + const body = { action: action.value, kind: kind.value, tz: tz.value }; + if (kind.value === "weekly") { + let mask = 0; + days.forEach((cb, i) => { + if (cb.checked) mask |= 1 << i; + }); + if (!mask) { + msg.textContent = "Pick at least one day."; + msg.classList.add("err"); + return; + } + body.days_mask = mask; + body.time_of_day = time.value; + } else { + if (!at.value) { + msg.textContent = "Pick a date and time."; + msg.classList.add("err"); + return; + } + // Send the local wall-clock value; the server reads it in the zone above. + body.at_utc = at.value.replace("T", " "); + } + try { + await api.createSchedule(streamID, body); + close(); + toast("Schedule added"); + if (onDone) onDone(); + } catch (err) { + msg.textContent = err.message; + msg.classList.add("err"); + } + }); + + const close = openModal(form); +} diff --git a/apps/streamd/internal/ui/static/js/views/streams.js b/apps/streamd/internal/ui/static/js/views/streams.js new file mode 100644 index 0000000..0abf27f --- /dev/null +++ b/apps/streamd/internal/ui/static/js/views/streams.js @@ -0,0 +1,292 @@ +// Streams list: search, filter, sort, bulk actions. Create is a full page. + +import { + el, pill, setText, reconcile, toast, confirmDialog, debounce, fmtAge, clear, append, +} from "../util.js"; +import { state, subscribe, refresh, canEdit } from "../store.js"; +import { api } from "../api.js"; +import { publishLinks, tagList } from "../components.js"; + +const view = { + q: "", + health: "all", + tag: "all", + sort: "name", + dir: 1, + selected: new Set(), +}; + +export function streams(root) { + const tbody = el("tbody"); + const countLabel = el("span.muted"); + const bulkBar = el("div.row"); + + const search = el("input", { + type: "search", placeholder: "Search name, title, tag…", value: view.q, + oninput: debounce((e) => { + view.q = e.target.value.trim().toLowerCase(); + paint(); + }), + }); + const healthSel = el("select", { + onchange: (e) => { + view.health = e.target.value; + paint(); + }, + }, ...["all", "ok", "starting", "down", "stopped"].map((v) => + el("option", { value: v, text: v === "all" ? "Any health" : v, selected: view.health === v }))); + const tagSel = el("select", { + onchange: (e) => { + view.tag = e.target.value; + paint(); + }, + }); + + const head = el("thead", el("tr", + el("th", { style: { width: "28px" } }, el("input", { + type: "checkbox", title: "Select all shown", + onchange: (e) => { + const shown = visible(); + if (e.target.checked) shown.forEach((s) => view.selected.add(s.id)); + else shown.forEach((s) => view.selected.delete(s.id)); + paint(); + }, + })), + sortTh("name", "Stream"), + sortTh("health", "Health"), + sortTh("viewers", "Viewers"), + el("th", { text: "Publish" }), + el("th", { text: "Actions" }), + )); + + root.append(el("div.stack", + el("div.card", + el("div.card-head", + el("h2", { text: "Streams" }), + countLabel, + el("span.spacer"), + search, healthSel, tagSel, + canEdit() ? el("button.sm", { + text: "+ Add stream", + onclick: () => { location.hash = "#/streams/new"; }, + }) : null, + ), + bulkBar, + el("div.table-wrap", el("table", head, tbody)), + ), + )); + + function sortTh(key, label) { + const th = el("th.sortable", { + onclick: () => { + if (view.sort === key) view.dir *= -1; + else { + view.sort = key; + view.dir = 1; + } + paint(); + }, + }, el("span", { text: label }), el("span.arrow")); + th.dataset.sortKey = key; + return th; + } + + function visible() { + let list = (state.streams || []).slice(); + if (view.q) { + list = list.filter((s) => + `${s.name} ${s.title} ${s.tags} ${s.app} ${s.channel}`.toLowerCase().includes(view.q)); + } + if (view.health !== "all") list = list.filter((s) => (s.health || "stopped") === view.health); + if (view.tag !== "all") { + list = list.filter((s) => String(s.tags || "").split(",").includes(view.tag)); + } + const dir = view.dir; + list.sort((a, b) => { + switch (view.sort) { + case "health": + return dir * String(a.health || "").localeCompare(String(b.health || "")); + case "viewers": + return dir * ((a.viewers || 0) - (b.viewers || 0)); + default: + return dir * String(a.name).localeCompare(String(b.name)); + } + }); + return list; + } + + function paint() { + const list = visible(); + const total = (state.streams || []).length; + setText(countLabel, list.length === total ? `${total}` : `${list.length} of ${total}`); + + const tags = new Set(); + for (const s of state.streams || []) { + for (const t of String(s.tags || "").split(",").filter(Boolean)) tags.add(t); + } + const wantTags = ["all", ...Array.from(tags).sort()]; + if (tagSel.dataset.opts !== wantTags.join("|")) { + tagSel.dataset.opts = wantTags.join("|"); + clear(tagSel); + append(tagSel, wantTags.map((t) => + el("option", { value: t, text: t === "all" ? "Any tag" : t, selected: view.tag === t }))); + } + + for (const th of head.querySelectorAll("th.sortable")) { + const arrow = th.querySelector(".arrow"); + setText(arrow, th.dataset.sortKey === view.sort ? (view.dir > 0 ? "▲" : "▼") : ""); + } + + const ids = new Set((state.streams || []).map((s) => s.id)); + for (const id of Array.from(view.selected)) if (!ids.has(id)) view.selected.delete(id); + paintBulk(); + + if (!list.length) { + reconcile(tbody, [{ id: "none" }], (x) => x.id, + () => el("tr", el("td.empty", { colspan: "6" }, + total + ? el("span", { text: "No stream matches these filters." }) + : el("div", + el("p", { text: "No streams yet." }), + canEdit() + ? el("p", el("a", { href: "#/streams/new", text: "Add your first stream" })) + : null, + ), + )), () => {}); + return; + } + + reconcile(tbody, list, (s) => s.id, createRow, updateRow); + } + + function paintBulk() { + const n = view.selected.size; + clear(bulkBar); + if (!n || !canEdit()) return; + append(bulkBar, [ + el("span.muted", { text: `${n} selected` }), + el("button.ghost.sm", { text: "Start", onclick: () => bulk("start") }), + el("button.ghost.sm", { text: "Stop", onclick: () => bulk("stop") }), + el("button.ghost.sm", { text: "Restart", onclick: () => bulk("restart") }), + el("button.ghost.sm", { text: "Clear", onclick: () => { view.selected.clear(); paint(); } }), + ]); + bulkBar.style.marginBottom = "12px"; + } + + async function bulk(action) { + const ids = Array.from(view.selected); + if (!ids.length) return; + if (!(await confirmDialog( + `${action[0].toUpperCase()}${action.slice(1)} ${ids.length} stream(s)?`, + action === "start" + ? "Selected streams will start (or wake) now." + : "Viewers currently watching will be disconnected.", + action[0].toUpperCase() + action.slice(1), + action !== "start", + ))) return; + try { + const res = await api.bulk(ids, action); + const failed = (res.results || []).filter((r) => !r.ok); + if (failed.length) { + toast(`${res.ok_count} ok, ${failed.length} failed: ${failed[0].error}`, true); + } else { + toast(`${action} applied to ${res.ok_count} stream(s)`); + } + view.selected.clear(); + await refresh("bulk"); + } catch (err) { + toast(err.message, true); + } + } + + function createRow(s) { + const tr = el("tr", + el("td", el("input", { + type: "checkbox", class: "sel", + onchange: (e) => { + const id = Number(tr.dataset.key); + if (e.target.checked) view.selected.add(id); + else view.selected.delete(id); + paintBulk(); + }, + })), + el("td.name-cell"), + el("td.health-cell"), + el("td.viewers-cell.mono"), + el("td.links-cell"), + el("td.actions"), + ); + updateRow(tr, s); + return tr; + } + + function flagPills(s) { + const flags = []; + if (s.enabled === false) flags.push(pill("out of service", "off")); + if (s.on_demand) flags.push(pill("on-demand", "tag")); + if (s.public === false) flags.push(pill("private", "tag")); + if (!s.mpd) flags.push(pill("no manifest", "down")); + if (s.needs_capture) flags.push(pill("needs keys", "starting")); + for (const n of Array.from(tagList(s.tags).childNodes)) flags.push(n); + const shown = flags.slice(0, 2); + const rest = flags.length - shown.length; + if (rest > 0) { + const titles = flags.slice(2).map((n) => n.textContent).join(", "); + shown.push(el("span.flag-more", { text: `+${rest}`, title: titles })); + } + return shown; + } + + function updateRow(tr, s) { + tr.querySelector(".sel").checked = view.selected.has(s.id); + + const nameCell = tr.querySelector(".name-cell"); + nameCell.replaceChildren( + el("div", el("a", { href: `#/stream/${s.id}`, text: s.title || s.name })), + el("div.sub.mono", { text: s.name }), + el("div.row", { style: { gap: "4px", marginTop: "3px" } }, ...flagPills(s)), + ); + + tr.querySelector(".health-cell").replaceChildren( + el("div", pill(s.health || "stopped")), + s.last_error ? el("div.sub", { text: s.last_error, title: s.last_error }) : null, + s.playlist_age_s ? el("div.sub", { text: fmtAge(s.playlist_age_s) }) : null, + ); + + setText(tr.querySelector(".viewers-cell"), s.viewers ? String(s.viewers) : "—"); + tr.querySelector(".links-cell").replaceChildren( + publishLinks(s, { limit: 1, compact: true }), + ); + + const actions = tr.querySelector(".actions"); + if (!canEdit()) { + actions.replaceChildren(el("a", { href: `#/stream/${s.id}`, text: "Open" })); + return; + } + actions.replaceChildren(el("div.row", + el("button.ghost.sm", { text: "Start", onclick: () => act(s, "start") }), + el("button.ghost.sm", { text: "Stop", onclick: () => act(s, "stop") }), + el("a.sm", { href: `#/stream/${s.id}`, text: "Open" }), + )); + } + + async function act(s, what) { + if (what === "stop" && s.health === "ok") { + const ok = await confirmDialog(`Stop ${s.title || s.name}?`, + "Anyone watching will be disconnected.", "Stop"); + if (!ok) return; + } + try { + await api.action(s.id, what); + toast(`${s.name}: ${what}`); + await refresh("action"); + } catch (err) { + toast(err.message, true); + } + } + + const off = subscribe(paint); + paint(); + refresh("streams"); + return off; +} diff --git a/apps/streamd/internal/ui/static/vendor/README.md b/apps/streamd/internal/ui/static/vendor/README.md new file mode 100644 index 0000000..ddaa02b --- /dev/null +++ b/apps/streamd/internal/ui/static/vendor/README.md @@ -0,0 +1,13 @@ +# Vendored third-party assets + +These are served from streamd itself rather than a CDN, so the dashboard's +Content-Security-Policy can stay `default-src 'self'`. Loading them from a CDN +would mean trusting a third party with script execution on a page that holds an +operator session. + +| File | Version | Source | +|---|---|---| +| `hls.min.js` | 1.5.17 | https://cdn.jsdelivr.net/npm/hls.js@1.5.17/dist/hls.min.js | + +To update, download the new version, replace the file and change the version +here. Nothing else references the version number. diff --git a/apps/streamd/internal/ui/static/vendor/hls.min.js b/apps/streamd/internal/ui/static/vendor/hls.min.js new file mode 100644 index 0000000..d41730e --- /dev/null +++ b/apps/streamd/internal/ui/static/vendor/hls.min.js @@ -0,0 +1,2 @@ +!function t(e){var r,i;r=this,i=function(){"use strict";function r(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,i)}return r}function i(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,i=new Array(e);r=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function v(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var m={exports:{}};!function(t,e){var r,i,n,a,s;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var n=s.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");return n.path=s.normalizePath(n.path),s.buildURLFromParts(n)}var a=s.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):e;var o=s.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(u.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var h=o.path,d=h.substring(0,h.lastIndexOf("/")+1)+a.path;u.path=s.normalizePath(d)}else u.path=o.path,a.params||(u.params=o.params,a.query||(u.query=o.query));return null===u.path&&(u.path=r.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(u)},parseURL:function(t){var e=r.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(n,"");t.length!==(t=t.replace(a,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=s}(m);var p=m.exports,y=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},E=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=T},T=Number.MAX_SAFE_INTEGER||9007199254740991,S=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t}({}),L=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),A=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({}),R=function(){},b={trace:R,debug:R,log:R,warn:R,info:R,error:R},k=b;function D(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i"):R}(e)}))}function I(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){D(t,"debug","log","info","warn","error");try{k.log('Debug logs enabled for "'+e+'" in hls.js version 1.5.17')}catch(t){k=b}}else k=b}var w=k,C=/^(\d+)x(\d+)$/,_=/(.+?)=(".*?"|.*?)(?:,|$)/g,x=function(){function t(e){"string"==typeof e&&(e=t.parseAttrList(e)),o(this,e)}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=C.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(_.lastIndex=0;null!==(e=_.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1].trim()]=i}return r},s(t,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(t){return"X-"===t.substring(0,2)}))}}]),t}();function P(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}var F=function(){function t(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){var r=e.attr;for(var i in r)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==r[i]){w.warn('DATERANGE tag attribute: "'+i+'" does not match for tags with ID: "'+t.ID+'"'),this._badValueForSameId=i;break}t=o(new x({}),r,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var n=new Date(this.attr["END-DATE"]);y(n.getTime())&&(this._endDate=n)}}return s(t,[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){if(this._endDate)return this._endDate;var t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var t=this.attr.decimalFloatingPoint("DURATION");if(y(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&y(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}]),t}(),M=function(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}},O="audio",N="video",U="audiovideo",B=function(){function t(t){var e;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=((e={})[O]=null,e[N]=null,e[U]=null,e),this.baseurl=t}return t.prototype.setByteRange=function(t,e){var r,i=t.split("@",2);r=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]},s(t,[{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=p.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(t){this._url=t}}]),t}(),G=function(t){function e(e,r){var i;return(i=t.call(this,r)||this)._decryptdata=null,i.rawProgramDateTime=null,i.programDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.stats=new M,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=e,i}l(e,t);var r=e.prototype;return r.setKeyFormat=function(t){if(this.levelkeys){var e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}},r.abortRequests=function(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()},r.setElementaryStreamInfo=function(t,e,r,i,n,a){void 0===a&&(a=!1);var s=this.elementaryStreams,o=s[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:n,partial:a}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[O]=null,t[N]=null,t[U]=null},s(e,[{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{var e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!y(this.programDateTime))return null;var t=y(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e=Object.keys(this.levelkeys),r=e.length;if(r>1||1===r&&this.levelkeys[e[0]].encrypted)return!0}return!1}}]),e}(B),K=function(t){function e(e,r,i,n,a){var s;(s=t.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new M,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=n;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return l(e,t),s(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(B),H=function(){function t(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}return t.prototype.reloaded=function(t){if(!t)return this.advanced=!0,void(this.updated=!0);var e=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},s(t,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&y(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),t}();function V(t){return Uint8Array.from(atob(t),(function(t){return t.charCodeAt(0)}))}function Y(t){var e,r,i=t.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=V(l)):(e=W(l).subarray(0,16),(r=new Uint8Array(16)).set(e,16-e.length),n=r)}}return n}function W(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(function(t){return t.charCodeAt(0)}))}var j="undefined"!=typeof self?self:void 0,q={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},X="org.w3.clearkey",z="com.apple.streamingkeydelivery",Q="com.microsoft.playready",J="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function $(t){switch(t){case z:return q.FAIRPLAY;case Q:return q.PLAYREADY;case J:return q.WIDEVINE;case X:return q.CLEARKEY}}var Z="1077efecc0b24d02ace33c1e52e2fb4b",tt="e2719d58a985b3c9781ab030af78d30e",et="9a04f07998404286ab92e65be0885f95",rt="edef8ba979d64acea3c827dcd51d21ed";function it(t){return t===rt?q.WIDEVINE:t===et?q.PLAYREADY:t===Z||t===tt?q.CLEARKEY:void 0}function nt(t){switch(t){case q.FAIRPLAY:return z;case q.PLAYREADY:return Q;case q.WIDEVINE:return J;case q.CLEARKEY:return X}}function at(t){var e=t.drmSystems,r=t.widevineLicenseUrl,i=e?[q.FAIRPLAY,q.WIDEVINE,q.PLAYREADY,q.CLEARKEY].filter((function(t){return!!e[t]})):[];return!i[q.WIDEVINE]&&r&&i.push(q.WIDEVINE),i}var st,ot=null!=j&&null!=(st=j.navigator)&&st.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function lt(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}var ut,ht=function(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},dt=function(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},ct=function(t,e){for(var r=e,i=0;ht(t,e);)i+=10,i+=ft(t,e+6),dt(t,e+10)&&(i+=10),e+=i;if(i>0)return t.subarray(r,r+i)},ft=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},gt=function(t,e){return ht(t,e)&&ft(t,e+6)+10<=t.length-e},vt=function(t){for(var e=yt(t),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(a);break;case 12:case 13:s=t[h++],u+=String.fromCharCode((31&a)<<6|63&s);break;case 14:s=t[h++],o=t[h++],u+=String.fromCharCode((15&a)<<12|(63&s)<<6|(63&o)<<0)}}return u};function bt(){if(!navigator.userAgent.includes("PlayStation 4"))return ut||void 0===self.TextDecoder||(ut=new self.TextDecoder("utf-8")),ut}var kt={hexDump:function(t){for(var e="",r=0;r>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function Ot(t,e){var r=[];if(!e.length)return r;for(var i=t.byteLength,n=0;n1?n+a:i;if(Ct(t.subarray(n+4,n+8))===e[0])if(1===e.length)r.push(t.subarray(n+8,s));else{var o=Ot(t.subarray(n+8,s),e.slice(1));o.length&&It.apply(r,o)}n=s}return r}function Nt(t){var e=[],r=t[0],i=8,n=xt(t,i);i+=4;var a=0,s=0;0===r?(a=xt(t,i),s=xt(t,i+4),i+=8):(a=Pt(t,i),s=Pt(t,i+8),i+=16),i+=2;var o=t.length+s,l=_t(t,i);i+=2;for(var u=0;u>>31)return w.warn("SIDX has hierarchical references (not supported)"),null;var f=xt(t,h);h+=4,e.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+c-1}}),o+=c,i=h+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:e}}function Ut(t){for(var e=[],r=Ot(t,["moov","trak"]),n=0;n12){var h=4;if(3!==u[h++])break;h=Gt(u,h),h+=2;var d=u[h++];if(128&d&&(h+=2),64&d&&(h+=u[h++]),4!==u[h++])break;h=Gt(u,h);var c=u[h++];if(64!==c)break;if(n+="."+Kt(c),h+=12,5!==u[h++])break;h=Gt(u,h);var f=u[h++],g=(248&f)>>3;31===g&&(g+=1+((7&f)<<3)+((224&u[h])>>5)),n+="."+g}break;case"hvc1":case"hev1":var v=Ot(r,["hvcC"])[0],m=v[1],p=["","A","B","C"][m>>6],y=31&m,E=xt(v,2),T=(32&m)>>5?"H":"L",S=v[12],L=v.subarray(6,12);n+="."+p+y,n+="."+E.toString(16).toUpperCase(),n+="."+T+S;for(var A="",R=L.length;R--;){var b=L[R];(b||A)&&(A="."+b.toString(16).toUpperCase()+A)}n+=A;break;case"dvh1":case"dvhe":var k=Ot(r,["dvcC"])[0],D=k[2]>>1&127,I=k[2]<<5&32|k[3]>>3&31;n+="."+Ht(D)+"."+Ht(I);break;case"vp09":var w=Ot(r,["vpcC"])[0],C=w[4],_=w[5],x=w[6]>>4&15;n+="."+Ht(C)+"."+Ht(_)+"."+Ht(x);break;case"av01":var P=Ot(r,["av1C"])[0],F=P[1]>>>5,M=31&P[1],O=P[2]>>>7?"H":"M",N=(64&P[2])>>6,U=(32&P[2])>>5,B=2===F&&N?U?12:10:N?10:8,G=(16&P[2])>>4,K=(8&P[2])>>3,H=(4&P[2])>>2,V=3&P[2];n+="."+F+"."+Ht(M)+O+"."+Ht(B)+"."+G+"."+K+H+V+"."+Ht(1)+"."+Ht(1)+"."+Ht(1)+".0"}return{codec:n,encrypted:a}}function Gt(t,e){for(var r=e+5;128&t[e++]&&e>1&63;return 39===r||40===r}return 6==(31&e)}function Xt(t,e,r,i){var n=zt(t),a=0;a+=e;for(var s=0,o=0,l=0;a=n.length)break;s+=l=n[a++]}while(255===l);o=0;do{if(a>=n.length)break;o+=l=n[a++]}while(255===l);var u=n.length-a,h=a;if(ou){w.error("Malformed SEI payload. "+o+" is too small, only "+u+" bytes left to parse.");break}if(4===s){if(181===n[h++]){var d=_t(n,h);if(h+=2,49===d){var c=xt(n,h);if(h+=4,1195456820===c){var f=n[h++];if(3===f){var g=n[h++],v=64&g,m=v?2+3*(31&g):0,p=new Uint8Array(m);if(v){p[0]=g;for(var y=1;y16){for(var E=[],T=0;T<16;T++){var S=n[h++].toString(16);E.push(1==S.length?"0"+S:S),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var L=o-16,A=new Uint8Array(L),R=0;R0?(a=new Uint8Array(4),e.length>0&&new DataView(a.buffer).setUint32(0,e.length,!1)):a=new Uint8Array;var l=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(l.buffer).setUint32(0,r.byteLength,!1),function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(t,4),s=0,a=8;s>>24;if(0!==n&&1!==n)return{offset:r,size:e};var a=t.buffer,s=kt.hexDump(new Uint8Array(a,r+12,16)),o=t.getUint32(28),l=null,u=null;if(0===n){if(e-32>8*(15-r)&255;return e}(e);return new t(this.method,this.uri,"identity",this.keyFormatVersions,r)}var i=Y(this.uri);if(i)switch(this.keyFormat){case J:this.pssh=i,i.length>=22&&(this.keyId=i.subarray(i.length-22,i.length-6));break;case Q:var n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Qt(n,null,i);var a=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),s=String.fromCharCode.apply(null,Array.from(a)),o=s.substring(s.indexOf("<"),s.length),l=(new DOMParser).parseFromString(o,"text/xml").getElementsByTagName("KID")[0];if(l){var u=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(u){var h=V(u).subarray(0,16);!function(t){var e=function(t,e,r){var i=t[e];t[e]=t[r],t[r]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(h),this.keyId=h}}break;default:var d=i.subarray(0,16);if(16!==d.length){var c=new Uint8Array(16);c.set(d,16-d.length),d=c}this.keyId=d}if(!this.keyId||16!==this.keyId.byteLength){var f=$t[this.uri];if(!f){var g=Object.keys($t).length%Number.MAX_SAFE_INTEGER;f=new Uint8Array(16),new DataView(f.buffer,12,4).setUint32(0,g),$t[this.uri]=f}this.keyId=f}return this},t}(),te=/\{\$([a-zA-Z0-9-_]+)\}/g;function ee(t){return te.test(t)}function re(t,e,r){if(null!==t.variableList||t.hasVariableRefs)for(var i=r.length;i--;){var n=r[i],a=e[n];a&&(e[n]=ie(t,a))}}function ie(t,e){if(null!==t.variableList||t.hasVariableRefs){var r=t.variableList;return e.replace(te,(function(e){var i=e.substring(2,e.length-1),n=null==r?void 0:r[i];return void 0===n?(t.playlistParsingError||(t.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+i+'"')),e):n}))}return e}function ne(t,e,r){var i,n,a=t.variableList;if(a||(t.variableList=a={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(i))throw new Error('"'+i+'" does not match any query parameter in URI: "'+r+'"');n=s.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+e.message))}}else i=e.NAME,n=e.VALUE;i in a?t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+i+'"')):a[i]=n||""}function ae(t,e,r){var i=e.IMPORT;if(r&&i in r){var n=t.variableList;n||(t.variableList=n={}),n[i]=r[i]}else t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+i+'"'))}function se(t){if(void 0===t&&(t=!0),"undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}var oe={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function le(t,e,r){return void 0===r&&(r=!0),!t.split(",").some((function(t){return!ue(t,e,r)}))}function ue(t,e,r){var i;void 0===r&&(r=!0);var n=se(r);return null!=(i=null==n?void 0:n.isTypeSupported(he(t,e)))&&i}function he(t,e){return e+'/mp4;codecs="'+t+'"'}function de(t){if(t){var e=t.substring(0,4);return oe.video[e]}return 2}function ce(t){return t.split(",").reduce((function(t,e){var r=oe.video[e];return r?(2*r+t)/(t?3:2):(oe.audio[e]+t)/(t?2:1)}),0)}var fe={},ge=/flac|opus/i;function ve(t,e){return void 0===e&&(e=!0),t.replace(ge,(function(t){return function(t,e){if(void 0===e&&(e=!0),fe[t])return fe[t];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t],i=0;i0&&a.length0&&X.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=X.optionalFloat("PART-HOLD-BACK",0),h.holdBack=X.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var z=new x(I);h.partTarget=z.decimalFloatingPoint("PART-TARGET");break;case"PART":var Q=h.partList;Q||(Q=h.partList=[]);var J=g>0?Q[Q.length-1]:void 0,$=g++,Z=new x(I);re(h,Z,["BYTERANGE","URI"]);var tt=new K(Z,E,e,$,J);Q.push(tt),E.duration+=tt.duration;break;case"PRELOAD-HINT":var et=new x(I);re(h,et,["URI"]),h.preloadHint=et;break;case"RENDITION-REPORT":var rt=new x(I);re(h,rt,["URI"]),h.renditionReports=h.renditionReports||[],h.renditionReports.push(rt);break;default:w.warn("line parsed but not handled: "+s)}}}p&&!p.relurl?(d.pop(),v-=p.duration,h.partList&&(h.fragmentHint=p)):h.partList&&(De(E,p),E.cc=m,h.fragmentHint=E,u&&we(E,u,h));var it=d.length,nt=d[0],at=d[it-1];if((v+=h.skippedSegments*h.targetduration)>0&&it&&at){h.averagetargetduration=v/it;var st=at.sn;h.endSN="initSegment"!==st?st:0,h.live||(at.endList=!0),nt&&(h.startCC=nt.cc)}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(v+=h.fragmentHint.duration),h.totalduration=v,h.endCC=m,T>0&&function(t,e){for(var r=t[e],i=e;i--;){var n=t[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(d,T),h},t}();function Ae(t,e,r){var i,n,a=new x(t);re(r,a,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);var s=null!=(i=a.METHOD)?i:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,h=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&w.error("Invalid IV: "+a.IV);var d=o?Le.resolve(o,e):"",c=(u||"1").split("/").map(Number).filter(Number.isFinite);return new Zt(s,d,h,c,l)}function Re(t){var e=new x(t).decimalFloatingPoint("TIME-OFFSET");return y(e)?e:null}function be(t,e){var r=(t||"").split(/[ ,]+/).filter((function(t){return t}));["video","audio","text"].forEach((function(t){var i=r.filter((function(e){return function(t,e){var r=oe[e];return!!r&&!!r[t.slice(0,4)]}(e,t)}));i.length&&(e[t+"Codec"]=i.join(","),r=r.filter((function(t){return-1===i.indexOf(t)})))})),e.unknownCodecs=r}function ke(t,e,r){var i=e[r];i&&(t[r]=i)}function De(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),y(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Ie(t,e,r,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function we(t,e,r){t.levelkeys=e;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some((function(t){return e[t].isCommonEncryption}))||i.push(t)}var Ce="manifest",_e="level",xe="audioTrack",Pe="subtitleTrack",Fe="main",Me="audio",Oe="subtitle";function Ne(t){switch(t.type){case xe:return Me;case Pe:return Oe;default:return Fe}}function Ue(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}var Be=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}var e=t.prototype;return e.startLoad=function(t){},e.stopLoad=function(){this.destroyInternalLoaders()},e.registerListeners=function(){var t=this.hls;t.on(S.MANIFEST_LOADING,this.onManifestLoading,this),t.on(S.LEVEL_LOADING,this.onLevelLoading,this),t.on(S.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(S.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(S.MANIFEST_LOADING,this.onManifestLoading,this),t.off(S.LEVEL_LOADING,this.onLevelLoading,this),t.off(S.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(S.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,n=new(r||i)(e);return this.loaders[t.type]=n,n},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Ce,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,n=e.pathwayId,a=e.url,s=e.deliveryDirectives;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:_e,url:a,deliveryDirectives:s})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,n=e.url,a=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:xe,url:n,deliveryDirectives:a})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,n=e.url,a=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:Pe,url:n,deliveryDirectives:a})},e.load=function(t){var e,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(t);if(s){var l=s.context;if(l&&l.url===t.url&&l.level===t.level)return void w.trace("[playlist-loader]: playlist request ongoing");w.log("[playlist-loader]: aborting previous loader for type: "+t.type),s.abort()}if(r=t.type===Ce?a.manifestLoadPolicy.default:o({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),y(null==(e=t.deliveryDirectives)?void 0:e.part)&&(t.type===_e&&null!==t.level?i=this.hls.levels[t.level].details:t.type===xe&&null!==t.id?i=this.hls.audioTracks[t.id].details:t.type===Pe&&null!==t.id&&(i=this.hls.subtitleTracks[t.id].details),i)){var u=i.partTarget,h=i.targetduration;if(u&&h){var d=1e3*Math.max(3*u,.8*h);r=o({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var c=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},g={onSuccess:function(t,e,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=t.data;0===s.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),Le.isMediaPlaylist(s)?n.handleTrackOrLevelPlaylist(t,e,r,i||null,a):n.handleMasterPlaylist(t,e,r,i)):n.handleManifestParsingError(t,r,new Error("no EXTM3U delimiter"),i||null,e)},onError:function(t,e,r,i){n.handleNetworkError(e,r,!1,t,i)},onTimeout:function(t,e,r){n.handleNetworkError(e,r,!0,void 0,t)}};s.load(t,f,g)},e.handleMasterPlaylist=function(t,e,r,i){var n=this.hls,a=t.data,s=Ue(t,r),o=Le.parseMasterPlaylist(a,s);if(o.playlistParsingError)this.handleManifestParsingError(t,r,o.playlistParsingError,i,e);else{var l=o.contentSteering,u=o.levels,h=o.sessionData,d=o.sessionKeys,c=o.startTimeOffset,f=o.variableList;this.variableList=f;var g=Le.parseMasterPlaylistMedia(a,s,o),v=g.AUDIO,m=void 0===v?[]:v,p=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];m.length&&(m.some((function(t){return!t.url}))||!u[0].audioCodec||u[0].attrs.AUDIO||(w.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new x({}),bitrate:0,url:""}))),n.trigger(S.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:p,captions:y,contentSteering:l,url:s,stats:e,networkDetails:i,sessionData:h,sessionKeys:d,startTimeOffset:c,variableList:f})}},e.handleTrackOrLevelPlaylist=function(t,e,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=Ue(t,r),h=y(o)?o:y(s)?s:0,d=Ne(r),c=Le.parseLevelPlaylist(t.data,u,h,d,0,this.variableList);if(l===Ce){var f={attrs:new x({}),bitrate:0,details:c,name:"",url:u};a.trigger(S.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),r.levelDetails=c,this.handlePlaylistLoaded(c,t,e,r,i,n)},e.handleManifestParsingError=function(t,e,r,i,n){this.hls.trigger(S.ERROR,{type:L.NETWORK_ERROR,details:A.MANIFEST_PARSING_ERROR,fatal:e.type===Ce,url:t.url,err:r,error:r,reason:r.message,response:t,context:e,networkDetails:i,stats:n})},e.handleNetworkError=function(t,e,r,n,a){void 0===r&&(r=!1);var s="A network "+(r?"timeout":"error"+(n?" (status "+n.code+")":""))+" occurred while loading "+t.type;t.type===_e?s+=": "+t.level+" id: "+t.id:t.type!==xe&&t.type!==Pe||(s+=" id: "+t.id+' group-id: "'+t.groupId+'"');var o=new Error(s);w.warn("[playlist-loader]: "+s);var l=A.UNKNOWN,u=!1,h=this.getInternalLoader(t);switch(t.type){case Ce:l=r?A.MANIFEST_LOAD_TIMEOUT:A.MANIFEST_LOAD_ERROR,u=!0;break;case _e:l=r?A.LEVEL_LOAD_TIMEOUT:A.LEVEL_LOAD_ERROR,u=!1;break;case xe:l=r?A.AUDIO_TRACK_LOAD_TIMEOUT:A.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case Pe:l=r?A.SUBTITLE_TRACK_LOAD_TIMEOUT:A.SUBTITLE_LOAD_ERROR,u=!1}h&&this.resetInternalLoader(t.type);var d={type:L.NETWORK_ERROR,details:l,fatal:u,url:t.url,loader:h,context:t,error:o,networkDetails:e,stats:a};if(n){var c=(null==e?void 0:e.url)||t.url;d.response=i({url:c,data:void 0},n)}this.hls.trigger(S.ERROR,d)},e.handlePlaylistLoaded=function(t,e,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.id,h=i.groupId,d=i.deliveryDirectives,c=Ue(e,i),f=Ne(i),g="number"==typeof i.level&&f===Fe?l:void 0;if(t.fragments.length){t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));var v=t.playlistParsingError;if(v)s.trigger(S.ERROR,{type:L.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:v,reason:v.message,response:e,context:i,level:g,parent:f,networkDetails:n,stats:r});else switch(t.live&&a&&(a.getCacheAge&&(t.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case Ce:case _e:s.trigger(S.LEVEL_LOADED,{details:t,level:g||0,id:u||0,stats:r,networkDetails:n,deliveryDirectives:d});break;case xe:s.trigger(S.AUDIO_TRACK_LOADED,{details:t,id:u||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:d});break;case Pe:s.trigger(S.SUBTITLE_TRACK_LOADED,{details:t,id:u||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:d})}}else{var m=new Error("No Segments found in Playlist");s.trigger(S.ERROR,{type:L.NETWORK_ERROR,details:A.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:e,context:i,level:g,parent:f,networkDetails:n,stats:r})}},t}();function Ge(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function Ke(t,e){var r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(r){w.debug("[texttrack-utils]: "+r);try{var i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){w.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+t)}}"disabled"===r&&(t.mode=r)}function He(t){var e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(var r=t.cues.length;r--;)t.removeCue(t.cues[r]);"disabled"===e&&(t.mode=e)}function Ve(t,e,r,i){var n=t.mode;if("disabled"===n&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var a=function(t,e,r){var i=[],n=function(t,e){if(et[r].endTime)return-1;for(var i=0,n=r;i<=n;){var a=Math.floor((n+i)/2);if(et[a].startTime&&i-1)for(var a=n,s=t.length;a=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(t.cues,e,r),s=0;sQe&&(d=Qe),d-h<=0&&(d=h+.25);for(var c=0;ce.startDate&&(!t||e.startDate.05&&this.forwardBufferLength>1){var l=Math.min(2,Math.max(1,a)),u=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(l,Math.max(1,u))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},e.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},e.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},s(t,[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var h=i;return u+Math.min(1*this.stallCount,h)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,n=t-e-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return(r?t.buffered.end(r-1):e.edge)-this.currentTime}}]),t}(),tr=["NONE","TYPE-0","TYPE-1",null],er=["SDR","PQ","HLG"],rr="",ir="YES",nr="v2";function ar(t){var e=t.canSkipUntil,r=t.canSkipDateRanges,i=t.age;return e&&it.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration:e.start=Math.max(t.start-e.duration,0)}function hr(t,e,r,i,n,a){i-r<=0&&(w.warn("Fragment should have a positive duration",e),i=r+e.duration,a=n+e.duration);var s=r,o=i,l=e.startPTS,u=e.endPTS;if(y(l)){var h=Math.abs(l-r);y(e.deltaPTS)?e.deltaPTS=Math.max(h,e.deltaPTS):e.deltaPTS=h,s=Math.max(r,l),r=Math.min(r,l),n=Math.min(n,e.startDTS),o=Math.min(i,u),i=Math.max(i,u),a=Math.max(a,e.endDTS)}var d=r-e.start;0!==e.start&&(e.start=r),e.duration=i-e.start,e.startPTS=r,e.maxStartPTS=s,e.startDTS=n,e.endPTS=i,e.minEndPTS=o,e.endDTS=a;var c,f=e.sn;if(!t||ft.endSN)return 0;var g=f-t.startSN,v=t.fragments;for(v[g]=e,c=g;c>0;c--)ur(v[c],v[c-1]);for(c=g;c=0;n--){var a=i[n].initSegment;if(a){r=a;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var s,l,u,h,d,c=0;if(function(t,e,r){for(var i=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,s=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=n;u<=a;u++){var h=l[s+u],d=o[u];i&&!d&&u=i.length||fr(e,i[r].start)}function fr(t,e){if(e){for(var r=t.fragments,i=t.skippedSegments;i499)}(n)||!!r);return t.shouldRetry?t.shouldRetry(t,e,r,i,a):a}var Lr=function(t,e){for(var r=0,i=t.length-1,n=null,a=null;r<=i;){var s=e(a=t[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function Ar(t,e,r,i,n){void 0===r&&(r=0),void 0===i&&(i=0),void 0===n&&(n=.005);var a=null;if(t){a=e[t.sn-e[0].sn+1]||null;var s=t.endDTS-r;s>0&&s<15e-7&&(r+=15e-7)}else 0===r&&0===e[0].start&&(a=e[0]);if(a&&((!t||t.level===a.level)&&0===Rr(r,i,a)||function(t,e,r){if(e&&0===e.start&&e.level0){var i=e.tagList.reduce((function(t,e){return"INF"===e[0]&&(t+=parseFloat(e[1])),t}),r);return t.start<=i}return!1}(a,t,Math.min(n,i))))return a;var o=Lr(e,Rr.bind(null,r,i));return!o||o===t&&a?a:o}function Rr(t,e,r){if(void 0===t&&(t=0),void 0===e&&(e=0),r.start<=t&&r.start+r.duration>t)return 0;var i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function br(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}var kr=0,Dr=2,Ir=3,wr=5,Cr=0,_r=1,xr=2,Pr=function(){function t(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=w.log.bind(w,"[info]:"),this.warn=w.warn.bind(w,"[warning]:"),this.error=w.error.bind(w,"[error]:"),this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(S.ERROR,this.onError,this),t.on(S.MANIFEST_LOADING,this.onManifestLoading,this),t.on(S.LEVEL_UPDATED,this.onLevelUpdated,this)},e.unregisterListeners=function(){var t=this.hls;t&&(t.off(S.ERROR,this.onError,this),t.off(S.ERROR,this.onErrorOut,this),t.off(S.MANIFEST_LOADING,this.onManifestLoading,this),t.off(S.LEVEL_UPDATED,this.onLevelUpdated,this))},e.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},e.startLoad=function(t){},e.stopLoad=function(){this.playlistError=0},e.getVariantLevelIndex=function(t){return(null==t?void 0:t.type)===Fe?t.level:this.hls.loadLevel},e.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},e.onLevelUpdated=function(){this.playlistError=0},e.onError=function(t,e){var r,i;if(!e.fatal){var n=this.hls,a=e.context;switch(e.details){case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case A.FRAG_PARSING_ERROR:if(null!=(r=e.frag)&&r.gap)return void(e.errorAction={action:kr,flags:Cr});case A.FRAG_GAP:case A.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Dr);case A.LEVEL_EMPTY_ERROR:case A.LEVEL_PARSING_ERROR:var s,o,l=e.parent===Fe?e.level:n.loadLevel;return void(e.details===A.LEVEL_EMPTY_ERROR&&null!=(s=e.context)&&null!=(o=s.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,l):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,l)));case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.SUBTITLE_LOAD_ERROR:case A.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){var u=n.levels[n.loadLevel];if(u&&(a.type===xe&&u.hasAudioGroup(a.groupId)||a.type===Pe&&u.hasSubtitleGroup(a.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=Dr,void(e.errorAction.flags=_r)}return;case A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var h=n.levels[n.loadLevel],d=null==h?void 0:h.attrs["HDCP-LEVEL"];return void(d?e.errorAction={action:Dr,flags:xr,hdcpLevel:d}:this.keySystemError(e));case A.BUFFER_ADD_CODEC_ERROR:case A.REMUX_ALLOC_ERROR:case A.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(i=e.level)?i:n.loadLevel));case A.INTERNAL_EXCEPTION:case A.BUFFER_APPENDING_ERROR:case A.BUFFER_FULL_ERROR:case A.LEVEL_SWITCH_ERROR:case A.BUFFER_STALLED_ERROR:case A.BUFFER_SEEK_OVER_HOLE:case A.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:kr,flags:Cr})}e.type===L.KEY_SYSTEM_ERROR&&this.keySystemError(e)}},e.keySystemError=function(t){var e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)},e.getPlaylistRetryOrSwitchAction=function(t,e){var r=yr(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(Sr(r,i,pr(t),t.response))return{action:wr,flags:Cr,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(t,e);return r&&(n.retryConfig=r,n.retryCount=i),n},e.getFragRetryOrSwitchAction=function(t){var e=this.hls,r=this.getVariantLevelIndex(t.frag),i=e.levels[r],n=e.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=yr(t.details.startsWith("key")?s:a,t),l=e.levels.reduce((function(t,e){return t+e.fragmentError}),0);if(i&&(t.details!==A.FRAG_GAP&&i.fragmentError++,Sr(o,l,pr(t),t.response)))return{action:wr,flags:Cr,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(t,r);return o&&(u.retryConfig=o,u.retryCount=l),u},e.getLevelSwitchAction=function(t,e){var r=this.hls;null==e&&(e=r.loadLevel);var i=this.hls.levels[e];if(i){var n,a,s=t.details;i.loadError++,s===A.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,h=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||(r.loadLevel=-1);for(var c,f=null==(n=t.frag)?void 0:n.type,g=(f===Me&&s===A.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(s===A.BUFFER_ADD_CODEC_ERROR||s===A.BUFFER_APPEND_ERROR))&&l.some((function(t){var e=t.audioCodec;return i.audioCodec!==e})),v="video"===t.sourceBufferName&&(s===A.BUFFER_ADD_CODEC_ERROR||s===A.BUFFER_APPEND_ERROR)&&l.some((function(t){var e=t.codecSet,r=t.audioCodec;return i.codecSet!==e&&i.audioCodec===r})),m=null!=(a=t.context)?a:{},p=m.type,y=m.groupId,E=function(){var e=(T+u)%l.length;if(e!==u&&e>=h&&e<=d&&0===l[e].loadError){var r,n,a=l[e];if(s===A.FRAG_GAP&&f===Fe&&t.frag){var c=l[e].details;if(c){var m=Ar(t.frag,c.fragments,t.frag.start);if(null!=m&&m.gap)return 0}}else{if(p===xe&&a.hasAudioGroup(y)||p===Pe&&a.hasSubtitleGroup(y))return 0;if(f===Me&&null!=(r=i.audioGroups)&&r.some((function(t){return a.hasAudioGroup(t)}))||f===Oe&&null!=(n=i.subtitleGroups)&&n.some((function(t){return a.hasSubtitleGroup(t)}))||g&&i.audioCodec===a.audioCodec||!g&&i.audioCodec!==a.audioCodec||v&&i.codecSet===a.codecSet)return 0}return o=e,1}},T=l.length;T--&&(0===(c=E())||1!==c););if(o>-1&&r.loadLevel!==o)return t.levelRetry=!0,this.playlistError=0,{action:Dr,flags:Cr,nextAutoLevel:o}}return{action:Dr,flags:_r}},e.onErrorOut=function(t,e){var r;switch(null==(r=e.errorAction)?void 0:r.action){case kr:break;case Dr:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===A.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn('MediaSource ended after "'+e.sourceBufferName+'" sourceBuffer append error. Attempting to recover from media error.'),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()},e.sendAlternateToPenaltyBox=function(t){var e=this.hls,r=t.errorAction;if(r){var i=r.flags,n=r.hdcpLevel,a=r.nextAutoLevel;switch(i){case Cr:this.switchLevel(t,a);break;case xr:n&&(e.maxHdcpLevel=tr[tr.indexOf(n)-1],r.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+e.maxHdcpLevel+'" or lower')}r.resolved||this.switchLevel(t,a)}},e.switchLevel=function(t,e){void 0!==e&&t.errorAction&&(this.warn("switching to level "+e+" after "+t.details),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)},t}(),Fr=function(){function t(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=w.log.bind(w,e+":"),this.warn=w.warn.bind(w,e+":"),this.hls=t}var e=t.prototype;return e.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},e.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},e.startLoad=function(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()},e.stopLoad=function(){this.canLoad=!1,this.clearTimer()},e.switchParams=function(t,e,r){var i=null==e?void 0:e.renditionReports;if(i){for(var n=-1,a=0;a=0&&d>e.partTarget&&(h+=1)}var c=r&&ar(r);return new sr(u,h>=0?h:void 0,c)}}},e.loadPlaylist=function(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())},e.shouldLoadPlaylist=function(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)},e.shouldReloadPlaylist=function(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)},e.playlistLoaded=function(t,e,r){var i=this,n=e.details,a=e.stats,s=self.performance.now(),o=a.loading.first?Math.max(0,s-a.loading.first):0;if(n.advancedDateTime=Date.now()-o,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log("live playlist "+t+" "+(n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED")),r&&n.fragments.length>0&&dr(r,n),!this.canLoad||!n.live)return;var l,u=void 0,h=void 0;if(n.canBlockReload&&n.endSN&&n.advanced){var d=this.hls.config.lowLatencyMode,c=n.lastPartSn,f=n.endSN,g=n.lastPartIndex,v=c===f;-1!==g?(u=v?f+1:c,h=v?d?0:g:g+1):u=f+1;var m=n.age,p=m+n.ageHeader,y=Math.min(p-n.partTarget,1.5*n.targetduration);if(y>0){if(r&&y>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+y+" with playlist age: "+n.age),y=0;else{var E=Math.floor(y/n.targetduration);u+=E,void 0!==h&&(h+=Math.round(y%n.targetduration/n.partTarget)),this.log("CDN Tune-in age: "+n.ageHeader+"s last advanced "+m.toFixed(2)+"s goal: "+y+" skip sn "+E+" to part "+h)}n.tuneInGoal=y}if(l=this.getDeliveryDirectives(n,e.deliveryDirectives,u,h),d||!v)return void this.loadPlaylist(l)}else(n.canBlockReload||n.canSkipUntil)&&(l=this.getDeliveryDirectives(n,e.deliveryDirectives,u,h));var T=this.hls.mainForwardBufferInfo,S=T?T.end-T.len:0,L=function(t,e){void 0===e&&(e=1/0);var r=1e3*t.targetduration;if(t.updated){var i=t.fragments;if(i.length&&4*r>e){var n=1e3*i[i.length-1].duration;nthis.requestScheduled+L&&(this.requestScheduled=a.loading.start),void 0!==u&&n.canBlockReload?this.requestScheduled=a.loading.first+L-(1e3*n.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+L=u.maxNumRetry)return!1;if(i&&null!=(d=t.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var c=Er(u,l);this.timer=self.setTimeout((function(){return e.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" in '+c+"ms")}t.levelRetry=!0,n.resolved=!0}return h},t}(),Mr=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),Or=function(){function t(t,e,r,i){void 0===i&&(i=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Mr(t),this.fast_=new Mr(e),this.defaultTTFB_=i,this.ttfb_=new Mr(t)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==t&&(this.slow_=new Mr(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.fast_=new Mr(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new Mr(t,n.getEstimate(),n.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.sampleTTFB=function(t){var e=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(r,Math.max(t,5))},e.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},e.destroy=function(){},t}(),Nr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Ur={};function Br(t,e,r){var n=t.videoCodec,a=t.audioCodec;if(!n||!a||!r)return Promise.resolve(Nr);var s={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},o=t.videoRange;"SDR"!==o&&(s.transferFunction=o.toLowerCase());var l=n.split(",").map((function(t){return{type:"media-source",video:i(i({},s),{},{contentType:he(t,"video")})}}));return a&&t.audioGroups&&t.audioGroups.forEach((function(t){var r;t&&(null==(r=e.groups[t])||r.tracks.forEach((function(e){if(e.groupId===t){var r=e.channels||"",i=parseFloat(r);y(i)&&i>2&&l.push.apply(l,a.split(",").map((function(t){return{type:"media-source",audio:{contentType:he(t,"audio"),channels:""+i}}})))}})))})),Promise.all(l.map((function(t){var e=function(t){var e=t.audio,r=t.video,i=r||e;if(i){var n=i.contentType.split('"')[1];if(r)return"r"+r.height+"x"+r.width+"f"+Math.ceil(r.framerate)+(r.transferFunction||"sd")+"_"+n+"_"+Math.ceil(r.bitrate/1e5);if(e)return"c"+e.channels+(e.spatialRendering?"s":"n")+"_"+n}return""}(t);return Ur[e]||(Ur[e]=r.decodingInfo(t))}))).then((function(t){return{supported:!t.some((function(t){return!t.supported})),configurations:l,decodingInfoResults:t}})).catch((function(t){return{supported:!1,configurations:l,decodingInfoResults:[],error:t}}))}function Gr(t,e){var r=!1,i=[];return t&&(r="SDR"!==t,i=[t]),e&&(i=e.allowedVideoRanges||er.slice(0),i=(r=void 0!==e.preferHDR?e.preferHDR:function(){if("function"==typeof matchMedia){var t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}())?i.filter((function(t){return"SDR"!==t})):["SDR"]),{preferHDR:r,allowedVideoRanges:i}}function Kr(t,e){w.log('[abr] start candidates with "'+t+'" ignored because '+e)}function Hr(t,e,r){if("attrs"in t){var i=e.indexOf(t);if(-1!==i)return i}for(var n=0;n-1;i--)if(r(t[i]))return i;for(var n=e+1;n-1,p=e.getBwEstimate(),E=i.levels,T=E[t.level],L=o.total||Math.max(o.loaded,Math.round(l*T.averageBitrate/8)),A=m?u-v:u;A<1&&m&&(A=Math.min(u,8*o.loaded/p));var R=m?1e3*o.loaded/A:0,b=R?(L-o.loaded)/R:8*L/p+c/1e3;if(!(b<=g)){var k,D=R?8*R:p,I=Number.POSITIVE_INFINITY;for(k=t.level-1;k>h;k--){var C=E[k].maxBitrate;if((I=e.getTimeToLoadFrag(c/1e3,D,l*C,!E[k].details))=b||I>10*l)){i.nextLoadLevel=i.nextAutoLevel=k,m?e.bwEstimator.sample(u-Math.min(c,v),o.loaded):e.bwEstimator.sampleTTFB(u);var _=E[k].maxBitrate;e.getBwEstimate()*e.hls.config.abrBandWidthUpFactor>_&&e.resetEstimator(_),e.clearTimer(),w.warn("[abr] Fragment "+t.sn+(r?" part "+r.index:"")+" of level "+t.level+" is loading too slowly;\n Time to underbuffer: "+g.toFixed(3)+" s\n Estimated load time for current fragment: "+b.toFixed(3)+" s\n Estimated load time for down switch fragment: "+I.toFixed(3)+" s\n TTFB estimate: "+(0|v)+" ms\n Current BW estimate: "+(y(p)?0|p:"Unknown")+" bps\n New BW estimate: "+(0|e.getBwEstimate())+" bps\n Switching to level "+k+" @ "+(0|_)+" bps"),i.trigger(S.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:r,stats:o})}}}}}}},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}var e=t.prototype;return e.resetEstimator=function(t){t&&(w.log("setting initial bwe to "+t),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},e.initEstimator=function(){var t=this.hls.config;return new Or(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)},e.registerListeners=function(){var t=this.hls;t.on(S.MANIFEST_LOADING,this.onManifestLoading,this),t.on(S.FRAG_LOADING,this.onFragLoading,this),t.on(S.FRAG_LOADED,this.onFragLoaded,this),t.on(S.FRAG_BUFFERED,this.onFragBuffered,this),t.on(S.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(S.LEVEL_LOADED,this.onLevelLoaded,this),t.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(S.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(S.ERROR,this.onError,this)},e.unregisterListeners=function(){var t=this.hls;t&&(t.off(S.MANIFEST_LOADING,this.onManifestLoading,this),t.off(S.FRAG_LOADING,this.onFragLoading,this),t.off(S.FRAG_LOADED,this.onFragLoaded,this),t.off(S.FRAG_BUFFERED,this.onFragBuffered,this),t.off(S.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(S.LEVEL_LOADED,this.onLevelLoaded,this),t.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(S.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(S.ERROR,this.onError,this))},e.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},e.onManifestLoading=function(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},e.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},e.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},e.onFragLoading=function(t,e){var r,i=e.frag;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(r=e.part)?r:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},e.onLevelSwitching=function(t,e){this.clearTimer()},e.onError=function(t,e){if(!e.fatal)switch(e.details){case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case A.FRAG_LOAD_TIMEOUT:var r=e.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}},e.getTimeToLoadFrag=function(t,e,r,i){return t+r/e+(i?this.lastLevelLoadSec:0)},e.onLevelLoaded=function(t,e){var r=this.hls.config,i=e.stats.loading,n=i.end-i.start;y(n)&&(this.lastLevelLoadSec=n/1e3),e.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part,n=i?i.stats:r.stats;if(r.type===Fe&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var a=i?i.duration:r.duration,s=this.hls.levels[r.level],o=(s.loaded?s.loaded.bytes:0)+n.loaded,l=(s.loaded?s.loaded.duration:0)+a;s.loaded={bytes:o,duration:l},s.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){var u={stats:n,frag:r,part:i,id:r.type};this.onFragBuffered(S.FRAG_BUFFERED,u),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}},e.onFragBuffered=function(t,e){var r=e.frag,i=e.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}},e.ignoreFragment=function(t){return t.type!==Fe||"initSegment"===t.sn},e.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},e.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},e.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,a,i,l,0,u,h);if(d>=0)return d}var c=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-f,w.info("[abr] bitrate test took "+Math.round(1e3*f)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*c)+" ms"),u=h=1)}var g=this.findBestLevel(o,a,i,l,c,u,h);if(w.info("[abr] "+(l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g),g>-1)return g;var v=r.levels[a],m=r.levels[r.loadLevel];return(null==v?void 0:v.bitrate)<(null==m?void 0:m.bitrate)?a:r.loadLevel},e.getStarvationDelay=function(){var t=this.hls,e=t.media;if(!e)return 1/0;var r=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/r},e.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},e.findBestLevel=function(t,e,r,i,n,a,s){var o,l=this,u=i+n,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,c=this.fragCurrent,f=this.partCurrent,g=this.hls,v=g.levels,m=g.allAudioTracks,p=g.loadLevel,E=g.config;if(1===v.length)return 0;var T,S=v[d],L=!(null==S||null==(o=S.details)||!o.live),A=-1===p||-1===h,R="SDR",b=(null==S?void 0:S.frameRate)||0,k=E.audioPreference,D=E.videoPreference,I=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce((function(t,e){var r=t.groups[e.groupId];r||(r=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(e);var i=e.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||e.default,r.hasAutoSelect=r.hasAutoSelect||e.autoselect,r.hasDefault&&(t.hasDefaultAudio=!0),r.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(m));if(A){if(-1!==this.firstSelection)return this.firstSelection;var C=this.codecTiers||(this.codecTiers=function(t,e,r,i){return t.slice(r,i+1).reduce((function(t,r){if(!r.codecSet)return t;var i=r.audioGroups,n=t[r.codecSet];n||(t[r.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,r.bitrate);var a=Math.min(r.height,r.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,r.frameRate),n.maxScore=Math.max(n.maxScore,r.score),n.fragmentError+=r.fragmentError,n.videoRanges[r.videoRange]=(n.videoRanges[r.videoRange]||0)+1,i&&i.forEach((function(t){if(t){var r=e.groups[t];r&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(r.channels).forEach((function(t){n.channels[t]=(n.channels[t]||0)+r.channels[t]})))}})),t}),{})}(v,I,e,r)),_=function(t,e,r,i,n){for(var a=Object.keys(t),s=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=s&&2===parseInt(s),u=!0,h=!1,d=1/0,c=1/0,f=1/0,g=0,v=[],m=Gr(e,n),p=m.preferHDR,E=m.allowedVideoRanges,T=function(){var e=t[a[S]];u=e.channels[2]>0,d=Math.min(d,e.minHeight),c=Math.min(c,e.minFramerate),f=Math.min(f,e.minBitrate);var r=E.filter((function(t){return e.videoRanges[t]>0}));r.length>0&&(h=!0,v=r)},S=a.length;S--;)T();d=y(d)?d:0,c=y(c)?c:0;var L=Math.max(1080,d),A=Math.max(30,c);return f=y(f)?f:r,r=Math.max(f,r),h||(e=void 0,v=[]),{codecSet:a.reduce((function(e,i){var n=t[i];if(i===e)return e;if(n.minBitrate>r)return Kr(i,"min bitrate of "+n.minBitrate+" > current estimate of "+r),e;if(!n.hasDefaultAudio)return Kr(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Kr(i,'audio codec preference "'+o+'" not found'),e;if(s&&!l){if(!n.channels[s])return Kr(i,"no renditions with "+s+" channel sound found (channels options: "+Object.keys(n.channels)+")"),e}else if((!o||l)&&u&&0===n.channels[2])return Kr(i,"no renditions with stereo sound found"),e;return n.minHeight>L?(Kr(i,"min resolution of "+n.minHeight+" > maximum of "+L),e):n.minFramerate>A?(Kr(i,"min framerate of "+n.minFramerate+" > maximum of "+A),e):v.some((function(t){return n.videoRanges[t]>0}))?n.maxScore=ce(e)||n.fragmentError>t[e].fragmentError)?e:(g=n.maxScore,i):(Kr(i,"no variants with VIDEO-RANGE of "+JSON.stringify(v)+" found"),e)}),void 0),videoRanges:v,preferHDR:p,minFramerate:c,minBitrate:f}}(C,R,t,k,D),x=_.codecSet,P=_.videoRanges,F=_.minFramerate,M=_.minBitrate,O=_.preferHDR;T=x,R=O?P[P.length-1]:P[0],b=F,t=Math.max(t,M),w.log("[abr] picked start tier "+JSON.stringify(_))}else T=null==S?void 0:S.codecSet,R=null==S?void 0:S.videoRange;for(var N,U=f?f.duration:c?c.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,G=[],K=function(){var e,o=v[H],c=H>d;if(!o)return 0;if(E.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&function(t,e,r,i,n,a){var s=t.audioCodec?t.audioGroups:null,o=null==a?void 0:a.audioCodec,l=null==a?void 0:a.channels,u=l?parseInt(l):o?1/0:2,h=null;if(null!=s&&s.length)try{h=1===s.length&&s[0]?e.groups[s[0]].channels:s.reduce((function(t,r){if(r){var i=e.groups[r];if(!i)throw new Error("Audio track group "+r+" not found");Object.keys(i.channels).forEach((function(e){t[e]=(t[e]||0)+i.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==r||t.bitrate>Math.max(n,8e6))||!!h&&y(u)&&Object.keys(h).some((function(t){return parseInt(t)>u}))}(o,I,R,b,t,k)?(o.supportedPromise=Br(o,I,g),o.supportedPromise.then((function(t){if(l.hls){o.supportedResult=t;var e=l.hls.levels,r=e.indexOf(o);t.error?w.warn('[abr] MediaCapabilities decodingInfo error: "'+t.error+'" for level '+r+" "+JSON.stringify(t)):t.supported||(w.warn("[abr] Unsupported MediaCapabilities decodingInfo result for level "+r+" "+JSON.stringify(t)),r>-1&&e.length>1&&(w.log("[abr] Removing unsupported level "+r),l.hls.removeLevel(r)))}}))):o.supportedResult=Nr}if(T&&o.codecSet!==T||R&&o.videoRange!==R||c&&b>o.frameRate||!c&&b>0&&b=2*U&&0===n?v[H].averageBitrate:v[H].maxBitrate,x=l.getTimeToLoadFrag(B,m,_*C,void 0===D);if(m>=_&&(H===h||0===o.loadError&&0===o.fragmentError)&&(x<=B||!y(x)||L&&!l.bitrateTestDelay||x"+H+" adjustedbw("+Math.round(m)+")-bitrate="+Math.round(m-_)+" ttfb:"+B.toFixed(1)+" avgDuration:"+C.toFixed(1)+" maxFetchDuration:"+u.toFixed(1)+" fetchDuration:"+x.toFixed(1)+" firstSelection:"+A+" codecSet:"+T+" videoRange:"+R+" hls.loadLevel:"+p)),A&&(l.firstSelection=H),{v:H}}},H=r;H>=e;H--)if(0!==(N=K())&&N)return N.v;return-1},s(t,[{key:"firstAutoLevel",get:function(){var t=this.hls,e=t.maxAutoLevel,r=t.minAutoLevel,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(i,r,e,0,n,1,1);if(a>-1)return a;var s=this.hls.firstLevel,o=Math.min(Math.max(s,r),e);return w.warn("[abr] Could not find best starting auto level. Defaulting to first in playlist "+s+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;var i=e&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){var n=this.hls.levels;if(n.length>Math.max(t,i)&&n[t].loadError<=n[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(t){var e=this.hls,r=e.maxAutoLevel,i=e.minAutoLevel,n=Math.min(Math.max(t,i),r);this._nextAutoLevel!==n&&(this.nextAutoLevelKey="",this._nextAutoLevel=n)}}]),t}(),qr=function(){function t(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=t.prototype;return e.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function(){},e.hasInterval=function(){return!!this._tickInterval},e.hasNextTick=function(){return!!this._tickTimer},e.setInterval=function(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)},e.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}(),Xr="NOT_LOADED",zr="APPENDING",Qr="PARTIAL",Jr="OK",$r=function(){function t(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(S.BUFFER_APPENDED,this.onBufferAppended,this),t.on(S.FRAG_BUFFERED,this.onFragBuffered,this),t.on(S.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(S.BUFFER_APPENDED,this.onBufferAppended,this),t.off(S.FRAG_BUFFERED,this.onFragBuffered,this),t.off(S.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){var r=this.activePartLists[e];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;var a=n.end;if(n.start<=t&&null!==a&&t<=a)return n}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),n=i.length;n--;){var a=r[i[n]];if((null==a?void 0:a.body.type)===e&&a.buffered){var s=a.body;if(s.start<=t&&t<=s.end)return s}}return null},e.detectEvictedFragments=function(t,e,r,i){var n=this;this.timeRanges&&(this.timeRanges[t]=e);var a=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(i){var s=n.fragments[i];if(s&&!(a>=s.body.sn))if(s.buffered||s.loaded){var o=s.range[t];o&&o.time.some((function(t){var r=!n.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&n.removeFragment(s.body),r}))}else s.body.type===r&&n.removeFragment(s.body)}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,n=t.part;if(r&&"initSegment"!==i.sn){var a=ti(i),s=this.fragments[a];if(!(!s||s.buffered&&i.gap)){var o=!i.relurl;Object.keys(r).forEach((function(t){var a=i.elementaryStreams[t];if(a){var l=r[t],u=o||!0===a.partial;s.range[t]=e.getBufferedTimes(i,n,u,l)}})),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),Zr(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}}},e.removeParts=function(t,e){var r=this.activePartLists[e];r&&(this.activePartLists[e]=r.filter((function(e){return e.fragment.sn>=t})))},e.fragBuffered=function(t,e){var r=ti(t),i=this.fragments[r];!i&&e&&(i=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)},e.getBufferedTimes=function(t,e,r,i){for(var n={time:[],partial:r},a=t.start,s=t.end,o=t.minEndPTS||s,l=t.maxStartPTS||a,u=0;u=h&&o<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(ah){var c=Math.max(a,i.start(u)),f=Math.min(s,i.end(u));f>c&&(n.partial=!0,n.time.push({startPTS:c,endPTS:f}))}else if(s<=h)break}return n},e.getPartialFragment=function(t){var e,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&Zr(u)&&(r=u.body.start-s,i=u.body.end+s,t>=r&&t<=i&&(e=Math.min(t-r,i-t),a<=e&&(n=u.body,a=e)))})),n},e.isEndListAppended=function(t){var e=this.endListFragments[t];return void 0!==e&&(e.buffered||Zr(e))},e.getState=function(t){var e=ti(t),r=this.fragments[e];return r?r.buffered?Zr(r)?Qr:Jr:zr:Xr},e.isTimeBuffered=function(t,e,r){for(var i,n,a=0;a=i&&e<=n)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest){var n=i?null:e,a=ti(r);this.fragments[a]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,n=e.part,a=e.timeRanges;if("initSegment"!==i.sn){var s=i.type;if(n){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(n)}this.timeRanges=a,Object.keys(a).forEach((function(t){var e=a[t];r.detectEvictedFragments(t,e,s,n)}))}},e.onFragBuffered=function(t,e){this.detectPartialFragments(e)},e.hasFragment=function(t){var e=ti(t);return!!this.fragments[e]},e.hasParts=function(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)},e.removeFragmentsInRange=function(t,e,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.startt&&(o.buffered||n)&&a.removeFragment(l)}}))},e.removeFragment=function(t){var e=ti(t);t.stats.loaded=0,t.clearElementaryStreamInfo();var r=this.activePartLists[t.type];if(r){var i=t.sn;this.activePartLists[t.type]=r.filter((function(t){return t.fragment.sn!==i}))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1},t}();function Zr(t){var e,r,i;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(r=t.range.audio)?void 0:r.partial)||(null==(i=t.range.audiovideo)?void 0:i.partial))}function ti(t){return t.type+"_"+t.level+"_"+t.sn}var ei={length:0,start:function(){return 0},end:function(){return 0}},ri=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),n=0;n=i.start(n)&&r<=i.end(n))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var n,a=t.getBuffered(e),s=[];for(n=0;ns&&(i[a-1].end=t[n].end):i.push(t[n])}else i.push(t[n])}else i=t;for(var o,l=0,u=e,h=e,d=0;d=c&&er.startCC||t&&t.cc>>8^255&m^99,t[f]=m,e[m]=f;var p=c[f],y=c[p],E=c[y],T=257*c[m]^16843008*m;i[f]=T<<24|T>>>8,n[f]=T<<16|T>>>16,a[f]=T<<8|T>>>24,s[f]=T,T=16843009*E^65537*y^257*p^16843008*f,l[m]=T<<24|T>>>8,u[m]=T<<16|T>>>16,h[m]=T<<8|T>>>24,d[m]=T,f?(f=p^c[c[c[E^p]]],g^=c[c[g]]):f=g=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;is.end){var h=a>u;(a0&&null!=a&&a.key&&a.iv&&"AES-128"===a.method){var s=self.performance.now();return r.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).catch((function(e){throw i.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((function(n){var a=self.performance.now();return i.trigger(S.FRAG_DECRYPTED,{frag:t,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,r.completeInitSegmentLoad(e)}))}return r.completeInitSegmentLoad(e)})).catch((function(e){r.state!==Ei&&r.state!==Ii&&(r.warn(e),r.resetFragmentLoading(t))}))},r.completeInitSegmentLoad=function(t){if(!this.levels)throw new Error("init load aborted, missing levels");var e=t.frag.stats;this.state=Ti,t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now(),this.tick()},r.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.sn!==e.sn||t.level!==e.level},r.fragBufferedComplete=function(t,e){var r,i,n,a,s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+(this.playlistType===Fe?"level":"track")+" "+t.level+" (frag:["+(null!=(r=t.startPTS)?r:NaN).toFixed(3)+"-"+(null!=(i=t.endPTS)?i:NaN).toFixed(3)+"] > buffer:"+(s?yi(ri.getBuffered(s)):"(detached)")+")"),"initSegment"!==t.sn){var o;if(t.type!==Oe){var l=t.elementaryStreams;if(!Object.keys(l).some((function(t){return!!l[t]})))return void(this.state=Ti)}var u=null==(o=this.levels)?void 0:o[t.level];null!=u&&u.fragmentError&&(this.log("Resetting level fragment error count of "+u.fragmentError+" on frag buffered"),u.fragmentError=0)}this.state=Ti,s&&(!this.loadedmetadata&&t.type==Fe&&s.buffered.length&&(null==(n=this.fragCurrent)?void 0:n.sn)===(null==(a=this.fragPrevious)?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())},r.seekToStartPos=function(){},r._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,n=t.partsLoaded,a=!n||0===n.length||n.some((function(t){return!t})),s=new ii(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);e.flush(s)}},r._handleFragmentLoadProgress=function(t){},r._doFragLoad=function(t,e,r,i){var n,a=this;void 0===r&&(r=null);var s=null==e?void 0:e.details;if(!this.levels||!s)throw new Error("frag load aborted, missing level"+(s?"":" detail")+"s");var o=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key?!t.encrypted&&s.encryptedFragments.length&&this.keyLoader.loadClear(t,s.encryptedFragments):(this.log("Loading key for "+t.sn+" of ["+s.startSN+"-"+s.endSN+"], "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level),this.state=Si,this.fragCurrent=t,o=this.keyLoader.load(t).then((function(t){if(!a.fragContextChanged(t.frag))return a.hls.trigger(S.KEY_LOADED,t),a.state===Si&&(a.state=Ti),t})),this.hls.trigger(S.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),r=Math.max(t.start,r||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){var l=s.partList;if(l&&i){r>t.end&&s.fragmentHint&&(t=s.fragmentHint);var u=this.getNextPart(l,t,r);if(u>-1){var h,d=l[u];return this.log("Loading part sn: "+t.sn+" p: "+d.index+" cc: "+t.cc+" of playlist ["+s.startSN+"-"+s.endSN+"] parts [0-"+u+"-"+(l.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=d.start+d.duration,this.state=Li,h=o?o.then((function(r){return!r||a.fragContextChanged(r.frag)?null:a.doFragPartsLoad(t,d,e,i)})).catch((function(t){return a.handleFragLoadError(t)})):this.doFragPartsLoad(t,d,e,i).catch((function(t){return a.handleFragLoadError(t)})),this.hls.trigger(S.FRAG_LOADING,{frag:t,part:d,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(l,r))return Promise.resolve(null)}}this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(s?"of ["+s.startSN+"-"+s.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),y(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Li;var c,f=this.config.progressive;return c=f&&o?o.then((function(e){return!e||a.fragContextChanged(null==e?void 0:e.frag)?null:a.fragmentLoader.load(t,i)})).catch((function(t){return a.handleFragLoadError(t)})):Promise.all([this.fragmentLoader.load(t,f?i:void 0),o]).then((function(t){var e=t[0];return!f&&e&&i&&i(e),e})).catch((function(t){return a.handleFragLoadError(t)})),this.hls.trigger(S.FRAG_LOADING,{frag:t,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c},r.doFragPartsLoad=function(t,e,r,i){var n=this;return new Promise((function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList;!function e(o){n.fragmentLoader.loadPart(t,o,i).then((function(i){l[o.index]=i;var s=i.part;n.hls.trigger(S.FRAG_LOADED,i);var h=gr(r,t.sn,o.index+1)||vr(u,t.sn,o.index+1);if(!h)return a({frag:t,part:s,partsLoaded:l});e(h)})).catch(s)}(e)}))},r.handleFragLoadError=function(t){if("data"in t){var e=t.data;t.data&&e.details===A.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(S.ERROR,e)}else this.hls.trigger(S.ERROR,{type:L.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null},r._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===bi){var r=e.frag,i=e.part,n=e.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(r,i,n,t.partial)}else this.fragCurrent||this.state===Ei||this.state===Ii||(this.state=Ti)},r.getCurrentContext=function(t){var e=this.levels,r=this.fragCurrent,i=t.level,n=t.sn,a=t.part;if(null==e||!e[i])return this.warn("Levels object was unset while buffering fragment "+n+" of level "+i+". The current chunk will not be buffered."),null;var s=e[i],o=a>-1?gr(s,n,a):null,l=o?o.fragment:function(t,e,r){if(null==t||!t.details)return null;var i=t.details,n=i.fragments[e-i.startSN];return n||((n=i.fragmentHint)&&n.sn===e?n:ea&&this.flushMainBuffer(s,t.start)}else this.flushMainBuffer(0,t.start)},r.getFwdBufferInfo=function(t,e){var r=this.getLoadPosition();return y(r)?this.getFwdBufferInfoAtPos(t,r,e):null},r.getFwdBufferInfoAtPos=function(t,e,r){var i=this.config.maxBufferHole,n=ri.bufferInfo(t,e,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(e,r);if(a&&n.nextStart=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to "+n+"s"),!0)},r.getAppendedFrag=function(t,e){var r=this.fragmentTracker.getAppendedFrag(t,Fe);return r&&"fragment"in r?r.fragment:r},r.getNextFragment=function(t,e){var r=e.fragments,i=r.length;if(!i)return null;var n,a=this.config,s=r[0].start;if(e.live){var o=a.initialLiveManifestSize;if(ie},r.getNextFragmentLoopLoading=function(t,e,r,i,n){var a=t.gap,s=this.getNextFragment(this.nextLoadPosition,e);if(null===s)return s;if(t=s,a&&t&&!t.gap&&r.nextStart){var o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i);if(null!==o&&r.len+o.len>=n)return this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+t.sn),null}return t},r.mapToInitFragWhenRequired=function(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment},r.getNextPart=function(t,e,r){for(var i=-1,n=!1,a=!0,s=0,o=t.length;s-1&&rr.start&&r.loaded},r.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!y(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=t.startSN&&n<=t.endSN){var a=e[n-t.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(t,e){return Lr(t,(function(t){return t.cce?-1:0}))}(e,r.cc),i&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},r.getFragmentAtPosition=function(t,e,r){var i,n=this.config,a=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=n.maxFragLookUpTolerance,h=r.partList,d=!!(n.lowLatencyMode&&null!=h&&h.length&&l);if(d&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),i=te-u?0:u):s[s.length-1]){var c=i.sn-r.startSN,f=this.fragmentTracker.getState(i);if((f===Jr||f===Qr&&i.gap)&&(a=i),a&&i.sn===a.sn&&(!d||h[0].fragment.sn>i.sn)&&a&&i.level===a.level){var g=s[c+1];i=i.sn=a-e.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n"+t.startSN+" prev-sn: "+(o?o.sn:"na")+" fragments: "+i),l}return n},r.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},r.setStartPosition=function(t,e){var r=this.startPosition;if(r "+(null==(n=this.fragCurrent)?void 0:n.url))}else{var a=e.details===A.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(i,!0);var s=e.errorAction,o=s||{},l=o.action,u=o.retryCount,h=void 0===u?0:u,d=o.retryConfig;if(s&&l===wr&&d){this.resetStartWhenNotLoaded(this.levelLastLoaded);var c=Er(d,h);this.warn("Fragment "+i.sn+" of "+t+" "+i.level+" errored with "+e.details+", retrying loading "+(h+1)+"/"+d.maxNumRetry+" in "+c+"ms"),s.resolved=!0,this.retryDate=self.performance.now()+c,this.state=Ai}else if(d&&s){if(this.resetFragmentErrors(t),!(h.5;n&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);var a=!n;return a&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+r+" buffer"),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),a}return!1},r.resetFragmentErrors=function(t){t===Me&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Ei&&(this.state=Ti)},r.afterBufferFlushed=function(t,e,r){if(t){var i=ri.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,r),this.state===Di&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Ti},r.resetStartWhenNotLoaded=function(t){if(!this.loadedmetadata){this.startFragRequested=!1;var e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},r.resetWhenMissingContext=function(t){this.warn("The loading context changed while buffering fragment "+t.sn+" of level "+t.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},r.removeUnbufferedFrags=function(t){void 0===t&&(t=0),this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(t,e,r,i){var n,a=this,s=r.details;if(s){if(!Object.keys(t.elementaryStreams).reduce((function(e,n){var o=t.elementaryStreams[n];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return a.warn("Could not parse fragment "+t.sn+" "+n+" duration reliably ("+l+")"),e||!1;var u=i?0:hr(s,t,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return a.hls.trigger(S.LEVEL_PTS_UPDATED,{details:s,level:r,drift:u,type:n,frag:t,start:o.startPTS,end:o.endPTS}),!0}return e}),!1)&&null===(null==(n=this.transmuxer)?void 0:n.error)){var o=new Error("Found no media in fragment "+t.sn+" of level "+t.level+" resetting transmuxer to fallback to playlist timing");if(0===r.fragmentError&&(r.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(o.message),this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:t,reason:"Found no media in msn "+t.sn+' of level "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=ki,this.hls.trigger(S.FRAG_PARSED,{frag:t,part:e})}else this.warn("level.details undefined")},r.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},r.recoverWorkerError=function(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},s(e,[{key:"state",get:function(){return this._state},set:function(t){var e=this._state;e!==t&&(this._state=t,this.log(e+"->"+t))}}]),e}(qr),xi=function(){function t(){this.chunks=[],this.dataLength=0}var e=t.prototype;return e.push=function(t){this.chunks.push(t),this.dataLength+=t.length},e.flush=function(){var t,e=this.chunks,r=this.dataLength;return e.length?(t=1===e.length?e[0]:function(t,e){for(var r=new Uint8Array(e),i=0,n=0;n0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:We,duration:Number.POSITIVE_INFINITY});n>>5}function Bi(t,e){return e+1=t.length)return!1;var i=Ui(t,e);if(i<=r)return!1;var n=e+i;return n===t.length||Bi(t,n)}return!1}function Ki(t,e,r,i,n){if(!t.samplerate){var a=function(t,e,r,i){var n,a,s,o,l=navigator.userAgent.toLowerCase(),u=i,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=1+((192&e[r+2])>>>6);var d=(60&e[r+2])>>>2;if(!(d>h.length-1))return s=(1&e[r+2])<<2,s|=(192&e[r+3])>>>6,w.log("manifest codec:"+i+", ADTS type:"+n+", samplingIndex:"+d),/firefox/i.test(l)?d>=6?(n=5,o=new Array(4),a=d-3):(n=2,o=new Array(2),a=d):-1!==l.indexOf("android")?(n=2,o=new Array(2),a=d):(n=5,o=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&d>=6?a=d-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(d>=6&&1===s||/vivaldi/i.test(l))||!i&&1===s)&&(n=2,o=new Array(2)),a=d)),o[0]=n<<3,o[0]|=(14&d)>>1,o[1]|=(1&d)<<7,o[1]|=s<<3,5===n&&(o[1]|=(14&a)>>1,o[2]=(1&a)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[d],channelCount:s,codec:"mp4a.40."+n,manifestCodec:u};var c=new Error("invalid ADTS sampling index:"+d);t.emit(S.ERROR,S.ERROR,{type:L.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}(e,r,i,n);if(!a)return;t.config=a.config,t.samplerate=a.samplerate,t.channelCount=a.channelCount,t.codec=a.codec,t.manifestCodec=a.manifestCodec,w.log("parsed codec:"+t.codec+", rate:"+a.samplerate+", channels:"+a.channelCount)}}function Hi(t){return 9216e4/t}function Vi(t,e,r,i,n){var a,s=i+n*Hi(t.samplerate),o=function(t,e){var r=Ni(t,e);if(e+r<=t.length){var i=Ui(t,e)-r;if(i>0)return{headerLength:r,frameLength:i}}}(e,r);if(o){var l=o.frameLength,u=o.headerLength,h=u+l,d=Math.max(0,r+h-e.length);d?(a=new Uint8Array(h-u)).set(e.subarray(r+u,e.length),0):a=e.subarray(r+u,r+h);var c={unit:a,pts:s};return d||t.samples.push(c),{sample:c,length:h,missing:d}}var f=e.length-r;return(a=new Uint8Array(f)).set(e.subarray(r,e.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}var Yi=null,Wi=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],ji=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],qi=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Xi=[0,1,1,4];function zi(t,e,r,i,n){if(!(r+24>e.length)){var a=Qi(e,r);if(a&&r+a.frameLength<=e.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:e.subarray(r,r+a.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=a.channelCount,t.samplerate=a.sampleRate,t.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function Qi(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,n=t[e+2]>>4&15,a=t[e+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Wi[14*(3===r?3-i:3===i?3:4)+n-1],u=ji[3*(3===r?0:2===r?1:2)+a],h=3===o?1:2,d=qi[r][i],c=Xi[i],f=8*d*c,g=Math.floor(d*l/u+s)*c;if(null===Yi){var v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Yi=v?parseInt(v[1]):0}return!!Yi&&Yi<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Ji(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function $i(t,e){return e+18&&109===t[r+4]&&111===t[r+5]&&111===t[r+6]&&102===t[r+7])return!0;r=i>1?r+i:e}return!1}(t)},e.demux=function(t,e){this.timeOffset=e;var r=t,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Wt(this.remainderData,t));var a=function(t){var e={valid:null,remainder:null},r=Ot(t,["moof"]);if(r.length<2)return e.remainder=t,e;var i=r[r.length-1];return e.valid=lt(t,0,i.byteOffset-8),e.remainder=lt(t,i.byteOffset-8),e}(r);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=r;var s=this.extractID3Track(i,e);return n.samples=jt(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}},e.flush=function(){var t=this.timeOffset,e=this.videoTrack,r=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(e,this.timeOffset);return r.samples=jt(t,e),{videoTrack:e,audioTrack:Pi(),id3Track:i,textTrack:Pi()}},e.extractID3Track=function(t,e){var r=this.id3Track;if(t.samples.length){var i=Ot(t.samples,["emsg"]);i&&i.forEach((function(t){var i=function(t){var e=t[0],r="",i="",n=0,a=0,s=0,o=0,l=0,u=0;if(0===e){for(;"\0"!==Ct(t.subarray(u,u+1));)r+=Ct(t.subarray(u,u+1)),u+=1;for(r+=Ct(t.subarray(u,u+1)),u+=1;"\0"!==Ct(t.subarray(u,u+1));)i+=Ct(t.subarray(u,u+1)),u+=1;i+=Ct(t.subarray(u,u+1)),u+=1,n=xt(t,12),a=xt(t,16),o=xt(t,20),l=xt(t,24),u=28}else if(1===e){n=xt(t,u+=4);var h=xt(t,u+=4),d=xt(t,u+=4);for(u+=4,s=Math.pow(2,32)*h+d,E(s)||(s=Number.MAX_SAFE_INTEGER,w.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=xt(t,u),l=xt(t,u+=4),u+=4;"\0"!==Ct(t.subarray(u,u+1));)r+=Ct(t.subarray(u,u+1)),u+=1;for(r+=Ct(t.subarray(u,u+1)),u+=1;"\0"!==Ct(t.subarray(u,u+1));)i+=Ct(t.subarray(u,u+1)),u+=1;i+=Ct(t.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:t.subarray(u,t.byteLength)}}(t);if(en.test(i.schemeIdUri)){var n=y(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale,a=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var s=i.payload;r.samples.push({data:s,len:s.byteLength,dts:n,pts:n,type:qe,duration:a})}}))}return r},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}(),nn=function(t,e){var r=0,i=5;e+=i;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);i>0;){s[0]=t[e];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<>l,r=r?r<e.length)return-1;if(11!==e[r]||119!==e[r+1])return-1;var a=e[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&e[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>e.length)return-1;var u=e[r+6]>>5,h=0;2===u?h+=2:(1&u&&1!==u&&(h+=2),4&u&&(h+=2));var d=(e[r+6]<<8|e[r+7])>>12-h&1,c=[2,1,2,3,3,4,4,5][u]+d,f=e[r+5]>>3,g=7&e[r+5],v=new Uint8Array([a<<6|f<<1|g>>2,(3&g)<<6|u<<3|d<<2|o>>4,o<<4&224]),m=i+n*(1536/s*9e4),p=e.subarray(r,r+l);return t.config=v,t.channelCount=c,t.samplerate=s,t.samples.push({unit:p,pts:m}),l}var on=function(){function t(){this.VideoSample=null}var e=t.prototype;return e.createVideoSample=function(t,e,r,i){return{key:t,frame:!1,pts:e,dts:r,units:[],debug:i,length:0}},e.getLastNalUnit=function(t){var e,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){var n=i.units;r=n[n.length-1]}return r},e.pushAccessUnit=function(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var n=r[i-1];t.pts=n.pts,t.dts=n.dts}e.samples.push(t)}t.debug.length&&w.log(t.pts+"/"+t.dts+":"+t.debug)},t}(),ln=function(){function t(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}var e=t.prototype;return e.loadWord=function(){var t=this.data,e=this.bytesAvailable,r=t.byteLength-e,i=new Uint8Array(4),n=Math.min(4,e);if(0===n)throw new Error("no bytes available");i.set(t.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},e.skipBits=function(t){var e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;if(t>32&&w.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(e=t-e)>0&&this.bitsAvailable?r<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i4){var f=new ln(c).readSliceType();2!==f&&4!==f&&7!==f&&9!==f||(h=!0)}h&&null!=(d=l)&&d.frame&&!l.key&&(s.pushAccessUnit(l,t),l=s.VideoSample=null),l||(l=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts,"")),l.frame=!0,l.key=h;break;case 5:a=!0,null!=(o=l)&&o.frame&&!l.key&&(s.pushAccessUnit(l,t),l=s.VideoSample=null),l||(l=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts,"")),l.key=!0,l.frame=!0;break;case 6:a=!0,Xt(i.data,1,r.pts,e.samples);break;case 7:var g,v;a=!0,u=!0;var m=i.data,p=new ln(m).readSPS();if(!t.sps||t.width!==p.width||t.height!==p.height||(null==(g=t.pixelRatio)?void 0:g[0])!==p.pixelRatio[0]||(null==(v=t.pixelRatio)?void 0:v[1])!==p.pixelRatio[1]){t.width=p.width,t.height=p.height,t.pixelRatio=p.pixelRatio,t.sps=[m],t.duration=n;for(var y=m.subarray(1,4),E="avc1.",T=0;T<3;T++){var S=y[T].toString(16);S.length<2&&(S="0"+S),E+=S}t.codec=E}break;case 8:a=!0,t.pps=[i.data];break;case 9:a=!0,t.audFound=!0,l&&s.pushAccessUnit(l,t),l=s.VideoSample=s.createVideoSample(!1,r.pts,r.dts,"");break;case 12:a=!0;break;default:a=!1,l&&(l.debug+="unknown NAL "+i.type+" ")}l&&a&&l.units.push(i)})),i&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)},r.parseAVCNALu=function(t,e){var r,i,n=e.byteLength,a=t.naluState||0,s=a,o=[],l=0,u=-1,h=0;for(-1===a&&(u=0,h=31&e[0],a=0,l=1);l=0){var d={data:e.subarray(u,i),type:h};o.push(d)}else{var c=this.getLastNalUnit(t.samples);c&&(s&&l<=4-s&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-s)),i>0&&(c.data=Wt(c.data,e.subarray(0,i)),c.state=0))}l=0&&a>=0){var f={data:e.subarray(u,n),type:h,state:a};o.push(f)}if(0===o.length){var g=this.getLastNalUnit(t.samples);g&&(g.data=Wt(g.data,e))}return t.naluState=a,o},e}(on),hn=function(){function t(t,e,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new pi(e,{removePKCS7Padding:!1})}var e=t.prototype;return e.decryptBuffer=function(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)},e.decryptAacSample=function(t,e,r){var i=this,n=t[e].unit;if(!(n.length<=16)){var a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then((function(a){var s=new Uint8Array(a);n.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(t,e+1,r)}))}},e.decryptAacSamples=function(t,e,r){for(;;e++){if(e>=t.length)return void r();if(!(t[e].unit.length<32||(this.decryptAacSample(t,e,r),this.decrypter.isSync())))return}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,n=32;n=t.length)return void i();for(var n=t[e].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(t,e,r,i,a),this.decrypter.isSync())))return}}},t}(),dn=188,cn=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=r,this.videoParser=new un}t.probe=function(e){var r=t.syncOffset(e);return r>0&&w.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},t.syncOffset=function(t){for(var e=t.length,r=Math.min(940,e-dn)+1,i=0;i1&&(0===a&&s>2||o+dn>r))return a}i++}return-1},t.createTrack=function(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:wt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}};var e=t.prototype;return e.resetInitSegment=function(e,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=t.createTrack("video"),this._audioTrack=t.createTrack("audio",n),this._id3Track=t.createTrack("id3"),this._txtTrack=t.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,this._duration=n},e.resetTimeStamp=function(){},e.resetContiguity=function(){var t=this._audioTrack,e=this._videoTrack,r=this._id3Track;t&&(t.pesData=null),e&&(e.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},e.demux=function(e,r,i,n){var a;void 0===i&&(i=!1),void 0===n&&(n=!1),i||(this.sampleAes=null);var s=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack,h=s.pid,d=s.pesData,c=o.pid,f=l.pid,g=o.pesData,v=l.pesData,m=null,p=this.pmtParsed,y=this._pmtId,E=e.length;if(this.remainderData&&(E=(e=Wt(this.remainderData,e)).length,this.remainderData=null),E>4>1){if((b=L+5+e[L+4])===L+dn)continue}else b=L+4;switch(R){case h:A&&(d&&(a=yn(d))&&this.videoParser.parseAVCPES(s,u,a,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(e.subarray(b,L+dn)),d.size+=L+dn-b);break;case c:if(A){if(g&&(a=yn(g)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,a);break;case"mp3":this.parseMPEGPES(o,a);break;case"ac3":this.parseAC3PES(o,a)}g={data:[],size:0}}g&&(g.data.push(e.subarray(b,L+dn)),g.size+=L+dn-b);break;case f:A&&(v&&(a=yn(v))&&this.parseID3PES(l,a),v={data:[],size:0}),v&&(v.data.push(e.subarray(b,L+dn)),v.size+=L+dn-b);break;case 0:A&&(b+=e[b]+1),y=this._pmtId=gn(e,b);break;case y:A&&(b+=e[b]+1);var k=vn(e,b,this.typeSupported,i,this.observer);(h=k.videoPid)>0&&(s.pid=h,s.segmentCodec=k.segmentVideoCodec),(c=k.audioPid)>0&&(o.pid=c,o.segmentCodec=k.segmentAudioCodec),(f=k.id3Pid)>0&&(l.pid=f),null===m||p||(w.warn("MPEG-TS PMT found at "+L+" after unknown PID '"+m+"'. Backtracking to sync byte @"+T+" to parse all TS packets."),m=null,L=T-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=R}}else S++;S>0&&mn(this.observer,new Error("Found "+S+" TS packet/s that do not start with 0x47")),s.pesData=d,o.pesData=g,l.pesData=v;var D={audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};return n&&this.extractRemainingSamples(D),D},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.videoTrack,n=t.id3Track,a=t.textTrack,s=i.pesData,o=r.pesData,l=n.pesData;if(s&&(e=yn(s))?(this.videoParser.parseAVCPES(i,a,e,!0,this._duration),i.pesData=null):i.pesData=s,o&&(e=yn(o))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,e);break;case"mp3":this.parseMPEGPES(r,e);break;case"ac3":this.parseAC3PES(r,e)}r.pesData=null}else null!=o&&o.size&&w.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(e=yn(l))?(this.parseID3PES(n,e),n.pesData=null):n.pesData=l},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),n=this.sampleAes=new hn(this.observer,this.config,e);return this.decrypt(i,n)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,n=t.videoTrack;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(function(){n.samples?e.decryptAvcSamples(n.samples,0,0,(function(){r(t)})):r(t)})):n.samples&&e.decryptAvcSamples(n.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._duration=0},e.parseAACPES=function(t,e){var r,i,n,a=0,s=this.aacOverFlow,o=e.data;if(s){this.aacOverFlow=null;var l=s.missing,u=s.sample.unit.byteLength;if(-1===l)o=Wt(s.sample.unit,o);else{var h=u-l;s.sample.unit.set(o.subarray(0,l),h),t.samples.push(s.sample),a=s.missing}}for(r=a,i=o.length;r0;)o+=n;else w.warn("[tsdemuxer]: AC3 PES unknown PTS")},e.parseID3PES=function(t,e){if(void 0!==e.pts){var r=o({},e,{type:this._videoTrack?qe:We,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}else w.warn("[tsdemuxer]: ID3 PES unknown PTS")},t}();function fn(t,e){return((31&t[e+1])<<8)+t[e+2]}function gn(t,e){return(31&t[e+10])<<8|t[e+11]}function vn(t,e,r,i,n){var a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},s=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e0)for(var u=e+5,h=l;h>2;){106===t[u]&&(!0!==r.ac3?w.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3"));var d=t[u+1]+2;u+=d,h-=d}break;case 194:case 135:return mn(n,new Error("Unsupported EC-3 in M2TS found")),a;case 36:return mn(n,new Error("Unsupported HEVC in M2TS found")),a}e+=l+5}return a}function mn(t,e,r){w.warn("parsing error: "+e.message),t.emit(S.ERROR,S.ERROR,{type:L.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:e,reason:e.message})}function pn(t){w.log(t+" with AES-128-CBC encryption found in unencrypted stream")}function yn(t){var e,r,i,n,a,s=0,o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Wt(o[0],o[1]),o.splice(1,1);if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var l=e[7];192&l&&(n=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?n-(a=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(w.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var u=(i=e[8])+9;if(t.size<=u)return null;t.size-=u;for(var h=new Uint8Array(t.size),d=0,c=o.length;df){u-=f;continue}e=e.subarray(u),f-=u,u=0}h.set(e,s),s+=f}return r&&(r-=i+3),{data:h,pts:n,dts:a,len:r}}return null}var En=function(t){function e(){return t.apply(this,arguments)||this}l(e,t);var r=e.prototype;return r.resetInitSegment=function(e,r,i,n){t.prototype.resetInitSegment.call(this,e,r,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},e.probe=function(t){if(!t)return!1;var e=ct(t,0),r=(null==e?void 0:e.length)||0;if(e&&11===t[r]&&119===t[r+1]&&void 0!==vt(e)&&nn(t,r)<=16)return!1;for(var i=t.length;r1?r-1:0),n=1;n>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),a=0,e=8;a>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(Sn+1)),n=Math.floor(r%(Sn+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,a)},t.sdtp=function(e){var r,i,n=e.samples||[],a=new Uint8Array(4+n.length);for(r=0;r>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|e.sps.length].concat(a).concat([e.pps.length]).concat(s))),l=e.width,u=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.audioStsd=function(t){var e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])},t.mp4a=function(e){return t.box(t.types.mp4a,t.audioStsd(e),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){return t.box(t.types[".mp3"],t.audioStsd(e))},t.ac3=function(e){return t.box(t.types["ac-3"],t.audioStsd(e),t.box(t.types.dac3,e.config))},t.stsd=function(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?t.box(t.types.stsd,t.STSD,t.mp3(e)):"ac3"===e.segmentCodec?t.box(t.types.stsd,t.STSD,t.ac3(e)):t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,n=e.width,a=e.height,s=Math.floor(i/(Sn+1)),o=Math.floor(i%(Sn+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),n=e.id,a=Math.floor(r/(Sn+1)),s=Math.floor(r%(Sn+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,n,a,s,o,l,u=e.samples||[],h=u.length,d=12+16*h,c=new Uint8Array(d);for(r+=8+d,c.set(["video"===e.type?1:0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,c)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e);return Wt(t.FTYP,r)},t}();Ln.types=void 0,Ln.HDLR_TYPES=void 0,Ln.STTS=void 0,Ln.STSC=void 0,Ln.STCO=void 0,Ln.STSZ=void 0,Ln.VMHD=void 0,Ln.SMHD=void 0,Ln.STSD=void 0,Ln.FTYP=void 0,Ln.DINF=void 0;var An=9e4;function Rn(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=t*e*r;return i?Math.round(n):n}function bn(t,e){return void 0===e&&(e=!1),Rn(t,1e3,1/An,e)}var kn=null,Dn=null,In=function(){function t(t,e,r,i){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=r,this.ISGenerated=!1,null===kn){var n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);kn=n?parseInt(n[1]):0}if(null===Dn){var a=navigator.userAgent.match(/Safari\/(\d+)/i);Dn=a?parseInt(a[1]):0}}var e=t.prototype;return e.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},e.resetTimeStamp=function(t){w.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t},e.resetNextTimestamp=function(){w.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},e.resetInitSegment=function(){w.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},e.getVideoStartPts=function(t){var e=!1,r=t.reduce((function(t,r){var i=r.pts-t;return i<-4294967296?(e=!0,wn(t,r.pts)):i>0?t:r.pts}),t[0].pts);return e&&w.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,n,a,s,o){var l,u,h,d,c,f,g=n,v=n,m=t.pid>-1,p=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=s&&y>0||y>1;if((!m||E)&&(!p||T)||this.ISGenerated||s){if(this.ISGenerated){var S,L,A,R,b=this.videoTrackConfig;!b||e.width===b.width&&e.height===b.height&&(null==(S=e.pixelRatio)?void 0:S[0])===(null==(L=b.pixelRatio)?void 0:L[0])&&(null==(A=e.pixelRatio)?void 0:A[1])===(null==(R=b.pixelRatio)?void 0:R[1])||this.resetInitSegment()}else h=this.generateIS(t,e,n,a);var k,D=this.isVideoContiguous,I=-1;if(T&&(I=function(t){for(var e=0;e0){w.warn("[mp4-remuxer]: Dropped "+I+" out of "+y+" video samples due to a missing keyframe");var C=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(I),e.dropped+=I,k=v+=(e.samples[0].pts-C)/e.inputTimeScale}else-1===I&&(w.warn("[mp4-remuxer]: No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&T){var _=this.getVideoStartPts(e.samples),x=(wn(t.samples[0].pts,_)-_)/e.inputTimeScale;g+=Math.max(0,x),v+=Math.max(0,-x)}if(E){if(t.samplerate||(w.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(t,e,n,a)),u=this.remuxAudio(t,g,this.isAudioContiguous,a,p||T||o===Me?v:void 0),T){var P=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(w.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(t,e,n,a)),l=this.remuxVideo(e,v,D,P)}}else T&&(l=this.remuxVideo(e,v,D,0));l&&(l.firstKeyFrame=I,l.independent=-1!==I,l.firstKeyFramePTS=k)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=Cn(r,n,this._initPTS,this._initDTS)),i.samples.length&&(d=_n(i,n,this._initPTS))),{audio:u,video:l,initSegment:h,independent:f,text:d,id3:c}},e.generateIS=function(t,e,r,i){var n,a,s,o=t.samples,l=e.samples,u=this.typeSupported,h={},d=this._initPTS,c=!d||i,f="audio/mp4";if(c&&(n=a=1/0),t.config&&o.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",t.codec=""):u.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}h.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&u.mpeg?new Uint8Array(0):Ln.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(s=t.inputTimeScale,d&&s===d.timescale?c=!1:n=a=o[0].pts-Math.round(s*r))}if(e.sps&&e.pps&&l.length){if(e.timescale=e.inputTimeScale,h.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Ln.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(s=e.inputTimeScale,d&&s===d.timescale)c=!1;else{var g=this.getVideoStartPts(l),v=Math.round(s*r);a=Math.min(a,wn(l[0].dts,g)-v),n=Math.min(n,g-v)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(h).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:n,timescale:s},this._initDTS={baseTime:a,timescale:s}):n=s=void 0,{tracks:h,initPTS:n,timescale:s}},e.remuxVideo=function(t,e,r,i){var n,a,s=t.inputTimeScale,l=t.samples,u=[],h=l.length,d=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!r||null===c){var y=e*s,E=l[0].pts-wn(l[0].dts,l[0].pts);kn&&null!==c&&Math.abs(y-E-c)<15e3?r=!0:c=y-E}for(var T=d.baseTime*s/d.timescale,R=0;R0?R-1:R].dts&&(p=!0)}p&&l.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),n=l[0].dts;var k=(a=l[l.length-1].dts)-n,D=k?Math.round(k/(h-1)):g||t.inputTimeScale/30;if(r){var I=n-c,C=I>D,_=I<-1;if((C||_)&&(C?w.warn("AVC: "+bn(I,!0)+" ms ("+I+"dts) hole between fragments detected at "+e.toFixed(3)):w.warn("AVC: "+bn(-I,!0)+" ms ("+I+"dts) overlapping between fragments detected at "+e.toFixed(3)),!_||c>=l[0].pts||kn)){n=c;var x=l[0].pts-I;if(C)l[0].dts=n,l[0].pts=x;else for(var P=0;Px);P++)l[P].dts-=I,l[P].pts-=I;w.log("Video: Initial PTS/DTS adjusted: "+bn(x,!0)+"/"+bn(n,!0)+", delta: "+bn(I,!0)+" ms")}}for(var F=0,M=0,O=n=Math.max(0,n),N=0;N0?$.dts-l[J-1].dts:D;if(st=J>0?$.pts-l[J-1].pts:D,ot.stretchShortVideoTrack&&null!==this.nextAudioPts){var ut=Math.floor(ot.maxBufferHole*s),ht=(i?v+i*s:this.nextAudioPts)-$.pts;ht>ut?((g=ht-lt)<0?g=lt:j=!0,w.log("[mp4-remuxer]: It is approximately "+ht/90+" ms to the next segment; using duration "+g/90+" ms for the last video frame.")):g=lt}else g=lt}var dt=Math.round($.pts-$.dts);q=Math.min(q,g),z=Math.max(z,g),X=Math.min(X,st),Q=Math.max(Q,st),u.push(new Pn($.key,g,tt,dt))}if(u.length)if(kn){if(kn<70){var ct=u[0].flags;ct.dependsOn=2,ct.isNonSync=0}}else if(Dn&&Q-X0&&(i&&Math.abs(p-m)<9e3||Math.abs(wn(g[0].pts-y,p)-m)<20*u),g.forEach((function(t){t.pts=wn(t.pts-y,p)})),!r||m<0){if(g=g.filter((function(t){return t.pts>=0})),!g.length)return;m=0===n?0:i&&!f?Math.max(0,p):g[0].pts}if("aac"===t.segmentCodec)for(var E=this.config.maxAudioFramesDrift,T=0,R=m;T=E*u&&I<1e4&&f){var C=Math.round(D/u);(R=k-C*u)<0&&(C--,R+=u),0===T&&(this.nextAudioPts=m=R),w.warn("[mp4-remuxer]: Injecting "+C+" audio frame @ "+(R/a).toFixed(3)+"s due to "+Math.round(1e3*D/a)+" ms gap.");for(var _=0;_0))return;N+=v;try{F=new Uint8Array(N)}catch(t){return void this.observer.emit(S.ERROR,S.ERROR,{type:L.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:N,reason:"fail allocating audio mdat "+N})}d||(new DataView(F.buffer).setUint32(0,N),F.set(Ln.types.mdat,4))}F.set(H,v);var Y=H.byteLength;v+=Y,c.push(new Pn(!0,l,Y,0)),O=V}var W=c.length;if(W){var j=c[c.length-1];this.nextAudioPts=m=O+s*j.duration;var q=d?new Uint8Array(0):Ln.moof(t.sequenceNumber++,M/s,o({},t,{samples:c}));t.samples=[];var X=M/a,z=m/a,Q={data1:q,data2:F,startPTS:X,endPTS:z,startDTS:X,endDTS:z,type:"audio",hasAudio:!0,hasVideo:!1,nb:W};return this.isAudioContiguous=!0,Q}},e.remuxEmptyAudio=function(t,e,r,i){var n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),s=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,u=(null!==s?s:i.startDTS*n)+l,h=i.endDTS*n+l,d=1024*a,c=Math.ceil((h-u)/d),f=Tn.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(w.warn("[mp4-remuxer]: remux empty Audio"),f){for(var g=[],v=0;v4294967296;)t+=r;return t}function Cn(t,e,r,i){var n=t.samples.length;if(n){for(var a=t.inputTimeScale,s=0;s0;n||(i=Ot(e,["encv"])),i.forEach((function(t){Ot(n?t.subarray(28):t.subarray(78),["sinf"]).forEach((function(t){var e=Vt(t);if(e){var i=e.subarray(8,24);i.some((function(t){return 0!==t}))||(w.log("[eme] Patching keyId in 'enc"+(n?"a":"v")+">sinf>>tenc' box: "+kt.hexDump(i)+" -> "+kt.hexDump(r)),e.set(r,8))}}))}))})),t}(t,i)),this.emitInitSegment=!0},e.generateInitSegment=function(t){var e=this.audioCodec,r=this.videoCodec;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=Ut(t);i.audio&&(e=Mn(i.audio,O)),i.video&&(r=Mn(i.video,N));var n={};i.audio&&i.video?n.audiovideo={container:"video/mp4",codec:e+","+r,initSegment:t,id:"main"}:i.audio?n.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?n.video={container:"video/mp4",codec:r,initSegment:t,id:"main"}:w.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n},e.remux=function(t,e,r,i,n,a){var s,o,l=this.initPTS,u=this.lastEndTime,h={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};y(u)||(u=this.lastEndTime=n||0);var d=e.samples;if(null==d||!d.length)return h;var c={initPTS:void 0,timescale:1},f=this.initData;if(null!=(s=f)&&s.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return w.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=function(t,e){for(var r=0,i=0,n=0,a=Ot(t,["moof","traf"]),s=0;sn}(l,m,n,g)||c.timescale!==l.timescale&&a)&&(c.initPTS=m-n,l&&1===l.timescale&&w.warn("Adjusting initPTS by "+(c.initPTS-l.baseTime)),this.initPTS=l={baseTime:c.initPTS,timescale:1});var p=t?m-l.baseTime/l.timescale:u,E=p+g;!function(t,e,r){Ot(e,["moof","traf"]).forEach((function(e){Ot(e,["tfhd"]).forEach((function(i){var n=xt(i,4),a=t[n];if(a){var s=a.timescale||9e4;Ot(e,["tfdt"]).forEach((function(t){var e=t[0],i=r*s;if(i){var n=xt(t,4);if(0===e)n-=i,Mt(t,4,n=Math.max(n,0));else{n*=Math.pow(2,32),n+=xt(t,8),n-=i,n=Math.max(n,0);var a=Math.floor(n/(Dt+1)),o=Math.floor(n%(Dt+1));Mt(t,4,a),Mt(t,8,o)}}}))}}))}))}(f,d,l.baseTime/l.timescale),g>0?this.lastEndTime=E:(w.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var T=!!f.audio,S=!!f.video,L="";T&&(L+="audio"),S&&(L+="video");var A={data1:d,startPTS:p,startDTS:p,endPTS:E,endDTS:E,type:L,hasAudio:T,hasVideo:S,nb:1,dropped:0};return h.audio="audio"===A.type?A:void 0,h.video="audio"!==A.type?A:void 0,h.initSegment=c,h.id3=Cn(r,n,l,l),i.samples.length&&(h.text=_n(i,n,l)),h},t}();function Mn(t,e){var r=null==t?void 0:t.codec;if(r&&r.length>4)return r;if(e===O){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r)return ve(r,!1);var i="mp4a.40.5";return w.info('Parsed audio codec "'+r+'" or audio object type not handled. Using "'+i+'"'),i}return w.warn('Unhandled video codec "'+r+'"'),"hvc1"===r||"hev1"===r?"hvc1.1.6.L120.90":"av01"===r?"av01.0.04M.08":"avc1.42e01e"}try{xn=self.performance.now.bind(self.performance)}catch(t){w.debug("Unable to use Performance API on this environment"),xn=null==j?void 0:j.Date.now}var On=[{demux:rn,remux:Fn},{demux:cn,remux:In},{demux:tn,remux:In},{demux:En,remux:In}];On.splice(2,0,{demux:an,remux:In});var Nn=function(){function t(t,e,r,i,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i,this.id=n}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,i){var n=this,a=r.transmuxing;a.executeStart=xn();var s=new Uint8Array(t),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,h=u.contiguous,d=u.discontinuity,c=u.trackSwitch,f=u.accurateTimeOffset,g=u.timeOffset,v=u.initSegmentChange,m=l.audioCodec,p=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,R=function(t,e){var r=null;return t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(r=e),r}(s,e);if(R&&"AES-128"===R.method){var b=this.getDecrypter();if(!b.isSync())return this.decryptionPromise=b.webCryptoDecrypt(s,R.key.buffer,R.iv.buffer).then((function(t){var e=n.push(t,null,r);return n.decryptionPromise=null,e})),this.decryptionPromise;var k=b.softwareDecrypt(s,R.key.buffer,R.iv.buffer);if(r.part>-1&&(k=b.flush()),!k)return a.executeEnd=xn(),Un(r);s=new Uint8Array(k)}var D=this.needsProbing(d,c);if(D){var I=this.configureTransmuxer(s);if(I)return w.warn("[transmuxer] "+I.message),this.observer.emit(S.ERROR,S.ERROR,{type:L.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),a.executeEnd=xn(),Un(r)}(d||c||v||D)&&this.resetInitSegment(T,m,p,E,e),(d||v||D)&&this.resetInitialTimestamp(y),h||this.resetContiguity();var C=this.transmux(s,R,g,f,r),_=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,a.executeEnd=xn(),C},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=xn();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return a.then((function(){return e.flush(t)}));var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l,null,t))}var u=this.demuxer,h=this.remuxer;if(!u||!h)return r.executeEnd=xn(),[Un(t)];var d=u.flush(o);return Bn(d)?d.then((function(r){return e.flushRemux(s,r,t),s})):(this.flushRemux(s,d,t),s)},e.flushRemux=function(t,e,r){var i=e.audioTrack,n=e.videoTrack,a=e.id3Track,s=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;w.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var h=this.remuxer.remux(i,n,a,s,u,l,!0,this.id);t.push({remuxResult:h,chunkMeta:r}),r.transmuxing.executeEnd=xn()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i,n){var a=this.demuxer,s=this.remuxer;a&&s&&(a.resetInitSegment(t,e,r,i),s.resetInitSegment(t,e,r,n))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,n){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,n):this.transmuxUnencrypted(t,r,i,n)},e.transmuxUnencrypted=function(t,e,r,i){var n=this.demuxer.demux(t,e,!1,!this.config.progressive),a=n.audioTrack,s=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,e,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,n){var a=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:a.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,r,i,!1,a.id),chunkMeta:n}}))},e.configureTransmuxer=function(t){for(var e,r=this.config,i=this.observer,n=this.typeSupported,a=this.vendor,s=0,o=On.length;s1&&l.id===(null==m?void 0:m.stats.chunkCount),L=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=A),!a||!T&&L||(a.stats.parsing.start=A);var R=!(m&&(null==(h=n.initSegment)?void 0:h.url)===(null==(d=m.initSegment)?void 0:d.url)),b=new Kn(p,L,o,y,g,R);if(!L||p||R){w.log("[transmuxer-interface, "+n.type+"]: Starting new transmux session for sn: "+l.sn+" p: "+l.part+" level: "+l.level+" id: "+l.id+"\n discontinuity: "+p+"\n trackSwitch: "+y+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+g+"\n initSegmentChange: "+R);var k=new Gn(r,i,e,s,u);this.configureTransmuxer(k)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:v,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(f){var D=f.push(t,v,l,b);Bn(D)?(f.async=!0,D.then((function(t){c.handleTransmuxComplete(t)})).catch((function(t){c.transmuxerError(t,l,"transmuxer-interface push error")}))):(f.async=!1,this.handleTransmuxComplete(D))}},r.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(r){var i=r.flush(t);Bn(i)||r.async?(Bn(i)||(i=Promise.resolve(i)),i.then((function(r){e.handleFlushResult(r,t)})).catch((function(r){e.transmuxerError(r,t,"transmuxer-interface flush error")}))):this.handleFlushResult(i,t)}},r.transmuxerError=function(t,e,r){this.hls&&(this.error=t,this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:r}))},r.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},r.onWorkerMessage=function(t){var e=t.data;if(null!=e&&e.event){var r=this.hls;if(this.hls)switch(e.event){case"init":var i,n=null==(i=this.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":w[e.data.logType]&&w[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}}else w.warn("worker message received with no "+(e?"event name":"data"))},r.configureTransmuxer=function(t){var e=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)},r.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},e}();function Xn(t,e){if(t.length!==e.length)return!1;for(var r=0;r0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e,this.state=Ti):(this.loadedmetadata=!1,this.state=Ri),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()},r.doTick=function(){switch(this.state){case Ti:this.doTickIdle();break;case Ri:var e,r=this.levels,i=this.trackId,n=null==r||null==(e=r[i])?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=wi}break;case Ai:var a,s=performance.now(),o=this.retryDate;if(!o||s>=o||null!=(a=this.media)&&a.seeking){var l=this.levels,u=this.trackId;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==l?void 0:l[u])||null),this.state=Ti}break;case wi:var h=this.waitingData;if(h){var d=h.frag,c=h.part,f=h.cache,g=h.complete;if(void 0!==this.initPTS[d.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Li;var v={frag:d,part:c,payload:f.flush(),networkDetails:null};this._handleFragmentLoadProgress(v),g&&t.prototype._handleFragmentLoadComplete.call(this,v)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log("Waiting fragment cc ("+d.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var m=this.getLoadPosition(),p=ri.bufferInfo(this.mediaBuffer,m,this.config.maxBufferHole);Rr(p.end,this.config.maxFragLookUpTolerance,d)<0&&(this.log("Waiting fragment cc ("+d.cc+") @ "+d.start+" cancelled because another fragment at "+p.end+" is needed"),this.clearWaitingFragment())}}else this.state=Ti}this.onTickEnd()},r.clearWaitingFragment=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Ti)},r.resetLoadingState=function(){this.clearWaitingFragment(),t.prototype.resetLoadingState.call(this)},r.onTickEnd=function(){var t=this.media;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)},r.doTickIdle=function(){var t=this.hls,e=this.levels,r=this.media,i=this.trackId,n=t.config;if((r||!this.startFragRequested&&n.startFragPrefetch)&&null!=e&&e[i]){var a=e[i],s=a.details;if(!s||s.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(s))this.state=Ri;else{var o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,O,Me));var l=this.getFwdBufferInfo(o,Me);if(null!==l){var u=this.bufferedTrack,h=this.switchingTrack;if(!h&&this._streamEnded(l,s))return t.trigger(S.BUFFER_EOS,{type:"audio"}),void(this.state=Di);var d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Fe),c=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len),g=s.fragments,v=g[0].start,m=this.flushing?this.getLoadPosition():l.end;if(h&&r){var p=this.getLoadPosition();u&&!zn(h.attrs,u.attrs)&&(m=p),s.PTSKnown&&pv||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=v+.05)}if(!(c>=f&&!h&&md.end+s.targetduration;if(T||(null==d||!d.len)&&l.len){var L=this.getAppendedFrag(y.start,Fe);if(null===L)return;if(E||(E=!!L.gap||!!T&&0===d.len),T&&!E||E&&l.nextStart&&l.nextStart-1)n=a[o];else{var l=Hr(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var h={audioTracks:a};this.log("Updating audio tracks, "+a.length+" track(s) found in group(s): "+(null==r?void 0:r.join(","))),this.hls.trigger(S.AUDIO_TRACKS_UPDATED,h);var d=this.trackId;if(-1!==u&&-1===d)this.setAudioTrack(u);else if(a.length&&-1===d){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+a.length);this.warn(f.message),this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}},r.onError=function(t,e){!e.fatal&&e.context&&(e.context.type!==xe||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))},r.setAudioOption=function(t){var e=this.hls;if(e.config.audioPreference=t,t){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&Vr(t,i,Yr))return i;var n=Hr(t,this.tracksInGroup,Yr);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n),a}if(i){var s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);var o=function(t,e,r,i,n){var a=e[i],s=e.reduce((function(t,e,r){var i=e.uri;return(t[i]||(t[i]=[])).push(r),t}),{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),h=Wr(e,i,(function(e){if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==u)return!1;var i=e.audioGroups,a=r.filter((function(t){return!i||-1!==i.indexOf(t.groupId)}));return Hr(t,a,n)>-1}));return h>-1?h:Wr(e,i,(function(e){var i=e.audioGroups,a=r.filter((function(t){return!i||-1!==i.indexOf(t.groupId)}));return Hr(t,a,n)>-1}))}(t,e.levels,r,s,Yr);if(-1===o)return null;e.nextLoadLevel=o}if(t.channels||t.audioCodec){var l=Hr(t,r);if(l>-1)return r[l]}}}return null},r.setAudioTrack=function(t){var e=this.tracksInGroup;if(t<0||t>=e.length)this.warn("Invalid audio track id: "+t);else{this.clearTimer(),this.selectDefaultTrack=!1;var r=this.currentTrack,n=e[t],a=n.details&&!n.details.live;if(!(t===this.trackId&&n===r&&a||(this.log("Switching to audio-track "+t+' "'+n.name+'" lang:'+n.lang+" group:"+n.groupId+" channels:"+n.channels),this.trackId=t,this.currentTrack=n,this.hls.trigger(S.AUDIO_TRACK_SWITCHING,i({},n)),a))){var s=this.switchParams(n.url,null==r?void 0:r.details,n.details);this.loadPlaylist(s)}}},r.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=n[o].start&&s<=n[o].end){a=n[o];break}var l=r.start+r.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null)}}},r.onBufferFlushing=function(t,e){var r=e.startOffset,i=e.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;e.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach((function(t){for(var e=0;e=n.length)&&o){this.log("Subtitle track "+s+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+",duration:"+a.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(a.live||null!=(r=o.details)&&r.live){var u=this.mainDetails;if(a.deltaUpdateFailed||!u)return;var h,d=u.fragments[0];o.details?0===(l=this.alignPlaylists(a,o.details,null==(h=this.levelLastLoaded)?void 0:h.details))&&d&&fr(a,l=d.start):a.hasProgramDateTime&&u.hasProgramDateTime?(li(a,u),l=a.fragments[0].start):d&&fr(a,l=d.start)}o.details=a,this.levelLastLoaded=o,s===i&&(this.startFragRequested||!this.mainDetails&&a.live||this.setStartPosition(this.mainDetails||a,l),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===Ti&&(Ar(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+s)},r._handleFragmentLoadComplete=function(t){var e=this,r=t.frag,i=t.payload,n=r.decryptdata,a=this.hls;if(!this.fragContextChanged(r)&&i&&i.byteLength>0&&null!=n&&n.key&&n.iv&&"AES-128"===n.method){var s=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer).catch((function(t){throw a.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:r}),t})).then((function(t){var e=performance.now();a.trigger(S.FRAG_DECRYPTED,{frag:r,payload:t,stats:{tstart:s,tdecrypt:e}})})).catch((function(t){e.warn(t.name+": "+t.message),e.state=Ti}))}},r.doTick=function(){if(this.media){if(this.state===Ti){var t=this.currentTrackId,e=this.levels,r=null==e?void 0:e[t];if(!r||!e.length||!r.details)return;var i=this.config,n=this.getLoadPosition(),a=ri.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),s=a.end,o=a.len,l=this.getFwdBufferInfo(this.media,Fe),u=r.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+u.levelTargetDuration)return;var h=u.fragments,d=h.length,c=u.edge,f=null,g=this.fragPrevious;if(sc-v?0:v;!(f=Ar(g,h,Math.max(h[0].start,s),m))&&g&&g.start>>=0)>i-1)throw new DOMException("Failed to execute '"+e+"' on 'TimeRanges': The index provided ("+r+") is greater than the maximum bound ("+i+")");return t[r][e]};this.buffered={get length(){return t.length},end:function(r){return e("end",r,t.length)},start:function(r){return e("start",r,t.length)}}},ea=function(t){function e(e){var r;return(r=t.call(this,e,"[subtitle-track-controller]")||this).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){for(var t=null,e=Ye(r.media.textTracks),i=0;i-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},r.pollTrackChange=function(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)},r.onMediaDetaching=function(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Ye(this.media.textTracks).forEach((function(t){He(t)})),this.subtitleTrack=-1,this.media=null)},r.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},r.onManifestParsed=function(t,e){this.tracks=e.subtitleTracks},r.onSubtitleTrackLoaded=function(t,e){var r=e.id,i=e.groupId,n=e.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=e.details,this.log("Subtitle track "+r+' "'+a.name+'" lang:'+a.lang+" group:"+i+" loaded ["+n.startSN+"-"+n.endSN+"]"),r===this.trackId&&this.playlistLoaded(r,e,s)}else this.warn("Subtitle track with id:"+r+" and group:"+i+" not found in active group "+(null==a?void 0:a.groupId))},r.onLevelLoading=function(t,e){this.switchLevel(e.level)},r.onLevelSwitching=function(t,e){this.switchLevel(e.level)},r.switchLevel=function(t){var e=this.hls.levels[t];if(e){var r=e.subtitleGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some((function(t){return-1===(null==i?void 0:i.indexOf(t))}))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter((function(t){return!r||-1!==r.indexOf(t.groupId)}));if(a.length)this.selectDefaultTrack&&!a.some((function(t){return t.default}))&&(this.selectDefaultTrack=!1),a.forEach((function(t,e){t.id=e}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.subtitlePreference;if(!n&&s){this.selectDefaultTrack=!1;var o=Hr(s,a);if(o>-1)n=a[o];else{var l=Hr(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var h={subtitleTracks:a};this.log("Updating subtitle tracks, "+a.length+' track(s) found in "'+(null==r?void 0:r.join(","))+'" group-id'),this.hls.trigger(S.SUBTITLE_TRACKS_UPDATED,h),-1!==u&&-1===this.trackId&&this.setSubtitleTrack(u)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}},r.findTrackId=function(t){for(var e=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}if(r)return null;var a=Hr(t,e);if(a>-1)return e[a]}}return null},r.loadPlaylist=function(e){t.prototype.loadPlaylist.call(this);var r=this.currentTrack;if(this.shouldLoadPlaylist(r)&&r){var i=r.id,n=r.groupId,a=r.url;if(e)try{a=e.addDirectives(a)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Loading subtitle playlist for id "+i),this.hls.trigger(S.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:e||null})}},r.toggleTrackModes=function(){var t=this.media;if(t){var e,r=Ye(t.textTracks),i=this.currentTrack;if(i&&((e=r.filter((function(t){return Qn(i,t)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+i.name+'" and language "'+i.lang+'"')),[].slice.call(r).forEach((function(t){"disabled"!==t.mode&&t!==e&&(t.mode="disabled")})),e){var n=this.subtitleDisplay?"showing":"hidden";e.mode!==n&&(e.mode=n)}}},r.setSubtitleTrack=function(t){var e=this.tracksInGroup;if(this.media)if(t<-1||t>=e.length||!y(t))this.warn("Invalid subtitle track id: "+t);else{this.clearTimer(),this.selectDefaultTrack=!1;var r=this.currentTrack,i=e[t]||null;if(this.trackId=t,this.currentTrack=i,this.toggleTrackModes(),i){var n=!!i.details&&!i.details.live;if(t!==this.trackId||i!==r||!n){this.log("Switching to subtitle-track "+t+(i?' "'+i.name+'" lang:'+i.lang+" group:"+i.groupId:""));var a=i.id,s=i.groupId,o=void 0===s?"":s,l=i.name,u=i.type,h=i.url;this.hls.trigger(S.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:h});var d=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(d)}}else this.hls.trigger(S.SUBTITLE_TRACK_SWITCH,{id:t})}else this.queuedDefaultTrack=t},s(e,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}}]),e}(Fr),ra=function(){function t(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}var e=t.prototype;return e.append=function(t,e,r){var i=this.queues[e];i.push(t),1!==i.length||r||this.executeNext(e)},e.insertAbort=function(t,e){this.queues[e].unshift(t),this.executeNext(e)},e.appendBlocker=function(t){var e,r=new Promise((function(t){e=t})),i={execute:e,onStart:function(){},onComplete:function(){},onError:function(){}};return this.append(i,t),r},e.executeNext=function(t){var e=this.queues[t];if(e.length){var r=e[0];try{r.execute()}catch(e){w.warn('[buffer-operation-queue]: Exception executing "'+t+'" SourceBuffer operation: '+e),r.onError(e);var i=this.buffers[t];null!=i&&i.updating||this.shiftAndExecuteNext(t)}}},e.shiftAndExecuteNext=function(t){this.queues[t].shift(),this.executeNext(t)},e.current=function(t){return this.queues[t][0]},t}(),ia=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,na=function(){function t(t){var e=this;this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=function(t){e.hls&&e.hls.pauseBuffering()},this._onStartStreaming=function(t){e.hls&&e.hls.resumeBuffering()},this._onMediaSourceOpen=function(){var t=e.media,r=e.mediaSource;e.log("Media source opened"),t&&(t.removeEventListener("emptied",e._onMediaEmptied),e.updateMediaElementDuration(),e.hls.trigger(S.MEDIA_ATTACHED,{media:t,mediaSource:r})),r&&r.removeEventListener("sourceopen",e._onMediaSourceOpen),e.checkPendingTracks()},this._onMediaSourceClose=function(){e.log("Media source closed")},this._onMediaSourceEnded=function(){e.log("Media source ended")},this._onMediaEmptied=function(){var t=e.mediaSrc,r=e._objectUrl;t!==r&&w.error("Media element src was set while attaching MediaSource ("+r+" > "+t+")")},this.hls=t;var r,i="[buffer-controller]";this.appendSource=(r=se(t.config.preferManagedMediaSource),"undefined"!=typeof self&&r===self.ManagedMediaSource),this.log=w.log.bind(w,i),this.warn=w.warn.bind(w,i),this.error=w.error.bind(w,i),this._initSourceBuffer(),this.registerListeners()}var e=t.prototype;return e.hasSourceTypes=function(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null},e.registerListeners=function(){var t=this.hls;t.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(S.MANIFEST_LOADING,this.onManifestLoading,this),t.on(S.MANIFEST_PARSED,this.onManifestParsed,this),t.on(S.BUFFER_RESET,this.onBufferReset,this),t.on(S.BUFFER_APPENDING,this.onBufferAppending,this),t.on(S.BUFFER_CODECS,this.onBufferCodecs,this),t.on(S.BUFFER_EOS,this.onBufferEos,this),t.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(S.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(S.FRAG_PARSED,this.onFragParsed,this),t.on(S.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(S.MANIFEST_LOADING,this.onManifestLoading,this),t.off(S.MANIFEST_PARSED,this.onManifestParsed,this),t.off(S.BUFFER_RESET,this.onBufferReset,this),t.off(S.BUFFER_APPENDING,this.onBufferAppending,this),t.off(S.BUFFER_CODECS,this.onBufferCodecs,this),t.off(S.BUFFER_EOS,this.onBufferEos,this),t.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(S.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(S.FRAG_PARSED,this.onFragParsed,this),t.off(S.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new ra(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null},e.onManifestLoading=function(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media,i=se(this.appendSource);if(r&&i){var n,a=this.mediaSource=new i;this.log("created media source: "+(null==(n=a.constructor)?void 0:n.name)),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming));var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,aa(r),function(t,e){var r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}(r,s),r.load()}catch(t){r.src=s}else r.src=s;r.addEventListener("emptied",this._onMediaEmptied)}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn("onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(t.removeAttribute("src"),this.appendSource&&aa(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(S.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){t.resetBuffer(e)})),this._initSourceBuffer()},e.resetBuffer=function(t){var e=this.sourceBuffer[t];try{var r;e&&(this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e))}catch(e){this.warn("onBufferReset "+t,e)}},e.onBufferCodecs=function(t,e){var r=this,i=this.getSourceBufferTypes().length,n=Object.keys(e);if(n.forEach((function(t){if(i){var n=r.tracks[t];if(n&&"function"==typeof n.buffer.changeType){var a,s=e[t],o=s.id,l=s.codec,u=s.levelCodec,h=s.container,d=s.metadata,c=me(n.codec,n.levelCodec),f=null==c?void 0:c.replace(ia,"$1"),g=me(l,u),v=null==(a=g)?void 0:a.replace(ia,"$1");if(g&&f!==v){"audio"===t.slice(0,5)&&(g=ve(g,r.appendSource));var m=h+";codecs="+g;r.appendChangeType(t,m),r.log("switching codec "+c+" to "+g),r.tracks[t]={buffer:n.buffer,codec:l,container:h,levelCodec:u,metadata:d,id:o}}}}else r.pendingTracks[t]=e[t]})),!i){var a=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==a&&(this.log(a+" bufferCodec event(s) expected "+n.join(",")),this.bufferCodecEventsExpected=a),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,n={execute:function(){var n=r.sourceBuffer[t];n&&(r.log("changing "+t+" sourceBuffer type to "+e),n.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Failed to change "+t+" SourceBuffer type",e)}};i.append(n,t,!!this.pendingTracks[t])},e.onBufferAppending=function(t,e){var r=this,i=this.hls,n=this.operationQueue,a=this.tracks,s=e.data,o=e.type,l=e.frag,u=e.part,h=e.chunkMeta,d=h.buffering[o],c=self.performance.now();d.start=c;var f=l.stats.buffering,g=u?u.stats.buffering:null;0===f.start&&(f.start=c),g&&0===g.start&&(g.start=c);var v=a.audio,m=!1;"audio"===o&&"audio/mpeg"===(null==v?void 0:v.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var p=l.start,y={execute:function(){if(d.executeStart=self.performance.now(),m){var t=r.sourceBuffer[o];if(t){var e=p-t.timestampOffset;Math.abs(e)>=.1&&(r.log("Updating audio SourceBuffer timestampOffset to "+p+" (delta: "+e+") sn: "+l.sn+")"),t.timestampOffset=p)}}r.appendExecutor(s,o)},onStart:function(){},onComplete:function(){var t=self.performance.now();d.executeEnd=d.end=t,0===f.first&&(f.first=t),g&&0===g.first&&(g.first=t);var e=r.sourceBuffer,i={};for(var n in e)i[n]=ri.getBuffered(e[n]);r.appendErrors[o]=0,"audio"===o||"video"===o?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(S.BUFFER_APPENDED,{type:o,frag:l,part:u,chunkMeta:h,parent:l.type,timeRanges:i})},onError:function(t){var e={type:L.MEDIA_ERROR,parent:l.type,details:A.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:u,chunkMeta:h,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=A.BUFFER_FULL_ERROR;else{var n=++r.appendErrors[o];e.details=A.BUFFER_APPEND_ERROR,r.warn("Failed "+n+"/"+i.config.appendErrorMaxRetry+' times to append segment in "'+o+'" sourceBuffer'),n>=i.config.appendErrorMaxRetry&&(e.fatal=!0)}i.trigger(S.ERROR,e)}};n.append(y,o,!!this.pendingTracks[o])},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,n=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(S.BUFFER_FLUSHED,{type:t})},onError:function(e){r.warn("Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(n(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){i.append(n(t),t)}))},e.onFragParsed=function(t,e){var r=this,i=e.frag,n=e.part,a=[],s=n?n.elementaryStreams:i.elementaryStreams;s[U]?a.push("audiovideo"):(s[O]&&a.push("audio"),s[N]&&a.push("video")),0===a.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,n&&(n.stats.buffering.end=t);var e=n?n.stats:i.stats;r.hls.trigger(S.FRAG_BUFFERED,{frag:i,part:n,stats:e,id:i.type})}),a)},e.onFragChanged=function(t,e){this.trimBuffers()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var n=r.sourceBuffer[i];return!n||e.type&&e.type!==i||(n.ending=!0,n.ended||(n.ended=!0,r.log(i+" sourceBuffer now EOS"))),t&&!(n&&!n.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((function(){r.getSourceBufferTypes().forEach((function(t){var e=r.sourceBuffer[t];e&&(e.ending=!1)}));var t=r.mediaSource;t&&"open"===t.readyState?(r.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+t.readyState)})))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.trimBuffers=function(){var t=this.hls,e=this.details,r=this.media;if(r&&null!==e&&this.getSourceBufferTypes().length){var i=t.config,n=r.currentTime,a=e.levelTargetDuration,s=e.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(y(s)&&s>0){var o=Math.max(s,a),l=Math.floor(n/a)*a-o;this.flushBackBuffer(n,a,l)}if(y(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){var u=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),h=Math.max(u,a),d=Math.floor(n/a)*a+h;this.flushFrontBuffer(n,a,d)}}},e.flushBackBuffer=function(t,e,r){var i=this,n=this.details,a=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(s){var o=a[s];if(o){var l=ri.getBuffered(o);if(l.length>0&&r>l.start(0)){if(i.hls.trigger(S.BACK_BUFFER_REACHED,{bufferEnd:r}),null!=n&&n.live)i.hls.trigger(S.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(o.ended&&l.end(l.length-1)-t<2*e)return void i.log("Cannot flush "+s+" back buffer while SourceBuffer is in ended state");i.hls.trigger(S.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:s})}}}))},e.flushFrontBuffer=function(t,e,r){var i=this,n=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(a){var s=n[a];if(s){var o=ri.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),h=o.end(l-1);if(r>u||t>=u&&t<=h)return;if(s.ended&&t-h<2*e)return void i.log("Cannot flush "+a+" front buffer while SourceBuffer is in ended state");i.hls.trigger(S.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}}))},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,i=this.mediaSource,n=t.fragments[0].start+t.totalduration,a=r.duration,s=y(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(t)):(n>s&&n>a||!y(a))&&(this.log("Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),n=Math.max(i,i+t.totalduration);this.log("Media Source duration is set to "+e.duration+". Setting seekable range to "+i+"-"+n+"."),e.setLiveSeekableRange(i,n)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&(!t||2===i||"audiovideo"in r)){this.createSourceBuffers(r),this.pendingTracks={};var n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(S.BUFFER_CREATED,{tracks:this.tracks}),n.forEach((function(t){e.executeNext(t)}));else{var a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}},e.createSourceBuffers=function(t){var e=this,r=this.sourceBuffer,i=this.mediaSource;if(!i)throw Error("createSourceBuffers called when mediaSource was null");var n=function(n){if(!r[n]){var a,s=t[n];if(!s)throw Error("source buffer exists for track "+n+", however track does not");var o=-1===(null==(a=s.levelCodec)?void 0:a.indexOf(","))?s.levelCodec:s.codec;o&&"audio"===n.slice(0,5)&&(o=ve(o,e.appendSource));var l=s.container+";codecs="+o;e.log("creating sourceBuffer("+l+")");try{var u=r[n]=i.addSourceBuffer(l),h=n;e.addBufferListener(h,"updatestart",e._onSBUpdateStart),e.addBufferListener(h,"updateend",e._onSBUpdateEnd),e.addBufferListener(h,"error",e._onSBUpdateError),e.appendSource&&e.addBufferListener(h,"bufferedchange",(function(t,r){var i=r.removedRanges;null!=i&&i.length&&e.hls.trigger(S.BUFFER_FLUSHED,{type:n})})),e.tracks[n]={buffer:u,codec:o,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(t){e.error("error while trying to add sourceBuffer: "+t.message),e.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:l})}}};for(var a in t)n(a)},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e;if("closed"!==(null==(e=this.mediaSource)?void 0:e.readyState)){var r=this.operationQueue;r.current(t).onComplete(),r.shiftAndExecuteNext(t)}else this.resetBuffer(t)},e._onSBUpdateError=function(t,e){var r,i=new Error(t+" SourceBuffer error. MediaSource readyState: "+(null==(r=this.mediaSource)?void 0:r.readyState));this.error(""+i,e),this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});var n=this.operationQueue.current(t);n&&n.onError(i)},e.removeExecutor=function(t,e,r){var i=this.media,n=this.mediaSource,a=this.operationQueue,s=this.sourceBuffer[t];if(!i||!n||!s)return this.warn("Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void a.shiftAndExecuteNext(t);var o=y(i.duration)?i.duration:1/0,l=y(n.duration)?n.duration:1/0,u=Math.max(0,e),h=Math.min(r,o,l);h>u&&(!s.ending||s.ended)?(s.ended=!1,this.log("Removing ["+u+","+h+"] from the "+t+" SourceBuffer"),s.remove(u,h)):a.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.sourceBuffer[e];if(r)r.ended=!1,r.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error("Attempting to append to the "+e+" SourceBuffer, but it does not exist")},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);var i=this.operationQueue,n=e.map((function(t){return i.appendBlocker(t)}));Promise.all(n).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];null!=e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var n=r.bind(this,t);this.listeners[t].push({event:e,listener:n}),i.addEventListener(e,n)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},s(t,[{key:"mediaSrc",get:function(){var t,e,r=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==r?void 0:r.src}}]),t}();function aa(t){var e=t.querySelectorAll("source");[].slice.call(e).forEach((function(e){t.removeChild(e)}))}var sa={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},oa=function(t){return String.fromCharCode(sa[t]||t)},la=15,ua=100,ha={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},da={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ca={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},fa={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ga=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],va=function(){function t(){this.time=null,this.verboseLevel=0}return t.prototype.log=function(t,e){if(this.verboseLevel>=t){var r="function"==typeof e?e():e;w.log(this.time+" ["+t+"] "+r)}},t}(),ma=function(t){for(var e=[],r=0;rua&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ua)},e.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var r=this.pos+1;r=144&&this.backSpace();var r=oa(t);this.pos>=ua?this.logger.log(0,(function(){return"Cannot insert "+t.toString(16)+" ("+r+") at position "+e.pos+". Skipping it!"})):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))},e.clearFromPos=function(t){var e;for(e=t;e0&&(r=t?"["+e.join(" | ")+"]":e.join("\n")),r},e.getTextAndFormat=function(){return this.rows},t}(),Sa=function(){function t(t,e,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Ta(r),this.nonDisplayedMemory=new Ta(r),this.lastOutputScreen=new Ta(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var e=t.prototype;return e.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},e.getHandler=function(){return this.outputFilter},e.setHandler=function(t){this.outputFilter=t},e.setPAC=function(t){this.writeScreen.setPAC(t)},e.setBkgData=function(t){this.writeScreen.setBkgData(t)},e.setMode=function(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(function(){return"MODE="+t})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)},e.insertChars=function(t){for(var e=this,r=0;r=46,e.italics)e.foreground="white";else{var r=Math.floor(t/2)-16;e.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)},e.outputDataUpdate=function(t){void 0===t&&(t=!1);var e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))},e.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}(),La=function(){function t(t,e,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var i=this.logger=new va;this.channels=[null,new Sa(t,e,i),new Sa(t+1,r,i)]}var e=t.prototype;return e.getHandler=function(t){return this.channels[t].getHandler()},e.setHandler=function(t,e){this.channels[t].setHandler(e)},e.addData=function(t,e){var r=this;this.logger.time=t;for(var i=function(t){var i=127&e[t],n=127&e[t+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,(function(){return"["+ma([e[t],e[t+1]])+"] -> ("+ma([i,n])+")"}));var o=r.cmdHistory;if(i>=16&&i<=31){if(function(t,e,r){return r.a===t&&r.b===e}(i,n,o))return Aa(null,null,o),r.logger.log(3,(function(){return"Repeated command ("+ma([i,n])+") is dropped"})),0;Aa(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else Aa(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;l&&l>0?r.channels[l].insertChars(s):r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,(function(){return"Couldn't parse cleaned data "+ma([i,n])+" orig: "+ma([e[t],e[t+1]])}))},n=0;n=32&&e<=47||(23===t||31===t)&&e>=33&&e<=35))return!1;var r=20===t||21===t||23===t?1:2,i=this.channels[r];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=r,!0},e.parseMidrow=function(t,e){var r=0;if((17===t||25===t)&&e>=32&&e<=47){if((r=17===t?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(e),this.logger.log(3,(function(){return"MIDROW ("+ma([t,e])+")"})),!0)}return!1},e.parsePAC=function(t,e){var r;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127||(16===t||24===t)&&e>=64&&e<=95))return!1;var i=t<=23?1:2;r=e>=64&&e<=95?1===i?ha[t]:ca[t]:1===i?da[t]:fa[t];var n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(r,e)),this.currentChannel=i,!0)},e.interpretPAC=function(t,e){var r,i={color:null,italics:!1,indent:null,underline:!1,row:t};return r=e>95?e-96:e-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},e.parseChars=function(t,e){var r,i,n=null,a=null;return t>=25?(r=2,a=t-8):(r=1,a=t),a>=17&&a<=19?(i=17===a?e+80:18===a?e+112:e+144,this.logger.log(2,(function(){return"Special char '"+oa(i)+"' in channel "+r})),n=[i]):t>=32&&t<=127&&(n=0===e?[t]:[t,e]),n&&this.logger.log(3,(function(){return"Char codes = "+ma(n).join(",")})),n},e.parseBackgroundAttributes=function(t,e){var r;if(!((16===t||24===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=45&&e<=47))return!1;var i={};16===t||24===t?(r=Math.floor((e-32)/2),i.background=ga[r],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));var n=t<=23?1:2;return this.channels[n].setBkgData(i),!0},e.reset=function(){for(var t=0;tt)&&(this.startTime=t),this.endTime=e,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function(){this.cueRanges=[],this.startTime=null},t}(),ba=function(){if(null!=j&&j.VTTCue)return self.VTTCue;var t=["","lr","rl"],e=["start","middle","end","left","right"];function r(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;var r=e.toLowerCase();return!!~t.indexOf(r)&&r}function i(t){return r(e,t)}function n(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return T},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return L},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),ka=function(){function t(){}return t.prototype.decode=function(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))},t}();function Da(t){function e(t,e,r,i){return 3600*(0|t)+60*(0|e)+(0|r)+parseFloat(i||0)}var r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}var Ia=function(){function t(){this.values=Object.create(null)}var e=t.prototype;return e.set=function(t,e){this.get(t)||""===e||(this.values[t]=e)},e.get=function(t,e,r){return r?this.has(t)?this.values[t]:e[r]:this.has(t)?this.values[t]:e},e.has=function(t){return t in this.values},e.alt=function(t,e,r){for(var i=0;i=0&&r<=100)return this.set(t,r),!0}return!1},t}();function wa(t,e,r,i){var n=i?t.split(i):[t];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);2===s.length&&e(s[0],s[1])}}var Ca=new ba(0,0,""),_a="middle"===Ca.align?"middle":"center";function xa(t,e,r){var i=t;function n(){var e=Da(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=n(),a(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),a(),e.endTime=n(),a(),function(t,e){var i=new Ia;wa(t,(function(t,e){var n;switch(t){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===e){i.set(t,r[a].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":n=e.split(","),i.integer(t,n[0]),i.percent(t,n[0])&&i.set("snapToLines",!1),i.alt(t,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",_a,"end"]);break;case"position":n=e.split(","),i.percent(t,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",_a,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",_a,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===Ca.line&&(n=-1),e.line=n,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",_a);var a=i.get("position","auto");"auto"===a&&50===Ca.position&&(a="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=a}(t,e)}function Pa(t){return t.replace(//gi,"\n")}var Fa=function(){function t(){this.state="INITIAL",this.buffer="",this.decoder=new ka,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=t.prototype;return e.parse=function(t){var e=this;function r(){var t=e.buffer,r=0;for(t=Pa(t);r>>0).toString()};function Ua(t,e,r){return Na(t.toString())+Na(e.toString())+Na(r)}function Ba(t,e,r,i,n,a,s){var o,l,u,h=new Fa,d=Rt(new Uint8Array(t)).trim().replace(Ma,"\n").split("\n"),c=[],f=e?(o=e.baseTime,void 0===(l=e.timescale)&&(l=1),Rn(o,An,1/l)):0,g="00:00.000",v=0,m=0,p=!0;h.oncue=function(t){var a=r[i],s=r.ccOffset,o=(v-f)/9e4;if(null!=a&&a.new&&(void 0!==m?s=r.ccOffset=a.start:function(t,e,r){var i=t[e],n=t[i.prevCC];if(!n||!n.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(a=n)&&a.new;){var a;t.ccOffset+=i.start-n.start,i.new=!1,n=t[(i=n).prevCC]}t.presentationOffset=r}(r,i,o)),o){if(!e)return void(u=new Error("Missing initPTS for VTT MPEGTS"));s=o-r.presentationOffset}var l=t.endTime-t.startTime,h=wn(9e4*(t.startTime+s-m),9e4*n)/9e4;t.startTime=Math.max(h,0),t.endTime=Math.max(h+l,0);var d=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(d)),t.id||(t.id=Ua(t.startTime,t.endTime,d)),t.endTime>0&&c.push(t)},h.onparsingerror=function(t){u=t},h.onflush=function(){u?s(u):a(c)},d.forEach((function(t){if(p){if(Oa(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((function(t){Oa(t,"LOCAL:")?g=t.slice(6):Oa(t,"MPEGTS:")&&(v=parseInt(t.slice(7)))}));try{m=function(t){var e=parseInt(t.slice(-3)),r=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(y(e)&&y(r)&&y(i)&&y(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*r,(e+=6e4*i)+36e5*n}(g)/1e3}catch(t){u=t}return}""===t&&(p=!1)}h.parse(t+"\n")})),h.flush()}var Ga="stpp.ttml.im1t",Ka=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ha=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Va={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ya(t,e,r,i){var n=Ot(new Uint8Array(t),["mdat"]);if(0!==n.length){var a,s,l,u,h=n.map((function(t){return Rt(t)})),d=(a=e.baseTime,s=1,void 0===(l=e.timescale)&&(l=1),void 0===u&&(u=!1),Rn(a,s,1/l,u));try{h.forEach((function(t){return r(function(t,e){var r=(new DOMParser).parseFromString(t,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((function(t,e){return t[e]=i.getAttribute("ttp:"+e)||n[e],t}),{}),s="preserve"!==i.getAttribute("xml:space"),l=ja(Wa(i,"styling","style")),u=ja(Wa(i,"layout","region")),h=Wa(i,"body","[begin]");return[].map.call(h,(function(t){var r=qa(t,s);if(!r||!t.hasAttribute("begin"))return null;var i=Qa(t.getAttribute("begin"),a),n=Qa(t.getAttribute("dur"),a),h=Qa(t.getAttribute("end"),a);if(null===i)throw za(t);if(null===h){if(null===n)throw za(t);h=i+n}var d=new ba(i-e,h-e,r);d.id=Ua(d.startTime,d.endTime,d.text);var c=function(t,e,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return s&&r.hasOwnProperty(s)&&(n=r[s]),a.reduce((function(r,a){var s=Xa(e,i,a)||Xa(t,i,a)||Xa(n,i,a);return s&&(r[a]=s),r}),{})}(u[t.getAttribute("region")],l[t.getAttribute("style")],l),f=c.textAlign;if(f){var g=Va[f];g&&(d.lineAlign=g),d.align=f}return o(d,c),d})).filter((function(t){return null!==t}))}(t,d))}))}catch(t){i(t)}}else i(new Error("Could not parse IMSC1 mdat"))}function Wa(t,e,r){var i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function ja(t){return t.reduce((function(t,e){var r=e.getAttribute("xml:id");return r&&(t[r]=e),t}),{})}function qa(t,e){return[].slice.call(t.childNodes).reduce((function(t,r,i){var n;return"br"===r.nodeName&&i?t+"\n":null!=(n=r.childNodes)&&n.length?qa(r,e):e?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent}),"")}function Xa(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function za(t){return new Error("Could not parse ttml timestamp "+t)}function Qa(t,e){if(!t)return null;var r=Da(t);return null===r&&(Ka.test(t)?r=function(t,e){var r=Ka.exec(t),i=(0|r[4])+(0|r[5])/e.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/e.frameRate}(t,e):Ha.test(t)&&(r=function(t,e){var r=Ha.exec(t),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),r}var Ja=function(){function t(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(S.MANIFEST_LOADING,this.onManifestLoading,this),t.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(S.FRAG_LOADING,this.onFragLoading,this),t.on(S.FRAG_LOADED,this.onFragLoaded,this),t.on(S.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(S.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(S.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(S.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this)}var e=t.prototype;return e.destroy=function(){var t=this.hls;t.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(S.MANIFEST_LOADING,this.onManifestLoading,this),t.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(S.FRAG_LOADING,this.onFragLoading,this),t.off(S.FRAG_LOADED,this.onFragLoaded,this),t.off(S.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(S.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(S.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(S.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0},e.initCea608Parsers=function(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){var t=new Ra(this,"textTrack1"),e=new Ra(this,"textTrack2"),r=new Ra(this,"textTrack3"),i=new Ra(this,"textTrack4");this.cea608Parser1=new La(1,t,e),this.cea608Parser2=new La(3,r,i)}},e.addCues=function(t,e,r,i,n){for(var a,s,o,l,u=!1,h=n.length;h--;){var d=n[h],c=(a=d[0],s=d[1],o=e,l=r,Math.min(s,l)-Math.max(a,o));if(c>=0&&(d[0]=Math.min(d[0],e),d[1]=Math.max(d[1],r),u=!0,c/(r-e)>.5))return}if(u||n.push([e,r]),this.config.renderTextTracksNatively){var f=this.captionsTracks[t];this.Cues.newCue(f,e,r,i)}else{var g=this.Cues.newCue(null,e,r,i);this.hls.trigger(S.CUES_PARSED,{type:"captions",cues:g,track:t})}},e.onInitPtsFound=function(t,e){var r=this,i=e.frag,n=e.id,a=e.initPTS,s=e.timescale,o=this.unparsedVttFrags;"main"===n&&(this.initPTS[i.cc]={baseTime:a,timescale:s}),o.length&&(this.unparsedVttFrags=[],o.forEach((function(t){r.onFragLoaded(S.FRAG_LOADED,t)})))},e.getExistingTrack=function(t,e){var r=this.media;if(r)for(var i=0;ii.cc||l.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})}))}else s.push(t)},e._fallbackToIMSC1=function(t,e){var r=this,i=this.tracks[t.level];i.textCodec||Ya(e,this.initPTS[t.cc],(function(){i.textCodec=Ga,r._parseIMSC1(t,e)}),(function(){i.textCodec="wvtt"}))},e._appendCues=function(t,e){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach((function(t){return Ke(i,t)}))}else{var n=this.tracks[e];if(!n)return;var a=n.default?"default":"subtitles"+e;r.trigger(S.CUES_PARSED,{type:"subtitles",cues:t,track:a})}},e.onFragDecrypted=function(t,e){e.frag.type===Oe&&this.onFragLoaded(S.FRAG_LOADED,e)},e.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},e.onFragParsingUserdata=function(t,e){this.initCea608Parsers();var r=this.cea608Parser1,i=this.cea608Parser2;if(this.enabled&&r&&i){var n=e.frag,a=e.samples;if(n.type!==Fe||"NONE"!==this.closedCaptionsForLevel(n))for(var s=0;sthis.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},e.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(t,i){return r.isLevelAllowed(t)&&i<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},e.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},e.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},e.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},e.isLevelAllowed=function(t){return!this.restrictedLevels.some((function(e){return t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height}))},t.getMaxLevelByMediaSize=function(t,e,r){if(null==t||!t.length)return-1;for(var i,n,a=t.length-1,s=Math.max(e,r),o=0;o=s||l.height>=s)&&(i=l,!(n=t[o+1])||i.width!==n.width||i.height!==n.height)){a=o;break}}return a},s(t,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}}]),t}(),es=function(){function t(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=e-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(S.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;w.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(S.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}(),rs="[eme]",is=function(){function t(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=w.debug.bind(w,rs),this.log=w.log.bind(w,rs),this.warn=w.warn.bind(w,rs),this.error=w.error.bind(w,rs),this.hls=e,this.config=e.config,this.registerListeners()}var e=t.prototype;return e.destroy=function(){this.unregisterListeners(),this.onMediaDetached();var t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null},e.registerListeners=function(){this.hls.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(S.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(S.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(S.MANIFEST_LOADED,this.onManifestLoaded,this)},e.unregisterListeners=function(){this.hls.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(S.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(S.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(S.MANIFEST_LOADED,this.onManifestLoaded,this)},e.getLicenseServerUrl=function(t){var e=this.config,r=e.drmSystems,i=e.widevineLicenseUrl,n=r[t];if(n)return n.licenseUrl;if(t===q.WIDEVINE&&i)return i;throw new Error('no license server URL configured for key-system "'+t+'"')},e.getServerCertificateUrl=function(t){var e=this.config.drmSystems[t];if(e)return e.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+t+'"]')},e.attemptKeySystemAccess=function(t){var e=this,r=this.hls.levels,i=function(t,e,r){return!!t&&r.indexOf(t)===e},n=r.map((function(t){return t.audioCodec})).filter(i),a=r.map((function(t){return t.videoCodec})).filter(i);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise((function(r,i){!function t(s){var o=s.shift();e.getMediaKeysPromise(o,n,a).then((function(t){return r({keySystem:o,mediaKeys:t})})).catch((function(e){s.length?t(s):i(e instanceof ls?e:new ls({type:L.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))}(t)}))},e.requestMediaKeySystemAccess=function(t,e){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function "+r;return null===ot&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(i))}return r(t,e)},e.getMediaKeysPromise=function(t,e,r){var i=this,n=function(t,e,r,i){var n;switch(t){case q.FAIRPLAY:n=["cenc","sinf"];break;case q.WIDEVINE:case q.PLAYREADY:n=["cenc"];break;case q.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+t)}return function(t,e,r,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map((function(t){return{contentType:'audio/mp4; codecs="'+t+'"',robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}})),videoCapabilities:r.map((function(t){return{contentType:'video/mp4; codecs="'+t+'"',robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}}))}]}(n,e,r,i)}(t,e,r,this.config.drmSystemOptions),a=this.keySystemAccessPromises[t],s=null==a?void 0:a.keySystemAccess;if(!s){this.log('Requesting encrypted media "'+t+'" key-system access with config: '+JSON.stringify(n)),s=this.requestMediaKeySystemAccess(t,n);var o=this.keySystemAccessPromises[t]={keySystemAccess:s};return s.catch((function(e){i.log('Failed to obtain access to key-system "'+t+'": '+e)})),s.then((function(e){i.log('Access for key-system "'+e.keySystem+'" obtained');var r=i.fetchServerCertificate(t);return i.log('Create media-keys for "'+t+'"'),o.mediaKeys=e.createMediaKeys().then((function(e){return i.log('Media-keys created for "'+t+'"'),r.then((function(r){return r?i.setMediaKeysServerCertificate(e,t,r):e}))})),o.mediaKeys.catch((function(e){i.error('Failed to create media-keys for "'+t+'"}: '+e)})),o.mediaKeys}))}return s.then((function(){return a.mediaKeys}))},e.createMediaKeySessionContext=function(t){var e=t.decryptdata,r=t.keySystem,i=t.mediaKeys;this.log('Creating key-system session "'+r+'" keyId: '+kt.hexDump(e.keyId||[]));var n=i.createSession(),a={decryptdata:e,keySystem:r,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a},e.renewKeySession=function(t){var e=t.decryptdata;if(e.pssh){var r=this.createMediaKeySessionContext(t),i=this.getKeyIdString(e);this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(r,"cenc",e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)},e.getKeyIdString=function(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return kt.hexDump(t.keyId)},e.updateKeySession=function(t,e){var r,i=t.mediaKeysSession;return this.log('Updating key-session "'+i.sessionId+'" for keyID '+kt.hexDump((null==(r=t.decryptdata)?void 0:r.keyId)||[])+"\n } (data length: "+(e?e.byteLength:e)+")"),i.update(e)},e.selectKeySystemFormat=function(t){var e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: "+t.sn+" "+t.type+": "+t.level+") key formats "+e.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise},e.getKeyFormatPromise=function(t){var e=this;return new Promise((function(r,i){var n=at(e.config),a=t.map($).filter((function(t){return!!t&&-1!==n.indexOf(t)}));return e.getKeySystemSelectionPromise(a).then((function(t){var e=t.keySystem,n=nt(e);n?r(n):i(new Error('Unable to find format for key-system "'+e+'"'))})).catch(i)}))},e.loadKey=function(t){var e=this,r=t.keyInfo.decryptdata,i=this.getKeyIdString(r),n="(keyId: "+i+' format: "'+r.keyFormat+'" method: '+r.method+" uri: "+r.uri+")";this.log("Starting session for key "+n);var a=this.keyIdToKeySessionPromise[i];return a||(a=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(r).then((function(i){var a=i.keySystem,s=i.mediaKeys;return e.throwIfDestroyed(),e.log("Handle encrypted media sn: "+t.frag.sn+" "+t.frag.type+": "+t.frag.level+" using key "+n),e.attemptSetMediaKeys(a,s).then((function(){e.throwIfDestroyed();var t=e.createMediaKeySessionContext({keySystem:a,mediaKeys:s,decryptdata:r});return e.generateRequestWithPreferredKeySession(t,"cenc",r.pssh,"playlist-key")}))}))).catch((function(t){return e.handleError(t)})),a},e.throwIfDestroyed=function(t){if(!this.hls)throw new Error("invalid state")},e.handleError=function(t){this.hls&&(this.error(t.message),t instanceof ls?this.hls.trigger(S.ERROR,t.data):this.hls.trigger(S.ERROR,{type:L.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))},e.getKeySystemForKeyPromise=function(t){var e=this.getKeyIdString(t),r=this.keyIdToKeySessionPromise[e];if(!r){var i=$(t.keyFormat),n=i?[i]:at(this.config);return this.attemptKeySystemAccess(n)}return r},e.getKeySystemSelectionPromise=function(t){if(t.length||(t=at(this.config)),0===t.length)throw new ls({type:L.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+JSON.stringify({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(t)},e._onMediaEncrypted=function(t){var e=this,r=t.initDataType,i=t.initData,n='"'+t.type+'" event: init data type: "'+r+'"';if(this.debug(n),null!==i){var a,s;if("sinf"===r&&this.config.drmSystems[q.FAIRPLAY]){var o=Ct(new Uint8Array(i));try{var l=V(JSON.parse(o).sinf),u=Vt(new Uint8Array(l));if(!u)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=u.subarray(8,24),s=q.FAIRPLAY}catch(t){return void this.warn(n+" Failed to parse sinf: "+t)}}else{var h=function(t){var e=[];if(t instanceof ArrayBuffer)for(var r=t.byteLength,i=0;i+320)for(var a,s=0,o=n.length;s in key message");return W(atob(f))},e.setupLicenseXHR=function(t,e,r,i){var n=this,a=this.config.licenseXhrSetup;return a?Promise.resolve().then((function(){if(!r.decryptdata)throw new Error("Key removed");return a.call(n.hls,t,e,r,i)})).catch((function(s){if(!r.decryptdata)throw s;return t.open("POST",e,!0),a.call(n.hls,t,e,r,i)})).then((function(r){return t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:r||i}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:i}))},e.requestLicense=function(t,e){var r=this,i=this.config.keyLoadPolicy.default;return new Promise((function(n,a){var s=r.getLicenseServerUrl(t.keySystem);r.log("Sending license request to URL: "+s);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!r.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(4===o.readyState)if(200===o.status){r._requestLicenseFailureCount=0;var l=o.response;r.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var u=r.config.licenseResponseCallback;if(u)try{l=u.call(r.hls,o,s,t)}catch(t){r.error(t)}n(l)}else{var h=i.errorRetry,d=h?h.maxNumRetry:0;if(r._requestLicenseFailureCount++,r._requestLicenseFailureCount>d||o.status>=400&&o.status<500)a(new ls({type:L.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:s,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+s+"). Status: "+o.status+" ("+o.statusText+")"));else{var c=d-r._requestLicenseFailureCount+1;r.warn("Retrying license request, "+c+" attempts left"),r.requestLicense(t,e).then(n,a)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,r.setupLicenseXHR(o,s,t,e).then((function(e){var i=e.xhr,n=e.licenseChallenge;t.keySystem==q.PLAYREADY&&(n=r.unpackPlayReadyKeyMessage(i,n)),i.send(n)}))}))},e.onMediaAttached=function(t,e){if(this.config.emeEnabled){var r=e.media;this.media=r,r.addEventListener("encrypted",this.onMediaEncrypted),r.addEventListener("waitingforkey",this.onWaitingForKey)}},e.onMediaDetached=function(){var e=this,r=this.media,i=this.mediaKeySessions;r&&(r.removeEventListener("encrypted",this.onMediaEncrypted),r.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Zt.clearKeyUriToKeyIdMap();var n=i.length;t.CDMCleanupPromise=Promise.all(i.map((function(t){return e.removeSession(t)})).concat(null==r?void 0:r.setMediaKeys(null).catch((function(t){e.log("Could not clear media keys: "+t)})))).then((function(){n&&(e.log("finished closing key sessions and clearing media keys"),i.length=0)})).catch((function(t){e.log("Could not close sessions and clear media keys: "+t)}))},e.onManifestLoading=function(){this.keyFormatPromise=null},e.onManifestLoaded=function(t,e){var r=e.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce((function(t,e){return-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t}),[]);this.log("Selecting key-system from session-keys "+i.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(i)}},e.removeSession=function(t){var e=this,r=t.mediaKeysSession,i=t.licenseXhr;if(r){this.log("Remove licenses and keys and close session "+r.sessionId),t._onmessage&&(r.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;var n=this.mediaKeySessions.indexOf(t);return n>-1&&this.mediaKeySessions.splice(n,1),r.remove().catch((function(t){e.log("Could not remove session: "+t)})).then((function(){return r.close()})).catch((function(t){e.log("Could not close session: "+t)}))}},t}();is.CDMCleanupPromise=void 0;var ns,as,ss,os,ls=function(t){function e(e,r){var i;return(i=t.call(this,r)||this).data=void 0,e.error||(e.error=new Error(r)),i.data=e,e.err=e.error,i}return l(e,t),e}(c(Error));!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(ns||(ns={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(as||(as={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(ss||(ss={}));var us=((os={})[ss.OBJECT]=["br","d","ot","tb"],os[ss.REQUEST]=["bl","dl","mtp","nor","nrr","su"],os[ss.SESSION]=["cid","pr","sf","sid","st","v"],os[ss.STATUS]=["bs","rtp"],os),hs=function t(e,r){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map((function(e){return e instanceof t?e:new t(e)}))),this.value=e,this.params=r},ds=function(t){this.description=void 0,this.description=t},cs="Dict";function fs(t,e,r,i){return new Error("failed to "+t+' "'+(n=e,(Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n))+'" as ')+r,{cause:i});var n}var gs="Bare Item",vs="Boolean",ms="Byte Sequence",ps="Decimal",ys="Integer",Es=/[\x00-\x1f\x7f]+/,Ts="Token",Ss="Key";function Ls(t,e,r){return fs("serialize",t,e,r)}function As(t){if(!1===ArrayBuffer.isView(t))throw Ls(t,ms);return":"+(e=t,btoa(String.fromCharCode.apply(String,e))+":");var e}function Rs(t){if(function(t){return t<-999999999999999||99999999999999912)throw Ls(t,ps);var r=e.toString();return r.includes(".")?r:r+".0"}var Ds="String";function Is(t){var e,r=(e=t).description||e.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw Ls(r,Ts);return r}function ws(t){switch(typeof t){case"number":if(!y(t))throw Ls(t,gs);return Number.isInteger(t)?Rs(t):ks(t);case"string":return function(t){if(Es.test(t))throw Ls(t,Ds);return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(t);case"symbol":return Is(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Ls(t,vs);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return"@"+Rs(t.getTime()/1e3)}(t);if(t instanceof Uint8Array)return As(t);if(t instanceof ds)return Is(t);default:throw Ls(t,gs)}}function Cs(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Ls(t,Ss);return t}function _s(t){return null==t?"":Object.entries(t).map((function(t){var e=t[0],r=t[1];return!0===r?";"+Cs(e):";"+Cs(e)+"="+ws(r)})).join("")}function xs(t){return t instanceof hs?""+ws(t.value)+_s(t.params):ws(t)}function Ps(t,e){var r;if(void 0===e&&(e={whitespace:!0}),"object"!=typeof t)throw Ls(t,cs);var i=t instanceof Map?t.entries():Object.entries(t),n=null!=(r=e)&&r.whitespace?" ":"";return Array.from(i).map((function(t){var e=t[0],r=t[1];r instanceof hs==0&&(r=new hs(r));var i,n=Cs(e);return!0===r.value?n+=_s(r.params):(n+="=",Array.isArray(r.value)?n+="("+(i=r).value.map(xs).join(" ")+")"+_s(i.params):n+=xs(r)),n})).join(","+n)}var Fs=function(t){return"ot"===t||"sf"===t||"st"===t},Ms=function(t){return"number"==typeof t?y(t):null!=t&&""!==t&&!1!==t},Os=function(t){return Math.round(t)},Ns=function(t){return 100*Os(t/100)},Us={br:Os,d:Os,bl:Ns,dl:Ns,mtp:Ns,nor:function(t,e){return null!=e&&e.baseUrl&&(t=function(t,e){var r=new URL(t),i=new URL(e);if(r.origin!==i.origin)return t;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1);n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")}(t,e.baseUrl)),encodeURIComponent(t)},rtp:Ns,tb:Os};function Bs(t,e){return void 0===e&&(e={}),t?function(t,e){return Ps(t,e)}(function(t,e){var r={};if(null==t||"object"!=typeof t)return r;var i=Object.keys(t).sort(),n=o({},Us,null==e?void 0:e.formatters),a=null==e?void 0:e.filter;return i.forEach((function(i){if(null==a||!a(i)){var s=t[i],o=n[i];o&&(s=o(s,e)),"v"===i&&1===s||"pr"==i&&1===s||Ms(s)&&(Fs(i)&&"string"==typeof s&&(s=new ds(s)),r[i]=s)}})),r}(t,e),o({whitespace:!1},e)):""}function Gs(t,e,r){return o(t,function(t,e){var r;if(void 0===e&&(e={}),!t)return{};var i=Object.entries(t),n=Object.entries(us).concat(Object.entries((null==(r=e)?void 0:r.customHeaderMap)||{})),a=i.reduce((function(t,e){var r,i=e[0],a=e[1],s=(null==(r=n.find((function(t){return t[1].includes(i)})))?void 0:r[0])||ss.REQUEST;return null!=t[s]||(t[s]={}),t[s][i]=a,t}),{});return Object.entries(a).reduce((function(t,r){var i=r[0],n=r[1];return t[i]=Bs(n,e),t}),{})}(e,r))}var Ks="CMCD",Hs=/CMCD=[^&#]+/;function Vs(t,e,r){var i=function(t,e){if(void 0===e&&(e={}),!t)return"";var r=Bs(t,e);return Ks+"="+encodeURIComponent(r)}(e,r);if(!i)return t;if(Hs.test(t))return t.replace(Hs,i);var n=t.includes("?")?"&":"?";return""+t+n+i}var Ys=function(){function t(t){var e=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){e.initialized&&(e.starved=!0),e.buffering=!0},this.onPlaying=function(){e.initialized||(e.initialized=!0),e.buffering=!1},this.applyPlaylistData=function(t){try{e.apply(t,{ot:ns.MANIFEST,su:!e.initialized})}catch(t){w.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=function(t){try{var r=t.frag,i=e.hls.levels[r.level],n=e.getObjectType(r),a={d:1e3*r.duration,ot:n};n!==ns.VIDEO&&n!==ns.AUDIO&&n!=ns.MUXED||(a.br=i.bitrate/1e3,a.tb=e.getTopBandwidth(n)/1e3,a.bl=e.getBufferLength(n)),e.apply(t,a)}catch(t){w.warn("Could not generate segment CMCD data.",t)}},this.hls=t;var r=this.config=t.config,i=r.cmcd;null!=i&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch(i){try{var t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==t?e:3&e|8).toString(16)}))}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(S.MEDIA_DETACHED,this.onMediaDetached,this),t.on(S.BUFFER_CREATED,this.onBufferCreated,this)},e.unregisterListeners=function(){var t=this.hls;t.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(S.MEDIA_DETACHED,this.onMediaDetached,this),t.off(S.BUFFER_CREATED,this.onBufferCreated,this)},e.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null},e.onMediaAttached=function(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},e.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},e.onBufferCreated=function(t,e){var r,i;this.audioBuffer=null==(r=e.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer},e.createData=function(){var t;return{v:1,sf:as.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},e.apply=function(t,e){void 0===e&&(e={}),o(e,this.createData());var r=e.ot===ns.INIT||e.ot===ns.VIDEO||e.ot===ns.MUXED;this.starved&&r&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);var i=this.includeKeys;i&&(e=Object.keys(e).reduce((function(t,r){return i.includes(r)&&(t[r]=e[r]),t}),{})),this.useHeaders?(t.headers||(t.headers={}),Gs(t.headers,e)):t.url=Vs(t.url,e)},e.getObjectType=function(t){var e=t.type;return"subtitle"===e?ns.TIMED_TEXT:"initSegment"===t.sn?ns.INIT:"audio"===e?ns.AUDIO:"main"===e?this.hls.audioTracks.length?ns.VIDEO:ns.MUXED:void 0},e.getTopBandwidth=function(t){var e,r=0,i=this.hls;if(t===ns.AUDIO)e=i.audioTracks;else{var n=i.maxAutoLevel,a=n>-1?n+1:i.levels.length;e=i.levels.slice(0,a)}for(var s,o=g(e);!(s=o()).done;){var l=s.value;l.bitrate>r&&(r=l.bitrate)}return r>0?r:NaN},e.getBufferLength=function(t){var e=this.hls.media,r=t===ns.AUDIO?this.audioBuffer:this.videoBuffer;return r&&e?1e3*ri.bufferInfo(r,e.currentTime,this.config.maxBufferHole).len:NaN},e.createPlaylistLoader=function(){var t=this.config.pLoader,e=this.applyPlaylistData,r=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new r(t)}var i=t.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(t,r,i){e(t),this.loader.load(t,r,i)},s(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},e.createFragmentLoader=function(){var t=this.config.fLoader,e=this.applyFragmentData,r=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new r(t)}var i=t.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(t,r,i){e(t),this.loader.load(t,r,i)},s(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},t}(),Ws=function(){function t(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=w.log.bind(w,"[content-steering]:"),this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(S.MANIFEST_LOADING,this.onManifestLoading,this),t.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(S.MANIFEST_PARSED,this.onManifestParsed,this),t.on(S.ERROR,this.onError,this)},e.unregisterListeners=function(){var t=this.hls;t&&(t.off(S.MANIFEST_LOADING,this.onManifestLoading,this),t.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(S.MANIFEST_PARSED,this.onManifestParsed,this),t.off(S.ERROR,this.onError,this))},e.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}},e.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},e.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},e.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},e.removeLevel=function(t){var e=this.levels;e&&(this.levels=e.filter((function(e){return e!==t})))},e.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},e.onManifestLoaded=function(t,e){var r=e.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},e.onManifestParsed=function(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks},e.onError=function(t,e){var r=e.errorAction;if((null==r?void 0:r.action)===Dr&&r.flags===_r){var i=this.levels,n=this.pathwayPriority,a=this.pathwayId;if(e.context){var s=e.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=i.reduce((function(t,e){return-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t}),[])),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a),r.resolved||w.warn("Could not resolve "+e.details+' ("'+e.error.message+'") with content-steering for Pathway: '+a+" levels: "+(i?i.length:i)+" priorities: "+JSON.stringify(n)+" penalized: "+JSON.stringify(this.penalizedPathways))}},e.filterParsedLevels=function(t){this.levels=t;var e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){var r=t[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),e=this.getLevelsForPathway(r),this.pathwayId=r}return e.length!==t.length&&this.log("Found "+e.length+"/"+t.length+' levels in Pathway "'+this.pathwayId+'"'),e},e.getLevelsForPathway=function(t){return null===this.levels?[]:this.levels.filter((function(e){return t===e.pathwayId}))},e.updatePathwayPriority=function(t){var e;this.pathwayPriority=t;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(t){i-r[t]>3e5&&delete r[t]}));for(var n=0;n0){this.log('Setting Pathway to "'+a+'"'),this.pathwayId=a,mr(e),this.hls.trigger(S.LEVELS_UPDATED,{levels:e});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=s);break}}}},e.getPathwayForGroupId=function(t,e,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;var a=e.status,s="text"!==e.responseType;if(a>=200&&a<300&&(s&&e.response||null!==e.responseText)){r.loading.end=Math.max(self.performance.now(),r.loading.first);var o=s?e.response:e.responseText,l="arraybuffer"===e.responseType?o.byteLength:o.length;if(r.loaded=r.total=l,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,o,e),!this.callbacks)return;var h={url:e.responseURL,data:o,code:a};this.callbacks.onSuccess(h,r,t,e)}else{var d=n.loadPolicy.errorRetry;Sr(d,r.retry,!1,{url:t.url,data:void 0,code:a})?this.retry(d):(w.error(a+" while loading "+t.url),this.callbacks.onError({code:a,text:e.statusText},t,e,r))}}}},e.loadtimeout=function(){if(this.config){var t=this.config.loadPolicy.timeoutRetry;if(Sr(t,this.stats.retry,!0))this.retry(t);else{var e;w.warn("timeout while loading "+(null==(e=this.context)?void 0:e.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}},e.retry=function(t){var e=this.context,r=this.stats;this.retryDelay=Er(t,r.retry),r.retry++,w.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==e?void 0:e.url)+", retrying "+r.retry+"/"+t.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&Xs.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},e.getResponseHeader=function(t){return this.loader&&new RegExp("^"+t+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null},t}(),Qs=/(\d+)-(\d+)\/(\d+)/,Js=function(){function t(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||$s,this.controller=new self.AbortController,this.stats=new M}var e=t.prototype;return e.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},e.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},e.abort=function(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function(t,e,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var a=function(t,e){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(o({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}(t,this.controller.signal),s=r.onProgress,l="arraybuffer"===t.responseType,u=l?"byteLength":"length",h=e.loadPolicy,d=h.maxTimeToFirstByteMs,c=h.maxLoadTimeMs;this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,a),self.clearTimeout(this.requestTimeout),e.timeout=d&&y(d)?d:c,this.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,t,i.response)}),e.timeout),self.fetch(this.request).then((function(a){i.response=i.loader=a;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(i.requestTimeout),e.timeout=c,i.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,t,i.response)}),c-(o-n.loading.start)),!a.ok){var u=a.status,h=a.statusText;throw new to(h||"fetch, bad network response",u,a)}return n.loading.first=o,n.total=function(t){var e=t.get("Content-Range");if(e){var r=function(t){var e=Qs.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(y(r))return r}var i=t.get("Content-Length");if(i)return parseInt(i)}(a.headers)||n.total,s&&y(e.highWaterMark)?i.loadProgressively(a,n,t,e.highWaterMark,s):l?a.arrayBuffer():"json"===t.responseType?a.json():a.text()})).then((function(a){var o=i.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var l=a[u];l&&(n.loaded=n.total=l);var h={url:o.url,data:a,code:o.status};s&&!y(e.highWaterMark)&&s(n,t,a,o),r.onSuccess(h,n,t,o)})).catch((function(e){if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=e&&e.code||0,s=e?e.message:null;r.onError({code:a,text:s},t,e?e.details:null,n)}}))},e.getCacheAge=function(){var t=null;if(this.response){var e=this.response.headers.get("age");t=e?parseFloat(e):null}return t},e.getResponseHeader=function(t){return this.response?this.response.headers.get(t):null},e.loadProgressively=function(t,e,r,i,n){void 0===i&&(i=0);var a=new xi,s=t.body.getReader();return function o(){return s.read().then((function(s){if(s.done)return a.dataLength&&n(e,r,a.flush(),t),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return e.loaded+=u,u=i&&n(e,r,a.flush(),t)):n(e,r,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function $s(t,e){return new self.Request(t.url,e)}var Zs,to=function(t){function e(e,r,i){var n;return(n=t.call(this,e)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return l(e,t),e}(c(Error)),eo=/\s/,ro=i(i({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:zs,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:jr,bufferController:na,capLevelController:ts,errorController:Pr,fpsController:es,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ot,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:{newCue:function(t,e,r,i){for(var n,a,s,o,l,u=[],h=self.VTTCue||self.TextTrackCue,d=0;d=16?o--:o++;var g=Pa(l.trim()),v=Ua(e,r,g);null!=t&&null!=(c=t.cues)&&c.getCueById(v)||((a=new h(e,r,g)).id=v,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return t&&u.length&&(u.sort((function(t,e){return"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line})),u.forEach((function(e){return Ke(t,e)}))),u}},enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:Zn,subtitleTrackController:ea,timelineController:Ja,audioStreamController:Jn,audioTrackController:$n,emeController:is,cmcdController:Ys,contentSteeringController:Ws});function io(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(io):Object.keys(t).reduce((function(e,r){return e[r]=io(t[r]),e}),{}):t}function no(t){var e=t.loader;e!==Js&&e!==zs?(w.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=Js,t.progressive=!0,t.enableSoftwareAES=!0,w.log("[config]: Progressive streaming enabled, using FetchLoader"))}var ao=function(t){function e(e,r){var i;return(i=t.call(this,e,"[level-controller]")||this)._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}l(e,t);var r=e.prototype;return r._registerListeners=function(){var t=this.hls;t.on(S.MANIFEST_LOADING,this.onManifestLoading,this),t.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(S.LEVEL_LOADED,this.onLevelLoaded,this),t.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(S.FRAG_BUFFERED,this.onFragBuffered,this),t.on(S.ERROR,this.onError,this)},r._unregisterListeners=function(){var t=this.hls;t.off(S.MANIFEST_LOADING,this.onManifestLoading,this),t.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(S.LEVEL_LOADED,this.onLevelLoaded,this),t.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(S.FRAG_BUFFERED,this.onFragBuffered,this),t.off(S.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),t.prototype.destroy.call(this)},r.stopLoad=function(){this._levels.forEach((function(t){t.loadError=0,t.fragmentError=0})),t.prototype.stopLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},r.onManifestLoading=function(t,e){this.resetLevels()},r.onManifestLoaded=function(t,e){var r=this.hls.config.preferManagedMediaSource,i=[],n={},a={},s=!1,o=!1,l=!1;e.levels.forEach((function(t){var e,u,h=t.attrs,d=t.audioCodec,c=t.videoCodec;-1!==(null==(e=d)?void 0:e.indexOf("mp4a.40.34"))&&(Zs||(Zs=/chrome|firefox/i.test(navigator.userAgent)),Zs&&(t.audioCodec=d=void 0)),d&&(t.audioCodec=d=ve(d,r)),0===(null==(u=c)?void 0:u.indexOf("avc1"))&&(c=t.videoCodec=function(t){for(var e=t.split(","),r=0;r2){var n=i.shift()+".";n+=parseInt(i.shift()).toString(16),n+=("000"+parseInt(i.shift()).toString(16)).slice(-4),e[r]=n}}return e.join(",")}(c));var f=t.width,g=t.height,v=t.unknownCodecs;if(s||(s=!(!f||!g)),o||(o=!!c),l||(l=!!d),!(null!=v&&v.length||d&&!le(d,"audio",r)||c&&!le(c,"video",r))){var m=h.CODECS,p=h["FRAME-RATE"],y=h["HDCP-LEVEL"],E=h["PATHWAY-ID"],T=h.RESOLUTION,S=h["VIDEO-RANGE"],L=(E||".")+"-"+t.bitrate+"-"+T+"-"+p+"-"+m+"-"+S+"-"+y;if(n[L])if(n[L].uri===t.url||t.attrs["PATHWAY-ID"])n[L].addGroupId("audio",h.AUDIO),n[L].addGroupId("text",h.SUBTITLES);else{var A=a[L]+=1;t.attrs["PATHWAY-ID"]=new Array(A+1).join(".");var R=new or(t);n[L]=R,i.push(R)}else{var b=new or(t);n[L]=b,a[L]=1,i.push(b)}}})),this.filterAndSortMediaOptions(i,e,s,o,l)},r.filterAndSortMediaOptions=function(t,e,r,i,n){var a=this,s=[],o=[],l=t;if((r||i)&&n&&(l=l.filter((function(t){var e,r=t.videoCodec,i=t.videoRange,n=t.width,a=t.height;return(!!r||!(!n||!a))&&!!(e=i)&&er.indexOf(e)>-1}))),0!==l.length){if(e.audioTracks){var u=this.hls.config.preferManagedMediaSource;so(s=e.audioTracks.filter((function(t){return!t.audioCodec||le(t.audioCodec,"audio",u)})))}e.subtitles&&so(o=e.subtitles);var h=l.slice(0);l.sort((function(t,e){if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return er.indexOf(t.videoRange)-er.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){var i=de(t.videoCodec),n=de(e.videoCodec);if(i!==n)return n-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){var a=ce(t.codecSet),s=ce(e.codecSet);if(a!==s)return s-a}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));var d=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==h.length)for(var c=0;cm&&m===ro.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=p)}break}var y=n&&!i,E={levels:l,audioTracks:s,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:n,video:i,altAudio:!y&&s.some((function(t){return!!t.url}))};this.hls.trigger(S.MANIFEST_PARSED,E),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}else Promise.resolve().then((function(){if(a.hls){e.levels.length&&a.warn("One or more CODECS in variant not supported: "+JSON.stringify(e.levels[0].attrs));var t=new Error("no level with compatible codecs found in manifest");a.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}))},r.onError=function(t,e){!e.fatal&&e.context&&e.context.type===_e&&e.context.level===this.level&&this.checkRetry(e)},r.onFragBuffered=function(t,e){var r=e.frag;if(void 0!==r&&r.type===Fe){var i=r.elementaryStreams;if(!Object.keys(i).some((function(t){return!!i[t]})))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of "+n.loadError+" on frag buffered"),n.loadError=0)}},r.onLevelLoaded=function(t,e){var r,i,n=e.level,a=e.details,s=this._levels[n];if(!s)return this.warn("Invalid level index "+n),void(null!=(i=e.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));n===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0),this.playlistLoaded(n,e,s.details)):null!=(r=e.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)},r.loadPlaylist=function(e){t.prototype.loadPlaylist.call(this);var r=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){var n=i.uri;if(e)try{n=e.addDirectives(n)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}var a=i.attrs["PATHWAY-ID"];this.log("Loading level index "+r+(void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:"")+" with"+(a?" Pathway "+a:"")+" "+n),this.clearTimer(),this.hls.trigger(S.LEVEL_LOADING,{url:n,level:r,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}},r.removeLevel=function(t){var e,r=this,i=this._levels.filter((function(e,i){return i!==t||(r.steering&&r.steering.removeLevel(e),e===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((function(t){return t.level=-1}))),!1)}));mr(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(S.LEVELS_UPDATED,{levels:i})},r.onLevelsUpdated=function(t,e){var r=e.levels;this._levels=r},r.checkMaxAutoUpdated=function(){var t=this.hls,e=t.autoLevelCapping,r=t.maxAutoLevel,i=t.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(S.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))},s(e,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e=this._levels;if(0!==e.length){if(t<0||t>=e.length){var r=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(S.ERROR,{type:L.OTHER_ERROR,details:A.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:r,reason:r.message}),i)return;t=Math.min(t,e.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=e[t],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=o,n!==t||!o.details||!a||s!==l){this.log("Switching to level "+t+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+n+(s?" with Pathway "+s:""));var u={level:t,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(S.LEVEL_SWITCHING,u);var h=o.details;if(!h||h.live){var d=this.switchParams(o.uri,null==a?void 0:a.details,h);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}]),e}(Fr);function so(t){var e={};t.forEach((function(t){var r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++}))}var oo=function(){function t(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}var e=t.prototype;return e.abort=function(t){for(var e in this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[e].loader;if(r){var i;if(t&&t!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}},e.detach=function(){for(var t in this.keyUriToKeyInfo){var e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}},e.destroy=function(){for(var t in this.detach(),this.keyUriToKeyInfo){var e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}},e.createKeyLoadError=function(t,e,r,i,n){return void 0===e&&(e=A.KEY_LOAD_ERROR),new fi({type:L.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:n,error:r,networkDetails:i})},e.loadClear=function(t,e){var r=this;if(this.emeController&&this.config.emeEnabled)for(var i=t.sn,n=t.cc,a=function(){var t=e[s];if(n<=t.cc&&("initSegment"===i||"initSegment"===t.sn||i2,c=!h||e&&e.start<=a||h-a>2&&!this.fragmentTracker.getPartialFragment(a);if(d||c)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var f;if(!(u.len>0||h))return;var g=Math.max(h,u.start||0)-a,v=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==v||null==(f=v.details)?void 0:f.live)?2*v.details.targetduration:2,p=this.fragmentTracker.getPartialFragment(a);if(g>0&&(g<=m||p))return void(i.paused||this._trySkipBufferHole(p))}var y=self.performance.now();if(null!==n){var E=y-n;if(s||!(E>=250)||(this._reportStall(u),this.media)){var T=ri.bufferInfo(i,a,r.maxBufferHole);this._tryFixBufferStall(T,E)}}else this.stalled=y}else if(this.moved=!0,s||(this.nudgeRetry=0),null!==n){if(this.stallReported){var S=self.performance.now()-n;w.warn("playback not stuck anymore @"+a+", after "+Math.round(S)+"ms"),this.stallReported=!1}this.stalled=null}}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,n=this.media;if(null!==n){var a=n.currentTime,s=i.getPartialFragment(a);if(s&&(this._trySkipBufferHole(s)||!this.media))return;(t.len>r.maxBufferHole||t.nextStart&&t.nextStart-a1e3*r.highBufferWatchdogPeriod&&(w.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},e._reportStall=function(t){var e=this.hls,r=this.media;if(!this.stallReported&&r){this.stallReported=!0;var i=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+JSON.stringify(t)+")");w.warn(i.message),e.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len})}},e._trySkipBufferHole=function(t){var e=this.config,r=this.hls,i=this.media;if(null===i)return 0;var n=i.currentTime,a=ri.bufferInfo(i,n,0),s=n0&&a.len<1&&i.readyState<3,u=s-n;if(u>0&&(o||l)){if(u>e.maxBufferHole){var h=this.fragmentTracker,d=!1;if(0===n){var c=h.getAppendedFrag(0,Fe);c&&s1?(i=0,this.bitrateTest=!0):i=r.firstAutoLevel),r.nextLoadLevel=i,this.level=r.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=Ti,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Ei},r.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case Ci:var t=this.levels,e=this.level,r=null==t?void 0:t[e],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(i))break;this.state=Ti;break}if(this.hls.nextLoadLevel!==this.level){this.state=Ti;break}break;case Ai:var n,a=self.performance.now(),s=this.retryDate;if(!s||a>=s||null!=(n=this.media)&&n.seeking){var o=this.levels,l=this.level,u=null==o?void 0:o[l];this.resetStartWhenNotLoaded(u||null),this.state=Ti}}this.state===Ti&&this.doTickIdle(),this.onTickEnd()},r.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},r.doTickIdle=function(){var t=this.hls,e=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==e&&(i||!this.startFragRequested&&t.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=t.nextLoadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={};return this.altAudio&&(l.type="video"),this.hls.trigger(S.BUFFER_EOS,l),void(this.state=Di)}t.loadLevel!==n&&-1===t.manualLevel&&this.log("Adapting to level "+n+" from level "+this.level),this.level=t.nextLoadLevel=n;var u=a.details;if(!u||this.state===Ci||u.live&&this.levelLastLoaded!==a)return this.level=n,void(this.state=Ci);var h=s.len,d=this.getMaxBufferLength(a.maxBitrate);if(!(h>=d)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=null);var c=this.backtrackFragment?this.backtrackFragment.start:s.end,f=this.getNextFragment(c,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==Jr){var g,v=(null!=(g=this.backtrackFragment)?g:f).sn-u.startSN,m=u.fragments[v-1];m&&f.cc===m.cc&&(f=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var p=this.audioOnly&&!this.altAudio?O:N,y=(p===N?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p,Fe)}f=this.getNextFragmentLoopLoading(f,u,s,Fe,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,c))}}}}},r.loadFragment=function(e,r,i){var n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===Xr||n===Qr?"initSegment"===e.sn?this._loadInitSegment(e,r):this.bitrateTest?(this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e,r)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):this.clearTrackerIfNeeded(e)},r.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,Fe)},r.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},r.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},r.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var a=this.getMainFwdBufferInfo();if(!a||a.len<2*n.targetduration)return}if(!e.paused&&t){var s=t[this.hls.nextLoadLevel],o=this.fragLastKbps;r=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(e.currentTime+r);if(l){var u=this.followingBufferedFrag(l);if(u){this.abortCurrentFrag();var h=u.maxStartPTS?u.maxStartPTS:u.start,d=u.duration,c=Math.max(l.end,h+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},r.abortCurrentFrag=function(){var t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Si:case Li:case Ai:case bi:case ki:this.state=Ti}this.nextLoadPosition=this.getLoadPosition()},r.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},r.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new ho(this.config,i,this.fragmentTracker,this.hls)},r.onMediaDetaching=function(){var e=this.media;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},r.onMediaPlaying=function(){this.tick()},r.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;y(e)&&this.log("Media seeked to "+e.toFixed(3));var r=this.getMainFwdBufferInfo();null!==r&&0!==r.len?this.tick():this.warn('Main forward buffer length on "seeked" event '+(r?r.len:"empty")+")")},r.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(S.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1},r.onManifestParsed=function(t,e){var r,i,n=!1,a=!1;e.levels.forEach((function(t){var e=t.audioCodec;e&&(n=n||-1!==e.indexOf("mp4a.40.2"),a=a||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=n&&a&&!("function"==typeof(null==(i=lo())||null==(r=i.prototype)?void 0:r.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},r.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===Ti){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=Ci)}},r.onLevelLoaded=function(t,e){var r,i=this.levels,n=e.level,a=e.details,s=a.totalduration;if(i){this.log("Level "+n+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+", cc ["+a.startCC+", "+a.endCC+"] duration:"+s);var o=i[n],l=this.fragCurrent;!l||this.state!==Li&&this.state!==Ai||l.level!==e.level&&l.loader&&this.abortCurrentFrag();var u=0;if(a.live||null!=(r=o.details)&&r.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,o.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(o.details=a,this.levelLastLoaded=o,this.hls.trigger(S.LEVEL_UPDATED,{details:a,level:n}),this.state===Ci){if(this.waitForCdnTuneIn(a))return;this.state=Ti}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}else this.warn("Levels were reset while loading level "+n)},r._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,n=t.payload,a=this.levels;if(a){var s=a[r.level],o=s.details;if(!o)return this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset"),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,h=null==(e=r.initSegment)?void 0:e.data,d=this._getAudioCodec(s),c=this.transmuxer=this.transmuxer||new qn(this.hls,Fe,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,v=new ii(r.level,r.sn,r.stats.chunkCount,n.byteLength,f,g),m=this.initPTS[r.cc];c.push(n,h,d,l,r,i,o.totalduration,u,v,m)}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r.onAudioTrackSwitching=function(t,e){var r=this.altAudio;if(!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i&&(this.log("Switching to main audio track, cancel main fragment load"),i.abortRequests(),this.fragmentTracker.removeFragment(i)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var n=this.hls;r&&(n.trigger(S.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(S.AUDIO_TRACK_SWITCHED,e)}},r.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i,this.tick()},r.onBufferCreated=function(t,e){var r,i,n=e.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},r.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===Fe){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===ki&&(this.state=Ti));var n=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},r.onError=function(t,e){var r;if(e.fatal)this.state=Ii;else switch(e.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Fe,e);break;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ci||(null==(r=e.context)?void 0:r.type)!==_e||(this.state=Ti);break;case A.BUFFER_APPEND_ERROR:case A.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===A.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}},r.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){if(this.loadedmetadata||!ri.getBuffered(t).length){var r=this.state!==Ti?this.fragCurrent:null;e.poll(this.lastCurrentTime,r)}this.lastCurrentTime=t.currentTime}},r.onFragLoadEmergencyAborted=function(){this.state=Ti,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},r.onBufferFlushed=function(t,e){var r=e.type;if(r!==O||this.audioOnly&&!this.altAudio){var i=(r===N?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,Fe),this.tick()}},r.onLevelsUpdated=function(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var t=this.media;if(t){var e=t.currentTime,r=this.startPosition;if(r>=0&&e0&&(nT.cc;if(!1!==n.independent){var R=h.startPTS,b=h.endPTS,k=h.startDTS,D=h.endDTS;if(l)l.elementaryStreams[h.type]={startPTS:R,endPTS:b,startDTS:k,endDTS:D};else if(h.firstKeyFrame&&h.independent&&1===a.id&&!A&&(this.couldBacktrack=!0),h.dropped&&h.independent){var I=this.getMainFwdBufferInfo(),w=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,C=h.firstKeyFramePTS?h.firstKeyFramePTS:R;if(!L&&w2&&(o.gap=!0);o.setElementaryStreamInfo(h.type,R,b,k,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,a,L||A)}else{if(!L&&!A)return void this.backtrack(o);o.gap=!0}}if(v){var _=v.startPTS,x=v.endPTS,P=v.startDTS,F=v.endDTS;l&&(l.elementaryStreams[O]={startPTS:_,endPTS:x,startDTS:P,endDTS:F}),o.setElementaryStreamInfo(O,_,x,P,F),this.bufferFragmentData(v,o,l,a)}if(g&&null!=c&&null!=(e=c.samples)&&e.length){var M={id:r,frag:o,details:g,samples:c.samples};i.trigger(S.FRAG_PARSING_METADATA,M)}if(g&&d){var N={id:r,frag:o,details:g,samples:d.samples};i.trigger(S.FRAG_PARSING_USERDATA,N)}}}else this.resetWhenMissingContext(a)},r._bufferInitSegment=function(t,e,r,i){var n=this;if(this.state===bi){this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;var a=e.audio,s=e.video,o=e.audiovideo;if(a){var l=t.audioCodec,u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var h=a.metadata;h&&"channelCount"in h&&1!==(h.channelCount||1)&&-1===u.indexOf("firefox")&&(l="mp4a.40.5")}l&&-1!==l.indexOf("mp4a.40.5")&&-1!==u.indexOf("android")&&"audio/mpeg"!==a.container&&(l="mp4a.40.2",this.log("Android: force audio codec to "+l)),t.audioCodec&&t.audioCodec!==l&&this.log('Swapping manifest audio codec "'+t.audioCodec+'" for "'+l+'"'),a.levelCodec=l,a.id="main",this.log("Init audio buffer, container:"+a.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(t.audioCodec||"")+"/"+a.codec+"]")}s&&(s.levelCodec=t.videoCodec,s.id="main",this.log("Init video buffer, container:"+s.container+", codecs[level/parsed]=["+(t.videoCodec||"")+"/"+s.codec+"]")),o&&this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+t.codecs+"/"+o.codec+"]"),this.hls.trigger(S.BUFFER_CODECS,e),Object.keys(e).forEach((function(t){var a=e[t].initSegment;null!=a&&a.byteLength&&n.hls.trigger(S.BUFFER_APPENDING,{type:t,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})})),this.tickImmediate()}},r.getMainFwdBufferInfo=function(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Fe)},r.backtrack=function(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Ti},r.checkFragmentChanged=function(){var t=this.media,e=null;if(t&&t.readyState>1&&!1===t.seeking){var r=t.currentTime;if(ri.isBuffered(t,r)?e=this.getAppendedFrag(r):ri.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){this.backtrackFragment=null;var i=this.fragPlaying,n=e.level;i&&e.sn===i.sn&&i.level===n||(this.fragPlaying=e,this.hls.trigger(S.FRAG_CHANGED,{frag:e}),i&&i.level===n||this.hls.trigger(S.LEVEL_SWITCHED,{level:n}))}}},s(e,[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentFrag",get:function(){var t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}},{key:"currentProgramDateTime",get:function(){var t=this.media;if(t){var e=t.currentTime,r=this.currentFrag;if(r&&y(e)&&y(r.programDateTime)){var i=r.programDateTime+1e3*(e-r.start);return new Date(i)}}return null}},{key:"currentLevel",get:function(){var t=this.currentFrag;return t?t.level:-1}},{key:"nextBufferedFrag",get:function(){var t=this.currentFrag;return t?this.followingBufferedFrag(t):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}]),e}(_i),fo=function(){function t(e){void 0===e&&(e={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Vn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,I(e.debug||!1,"Hls instance");var r=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=io(t),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(t){var i=("level"===t?"playlist":t)+"LoadPolicy",a=void 0===e[i],s=[];n.forEach((function(n){var o=t+"Loading"+n,l=e[o];if(void 0!==l&&a){s.push(o);var u=r[i].default;switch(e[i]={default:u},n){case"TimeOut":u.maxLoadTimeMs=l,u.maxTimeToFirstByteMs=l;break;case"MaxRetry":u.errorRetry.maxNumRetry=l,u.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":u.errorRetry.retryDelayMs=l,u.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=l,u.timeoutRetry.maxRetryDelayMs=l}}})),s.length&&w.warn('hls.js config: "'+s.join('", "')+'" setting(s) are deprecated, use "'+i+'": '+JSON.stringify(e[i]))})),i(i({},r),e)}(t.DefaultConfig,e);this.userConfig=e,r.progressive&&no(r);var n=r.abrController,a=r.bufferController,s=r.capLevelController,o=r.errorController,l=r.fpsController,u=new o(this),h=this.abrController=new n(this),d=this.bufferController=new a(this),c=this.capLevelController=new s(this),f=new l(this),g=new Be(this),v=new $e(this),m=r.contentSteeringController,p=m?new m(this):null,y=this.levelController=new ao(this,p),E=new $r(this),T=new oo(this.config),L=this.streamController=new co(this,E,T);c.setStreamController(L),f.setStreamController(L);var A=[g,y,L];p&&A.splice(1,0,p),this.networkControllers=A;var R=[h,d,c,f,v,E];this.audioTrackController=this.createController(r.audioTrackController,A);var b=r.audioStreamController;b&&A.push(new b(this,E,T)),this.subtitleTrackController=this.createController(r.subtitleTrackController,A);var k=r.subtitleStreamController;k&&A.push(new k(this,E,T)),this.createController(r.timelineController,R),T.emeController=this.emeController=this.createController(r.emeController,R),this.cmcdController=this.createController(r.cmcdController,R),this.latencyController=this.createController(Ze,R),this.coreComponents=R,A.push(u);var D=u.onErrorOut;"function"==typeof D&&this.on(S.ERROR,D,u)}t.isMSESupported=function(){return uo()},t.isSupported=function(){return function(){if(!uo())return!1;var t=se();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(e){return t.isTypeSupported(he(e,"video"))}))||["mp4a.40.2","fLaC"].some((function(e){return t.isTypeSupported(he(e,"audio"))})))}()},t.getMediaSource=function(){return se()};var e=t.prototype;return e.createController=function(t,e){if(t){var r=new t(this);return e&&e.push(r),r}return null},e.on=function(t,e,r){void 0===r&&(r=this),this._emitter.on(t,e,r)},e.once=function(t,e,r){void 0===r&&(r=this),this._emitter.once(t,e,r)},e.removeAllListeners=function(t){this._emitter.removeAllListeners(t)},e.off=function(t,e,r,i){void 0===r&&(r=this),this._emitter.off(t,e,r,i)},e.listeners=function(t){return this._emitter.listeners(t)},e.emit=function(t,e,r){return this._emitter.emit(t,e,r)},e.trigger=function(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(w.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;var r=t===S.ERROR;this.trigger(S.ERROR,{type:L.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:r,event:t,error:e}),this.triggeringException=!1}}return!1},e.listenerCount=function(t){return this._emitter.listenerCount(t)},e.destroy=function(){w.log("destroy"),this.trigger(S.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((function(t){return t.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(t){return t.destroy()})),this.coreComponents.length=0;var t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null},e.attachMedia=function(t){w.log("attachMedia"),this._media=t,this.trigger(S.MEDIA_ATTACHING,{media:t})},e.detachMedia=function(){w.log("detachMedia"),this.trigger(S.MEDIA_DETACHING,void 0),this._media=null},e.loadSource=function(t){this.stopLoad();var e=this.media,r=this.url,i=this.url=p.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,w.log("loadSource:"+i),e&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(S.MANIFEST_LOADING,{url:t})},e.startLoad=function(t){void 0===t&&(t=-1),w.log("startLoad("+t+")"),this.started=!0,this.networkControllers.forEach((function(e){e.startLoad(t)}))},e.stopLoad=function(){w.log("stopLoad"),this.started=!1,this.networkControllers.forEach((function(t){t.stopLoad()}))},e.resumeBuffering=function(){this.started&&this.networkControllers.forEach((function(t){"fragmentLoader"in t&&t.startLoad(-1)}))},e.pauseBuffering=function(){this.networkControllers.forEach((function(t){"fragmentLoader"in t&&t.stopLoad()}))},e.swapAudioCodec=function(){w.log("swapAudioCodec"),this.streamController.swapAudioCodec()},e.recoverMediaError=function(){w.log("recoverMediaError");var t=this._media;this.detachMedia(),t&&this.attachMedia(t)},e.removeLevel=function(t){this.levelController.removeLevel(t)},e.setAudioOption=function(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)},e.setSubtitleOption=function(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null},s(t,[{key:"levels",get:function(){var t=this.levelController.levels;return t||[]}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){w.log("set currentLevel:"+t),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){w.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){w.log("set loadLevel:"+t),this.levelController.manualLevel=t}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(t){this.levelController.nextLoadLevel=t}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(t){w.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){var t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t},set:function(t){w.log("set startLevel:"+t),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(t){var e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(t){this._autoLevelCapping!==t&&(w.log("set autoLevelCapping:"+t),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimate():NaN},set:function(t){this.abrController.resetEstimator(t)}},{key:"ttfbEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(t){(function(t){return tr.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var t=this.levels,e=this.config.minAutoBitrate;if(!t)return 0;for(var r=t.length,i=0;i=e)return i;return 0}},{key:"maxAutoLevel",get:function(){var t,e=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(t=-1===r&&null!=e&&e.length?e.length-1:r,i)for(var n=t;n--;){var a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return t}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(t){this.abrController.nextAutoLevel=t}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"allAudioTracks",get:function(){var t=this.audioTrackController;return t?t.allAudioTracks:[]}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"allSubtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}],[{key:"version",get:function(){return"1.5.17"}},{key:"Events",get:function(){return S}},{key:"ErrorTypes",get:function(){return L}},{key:"ErrorDetails",get:function(){return A}},{key:"DefaultConfig",get:function(){return t.defaultConfig?t.defaultConfig:ro},set:function(e){t.defaultConfig=e}}]),t}();return fo.defaultConfig=void 0,fo},"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(r="undefined"!=typeof globalThis?globalThis:r||self).Hls=i()}(!1); +//# sourceMappingURL=hls.min.js.map diff --git a/apps/streamd/internal/ui/ui.go b/apps/streamd/internal/ui/ui.go index 0fcaf03..1951cdd 100644 --- a/apps/streamd/internal/ui/ui.go +++ b/apps/streamd/internal/ui/ui.go @@ -1,14 +1,20 @@ +// Package ui serves the embedded dashboard: one HTML shell plus ES modules +// and a vendored copy of hls.js. There is no build step, which is why the +// JavaScript is plain modules rather than a bundle. package ui import ( "embed" "io/fs" "net/http" + "strings" ) -//go:embed index.html app.css app.js +//go:embed index.html all:static var files embed.FS +// Handler serves the single-page shell for every non-asset path, so the hash +// router can own navigation. func Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" && r.URL.Path != "/index.html" { @@ -17,18 +23,37 @@ func Handler() http.Handler { } b, err := files.ReadFile("index.html") if err != nil { - http.Error(w, err.Error(), 500) + http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") + // The shell references hashed-by-content assets only loosely, so keep + // it uncached to avoid serving a stale page against new modules. + w.Header().Set("Cache-Control", "no-cache") _, _ = w.Write(b) }) } +// Static serves the dashboard assets. Directory listings are refused: the +// asset tree is not interesting, and an index is one more thing to leak. func Static() http.Handler { - sub, err := fs.Sub(files, ".") + sub, err := fs.Sub(files, "static") if err != nil { panic(err) } - return http.FileServer(http.FS(sub)) + fileServer := http.FileServer(http.FS(sub)) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "" || r.URL.Path == "/" || strings.HasSuffix(r.URL.Path, "/") { + http.NotFound(w, r) + return + } + // The vendored library is immutable for a given version; the rest is + // revalidated so an updated build is picked up on reload. + if strings.HasPrefix(r.URL.Path, "/vendor/") { + w.Header().Set("Cache-Control", "public, max-age=86400") + } else { + w.Header().Set("Cache-Control", "no-cache") + } + fileServer.ServeHTTP(w, r) + }) } diff --git a/apps/streamd/internal/ws/hub.go b/apps/streamd/internal/ws/hub.go index 1bec51f..9e4fabc 100644 --- a/apps/streamd/internal/ws/hub.go +++ b/apps/streamd/internal/ws/hub.go @@ -2,7 +2,7 @@ package ws import ( "encoding/json" - "log" + "log/slog" "net/http" "strings" "sync" @@ -10,6 +10,7 @@ import ( "github.com/gorilla/websocket" + "drmdecryption/apps/streamd/internal/auth" "drmdecryption/apps/streamd/internal/db" ) @@ -19,21 +20,26 @@ const ( claimRenewTTL = 90 * time.Second writeWait = 10 * time.Second pongWait = 60 * time.Second + // captureDebounce stops a flapping stream from spamming every agent with + // the same request. One push per stream per window is plenty. + captureDebounce = 30 * time.Second ) -var upgrader = websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { return true }, -} - // Hub tracks agent WebSocket sessions and UI listeners. type Hub struct { Store *db.Store - Token string - Log *log.Logger + Log *slog.Logger + // AllowedOrigins are extra origins permitted to open a socket, beyond the + // server's own. Empty means same-origin only. + AllowedOrigins []string mu sync.Mutex agents map[string]*agentConn // agent_id -> conn uis map[*websocket.Conn]struct{} + // lastCapture debounces capture pushes per stream id. + lastCapture map[int64]time.Time + + upgrader websocket.Upgrader } type agentConn struct { @@ -55,19 +61,70 @@ type outbound struct { Error string `json:"error,omitempty"` Agents []any `json:"agents,omitempty"` Message string `json:"message,omitempty"` + + // Capture request fields. The agent needs enough to enqueue a job without + // a round trip, and deliberately never receives the credentials. + StreamID int64 `json:"stream_id,omitempty"` + StreamName string `json:"stream_name,omitempty"` + App string `json:"app,omitempty"` + Channel string `json:"channel,omitempty"` + Reason string `json:"reason,omitempty"` } -func NewHub(store *db.Store, token string, lg *log.Logger) *Hub { +func NewHub(store *db.Store, lg *slog.Logger, allowedOrigins []string) *Hub { if lg == nil { - lg = log.Default() + lg = slog.Default() } - return &Hub{ - Store: store, - Token: token, - Log: lg, - agents: map[string]*agentConn{}, - uis: map[*websocket.Conn]struct{}{}, + h := &Hub{ + Store: store, + Log: lg, + AllowedOrigins: allowedOrigins, + agents: map[string]*agentConn{}, + uis: map[*websocket.Conn]struct{}{}, + lastCapture: map[int64]time.Time{}, } + // A WebSocket handshake is not subject to the same-origin policy, so + // without this check any page on the internet could open /ws/ui against a + // logged-in operator's browser and read the event stream. + h.upgrader = websocket.Upgrader{CheckOrigin: h.checkOrigin} + return h +} + +func (h *Hub) checkOrigin(r *http.Request) bool { + origin := strings.TrimSpace(r.Header.Get("Origin")) + if origin == "" { + // Non-browser clients (the agent) send no Origin. They are + // authenticated by bearer token instead. + return true + } + host := strings.ToLower(hostOnly(origin)) + if host != "" && host == strings.ToLower(hostOnly("//"+r.Host)) { + return true + } + for _, allowed := range h.AllowedOrigins { + allowed = strings.TrimRight(strings.TrimSpace(allowed), "/") + if allowed == "" { + continue + } + if allowed == "*" || strings.EqualFold(allowed, strings.TrimRight(origin, "/")) { + return true + } + } + h.Log.Warn("ws: rejected cross-origin handshake", "origin", origin, "host", r.Host) + return false +} + +// hostOnly extracts host[:port] from an origin or //host form. +func hostOnly(u string) string { + if i := strings.Index(u, "://"); i >= 0 { + u = u[i+3:] + } else { + u = strings.TrimPrefix(u, "//") + } + if i := strings.IndexAny(u, "/?#"); i >= 0 { + u = u[:i] + } + return u } func (h *Hub) Mount(mux *http.ServeMux) { @@ -93,9 +150,9 @@ func (h *Hub) RunExpireLoop(stop <-chan struct{}) { func (h *Hub) tick() { n, err := h.Store.ExpireClaims() if err != nil { - h.Log.Printf("ws: expire claims: %v", err) + h.Log.Error("ws: expire claims", "err", err) } else if n > 0 { - h.Log.Printf("ws: expired %d stale claim(s)", n) + h.Log.Info("ws: expired stale claims", "count", n) h.broadcastUI(outbound{Type: "claims_changed", Message: "expired"}) } @@ -109,36 +166,29 @@ func (h *Hub) tick() { } h.mu.Unlock() for _, id := range stale { - h.Log.Printf("ws: agent %s heartbeat stale — releasing claims", id) + h.Log.Warn("ws: agent heartbeat stale — releasing claims", "agent", id) h.dropAgent(id, true) } } -func (h *Hub) authToken(r *http.Request) bool { - if h.Token == "" { - return true - } - tok := r.URL.Query().Get("token") - if tok == "" { - auth := r.Header.Get("Authorization") - tok = strings.TrimPrefix(auth, "Bearer ") - } - if tok == "" { - tok = r.Header.Get("X-Streamd-Token") - } - return tok == h.Token -} - func (h *Hub) handleAgentsAPI(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed) return } + if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { + return + } writeJSON(w, map[string]any{"agents": h.snapshotAgents()}) } +// handleUI serves the dashboard's event stream. It now requires a principal: +// it previously had no authentication at all. func (h *Hub) handleUI(w http.ResponseWriter, r *http.Request) { - conn, err := upgrader.Upgrade(w, r, nil) + if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { + return + } + conn, err := h.upgrader.Upgrade(w, r, nil) if err != nil { return } @@ -159,24 +209,51 @@ func (h *Hub) handleUI(w http.ResponseWriter, r *http.Request) { }) // Push initial agent list. h.sendJSON(conn, outbound{Type: "agents", Agents: h.snapshotAgents()}) + + // Keep the socket alive from this side too, so an idle dashboard behind a + // proxy with an idle timeout is not disconnected every minute. + stop := make(chan struct{}) + defer close(stop) + go func() { + t := time.NewTicker(agentHeartbeatEvery) + defer t.Stop() + for { + select { + case <-stop: + return + case <-t.C: + _ = conn.SetWriteDeadline(time.Now().Add(writeWait)) + if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeWait)); err != nil { + return + } + } + } + }() + for { if _, _, err := conn.ReadMessage(); err != nil { return } + _ = conn.SetReadDeadline(time.Now().Add(pongWait)) } } func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) { - if !h.authToken(r) { - http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized) + // Agents authenticate with a bearer API key. The ?token= query form is + // gone: it leaked the secret into proxy logs. + p, ok := auth.Guard(w, r, auth.RoleOperator) + if !ok { return } agentID := strings.TrimSpace(r.URL.Query().Get("agent_id")) + if agentID == "" { + agentID = p.AgentID + } if agentID == "" { http.Error(w, `{"error":"agent_id required"}`, http.StatusBadRequest) return } - conn, err := upgrader.Upgrade(w, r, nil) + conn, err := h.upgrader.Upgrade(w, r, nil) if err != nil { return } @@ -184,7 +261,7 @@ func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) { conn: conn, agentID: agentID, lastSeen: time.Now().UTC(), - send: make(chan []byte, 8), + send: make(chan []byte, 16), } h.mu.Lock() if old, ok := h.agents[agentID]; ok { @@ -193,7 +270,7 @@ func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) { } h.agents[agentID] = ac h.mu.Unlock() - h.Log.Printf("ws: agent connected id=%s", agentID) + h.Log.Info("ws: agent connected", "agent", agentID, "key", p.Name) h.broadcastUI(outbound{Type: "agent_online", AgentID: agentID, Agents: h.snapshotAgents()}) go h.agentWriter(ac) @@ -263,12 +340,12 @@ func (h *Hub) dropAgent(agentID string, releaseClaims bool) { if releaseClaims { n, err := h.Store.ReleaseAgentClaims(agentID) if err != nil { - h.Log.Printf("ws: release claims for %s: %v", agentID, err) + h.Log.Error("ws: release claims", "agent", agentID, "err", err) } else if n > 0 { - h.Log.Printf("ws: released %d claim(s) for disconnected agent %s", n, agentID) + h.Log.Info("ws: released claims for disconnected agent", "agent", agentID, "count", n) } } - h.Log.Printf("ws: agent disconnected id=%s", agentID) + h.Log.Info("ws: agent disconnected", "agent", agentID) h.broadcastUI(outbound{Type: "agent_offline", AgentID: agentID, Agents: h.snapshotAgents()}) } @@ -299,12 +376,80 @@ func (h *Hub) queue(ac *agentConn, msg outbound) { if err != nil { return } + // Never block the caller on a wedged agent: dropping a heartbeat ack is + // harmless, and a capture request will be retried on the next poll. select { case ac.send <- b: default: } } +// RequestCapture asks every connected agent to refresh this stream's +// credentials now. Returns how many agents were notified. +// +// This is what makes an on-demand wake and a scheduled pre-roll responsive: +// without it the agent would not notice until its next poll, up to 30s later, +// with a viewer already waiting. +func (h *Hub) RequestCapture(st db.Stream, reason string) int { + h.mu.Lock() + if last, ok := h.lastCapture[st.ID]; ok && time.Since(last) < captureDebounce { + h.mu.Unlock() + return 0 + } + h.lastCapture[st.ID] = time.Now() + // Keep the debounce map from growing with deleted streams. + if len(h.lastCapture) > 1000 { + for id, t := range h.lastCapture { + if time.Since(t) > 10*time.Minute { + delete(h.lastCapture, id) + } + } + } + conns := make([]*agentConn, 0, len(h.agents)) + for _, a := range h.agents { + conns = append(conns, a) + } + h.mu.Unlock() + + if len(conns) == 0 { + return 0 + } + msg := outbound{ + Type: "capture_requested", + StreamID: st.ID, + StreamName: st.Name, + App: st.App, + Channel: st.Channel, + Reason: reason, + } + for _, ac := range conns { + h.queue(ac, msg) + } + h.Log.Info("ws: capture requested", "stream", st.Name, "reason", reason, "agents", len(conns)) + return len(conns) +} + +// NotifyStreamChanged tells the dashboard to refresh, and nudges agents to +// re-poll rather than wait out their interval. +func (h *Hub) NotifyStreamChanged(name, reason string) { + h.broadcastUI(outbound{Type: "streams_changed", StreamName: name, Reason: reason}) + h.mu.Lock() + conns := make([]*agentConn, 0, len(h.agents)) + for _, a := range h.agents { + conns = append(conns, a) + } + h.mu.Unlock() + for _, ac := range conns { + h.queue(ac, outbound{Type: "stream_changed", StreamName: name, Reason: reason}) + } +} + +// NotifyRuntime pushes a live health delta to the dashboard, so it does not +// have to poll the whole stream list on a timer. +func (h *Hub) NotifyRuntime(name, health string) { + h.broadcastUI(outbound{Type: "runtime", StreamName: name, Message: health}) +} + func (h *Hub) sendJSON(conn *websocket.Conn, msg outbound) { b, _ := json.Marshal(msg) _ = conn.SetWriteDeadline(time.Now().Add(writeWait)) diff --git a/apps/streamd/servecmd/servecmd.go b/apps/streamd/servecmd/servecmd.go index d73c2ea..63bcf3b 100644 --- a/apps/streamd/servecmd/servecmd.go +++ b/apps/streamd/servecmd/servecmd.go @@ -5,10 +5,10 @@ package servecmd import ( "flag" "fmt" - "log" + "log/slog" + "net" "net/http" "os" - "os/exec" "os/signal" "path/filepath" "strings" @@ -16,9 +16,14 @@ import ( "time" "drmdecryption/apps/streamd/internal/api" + "drmdecryption/apps/streamd/internal/auth" "drmdecryption/apps/streamd/internal/db" "drmdecryption/apps/streamd/internal/deps" + "drmdecryption/apps/streamd/internal/hlsgate" + "drmdecryption/apps/streamd/internal/httpx" + "drmdecryption/apps/streamd/internal/scheduler" "drmdecryption/apps/streamd/internal/supervisor" + "drmdecryption/apps/streamd/internal/tsfanout" "drmdecryption/apps/streamd/internal/ui" "drmdecryption/apps/streamd/internal/ws" ) @@ -52,29 +57,73 @@ Usage: streamd serve [flags] serve flags: - --bind listen address (default 0.0.0.0:8083) - --data data dir for sqlite + www + work (default .cache/streamd) - --token shared bearer token for mutating API (or STREAMD_TOKEN) - --nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download) - --ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download) - --mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download) - --bin-dir where to install/look for media tools (default /bin) - --skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt + --bind listen address (default 127.0.0.1:8083) + --data data dir for sqlite + www + work (default .cache/streamd) + --nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download) + --ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download) + --mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download) + --bin-dir where to install/look for media tools (default /bin) + --skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt + --log-level debug | info | warn | error (default info) + +access control: + --admin-user create this admin account on first run (with --admin-pass) + --admin-pass password for --admin-user (prefer STREAMD_ADMIN_PASS) + --token legacy shared bearer token, treated as an admin API key + (or STREAMD_TOKEN). Prefer per-agent keys in the dashboard. + --session-ttl how long a login lasts without activity (default 12h) + --trusted-proxies CIDRs allowed to set X-Forwarded-For/-Proto (e.g. 127.0.0.1/32) + --allowed-origins extra CORS origins, comma separated (default same-origin only) + --cookie-secure always mark cookies Secure (set this behind a TLS proxy) + --audit-retain how long to keep audit rows (default 2160h / 90d) + +on-demand and scheduling: + --ondemand-wait hold a viewer request this long while a stream starts + --ondemand-capture-wait as above, when credentials must be captured first + --schedule-preroll refresh credentials this far before a scheduled start + --ts-fanout-buffer live MPEG-TS bytes buffered per stream for /live/ + +Bind defaults to 127.0.0.1 — put a TLS-terminating reverse proxy in front and +set --trusted-proxies to that proxy. Use --bind 0.0.0.0:8083 only deliberately. `) } func serveCmd(args []string) { fs := flag.NewFlagSet("serve", flag.ExitOnError) - bind := fs.String("bind", "0.0.0.0:8083", "listen address") + // Loopback by default. This used to be 0.0.0.0, which published the API — + // and before redaction, the Widevine keys — to the whole network. + bind := fs.String("bind", "127.0.0.1:8083", "listen address") data := fs.String("data", "", "data directory (sqlite, www, work, logs)") - token := fs.String("token", "", "API bearer token (default: STREAMD_TOKEN env)") + token := fs.String("token", "", "legacy admin API token (default: STREAMD_TOKEN env)") nre := fs.String("nre", "", "N_m3u8DL-RE binary") ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary") mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary") binDir := fs.String("bin-dir", "", "directory for media tool binaries (default /bin)") skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools") + logLevel := fs.String("log-level", "info", "debug | info | warn | error") + adminUser := fs.String("admin-user", "", "create this admin account on first run") + adminPass := fs.String("admin-pass", "", "password for --admin-user (or STREAMD_ADMIN_PASS)") + sessionTTL := fs.Duration("session-ttl", auth.DefaultSessionTTL, "login lifetime without activity") + trustedProxies := fs.String("trusted-proxies", "", "CIDRs allowed to set X-Forwarded-For") + allowedOrigins := fs.String("allowed-origins", "", "extra CORS origins, comma separated") + cookieSecure := fs.Bool("cookie-secure", false, "always mark cookies Secure") + auditRetain := fs.Duration("audit-retain", 90*24*time.Hour, "how long to keep audit rows") + tsBuffer := fs.Int("ts-fanout-buffer", tsfanout.DefaultBufferBytes, + "bytes of live MPEG-TS buffered per stream for /live/.ts") + ondemandWait := fs.Duration("ondemand-wait", hlsgate.DefaultWait, + "how long to hold a viewer request while an on-demand stream starts") + ondemandCaptureWait := fs.Duration("ondemand-capture-wait", hlsgate.DefaultCaptureWait, + "as --ondemand-wait, but when credentials must be captured first") + preroll := fs.Duration("schedule-preroll", scheduler.DefaultPreroll, + "how far ahead of a scheduled start to refresh credentials") _ = fs.Parse(args) + lg := newLogger(*logLevel) + slog.SetDefault(lg) + // deps still wants a *log.Logger; bridge it onto the same handler so one + // stream of output stays coherent. + depsLog := slog.NewLogLogger(lg.Handler(), slog.LevelInfo) + dataDir := *data if dataDir == "" { dataDir = filepath.Join(".", ".cache", "streamd") @@ -84,159 +133,255 @@ func serveCmd(args []string) { tok = os.Getenv("STREAMD_TOKEN") } + trust := httpx.Trust{} + if nets, err := httpx.ParseCIDRs(*trustedProxies); err != nil { + lg.Error("invalid --trusted-proxies", "err", err) + os.Exit(2) + } else { + trust.Proxies = nets + } + origins := splitList(*allowedOrigins) + for _, sub := range []string{"www", "work", "logs"} { if err := os.MkdirAll(filepath.Join(dataDir, sub), 0o755); err != nil { - log.Fatal(err) + lg.Error("create data dir", "err", err) + os.Exit(1) } } store, err := db.Open(dataDir) if err != nil { - log.Fatalf("db: %v", err) + lg.Error("open database", "err", err) + os.Exit(1) } defer store.Close() + authStore, err := auth.New(store.DB, tok) + if err != nil { + lg.Error("init auth tables", "err", err) + os.Exit(1) + } + mw := auth.NewMiddleware(authStore, trust, *cookieSecure) + mw.SessionTTL = *sessionTTL + authH := auth.NewHandler(authStore, mw, lg) + + bootstrapAdmin(lg, authStore, authH, *adminUser, *adminPass) + depStatus, _ := deps.Ensure(deps.Options{ BinDir: *binDir, SkipDownload: *skipDeps, - Log: log.Default(), + Log: depsLog, }, *nre, *ffmpeg, *mp4decrypt) - nrePath := depStatus.NRE - ffPath := depStatus.FFmpeg - decPath := depStatus.MP4Decrypt + + fanout := tsfanout.NewSet(*tsBuffer) + hub := ws.NewHub(store, lg, origins) sup := supervisor.NewMedia(supervisor.Options{ Store: store, DataDir: dataDir, - NRE: nrePath, - FFmpeg: ffPath, - MP4Decrypt: decPath, - Log: log.Default(), + NRE: depStatus.NRE, + FFmpeg: depStatus.FFmpeg, + MP4Decrypt: depStatus.MP4Decrypt, + Log: lg, + Fanout: fanout, + Notifier: hub, }) defer sup.Close() + gate := hlsgate.New(hlsgate.Config{ + Store: store, + WWWRoot: filepath.Join(dataDir, "www"), + Sup: sup, + Fanout: fanout, + Capture: hub, + Trust: trust, + Log: lg, + Wait: *ondemandWait, + CaptureWait: *ondemandCaptureWait, + }) + // The supervisor records viewer counts in its metrics series, and the + // gate is what knows them. + sup.ViewersFn = gate.ViewersFor + + sched := scheduler.New(store, sup, hub, lg, *preroll) + apiH := &api.Handler{ Store: store, - Token: tok, + Auth: authStore, + Trust: trust, Supervisor: sup, + Capture: hub, StartedAt: time.Now(), Deps: depStatus, WWWRoot: filepath.Join(dataDir, "www"), + LogRoot: filepath.Join(dataDir, "logs"), + Notifier: hub, + Viewers: gate, + Scheduler: sched, + Log: lg, } - hub := ws.NewHub(store, tok, log.Default()) mux := http.NewServeMux() apiH.Mount(mux) + authH.Mount(mux) hub.Mount(mux) + // The media paths are served by the gate, not a bare FileServer: it wakes + // on-demand streams, counts viewers, sets cache headers per file kind and + // refuses directory listings. + gate.Mount(mux) mux.Handle("/", ui.Handler()) mux.Handle("/static/", http.StripPrefix("/static/", ui.Static())) - mux.Handle("/hls/", http.StripPrefix("/hls/", http.FileServer(http.Dir(filepath.Join(dataDir, "www"))))) + + // Order matters: the access log wraps everything so it sees final statuses, + // then CORS and security headers, then principal resolution, then the mux. + var handler http.Handler = mux + handler = mw.Attach(handler) + handler = httpx.SecurityHeaders(trust, handler) + handler = httpx.CORS(origins, handler) + handler = httpx.AccessLog(lg, trust, handler) srv := &http.Server{ Addr: *bind, - Handler: withCORS(mux), + Handler: handler, ReadHeaderTimeout: 10 * time.Second, + // No WriteTimeout: HLS responses, SSE log tails and websockets are all + // long-lived and a write deadline would cut them off. + IdleTimeout: 120 * time.Second, } - log.Printf("streamd listening on http://%s data=%s", *bind, dataDir) - log.Printf("media: nre=%s", nrePath) - log.Printf("media: ffmpeg=%s", ffPath) - log.Printf("media: mp4decrypt=%s", decPath) - log.Printf("ws: agents=/ws/agent ui=/ws/ui") - if tok == "" { - log.Printf("warning: no --token / STREAMD_TOKEN set; mutating API is open") + lg.Info("streamd listening", "addr", *bind, "data", dataDir) + lg.Info("media tools", "nre", depStatus.NRE, "ffmpeg", depStatus.FFmpeg, "mp4decrypt", depStatus.MP4Decrypt) + if len(trust.Proxies) == 0 { + lg.Info("no --trusted-proxies set: forwarded headers are ignored and client IPs come from the peer address") + } + if tok != "" { + lg.Warn("--token / STREAMD_TOKEN is in use as an admin API key; create per-agent keys in the dashboard and drop it") + } + if host, _, err := net.SplitHostPort(*bind); err == nil { + switch strings.ToLower(host) { + case "127.0.0.1", "localhost", "::1": + // Loopback is the safe default. + default: + lg.Warn("listening on a non-loopback address — the dashboard and API are reachable on the network; put a TLS reverse proxy in front, or bind 127.0.0.1", + "bind", *bind) + } } stopBG := make(chan struct{}) go hub.RunExpireLoop(stopBG) - - // Resume enabled streams that already have credentials (staggered). - go func() { - time.Sleep(500 * time.Millisecond) - list, err := store.ListStreams() - if err != nil { - return - } - for _, st := range list { - if !st.Enabled || strings.TrimSpace(st.MPD) == "" { - continue - } - mpd := strings.ToLower(strings.TrimSpace(st.MPD)) - if !strings.HasPrefix(mpd, "http://") && !strings.HasPrefix(mpd, "https://") { - log.Printf("auto-start skip %s: mpd is not an http(s) URL", st.Name) - continue - } - log.Printf("auto-start enabled stream %s", st.Name) - func(id int64, name string) { - defer func() { - if r := recover(); r != nil { - log.Printf("auto-start %s panic: %v", name, r) - } - }() - if err := sup.Start(id); err != nil { - log.Printf("auto-start %s: %v", name, err) - } - }(st.ID, st.Name) - time.Sleep(1500 * time.Millisecond) - } - }() + go authStore.RunMaintenance(stopBG, *auditRetain) + go store.RunHistoryMaintenance(stopBG) + go gate.RunIdleLoop(stopBG) + go sched.Run(stopBG) + go resumeEnabledStreams(lg, store, sup) go func() { ch := make(chan os.Signal, 1) signal.Notify(ch, os.Interrupt, syscall.SIGTERM) <-ch - log.Printf("shutting down…") + lg.Info("shutting down") close(stopBG) sup.Close() + _ = authStore.FlushAudit() _ = srv.Close() }() if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { - log.Fatal(err) + lg.Error("listen", "err", err) + os.Exit(1) } } -func withCORS(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Streamd-Token") - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") - if r.Method == http.MethodOptions { - w.WriteHeader(http.StatusNoContent) +func newLogger(level string) *slog.Logger { + var lv slog.Level + switch strings.ToLower(strings.TrimSpace(level)) { + case "debug": + lv = slog.LevelDebug + case "warn", "warning": + lv = slog.LevelWarn + case "error": + lv = slog.LevelError + default: + lv = slog.LevelInfo + } + // A text handler keeps the console output as readable as the old + // log.Printf lines while giving every record structured attributes. + return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lv})) +} + +// bootstrapAdmin creates the first account from flags when asked, or prints a +// one-time setup token so the dashboard can create it. +func bootstrapAdmin(lg *slog.Logger, store *auth.Store, h *auth.Handler, user, pass string) { + n, err := store.CountUsers() + if err != nil { + lg.Error("count users", "err", err) + return + } + if n > 0 { + h.SetSetupToken("") + return + } + if pass == "" { + pass = os.Getenv("STREAMD_ADMIN_PASS") + } + if user != "" && pass != "" { + if _, err := store.CreateUser(user, pass, auth.RoleAdmin); err != nil { + lg.Error("create admin account", "err", err) + } else { + lg.Info("created initial admin account", "user", strings.ToLower(strings.TrimSpace(user))) + h.SetSetupToken("") return } - next.ServeHTTP(w, r) - }) + } + tok := auth.NewSetupToken() + h.SetSetupToken(tok) + lg.Warn("no accounts exist yet — open the dashboard and use this one-time setup token to create the first admin", + "setup_token", tok) } -func firstExisting(explicit string, candidates ...string) string { - if explicit != "" { - if st, err := os.Stat(explicit); err == nil && !st.IsDir() { - return explicit - } - // still return explicit so exec fails clearly if user set a bad path - if filepath.IsAbs(explicit) || containsSep(explicit) { - return explicit - } +// resumeEnabledStreams restarts streams that were running before a restart. +// On-demand streams are deliberately left stopped: a viewer's first request +// starts them, which is the whole point. +func resumeEnabledStreams(lg *slog.Logger, store *db.Store, sup *supervisor.Media) { + time.Sleep(500 * time.Millisecond) + list, err := store.ListStreams() + if err != nil { + return } - for _, c := range candidates { - if c == "" { + for _, st := range list { + if !st.Enabled || strings.TrimSpace(st.MPD) == "" { continue } - if st, err := os.Stat(c); err == nil && !st.IsDir() { - return c + if st.OnDemand { + lg.Info("auto-start skipped: on-demand stream waits for a viewer", "stream", st.Name) + continue } - if p, err := execLookPath(c); err == nil { - return p + mpd := strings.ToLower(strings.TrimSpace(st.MPD)) + if !strings.HasPrefix(mpd, "http://") && !strings.HasPrefix(mpd, "https://") { + lg.Warn("auto-start skipped: mpd is not an http(s) URL", "stream", st.Name) + continue + } + lg.Info("auto-starting enabled stream", "stream", st.Name) + func(id int64, name string) { + defer func() { + if r := recover(); r != nil { + lg.Error("auto-start panicked", "stream", name, "panic", r) + } + }() + if err := sup.Start(id); err != nil { + lg.Error("auto-start failed", "stream", name, "err", err) + } + }(st.ID, st.Name) + time.Sleep(1500 * time.Millisecond) + } +} + +func splitList(s string) []string { + var out []string + for _, p := range strings.Split(s, ",") { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) } } - return explicit -} - -func containsSep(s string) bool { - return filepath.Base(s) != s -} - -func execLookPath(file string) (string, error) { - return exec.LookPath(file) + return out } diff --git a/apps/wvkey/README.md b/apps/wvkey/README.md index b9dee9c..e5060c9 100644 --- a/apps/wvkey/README.md +++ b/apps/wvkey/README.md @@ -47,6 +47,15 @@ Two license shapes: --pssh '' \ --license-url 'https://...' \ --quiet + +# wrapped JSON (Channel 4 / RedBee) — reuse the phone's license POST body +.venv/bin/python apps/wvkey/wvkey.py \ + --mode wrap \ + --wvd data/device.wvd \ + --pssh '' \ + --license-url 'https://...' \ + --wrap-json '{"token":"…","request":"…"}' \ + --quiet ``` Options: `--user-agent`, `--all` (print every CONTENT key — needed for multi-KID diff --git a/apps/wvkey/wvkey.py b/apps/wvkey/wvkey.py index 88fd19e..87c9e43 100644 --- a/apps/wvkey/wvkey.py +++ b/apps/wvkey/wvkey.py @@ -131,18 +131,163 @@ def fetch_content_keys_raw( 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"), + choices=("modulardrm", "raw", "wrap"), default="modulardrm", - help="modulardrm=RTE JSON; raw=Brightcove/octet-stream challenge", + 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, @@ -177,6 +322,21 @@ def main(argv: list[str] | None = None) -> int: 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) diff --git a/docs/README.md b/docs/README.md index bcbbd52..bf9437f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,6 +9,7 @@ | [capture.md](capture.md) | You need to discover an app's URLs, IDs and UI selectors | | [capture.md § Transparent](capture.md#transparent-capture-vpn-on-the-phone) | Phone VPN must stay on (BBC / NordVPN UK) — iptables MITM + pull | | [streamd.md](streamd.md) | You are running the control plane + agent | +| [streamd-server-setup.md](streamd-server-setup.md) | Dumb-friendly Linux server install: curl, chmod, MPD streams, keep-alive | | [providers/bbc.md](providers/bbc.md) | BBC iPlayer clear live DASH — transparent capture with UK VPN | | [providers/rte.md](providers/rte.md) | You are filling in `apps/modules/rte/module.yaml` | | [providers/tg4.md](providers/tg4.md) | You are filling in `apps/modules/tg4/module.yaml` | diff --git a/docs/images/streamd/dashboard.jpg b/docs/images/streamd/dashboard.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0cd25e12f6171761854552442ac0552fa868865f GIT binary patch literal 68132 zcmeFZ2V9d$*C-yBRV<(@QlwdEN|zFlt|GljlMYHJp-8U**G`w-1f-LM1gW8;A|NH9 zBqR`;(nA#pARusqxcj>MeeZpFZ~Oi4{eLs&dCqg@%$YMYXUaJ@`e8vro}QEK{CPG`UXDu~ydnYuBJwiwy1Fh${%0BN zy$75<{)_)n0M(JRfM3oYp*nkH?*l-B(q6y(Lbb1Ne}tpQsD3^23-$366zx0+f2078 z{6h8X(PPwmL;wvHCEssUzfqFD8cEj$WkPbMx9XzFnHMj--X}j&Pq&|Tm_Y3-yLjoI z?@T}7^d~ClTL9bCI-1Rh6=UKDV0TWwN`%yY%h}N171n9Jh}#3u&hG*Ar$H+VBNc(| zqnW`Xg_JTRvv0}GcllfTK1dTdmf4c~W_E>KC&0h4Kbn|MS0S#EgVnc4WQsL|XyqK_RK$9Vc70C0?~s`46S>RDK4f*99e2glqX zbsk2{BUQ^EWzEhdKWWs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K48E_a3bEF-w zsc0uoXOSG5;t&kLq84Hr(klAb8)$i6vi(5@rZ&<0W>hlyjpopvSIA3(IMbPfe{P>) zh~!I!p=ol&xJjv)z-DL+QyXYIUs82EhMs^X8{~9Ys0`t7nMfq*9*oOV6wvf9)DRjl zkVJmbgOzoL4n+DS!3OZ{4*b`DWLNPYlmk^g#ZSJg`azD^ zwDbfJohROcA50Bk^h7e@A+(4!m|d88V)_f%jiG?)8*|R(`d7$vEeN?&EDK)9x=dE9 zDg_UH>nwTX!{~7E&TkhqU{RR|eg6RU{;(;0JrAr(fO-PJn)pYo=Prw9KpR9Gaw8N=oZ*}>>cYPv2oz6T)m__f z8i$?#0Hz5(BVqZ>imu@P2Fv0@0sJ8T?N3&-?i&xNKEyinJjWyG3x?`_?qkto>5feh z(TUoKX+$!nA=VRo(0Z}Pux&o^=T|BpORTPS$Uw1{mi?E~x_w7NIvvN=A7Pn(kexY* z3=oYV?LpJiaReTf#?}dkxQVcp7}R}Fp@ps-#el=PnsYvtK`tJ3b1cIEiHs>dx_yXX zhnG%6&>WT+J5WREJP>+D4p@7MhuIvO9r+GeU5SYX)2W>&PDkn&lJXGD8IRcb`yc<= DtRx$B literal 0 HcmV?d00001 diff --git a/docs/images/streamd/people-keys.jpg b/docs/images/streamd/people-keys.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0f08597b16af10a0da6d5176dbb8dfc9c919be70 GIT binary patch literal 36618 zcmd3O1z43$x9BDn1nExc?(Xg`>F(|nBm@MdySq!eQMy4oC8a}JMU=buM*Z|V-~S)~ zbMJGWJNsp3)vSp%v1Z;^Z|85<0LU^D(h>j&2nc{7@CUfvfLM|i6*W*&QIwFD69+N? z0El4#FhB|c0Cx7S&MJ~3#F|>##DHIdk%^1rFX-PvppL6q05Apsrs$PjVUYeV@ZaEY z&cFhJGAF=4bPF&H0S$tU?_g{Y?BVL@3al#~2sUwa2Ejr=7{OUhMHC3j0byc`Utr^3 zU{f;}6QGPOP{!b|wmD=009+RU094FhG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sgO|eNN5cDx3XF#^UMPf{zt|MP#(F7^CCo6FaQd zXu8{q8U*`0R~Sh_7qn()4BvwY<0O=EH`%1avR{038aEI)G2`W3oki@MK{jZiLNg+9 zvg)Bg;GDTF>DyH8L=bgW`0J}nc7zGi_gJ6Y*Q((g=*>4e18wESaK@!bj4SP-NI!Y2 ztDlg6%3uD2OqEFhCrnH?s^Sx9Vkbt;oNw_QyL_UaDEgi3;|A2kiFY-0qo8FrP>g5v zcvij5PzK-HqwLU0p9tR-57%Hc6ME;8DcQi6@gxTajY)n;UGGse%vth|#V+7bcJ5>C zL%8OWDNS(4!==MZtN2Zm{5#eg)|2M$?|2KWx8I(M)bfp;I_9Cj7D~WoVxzxiO-}i0 z6fQByxmxc{%#>0;T*53}*_pHrOWGb9}Hxt7xoBz{-GL*Eni$2?Jk L)y`kv|C;|_zQ9{g literal 0 HcmV?d00001 diff --git a/docs/images/streamd/stream-detail.jpg b/docs/images/streamd/stream-detail.jpg new file mode 100644 index 0000000000000000000000000000000000000000..65082a2dd8df9d12c7a5a875132457420aef19c3 GIT binary patch literal 63459 zcmeEu1zc3i`}b0!prQiOAt6#CT_UI;CC#!lNV9Y|C@KmH$O4Nr((J+_v2>_(OD)nM zCEZ=`0{33={=E14`@iq!^Zsi%o_XRs&&-+g%$#TDob~X_;RxW8%me8M01ONafIj*U zaQGFYU;6%iJw;`O2htBE&?1p8*gm0Tcizd;tKE z4t$p}yaNCTo&x{{o!@1v3dh%rarKjekD{l7aM_5+>)u#XcCI^p7;!NtWpclPW#JOVs?^dG_1 zi>1gSgIoa4a?+D*fQnJGMzcq0932^x=rW+0b3*#~X z^D+k3WsJjW057_~FtLvO@Q;Lrje&`C2KOvlc#{6mU|?clpTWUB>;s&~LKnM)bqTH7 zV~srlIOV?o1No1HF`v-|3IImYnG0g*I}!K++tgyE{1A|P2#DA({8&*nRYudl*BU6M znfIh+Y!i(UYVSt*NZ2lpxCAJ#X-t{waZf+~$68JR!YV6XaiVyE^K!!ti+xqM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UTyGD59h?Dwia2hN*Mvw|FUh?XZ=T{ zrTH%#f2Mld{cl;?e4GD%%zsJff!HNhp@aNi z`Nc|aUt;R=KF+*Ge2itC{FOc^0{~RwV5q9CVyWicKspYA=($H`Al35NH}2zjpACxH z46By=U!!J{-Ns;0yhqH%47$X_FDd>GLNeGF+a|M0EFz%9H?ULP_MpB(ssKj24C`v9 zMqY;Vfe(w~;j)c6cbE$aulMy9Rvt5YurgL2UH4fnD0h-#G7eir*UKiI@P=KY#ec?N|W)6(#c^hAvGV>wA*d*#m5yf5uA_y$Tz z{M;udwd$aBoF(q-X=X&5K-*PC#1o7=*>ARFCu&Bl{9~I6h~{l~nwY8q*4& z4m==?tIyOv>qiTJqtN>onfQULx5=9(F^u!WPj4_VamRzyYPXHhW7HOVn5>{dql*qk z=Q9=k?nAAUf+SbB$+_IQS;tr&7>ksY94a1bMPo2hr}>RHglARf6_K-JQ`L`DUksPd zlr0I3jaeG(-4F|m-*>S+gj^?SwcX+r^WQ&%dxz@{T0{5n(U=dy4H~+w`Ow{M*`LF&(~57TY&u_rUNCbf0#R!)Sry7+k3SYyq#?z1oU`eVcWkKen3In{njN++xFxxzpbj-?Y>4}le&I1`lmcXn5Ht8Kb=PAMETlINP>qycruxu z_Viv?+OS=6U(RNRy|Zo2u{v{(>2ZEg4AebpEUvjxc>0+_BVJY|c!Db9M2Tgog7~yY zF23>GsVh2>)B(J5I5s~mrhaxAbu~F zJ*eGCQ|{tC@g(FiH_wW@KQOL@+XK$47G@b1hzV}+$V)Jy- z5++sXe-H}C9E52>l+~qkxszNE34wvlZf4qd> j2)^gjS8%$TR^z|=gy|O+oZ*idoaL{uf2(8j``7;h8QdL@ literal 0 HcmV?d00001 diff --git a/docs/images/streamd/streams.jpg b/docs/images/streamd/streams.jpg new file mode 100644 index 0000000000000000000000000000000000000000..20dc01b1d927b47bb0e987283bb907f6aa0287f7 GIT binary patch literal 82750 zcmeFZ1z4QRvM4%0fP@4H?vUV4@G!W$y9d|7AwaMs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CYU}fHm#hrBYAvH~0enM9t@6W?gJSv*KX@XuB*FoZp(ACM=Hgp2aw&AifP2x`A%f7M&zEV7=>= zGHZH+5>+&PXt;@+UANrnhysXW_ggxX;UI2;oT@o2kF zxD8u3_j}mxwrC{>4!V6z%1T7$F91Fk0$rV2qWlYxi!A^x>5mdUMe6FfmYVBkT;+%@ zYmx!n%65~#pFU^GB3WmLXr>^HKwPVqJehX6c4Cz06jEY`tL zl${Pn7yMv&n$TU(RpPPTxi5qI2J!woywC*hN(=V|0cMs+V_^y9{AhEs51eMMnc4g< zx^CL7^$^Sa_q`j_b0S$>ct;G8SkPM=3WN5r;2SI#*dn2uM@qkb9H~aR+l++3>Prz_ zQ#;qr!W|=r+6C@McJY>83= zV-pHVCA66SDEDnUl#ri%;vGOLrv>>(Y$s->EDTovnPd5#&>yZba4ispPZ-HCt4NhQ zq$bm}pJ##7dh8je6klpRwmSSxVM>*@*E4n_LisDjT5KH6HAh(9P2}}UD=o=Y_h(0H z0f6Y};#ja!Rs&YJ+82scYZwxi|4)j8!nuSUvI2e4ETVYlo)~ z6~Y;|^I%G{qkp(508Rxy2wS05SB)&|n*o5hRZ-bzJUNvku>;hRYCBrqWg^pv1{FHH zZ5&bG_gyIeRicVNrO7wC92OU#ZL@MpQn6j$4|8JL7YVs^S(ruGxh--S>HtGA^vYr2 zrTm5)nzv`_Xkm_3^?2_w#>_AjfPEPuC1j=Kh;0wVl6bXRHb%FhyTAgnXZu~?Q{~|} zaE`. + +You do **not** need Go, git, or a full repo checkout. One binary is enough. + +For the deep reference (every flag, every API route), see [streamd.md](streamd.md). + +--- + +## What each piece does + +| Piece | Command | Job | +|---|---|---| +| **streamd** | `drm serve` | Dashboard + API + pulls the MPD and serves HLS | +| **agent** | `drm agent run` | Optional. Uses a phone to refresh MPD/keys when they expire | + +If you already have a working MPD URL and Widevine keys (`KID:KEY`), you can run +**streamd alone**. Start the agent later when you want automatic refresh. + +--- + +## 0. What you need + +- A Linux server (x86_64 or ARM64) +- SSH access +- `curl` (almost every distro has it) +- Outbound HTTPS (streamd downloads ffmpeg / N_m3u8DL-RE on first start) + +Check your CPU type: + +```bash +uname -m +``` + +- `x86_64` → download `drm-linux-amd64` +- `aarch64` → download `drm-linux-arm64` + +--- + +## 1. Make a folder and download the binary + +```bash +mkdir -p ~/null-drm +cd ~/null-drm +``` + +Pick the matching line (replace `v0.1.4` if a newer `v*` release exists — check +[releases](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases)): + +```bash +# Intel / AMD 64-bit +curl -fL -o drm \ + "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/v0.1.4/drm-linux-amd64" + +# OR ARM 64-bit (Raspberry Pi 4+, many cloud ARM VMs) +# curl -fL -o drm \ +# "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/v0.1.4/drm-linux-arm64" +``` + +Make it executable and check it works: + +```bash +chmod +x drm +./drm help +``` + +You should see a list of commands including `serve` and `agent`. + +Optional layout after first run: + +```text +~/null-drm/ + drm # the binary + .cache/streamd/ # created by serve (database, HLS, logs) + .cache/agent/ # created by agent + agent.yaml # you create this for the agent + data/ # optional .wvd for key fetch + modules/ # optional provider zips (agent / capture) + bin/ # auto-downloaded ffmpeg, N_m3u8DL-RE, mp4decrypt +``` + +--- + +## 2. Start streamd (first time) + +Pick a password. Create the first admin account on the command line so you are +not stuck hunting a setup token in the logs: + +```bash +cd ~/null-drm + +./drm serve \ + --bind 0.0.0.0:8083 \ + --data .cache/streamd \ + --admin-user admin \ + --admin-pass 'CHANGE_ME_NOW' +``` + +What those flags mean: + +| Flag | Meaning | +|---|---| +| `--bind 0.0.0.0:8083` | Listen on all interfaces so you can open it from your PC | +| `--data .cache/streamd` | Where the DB, HLS files, and logs live | +| `--admin-user` / `--admin-pass` | First admin account (only used when the DB is empty) | + +You will see a startup warning about binding non-loopback. That is expected on a +server. Prefer putting a reverse proxy (Caddy / nginx) with TLS in front later. + +On first start, streamd downloads ffmpeg, N_m3u8DL-RE, and mp4decrypt into +`bin/`. Wait until the log says it is listening. + +Open in your browser (use the server IP): + +```text +http://YOUR_SERVER_IP:8083 +``` + +Sign in with `admin` / the password you set. + +**Firewall tip:** if the page does not load, open TCP 8083: + +```bash +# Ubuntu ufw example +sudo ufw allow 8083/tcp +sudo ufw reload +``` + +--- + +## 3. Create an API key for the agent (and for curl) + +In the dashboard: + +1. Open **Settings → API keys** (or **People & keys**) +2. **New API key** +3. Role: **operator** +4. Copy the secret once (`ndk_…`) — it is shown only then + +You will paste that into `agent.yaml` and into curl examples below. Call it +`YOUR_API_KEY` in the rest of this guide. + +--- + +## 4. Add an MPD stream and start it + +### Option A — dashboard (easiest) + +1. Go to **Streams → Add stream** (or **Create**) +2. **Basics:** name like `city-news`, leave **Enabled** checked +3. **Source:** paste the MPD URL (`https://…/manifest.mpd`) +4. Paste keys if the stream is encrypted — one `KID:KEY` per line. Leave empty + for clear streams (e.g. some BBC) +5. Optional proxy: `socks5://127.0.0.1:1080` if origin needs a UK/IE SOCKS hop +6. Create the stream +7. Open the stream → **Start** (or it may already be running if Enabled + MPD are set) + +When it is healthy, copy the play URL from the dashboard (Copy button), or use: + +```text +http://YOUR_SERVER_IP:8083/hls/city-news/index.m3u8 +``` + +HD / SD variants (if you enabled them) are: + +```text +http://YOUR_SERVER_IP:8083/hls/city-news-hd/index.m3u8 +http://YOUR_SERVER_IP:8083/hls/city-news-sd/index.m3u8 +``` + +### Option B — curl (no browser) + +Create: + +```bash +export STREAMD_API_KEY='YOUR_API_KEY' + +curl -sS -X POST "http://127.0.0.1:8083/api/streams" \ + -H "Authorization: Bearer $STREAMD_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "city-news", + "title": "City News", + "mpd": "https://example.com/path/manifest.mpd", + "key": "KIDHEX:KEYHEX", + "enabled": true, + "drm_mode": "auto" + }' +``` + +Start (use the numeric `id` from the create response, or from `GET /api/streams`): + +```bash +curl -sS -X POST "http://127.0.0.1:8083/api/streams/1/start" \ + -H "Authorization: Bearer $STREAMD_API_KEY" +``` + +List streams: + +```bash +curl -sS "http://127.0.0.1:8083/api/streams" \ + -H "Authorization: Bearer $STREAMD_API_KEY" +``` + +Push fresh credentials later (what the agent does after a phone capture): + +```bash +curl -sS -X POST "http://127.0.0.1:8083/api/streams/1/credentials" \ + -H "Authorization: Bearer $STREAMD_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "mpd": "https://example.com/path/manifest.mpd", + "key": "KIDHEX:KEYHEX\nKIDHEX2:KEYHEX2" + }' +``` + +Health check (no auth): + +```bash +curl -sS "http://127.0.0.1:8083/api/health" +``` + +--- + +## 5. Agent (optional — auto refresh with a phone) + +Skip this section if you will paste MPD/keys yourself forever. + +### What the agent needs + +- streamd already running and reachable +- An **operator** API key +- `adb` on the server `PATH` +- A rooted phone with the streaming app **already installed** (agent never installs apps) +- USB debugging authorised (`adb devices` shows `device`) +- Provider modules under `modules/` if you use phone capture for that app +- A `.wvd` at `data/device.wvd` (or set `wvd:` in the config) for key fetch + +### Config file + +```bash +cd ~/null-drm +nano agent.yaml +``` + +Paste (edit the URL and key): + +```yaml +streamd_url: http://127.0.0.1:8083 +api_key: "YOUR_API_KEY" +poll_interval_sec: 30 +data_dir: .cache/agent +workers: 1 +max_attempts: 5 +capture_wait_sec: 180 +devices: [] +# wvd: data/device.wvd +# agent_id: my-server +``` + +Save, then run: + +```bash +cd ~/null-drm +./drm agent run --config agent.yaml +``` + +Useful checks: + +```bash +./drm agent devices +./drm agent status +./drm agent enqueue --stream city-news --reason manual +``` + +In the dashboard, **Refresh keys** on a stream asks connected agents to capture now. + +--- + +## 6. Keep it running when you close the terminal + +If you close SSH while `drm serve` is in the foreground, it dies. Pick one method. + +### Method A — `screen` (simplest) + +```bash +sudo apt-get update && sudo apt-get install -y screen # Debian/Ubuntu +# Fedora: sudo dnf install screen +``` + +Start streamd inside a named screen: + +```bash +cd ~/null-drm +screen -S streamd +./drm serve --bind 0.0.0.0:8083 --data .cache/streamd +``` + +Detach without killing it: press **`Ctrl+A`**, then **`D`**. + +Come back later: + +```bash +screen -r streamd +``` + +Second screen for the agent: + +```bash +screen -S agent +cd ~/null-drm +./drm agent run --config agent.yaml +# Ctrl+A then D +``` + +List sessions: `screen -ls` + +### Method B — `tmux` (same idea) + +```bash +sudo apt-get install -y tmux +cd ~/null-drm +tmux new -s streamd +./drm serve --bind 0.0.0.0:8083 --data .cache/streamd +# Detach: Ctrl+B then D +# Reattach: tmux attach -t streamd +``` + +### Method C — `nohup` (one-liner, no session to reattach) + +```bash +cd ~/null-drm +nohup ./drm serve --bind 0.0.0.0:8083 --data .cache/streamd > streamd.log 2>&1 & +echo $! > streamd.pid + +# optional agent +nohup ./drm agent run --config agent.yaml > agent.log 2>&1 & +echo $! > agent.pid +``` + +Stop later: + +```bash +kill "$(cat streamd.pid)" +kill "$(cat agent.pid)" +``` + +### Method D — systemd (survives reboot — recommended for a real server) + +Create a user unit (no root binary needed). Paths assume install in `/home/ubuntu/null-drm` +— change `User=`, paths, and password as needed. + +```bash +sudo tee /etc/systemd/system/streamd.service >/dev/null <<'EOF' +[Unit] +Description=Null-DRM streamd (drm serve) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=ubuntu +WorkingDirectory=/home/ubuntu/null-drm +ExecStart=/home/ubuntu/null-drm/drm serve --bind 0.0.0.0:8083 --data /home/ubuntu/null-drm/.cache/streamd +Restart=on-failure +RestartSec=5 +# Optional first-boot admin (ignored once users exist): +# Environment=STREAMD_ADMIN_PASS=CHANGE_ME + +[Install] +WantedBy=multi-user.target +EOF + +sudo tee /etc/systemd/system/drm-agent.service >/dev/null <<'EOF' +[Unit] +Description=Null-DRM credentials agent +After=network-online.target streamd.service +Wants=network-online.target +Requires=streamd.service + +[Service] +Type=simple +User=ubuntu +WorkingDirectory=/home/ubuntu/null-drm +ExecStart=/home/ubuntu/null-drm/drm agent run --config /home/ubuntu/null-drm/agent.yaml +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=multi-user.target +EOF + +sudo systemctl daemon-reload +sudo systemctl enable --now streamd.service +# when ready for the agent: +# sudo systemctl enable --now drm-agent.service +``` + +Useful commands: + +```bash +sudo systemctl status streamd +sudo journalctl -u streamd -f +sudo systemctl restart streamd +sudo systemctl stop streamd +``` + +Same pattern with `drm-agent` for the agent unit. + +--- + +## 7. Quick “am I done?” checklist + +```bash +cd ~/null-drm + +# binary runs +./drm help + +# streamd answers +curl -sS http://127.0.0.1:8083/api/health + +# at least one stream exists and is enabled +curl -sS http://127.0.0.1:8083/api/streams \ + -H "Authorization: Bearer YOUR_API_KEY" + +# HLS playlist exists after start (name = stream name) +curl -sI "http://127.0.0.1:8083/hls/city-news/index.m3u8" +``` + +Play the m3u8 in VLC / ffplay / any HLS player using the server IP URL. + +--- + +## 8. Common problems + +| Symptom | Fix | +|---|---| +| `Permission denied` running `./drm` | `chmod +x drm` | +| Browser cannot open the page | Use `--bind 0.0.0.0:8083`, open firewall port 8083, check `curl` from the server itself | +| Stream will not start | MPD must be `http://` or `https://`. Encrypted streams need `KID:KEY` lines | +| Agent does nothing | Operator API key wrong; stream **Enabled**; phone in `adb devices` as `device`; app installed | +| Dies when SSH closes | Use screen/tmux/nohup/systemd from §6 | +| Deps download fails | Server needs outbound HTTPS; or place ffmpeg / N_m3u8DL-RE / mp4decrypt on `PATH` / in `bin/` and use `--skip-deps` only if you already have them | +| Want loopback only + proxy | Bind `127.0.0.1:8083` and put Caddy/nginx in front with TLS | + +--- + +## 9. Stopping / upgrading + +Stop a foreground or screen session with `Ctrl+C` inside that session. + +Upgrade: + +```bash +cd ~/null-drm +# stop streamd first (systemctl stop streamd / kill / Ctrl+C) +curl -fL -o drm.new \ + "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/v0.1.4/drm-linux-amd64" +chmod +x drm.new +mv drm drm.bak +mv drm.new drm +# start again +``` + +Back up `.cache/streamd/streamd.db` before big upgrades. + +--- + +## See also + +- [streamd.md](streamd.md) — full control-plane + agent reference +- [release.md](release.md) — all binary names / build notes +- [quickstart.md](quickstart.md) — capture + modules from a full checkout diff --git a/docs/streamd.md b/docs/streamd.md index 4effc89..c476616 100644 --- a/docs/streamd.md +++ b/docs/streamd.md @@ -3,17 +3,22 @@ Two long-running pieces: `drm serve` holds the state and the dashboard, `drm agent run` keeps credentials fresh using real phones. +**New to Linux servers?** Start with the copy-paste guide: +[streamd-server-setup.md](streamd-server-setup.md) (download, chmod, add MPD +streams, screen/systemd so it survives closing the terminal). + ## drm serve ```bash -./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET +./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd ``` | Flag | Default | Purpose | |---|---|---| -| `--bind` | `0.0.0.0:8083` | listen address | +| `--bind` | `127.0.0.1:8083` | listen address (loopback). Non-loopback logs a warning | | `--data` | `.cache/streamd` | SQLite, work dirs, HLS output, logs | -| `--token` | `$STREAMD_TOKEN` | bearer token for mutating routes | +| `--token` | `$STREAMD_TOKEN` | legacy admin API key (prefer dashboard API keys) | +| `--admin-user` / `--admin-pass` | — | create first admin on empty install | | `--nre` | `$NRE_PATH`, `bin/`, `PATH`, auto-download | N_m3u8DL-RE | | `--ffmpeg` | `$FFMPEG_PATH`, `bin/`, `PATH`, auto-download | ffmpeg | | `--mp4decrypt` | `$MP4DECRYPT_PATH`, `bin/`, `PATH`, auto-download | Bento4 mp4decrypt | @@ -24,9 +29,12 @@ On start, `serve` resolves media tools and **downloads** ffmpeg (BtbN static), N_m3u8DL-RE (v0.6.0-beta), and mp4decrypt (Bento4) into `bin/` when missing. macOS ffmpeg is not auto-fetched — install with `brew install ffmpeg`. -Open . GET routes are unauthenticated; anything mutating -needs `Authorization: Bearer `. The header shows ffmpeg / NRE / mp4decrypt -status from `/api/health` → `deps`. +Open and sign in (or complete first-run setup). Auth is +session cookies for the dashboard and **API keys** (Settings → API keys) for +agents/scripts. Roles: `admin`, `operator`, `viewer`. `GET /api/health` stays +anonymous for liveness; stream list and mutations need a principal. Legacy +`--token` / `STREAMD_TOKEN` still works as an admin key and prints a migration +warning. ### Keys and proxy @@ -53,6 +61,7 @@ status from `/api/health` → `deps`. | `PATCH /api/streams/:id` | update | | `DELETE /api/streams/:id` | remove | | `POST /api/streams/:id/start\|stop\|restart` | desired state | +| `POST /api/streams/:id/capture` | ask connected agents to refresh credentials now | | `POST /api/streams/:id/credentials` | push a fresh manifest + keys | | `POST /api/streams/:id/claim` | agent claims the stream | @@ -107,7 +116,9 @@ at init time. ## drm agent run ```bash -export STREAMD_TOKEN=SECRET +# Prefer an operator API key from the streamd dashboard (Settings → API keys). +export STREAMD_API_KEY=ndk_… +# or: export STREAMD_TOKEN=… (legacy alias) ./bin/drm agent run --config apps/agent/agent.yaml ``` @@ -121,7 +132,9 @@ What it does, in a loop: 6. force-stop the app and release the device It never installs apps and never runs a downloader. A websocket heartbeat keeps its -claims alive, so claims expire automatically if the agent dies. +claims alive, so claims expire automatically if the agent dies. Streamd can also +push a capture immediately (`POST /api/streams/:id/capture` or the dashboard +**Refresh keys** button). ### Subcommands @@ -138,7 +151,10 @@ claims alive, so claims expire automatically if the agent dies. ```yaml streamd_url: http://127.0.0.1:8083 -# token: taken from $STREAMD_TOKEN when unset +# Prefer an API key created in the streamd dashboard (operator role): +# api_key: ndk_… +# token: … # alias for api_key (legacy name) +# Or set STREAMD_API_KEY / STREAMD_TOKEN in the environment. poll_interval_sec: 30 data_dir: .cache/agent workers: 1 @@ -160,14 +176,15 @@ run by the host; not linked into `drm.exe`). ```bash # terminal 1 -./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET +./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd -# terminal 2 -export STREAMD_TOKEN=SECRET +# terminal 2 — after creating an operator API key in the dashboard +export STREAMD_API_KEY=ndk_… ./bin/drm agent run --config apps/agent/agent.yaml ``` -Then create a stream, enable it, and watch the agent pick it up: +Then create a stream, leave **Enabled** checked (required for on-demand wake), +and watch the agent pick it up: ```bash ./bin/drm agent status diff --git a/modules/README.md b/modules/README.md index 82b89f0..39a7a7a 100644 --- a/modules/README.md +++ b/modules/README.md @@ -12,6 +12,7 @@ modules/ rte/ tg4/ itv/ # ITVX stub (phone capture; UK geo) + c4/ # Channel 4 / All 4 Live (UK geo) ``` ## Config files @@ -35,7 +36,7 @@ DRM_MODULES_DIR=D:\mods drm capture --app rte --channel rteone ## Releases -Push a `modules-v*` tag to publish per-module zips (`bbc.zip`, `rte.zip`, `tg4.zip`, `itv.zip`) via +Push a `modules-v*` tag to publish per-module zips (`bbc.zip`, `rte.zip`, `tg4.zip`, `itv.zip`, `c4.zip`, `my5.zip`) via Forgejo Actions. Host `drm` stays on separate `v*` tags. Requires Go on PATH to build from source. Release zips may ship `.bin/` prebuilt. diff --git a/modules/c4/go.mod b/modules/c4/go.mod new file mode 100644 index 0000000..72035f9 --- /dev/null +++ b/modules/c4/go.mod @@ -0,0 +1,15 @@ +module null-drm/modules/c4 + +go 1.25.0 + +require ( + drmdecryption v0.0.0 + drmdecryption/modules v0.0.0 +) + +require gopkg.in/yaml.v3 v3.0.1 // indirect + +replace ( + drmdecryption => ../../apps/pkg + drmdecryption/modules => ../../apps/modules +) diff --git a/modules/c4/go.sum b/modules/c4/go.sum new file mode 100644 index 0000000..a62c313 --- /dev/null +++ b/modules/c4/go.sum @@ -0,0 +1,4 @@ +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= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/modules/c4/main.go b/modules/c4/main.go new file mode 100644 index 0000000..fc6bfc4 --- /dev/null +++ b/modules/c4/main.go @@ -0,0 +1,171 @@ +// Command c4 is the external Channel 4 provider module. +// Built on demand by the drm host: modules/c4/.bin/c4[.exe] +package main + +import ( + "encoding/json" + "flag" + "fmt" + "os" + + "drmdecryption/adb" + appreg "drmdecryption/app" + "drmdecryption/modcfg" + "drmdecryption/modhost" + "drmdecryption/modules/c4" +) + +func main() { + if len(os.Args) < 2 { + usage() + os.Exit(2) + } + cmd, args := os.Args[1], os.Args[2:] + var err error + switch cmd { + case "describe": + err = cmdDescribe() + case "launch": + err = cmdLaunch(args) + case "autoplay": + err = cmdAutoplay(args) + case "catalog": + err = cmdCatalog(args) + case "help", "-h", "--help": + usage() + return + default: + usage() + err = fmt.Errorf("unknown command %q", cmd) + } + if err != nil { + fmt.Fprintln(os.Stderr, "[!]", err) + os.Exit(1) + } +} + +func usage() { + fmt.Fprint(os.Stderr, `c4 — Null DRM external module (Channel 4 / All 4) + +Usage: + c4 describe + c4 launch [--serial SERIAL] + c4 autoplay --channel ID [--serial SERIAL] + c4 catalog --channel ID [--json] +`) +} + +func loadApp() (appreg.App, error) { + return c4.New() +} + +func cmdDescribe() error { + a, err := loadApp() + if err != nil { + return err + } + d := modhost.Describe{ + Protocol: modhost.ProtocolVersion, + Name: a.Name(), + Package: a.Package(), + LicenseURL: a.LicenseURL(), + KeyMode: a.KeyMode(), + ProxyBin: a.ProxyBin(), + CAHash: a.CAHash(), + TransparentMITM: true, + Rewriter: "none", + ValuesPath: modcfg.Path(a.Name()), + } + if rw, ok := a.(appreg.RequireWVD); ok { + d.RequireWVD = rw.RequireWVD() + } + if mh, ok := a.(appreg.MitmHostList); ok { + d.MitmHosts = mh.MitmHosts() + } + if sd, ok := a.(appreg.StreamDefaults); ok { + d.Rewriter = sd.RewriterName() + } + type loaded interface { + ConfigLoaded() bool + ConfigPath() string + } + if L, ok := a.(loaded); ok { + d.ValuesLoaded = L.ConfigLoaded() + if L.ConfigPath() != "" { + d.ValuesPath = L.ConfigPath() + } + } + if _, ok := a.(appreg.Catalog); ok { + d.HasCatalog = true + } + h := a.CaptureHints() + d.Require = h.Require + d.Score = h.Score + d.ChannelMPDPrefer = map[string][]string{ + "channel4": {"channel(c4)"}, + "e4": {"channel(e4)"}, + "more4": {"channel(m4)"}, + "film4": {"channel(f4)"}, + "fourseven": {"channel(4s)"}, + } + for _, ch := range a.Channels() { + d.Channels = append(d.Channels, modhost.Channel{ID: ch.ID, Label: ch.Label}) + } + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(d) +} + +func cmdLaunch(args []string) error { + fs := flag.NewFlagSet("launch", flag.ContinueOnError) + serial := fs.String("serial", "", "adb device serial") + if err := fs.Parse(args); err != nil { + return err + } + a, err := loadApp() + if err != nil { + return err + } + c := adb.New() + if *serial != "" { + c = c.WithSerial(*serial) + } + return a.Launch(c) +} + +func cmdAutoplay(args []string) error { + fs := flag.NewFlagSet("autoplay", flag.ContinueOnError) + serial := fs.String("serial", "", "adb device serial") + channel := fs.String("channel", "", "channel id") + if err := fs.Parse(args); err != nil { + return err + } + if *channel == "" { + return fmt.Errorf("--channel is required") + } + a, err := loadApp() + if err != nil { + return err + } + c := adb.New() + if *serial != "" { + c = c.WithSerial(*serial) + } + return a.AutoPlay(c, *channel) +} + +func cmdCatalog(args []string) error { + fs := flag.NewFlagSet("catalog", flag.ContinueOnError) + channel := fs.String("channel", "", "channel id") + _ = fs.Bool("json", false, "print JSON") + if err := fs.Parse(args); err != nil { + return err + } + if *channel == "" { + return fmt.Errorf("--channel is required") + } + if _, err := loadApp(); err != nil { + return err + } + return fmt.Errorf("c4 module has no catalog — use phone capture (UK geo)") +} diff --git a/modules/c4/module-publish.yaml b/modules/c4/module-publish.yaml new file mode 100644 index 0000000..b7d7c23 --- /dev/null +++ b/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/modules/my5/go.mod b/modules/my5/go.mod new file mode 100644 index 0000000..32bc678 --- /dev/null +++ b/modules/my5/go.mod @@ -0,0 +1,15 @@ +module null-drm/modules/my5 + +go 1.25.0 + +require ( + drmdecryption v0.0.0 + drmdecryption/modules v0.0.0 +) + +require gopkg.in/yaml.v3 v3.0.1 // indirect + +replace ( + drmdecryption => ../../apps/pkg + drmdecryption/modules => ../../apps/modules +) diff --git a/modules/my5/go.sum b/modules/my5/go.sum new file mode 100644 index 0000000..a62c313 --- /dev/null +++ b/modules/my5/go.sum @@ -0,0 +1,4 @@ +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= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/modules/my5/main.go b/modules/my5/main.go new file mode 100644 index 0000000..2663533 --- /dev/null +++ b/modules/my5/main.go @@ -0,0 +1,169 @@ +// Command my5 is the external Channel 5 (My5 / "5") provider module. +// Built on demand by the drm host: modules/my5/.bin/my5[.exe] +package main + +import ( + "encoding/json" + "flag" + "fmt" + "os" + + "drmdecryption/adb" + appreg "drmdecryption/app" + "drmdecryption/modcfg" + "drmdecryption/modhost" + "drmdecryption/modules/my5" +) + +func main() { + if len(os.Args) < 2 { + usage() + os.Exit(2) + } + cmd, args := os.Args[1], os.Args[2:] + var err error + switch cmd { + case "describe": + err = cmdDescribe() + case "launch": + err = cmdLaunch(args) + case "autoplay": + err = cmdAutoplay(args) + case "catalog": + err = cmdCatalog(args) + case "help", "-h", "--help": + usage() + return + default: + usage() + err = fmt.Errorf("unknown command %q", cmd) + } + if err != nil { + fmt.Fprintln(os.Stderr, "[!]", err) + os.Exit(1) + } +} + +func usage() { + fmt.Fprint(os.Stderr, `my5 — Null DRM external module (Channel 5 / My5 / "5") + +Usage: + my5 describe + my5 launch [--serial SERIAL] + my5 autoplay --channel ID [--serial SERIAL] + my5 catalog --channel ID [--json] +`) +} + +func loadApp() (appreg.App, error) { + return my5.New() +} + +func cmdDescribe() error { + a, err := loadApp() + if err != nil { + return err + } + d := modhost.Describe{ + Protocol: modhost.ProtocolVersion, + Name: a.Name(), + Package: a.Package(), + LicenseURL: a.LicenseURL(), + KeyMode: a.KeyMode(), + ProxyBin: a.ProxyBin(), + CAHash: a.CAHash(), + TransparentMITM: true, + Rewriter: "none", + ValuesPath: modcfg.Path(a.Name()), + } + if mh, ok := a.(appreg.MitmHostList); ok { + d.MitmHosts = mh.MitmHosts() + } + if sd, ok := a.(appreg.StreamDefaults); ok { + d.Rewriter = sd.RewriterName() + } + type loaded interface { + ConfigLoaded() bool + ConfigPath() string + } + if L, ok := a.(loaded); ok { + d.ValuesLoaded = L.ConfigLoaded() + if L.ConfigPath() != "" { + d.ValuesPath = L.ConfigPath() + } + } + if _, ok := a.(appreg.Catalog); ok { + d.HasCatalog = true + } + h := a.CaptureHints() + d.Require = h.Require + d.Score = h.Score + // Prefer substrings refined after first captures; safe defaults for now. + d.ChannelMPDPrefer = map[string][]string{ + "channel5": {"channel5"}, + "5usa": {"5usa", "usa"}, + "5star": {"5star"}, + "5action": {"5action"}, + "5select": {"5select"}, + } + for _, ch := range a.Channels() { + d.Channels = append(d.Channels, modhost.Channel{ID: ch.ID, Label: ch.Label}) + } + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(d) +} + +func cmdLaunch(args []string) error { + fs := flag.NewFlagSet("launch", flag.ContinueOnError) + serial := fs.String("serial", "", "adb device serial") + if err := fs.Parse(args); err != nil { + return err + } + a, err := loadApp() + if err != nil { + return err + } + c := adb.New() + if *serial != "" { + c = c.WithSerial(*serial) + } + return a.Launch(c) +} + +func cmdAutoplay(args []string) error { + fs := flag.NewFlagSet("autoplay", flag.ContinueOnError) + serial := fs.String("serial", "", "adb device serial") + channel := fs.String("channel", "", "channel id") + if err := fs.Parse(args); err != nil { + return err + } + if *channel == "" { + return fmt.Errorf("--channel is required") + } + a, err := loadApp() + if err != nil { + return err + } + c := adb.New() + if *serial != "" { + c = c.WithSerial(*serial) + } + return a.AutoPlay(c, *channel) +} + +func cmdCatalog(args []string) error { + fs := flag.NewFlagSet("catalog", flag.ContinueOnError) + channel := fs.String("channel", "", "channel id") + _ = fs.Bool("json", false, "print JSON") + if err := fs.Parse(args); err != nil { + return err + } + if *channel == "" { + return fmt.Errorf("--channel is required") + } + if _, err := loadApp(); err != nil { + return err + } + return fmt.Errorf("my5 module has no catalog — use phone capture (UK geo)") +} diff --git a/modules/my5/module-publish.yaml b/modules/my5/module-publish.yaml new file mode 100644 index 0000000..cdb0582 --- /dev/null +++ b/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/scripts/build-modules-release.ps1 b/scripts/build-modules-release.ps1 index 53674b1..32e2c79 100644 --- a/scripts/build-modules-release.ps1 +++ b/scripts/build-modules-release.ps1 @@ -31,7 +31,7 @@ function Resolve-Go { $GoExe = Resolve-Go New-Item -ItemType Directory -Force -Path $Out | Out-Null -$Modules = @("bbc", "rte", "tg4", "itv") +$Modules = @("bbc", "rte", "tg4", "itv", "c4", "my5") $Targets = @( @{ GOOS = "windows"; GOARCH = "amd64"; Ext = ".exe" }, @{ GOOS = "windows"; GOARCH = "arm64"; Ext = ".exe" }, @@ -111,4 +111,4 @@ foreach ($z in $builtZips) { } [System.IO.File]::WriteAllLines($sumsPath, $lines) Write-Host "DONE modules release $Version → $Out" -Get-ChildItem $Out -Filter "*.zip" | Where-Object { $_.Name -match '^(bbc|rte|tg4|itv)\.zip$' } | Format-Table Name, Length +Get-ChildItem $Out -Filter "*.zip" | Where-Object { $_.Name -match '^(bbc|rte|tg4|itv|c4)\.zip$' } | Format-Table Name, Length diff --git a/scripts/build-modules-release.sh b/scripts/build-modules-release.sh index a4f9111..4d17199 100644 --- a/scripts/build-modules-release.sh +++ b/scripts/build-modules-release.sh @@ -9,7 +9,7 @@ if [[ -z "$VERSION" ]]; then fi mkdir -p "$OUT" -MODULES=(bbc rte tg4 itv) +MODULES=(bbc rte tg4 itv c4 my5) TARGETS=( "windows amd64 .exe" "windows arm64 .exe" @@ -65,4 +65,4 @@ for z in "${built[@]}"; do ( cd "$(dirname "$z")" && sha256sum "$(basename "$z")" ) >> "$sums" done echo "DONE modules release $VERSION → $OUT" -ls -la "$OUT"/bbc.zip "$OUT"/rte.zip "$OUT"/tg4.zip "$OUT"/itv.zip 2>/dev/null || true +ls -la "$OUT"/bbc.zip "$OUT"/rte.zip "$OUT"/tg4.zip "$OUT"/itv.zip "$OUT"/c4.zip "$OUT"/my5.zip 2>/dev/null || true diff --git a/scripts/notify-telegram.ps1 b/scripts/notify-telegram.ps1 index 17c303b..a8396b6 100644 --- a/scripts/notify-telegram.ps1 +++ b/scripts/notify-telegram.ps1 @@ -67,7 +67,7 @@ function New-TelegramBody { if ($Kind -eq "modules") { return ( "$Title" + $nl + - "Provider module zips: $( & $code 'bbc.zip' ), $( & $code 'rte.zip' ), $( & $code 'tg4.zip' ), $( & $code 'itv.zip' )" + $nl + $nl + + "Provider module zips: $( & $code 'bbc.zip' ), $( & $code 'rte.zip' ), $( & $code 'tg4.zip' ), $( & $code 'itv.zip' ), $( & $code 'c4.zip' ), $( & $code 'my5.zip' )" + $nl + $nl + "Unpack each into $( & $code 'modules//' ) and edit $( & $code 'module.yaml' ) for secrets." + $nl + $nl + "Download $Tag" ) diff --git a/scripts/notify-telegram.sh b/scripts/notify-telegram.sh index b403fd9..91e790c 100644 --- a/scripts/notify-telegram.sh +++ b/scripts/notify-telegram.sh @@ -59,7 +59,7 @@ if [[ -n "${RELEASE_BODY:-}" ]]; then BODY="$RELEASE_BODY" elif [[ "$KIND" == "modules" ]]; then BODY="${TITLE} -Provider module zips: bbc.zip, rte.zip, tg4.zip, itv.zip +Provider module zips: bbc.zip, rte.zip, tg4.zip, itv.zip, c4.zip, my5.zip Unpack each into modules/<name>/ and edit module.yaml for secrets.