diff --git a/CHANGELOG.md b/CHANGELOG.md index 8232c79b..28e2f21a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +> **Breaking for the HLS opt-in on a relay with auth on.** A key no longer signs for its prefix's mirror beneath `/.hls/` on its own: it signs for the mirror beneath an opt-in directory only when its entry in the key set lists the opt-in (`"optIns": ["hls"]`). Add the member to each key whose publishers opt into `qumo hls` (or re-issue the key set with `qumo auth keygen -opt-ins hls`); until then the relay refuses their opt-in tokens, saying the root lies outside "the opt-ins it holds []". A relay with auth off is unaffected. + ### Added -- **`qumo abr` transcodes broadcasts into an adaptive-bitrate ladder (`internal/abr`).** A relay client: for every broadcast announced beneath `ABR_PREFIX` it publishes an ABR broadcast beside it, at the same path with `ABR_SUFFIX` appended (`/live/cam1` → `/live/cam1.abr`), carrying the source's tracks as they are plus one rendition per rung of `ABR_LADDER` (default `720:2500,360:800`) shorter than the source video, encoded by ffmpeg (`ABR_FFMPEG`, `ABR_CODEC`, `ABR_PRESET`). Every video track is in one MSF alternate group (`altGroup`) with its size, bitrate and decoder configuration, and every rendition numbers its groups as the source does, each opening with a keyframe at the same frame, so a player can switch between them at any group boundary. Rendition frames keep the exact LOC timestamp of the source frame they were encoded from. One ffmpeg decodes the source once for every rendition, adding about 10 ms per frame; the source track is forwarded without re-encoding and never waits on it. Aliases, broadcasts that redirect subscribers to another (such as HLS opt-ins), are not transcoded: the broadcast they name is. The source must be H.264 without B-frames. -- **The playground plays ABR broadcasts adaptively (`playground`).** A broadcast whose video tracks share an alternate group is played adaptively: the viewer switches renditions at group boundaries, stepping down when frames fall behind their media time to what the rate measured since then carries, and up one rendition after a calm stretch. A step up keeps the old rendition until its last group before the switch has arrived; a step down drops it at once. The subscribe board picks a rendition by hand or automatically, and shows the rendition playing, the receive rate and the lag. +- **`qumo abr` transcodes broadcasts into an adaptive-bitrate ladder (`internal/abr`).** A publisher opts a broadcast in by announcing it beneath `/.abr/` (`/.abr/live/cam1` for `/live/cam1`), a redirect to it (`internal/optin`, shared with HLS); `qumo abr` then publishes `/live/cam1` + `ABR_SUFFIX` (`.abr`) with the source tracks as they are plus one H.264 rendition per `ABR_LADDER` rung shorter than the source (default `720:2500,360:800`; `ABR_FFMPEG`, `ABR_CODEC`, `ABR_PRESET`), all in one MSF `altGroup` with groups aligned to the source's, so a player can switch at any group boundary. Sources: H.264 (AVCC or Annex B) or VP9, without B-frames. A key holds an opt-in only when its key-set entry lists it (`"optIns": ["hls", "abr"]`, `qumo auth keygen -opt-ins`); the relay refuses other opt-in tokens and revokes a removed one within 30 s. `RELAY_SIGNING_KEY` lets `qumo abr` sign its own relay credential. See `docs/site/content/en/docs/cli/abr.md`. +- **The playground opts a broadcast into ABR, and plays ABR broadcasts adaptively (`playground`).** The publish board's ABR box announces the broadcast's opt-in beneath `/.abr/` beside it, as the HLS scenario does beneath `/.hls/`. A broadcast whose video tracks share an alternate group is played adaptively: the viewer switches renditions at group boundaries, stepping down when frames fall behind their media time to what the rate measured since then carries, and up one rendition after a calm stretch. A step up keeps the old rendition until its last group before the switch has arrived; a step down drops it at once. The subscribe board picks a rendition by hand or automatically, and shows the rendition playing, the receive rate and the lag. +- **`PEERS` names are resolved again while the relay runs, so peers behind a name join and leave without a restart; an entry without a port is an SRV name (`_moqt._udp.hubs.example.com`) (`internal/relay`).** A `PEERS` entry that is neither `host:port` nor a name without a port now stops the relay at startup, and a host that doesn't resolve is retried instead of being dialed by name. +- **The relay re-reads its certificates while it runs (`internal/relay`).** About once a minute it reads `CERT_FILE`/`KEY_FILE`, `PEER_CERT_FILE`/`PEER_KEY_FILE` and `CA_FILE` and compares them with what it holds; what changed is taken from the next TLS handshake on, so cert-manager, a Vault or step-ca agent, or any job that writes the files needs no restart. A public certificate is taken once it parses and matches its key; a peer certificate and the CA together, once they pass the startup checks (issued by the CA, the peering name, valid now). Anything else is logged, once per distinct error rather than at every read, and the certificates in use are kept; renewal tools should replace the files atomically (write, then rename). Sessions already established are untouched. The CA is now checked at each handshake on both sides: as the dialed relay (`GetConfigForClient`) and as the dialer (`VerifyConnection` against the current CA, with the same checks crypto/tls made). The relay's key-set and usage requests are signed with the renewed peer certificate (`reqsign.Signer.Rotate`), and `qumo dns` re-reads its `PEER_CERT_FILE`/`PEER_KEY_FILE` on the same one-minute cadence and signs its feed reads with a renewed pair (`internal/certreload`, shared by both). New metrics: `qumo_relay_cert_reloads_total{cert,result}` and `qumo_relay_cert_not_after_seconds{cert}`, and `qumo_dns_cert_reloads_total{cert,result}` and `qumo_dns_cert_not_after_seconds{cert}`; alert on the `not_after` gauges. A CA is rotated by putting the new one beside the old in `CA_FILE` first ([TLS & mTLS](docs/site/content/en/docs/deployment/tls.md#certificate-renewal)). ### Fixed @@ -24,10 +28,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **`PEERS` names are resolved again while the relay runs, so peers behind a name join and leave without a restart; an entry without a port is an SRV name (`_moqt._udp.hubs.example.com`) (`internal/relay`).** A `PEERS` entry that is neither `host:port` nor a name without a port now stops the relay at startup, and a host that doesn't resolve is retried instead of being dialed by name. - -- **The relay re-reads its certificates while it runs (`internal/relay`).** About once a minute it reads `CERT_FILE`/`KEY_FILE`, `PEER_CERT_FILE`/`PEER_KEY_FILE` and `CA_FILE` and compares them with what it holds; what changed is taken from the next TLS handshake on, so cert-manager, a Vault or step-ca agent, or any job that writes the files needs no restart. A public certificate is taken once it parses and matches its key; a peer certificate and the CA together, once they pass the startup checks (issued by the CA, the peering name, valid now). Anything else is logged, once per distinct error rather than at every read, and the certificates in use are kept; renewal tools should replace the files atomically (write, then rename). Sessions already established are untouched. The CA is now checked at each handshake on both sides: as the dialed relay (`GetConfigForClient`) and as the dialer (`VerifyConnection` against the current CA, with the same checks crypto/tls made). The relay's key-set and usage requests are signed with the renewed peer certificate (`reqsign.Signer.Rotate`), and `qumo dns` re-reads its `PEER_CERT_FILE`/`PEER_KEY_FILE` on the same one-minute cadence and signs its feed reads with a renewed pair (`internal/certreload`, shared by both). New metrics: `qumo_relay_cert_reloads_total{cert,result}` and `qumo_relay_cert_not_after_seconds{cert}`, and `qumo_dns_cert_reloads_total{cert,result}` and `qumo_dns_cert_not_after_seconds{cert}`; alert on the `not_after` gauges. A CA is rotated by putting the new one beside the old in `CA_FILE` first ([TLS & mTLS](docs/site/content/en/docs/deployment/tls.md#certificate-renewal)). - - **A relay signs its key-set and usage requests, and `qumo dns` its feed reads, with its peer identity (`internal/reqsign`, #601).** With `PEER_CERT_FILE` and `PEER_KEY_FILE` (an ECDSA key; `qumo dns` takes the same two settings), each request carries `X-Relay-Certificate`, `X-Relay-Timestamp` and `X-Relay-Signature`: the key's ECDSA signature (ASN.1, base64) over SHA-256 of `qumo-relay-request`, the method, the request URI (path and query), the timestamp and the hex SHA-256 of the body, one per line, signed again on every retry. The receiver then knows which relay is calling from a key only that relay holds, and a captured request can't be changed or used for long, where a bearer token copied from a node could be reused until it is replaced. The bearer token (`QUMO_RELAY_TOKEN`, `QUMO_DNS_FEED_TOKEN`) is still sent beside it. A 401 is logged with the server's `Date` beside the local time. Funnel, HLS and ingest, which have no peer identity, are unchanged. ## [v0.20.261114] - 2026-11-14 diff --git a/README.md b/README.md index 079b553a..9c9c33d0 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ qumo rtmp # Start an RTMP ingest server (bridges RTMP → MoQT over TCP qumo rtsp # Pull from an RTSP source (e.g. an IP camera) and republish as MoQT qumo rtsp-push # Start the RTSP push ingest server (TCP :8554; bridges RTSP → MoQT) qumo hls # Start the HLS/DASH egress server (subscribes to a relay, serves HLS/DASH) -qumo abr # Transcode broadcasts into an ABR ladder with ffmpeg and republish them (renditions in one MSF altGroup) +qumo abr # Transcode broadcasts opted in beneath /.abr/ into an ABR ladder with ffmpeg (renditions in one MSF altGroup) qumo funnel # Funnel many HTTP senders into one MoQT track (announce + POST records) qumo playground # One-command local demo: in-process relay + embedded web UI on http://127.0.0.1:8080 qumo loadgen # Out-of-process capacity load generator (publish|subscribe) — see [docs/perf](docs/perf/README.md#benchmarking--capacity) diff --git a/cmd/seed-moq/main.go b/cmd/seed-moq/main.go index acba292f..83071efd 100644 --- a/cmd/seed-moq/main.go +++ b/cmd/seed-moq/main.go @@ -40,7 +40,7 @@ import ( "github.com/qumo-dev/qumo/internal/cmaf" "github.com/qumo-dev/qumo/internal/envconfig" - "github.com/qumo-dev/qumo/internal/hlsoptin" + "github.com/qumo-dev/qumo/internal/optin" "github.com/qumo-dev/qumo/internal/quicconfig" ) @@ -102,7 +102,7 @@ func main() { // Opt the broadcast into the HLS egress, which serves what is announced // beneath /.hls/. The opt-in has no tracks of its own: it redirects every // subscription to the broadcast, keeping the track name. - mux.Publish(ctx, moqt.BroadcastPath("/.hls"+path), hlsoptin.Handler(moqt.BroadcastPath(path))) + mux.Publish(ctx, moqt.BroadcastPath("/.hls"+path), optin.Handler(moqt.BroadcastPath(path))) httpMux := http.NewServeMux() httpMux.Handle("/", &moqt.WebTransportHandler{ diff --git a/docs/site/content/en/docs/cli/abr.md b/docs/site/content/en/docs/cli/abr.md index 87565ff5..a379ec8a 100644 --- a/docs/site/content/en/docs/cli/abr.md +++ b/docs/site/content/en/docs/cli/abr.md @@ -5,16 +5,50 @@ weight: 5 --- Transcodes the broadcasts on a relay into an adaptive-bitrate (ABR) ladder. -For every broadcast announced beneath `ABR_PREFIX`, it publishes an ABR -broadcast beside it, at the same path with `ABR_SUFFIX` appended -(`/live/cam1` → `/live/cam1.abr`). The ABR broadcast carries the source's -tracks as they are, plus one rendition per rung of the ladder that is shorter -than the source video, encoded by [ffmpeg](https://ffmpeg.org/). +A publisher opts a broadcast in as it opts one into [`qumo hls`]({{< relref "hls" >}}): +by announcing it again beneath `/.abr/` (`/.abr/live/cam1` for `/live/cam1`). +For every opt-in, `qumo abr` publishes an ABR broadcast beside the broadcast, +at the same path with `ABR_SUFFIX` appended (`/live/cam1.abr`). It carries the +source's tracks as they are, plus one rendition per rung of the ladder that is +shorter than the source video, encoded by [ffmpeg](https://ffmpeg.org/). + +## Opting in + +The opt-in carries no media. It answers every subscription with a redirect to +the broadcast, keeping the track name (`internal/optin`, the same handler as +the HLS opt-in). `qumo abr` reads the catalog through it and follows the +redirect only to the broadcast the opt-in names: an opt-in that redirects +elsewhere, or answers itself, is refused, so no one can have another +publisher's broadcast transcoded under their own name. Paths are compared +exactly, as the relay grants and routes them: an opt-in spelled with a +trailing or doubled slash, or a `.` or `..` segment, is refused rather than +read as the cleaned path it might name. Withdrawing the opt-in +withdraws the ABR broadcast; the broadcast itself plays on. + +### Paying for the opt-in + +Transcoding costs the operator, so the opt-in is an option a tenant holds, +not one every key has. A signing key confined to a prefix +(`qumo auth keygen -prefix acme/`) signs for the prefix's mirror beneath an +opt-in directory only when its entry in the relay's key set (`QUMO_AUTH_KEYS`) +lists that opt-in: + +```json +{ "kid": "…", "prefix": "/acme/", "optIns": ["hls", "abr"] } +``` + +A control plane that sells ABR sets `optIns` when the tenant pays and removes +`abr` when it stops. The relay re-reads the key set every 30 s, so a new opt-in +is refused within half a minute, and one on air ends at the next 30 s check of +live sessions. HLS is held the same way (`"hls"`), and a key whose entry lists +no `optIns` holds none. -An alias is not transcoded: a broadcast that answers subscriptions with a -redirect to another, such as the HLS opt-in a publisher announces beneath -`/.hls/`, is another name for the broadcast it points to, which is announced -and transcoded at its own path. +The tenant's app signs the opt-in's token with the same key as the +broadcast's: `/.abr/acme/live/cam1` beside `/acme/live/cam1`, presented on the +publisher's session as a ticket, since a session's credentials all come from +one key. The app needs no new key when its tenant pays; the relay refuses the +token until the key set lists `abr`. `qumo auth keygen -opt-ins hls,abr` writes +the member for a key set kept by hand. It dials the relay as an ordinary client: it subscribes to the source like any viewer and publishes the ABR broadcast like any publisher. The relay itself @@ -32,13 +66,14 @@ variables. Needs `ffmpeg` (or `ABR_FFMPEG`) on the host. ## Example ```console -$ RELAY_URL=https://relay:4433 ABR_PREFIX=/live/ ABR_LADDER=720:2500,360:800 qumo abr -INFO abr: starting relay=https://relay:4433 prefix=/live/ suffix=.abr ladder=720:2500,360:800 codec=libx264 +$ RELAY_URL=https://relay:4433 ABR_LADDER=720:2500,360:800 qumo abr +INFO abr: starting relay=https://relay:4433 opt_in=/.abr/ suffix=.abr ladder=720:2500,360:800 codec=libx264 INFO abr: connected to the relay -INFO abr: transcoding source=/live/cam1 abr=/live/cam1.abr +INFO abr: transcoding opt_in=/.abr/live/cam1 source=/live/cam1 abr=/live/cam1.abr ``` -A 1080p source at `/live/cam1` then has `/live/cam1.abr` beside it, whose +A 1080p source at `/live/cam1`, opted in at `/.abr/live/cam1`, then has +`/live/cam1.abr` beside it, whose catalog lists: | Track | Picture | Bitrate | From | @@ -53,7 +88,10 @@ catalog lists: - **One alternate group.** Every video track has `altGroup: 1` in the MSF catalog, with its `width`, `height`, `bitrate`, codec and decoder configuration (`initRef`), so a player knows they are alternatives of one - picture and what each costs. + picture and what each costs. The source's size is the one its catalog + states, or, when that states none (or a zero), the size decoded from its + video. An Annex B source's size is decoded only at its first keyframe, so its + entry has no size until then. - **Aligned groups.** Every rendition numbers its groups as the source does, and group N of each track starts at the same frame, with a keyframe. A player can leave one track after group N and join another at group N+1 @@ -80,10 +118,22 @@ held up by the encoder. ## Requirements -- The source video must be H.264 (`avc1`) **without B-frames**: LOC carries - presentation timestamps only, so frames must arrive in presentation order. - OBS and ffmpeg in their low-latency settings (`-bf 0`, `-tune zerolatency`) - qualify. +- The source video must be one of: + - H.264 (`avc1`) with its decoder configuration in the catalog and + length-prefixed frames, as RTMP and RTSP ingest publish it; + - H.264 (`avc1`) in Annex B, its parameter sets in the stream before each + keyframe, as a browser's WebCodecs encoder in `annexb` format sends it: + the configuration is read from the first keyframe, and the frames are + rewritten with lengths for ffmpeg; + - VP9 with a full codec string (`vp09.PP.LL.DD`) and its picture size in + the catalog, as a browser's hardware encoder often sends it. + + Renditions are H.264 whatever the source. Another codec is forwarded + without renditions. +- The source must have **no B-frames**: LOC carries presentation timestamps + only, so frames must arrive in presentation order. OBS and ffmpeg in their + low-latency settings (`-bf 0`, `-tune zerolatency`) and browser encoders in + `realtime` mode qualify. - `ABR_CODEC` must be an H.264 encoder, so browsers decode every rendition with the same decoder. @@ -91,11 +141,11 @@ held up by the encoder. | Variable | Default | Description | |---|---|---| -| `RELAY_URL` | `https://localhost:4433` | The relay to transcode broadcasts of, dialed as a client. It may carry a credential as `?jwt=` that grants subscribing to the sources and publishing the ABR broadcasts. | +| `RELAY_URL` | `https://localhost:4433` | The relay to transcode broadcasts of, dialed as a client. It may carry a credential as `?jwt=` that grants listing and subscribing to the opt-ins beneath `/.abr/` and the broadcasts they name, and publishing the ABR broadcasts. | +| `RELAY_SIGNING_KEY` | (unset) | A signing key (`qumo auth keygen`) the relay's key set trusts, for the whole namespace (prefix `/`). The transcoder signs a fresh credential with it on every dial, in place of any `?jwt=`, granting what it needs (subscribing anywhere, to read opt-ins and their broadcasts, and publishing the ABR broadcasts), and renews it on the session before it lapses. A credential fixed in `RELAY_URL` lapses with its token. | | `RELAY_CA_FILE` | (unset) | PEM certificate to trust as the relay's root, instead of the system roots. | | `RELAY_TLS_INSECURE` | `false` | Skip relay TLS verification, for a self-signed dev relay. | -| `ABR_PREFIX` | `/` | The directory whose broadcasts are transcoded. | -| `ABR_SUFFIX` | `.abr` | Appended to a source's path to name its ABR broadcast. Broadcasts already ending in it are not transcoded again, nor are aliases (broadcasts that redirect subscribers to another). | +| `ABR_SUFFIX` | `.abr` | Appended to a source's path to name its ABR broadcast. An opt-in for a broadcast already ending in it is ignored. | | `ABR_LADDER` | `720:2500,360:800` | The renditions: comma-separated `height:kbps`. Rungs as tall as the source or taller are skipped. | | `ABR_FFMPEG` | `ffmpeg` | The ffmpeg executable. | | `ABR_CODEC` | `libx264` | The ffmpeg H.264 encoder, e.g. `h264_nvenc` or `h264_vaapi` for hardware encoding. | diff --git a/docs/site/content/en/docs/cli/auth.md b/docs/site/content/en/docs/cli/auth.md index 49351d84..e31b3664 100644 --- a/docs/site/content/en/docs/cli/auth.md +++ b/docs/site/content/en/docs/cli/auth.md @@ -26,12 +26,13 @@ qumo auth [flags] ### keygen ``` -qumo auth keygen [-prefix /acme/app/] [-out signing-key.jwk] [-keys keys.json] +qumo auth keygen [-prefix /acme/app/] [-opt-ins hls,abr] [-out signing-key.jwk] [-keys keys.json] ``` | Flag | Default | Description | |---|---|---| -| `-prefix` | `/` (none) | Confine the key to a directory: the root of every token signed with it must lie at or beneath it, or beneath its mirror under `/.hls/` (`/.hls/acme/app/`, the [HLS opt-in]({{< relref "hls#opting-in-on-a-relay-with-auth-on" >}})), and so every path it grants. A bare path (`acme/app`) reads as the directory it names (`/acme/app/`), and a key set written with one still loads. | +| `-prefix` | `/` (none) | Confine the key to a directory: the root of every token signed with it must lie at or beneath it, or beneath its mirror under the directory of an opt-in it holds (`/.hls/acme/app/` with `-opt-ins hls`, the [HLS opt-in]({{< relref "hls#opting-in-on-a-relay-with-auth-on" >}}); `/.abr/acme/app/` with `-opt-ins abr`), and so every path it grants. A bare path (`acme/app`) reads as the directory it names (`/acme/app/`), and a key set written with one still loads. | +| `-opt-ins` | none | The opt-ins the key signs for, comma-separated (`hls`, `abr`), written to the key set as `optIns`: the key's prefix is mirrored beneath `/.hls/` and `/.abr/` only for the opt-ins listed, every one alike, and a key that lists none holds none. A control plane that sells an egress sets the member as its tenant pays ([ABR](../abr/#paying-for-the-opt-in)). | | `-out` | `signing-key.jwk` | The private signing key (an Ed25519 JWK). Keep it on your app's server. | | `-keys` | `keys.json` | The public key set (a JWK Set) for `QUMO_AUTH_KEYS`. | @@ -51,7 +52,7 @@ Signs a token granting, beneath `-root`, each action on the path patterns its fl A token grants what a MoQ grant does: a **`root`**, the directory of broadcast paths it applies to, and for each action the **path patterns** beneath the root its bearer may act on, on every track of each broadcast they match. It is gomoqt's `moqt.Grant`, so the relay hands the root and the `publish` and `subscribe` patterns to the session as they are. -- **`root`**: a directory of broadcast paths, written as MoQ writes one: `/acme/app/rooms/42/`, or `/` for every path. It must lie at or beneath the key's prefix, or beneath the prefix's mirror under `/.hls/` (`/.hls/acme/app/` for `/acme/app/`), and is refused in any other spelling: without its slashes, with a doubled one, or holding a `.` or `..` segment, `*`, `{` or `}`. Every pattern lies beneath it, so it confines what the token grants to the key's tenant. Its own path is not a broadcast: no pattern reaches it, so give each broadcast a path beneath a root, as a file lies in a directory. A key confined to `/acme/app/` can't grant the broadcast `/acme/app` itself. +- **`root`**: a directory of broadcast paths, written as MoQ writes one: `/acme/app/rooms/42/`, or `/` for every path. It must lie at or beneath the key's prefix, or beneath the prefix's mirror under the directory of an opt-in the key holds (`/.hls/acme/app/` for `/acme/app/` once the key set lists `hls`; `/.abr/acme/app/` once it lists `abr`), and is refused in any other spelling: without its slashes, with a doubled one, or holding a `.` or `..` segment, `*`, `{` or `}`. Every pattern lies beneath it, so it confines what the token grants to the key's tenant. Its own path is not a broadcast: no pattern reaches it, so give each broadcast a path beneath a root, as a file lies in a directory. A key confined to `/acme/app/` can't grant the broadcast `/acme/app` itself. - **`publish`**, **`subscribe`**, **`create`**, **`post`**, **`redact`**: each a list of patterns relative to the root, matching broadcast paths as `moqt.Grant` reads them, the way an `http.ServeMux` pattern matches URL paths. With the root `/acme/app/rooms/42/`, `/7` matches `/acme/app/rooms/42/7` alone, `/7/` every path beneath it, and `/` every path beneath the root (not the root itself). A segment may be a wildcard: `{name}` matches any one segment (`/{user}/audio`), `{name...}` as the last segment the rest of the path, and `{$}` as the last segment only the `/` before it. A pattern starts with `/` and may not hold a `.` or `..` segment; one that doesn't parse, or comes without a root, refuses the token. The actions are `publish` (sending a broadcast's tracks through a relay), `subscribe` (receiving a track, live or as history: a relay's FETCH and a funnel's `GET` read history with it), `post` (sending one message into a track that exists at a funnel, which gathers many senders into it and publishes it; a relay never reads it as publishing), `redact` (taking a record out of a funnel's track; for credentials the app keeps to itself) and `create` (creating a track at a [funnel](../funnel/#credentials), which the funnel then publishes; for the app, which decides which tracks a broadcast has). @@ -88,7 +89,7 @@ A ticket: - must be signed by **the same key** as the session's credential, so everything a session may do is one tenant's; - is verified as a credential is at connect, and a key paused with `"pause": ["publish"]` refuses one that may publish, unless the session has been granted what may publish already: a pause stops what is new, and a publisher on air renews its grant; -- is revoked too when its key leaves the set, or its key's prefix no longer holds its root, at the next 30 s check; +- is revoked too when its key leaves the set, or its key's prefix (and the opt-ins it holds) no longer holds its root, at the next 30 s check; - that could not be checked just now, as while the relay has no usable key set, is answered `AUTH_ERROR` with `INTERNAL` (`0x1`), which the client may retry; a refused one with `UNAUTHORIZED` (`0x2`); - is withdrawn by the client closing its Auth Stream, or by a later ticket for the same root ([below](#renewing-a-grant)); - is a bearer token, as a credential is: any session of the same key's tenant that holds it may present it. diff --git a/docs/site/content/en/docs/cli/hls.md b/docs/site/content/en/docs/cli/hls.md index 2f1e0ec6..ec3007bd 100644 --- a/docs/site/content/en/docs/cli/hls.md +++ b/docs/site/content/en/docs/cli/hls.md @@ -67,9 +67,12 @@ token of its own: `/.hls/acme/room/42/cam`, which a token rooted at `/acme/room/42/` doesn't cover; the opt-in is a token rooted at, e.g., `/.hls/acme/room/42/` with `publish` `/cam`. -- **Signed by the app's own key.** A key confined to `/acme/` also signs for - `/.hls/acme/`, so the opt-in needs no other key, and a client presents it - as a ticket on the session it publishes on. +- **Signed by the app's own key, once its key holds HLS.** A key confined to + `/acme/` signs for `/.hls/acme/` when its entry in the relay's key set lists + the opt-in (`"optIns": ["hls"]`, written by `qumo auth keygen -opt-ins hls` + or set by a control plane as its tenant pays), so the opt-in needs no other + key, and a client presents it as a ticket on the session it publishes on. A + key whose entry lists no `optIns` holds none: the relay refuses the token. - **The app decides.** Neither the relay nor the egress checks that the bearer publishes `/acme/room/42/cam`: the egress subscribes with its own grant. Issue an opt-in only for a broadcast the app means to serve over @@ -82,6 +85,7 @@ token of its own: ```bash # an opt-in for /acme/room/42/cam, signed by the app's key confined to /acme/ +# (its key set entry lists "optIns": ["hls"]) qumo auth token -key signing-key.jwk -root /.hls/acme/room/42/ -publish /cam ``` diff --git a/internal/abr/annexb_pipeline_test.go b/internal/abr/annexb_pipeline_test.go new file mode 100644 index 00000000..4ce2f832 --- /dev/null +++ b/internal/abr/annexb_pipeline_test.go @@ -0,0 +1,104 @@ +package abr + +import ( + "context" + "testing" + "time" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/qumo-dev/gomoqt/msf" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/qumo-dev/qumo/internal/cmaf" + "github.com/qumo-dev/qumo/internal/optin" +) + +// serveOneGroup serves body as the one frame of one group, then holds the +// track open until the subscriber leaves. +func serveOneGroup(tw *moqt.TrackWriter, body []byte) { + gw, err := tw.OpenGroup(tw.Context()) + if err != nil { + return + } + frame := moqt.NewFrame(len(body)) + _, _ = frame.Write(body) // not actionable: the test asserts what the pipeline read + _ = gw.WriteFrame(frame) // not actionable: as above + _ = gw.Close() // not actionable: as above + <-tw.Context().Done() +} + +// A browser's source (Annex B H.264, no size in its catalog) is published +// through the whole pipeline with no size or label until its first keyframe, +// then with the size decoded from that keyframe's parameter sets. Its ladder +// has no rung below the source, so no encoder (nor ffmpeg) starts. +func TestRun_AnnexBSourceSizedAtFirstKeyframe(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + defer cancel() + + catalog, err := msf.Catalog{Version: 1, Tracks: []msf.Track{{ + Name: "video", Role: msf.RoleVideo, Packaging: msf.PackagingLOC, IsLive: new(true), Codec: "avc1.42c01e", + }}}.MarshalJSON() + require.NoError(t, err) + sps, pps := parameterSets(t, avcRecord360p) + keyframe := cmaf.EncodeLOC(1_000_000, annexB(sps, pps, []byte{0x65, 0x88, 0x84, 0x00})) + release := make(chan struct{}) + + source := moqt.NewTrackMux(0) + source.PublishFunc(ctx, "/live/cam", func(tw *moqt.TrackWriter) { + switch tw.TrackName { + case msf.DefaultCatalogTrackName: + serveOneGroup(tw, catalog) + case "video": + select { + case <-release: + serveOneGroup(tw, keyframe) + case <-tw.Context().Done(): + } + default: + tw.CloseWithError(moqt.SubscribeErrorCodeNotFound) + } + }) + source.Publish(ctx, "/.abr/live/cam", optin.Handler("/live/cam")) + sess := loopbackSession(t, ctx, source) + + out := moqt.NewTrackMux(0) + done := make(chan error, 1) + go func() { + done <- run(ctx, sess, out, "/.abr/live/cam", "/live/cam", "/live/cam.abr", Config{Ladder: []Rung{{Height: 720, Bitrate: 2_500_000}}}) + }() + sourceRendition := func() (msf.Track, bool) { + _, h := out.TrackHandler("/live/cam.abr") + o, ok := h.(*outputBroadcast) + if !ok { + return msf.Track{}, false + } + for _, tr := range o.b.Catalog().Tracks { + if tr.Name == "video" { + return tr, true + } + } + return msf.Track{}, false + } + + require.Eventually(t, func() bool { _, ok := sourceRendition(); return ok }, 10*time.Second, 20*time.Millisecond, + "the source rendition is published before its first keyframe") + before, _ := sourceRendition() + assert.Nil(t, before.Width, "no size is known yet") + assert.Nil(t, before.Height) + assert.Empty(t, before.Label) + + close(release) + require.Eventually(t, func() bool { tr, _ := sourceRendition(); return tr.Height != nil }, 10*time.Second, 20*time.Millisecond, + "sized at the first keyframe") + after, _ := sourceRendition() + require.NotNil(t, after.Width) + assert.EqualValues(t, 640, *after.Width) + assert.EqualValues(t, 360, *after.Height) + assert.Equal(t, "360p (source)", after.Label) + require.NotNil(t, after.AltGroup) + assert.EqualValues(t, videoAltGroup, *after.AltGroup) + + cancel() + <-done +} diff --git a/internal/abr/cmd.go b/internal/abr/cmd.go index 973fbab3..399c99c1 100644 --- a/internal/abr/cmd.go +++ b/internal/abr/cmd.go @@ -14,12 +14,16 @@ import ( "syscall" "time" + "github.com/quic-go/quic-go" "github.com/qumo-dev/gomoqt/moqt" "github.com/qumo-dev/qumo/internal/envconfig" + "github.com/qumo-dev/qumo/internal/optin" "github.com/qumo-dev/qumo/internal/quicconfig" + "github.com/qumo-dev/qumo/internal/relaycred" "github.com/qumo-dev/qumo/internal/tlsclient" "github.com/qumo-dev/qumo/internal/upstream" + "github.com/qumo-dev/qumo/token" ) // retryInterval is how long to wait before dialing the relay again, or @@ -27,25 +31,34 @@ import ( const retryInterval = 2 * time.Second // Run starts the ABR transcoder. It connects to a relay, and for every -// broadcast announced beneath ABR_PREFIX publishes an ABR broadcast beside it, -// at the same path with ABR_SUFFIX appended (/live/cam1 → /live/cam1.abr): the -// source's tracks as they are, plus each rendition of the ladder shorter than -// the source video, encoded by ffmpeg. Every video track is in one MSF -// alternate group, and every rendition numbers its groups as the source does, -// so a player can switch between them at any group boundary. +// broadcast a publisher opts in, by announcing it beneath token.ABRDirectory +// (/.abr/live/cam1 for /live/cam1) as qumo hls is opted into beneath /.hls/, +// publishes an ABR broadcast beside it, at the same path with ABR_SUFFIX +// appended (/live/cam1.abr): the source's tracks as they are, plus each +// rendition of the ladder shorter than the source video, encoded by ffmpeg. +// Every video track is in one MSF alternate group, and every rendition numbers +// its groups as the source does, so a player can switch between them at any +// group boundary. +// +// The opt-in carries no media: it redirects every subscription to the +// broadcast (see internal/optin), and the transcoder follows a redirect only +// there. A publisher opts in only what it may publish: a key confined to a +// prefix signs for the prefix's mirror beneath /.abr/ once its key set entry +// holds the abr opt-in (token.Key.OptIns). // // Configuration is read from environment variables (qumo convention): // // RELAY_URL - the relay, e.g. "https://relay:4433" (default "https://localhost:4433"); -// it may carry a credential as ?jwt= that grants subscribing -// to the sources and publishing the ABR broadcasts +// it may carry a credential as ?jwt= granting what RelayGrant +// does, which lapses with it +// RELAY_SIGNING_KEY - a signing key (qumo auth keygen) the relay's key set trusts, +// for the whole namespace (prefix "/"): the transcoder signs a +// credential granting RelayGrant with it on every dial, in place +// of any ?jwt=, and a fresh one on the session before it lapses // RELAY_CA_FILE - PEM cert to trust as the relay's root (default: the system roots) // RELAY_TLS_INSECURE - skip relay TLS verification, for a self-signed dev relay (default "false") -// ABR_PREFIX - the directory whose broadcasts are transcoded (default "/") // ABR_SUFFIX - appended to a source's path to name its ABR broadcast (default ".abr"); -// broadcasts already ending in it are not transcoded again, nor are -// aliases: broadcasts that redirect subscribers to another, such as -// HLS opt-ins (only the broadcast they name is) +// an opt-in for a broadcast already ending in it is ignored // ABR_LADDER - the renditions, height:kbps, comma-separated (default "720:2500,360:800") // ABR_FFMPEG - the ffmpeg executable (default "ffmpeg") // ABR_CODEC - the ffmpeg H.264 encoder (default "libx264"; e.g. "h264_nvenc") @@ -53,7 +66,9 @@ const retryInterval = 2 * time.Second // QUIC_* - QUIC transport settings of the session to the relay // (quicconfig.FromEnv lists them) // -// The source video must be H.264 (avc1) without B-frames. +// The source video must be H.264 (avc1: AVCC with its configuration in the +// catalog, or Annex B with its parameter sets in the stream) or VP9, without +// B-frames. Renditions are H.264. func Run(_ []string) error { ladder, err := ParseLadder(envconfig.String("ABR_LADDER", DefaultLadder)) if err != nil { @@ -73,10 +88,6 @@ func Run(_ []string) error { if _, err := exec.LookPath(cfg.Encoder.FFmpeg); err != nil { return fmt.Errorf("abr: ABR_FFMPEG: %w", err) } - prefix := envconfig.String("ABR_PREFIX", "/") - if !strings.HasPrefix(prefix, "/") { - return fmt.Errorf("abr: ABR_PREFIX %q must start with /", prefix) - } suffix := envconfig.String("ABR_SUFFIX", ".abr") if suffix == "" { return errors.New("abr: ABR_SUFFIX must not be empty: the ABR broadcast would replace its source") @@ -92,21 +103,31 @@ func Run(_ []string) error { if err := tlsclient.Apply(tc, envconfig.String("RELAY_CA_FILE", ""), envconfig.String("RELAY_TLS_INSECURE", "false") == "true"); err != nil { return fmt.Errorf("abr: relay TLS: %w", err) } + d := relayDialer{url: relayURL, tls: tc, quic: quicConfig} + if keyFile := envconfig.String("RELAY_SIGNING_KEY", ""); keyFile != "" { + key, err := token.LoadSigningKey(keyFile) + if err != nil { + return fmt.Errorf("abr: RELAY_SIGNING_KEY: %w", err) + } + if err := checkSigningKey(key); err != nil { + return fmt.Errorf("abr: RELAY_SIGNING_KEY: %w", err) + } + d.key = &key + } ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer cancel() t := &Transcoder{ - Prefix: prefix, Suffix: suffix, Config: cfg, } - slog.Info("abr: starting", "relay", upstream.RelayName(relayURL), "prefix", prefix, "suffix", suffix, + slog.Info("abr: starting", "relay", upstream.RelayName(relayURL), "opt_in", token.ABRDirectory, "suffix", suffix, "ladder", envconfig.String("ABR_LADDER", DefaultLadder), "codec", cfg.Encoder.Codec) for { // A TrackMux per session, so a session's ABR broadcasts end with it. mux := moqt.NewTrackMux(0) - sess, err := (&moqt.Dialer{TLSConfig: tc.Clone(), QUICConfig: quicConfig}).Dial(ctx, relayURL, mux) + sess, err := d.dial(ctx, mux) if err == nil { slog.Info("abr: connected to the relay") err = t.Serve(ctx, sess, mux) @@ -125,38 +146,99 @@ func Run(_ []string) error { } } -// A Transcoder publishes an ABR broadcast for every broadcast announced -// beneath Prefix. +// RelayGrant is what the transcoder's session to the relay needs: listing +// and subscribing to the opt-ins beneath token.ABRDirectory and the +// broadcasts they name, and publishing the ABR broadcasts beside those. The +// opt-ins and the broadcasts lie anywhere, so the grant is the whole +// namespace. +func RelayGrant() token.Grant { + return token.Grant{Root: "/", Subscribe: []string{"/"}, Publish: []string{"/"}} +} + +// checkSigningKey reports why key cannot sign the transcoder's credential: +// confined to less than the whole namespace, which RelayGrant needs. +func checkSigningKey(key token.SigningKey) error { + if p := key.Prefix; p != "" && p != "/" { + return fmt.Errorf("the key is confined to %q, but the transcoder reads the opt-ins beneath %q and the broadcasts they name, and publishes beside them: use a key for the whole namespace (prefix \"/\")", + p, token.ABRDirectory) + } + return nil +} + +// relayDialer opens the transcoder's sessions to the relay. +type relayDialer struct { + url string + tls *tls.Config + quic *quic.Config + // key, when set, signs a credential granting RelayGrant for each + // session in place of any ?jwt= in url, and a fresh one on the session + // before its grant lapses. + key *token.SigningKey +} + +// dial opens a session to the relay serving mux. +func (d relayDialer) dial(ctx context.Context, mux *moqt.TrackMux) (*moqt.Session, error) { + target, lapses, err := d.target() + if err != nil { + return nil, err + } + sess, err := (&moqt.Dialer{TLSConfig: d.tls.Clone(), QUICConfig: d.quic}).Dial(ctx, target, mux) + if err != nil { + return nil, fmt.Errorf("abr: dial relay: %w", err) + } + if d.key != nil { + go relaycred.Keep(sess, *d.key, RelayGrant(), lapses) + } + return sess, nil +} + +// target returns the URL to dial, carrying a freshly signed credential when +// the transcoder signs its own, and when that credential's grant lapses (zero +// for none). +func (d relayDialer) target() (string, time.Time, error) { + if d.key == nil { + return d.url, time.Time{}, nil + } + return relaycred.Target(d.url, *d.key, RelayGrant()) +} + +// A Transcoder publishes an ABR broadcast for every broadcast opted in +// beneath token.ABRDirectory. type Transcoder struct { - // Prefix is the directory whose broadcasts are transcoded. - Prefix string // Suffix is appended to a source's path to name its ABR broadcast. Suffix string // Config is what each pipeline makes of its source. Config Config } -// Serve transcodes the broadcasts sess announces beneath Prefix, publishing the -// ABR broadcasts on mux, the TrackMux sess was dialed with, until ctx or sess -// ends. +// Serve transcodes the broadcasts opted in beneath token.ABRDirectory on +// sess, publishing the ABR broadcasts on mux, the TrackMux sess was dialed +// with, until ctx or sess ends. func (t *Transcoder) Serve(ctx context.Context, sess *moqt.Session, mux *moqt.TrackMux) error { ctx, cancel := context.WithCancel(ctx) defer cancel() stop := context.AfterFunc(sess.Context(), cancel) defer stop() - ar, err := sess.AcceptAnnounce(t.Prefix) + ar, err := sess.AcceptAnnounce(token.ABRDirectory) if err != nil { - return fmt.Errorf("abr: accept announcements: %w", err) + return fmt.Errorf("abr: accept opt-ins: %w", err) } defer ar.Close() // not actionable: the session is ending var wg sync.WaitGroup defer wg.Wait() for ann := range ar.Announcements(ctx) { - src := ann.BroadcastPath() - if strings.HasSuffix(string(src), t.Suffix) { - continue // an ABR broadcast, perhaps this transcoder's own + optIn := ann.BroadcastPath() + src, ok := optedIn(optIn) + if !ok { + slog.Warn("abr: refusing opt-in: not spelled as its broadcast's opt-in", "opt_in", optIn, "broadcast", src) + continue + } + if src == "/" || strings.HasSuffix(string(src), t.Suffix) { + // No broadcast, or an ABR broadcast: it is not transcoded again. + slog.Info("abr: ignoring opt-in", "opt_in", optIn) + continue } dst := moqt.BroadcastPath(string(src) + t.Suffix) wg.Go(func() { @@ -164,24 +246,38 @@ func (t *Transcoder) Serve(ctx context.Context, sess *moqt.Session, mux *moqt.Tr defer cancel() stop := ann.AfterFunc(cancel) defer stop() - t.transcode(annCtx, sess, mux, src, dst) + t.transcode(annCtx, sess, mux, optIn, src, dst) }) } return context.Cause(ctx) } -// transcode runs the pipeline for src until ctx ends, restarting it when it -// fails while src is still announced. -func (t *Transcoder) transcode(ctx context.Context, sess *moqt.Session, mux *moqt.TrackMux, src, dst moqt.BroadcastPath) { +// optedIn returns the broadcast the opt-in optIn names, and false when optIn +// is not that broadcast's opt-in exactly as optin.Path spells it. A relay +// tells broadcasts apart, and grants them, by their exact paths, and the +// transcoder may read every one: /.abr/acme/../victim/cam is granted beneath +// /.abr/acme/, yet would name /victim/cam, and a doubled or trailing slash +// names a broadcast other than the cleaned one the transcoder would read. +func optedIn(optIn moqt.BroadcastPath) (moqt.BroadcastPath, bool) { + b, ok := optin.Broadcast(string(optIn), token.ABRDirectory) + src := moqt.BroadcastPath(b) + return src, ok && (src == "/" || optin.Path(token.ABRDirectory, src) == optIn) +} + +// transcode runs the pipeline for src, opted in as optIn, until ctx ends, +// restarting it when it fails while the opt-in is still announced. +func (t *Transcoder) transcode(ctx context.Context, sess *moqt.Session, mux *moqt.TrackMux, optIn, src, dst moqt.BroadcastPath) { for { - slog.Info("abr: transcoding", "source", src, "abr", dst) - err := run(ctx, sess, mux, src, dst, t.Config) + slog.Info("abr: transcoding", "opt_in", optIn, "source", src, "abr", dst) + err := run(ctx, sess, mux, optIn, src, dst, t.Config) if ctx.Err() != nil { - slog.Info("abr: source ended", "source", src) + slog.Info("abr: opt-in ended", "opt_in", optIn) return } - if alias, ok := errors.AsType[*AliasError](err); ok { - slog.Info("abr: not transcoding an alias", "source", src, "redirects_to", alias.Target) + if mis, ok := errors.AsType[*MisdirectedError](err); ok { + // Not worth retrying: the opt-in names another broadcast than + // the one it would have transcoded. + slog.Warn("abr: refusing opt-in", "error", mis) return } if err == nil { diff --git a/internal/abr/cmd_test.go b/internal/abr/cmd_test.go new file mode 100644 index 00000000..c8d4be47 --- /dev/null +++ b/internal/abr/cmd_test.go @@ -0,0 +1,101 @@ +package abr + +import ( + "net/url" + "testing" + "time" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/qumo-dev/qumo/token" +) + +func TestRelayGrant(t *testing.T) { + g := RelayGrant() + assert.Equal(t, "/", g.Root) + for _, path := range []string{"/.abr/live/cam1", "/live/cam1"} { + assert.True(t, g.Allows(token.ActionSubscribe, path), "subscribe %s", path) + } + assert.True(t, g.Allows(token.ActionPublish, "/live/cam1.abr")) +} + +func TestCheckSigningKey(t *testing.T) { + whole, err := token.GenerateKey("/") + require.NoError(t, err) + assert.NoError(t, checkSigningKey(whole)) + + tenant, err := token.GenerateKey("/acme/") + require.NoError(t, err) + assert.ErrorContains(t, checkSigningKey(tenant), "whole namespace", + "a tenant's key cannot reach the opt-ins beneath /.abr/") +} + +// An opt-in names its broadcast only when spelled exactly as that +// broadcast's opt-in: a relay grants and routes exact paths, so one that +// cleans to another broadcast (a ".." climbing out of the publisher's own +// directory) is refused rather than read with the transcoder's grant. +func TestOptedIn(t *testing.T) { + tests := map[string]struct { + optIn moqt.BroadcastPath + want moqt.BroadcastPath + wantOK bool + }{ + "a broadcast": {optIn: "/.abr/live/cam1", want: "/live/cam1", wantOK: true}, + "a single segment": {optIn: "/.abr/cam", want: "/cam", wantOK: true}, + "the bare directory": {optIn: "/.abr", want: "/", wantOK: true}, + "the directory, trailing slash": {optIn: "/.abr/", want: "/", wantOK: true}, + "a trailing slash": {optIn: "/.abr/live/cam1/", want: "/live/cam1", wantOK: false}, + "a doubled slash": {optIn: "/.abr/live//cam1", want: "/live/cam1", wantOK: false}, + "a dot segment": {optIn: "/.abr/live/./cam1", want: "", wantOK: false}, + "climbing into another's": {optIn: "/.abr/acme/../victim/cam", want: "", wantOK: false}, + "climbing out of the directory": {optIn: "/.abr/../victim/cam", want: "", wantOK: false}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + got, ok := optedIn(tt.optIn) + assert.Equal(t, tt.want, got) + assert.Equal(t, tt.wantOK, ok) + }) + } +} + +func TestRelayDialerTarget(t *testing.T) { + t.Run("without a key, the URL as given", func(t *testing.T) { + d := relayDialer{url: "https://relay:4433/?jwt=fixed"} + target, lapses, err := d.target() + require.NoError(t, err) + assert.Equal(t, "https://relay:4433/?jwt=fixed", target) + assert.True(t, lapses.IsZero()) + }) + + t.Run("with a key, a fresh credential in place of ?jwt=", func(t *testing.T) { + key, err := token.GenerateKey("/") + require.NoError(t, err) + d := relayDialer{url: "https://relay:4433/?jwt=stale&x=1", key: &key} + before := time.Now() + target, lapses, err := d.target() + require.NoError(t, err) + + u, err := url.Parse(target) + require.NoError(t, err) + assert.Equal(t, "1", u.Query().Get("x"), "the rest of the query is kept") + credential := u.Query().Get("jwt") + require.NotEqual(t, "stale", credential) + + c, err := token.Verify(credential, map[string]token.Key{key.ID: key.Public()}, time.Now()) + require.NoError(t, err) + assert.Equal(t, RelayGrant(), c.Grant) + assert.WithinDuration(t, before.Add(token.MaxLifetime), lapses, time.Minute) + }) + + t.Run("an invalid URL does not echo its credential", func(t *testing.T) { + key, err := token.GenerateKey("/") + require.NoError(t, err) + d := relayDialer{url: "https://relay:4433/%zz?jwt=secret", key: &key} + _, _, err = d.target() + require.Error(t, err) + assert.NotContains(t, err.Error(), "secret") + }) +} diff --git a/internal/abr/output.go b/internal/abr/output.go index 96731233..7a67bc12 100644 --- a/internal/abr/output.go +++ b/internal/abr/output.go @@ -96,12 +96,25 @@ func (o *outputBroadcast) addTrack(t msf.Track, init []byte, info moqt.PublishIn // setBitrate states the bitrate of the track named name in the catalog. func (o *outputBroadcast) setBitrate(name string, bitrate int64) error { + return o.update(name, func(t *msf.Track) { t.Bitrate = new(bitrate) }) +} + +// setSize states the size and label of the track named name in the catalog, +// once it is known after the track was added. +func (o *outputBroadcast) setSize(name string, width, height int64, label string) error { + return o.update(name, func(t *msf.Track) { + t.Width, t.Height, t.Label = new(width), new(height), label + }) +} + +// update changes the catalog entry of the track named name with change. +func (o *outputBroadcast) update(name string, change func(*msf.Track)) error { o.mu.Lock() defer o.mu.Unlock() catalog := o.b.Catalog() for i := range catalog.Tracks { if catalog.Tracks[i].Name == name { - catalog.Tracks[i].Bitrate = new(bitrate) + change(&catalog.Tracks[i]) return o.b.SetCatalog(catalog) } } diff --git a/internal/abr/output_test.go b/internal/abr/output_test.go index fa49ffba..1c728e64 100644 --- a/internal/abr/output_test.go +++ b/internal/abr/output_test.go @@ -83,3 +83,23 @@ func TestOutputBroadcastSetBitrate(t *testing.T) { assert.Error(t, o.setBitrate("nope", 1)) } + +// A size learned after the track was added (an Annex B source's) is stated +// in the catalog, keeping what else the entry states. +func TestOutputBroadcastSetSize(t *testing.T) { + o, err := newOutputBroadcast() + require.NoError(t, err) + defer o.close() + require.NoError(t, o.addTrack(msf.Track{Name: "video", Packaging: msf.PackagingLOC, Role: msf.RoleVideo, IsLive: new(true), Codec: "avc1.42c01e"}, nil, defaultVideoInfo, newTrack())) + + require.NoError(t, o.setSize("video", 640, 360, "360p (source)")) + got := catalogTrack(t, o, "video") + require.NotNil(t, got.Width) + require.NotNil(t, got.Height) + assert.EqualValues(t, 640, *got.Width) + assert.EqualValues(t, 360, *got.Height) + assert.Equal(t, "360p (source)", got.Label) + assert.Equal(t, "avc1.42c01e", got.Codec) + + assert.Error(t, o.setSize("nope", 1, 1, "")) +} diff --git a/internal/abr/pipeline.go b/internal/abr/pipeline.go index 0ddf7043..993c3ddf 100644 --- a/internal/abr/pipeline.go +++ b/internal/abr/pipeline.go @@ -27,15 +27,17 @@ type Config struct { Encoder EncoderConfig } -// An AliasError reports that a source broadcast is an alias of another: it -// answers subscriptions with a redirect to Target, as an HLS opt-in does. -// An alias is not transcoded; Target, announced at its own path, is. -type AliasError struct { - Alias, Target moqt.BroadcastPath +// A MisdirectedError reports that an opt-in redirected the transcoder +// elsewhere than to the broadcast it names, or answered itself, or that a +// track of that broadcast redirected elsewhere: the transcoder reads only the +// broadcast an opt-in names, so an opt-in cannot have another's broadcast +// transcoded under its name. +type MisdirectedError struct { + OptIn, Broadcast, To moqt.BroadcastPath } -func (e *AliasError) Error() string { - return fmt.Sprintf("abr: %s redirects to %s", e.Alias, e.Target) +func (e *MisdirectedError) Error() string { + return fmt.Sprintf("abr: the opt-in %s leads to %s, not %s", e.OptIn, e.To, e.Broadcast) } // encodeQueue is how many source frames may wait for the encoder. Past it the @@ -45,10 +47,11 @@ const encodeQueue = 120 // pipeline turns one source broadcast into its output broadcast. type pipeline struct { - sess *moqt.Session - src moqt.BroadcastPath - cfg Config - out *outputBroadcast + sess *moqt.Session + optIn moqt.BroadcastPath // the opt-in the catalog is read through + src moqt.BroadcastPath + cfg Config + out *outputBroadcast // started names the source tracks being handled, and transcoding // reports that one of them is being transcoded. Only the catalog @@ -57,9 +60,10 @@ type pipeline struct { transcoding bool } -// run runs the pipeline for src until ctx ends or the source broadcast ends, -// publishing the output broadcast at dst on mux while it runs. -func run(ctx context.Context, sess *moqt.Session, mux *moqt.TrackMux, src, dst moqt.BroadcastPath, cfg Config) error { +// run runs the pipeline for src, opted in as optIn, until ctx ends or the +// source broadcast ends, publishing the output broadcast at dst on mux while +// it runs. +func run(ctx context.Context, sess *moqt.Session, mux *moqt.TrackMux, optIn, src, dst moqt.BroadcastPath, cfg Config) error { out, err := newOutputBroadcast() if err != nil { return err @@ -68,28 +72,42 @@ func run(ctx context.Context, sess *moqt.Session, mux *moqt.TrackMux, src, dst m ctx, cancel := context.WithCancel(ctx) defer cancel() + + p := &pipeline{sess: sess, optIn: optIn, src: src, cfg: cfg, out: out, started: map[string]bool{}} + // The ABR broadcast is announced once its source is reached, so an + // opt-in whose broadcast is gone announces nothing while it is retried. + catalog, err := p.subscribeCatalog(ctx) + if err != nil { + return err + } + defer catalog.Close() // not actionable: the pipeline is ending mux.Publish(ctx, dst, out) - p := &pipeline{sess: sess, src: src, cfg: cfg, out: out, started: map[string]bool{}} g, ctx := errgroup.WithContext(ctx) - g.Go(func() error { return p.followCatalog(ctx, g) }) + g.Go(func() error { return p.followCatalog(ctx, g, catalog) }) return g.Wait() } -// followCatalog reads the source's catalog, and each update of it, and starts -// handling every track as it first appears in it. It returns when the source -// ends its catalog track. -func (p *pipeline) followCatalog(ctx context.Context, g *errgroup.Group) error { - tr, err := p.sess.Subscribe(ctx, p.src, msf.DefaultCatalogTrackName, &moqt.SubscribeConfig{Ordered: true}) +// subscribeCatalog subscribes to the source's catalog through the opt-in, +// which must redirect to the source. +func (p *pipeline) subscribeCatalog(ctx context.Context) (*moqt.TrackReader, error) { + tr, err := p.sess.Subscribe(ctx, p.optIn, msf.DefaultCatalogTrackName, &moqt.SubscribeConfig{Ordered: true}) if err != nil { - return fmt.Errorf("abr: subscribe catalog: %w", err) + return nil, fmt.Errorf("abr: subscribe catalog through the opt-in %s: %w", p.optIn, err) } - defer tr.Close() // not actionable: the pipeline is ending if tr.BroadcastPath != p.src { - // The source redirected the subscription: it is another name for a - // broadcast, which is transcoded under its own name. - return &AliasError{Alias: p.src, Target: tr.BroadcastPath} + // The opt-in redirected elsewhere than to its broadcast, or did not + // redirect at all: its media would not be the broadcast's. + _ = tr.Close() // not actionable: refused either way + return nil, &MisdirectedError{OptIn: p.optIn, Broadcast: p.src, To: tr.BroadcastPath} } + return tr, nil +} + +// followCatalog reads the source's catalog from tr, and each update of it, +// and starts handling every track as it first appears in it. It returns when +// the source ends its catalog track. +func (p *pipeline) followCatalog(ctx context.Context, g *errgroup.Group, tr *moqt.TrackReader) error { f := moqt.NewFrame(0) for { gr, err := tr.AcceptGroup(ctx) @@ -121,9 +139,10 @@ func (p *pipeline) followCatalog(ctx context.Context, g *errgroup.Group) error { if err != nil { slog.Warn("abr: source track has unusable init data; forwarding it without", "broadcast", p.src, "track", t.Name, "error", err) } - if t.Role == msf.RoleVideo && !p.transcoding && isAVC(t.Codec) && init != nil { + format, transcodable := formatOf(t, init) + if t.Role == msf.RoleVideo && !p.transcoding && transcodable { p.transcoding = true - g.Go(func() error { return p.transcode(ctx, t, init) }) + g.Go(func() error { return p.transcode(ctx, t, init, format) }) } else { g.Go(func() error { return p.forward(ctx, t, init) }) } @@ -170,6 +189,37 @@ func outputTrack(t msf.Track) msf.Track { return t } +// sourceSize returns the size of the source video track t, whose decoded +// configuration is sc (nil until known): the catalog's when it states a +// positive width and height, else sc's, and false when neither is known. A +// size of zero names no picture, so a catalog stating one states none. +func sourceSize(t msf.Track, sc *sourceConfig) (width, height int, ok bool) { + if t.Width != nil && t.Height != nil && *t.Width > 0 && *t.Height > 0 { + return int(*t.Width), int(*t.Height), true + } + if sc != nil && sc.Width > 0 && sc.Height > 0 { + return sc.Width, sc.Height, true + } + return 0, 0, false +} + +// sourceRendition returns the catalog entry of the source video track t as +// the top rendition, sized by sourceSize, and labelled by its height when t +// has no label. Without a known size it states none, rather than the +// catalog's unusable one. +func sourceRendition(t msf.Track, sc *sourceConfig) msf.Track { + src := outputTrack(t) + src.AltGroup = new(int64(videoAltGroup)) + src.Width, src.Height = nil, nil + if width, height, ok := sourceSize(t, sc); ok { + src.Width, src.Height = new(int64(width)), new(int64(height)) + if src.Label == "" { + src.Label = fmt.Sprintf("%dp (source)", height) + } + } + return src +} + // forward republishes a source track as it is, group for group. func (p *pipeline) forward(ctx context.Context, t msf.Track, init []byte) error { def := defaultAudioInfo @@ -199,6 +249,12 @@ func (p *pipeline) readTrack(ctx context.Context, name string, return fmt.Errorf("abr: subscribe %s: %w", name, err) } defer tr.Close() // not actionable: the pipeline is ending + if tr.BroadcastPath != p.src { + // The session follows redirects, and the transcoder may read every + // broadcast: followed elsewhere, a source could have another's + // media published as its own renditions. + return &MisdirectedError{OptIn: p.optIn, Broadcast: p.src, To: tr.BroadcastPath} + } // The sequence of the last group read; read reports there has been one, // so a first group numbered 0 is read rather than taken as seen. @@ -232,31 +288,118 @@ func (p *pipeline) readTrack(ctx context.Context, name string, } // transcode forwards the source video track and encodes it into the -// renditions of the ladder shorter than it. -func (p *pipeline) transcode(ctx context.Context, t msf.Track, init []byte) error { - cfg, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, init...)) +// renditions of the ladder shorter than it. The encoders start once the +// source's configuration is known: at once, or for an Annex B source at its +// first keyframe. +func (p *pipeline) transcode(ctx context.Context, t msf.Track, init []byte, format sourceFormat) error { + in, err := newSource(t, init, format) if err != nil { - return fmt.Errorf("abr: source decoder configuration: %w", err) - } - width, height := cfg.Width, cfg.Height - if t.Width != nil && t.Height != nil && *t.Width > 0 && *t.Height > 0 { - width, height = int(*t.Width), int(*t.Height) + return err } info := p.publishInfo(ctx, t.Name, defaultVideoInfo) // The source itself is the top rendition. - src := outputTrack(t) - src.AltGroup = new(int64(videoAltGroup)) - src.Width, src.Height = new(int64(width)), new(int64(height)) - if src.Label == "" { - src.Label = fmt.Sprintf("%dp (source)", height) - } + src := sourceRendition(t, in.config) srcOut := newTrack() defer srcOut.close() if err := p.out.addTrack(src, init, info, srcOut); err != nil { return err } + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + var enc *encoding + defer func() { + if enc != nil { + enc.closeTracks() + } + }() + startEncoding := func(sc sourceConfig) bool { + if src.Height == nil { + // Published before its size was known (an Annex B source whose + // catalog states none): state the decoded one now. + if sized := sourceRendition(t, &sc); sized.Height != nil { + if err := p.out.setSize(src.Name, *sized.Width, *sized.Height, sized.Label); err != nil { + slog.Warn("abr: state source size", "error", err) + } + } + } + width, height, _ := sourceSize(t, &sc) + slog.Info("abr: encoding renditions", "broadcast", p.src, "source", format, "width", width, "height", height) + e, err := p.startEncoding(ctx, sc, width, height, info) + if err != nil { + cancel(err) + return false + } + enc = e + return true + } + if in.config != nil && !startEncoding(*in.config) { + return context.Cause(ctx) + } + + rate := newBitrateMeter() + dropping := false + err = p.readTrack(ctx, t.Name, srcOut.openGroup, func(seq moqt.GroupSequence, i int, f *moqt.Frame) { + srcOut.writeFrame(f) + ts, data, err := cmaf.DecodeLOC(f.Body()) + if err != nil { + slog.Warn("abr: source frame is not LOC", "broadcast", p.src, "error", err) + return + } + if bps, ok := rate.add(ts, len(data), i == 0); ok { + if err := p.out.setBitrate(src.Name, bps); err != nil { + slog.Warn("abr: state source bitrate", "error", err) + } + } + data, ok := in.frame(data, i == 0) + if !ok { + return // not decodable yet, before the first keyframe of an Annex B source + } + // Once the encoders failed to start, ctx is cancelled: the rest of + // the group must not start ffmpeg again for each frame. + if enc == nil && (ctx.Err() != nil || !startEncoding(*in.config)) { + return + } + if len(enc.encoders) == 0 || (dropping && i != 0) { + return + } + select { + case enc.queue <- sourceFrame{frameInfo: frameInfo{Group: seq, First: i == 0, Timestamp: ts, WireTimestamp: f.Timestamp}, Data: data}: + dropping = false + default: + if !dropping { + slog.Warn("abr: encoder is behind; dropping source frames up to the next group", "broadcast", p.src) + } + dropping = true + } + }, srcOut.endGroup) + if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) { + err = cause // the encoders did not start + } + if enc != nil { + if ferr := enc.finish(); ferr != nil && err == nil && ctx.Err() == nil { + err = ferr + } + } + return err +} + +// encoding is the renditions of a source being encoded, and the encoders and +// queue that encode them. +type encoding struct { + r *renditions + encoders []*encoder + // queue feeds the encoders, so a slow encoder never holds up the source + // track's own forwarding; fed reports how feeding them ended. + queue chan sourceFrame + fed chan error +} + +// startEncoding starts encoding the renditions of the ladder shorter than a +// source of width×height, configured as sc, publishing them with the +// source's publisher properties info. +func (p *pipeline) startEncoding(ctx context.Context, sc sourceConfig, width, height int, info moqt.PublishInfo) (*encoding, error) { var outputs []output for _, r := range below(p.cfg.Ladder, height) { w, h := r.Size(width, height) @@ -268,7 +411,6 @@ func (p *pipeline) transcode(ctx context.Context, t msf.Track, init []byte) erro r := &renditions{out: p.out, outputs: outputs, info: info, tracks: make([]*track, len(outputs)), configured: make([]bool, len(outputs))} for i := range r.tracks { r.tracks[i] = newTrack() - defer r.tracks[i].close() } // One ffmpeg decodes the source once for every rendition. Windows cannot @@ -286,55 +428,32 @@ func (p *pipeline) transcode(ctx context.Context, t msf.Track, init []byte) erro } groups = append(groups, all) } - sc := sourceConfig{Codec: t.Codec, Width: cfg.Width, Height: cfg.Height, Description: init} encoders, err := startEncoders(ctx, p.cfg.Encoder, sc, outputs, groups, r) if err != nil { - return err + for _, t := range r.tracks { + t.close() + } + return nil, err } - - // The encoders are fed from a queue, so a slow encoder never holds up the - // source track's own forwarding. - queue := make(chan sourceFrame, encodeQueue) - fed := make(chan error, 1) + e := &encoding{r: r, encoders: encoders, queue: make(chan sourceFrame, encodeQueue), fed: make(chan error, 1)} go func() { - fed <- feed(queue, encoders) + e.fed <- feed(e.queue, encoders) }() + return e, nil +} - rate := newBitrateMeter() - dropping := false - err = p.readTrack(ctx, t.Name, srcOut.openGroup, func(seq moqt.GroupSequence, i int, f *moqt.Frame) { - srcOut.writeFrame(f) - ts, data, err := cmaf.DecodeLOC(f.Body()) - if err != nil { - slog.Warn("abr: source frame is not LOC", "broadcast", p.src, "error", err) - return - } - if bps, ok := rate.add(ts, len(data), i == 0); ok { - if err := p.out.setBitrate(src.Name, bps); err != nil { - slog.Warn("abr: state source bitrate", "error", err) - } - } - if len(encoders) == 0 { - return - } - if dropping && i != 0 { - return - } - select { - case queue <- sourceFrame{frameInfo: frameInfo{Group: seq, First: i == 0, Timestamp: ts, WireTimestamp: f.Timestamp}, Data: data}: - dropping = false - default: - if !dropping { - slog.Warn("abr: encoder is behind; dropping source frames up to the next group", "broadcast", p.src) - } - dropping = true - } - }, srcOut.endGroup) - close(queue) - if ferr := <-fed; ferr != nil && err == nil && ctx.Err() == nil { - err = ferr +// finish closes the queue, waits for the encoders to drain and exit, and +// returns how feeding them ended. +func (e *encoding) finish() error { + close(e.queue) + return <-e.fed +} + +// closeTracks ends the renditions' tracks for their subscribers. +func (e *encoding) closeTracks() { + for _, t := range e.r.tracks { + t.close() } - return err } // startEncoders starts an encoder for each group of output indexes. If one diff --git a/internal/abr/pipeline_test.go b/internal/abr/pipeline_test.go index 083b4fa4..3c7ad15e 100644 --- a/internal/abr/pipeline_test.go +++ b/internal/abr/pipeline_test.go @@ -77,9 +77,55 @@ func TestOutputTrack(t *testing.T) { assert.Equal(t, "avc1.64001f", got.Codec) } -func TestAliasError(t *testing.T) { - err := &AliasError{Alias: "/.hls/live/cam1", Target: "/live/cam1"} - assert.Equal(t, "abr: /.hls/live/cam1 redirects to /live/cam1", err.Error()) +// The source rendition is sized by its catalog when that states a positive +// width and height, else by its decoded configuration, and states no size +// (nor a label from one) when neither is known: never 0p. +func TestSourceRendition(t *testing.T) { + decoded := &sourceConfig{Width: 640, Height: 360} + tests := map[string]struct { + width, height *int64 + label string + config *sourceConfig + wantSize []int64 // width, height; nil for none + wantLabel string + }{ + "catalog size": {width: new(int64(1280)), height: new(int64(720)), config: decoded, wantSize: []int64{1280, 720}, wantLabel: "720p (source)"}, + "catalog size, not decoded yet": {width: new(int64(1280)), height: new(int64(720)), wantSize: []int64{1280, 720}, wantLabel: "720p (source)"}, + "catalog label kept": {width: new(int64(1280)), height: new(int64(720)), label: "HD", wantSize: []int64{1280, 720}, wantLabel: "HD"}, + "no catalog size, decoded": {config: decoded, wantSize: []int64{640, 360}, wantLabel: "360p (source)"}, + "no catalog size, not decoded yet": {}, + "no catalog height, decoded": {width: new(int64(1280)), config: decoded, wantSize: []int64{640, 360}, wantLabel: "360p (source)"}, + "zero width, decoded": {width: new(int64(0)), height: new(int64(720)), config: decoded, wantSize: []int64{640, 360}, wantLabel: "360p (source)"}, + "zero height, decoded": {width: new(int64(1280)), height: new(int64(0)), config: decoded, wantSize: []int64{640, 360}, wantLabel: "360p (source)"}, + "zero size, decoded": {width: new(int64(0)), height: new(int64(0)), config: decoded, wantSize: []int64{640, 360}, wantLabel: "360p (source)"}, + "zero size, not decoded yet": {width: new(int64(0)), height: new(int64(0))}, + "zero size, catalog label kept": {width: new(int64(0)), height: new(int64(0)), label: "cam", wantLabel: "cam"}, + "negative size, decoded": {width: new(int64(-1)), height: new(int64(-1)), config: decoded, wantSize: []int64{640, 360}, wantLabel: "360p (source)"}, + "decoded size unusable": {config: &sourceConfig{}}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + track := msf.Track{Name: "video", Namespace: "/live/cam1", Codec: "avc1.42c01e", Width: tt.width, Height: tt.height, Label: tt.label} + got := sourceRendition(track, tt.config) + require.NotNil(t, got.AltGroup) + assert.EqualValues(t, videoAltGroup, *got.AltGroup) + assert.Empty(t, got.Namespace) + assert.Equal(t, tt.wantLabel, got.Label) + if tt.wantSize == nil { + assert.Nil(t, got.Width) + assert.Nil(t, got.Height) + return + } + require.NotNil(t, got.Width) + require.NotNil(t, got.Height) + assert.Equal(t, tt.wantSize, []int64{*got.Width, *got.Height}) + }) + } +} + +func TestMisdirectedError(t *testing.T) { + err := &MisdirectedError{OptIn: "/.abr/live/cam1", Broadcast: "/live/cam1", To: "/live/other"} + assert.Equal(t, "abr: the opt-in /.abr/live/cam1 leads to /live/other, not /live/cam1", err.Error()) } // newTestRenditions returns renditions publishing into a fresh output diff --git a/internal/abr/redirect_test.go b/internal/abr/redirect_test.go new file mode 100644 index 00000000..8fd67de7 --- /dev/null +++ b/internal/abr/redirect_test.go @@ -0,0 +1,95 @@ +package abr + +import ( + "context" + "crypto/tls" + "errors" + "io" + "log/slog" + "net" + "testing" + "time" + + "github.com/quic-go/quic-go" + "github.com/qumo-dev/gomoqt/moqt" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/qumo-dev/qumo/internal/devcert" +) + +// loopbackSession dials a MoQ server serving mux and returns the session, +// which follows redirects as the transcoder's does. +func loopbackSession(tb testing.TB, ctx context.Context, mux *moqt.TrackMux) *moqt.Session { + tb.Helper() + ca, err := devcert.NewCA("abr-test", time.Hour) + require.NoError(tb, err) + cert, err := ca.Issue(devcert.Leaf{CommonName: "localhost", DNSNames: []string{"localhost"}, Validity: time.Hour}) + require.NoError(tb, err) + + pc, err := net.ListenPacket("udp", "127.0.0.1:0") + require.NoError(tb, err) + addr := pc.LocalAddr().String() + require.NoError(tb, pc.Close()) + + srv := &moqt.Server{ + Addr: addr, + TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}, NextProtos: []string{moqt.NextProtoMOQ}}, + QUICConfig: &quic.Config{EnableDatagrams: true}, + TrackMux: mux, + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + Handler: moqt.HandleFunc(func(sess *moqt.Session) { <-sess.Context().Done() }), + } + go func() { + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, moqt.ErrServerClosed) { + tb.Logf("server: %v", err) + } + }() + tb.Cleanup(func() { _ = srv.Close() }) // not actionable: test teardown + + dialer := &moqt.Dialer{TLSConfig: &tls.Config{InsecureSkipVerify: true}} //nolint:gosec // test-only self-signed cert + var sess *moqt.Session + require.Eventually(tb, func() bool { + s, err := dialer.Dial(ctx, "moqt://"+addr+"/", nil) + if err != nil { + return false + } + sess = s + return true + }, 5*time.Second, 50*time.Millisecond) + tb.Cleanup(func() { _ = sess.CloseWithError(moqt.NoError, "done") }) // not actionable: test teardown + return sess +} + +// A source track that redirects to another broadcast is not read: the +// transcoder may read every broadcast, so following it would publish +// someone else's media as the source's renditions. +func TestReadTrackRefusesARedirectedTrack(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + mux := moqt.NewTrackMux(0) + mux.PublishFunc(ctx, "/victim/cam", func(tw *moqt.TrackWriter) { + gw, err := tw.OpenGroup(tw.Context()) + if err != nil { + return + } + frame := moqt.NewFrame(1) + _, _ = frame.Write([]byte{0}) // not actionable: the test fails on any frame read + _ = gw.WriteFrame(frame) // not actionable: as above + _ = gw.Close() // not actionable: as above + <-tw.Context().Done() + }) + mux.PublishFunc(ctx, "/acme/cam", func(tw *moqt.TrackWriter) { + if err := tw.Redirect(tw.Context(), moqt.Redirect{BroadcastPath: "/victim/cam", TrackName: tw.TrackName}); err != nil { + tw.CloseWithError(moqt.SubscribeErrorCodeNotFound) + } + }) + p := &pipeline{sess: loopbackSession(t, ctx, mux), optIn: "/.abr/acme/cam", src: "/acme/cam"} + + err := p.readTrack(ctx, "video", func(moqt.GroupSequence) bool { return true }, + func(moqt.GroupSequence, int, *moqt.Frame) { t.Error("read a frame of another broadcast") }, func() {}) + + mis, ok := errors.AsType[*MisdirectedError](err) + require.True(t, ok, "got %v", err) + assert.Equal(t, moqt.BroadcastPath("/victim/cam"), mis.To) +} diff --git a/internal/abr/source.go b/internal/abr/source.go new file mode 100644 index 00000000..d826c2cb --- /dev/null +++ b/internal/abr/source.go @@ -0,0 +1,210 @@ +package abr + +import ( + "encoding/binary" + "errors" + "fmt" + "strings" + + "github.com/qumo-dev/gomoqt/msf" + + "github.com/qumo-dev/qumo/internal/ingest" +) + +// H.264 NAL unit types (ITU-T H.264 Table 7-1). +const ( + nalSPS = 7 + nalPPS = 8 + nalAUD = 9 +) + +// A sourceFormat is how a source video track's frames are coded, and so what +// it takes to hand them to ffmpeg. +type sourceFormat int + +const ( + // formatAVCC is H.264 with length-prefixed NAL units and its parameter + // sets in the catalog, as RTMP and RTSP ingest publish it. + formatAVCC sourceFormat = iota + // formatAnnexB is H.264 with start codes and its parameter sets in the + // stream, before each keyframe, as WebCodecs encodes it in "annexb" format. + formatAnnexB + // formatVP9 is VP9, whose configuration the codec string and picture size + // state. + formatVP9 +) + +func (f sourceFormat) String() string { + switch f { + case formatAVCC: + return "H.264 (AVCC)" + case formatAnnexB: + return "H.264 (Annex B)" + case formatVP9: + return "VP9" + } + return fmt.Sprintf("format %d", int(f)) +} + +// formatOf reports how the catalog's video track t, with init data init, is +// coded, and false when the transcoder cannot take it. +// +// An avc1 track with init data is AVCC; one without carries its parameter +// sets in the stream, so its frames are Annex B. A VP9 track needs the full +// codec string (profile, level, bit depth) and its picture size, which +// together are its configuration. +func formatOf(t msf.Track, init []byte) (sourceFormat, bool) { + switch { + case isAVC(t.Codec) && init != nil: + return formatAVCC, true + case isAVC(t.Codec): + return formatAnnexB, true + case strings.HasPrefix(t.Codec, "vp09.") && strings.Count(t.Codec, ".") >= 3 && + t.Width != nil && t.Height != nil && *t.Width > 0 && *t.Height > 0: + return formatVP9, true + } + return 0, false +} + +// A source adapts a source video track's frames to the encoder's input, and +// knows the configuration the encoder decodes them with: at once for AVCC and +// VP9, and for Annex B from the parameter sets of the first keyframe. +type source struct { + format sourceFormat + codec string + // config is the encoder's view of the source, nil until known. + config *sourceConfig +} + +// newSource returns the source for track t, with init data init, coded as +// format. +func newSource(t msf.Track, init []byte, format sourceFormat) (*source, error) { + s := &source{format: format, codec: t.Codec} + switch format { + case formatAVCC: + cfg, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, init...)) + if err != nil { + return nil, fmt.Errorf("abr: source decoder configuration: %w", err) + } + s.config = &sourceConfig{Codec: t.Codec, Width: cfg.Width, Height: cfg.Height, Description: init} + case formatVP9: + s.config = &sourceConfig{Codec: t.Codec, Width: int(*t.Width), Height: int(*t.Height)} + } + return s, nil +} + +// frame returns data, a frame of the source, as the encoder takes it, and +// false for a frame the encoder cannot take yet. first reports that the frame +// opens a group, so is a keyframe. +// +// An Annex B frame is rewritten with 4-byte lengths, dropping access unit +// delimiters. Until the source's configuration is known, its frames are +// refused but for a keyframe carrying its parameter sets, which makes it known. +func (s *source) frame(data []byte, first bool) ([]byte, bool) { + if s.format != formatAnnexB { + return data, s.config != nil + } + if !hasStartCode(data) { + // Not Annex B after all: the publisher sends AVCC without stating + // its configuration, which cannot be decoded. + return nil, false + } + nalus := splitAnnexB(data) + if s.config == nil { + if !first { + return nil, false + } + record, err := avcRecord(nalus) + if err != nil { + return nil, false + } + cfg, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, record...)) + if err != nil { + return nil, false + } + s.config = &sourceConfig{Codec: s.codec, Width: cfg.Width, Height: cfg.Height, Description: record} + } + return avcc(nalus), true +} + +// hasStartCode reports whether b opens with an Annex B start code. +func hasStartCode(b []byte) bool { + return len(b) >= 3 && b[0] == 0 && b[1] == 0 && (b[2] == 1 || (len(b) >= 4 && b[2] == 0 && b[3] == 1)) +} + +// splitAnnexB returns the NAL units of an Annex B byte stream, without their +// start codes. +func splitAnnexB(b []byte) [][]byte { + var nalus [][]byte + start := -1 // start of the current NAL unit, past its start code + for i := 0; i+2 < len(b); { + if b[i] == 0 && b[i+1] == 0 && b[i+2] == 1 { + if start >= 0 { + nalus = appendNALU(nalus, b[start:i]) + } + i += 3 + start = i + continue + } + i++ + } + if start >= 0 { + nalus = appendNALU(nalus, b[start:]) + } + return nalus +} + +// appendNALU appends n to nalus without the zero bytes that trail it: the +// leading zero of a 4-byte start code, and trailing_zero_8bits. +func appendNALU(nalus [][]byte, n []byte) [][]byte { + for len(n) > 0 && n[len(n)-1] == 0 { + n = n[:len(n)-1] + } + if len(n) == 0 { + return nalus + } + return append(nalus, n) +} + +// avcc returns nalus as an AVCC frame, each prefixed by its 4-byte length, +// leaving out access unit delimiters, which a sample does not carry. +func avcc(nalus [][]byte) []byte { + size := 0 + for _, n := range nalus { + size += 4 + len(n) + } + out := make([]byte, 0, size) + for _, n := range nalus { + if n[0]&0x1f == nalAUD { + continue + } + out = binary.BigEndian.AppendUint32(out, uint32(len(n))) + out = append(out, n...) + } + return out +} + +// avcRecord builds the AVCDecoderConfigurationRecord of the parameter sets +// among nalus, with 4-byte NAL unit lengths. +func avcRecord(nalus [][]byte) ([]byte, error) { + var sps, pps [][]byte + for _, n := range nalus { + switch n[0] & 0x1f { + case nalSPS: + sps = append(sps, n) + case nalPPS: + pps = append(pps, n) + } + } + if len(sps) == 0 || len(pps) == 0 || len(sps[0]) < 4 { + return nil, errors.New("abr: keyframe carries no SPS and PPS") + } + return ingest.BuildAVCDecoderConfigurationRecord(&ingest.AVCConfig{ + ProfileIDC: sps[0][1], + ProfileCompat: sps[0][2], + LevelIDC: sps[0][3], + NALULenSize: 4, + SPS: sps, + PPS: pps, + }) +} diff --git a/internal/abr/source_test.go b/internal/abr/source_test.go new file mode 100644 index 00000000..b0142f3d --- /dev/null +++ b/internal/abr/source_test.go @@ -0,0 +1,301 @@ +package abr + +import ( + "bytes" + "context" + "encoding/binary" + "os/exec" + "strconv" + "testing" + "time" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/qumo-dev/gomoqt/msf" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/qumo-dev/qumo/internal/ingest" +) + +// parameterSets returns the SPS and PPS of an AVCDecoderConfigurationRecord. +func parameterSets(t *testing.T, record []byte) (sps, pps []byte) { + t.Helper() + cfg, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, record...)) + require.NoError(t, err) + return cfg.SPS[0], cfg.PPS[0] +} + +// annexB joins nalus into an Annex B byte stream with 4-byte start codes. +func annexB(nalus ...[]byte) []byte { + var b []byte + for _, n := range nalus { + b = append(b, 0, 0, 0, 1) + b = append(b, n...) + } + return b +} + +// annexBFromAVCC rewrites an AVCC frame (4-byte lengths) as Annex B, led by +// an access unit delimiter and, for a keyframe, the parameter sets, as a +// WebCodecs encoder in "annexb" format writes it. +func annexBFromAVCC(t *testing.T, data []byte, key bool, sps, pps []byte) []byte { + t.Helper() + nalus := [][]byte{{0x09, 0xf0}} // AUD + if key { + nalus = append(nalus, sps, pps) + } + for len(data) > 0 { + require.GreaterOrEqual(t, len(data), 4) + n := int(binary.BigEndian.Uint32(data)) + nalus = append(nalus, data[4:4+n]) + data = data[4+n:] + } + return annexB(nalus...) +} + +func TestSplitAnnexB(t *testing.T) { + a, b, c := []byte{0x67, 1, 2}, []byte{0x68, 3}, []byte{0x65, 4, 5, 6} + tests := map[string]struct { + in []byte + want [][]byte + }{ + "4-byte start codes": {in: annexB(a, b, c), want: [][]byte{a, b, c}}, + "3-byte start codes": {in: append(append([]byte{0, 0, 1}, a...), append([]byte{0, 0, 1}, b...)...), want: [][]byte{a, b}}, + "mixed, with trailing zero bytes": { + in: append(append(append([]byte{0, 0, 0, 1}, a...), 0, 0), append([]byte{0, 0, 1}, c...)...), + want: [][]byte{a, c}, + }, + "no start code": {in: []byte{1, 2, 3}, want: nil}, + "an empty unit": {in: []byte{0, 0, 1, 0, 0, 1, 0x65, 9}, want: [][]byte{{0x65, 9}}}, + "too short to say": {in: []byte{0, 0}, want: nil}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + assert.Equal(t, tt.want, splitAnnexB(tt.in)) + }) + } +} + +func TestAVCC(t *testing.T) { + got := avcc([][]byte{{0x09, 0xf0}, {0x67, 1}, {0x65, 2, 3}}) + assert.Equal(t, []byte{0, 0, 0, 2, 0x67, 1, 0, 0, 0, 3, 0x65, 2, 3}, got, "access unit delimiters are left out") +} + +func TestHasStartCode(t *testing.T) { + assert.True(t, hasStartCode([]byte{0, 0, 1, 0x65})) + assert.True(t, hasStartCode([]byte{0, 0, 0, 1, 0x65})) + assert.False(t, hasStartCode([]byte{0, 0, 0, 5, 0x65}), "an AVCC length") + assert.False(t, hasStartCode([]byte{0, 0})) +} + +func TestAVCRecord(t *testing.T) { + sps, pps := parameterSets(t, avcRecord360p) + record, err := avcRecord([][]byte{{0x09, 0xf0}, sps, pps, {0x65, 1}}) + require.NoError(t, err) + cfg, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, record...)) + require.NoError(t, err) + assert.Equal(t, 640, cfg.Width) + assert.Equal(t, 360, cfg.Height) + assert.Equal(t, "avc1.42c01e", cfg.CodecString()) + assert.Equal(t, 4, cfg.NALULenSize) + + _, err = avcRecord([][]byte{{0x65, 1}}) + assert.Error(t, err, "a frame without parameter sets") + _, err = avcRecord([][]byte{sps}) + assert.Error(t, err, "an SPS without a PPS") +} + +func TestFormatOf(t *testing.T) { + size := func(t msf.Track) msf.Track { + t.Width, t.Height = new(int64(640)), new(int64(360)) + return t + } + tests := map[string]struct { + track msf.Track + init []byte + want sourceFormat + wantOK bool + }{ + "H.264 with init data is AVCC": {track: msf.Track{Codec: "avc1.64001f"}, init: []byte{1}, want: formatAVCC, wantOK: true}, + "H.264 without init is Annex B": {track: msf.Track{Codec: "avc1.64001f"}, want: formatAnnexB, wantOK: true}, + "VP9 with its size": {track: size(msf.Track{Codec: "vp09.00.10.08"}), want: formatVP9, wantOK: true}, + "VP9 without a size": {track: msf.Track{Codec: "vp09.00.10.08"}}, + "VP9 without profile and level": {track: size(msf.Track{Codec: "vp09"})}, + "AV1 is not taken": {track: size(msf.Track{Codec: "av01.0.08M.08"})}, + "avc3 carries its sets in band": {track: msf.Track{Codec: "avc3.64001f"}}, + "a track with no codec": {track: msf.Track{}}, + "VP8 states no configuration": {track: size(msf.Track{Codec: "vp8"})}, + "HEVC is not taken": {track: size(msf.Track{Codec: "hev1.1.6.L93.B0"})}, + "VP9 with zero size is not taken": {track: msf.Track{Codec: "vp09.00.10.08", Width: new(int64(0)), Height: new(int64(0))}}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + got, ok := formatOf(tt.track, tt.init) + assert.Equal(t, tt.wantOK, ok) + if tt.wantOK { + assert.Equal(t, tt.want, got) + } + }) + } +} + +func TestSourceAnnexB(t *testing.T) { + sps, pps := parameterSets(t, avcRecord360p) + s, err := newSource(msf.Track{Codec: "avc1.42c01e"}, nil, formatAnnexB) + require.NoError(t, err) + assert.Nil(t, s.config, "known only from the stream") + + // Joined mid-group: nothing is decodable before a keyframe. + _, ok := s.frame(annexB([]byte{0x41, 1}), false) + assert.False(t, ok) + // A keyframe without its parameter sets does not make it known either. + _, ok = s.frame(annexB([]byte{0x65, 1}), true) + assert.False(t, ok) + + got, ok := s.frame(annexB([]byte{0x09, 0xf0}, sps, pps, []byte{0x65, 7}), true) + require.True(t, ok) + require.NotNil(t, s.config) + assert.Equal(t, 640, s.config.Width) + assert.Equal(t, 360, s.config.Height) + assert.Equal(t, avcc([][]byte{sps, pps, {0x65, 7}}), got, "rewritten as AVCC, without the delimiter") + + got, ok = s.frame(annexB([]byte{0x41, 8}), false) + require.True(t, ok) + assert.Equal(t, []byte{0, 0, 0, 2, 0x41, 8}, got) + + // AVCC sent without a configuration cannot be decoded. + _, ok = s.frame([]byte{0, 0, 0, 2, 0x41, 8}, false) + assert.False(t, ok) +} + +func TestSourceAVCCAndVP9(t *testing.T) { + s, err := newSource(msf.Track{Codec: "avc1.42c01e"}, avcRecord360p, formatAVCC) + require.NoError(t, err) + require.NotNil(t, s.config) + assert.Equal(t, 640, s.config.Width) + got, ok := s.frame([]byte{0, 0, 0, 1, 0x41}, false) + assert.True(t, ok) + assert.Equal(t, []byte{0, 0, 0, 1, 0x41}, got, "passed as is") + + _, err = newSource(msf.Track{Codec: "avc1.42c01e"}, []byte{1, 2}, formatAVCC) + assert.Error(t, err, "init data that does not parse") + + vp9 := msf.Track{Codec: "vp09.00.10.08", Width: new(int64(1280)), Height: new(int64(720))} + s, err = newSource(vp9, nil, formatVP9) + require.NoError(t, err) + assert.Equal(t, sourceConfig{Codec: "vp09.00.10.08", Width: 1280, Height: 720}, *s.config) + got, ok = s.frame([]byte{0x82, 0x49}, true) + assert.True(t, ok) + assert.Equal(t, []byte{0x82, 0x49}, got) +} + +// encodeAll feeds src through an encoder for outputs and returns what the +// sink recorded. +func encodeAll(t *testing.T, sc sourceConfig, src []sourceFrame, outputs []output) *recordingSink { + t.Helper() + sink := newRecordingSink() + enc, err := newEncoder(EncoderConfig{FFmpeg: "ffmpeg", Codec: "libx264", Preset: "ultrafast"}, sc, outputs, sink) + require.NoError(t, err) + ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) + defer cancel() + require.NoError(t, enc.start(ctx)) + for _, f := range src { + require.NoError(t, enc.encode(f)) + } + require.NoError(t, enc.close()) + return sink +} + +// assertRenditions checks that every source frame came out of every rendition, +// with its timestamps, and that every group opens on a keyframe. +func assertRenditions(t *testing.T, sink *recordingSink, src []sourceFrame, outputs []output) { + t.Helper() + assert.False(t, sink.early) + for i, o := range outputs { + got := sink.frames[i] + require.Len(t, got, len(src), o.Rung.TrackName()) + for k, f := range got { + assert.Equal(t, src[k].frameInfo, f.frameInfo, "%s frame %d", o.Rung.TrackName(), k) + if f.First { + assert.True(t, f.Keyframe, "%s frame %d", o.Rung.TrackName(), k) + } + } + } +} + +func TestEncoderAnnexBSource(t *testing.T) { + record, frames := testSource(t, 640, 360, 60, 30) + sps, pps := parameterSets(t, record) + s, err := newSource(msf.Track{Codec: "avc1.42c01e"}, nil, formatAnnexB) + require.NoError(t, err) + + var src []sourceFrame + for _, f := range frames { + data, ok := s.frame(annexBFromAVCC(t, f.Data, f.First, sps, pps), f.First) + require.True(t, ok) + f.Data = data + src = append(src, f) + } + outputs := []output{{Rung: Rung{Height: 240, Bitrate: 400_000}, Width: 426, Height: 240}} + assertRenditions(t, encodeAll(t, *s.config, src, outputs), src, outputs) +} + +// testVP9Source encodes a synthetic VP9 source with ffmpeg and returns its +// frames, grouped at keyframes, read from an IVF stream. +func testVP9Source(t *testing.T, width, height, frames, gop int) []sourceFrame { + t.Helper() + if _, err := exec.LookPath("ffmpeg"); err != nil { + t.Skip("ffmpeg not on PATH") + } + out, err := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error", + "-f", "lavfi", "-i", "testsrc2=size="+strconv.Itoa(width)+"x"+strconv.Itoa(height)+":rate=30", + "-frames:v", strconv.Itoa(frames), "-c:v", "libvpx-vp9", "-deadline", "realtime", "-cpu-used", "8", + "-g", strconv.Itoa(gop), "-keyint_min", strconv.Itoa(gop), "-pix_fmt", "yuv420p", "-f", "ivf", "pipe:1").Output() + if err != nil { + t.Skipf("ffmpeg cannot encode VP9: %v", err) + } + // IVF: a 32-byte file header, then frames of a 12-byte header (size, + // timestamp) and data. A VP9 keyframe has frame_type 0, bit 2 (profile + // 0) of its first byte. + require.Equal(t, "DKIF", string(out[:4])) + r := bytes.NewReader(out[32:]) + var src []sourceFrame + var group moqt.GroupSequence + hdr := make([]byte, 12) + for { + if _, err := r.Read(hdr); err != nil { + break + } + data := make([]byte, binary.LittleEndian.Uint32(hdr)) + _, err := r.Read(data) + require.NoError(t, err) + key := data[0]&0x04 == 0 + if key { + group++ + } + ts := uint64(1_794_839_947_021_017 + len(src)*33_367) + src = append(src, sourceFrame{frameInfo: frameInfo{Group: group, First: key, Timestamp: ts, WireTimestamp: ts}, Data: data}) + } + require.Len(t, src, frames) + return src +} + +func TestEncoderVP9Source(t *testing.T) { + src := testVP9Source(t, 640, 360, 60, 30) + keys := 0 + for _, f := range src { + if f.First { + keys++ + } + } + require.Equal(t, 2, keys, "a keyframe every 30 frames") + s, err := newSource(msf.Track{Codec: "vp09.00.10.08", Width: new(int64(640)), Height: new(int64(360))}, nil, formatVP9) + require.NoError(t, err) + outputs := []output{{Rung: Rung{Height: 240, Bitrate: 400_000}, Width: 426, Height: 240}} + sink := encodeAll(t, *s.config, src, outputs) + assertRenditions(t, sink, src, outputs) + + cfg, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, sink.configs[0]...)) + require.NoError(t, err) + assert.Contains(t, cfg.CodecString(), "avc1.", "the renditions are H.264, whatever the source") +} diff --git a/internal/auth/cmd.go b/internal/auth/cmd.go index 63a7d4d8..9aae297c 100644 --- a/internal/auth/cmd.go +++ b/internal/auth/cmd.go @@ -57,12 +57,32 @@ func Run(args []string) error { } } -// prefixLabel describes what a key with prefix may grant, for the terminal. -func prefixLabel(prefix string) string { +// prefixLabel describes what a key with prefix, holding optIns, may grant, +// for the terminal. +func prefixLabel(prefix string, optIns []token.OptIn) string { if prefix == "/" { return "any root (no prefix)" } - return "a root at or beneath " + prefix + " or its HLS opt-in " + token.HLSDirectory + strings.TrimPrefix(prefix, "/") + label := "a root at or beneath " + prefix + if len(optIns) == 0 { + return label + " (no opt-ins)" + } + mirrors := make([]string, len(optIns)) + for i, o := range optIns { + mirrors[i] = o.Directory() + strings.TrimPrefix(prefix, "/") + } + return label + " or its opt-ins " + strings.Join(mirrors, ", ") +} + +// parseOptIns reads a comma-separated list of opt-ins: "" is none. +func parseOptIns(s string) []token.OptIn { + var out []token.OptIn + for part := range strings.SplitSeq(s, ",") { + if part = strings.TrimSpace(part); part != "" { + out = append(out, token.OptIn(part)) + } + } + return out } // runKeygen writes a new signing key pair: the private key, for the app that @@ -72,7 +92,8 @@ func prefixLabel(prefix string) string { // one. The summary goes to out and the prompt to info. func runKeygen(args []string, out, info io.Writer, in io.Reader) error { fs := flag.NewFlagSet("qumo auth keygen", flag.ContinueOnError) - prefix := fs.String("prefix", "/", "confine the key to this directory (e.g. /acme/app/) and its HLS opt-in mirror (/.hls/acme/app/); / for none") + prefix := fs.String("prefix", "/", "confine the key to this directory (e.g. /acme/app/) and its mirrors beneath the opt-ins it holds (/.hls/acme/app/); / for none") + optIns := fs.String("opt-ins", "", "the opt-ins the key signs for, comma-separated (hls, abr), written to the key set as \"optIns\" (a control plane sets them as its tenant pays); none by default") privPath := fs.String("out", "signing-key.jwk", "where to write the private signing key (keep it on the app's server)") pubPath := fs.String("keys", "keys.json", "where to write the public key set (QUMO_AUTH_KEYS)") yes := fs.Bool("yes", false, "confirm without asking, as a piped run does") @@ -87,17 +108,23 @@ func runKeygen(args []string, out, info io.Writer, in io.Reader) error { if err != nil { return err } - set, err := token.MarshalKeySet(key.Public()) + pub := key.Public() + pub.OptIns = parseOptIns(*optIns) + set, err := token.MarshalKeySet(pub) if err != nil { return err } + // MarshalKeySet checked them: what the key set holds is what is shown. + if keys, err := token.ParseKeySet(set); err == nil { + pub = keys[pub.ID] + } // The key and where it lies, before any file does: the key's prefix is // the one setting a re-issue won't give back, and a bare prefix makes // the key the tenant of everything. var fields strings.Builder fmt.Fprintf(&fields, "Generated an Ed25519 signing key.\n\n") fmt.Fprintf(&fields, " %-13s %s\n", "Key ID:", key.ID) - fmt.Fprintf(&fields, " %-13s %s\n", "Grants:", prefixLabel(key.Prefix)) + fmt.Fprintf(&fields, " %-13s %s\n", "Grants:", prefixLabel(key.Prefix, pub.OptIns)) fmt.Fprintf(&fields, " %-13s %s (private: keep it on your app's server)\n", "Signing key:", *privPath) fmt.Fprintf(&fields, " %-13s %s (public: for the relay)\n", "Key set:", *pubPath) var next strings.Builder diff --git a/internal/auth/cmd_test.go b/internal/auth/cmd_test.go index db1ab2b9..bf0b4a7d 100644 --- a/internal/auth/cmd_test.go +++ b/internal/auth/cmd_test.go @@ -180,26 +180,58 @@ func TestRunToken_NoTicketFlag(t *testing.T) { func TestRunKeygen_SaysWhatTheKeyGrants(t *testing.T) { tests := map[string]struct { prefix string + args []string want []string + // wantOptIns is what keys.json lists. + wantOptIns []token.OptIn }{ - "a prefix": {prefix: "acme/app", want: []string{"a root at or beneath /acme/app/ or its HLS opt-in /.hls/acme/app/", "-root /acme/app/ -publish /demo"}}, - "none": {want: []string{"any root (no prefix)", "-root / -publish /demo"}}, + "a prefix, no opt-ins": {prefix: "acme/app", want: []string{"a root at or beneath /acme/app/ (no opt-ins)", "-root /acme/app/ -publish /demo"}}, + "HLS": { + prefix: "acme/app", args: []string{"-opt-ins", "hls"}, + want: []string{"a root at or beneath /acme/app/ or its opt-ins /.hls/acme/app/"}, + wantOptIns: []token.OptIn{token.OptInHLS}, + }, + "none": {want: []string{"any root (no prefix)", "-root / -publish /demo"}}, + "ABR paid for": { + prefix: "acme/app", args: []string{"-opt-ins", "abr, hls"}, + want: []string{"a root at or beneath /acme/app/ or its opt-ins /.hls/acme/app/, /.abr/acme/app/"}, + wantOptIns: []token.OptIn{token.OptInHLS, token.OptInABR}, + }, + "an empty list": { + prefix: "acme/app", args: []string{"-opt-ins", ""}, + want: []string{"a root at or beneath /acme/app/ (no opt-ins)"}, + }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { dir := t.TempDir() + keysPath := filepath.Join(dir, "keys.json") var out bytes.Buffer - require.NoError(t, runKeygen([]string{"-prefix", tt.prefix, - "-out", filepath.Join(dir, "signing-key.jwk"), "-keys", filepath.Join(dir, "keys.json")}, &out, io.Discard, nil)) + require.NoError(t, runKeygen(append([]string{"-prefix", tt.prefix, + "-out", filepath.Join(dir, "signing-key.jwk"), "-keys", keysPath}, tt.args...), &out, io.Discard, nil)) for _, w := range tt.want { assert.Contains(t, out.String(), w) } + keys, err := token.LoadKeySet(keysPath) + require.NoError(t, err) + for _, k := range keys { + assert.Equal(t, tt.wantOptIns, k.OptIns) + } }) } } +func TestRunKeygen_RefusesAnUnknownOptIn(t *testing.T) { + dir := t.TempDir() + err := runKeygen([]string{"-prefix", "acme", "-opt-ins", "dash", + "-out", filepath.Join(dir, "signing-key.jwk"), "-keys", filepath.Join(dir, "keys.json")}, &bytes.Buffer{}, io.Discard, nil) + assert.ErrorContains(t, err, "dash") + _, statErr := os.Stat(filepath.Join(dir, "signing-key.jwk")) + assert.ErrorIs(t, statErr, os.ErrNotExist, "nothing written") +} + // The summary names the two paths and what the key grants, and stops // there: every value a run will use is in it already, so it adds no // args line of its own. diff --git a/internal/hls/catalog_redirect_test.go b/internal/hls/catalog_redirect_test.go index 41450b03..5dac5476 100644 --- a/internal/hls/catalog_redirect_test.go +++ b/internal/hls/catalog_redirect_test.go @@ -17,7 +17,7 @@ import ( "github.com/stretchr/testify/require" "github.com/qumo-dev/qumo/internal/devcert" - "github.com/qumo-dev/qumo/internal/hlsoptin" + "github.com/qumo-dev/qumo/internal/optin" "github.com/qumo-dev/qumo/internal/relay" ) @@ -105,12 +105,12 @@ func TestFetchCatalog_OptIn(t *testing.T) { defer cancel() mux := moqt.NewTrackMux(0) mux.PublishFunc(ctx, "/acme/cam", serveCatalog(t, catalog)) - mux.Publish(ctx, "/.hls/acme/cam", hlsoptin.Handler("/acme/cam")) + mux.Publish(ctx, "/.hls/acme/cam", optin.Handler("/acme/cam")) mux.PublishFunc(ctx, "/legacy/cam", serveCatalog(t, catalog)) mux.Publish(ctx, "/.hls/legacy/cam", moqt.NotFoundTrackHandler) // An opt-in that redirects to its broadcast before that is published: an // error to retry, not an opt-in from before the redirect. - mux.Publish(ctx, "/.hls/early/cam", hlsoptin.Handler("/early/cam")) + mux.Publish(ctx, "/.hls/early/cam", optin.Handler("/early/cam")) mux.Publish(ctx, "/.hls/gone/cam", moqt.NotFoundTrackHandler) sess := loopbackPublisher(t, ctx, mux) diff --git a/internal/hls/feed.go b/internal/hls/feed.go index e21b7082..47aac2f7 100644 --- a/internal/hls/feed.go +++ b/internal/hls/feed.go @@ -24,6 +24,7 @@ import ( "github.com/okdaichi/qumo-ledger/ledger/store" "github.com/qumo-dev/qumo/internal/cmaf" + "github.com/qumo-dev/qumo/internal/optin" "github.com/qumo-dev/qumo/internal/relay" "github.com/qumo-dev/qumo/internal/relaycred" "github.com/qumo-dev/qumo/internal/tlsclient" @@ -175,18 +176,7 @@ func (c feedConfig) target() (string, time.Time, error) { if c.signingKey == nil { return c.relayURL, time.Time{}, nil } - credential, lapses, err := relaycred.Sign(*c.signingKey, c.grant()) - if err != nil { - return "", time.Time{}, err - } - u, err := url.Parse(c.relayURL) - if err != nil { - return "", time.Time{}, errors.New("RELAY_URL: invalid URL") - } - query := u.Query() - query.Set("jwt", credential) - u.RawQuery = query.Encode() - return u.String(), lapses, nil + return relaycred.Target(c.relayURL, *c.signingKey, c.grant()) } // relayTLSConfig builds the client TLS config for dialing the relay. The egress @@ -374,7 +364,7 @@ func (g *broadcastGate) acquire(ctx context.Context, broadcast string) (func(), // them into ledger tracks until the announcement ends. func handleAnnouncement(ctx context.Context, session *moqt.Session, ann *moqt.Announcement, store store.Store, mux *streamMux, gate *broadcastGate, window uint64, cfg feedConfig) { annPath := string(ann.BroadcastPath()) - realBroadcast, ok := broadcastPathFromAnnounce(annPath, announcePrefix) + realBroadcast, ok := optin.Broadcast(annPath, announcePrefix) if !ok { slog.Warn("hls: refusing opt-in with a . or .. segment", "announce", annPath) return diff --git a/internal/hls/mux.go b/internal/hls/mux.go index 9c96ee51..80a84076 100644 --- a/internal/hls/mux.go +++ b/internal/hls/mux.go @@ -10,54 +10,21 @@ import ( "time" "github.com/qumo-dev/gomoqt/moqt" -) -// broadcastPathFromAnnounce strips the announcement prefix from annPath to find -// the target broadcast path where the publisher uploads media. -// -// For example, with prefix "/.hls/": -// -// "/.hls/live/cam1" -> "/live/cam1" -// "/.hls/cam" -> "/cam" -// "/.hls" -> "/" -// -// It reports false for a path with a "." or ".." segment. The relay grants -// and routes exact paths, so /.hls/acme/../victim/cam is announced under a -// grant for /.hls/acme/, yet cleans to /victim/cam, which the egress can read -// and would serve. -func broadcastPathFromAnnounce(annPath, prefix string) (string, bool) { - cleanPrefix := strings.TrimSuffix(prefix, "/") - p := strings.TrimPrefix(annPath, cleanPrefix) - if !strings.HasPrefix(p, "/") { - p = "/" + p - } - if hasDotSegment(p) { - return "", false - } - return path.Clean(p), true -} + "github.com/qumo-dev/qumo/internal/optin" +) // sameBroadcast reports whether a and b name one broadcast, however spelled: // the egress cleans the paths it derives, a publisher may not. Paths with a // "." or ".." segment name none: cleaning one can climb into another // directory than the one the relay routes it in. func sameBroadcast(a, b moqt.BroadcastPath) bool { - if hasDotSegment(string(a)) || hasDotSegment(string(b)) { + if optin.HasDotSegment(string(a)) || optin.HasDotSegment(string(b)) { return false } return path.Clean(string(a)) == path.Clean(string(b)) } -// hasDotSegment reports whether p has a "." or ".." segment. -func hasDotSegment(p string) bool { - for seg := range strings.SplitSeq(p, "/") { - if seg == "." || seg == ".." { - return true - } - } - return false -} - // trackInfo holds metadata describing a media track in an HLS master playlist. type trackInfo struct { Name string diff --git a/internal/hls/mux_test.go b/internal/hls/mux_test.go index cabf8348..b8918237 100644 --- a/internal/hls/mux_test.go +++ b/internal/hls/mux_test.go @@ -10,38 +10,6 @@ import ( "github.com/stretchr/testify/require" ) -// An opt-in's broadcast is its path with the prefix stripped, cleaned of -// doubled and trailing slashes; one with a "." or ".." segment names none, as -// cleaning it could climb out of the directory the relay granted it in. -func Test_broadcastPathFromAnnounce(t *testing.T) { - tests := map[string]struct { - annPath, prefix string - want string - wantOK bool - }{ - "standard .hls prefix with trailing slash": {annPath: "/.hls/live/cam1", prefix: "/.hls/", want: "/live/cam1", wantOK: true}, - "standard .hls prefix without trailing slash": {annPath: "/.hls/live/cam1", prefix: "/.hls", want: "/live/cam1", wantOK: true}, - "single segment path": {annPath: "/.hls/cam", prefix: "/.hls/", want: "/cam", wantOK: true}, - "hls/live under .hls prefix": {annPath: "/.hls/hls/live", prefix: "/.hls/", want: "/hls/live", wantOK: true}, - "custom prefix": {annPath: "/custom/stream/room1", prefix: "/custom/stream/", want: "/room1", wantOK: true}, - "bare prefix": {annPath: "/.hls", prefix: "/.hls/", want: "/", wantOK: true}, - "a trailing slash": {annPath: "/.hls/live/cam1/", prefix: "/.hls/", want: "/live/cam1", wantOK: true}, - "a doubled slash": {annPath: "/.hls/live//cam1", prefix: "/.hls/", want: "/live/cam1", wantOK: true}, - "a name with dots": {annPath: "/.hls/live/cam1..hd", prefix: "/.hls/", want: "/live/cam1..hd", wantOK: true}, - "a . segment": {annPath: "/.hls/live/./cam1", prefix: "/.hls/", wantOK: false}, - "climbing into another's directory": {annPath: "/.hls/acme/../victim/cam", prefix: "/.hls/", wantOK: false}, - "climbing out of the prefix": {annPath: "/.hls/../victim/cam", prefix: "/.hls/", wantOK: false}, - "a trailing ..": {annPath: "/.hls/acme/..", prefix: "/.hls/", wantOK: false}, - } - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - got, ok := broadcastPathFromAnnounce(tt.annPath, tt.prefix) - assert.Equal(t, tt.wantOK, ok) - assert.Equal(t, tt.want, got) - }) - } -} - func Test_renderMasterPlaylist(t *testing.T) { t.Run("single video track", func(t *testing.T) { tracks := []trackInfo{ diff --git a/internal/hlsoptin/optin.go b/internal/hlsoptin/optin.go deleted file mode 100644 index 6cfd2902..00000000 --- a/internal/hlsoptin/optin.go +++ /dev/null @@ -1,19 +0,0 @@ -// Package hlsoptin serves a publisher's opt-in to the HLS egress: the -// announcement beneath token.HLSDirectory that asks qumo hls to serve a -// broadcast. It is kept apart from the egress so a publisher need not import -// it. -package hlsoptin - -import "github.com/qumo-dev/gomoqt/moqt" - -// Handler serves the opt-in of broadcast, announced as broadcast's path -// beneath token.HLSDirectory: it redirects every subscription to broadcast, -// keeping the track name, and refuses a subscriber that does not follow -// redirects with NOT_FOUND. The egress follows a redirect only to broadcast. -func Handler(broadcast moqt.BroadcastPath) moqt.TrackHandler { - return moqt.TrackHandlerFunc(func(tw *moqt.TrackWriter) { - if err := tw.Redirect(tw.Context(), moqt.Redirect{BroadcastPath: broadcast}); err != nil { - tw.CloseWithError(moqt.SubscribeErrorCodeNotFound) - } - }) -} diff --git a/internal/integration/abr_auth_test.go b/internal/integration/abr_auth_test.go new file mode 100644 index 00000000..6c19b738 --- /dev/null +++ b/internal/integration/abr_auth_test.go @@ -0,0 +1,135 @@ +//go:build integration + +package integration + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/qumo-dev/gomoqt/msf" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/qumo-dev/qumo/internal/abr" + "github.com/qumo-dev/qumo/internal/auth" + "github.com/qumo-dev/qumo/internal/optin" + "github.com/qumo-dev/qumo/internal/relay" + "github.com/qumo-dev/qumo/token" +) + +// verifierFor returns a Verifier trusting keys, as a key set lists them. +func verifierFor(t *testing.T, keys ...token.Key) *auth.Verifier { + t.Helper() + set, err := token.MarshalKeySet(keys...) + require.NoError(t, err) + path := filepath.Join(t.TempDir(), "keys.json") + require.NoError(t, os.WriteFile(path, set, 0o600)) + v, err := auth.NewVerifier(auth.VerifierConfig{Keys: path}) + require.NoError(t, err) + return v +} + +// TestABR_PaidOptIn runs the opt-in against a relay that verifies tokens, as +// a control plane sells ABR: the tenant's key holds the ABR opt-in once the +// key set lists it (optIns), which the control plane sets when ABR is paid +// for. Unpaid, a ticket for the opt-in is refused, the opt-in is not routed +// and nothing is transcoded; paid, the same ticket is granted, the opt-in is +// routed and the transcoder, connected with its own credential +// (abr.RelayGrant), publishes the ABR broadcast. +func TestABR_PaidOptIn(t *testing.T) { + tests := map[string]struct { + optIns []token.OptIn // the key set's optIns for the tenant's key + paid bool + }{ + "unpaid: the key set lists no ABR": {optIns: nil}, + "unpaid: an empty list": {optIns: []token.OptIn{}}, + "paid: the key set lists ABR": {optIns: []token.OptIn{token.OptInHLS, token.OptInABR}, paid: true}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + runPaidOptIn(t, tt.optIns, tt.paid) + }) + } +} + +func runPaidOptIn(t *testing.T, optIns []token.OptIn, paid bool) { + const ( + src = moqt.BroadcastPath("/live/paid") + dst = moqt.BroadcastPath("/live/paid.abr") + ) + optInPath := optin.Path(token.ABRDirectory, src) + newKey := func(prefix string) token.SigningKey { + k, err := token.GenerateKey(prefix) + require.NoError(t, err) + return k + } + tenant := newKey("/live/") // the tenant's key; its app signs every token below + operator := newKey("/") // the transcoder's (RELAY_SIGNING_KEY) + tenantPub := tenant.Public() + tenantPub.OptIns = optIns + verifier := verifierFor(t, tenantPub, operator.Public()) + addr, srv := startAuthRelay(t, verifier.Authorize, nil, func(s *relay.Server) { s.Tickets = verifier }) + sign := func(key token.SigningKey, g token.Grant) string { + tok, err := token.Sign(key, g, time.Minute) + require.NoError(t, err) + return tok + } + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + // The broadcast: a catalog listing one audio track. + b, err := msf.NewBroadcast(msf.Catalog{Version: 1}) + require.NoError(t, err) + require.NoError(t, b.RegisterTrack(msf.Track{ + Name: "audio", Packaging: msf.PackagingLOC, Role: msf.RoleAudio, IsLive: new(true), + Codec: "opus", SampleRate: new(int64(48000)), ChannelConfig: "2", + }, moqt.TrackHandlerFunc(func(tw *moqt.TrackWriter) { <-tw.Context().Done() }))) + pubMux := moqt.NewTrackMux(0) + pubMux.Publish(ctx, src, b) + // Native QUIC, as TestRelay_Tickets uses: over WebTransport, a relay + // closing a session that holds a granted ticket waits on its Auth + // Stream's reader, which waits on the session to be gone. + pub := dialOver(t, nativeURL(addr)+"/?jwt="+sign(tenant, token.Grant{Root: "/live/", Publish: []string{"/paid"}}), nil, pubMux) + require.Eventually(t, routed(srv, src), 5*time.Second, 25*time.Millisecond) + + // The transcoder, with the credential qumo abr signs for itself. Native + // QUIC as well: a WebTransport session the relay closes at shutdown can + // wait on its streams for good (webtransport-go), holding the cleanup. + abrMux := moqt.NewTrackMux(0) + abrSess := dialOver(t, nativeURL(addr)+"/?jwt="+sign(operator, abr.RelayGrant()), nil, abrMux) + tc := &abr.Transcoder{Suffix: ".abr", Config: abr.Config{ + Ladder: []abr.Rung{{Height: 360, Bitrate: 800_000}}, + Encoder: abr.EncoderConfig{FFmpeg: "ffmpeg", Codec: "libx264"}, + }} + go func() { _ = tc.Serve(ctx, abrSess, abrMux) }() + + // The publisher's app signs a ticket for the opt-in with the tenant's + // key, on the same session: whether the key holds it is the key set's. + actx, acancel := context.WithTimeout(ctx, 3*time.Second) + defer acancel() + cred, err := pub.Auth(actx, []byte(sign(tenant, token.Grant{Root: "/.abr/live/", Publish: []string{"/paid"}}))) + if !paid { + authErr, ok := errors.AsType[*moqt.AuthError](err) + require.True(t, ok, "the ticket is refused with AUTH_ERROR, not %v", err) + assert.Equal(t, moqt.UnauthorizedSessionErrorCode, authErr.Code) + + pubMux.Publish(ctx, optInPath, optin.Handler(src)) + assert.Never(t, func() bool { return routed(srv, optInPath)() || routed(srv, dst)() }, + 2*time.Second, 25*time.Millisecond, "an opt-in was announced without ABR paid for") + return + } + require.NoError(t, err, "the ticket is granted once ABR is paid for") + t.Cleanup(func() { _ = cred.Close() }) + assert.Equal(t, "/.abr/live/", cred.Grant().Root) + + pubMux.Publish(ctx, optInPath, optin.Handler(src)) + require.Eventually(t, routed(srv, optInPath), 5*time.Second, 25*time.Millisecond) + require.Eventually(t, routed(srv, dst), 10*time.Second, 50*time.Millisecond, + "the transcoder, on its own credential, did not publish the ABR broadcast") +} diff --git a/internal/integration/abr_test.go b/internal/integration/abr_test.go index 8a3b66b8..c99cc864 100644 --- a/internal/integration/abr_test.go +++ b/internal/integration/abr_test.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "net" + "slices" "sync" "testing" "time" @@ -21,24 +22,28 @@ import ( "github.com/qumo-dev/qumo/internal/abr" "github.com/qumo-dev/qumo/internal/cmaf" "github.com/qumo-dev/qumo/internal/ffpub" - "github.com/qumo-dev/qumo/internal/hlsoptin" "github.com/qumo-dev/qumo/internal/ingest" + "github.com/qumo-dev/qumo/internal/optin" + "github.com/qumo-dev/qumo/token" ) // TestABR_RenditionsBesideSource publishes a 720p broadcast over RTMP to an -// ingest behind a relay, runs the ABR transcoder against the relay, and -// subscribes to the ABR broadcast it publishes: the catalog lists the source -// video and each rendition shorter than it in one alternate group, and every -// video track numbers its groups as the source does, each group starting at -// the same frame with a keyframe. +// ingest behind a relay, opts it into the ABR transcoder beneath /.abr/, runs +// the transcoder against the relay, and subscribes to the ABR broadcast it +// publishes: the catalog lists the source video and each rendition shorter +// than it in one alternate group, and every video track numbers its groups as +// the source does, each group starting at the same frame with a keyframe. func TestABR_RenditionsBesideSource(t *testing.T) { if !ffpub.Available() { t.Skip("ffmpeg not on PATH") } const ( - src = moqt.BroadcastPath("/live/abrtest") - dst = moqt.BroadcastPath("/live/abrtest.abr") - alias = moqt.BroadcastPath("/.hls/live/abrtest") + src = moqt.BroadcastPath("/live/abrtest") + dst = moqt.BroadcastPath("/live/abrtest.abr") + // A broadcast announced without an opt-in. + plain = moqt.BroadcastPath("/live/plain") + // An opt-in that redirects to another's broadcast than its own. + misdirected = moqt.BroadcastPath("/live/misdirected") ) addr, srv := startAuthRelay(t, authOff, nil) url := "https://" + addr + "/" @@ -71,9 +76,14 @@ func TestABR_RenditionsBesideSource(t *testing.T) { pubCtx, stopPub := context.WithCancel(ctx) defer stopPub() require.NoError(t, pub.Start(pubCtx)) - // An HLS opt-in for the source: an alias, which redirects every - // subscription to it, and which is not to be transcoded again. - ingestMux.Publish(ctx, alias, hlsoptin.Handler(src)) + // The opt-in, as an MoQ publisher announces it: no media, a redirect to + // the broadcast. It may be withdrawn on its own. + optInCtx, withdraw := context.WithCancel(ctx) + defer withdraw() + ingestMux.Publish(optInCtx, optin.Path(token.ABRDirectory, src), optin.Handler(src)) + // Neither of these is transcoded. + ingestMux.PublishFunc(ctx, plain, func(tw *moqt.TrackWriter) { tw.CloseWithError(moqt.SubscribeErrorCodeNotFound) }) + ingestMux.Publish(ctx, optin.Path(token.ABRDirectory, misdirected), optin.Handler(src)) t.Cleanup(func() { stopPub() // ffmpeg publishes until its context ends _ = pub.Wait() @@ -82,18 +92,25 @@ func TestABR_RenditionsBesideSource(t *testing.T) { // The transcoder. tc := &abr.Transcoder{ - Prefix: "/", Suffix: ".abr", Config: abr.Config{ Ladder: []abr.Rung{{Height: 360, Bitrate: 800_000}, {Height: 240, Bitrate: 400_000}}, Encoder: abr.EncoderConfig{FFmpeg: "ffmpeg", Codec: "libx264", Preset: "ultrafast"}, }, } + // Every announcement beneath /live/ from here on, however briefly made. + watcher := dialOver(t, url, nil, moqt.NewTrackMux(0)) + announced := watchAnnouncements(t, ctx, watcher, "/live/") + abrMux := moqt.NewTrackMux(0) abrSess := dialOver(t, url, nil, abrMux) go func() { _ = tc.Serve(ctx, abrSess, abrMux) }() require.Eventually(t, routed(srv, dst), 10*time.Second, 50*time.Millisecond) - require.Never(t, routed(srv, alias+".abr"), 3*time.Second, 100*time.Millisecond, "the alias was transcoded") + // Long enough for a refused opt-in to have been retried, had it been. + time.Sleep(3 * time.Second) + for _, p := range []moqt.BroadcastPath{plain + ".abr", misdirected + ".abr"} { + assert.NotContains(t, announced(), p, "a broadcast was transcoded without its own opt-in") + } // The viewer. viewer := dialOver(t, url, nil, moqt.NewTrackMux(0)) @@ -178,6 +195,18 @@ func TestABR_RenditionsBesideSource(t *testing.T) { } }) + t.Run("withdrawing the opt-in ends the ABR broadcast", func(t *testing.T) { + require.True(t, routed(srv, dst)(), "routed while opted in") + withdraw() + require.Eventually(t, func() bool { return !routed(srv, dst)() }, 15*time.Second, 100*time.Millisecond, + "the ABR broadcast outlived its opt-in") + require.True(t, routed(srv, src)(), "the source itself plays on") + + // Opting in again brings it back. + ingestMux.Publish(ctx, optin.Path(token.ABRDirectory, src), optin.Handler(src)) + require.Eventually(t, routed(srv, dst), 15*time.Second, 100*time.Millisecond) + }) + t.Run("the ABR broadcast ends with its source", func(t *testing.T) { require.True(t, routed(srv, dst)(), "routed while the source plays") stopPub() @@ -186,6 +215,32 @@ func TestABR_RenditionsBesideSource(t *testing.T) { }) } +// watchAnnouncements records every broadcast announced beneath prefix on +// sess from now until ctx ends, and returns what it has recorded so far. +// Unlike polling a route, it misses no announcement however brief. +func watchAnnouncements(t *testing.T, ctx context.Context, sess *moqt.Session, prefix string) func() []moqt.BroadcastPath { + t.Helper() + ar, err := sess.AcceptAnnounce(prefix) + require.NoError(t, err) + var ( + mu sync.Mutex + seen []moqt.BroadcastPath + ) + go func() { + defer ar.Close() + for ann := range ar.Announcements(ctx) { + mu.Lock() + seen = append(seen, ann.BroadcastPath()) + mu.Unlock() + } + }() + return func() []moqt.BroadcastPath { + mu.Lock() + defer mu.Unlock() + return slices.Clone(seen) + } +} + // waitCatalog subscribes to path's catalog and returns the first one that // lists every track in want. func waitCatalog(t *testing.T, sess *moqt.Session, path moqt.BroadcastPath, want []string) msf.Catalog { diff --git a/internal/integration/relay_optin_paths_test.go b/internal/integration/relay_optin_paths_test.go index dc7d7575..6cc28b7b 100644 --- a/internal/integration/relay_optin_paths_test.go +++ b/internal/integration/relay_optin_paths_test.go @@ -19,7 +19,7 @@ import ( // /.hls/acme/ announces /.hls/acme/../victim/cam, which cleans to an opt-in // for /victim/cam. So the HLS egress, which may read every broadcast, must // refuse an opt-in path with a "." or ".." segment rather than clean it -// (broadcastPathFromAnnounce). +// (optin.Broadcast). func TestRelay_RoutesOptInDotSegmentsAsGranted(t *testing.T) { key, _, keysFile := writeKeys(t) verifier, err := auth.NewVerifier(auth.VerifierConfig{Keys: keysFile}) diff --git a/internal/optin/optin.go b/internal/optin/optin.go new file mode 100644 index 00000000..ae8b3241 --- /dev/null +++ b/internal/optin/optin.go @@ -0,0 +1,67 @@ +// Package optin serves and reads a publisher's opt-in to an egress: an +// announcement beneath an opt-in directory (token.HLSDirectory, +// token.ABRDirectory) that asks the egress to serve a broadcast. The opt-in +// for /live/cam1 is /.hls/live/cam1 or /.abr/live/cam1. It carries no media: +// it redirects every subscription to the broadcast, which the egress follows. +// It is kept apart from the egresses so a publisher need not import them. +package optin + +import ( + "path" + "strings" + + "github.com/qumo-dev/gomoqt/moqt" +) + +// Handler serves the opt-in of broadcast, announced as broadcast's path +// beneath an opt-in directory: it redirects every subscription to broadcast, +// keeping the track name, and refuses a subscriber that does not follow +// redirects with NOT_FOUND. An egress follows a redirect only to broadcast. +func Handler(broadcast moqt.BroadcastPath) moqt.TrackHandler { + return moqt.TrackHandlerFunc(func(tw *moqt.TrackWriter) { + if err := tw.Redirect(tw.Context(), moqt.Redirect{BroadcastPath: broadcast}); err != nil { + tw.CloseWithError(moqt.SubscribeErrorCodeNotFound) + } + }) +} + +// Path returns the opt-in of broadcast beneath dir, an opt-in directory: +// Path("/.abr/", "/live/cam1") is "/.abr/live/cam1". +func Path(dir string, broadcast moqt.BroadcastPath) moqt.BroadcastPath { + return moqt.BroadcastPath(strings.TrimSuffix(dir, "/") + "/" + strings.TrimPrefix(string(broadcast), "/")) +} + +// Broadcast returns the broadcast an opt-in announced as optIn, beneath dir, +// asks an egress to serve: optIn with dir stripped, cleaned of doubled and +// trailing slashes. +// +// Broadcast("/.hls/live/cam1", "/.hls/") is "/live/cam1" +// Broadcast("/.hls/cam", "/.hls/") is "/cam" +// Broadcast("/.hls", "/.hls/") is "/" +// +// It reports false for an opt-in with a "." or ".." segment. A relay grants +// and routes exact paths, so /.hls/acme/../victim/cam is announced under a +// grant for /.hls/acme/, yet cleans to /victim/cam, which an egress can read +// and would serve. +func Broadcast(optIn, dir string) (string, bool) { + p := strings.TrimPrefix(optIn, strings.TrimSuffix(dir, "/")) + if !strings.HasPrefix(p, "/") { + p = "/" + p + } + if HasDotSegment(p) { + return "", false + } + return path.Clean(p), true +} + +// HasDotSegment reports whether p, a broadcast path, has a "." or ".." +// segment, which cleaning it would resolve into another path than the one a +// relay routes. +func HasDotSegment(p string) bool { + for seg := range strings.SplitSeq(p, "/") { + if seg == "." || seg == ".." { + return true + } + } + return false +} diff --git a/internal/optin/optin_test.go b/internal/optin/optin_test.go new file mode 100644 index 00000000..d63c69bd --- /dev/null +++ b/internal/optin/optin_test.go @@ -0,0 +1,78 @@ +package optin + +import ( + "testing" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/stretchr/testify/assert" + + "github.com/qumo-dev/qumo/token" +) + +// An opt-in's broadcast is its path with the directory stripped, cleaned of +// doubled and trailing slashes; one with a "." or ".." segment names none, as +// cleaning it could climb out of the directory the relay granted it in. +func TestBroadcast(t *testing.T) { + tests := map[string]struct { + optIn, dir string + want string + wantOK bool + }{ + "HLS, directory with a trailing slash": {optIn: "/.hls/live/cam1", dir: "/.hls/", want: "/live/cam1", wantOK: true}, + "HLS, directory without a trailing slash": {optIn: "/.hls/live/cam1", dir: "/.hls", want: "/live/cam1", wantOK: true}, + "ABR": {optIn: "/.abr/live/cam1", dir: token.ABRDirectory, want: "/live/cam1", wantOK: true}, + "a single segment": {optIn: "/.hls/cam", dir: "/.hls/", want: "/cam", wantOK: true}, + "a broadcast named like hls": {optIn: "/.hls/hls/live", dir: "/.hls/", want: "/hls/live", wantOK: true}, + "another directory": {optIn: "/custom/stream/room1", dir: "/custom/stream/", want: "/room1", wantOK: true}, + "the bare directory": {optIn: "/.hls", dir: "/.hls/", want: "/", wantOK: true}, + "a trailing slash": {optIn: "/.hls/live/cam1/", dir: "/.hls/", want: "/live/cam1", wantOK: true}, + "a doubled slash": {optIn: "/.hls/live//cam1", dir: "/.hls/", want: "/live/cam1", wantOK: true}, + "a name with dots": {optIn: "/.hls/live/cam1..hd", dir: "/.hls/", want: "/live/cam1..hd", wantOK: true}, + "a . segment": {optIn: "/.abr/live/./cam1/", dir: "/.abr/", wantOK: false}, + "climbing into another's directory": {optIn: "/.hls/acme/../victim/cam", dir: "/.hls/", wantOK: false}, + "climbing out of the directory": {optIn: "/.hls/../victim/cam", dir: "/.hls/", wantOK: false}, + "a trailing ..": {optIn: "/.hls/acme/..", dir: "/.hls/", wantOK: false}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + got, ok := Broadcast(tt.optIn, tt.dir) + assert.Equal(t, tt.wantOK, ok) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestHasDotSegment(t *testing.T) { + tests := map[string]struct { + path string + want bool + }{ + "plain": {path: "/acme/cam", want: false}, + "dots in a name": {path: "/acme/cam..hd", want: false}, + "a . segment": {path: "/acme/./cam", want: true}, + "a .. segment": {path: "/acme/../cam", want: true}, + "a trailing ..": {path: "/acme/..", want: true}, + "empty segments": {path: "/acme//cam/", want: false}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + assert.Equal(t, tt.want, HasDotSegment(tt.path)) + }) + } +} + +func TestPath(t *testing.T) { + assert.Equal(t, moqt.BroadcastPath("/.abr/live/cam1"), Path(token.ABRDirectory, "/live/cam1")) + assert.Equal(t, moqt.BroadcastPath("/.hls/live/cam1"), Path("/.hls", "/live/cam1")) + assert.Equal(t, moqt.BroadcastPath("/.abr/cam"), Path(token.ABRDirectory, "cam")) +} + +func TestPathRoundTrip(t *testing.T) { + for _, dir := range []string{token.HLSDirectory, token.ABRDirectory} { + for _, b := range []string{"/live/cam1", "/a", "/room/42/cam"} { + got, ok := Broadcast(string(Path(dir, moqt.BroadcastPath(b))), dir) + assert.True(t, ok, "%s %s", dir, b) + assert.Equal(t, b, got, "%s %s", dir, b) + } + } +} diff --git a/internal/relaycred/relaycred.go b/internal/relaycred/relaycred.go index c3a1cf33..e46497e5 100644 --- a/internal/relaycred/relaycred.go +++ b/internal/relaycred/relaycred.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "log/slog" + "net/url" "time" "github.com/qumo-dev/gomoqt/moqt" @@ -39,6 +40,26 @@ func Sign(key token.SigningKey, g token.Grant) (string, time.Time, error) { return tok, lapses, nil } +// Target returns relayURL carrying a credential granting g, freshly signed +// with key, as ?jwt= in place of any it carried, and when that credential's +// grant lapses (Sign). +func Target(relayURL string, key token.SigningKey, g token.Grant) (string, time.Time, error) { + credential, lapses, err := Sign(key, g) + if err != nil { + return "", time.Time{}, err + } + u, err := url.Parse(relayURL) + if err != nil { + // url.Parse's error quotes the URL, whose query may carry a + // credential: report only that it is invalid. + return "", time.Time{}, errors.New("RELAY_URL: invalid URL") + } + query := u.Query() + query.Set("jwt", credential) + u.RawQuery = query.Encode() + return u.String(), lapses, nil +} + // credential is a token presented on an Auth Stream, as keeping a grant in // force needs one: *moqt.Credential. type credential interface { diff --git a/internal/upstream/upstream.go b/internal/upstream/upstream.go index ce677f18..cffbeb19 100644 --- a/internal/upstream/upstream.go +++ b/internal/upstream/upstream.go @@ -210,18 +210,7 @@ func (u *Upstream) target() (string, time.Time, error) { if u.key == nil { return u.url, time.Time{}, nil } - credential, lapses, err := relaycred.Sign(*u.key, publishGrant(u.publish)) - if err != nil { - return "", time.Time{}, err - } - parsed, err := url.Parse(u.url) - if err != nil { - return "", time.Time{}, err - } - query := parsed.Query() - query.Set("jwt", credential) - parsed.RawQuery = query.Encode() - return parsed.String(), lapses, nil + return relaycred.Target(u.url, *u.key, publishGrant(u.publish)) } // RelayName describes relayURL for a startup banner without its credential: diff --git a/playground/dist/assets/index-B2Q5waeK.css b/playground/dist/assets/index-B2Q5waeK.css deleted file mode 100644 index e566216b..00000000 --- a/playground/dist/assets/index-B2Q5waeK.css +++ /dev/null @@ -1 +0,0 @@ -:root{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light dark;font-synthesis:none;text-rendering:optimizelegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;--app-max-width:1200px;--gap:16px;--radius:12px;--radius-sm:8px;--transition:.15s ease;--bg:#161619;--surface:#1e1e24;--surface-2:#27272e;--border:#33333c;--text:#ffffffeb;--text-muted:#ffffff8c;--accent:#646cff;--accent-hover:#535bf2;--ok:#3ddc84;--warn:#ffb02e;--err:#ff5a5f;--on-accent:#fff;--on-ok:#062a14;--on-err:#2a0606;--video-bg:#000;--overlay-bg:#000000a6;--overlay-text:#fff;--overlay-text-muted:#fff9;--group-complete:var(--text-muted);--group-receiving:var(--accent);--group-skipped:var(--warn);--group-aborted:var(--err);--group-late:var(--text-muted);--group-stopped:var(--text-muted);--group-rendered:var(--ok);--shadow-sm:0 1px 3px #0000003d;--shadow-md:0 4px 12px #0000004d;font-family:system-ui,Avenir,Helvetica,Arial,sans-serif;font-weight:400;line-height:1.5}@media (prefers-color-scheme:dark){:root{--lightningcss-light: ;--lightningcss-dark:initial}}@media (prefers-color-scheme:light){:root{--bg:#f4f4f8;--surface:#fff;--surface-2:#eef0f4;--border:#d4d4de;--text:#1a1f2b;--text-muted:#5a6473;--accent:#5552ff;--accent-hover:#4744e0;--ok:#1a9f54;--warn:#c47700;--err:#d23b40;--shadow-sm:0 1px 3px #00000014;--shadow-md:0 4px 12px #0000001a}}html,body{min-width:320px;min-height:100vh;margin:0}body{background:var(--bg);color:var(--text)}#root{width:100%}h1{margin:0;font-size:clamp(1.8rem,4vw,2.8rem);line-height:1.1}h2{margin:0 0 var(--gap) 0;font-size:1.15rem}a{color:var(--accent);-webkit-text-decoration:inherit;text-decoration:inherit}a:hover{color:var(--accent-hover)}code{background:var(--surface-2);border-radius:4px;padding:.1em .35em;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.85em}input,select,button{color:var(--text);font-family:inherit;font-size:.95rem}input,select{background:var(--surface-2);border:1px solid var(--border);border-radius:8px;padding:.45em .6em}input:focus,select:focus{outline:2px solid var(--accent);outline-offset:1px}button{border:1px solid var(--border);background:var(--surface-2);cursor:pointer;border-radius:8px;padding:.5em 1.1em;font-weight:500;transition:border-color .2s,background .2s,opacity .2s}button:hover:not(:disabled){border-color:var(--accent)}button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button:disabled{opacity:.5;cursor:not-allowed}.app{max-width:var(--app-max-width);text-align:left;margin:0 auto;padding:24px 20px 48px}.app-header{border-bottom:1px solid var(--border);margin-bottom:24px;padding-bottom:16px}.app-subtitle{color:var(--text-muted);margin:6px 0 0;font-size:.95rem}.dashboard{gap:var(--gap);flex-direction:column;display:flex}.top-controls{align-items:center;gap:var(--gap);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-sm);flex-wrap:wrap;padding:14px 18px;display:flex}.segmented{background:var(--surface-2);border:1px solid var(--border);border-radius:10px;flex-wrap:wrap;gap:4px;padding:4px;display:inline-flex}.segmented-btn{color:var(--text-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:7px;padding:.35em .9em;font-weight:500}.segmented-btn:hover:not(.active):not(:disabled){color:var(--text)}.segmented-btn.active{background:var(--accent);color:var(--on-accent);border-color:#0000}.segmented-btn:disabled{cursor:not-allowed;opacity:.5}.source-icon{vertical-align:-.2em;width:1.05em;height:1.05em;display:inline-block}.path-control{flex-wrap:wrap;align-items:center;gap:8px;min-width:0;margin-left:auto;display:flex}.path-control>label{color:var(--text-muted);font-size:.8rem}.path-input-field{min-width:16ch;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.path-hint{color:var(--text-muted);font-size:.8rem}.copy-btn{background:var(--surface-2);border:1px solid var(--border);color:var(--text);cursor:pointer;border-radius:8px;padding:.4em .8em;font-size:.85rem}.copy-btn:hover:not(:disabled){border-color:var(--accent)}.push-instructions{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-sm);padding:14px 16px}.push-instructions-head{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:8px;font-size:.9rem;display:flex}.push-instructions pre{background:var(--surface-2);border:1px solid var(--border);border-radius:8px;margin:0;padding:10px 12px;overflow-x:auto}.push-instructions pre code{white-space:pre;background:0 0;padding:0;font-size:.82rem}.connection-status{flex-wrap:wrap;align-items:center;gap:8px;min-width:0;font-size:.9rem;display:flex}.status-dot{background:var(--text-muted);border-radius:50%;flex:none;width:10px;height:10px;box-shadow:0 0}.connection-status[data-state=connecting] .status-dot{background:var(--warn);animation:1.4s ease-in-out infinite pulse}.connection-status[data-state=connected] .status-dot{background:var(--ok)}.connection-status[data-state=closed] .status-dot{background:var(--warn)}.connection-status[data-state=failed] .status-dot{background:var(--err)}.status-label{font-weight:600}.status-reason,.status-warn{color:var(--text-muted);font-size:.85rem}.connection-status[data-state=failed] .status-reason{color:var(--err)}.status-warn{color:var(--warn)}@keyframes pulse{0%,to{opacity:1}50%{opacity:.4}}.boards{gap:var(--gap);grid-template-columns:repeat(2,minmax(0,1fr));align-items:start;display:grid}@media (width<=760px){.boards{grid-template-columns:minmax(0,1fr)}}.boards.single{grid-template-columns:minmax(0,1fr)}.publish-board,.subscribe-board{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);min-width:0;box-shadow:var(--shadow-sm);transition:box-shadow var(--transition);padding:18px}.publish-board:hover,.subscribe-board:hover{box-shadow:var(--shadow-md)}.controls{flex-wrap:wrap;align-items:flex-end;gap:12px;margin-bottom:12px;display:flex}.source-selector,.path-input{flex-direction:column;gap:4px;display:flex}.source-selector label,.path-input label{color:var(--text-muted);font-size:.8rem}.path-input input{min-width:14ch;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.stream-controls{margin-left:auto}.encoder-controls{flex-wrap:wrap;align-items:flex-end;gap:12px;display:flex}.encoder-controls label{color:var(--text-muted);flex-direction:column;gap:4px;font-size:.8rem;display:flex}.bitrate-control{min-width:16ch}.bitrate-value{color:var(--text-muted);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.75rem}input[type=range]{accent-color:var(--accent);width:12ch}.viewer-controls{align-items:center;gap:8px;margin-top:12px;display:flex}.viewer-controls .copy-btn{padding:.35em .6em;font-size:1rem;line-height:1}.volume-slider{flex:1;max-width:160px}.rendition-select{border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface-2);color:inherit;font:inherit;margin-left:auto;padding:.3em .5em}.video-empty{aspect-ratio:16/9;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface-2);width:100%;color:var(--text-muted);text-align:center;flex-direction:column;justify-content:center;align-items:center;gap:8px;padding:20px;font-size:.9rem;display:flex}.video-empty-icon{opacity:.4;font-size:2rem}.video-preview:fullscreen{background:var(--video-bg);border-radius:0;justify-content:center;align-items:center;width:100vw;height:100vh;display:flex}.video-preview:fullscreen canvas{border:none;border-radius:0;width:auto!important;max-width:100%!important;height:100%!important;aspect-ratio:unset!important}.btn-start{background:var(--ok);color:var(--on-ok);transition:filter var(--transition);border-color:#0000;font-weight:600}.btn-start:hover:not(:disabled){filter:brightness(1.08);border-color:#0000}.btn-stop{background:var(--err);color:var(--on-err);transition:filter var(--transition);border-color:#0000;font-weight:600}.btn-stop:hover:not(:disabled){filter:brightness(1.08);border-color:#0000}.error-message{background:color-mix(in srgb, var(--err) 14%, transparent);border:1px solid var(--err);color:var(--err);border-radius:8px;margin-bottom:12px;padding:8px 12px;font-size:.9rem}.status-message{background:var(--surface-2);border:1px solid var(--border);color:var(--text-muted);border-radius:8px;margin-bottom:12px;padding:8px 12px;font-size:.85rem}.video-preview{width:100%;position:relative}.video-preview canvas,.video-preview video{aspect-ratio:16/9;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--video-bg);display:block;width:100%!important;max-width:100%!important;height:auto!important}.video-preview--waiting video{background:var(--surface)}.stats-overlay{background:var(--overlay-bg);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);border-radius:var(--radius-sm);color:var(--overlay-text);pointer-events:none;-webkit-user-select:none;user-select:none;flex-wrap:wrap;gap:4px 14px;margin:0;padding:5px 10px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.75rem;line-height:1.5;display:flex;position:absolute;top:8px;left:8px}.stats-overlay>div{gap:4px;display:inline-flex}.stats-overlay dt{color:var(--overlay-text-muted)}.stats-overlay dd{margin:0}.scenario-desc{color:var(--text-muted);margin-top:8px;font-size:.85rem}.camera-pull-form{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-sm);margin-bottom:var(--gap);padding:14px 16px}.camera-pull-form label{color:var(--text-muted);margin-bottom:4px;font-size:.8rem;display:block}.camera-pull-input{box-sizing:border-box;width:100%;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.85rem}.camera-pull-actions{margin-top:var(--gap)}.camera-pull-status{color:var(--text-muted);align-items:center;gap:6px;margin-top:8px;font-size:.85rem;display:flex}.camera-pull-status[data-state=connecting]{color:var(--warn)}.camera-pull-status[data-state=active]{color:var(--ok)}.camera-pull-status[data-state=error]{color:var(--err)}.devtools{margin-top:var(--gap);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-sm)}.devtools-toggle{border-radius:var(--radius);width:100%;color:var(--text);font:inherit;text-align:left;cursor:pointer;background:0 0;border:0;align-items:center;gap:8px;padding:10px 16px;font-weight:600;display:flex}.devtools-toggle-mark{color:var(--text-muted)}.devtools-body{gap:var(--gap);padding:4px 16px 16px;display:grid}.devtools-empty{color:var(--text-muted);margin:0;font-size:.85rem}.devtools-session{flex-wrap:wrap;gap:4px 24px;margin:0;font-size:.85rem;display:flex}.devtools-session>div{gap:6px;display:inline-flex}.devtools-session dt{color:var(--text-muted)}.devtools-session dd{font-variant-numeric:tabular-nums;margin:0}.devtools-status{align-items:baseline;gap:8px;margin:0;font-size:.95rem;display:flex}.devtools-status-mark{background:var(--text-muted);border-radius:50%;flex:none;width:.6em;height:.6em}.devtools-status.is-ok .devtools-status-mark{background:var(--ok)}.devtools-status.is-warn .devtools-status-mark{background:var(--warn)}.devtools-status.is-bad .devtools-status-mark{background:var(--err)}.devtools-session>div[title],.devtools-tracks th[title],.devtools-legend [title]{cursor:help}.devtools-more{font-size:.85rem}.devtools-more summary{width:fit-content;color:var(--text-muted);cursor:pointer}.devtools-more[open] summary{margin-bottom:8px}.devtools-more .devtools-session+.devtools-session{margin-top:4px}.devtools-hint{color:var(--text-muted);margin:0;font-size:.8rem}.devtools-log{gap:8px;display:grid}.devtools-heading{margin:0;font-size:.85rem;font-weight:600}.devtools-events{background:var(--surface-2);border-radius:var(--radius-sm);max-height:14em;margin:0;padding:8px 12px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.8rem;list-style:none;overflow-y:auto}.devtools-events ol{color:var(--text-muted);margin:0;padding:0 0 4px;list-style:none}.devtools-events li,.devtools-events summary{gap:12px;display:flex}.devtools-events>li{border-left:2px solid #0000;padding-left:8px}.devtools-events>li:hover{background:var(--surface)}.devtools-events details{flex:1;min-width:0}.devtools-events summary{cursor:pointer;list-style:none}.devtools-events summary::-webkit-details-marker{display:none}.devtools-events summary>span:after{content:" ▸";color:var(--text-muted)}.devtools-events details[open] summary>span:after{content:" ▾"}.devtools-events time{color:var(--text-muted);flex:none}.devtools-events li.is-warn{border-left-color:var(--warn)}.devtools-events li.is-bad{border-left-color:var(--err)}.devtools-scroll{overflow-x:auto}.devtools-tracks{border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;font-size:.85rem}.devtools-tracks th,.devtools-tracks td{border-bottom:1px solid var(--border);text-align:right;white-space:nowrap;padding:4px 12px 4px 0}.devtools-tracks th:first-child{text-align:left}.devtools-tracks thead th{color:var(--text-muted);font-weight:400}.devtools-timeline{gap:10px;display:grid}.devtools-controls{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;display:flex}.devtools-spans{align-items:center;gap:4px;display:inline-flex}.devtools-span{min-width:3.5em;color:var(--text-muted);font-variant-numeric:tabular-nums;text-align:right;font-size:.8rem}.devtools-controls .copy-btn[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.devtools-lane{grid-template-columns:6rem minmax(0,1fr);align-items:start;gap:8px;display:grid}.devtools-lane-name{color:var(--text-muted);font-size:.8rem}.devtools-plot-box{position:relative}.devtools-plot{cursor:grab;touch-action:pan-y;-webkit-user-select:none;user-select:none;width:100%;display:block}.devtools-plot:active{cursor:grabbing}.devtools-tip{z-index:1;background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius-sm);width:max-content;max-width:300px;box-shadow:var(--shadow-md);pointer-events:none;gap:2px;padding:6px 10px;font-size:.8rem;display:grid;position:absolute;top:calc(100% + 4px);transform:translate(-50%)}.devtools-tip time{color:var(--text-muted);font-variant-numeric:tabular-nums}.devtools-tip span:first-of-type{font-weight:600}.devtools-axis>div{color:var(--text-muted);justify-content:space-between;font-size:.75rem;display:flex}.devtools-legend{color:var(--text-muted);gap:4px;margin:0;font-size:.8rem;display:grid}.devtools-legend>div{grid-template-columns:6rem minmax(0,1fr);gap:8px;display:grid}.devtools-legend dt{color:var(--text)}.devtools-legend dd{flex-wrap:wrap;gap:2px 16px;margin:0;display:flex}.devtools-legend-mark{align-items:center;gap:6px;display:inline-flex}.devtools-swatch{width:12px;height:10px}.devtools-swatch.is-complete{background:var(--group-complete);opacity:.55}.devtools-swatch.is-receiving{background:var(--group-receiving)}.devtools-swatch.is-skipped{background:repeating-linear-gradient(45deg, var(--group-skipped) 0 2px, transparent 2px 4px)}.devtools-swatch.is-aborted{background:var(--group-aborted)}.devtools-swatch.is-late{box-sizing:border-box;border:1px solid var(--group-late)}.devtools-swatch.is-stopped{background:repeating-linear-gradient(45deg, var(--group-stopped) 0 2px, transparent 2px 4px);opacity:.7}.devtools-swatch.is-level{background:var(--group-receiving);opacity:.35}.devtools-swatch.is-glitch{background:var(--group-aborted);width:3px}.devtools-swatch.is-stall{background:var(--group-skipped);opacity:.45}.devtools-swatch.is-marker{background:var(--group-receiving);opacity:.45}.devtools-swatch.is-arrival{background:var(--group-late);height:4px}.devtools-swatch.is-held{background:var(--group-skipped);height:4px}.devtools-swatch.is-unrendered{background:var(--group-skipped);width:3px}.devtools-swatch.is-rendered{background:var(--group-rendered)} diff --git a/playground/dist/assets/index-CfmN1Zb8.css b/playground/dist/assets/index-CfmN1Zb8.css new file mode 100644 index 00000000..0446b991 --- /dev/null +++ b/playground/dist/assets/index-CfmN1Zb8.css @@ -0,0 +1 @@ +:root{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light dark;font-synthesis:none;text-rendering:optimizelegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;--app-max-width:1200px;--gap:16px;--radius:12px;--radius-sm:8px;--transition:.15s ease;--bg:#161619;--surface:#1e1e24;--surface-2:#27272e;--border:#33333c;--text:#ffffffeb;--text-muted:#ffffff8c;--accent:#646cff;--accent-hover:#535bf2;--ok:#3ddc84;--warn:#ffb02e;--err:#ff5a5f;--on-accent:#fff;--on-ok:#062a14;--on-err:#2a0606;--video-bg:#000;--overlay-bg:#000000a6;--overlay-text:#fff;--overlay-text-muted:#fff9;--group-complete:var(--text-muted);--group-receiving:var(--accent);--group-skipped:var(--warn);--group-aborted:var(--err);--group-late:var(--text-muted);--group-stopped:var(--text-muted);--group-rendered:var(--ok);--shadow-sm:0 1px 3px #0000003d;--shadow-md:0 4px 12px #0000004d;font-family:system-ui,Avenir,Helvetica,Arial,sans-serif;font-weight:400;line-height:1.5}@media (prefers-color-scheme:dark){:root{--lightningcss-light: ;--lightningcss-dark:initial}}@media (prefers-color-scheme:light){:root{--bg:#f4f4f8;--surface:#fff;--surface-2:#eef0f4;--border:#d4d4de;--text:#1a1f2b;--text-muted:#5a6473;--accent:#5552ff;--accent-hover:#4744e0;--ok:#1a9f54;--warn:#c47700;--err:#d23b40;--shadow-sm:0 1px 3px #00000014;--shadow-md:0 4px 12px #0000001a}}html,body{min-width:320px;min-height:100vh;margin:0}body{background:var(--bg);color:var(--text)}#root{width:100%}h1{margin:0;font-size:clamp(1.8rem,4vw,2.8rem);line-height:1.1}h2{margin:0 0 var(--gap) 0;font-size:1.15rem}a{color:var(--accent);-webkit-text-decoration:inherit;text-decoration:inherit}a:hover{color:var(--accent-hover)}code{background:var(--surface-2);border-radius:4px;padding:.1em .35em;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.85em}input,select,button{color:var(--text);font-family:inherit;font-size:.95rem}input,select{background:var(--surface-2);border:1px solid var(--border);border-radius:8px;padding:.45em .6em}input:focus,select:focus{outline:2px solid var(--accent);outline-offset:1px}button{border:1px solid var(--border);background:var(--surface-2);cursor:pointer;border-radius:8px;padding:.5em 1.1em;font-weight:500;transition:border-color .2s,background .2s,opacity .2s}button:hover:not(:disabled){border-color:var(--accent)}button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button:disabled{opacity:.5;cursor:not-allowed}.app{max-width:var(--app-max-width);text-align:left;margin:0 auto;padding:24px 20px 48px}.app-header{border-bottom:1px solid var(--border);margin-bottom:24px;padding-bottom:16px}.app-subtitle{color:var(--text-muted);margin:6px 0 0;font-size:.95rem}.dashboard{gap:var(--gap);flex-direction:column;display:flex}.top-controls{align-items:center;gap:var(--gap);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-sm);flex-wrap:wrap;padding:14px 18px;display:flex}.segmented{background:var(--surface-2);border:1px solid var(--border);border-radius:10px;flex-wrap:wrap;gap:4px;padding:4px;display:inline-flex}.segmented-btn{color:var(--text-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:7px;padding:.35em .9em;font-weight:500}.segmented-btn:hover:not(.active):not(:disabled){color:var(--text)}.segmented-btn.active{background:var(--accent);color:var(--on-accent);border-color:#0000}.segmented-btn:disabled{cursor:not-allowed;opacity:.5}.source-icon{vertical-align:-.2em;width:1.05em;height:1.05em;display:inline-block}.path-control{flex-wrap:wrap;align-items:center;gap:8px;min-width:0;margin-left:auto;display:flex}.path-control>label{color:var(--text-muted);font-size:.8rem}.path-input-field{min-width:16ch;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.path-hint{color:var(--text-muted);font-size:.8rem}.copy-btn{background:var(--surface-2);border:1px solid var(--border);color:var(--text);cursor:pointer;border-radius:8px;padding:.4em .8em;font-size:.85rem}.copy-btn:hover:not(:disabled){border-color:var(--accent)}.push-instructions{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-sm);padding:14px 16px}.push-instructions-head{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:8px;font-size:.9rem;display:flex}.push-instructions pre{background:var(--surface-2);border:1px solid var(--border);border-radius:8px;margin:0;padding:10px 12px;overflow-x:auto}.push-instructions pre code{white-space:pre;background:0 0;padding:0;font-size:.82rem}.connection-status{flex-wrap:wrap;align-items:center;gap:8px;min-width:0;font-size:.9rem;display:flex}.status-dot{background:var(--text-muted);border-radius:50%;flex:none;width:10px;height:10px;box-shadow:0 0}.connection-status[data-state=connecting] .status-dot{background:var(--warn);animation:1.4s ease-in-out infinite pulse}.connection-status[data-state=connected] .status-dot{background:var(--ok)}.connection-status[data-state=closed] .status-dot{background:var(--warn)}.connection-status[data-state=failed] .status-dot{background:var(--err)}.status-label{font-weight:600}.status-reason,.status-warn{color:var(--text-muted);font-size:.85rem}.connection-status[data-state=failed] .status-reason{color:var(--err)}.status-warn{color:var(--warn)}@keyframes pulse{0%,to{opacity:1}50%{opacity:.4}}.boards{gap:var(--gap);grid-template-columns:repeat(2,minmax(0,1fr));align-items:start;display:grid}@media (width<=760px){.boards{grid-template-columns:minmax(0,1fr)}}.boards.single{grid-template-columns:minmax(0,1fr)}.publish-board,.subscribe-board{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);min-width:0;box-shadow:var(--shadow-sm);transition:box-shadow var(--transition);padding:18px}.publish-board:hover,.subscribe-board:hover{box-shadow:var(--shadow-md)}.controls{flex-wrap:wrap;align-items:flex-end;gap:12px;margin-bottom:12px;display:flex}.source-selector,.path-input{flex-direction:column;gap:4px;display:flex}.source-selector label,.path-input label{color:var(--text-muted);font-size:.8rem}.path-input input{min-width:14ch;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.stream-controls{margin-left:auto}.encoder-controls{flex-wrap:wrap;align-items:flex-end;gap:12px;display:flex}.encoder-controls label{color:var(--text-muted);flex-direction:column;gap:4px;font-size:.8rem;display:flex}.bitrate-control{min-width:16ch}.encoder-controls label.abr-control{flex-direction:row;align-items:center;gap:6px}.abr-control input[type=checkbox]{accent-color:var(--accent)}.bitrate-value{color:var(--text-muted);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.75rem}input[type=range]{accent-color:var(--accent);width:12ch}.viewer-controls{align-items:center;gap:8px;margin-top:12px;display:flex}.viewer-controls .copy-btn{padding:.35em .6em;font-size:1rem;line-height:1}.volume-slider{flex:1;max-width:160px}.rendition-select{border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface-2);color:inherit;font:inherit;margin-left:auto;padding:.3em .5em}.video-empty{aspect-ratio:16/9;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface-2);width:100%;color:var(--text-muted);text-align:center;flex-direction:column;justify-content:center;align-items:center;gap:8px;padding:20px;font-size:.9rem;display:flex}.video-empty-icon{opacity:.4;font-size:2rem}.video-preview:fullscreen{background:var(--video-bg);border-radius:0;justify-content:center;align-items:center;width:100vw;height:100vh;display:flex}.video-preview:fullscreen canvas{border:none;border-radius:0;width:auto!important;max-width:100%!important;height:100%!important;aspect-ratio:unset!important}.btn-start{background:var(--ok);color:var(--on-ok);transition:filter var(--transition);border-color:#0000;font-weight:600}.btn-start:hover:not(:disabled){filter:brightness(1.08);border-color:#0000}.btn-stop{background:var(--err);color:var(--on-err);transition:filter var(--transition);border-color:#0000;font-weight:600}.btn-stop:hover:not(:disabled){filter:brightness(1.08);border-color:#0000}.error-message{background:color-mix(in srgb, var(--err) 14%, transparent);border:1px solid var(--err);color:var(--err);border-radius:8px;margin-bottom:12px;padding:8px 12px;font-size:.9rem}.status-message{background:var(--surface-2);border:1px solid var(--border);color:var(--text-muted);border-radius:8px;margin-bottom:12px;padding:8px 12px;font-size:.85rem}.video-preview{width:100%;position:relative}.video-preview canvas,.video-preview video{aspect-ratio:16/9;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--video-bg);display:block;width:100%!important;max-width:100%!important;height:auto!important}.video-preview--waiting video{background:var(--surface)}.stats-overlay{background:var(--overlay-bg);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);border-radius:var(--radius-sm);color:var(--overlay-text);pointer-events:none;-webkit-user-select:none;user-select:none;flex-wrap:wrap;gap:4px 14px;margin:0;padding:5px 10px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.75rem;line-height:1.5;display:flex;position:absolute;top:8px;left:8px}.stats-overlay>div{gap:4px;display:inline-flex}.stats-overlay dt{color:var(--overlay-text-muted)}.stats-overlay dd{margin:0}.scenario-desc{color:var(--text-muted);margin-top:8px;font-size:.85rem}.camera-pull-form{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-sm);margin-bottom:var(--gap);padding:14px 16px}.camera-pull-form label{color:var(--text-muted);margin-bottom:4px;font-size:.8rem;display:block}.camera-pull-input{box-sizing:border-box;width:100%;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.85rem}.camera-pull-actions{margin-top:var(--gap)}.camera-pull-status{color:var(--text-muted);align-items:center;gap:6px;margin-top:8px;font-size:.85rem;display:flex}.camera-pull-status[data-state=connecting]{color:var(--warn)}.camera-pull-status[data-state=active]{color:var(--ok)}.camera-pull-status[data-state=error]{color:var(--err)}.devtools{margin-top:var(--gap);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-sm)}.devtools-toggle{border-radius:var(--radius);width:100%;color:var(--text);font:inherit;text-align:left;cursor:pointer;background:0 0;border:0;align-items:center;gap:8px;padding:10px 16px;font-weight:600;display:flex}.devtools-toggle-mark{color:var(--text-muted)}.devtools-body{gap:var(--gap);padding:4px 16px 16px;display:grid}.devtools-empty{color:var(--text-muted);margin:0;font-size:.85rem}.devtools-session{flex-wrap:wrap;gap:4px 24px;margin:0;font-size:.85rem;display:flex}.devtools-session>div{gap:6px;display:inline-flex}.devtools-session dt{color:var(--text-muted)}.devtools-session dd{font-variant-numeric:tabular-nums;margin:0}.devtools-status{align-items:baseline;gap:8px;margin:0;font-size:.95rem;display:flex}.devtools-status-mark{background:var(--text-muted);border-radius:50%;flex:none;width:.6em;height:.6em}.devtools-status.is-ok .devtools-status-mark{background:var(--ok)}.devtools-status.is-warn .devtools-status-mark{background:var(--warn)}.devtools-status.is-bad .devtools-status-mark{background:var(--err)}.devtools-session>div[title],.devtools-tracks th[title],.devtools-legend [title]{cursor:help}.devtools-more{font-size:.85rem}.devtools-more summary{width:fit-content;color:var(--text-muted);cursor:pointer}.devtools-more[open] summary{margin-bottom:8px}.devtools-more .devtools-session+.devtools-session{margin-top:4px}.devtools-hint{color:var(--text-muted);margin:0;font-size:.8rem}.devtools-log{gap:8px;display:grid}.devtools-heading{margin:0;font-size:.85rem;font-weight:600}.devtools-events{background:var(--surface-2);border-radius:var(--radius-sm);max-height:14em;margin:0;padding:8px 12px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.8rem;list-style:none;overflow-y:auto}.devtools-events ol{color:var(--text-muted);margin:0;padding:0 0 4px;list-style:none}.devtools-events li,.devtools-events summary{gap:12px;display:flex}.devtools-events>li{border-left:2px solid #0000;padding-left:8px}.devtools-events>li:hover{background:var(--surface)}.devtools-events details{flex:1;min-width:0}.devtools-events summary{cursor:pointer;list-style:none}.devtools-events summary::-webkit-details-marker{display:none}.devtools-events summary>span:after{content:" ▸";color:var(--text-muted)}.devtools-events details[open] summary>span:after{content:" ▾"}.devtools-events time{color:var(--text-muted);flex:none}.devtools-events li.is-warn{border-left-color:var(--warn)}.devtools-events li.is-bad{border-left-color:var(--err)}.devtools-scroll{overflow-x:auto}.devtools-tracks{border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;font-size:.85rem}.devtools-tracks th,.devtools-tracks td{border-bottom:1px solid var(--border);text-align:right;white-space:nowrap;padding:4px 12px 4px 0}.devtools-tracks th:first-child{text-align:left}.devtools-tracks thead th{color:var(--text-muted);font-weight:400}.devtools-timeline{gap:10px;display:grid}.devtools-controls{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;display:flex}.devtools-spans{align-items:center;gap:4px;display:inline-flex}.devtools-span{min-width:3.5em;color:var(--text-muted);font-variant-numeric:tabular-nums;text-align:right;font-size:.8rem}.devtools-controls .copy-btn[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.devtools-lane{grid-template-columns:6rem minmax(0,1fr);align-items:start;gap:8px;display:grid}.devtools-lane-name{color:var(--text-muted);font-size:.8rem}.devtools-plot-box{position:relative}.devtools-plot{cursor:grab;touch-action:pan-y;-webkit-user-select:none;user-select:none;width:100%;display:block}.devtools-plot:active{cursor:grabbing}.devtools-tip{z-index:1;background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius-sm);width:max-content;max-width:300px;box-shadow:var(--shadow-md);pointer-events:none;gap:2px;padding:6px 10px;font-size:.8rem;display:grid;position:absolute;top:calc(100% + 4px);transform:translate(-50%)}.devtools-tip time{color:var(--text-muted);font-variant-numeric:tabular-nums}.devtools-tip span:first-of-type{font-weight:600}.devtools-axis>div{color:var(--text-muted);justify-content:space-between;font-size:.75rem;display:flex}.devtools-legend{color:var(--text-muted);gap:4px;margin:0;font-size:.8rem;display:grid}.devtools-legend>div{grid-template-columns:6rem minmax(0,1fr);gap:8px;display:grid}.devtools-legend dt{color:var(--text)}.devtools-legend dd{flex-wrap:wrap;gap:2px 16px;margin:0;display:flex}.devtools-legend-mark{align-items:center;gap:6px;display:inline-flex}.devtools-swatch{width:12px;height:10px}.devtools-swatch.is-complete{background:var(--group-complete);opacity:.55}.devtools-swatch.is-receiving{background:var(--group-receiving)}.devtools-swatch.is-skipped{background:repeating-linear-gradient(45deg, var(--group-skipped) 0 2px, transparent 2px 4px)}.devtools-swatch.is-aborted{background:var(--group-aborted)}.devtools-swatch.is-late{box-sizing:border-box;border:1px solid var(--group-late)}.devtools-swatch.is-stopped{background:repeating-linear-gradient(45deg, var(--group-stopped) 0 2px, transparent 2px 4px);opacity:.7}.devtools-swatch.is-level{background:var(--group-receiving);opacity:.35}.devtools-swatch.is-glitch{background:var(--group-aborted);width:3px}.devtools-swatch.is-stall{background:var(--group-skipped);opacity:.45}.devtools-swatch.is-marker{background:var(--group-receiving);opacity:.45}.devtools-swatch.is-arrival{background:var(--group-late);height:4px}.devtools-swatch.is-held{background:var(--group-skipped);height:4px}.devtools-swatch.is-unrendered{background:var(--group-skipped);width:3px}.devtools-swatch.is-rendered{background:var(--group-rendered)} diff --git a/playground/dist/assets/index-BafE-1dd.js b/playground/dist/assets/index-DOOx_UWb.js similarity index 89% rename from playground/dist/assets/index-BafE-1dd.js rename to playground/dist/assets/index-DOOx_UWb.js index 82902d51..eb8560c3 100644 --- a/playground/dist/assets/index-BafE-1dd.js +++ b/playground/dist/assets/index-DOOx_UWb.js @@ -53,7 +53,7 @@ `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=ns,c=!Qs.jitless,l=c&&rs.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?Eu([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function ku(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Ss(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Ds(e,r,$s())))}),t)}var Au=B(`$ZodUnion`,(e,t)=>{El.init(e,t),Hs(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),Hs(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Hs(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),Hs(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Uo(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>ku(t,r,e,i)):ku(o,r,e,i)}}),ju=B(`$ZodIntersection`,(e,t)=>{El.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Nu(e,t,n)):Nu(e,i,a)}});function Mu(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(is(e)&&is(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=Mu(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=Mu(t.value,n.value);if(!c.valid){if(Ss(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Pu=B(`$ZodTuple`,(e,t)=>{El.init(e,t);let n=t.items,r=Qs.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=Fu(n,`optin`),l=Fu(n,`optout`);if(!t.rest){if(o.lengthn.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length),d=t.rest?a?.abortEarly:void 0,f=!1;for(let e=0;e{u[e]=t})):(u[e]=t,d&&!f&&t.issues.length&&(f=Ss(t)))}if(t.rest&&!f){let e=n.length-1,r=o.slice(n.length),c=i.issues.length;for(let n of r){if(d&&i.issues.length!==c){if(Ss(i,c))break;c=i.issues.length}e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>Iu(t,i,e))):Iu(r,i,e)}}return s.length?Promise.all(s).then(()=>Lu(u,i,n,o,l)):Lu(u,i,n,o,l)}});function Fu(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function Iu(e,t,n){e.issues.length&&t.issues.push(...ws(n,e.issues)),t.value[n]=e.value}function Lu(e,t,n,r,i){for(let a=0;a=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...ws(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var Ru=B(`$ZodEnum`,(e,t)=>{El.init(e,t);let n=Lo(t.entries),r=new Set(n);e._zod.values=r,Hs(e,`pattern`,e=>{let t=Lo(e.def.entries).filter(e=>os.has(typeof e));return RegExp(t.length?`^(${t.map(e=>ss(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),zu=B(`$ZodTransform`,(e,t)=>{El.init(e,t),e._zod.optin=`optional`,Qs.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Zs(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Xs;return n.value=i,n}});function Bu(e,t){return e.value=t.issues.length?void 0:t.value,e}var Vu=B(`$ZodOptional`,(e,t)=>{El.init(e,t),Hs(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,Hs(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Hs(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Uo(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Bu(e,t)):Bu(e,r)}return t.innerType._zod.run(e,n)}}),Hu=B(`$ZodExactOptional`,(e,t)=>{Vu.init(e,t),Hs(e,`values`,e=>e.def.innerType._zod.values),Hs(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Uu=B(`$ZodNullable`,(e,t)=>{El.init(e,t),Hs(e,`optin`,e=>e.def.innerType._zod.optin),Hs(e,`optout`,e=>e.def.innerType._zod.optout),Hs(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Uo(t.source)}|null)$`):void 0}),Hs(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Wu=B(`$ZodDefault`,(e,t)=>{El.init(e,t),e._zod.optin=`defaulted`,Hs(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Gu(e,t)):Gu(r,t)}});function Gu(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Ku=B(`$ZodPrefault`,(e,t)=>{El.init(e,t),e._zod.optin=`defaulted`,Hs(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),qu=B(`$ZodNonOptional`,(e,t)=>{El.init(e,t),Hs(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Ju(t,e)):Ju(i,e)}});function Ju(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Yu(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Ds(e,r,$s()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var Xu=B(`$ZodCatch`,(e,t)=>{El.init(e,t),Hs(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),Hs(e,`optout`,e=>e.def.innerType._zod.optout),Hs(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Yu(e,r,t,n)):Yu(e,r,t,n)}}),Zu=B(`$ZodPipe`,(e,t)=>{El.init(e,t),Hs(e,`values`,e=>e.def.in._zod.values),Hs(e,`optin`,e=>e.def.in._zod.optin),Hs(e,`optout`,e=>e.def.out._zod.optout),Hs(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Qu(e,t.in,n)):Qu(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Qu(e,t.out,n)):Qu(r,t.out,n)}});function Qu(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var $u=B(`$ZodReadonly`,(e,t)=>{El.init(e,t),Hs(e,`propValues`,e=>e.def.innerType._zod.propValues),Hs(e,`values`,e=>e.def.innerType._zod.values),Hs(e,`optin`,e=>e.def.innerType?._zod?.optin),Hs(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ed):ed(r)}});function ed(e){return e.memo||(e.value=Object.freeze(e.value)),e}var td=B(`$ZodCustom`,(e,t)=>{ol.init(e,t),El.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>nd(t,n,r,e));nd(i,n,r,e)}});function nd(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Ms(e))}}var rd=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},id=`~memo`,ad=[];function od(e){return typeof e==`object`&&!!e}function sd(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var cd=new WeakMap,ld=0,ud=1,dd=2;function fd(e,t,n){let r=cd.get(e);if(r!==void 0)return r?dd:ld;if(t.has(e))return dd;t.add(e);let i=ld,a=e=>{if(i!==dd&&e?._zod){let r=fd(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=ld;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?ud:o.value?._zod?fd(o.value,t,n):ld;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=Ko(c);s(e?o(e,!0):ud),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?fd(r,t,!1):ud);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),pd(e,i)}function pd(e,t){return t!==ud&&cd.set(e,t===dd),t}function md(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var hd,gd=[],_d={alloc(e,t,n){let r=hd;if(!r)return n;hd=void 0;let i={value:n,issues:null};return r.set(t.value,i),gd.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&yd(n,e.value))throw new rd;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=fd(e,new Set,!1);if(i===ld)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===dd||r?n=!0:r=!0}let l=s.value;if(!od(l))return t(s,c);let u=c[id];u||(u={buckets:new WeakMap,backEdges:void 0},c[id]=u);let d;i===c?d=a:(d=md(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...sd(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;hd=d;let p=gd.length,m=t(s,c);hd=void 0;let h=gd.length>p?gd.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?sd(e.issues):ad),e)):(h&&(h.issues=m.issues.length?sd(m.issues):ad),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function vd(){return _d}function yd(e,t){let n=e[id]?.backEdges;return n!==void 0&&od(t)&&n.has(t)}var bd=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(js(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${ls(e.values[0])}`:`Invalid option: expected one of ${Ro(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${Ro(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function xd(){return{localeError:bd()}}var Sd,Cd=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function wd(){return new Cd}(Sd=globalThis).__zod_globalRegistry??(Sd.__zod_globalRegistry=wd());var Td=globalThis.__zod_globalRegistry;function Ed(e){return e.checks&&=[...e.checks],e}function Dd(e,t){return new e(Ed({type:`string`,...z(t)}))}function Od(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...z(t)})}function kd(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...z(t)})}function Ad(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...z(t)})}function jd(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...z(t)})}function Md(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...z(t)})}function Nd(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...z(t)})}function Pd(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...z(t)})}function Fd(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...z(t)})}function Id(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...z(t)})}function Ld(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...z(t)})}function Rd(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...z(t)})}function zd(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...z(t)})}function Bd(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...z(t)})}function Vd(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...z(t)})}function Hd(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...z(t)})}function Ud(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...z(t)})}function Wd(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...z(t)})}function Gd(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...z(t)})}function Kd(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...z(t)})}function qd(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...z(t)})}function Jd(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...z(t)})}function Yd(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...z(t)})}function Xd(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...z(t)})}function Zd(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...z(t)})}function Qd(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...z(t)})}function $d(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...z(t)})}function ef(e,t){return new e(Ed({type:`number`,checks:[],...z(t)}))}function tf(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...z(t)})}function nf(e,t){return new e({type:`boolean`,...z(t)})}function rf(e){return new e({type:`unknown`})}function af(e,t){return new e({type:`never`,...z(t)})}function of(e,t){return new ll({check:`less_than`,...z(t),value:e,inclusive:!1})}function sf(e,t){return new ll({check:`less_than`,...z(t),value:e,inclusive:!0})}function cf(e,t){return new ul({check:`greater_than`,...z(t),value:e,inclusive:!1})}function lf(e,t){return new ul({check:`greater_than`,...z(t),value:e,inclusive:!0})}function uf(e,t){return new dl({check:`multiple_of`,...z(t),value:e})}function df(e,t){return new pl({check:`max_length`,...z(t),maximum:e})}function ff(e,t){return new ml({check:`min_length`,...z(t),minimum:e})}function pf(e,t){return new hl({check:`length_equals`,...z(t),length:e})}function mf(e,t){return new _l({check:`string_format`,format:`regex`,...z(t),pattern:e})}function hf(e){return new vl({check:`string_format`,format:`lowercase`,...z(e)})}function gf(e){return new yl({check:`string_format`,format:`uppercase`,...z(e)})}function _f(e,t){return new bl({check:`string_format`,format:`includes`,...z(t),includes:e})}function vf(e,t){return new xl({check:`string_format`,format:`starts_with`,...z(t),prefix:e})}function yf(e,t){return new Sl({check:`string_format`,format:`ends_with`,...z(t),suffix:e})}function bf(e){return new Cl({check:`overwrite`,tx:e})}function xf(e){return bf(t=>t.normalize(e))}function Sf(){return bf(e=>e.trim())}function Cf(){return bf(e=>e.toLowerCase())}function wf(){return bf(e=>e.toUpperCase())}function Tf(){return bf(e=>es(e))}function Ef(e,t,n){return new e({type:`array`,element:t,...z(n)})}function Df(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...z(n)})}function Of(e,t){let n=kf(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Ms(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Ms(r))}},e(t.value,t)),t);return n}function kf(e,t){let n=new ol({check:`custom`,...z(t)});return n._zod.check=e,n}function Af(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Go(e,t,n[t]);return e}function jf(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Td,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function Mf(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function Nf(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Nf(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Af(o.schema,c),t.io===`input`&&Uf(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Pf(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Ff(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${Pf(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+Pf(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function If(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;If(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var Lf=new Set([`type`,`properties`,`required`,`additionalProperties`]),Rf=[`oneOf`,`anyOf`];function zf(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Bf(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Lf.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??zf(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Go(n,r,e.length===1?e[0]:Bf(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=zf(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function Vf(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Lf)if(t in e)return;let n=t.filter(e=>Rf.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Bf(t);else{let e=n[0],i=Rf.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Bf([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Af(e,r))}function Hf(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Af(i,s),Af(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())If(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])Vf(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Af(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Go(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Gf(t,`input`,e.processors),output:Gf(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Uf(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Uf(r.element,n);if(r.type===`set`)return Uf(r.valueType,n);if(r.type===`lazy`)return Uf(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return Uf(r.innerType,n);if(r.type===`intersection`)return Uf(r.left,n)||Uf(r.right,n);if(r.type===`record`||r.type===`map`)return Uf(r.keyType,n)||Uf(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Uf(r.in,n)||Uf(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Uf(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Uf(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Uf(e,n))return!0;return!!(r.rest&&Uf(r.rest,n))}return!1}var Wf=(e,t={})=>n=>{let r=jf({...n,processors:t});return Nf(e,r),Ff(r,e),Hf(r,e)},Gf=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=jf({...i??{},target:a,io:t,processors:n});return Nf(e,o),Ff(o,e),Hf(o,e)},Kf=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},qf=(e,t,n)=>{(e[t]===void 0||n{Kf(e,`minimum`,t),qf(e,`maximum`,t)},Yf=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Xf=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},Zf=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Qf=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},$f=(e,t)=>Kf(e,`minimum`,t.minimum),ep=(e,t)=>qf(e,`maximum`,t.maximum),tp=e=>(t,n)=>{Qf(t,n.format);let[r,i]=e[n.format];Kf(t,`minimum`,r),qf(t,`maximum`,i)},np={greater_than:(e,t)=>Kf(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>qf(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Yf(e,t.value),number_format:tp(ds),bigint_format:tp(fs),min_length:$f,max_length:ep,length_equals:(e,t)=>Jf(e,t.length),min_size:$f,max_size:ep,size_equals:(e,t)=>Jf(e,t.size),string_format:(e,t)=>{Qf(e,t.format),t.pattern&&Xf(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Zf(e,t.mime)};function rp(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)np[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Kf(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Kf(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&qf(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&qf(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Yf(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Zf(t,i.mime);for(let e of i.patterns??[])Xf(t,e);return t}var ip={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ap=new Map([[cu,Gc],[uu,Kc]]),op=e=>ap.get(e)??e,sp=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=rp(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=ip[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(op);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},cp=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=rp(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):Mf(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},lp=(e,t,n,r)=>{n.type=`boolean`},up=(e,t,n,r)=>{n.not={}},dp=(e,t,n,r)=>{let i=e._zod.def,a=Lo(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},fp=(e,t,n,r)=>{Mf(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},pp=(e,t,n,r)=>{Mf(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},mp=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=rp(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Nf(a.element,t,{...r,path:[...r.path,`items`]})};function hp(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?hp(t.out):t.type===`catch`?hp(t.innerType):e._zod.optin}var gp=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Mf(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Go(i.properties,e,Nf(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?hp(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Nf(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},_p=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Nf(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},vp=(e,t,n,r)=>{let i=e._zod.def,a=Nf(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Nf(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},yp=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>Nf(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Nf(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?hp(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=rp(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)},bp=(e,t,n,r)=>{let i=e._zod.def,a=Nf(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},xp=(e,t,n,r)=>{let i=e._zod.def;Nf(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Sp=Symbol();function Cp(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Mf(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Sp):JSON.parse(o)}var wp=(e,t,n,r)=>{let i=e._zod.def;Nf(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Cp(i.defaultValue,e,t,n,r);o!==Sp&&(n.default=o)},Tp=(e,t,n,r)=>{let i=e._zod.def;Nf(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Cp(i.defaultValue,e,t,n,r);o!==Sp&&(n._prefault=o)},Ep=(e,t,n,r)=>{let i=e._zod.def;Nf(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Mf(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Dp=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Nf(o,t,r);let s=t.seen.get(e);s.ref=o},Op=(e,t,n,r)=>{let i=e._zod.def;Nf(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},kp=(e,t,n,r)=>{let i=e._zod.def;Nf(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ap=new WeakSet([Object.prototype,Error.prototype]);function jp(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Mp=B(`ZodError`,(e,t)=>{ac.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Ap.has(n)||(Ap.add(n),jp(n,`format`,e=>t=>cc(e,t)),jp(n,`flatten`,e=>t=>sc(e,t)),jp(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,zo,2)}),jp(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,zo,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Np=uc(Mp),Pp=dc(Mp),Fp=fc(Mp),Ip=mc(Mp),Lp=bc(Mp),Rp=xc(Mp),zp=Sc(Mp),Bp=Cc(Mp),Vp=wc(Mp),Hp=Tc(Mp),Up=Ec(Mp),Wp=Dc(Mp);function Gp(){Qs.localeError||$s(xd())}function Kp(){Qs.memoizer||$s({memoizer:vd()})}var qp=B(`ZodType`,(e,t)=>(Gp(),El.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Qo(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return cs(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(uh(e,t))},superRefine(e,t){return this.check(dh(e,t))},overwrite(e){return this.check(bf(e))},optional(){return Km(this)},exactOptional(){return Jm(this)},nullable(){return Xm(this)},nullish(){return Km(Xm(this))},nonoptional(e){return nh(this,e)},array(){return Mm(this)},or(e){return Im([this,e])},and(e){return Rm(this,e)},transform(e){return oh(this,Wm(e))},default(e){return Qm(this,e)},prefault(e){return eh(this,e)},catch(e){return ih(this,e)},pipe(e){return oh(this,e)},readonly(){return ch(this)},describe(e){let t=this.clone();return Td.add(t,{description:e}),t},meta(...e){if(e.length===0)return Td.get(this);let t=this.clone();return Td.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Fs(this,`~standard`,{...kl(this),jsonSchema:{input:Gf(this,`input`),output:Gf(this,`output`)}})},set"~standard"(e){Ps(this,`~standard`,e)},parse:function e(t,n){return Np(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Pp(this,t,n,{callee:e})},safeParse(e,t){return Fp(this,e,t)},async safeParseAsync(e,t){return Ip(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ps(this,`spa`,e)},validate(e,t){return _c(this,e,t)},validateAsync(e,t){return yc(this,e,t)},encode:function e(t,n){return Lp(this,t,n,{callee:e})},decode:function e(t,n){return Rp(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await zp(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Bp(this,t,n,{callee:e})},safeEncode(e,t){return Vp(this,e,t)},safeDecode(e,t){return Hp(this,e,t)},async safeEncodeAsync(e,t){return Up(this,e,t)},async safeDecodeAsync(e,t){return Wp(this,e,t)},toJSONSchema(e){return Wf(this,{})(e)},get description(){return Td.get(this)?.description},get _def(){return this._zod.def}}),Jp=B(`_ZodString`,(e,t)=>{Al.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sp(e,t,n,r)},Is({format:e=>rp(e).format??null,minLength:e=>rp(e).minimum??null,maxLength:e=>rp(e).maximum??null},{regex(...e){return this.check(mf(...e))},includes(...e){return this.check(_f(...e))},startsWith(...e){return this.check(vf(...e))},endsWith(...e){return this.check(yf(...e))},min(...e){return this.check(ff(...e))},max(...e){return this.check(df(...e))},length(...e){return this.check(pf(...e))},nonempty(...e){return this.check(ff(1,...e))},lowercase(e){return this.check(hf(e))},uppercase(e){return this.check(gf(e))},trim(){return this.check(Sf())},normalize(...e){return this.check(xf(...e))},toLowerCase(){return this.check(Cf())},toUpperCase(){return this.check(wf())},slugify(){return this.check(Tf())}})),Yp=B(`ZodString`,(e,t)=>{Al.init(e,t),Jp.init(e,t)},{email(e){return this.check(Od(nm,e))},url(e){return this.check(Pd(am,e))},jwt(e){return this.check(Yd(bm,e))},emoji(e){return this.check(Fd(om,e))},guid(e){return this.check(kd(rm,e))},uuid(e){return this.check(Ad(im,e))},uuidv4(e){return this.check(jd(im,e))},uuidv6(e){return this.check(Md(im,e))},uuidv7(e){return this.check(Nd(im,e))},nanoid(e){return this.check(Id(sm,e))},cuid(e){return this.check(Ld(cm,e))},cuid2(e){return this.check(Rd(lm,e))},ulid(e){return this.check(zd(um,e))},base64(e){return this.check(Kd(_m,e))},base64url(e){return this.check(qd(vm,e))},xid(e){return this.check(Bd(dm,e))},ksuid(e){return this.check(Vd(fm,e))},ipv4(e){return this.check(Hd(pm,e))},ipv6(e){return this.check(Ud(mm,e))},cidrv4(e){return this.check(Wd(hm,e))},cidrv6(e){return this.check(Gd(gm,e))},e164(e){return this.check(Jd(ym,e))},datetime(e){return this.check(Xd(Qp,e))},date(e){return this.check(Zd($p,e))},time(e){return this.check(Qd(em,e))},duration(e){return this.check($d(tm,e))}});function Xp(e){return Dd(Yp,e)}var Zp=B(`ZodStringFormat`,(e,t)=>{jl.init(e,t),Jp.init(e,t)}),Qp=B(`ZodISODateTime`,(e,t)=>{Xl.init(e,t),Zp.init(e,t)}),$p=B(`ZodISODate`,(e,t)=>{Zl.init(e,t),Zp.init(e,t)}),em=B(`ZodISOTime`,(e,t)=>{Ql.init(e,t),Zp.init(e,t)}),tm=B(`ZodISODuration`,(e,t)=>{$l.init(e,t),Zp.init(e,t)}),nm=B(`ZodEmail`,(e,t)=>{Pl.init(e,t),Zp.init(e,t)}),rm=B(`ZodGUID`,(e,t)=>{Ml.init(e,t),Zp.init(e,t)}),im=B(`ZodUUID`,(e,t)=>{Nl.init(e,t),Zp.init(e,t)}),am=B(`ZodURL`,(e,t)=>{Hl.init(e,t),Zp.init(e,t)}),om=B(`ZodEmoji`,(e,t)=>{Ul.init(e,t),Zp.init(e,t)}),sm=B(`ZodNanoID`,(e,t)=>{Wl.init(e,t),Zp.init(e,t)}),cm=B(`ZodCUID`,(e,t)=>{Gl.init(e,t),Zp.init(e,t)}),lm=B(`ZodCUID2`,(e,t)=>{Kl.init(e,t),Zp.init(e,t)}),um=B(`ZodULID`,(e,t)=>{ql.init(e,t),Zp.init(e,t)}),dm=B(`ZodXID`,(e,t)=>{Jl.init(e,t),Zp.init(e,t)}),fm=B(`ZodKSUID`,(e,t)=>{Yl.init(e,t),Zp.init(e,t)}),pm=B(`ZodIPv4`,(e,t)=>{eu.init(e,t),Zp.init(e,t)}),mm=B(`ZodIPv6`,(e,t)=>{ru.init(e,t),Zp.init(e,t)}),hm=B(`ZodCIDRv4`,(e,t)=>{iu.init(e,t),Zp.init(e,t)}),gm=B(`ZodCIDRv6`,(e,t)=>{ou.init(e,t),Zp.init(e,t)}),_m=B(`ZodBase64`,(e,t)=>{lu.init(e,t),Zp.init(e,t)}),vm=B(`ZodBase64URL`,(e,t)=>{fu.init(e,t),Zp.init(e,t)}),ym=B(`ZodE164`,(e,t)=>{pu.init(e,t),Zp.init(e,t)}),bm=B(`ZodJWT`,(e,t)=>{hu.init(e,t),Zp.init(e,t)}),xm=B(`ZodNumber`,(e,t)=>{gu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cp(e,t,n,r),e.isFinite=!0},Is({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=rp(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=rp(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=rp(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>rp(e).format??null},{gt(e,t){return this.check(cf(e,t))},gte(e,t){return this.check(lf(e,t))},min(e,t){return this.check(lf(e,t))},lt(e,t){return this.check(of(e,t))},lte(e,t){return this.check(sf(e,t))},max(e,t){return this.check(sf(e,t))},int(e){return this.check(wm(e))},safe(e){return this.check(wm(e))},positive(e){return this.check(cf(0,e))},nonnegative(e){return this.check(lf(0,e))},negative(e){return this.check(of(0,e))},nonpositive(e){return this.check(sf(0,e))},multipleOf(e,t){return this.check(uf(e,t))},step(e,t){return this.check(uf(e,t))},finite(){return this}}));function Sm(e){return ef(xm,e)}var Cm=B(`ZodNumberFormat`,(e,t)=>{_u.init(e,t),xm.init(e,t)});function wm(e){return tf(Cm,e)}var Tm=B(`ZodBoolean`,(e,t)=>{vu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lp(e,t,n,r)});function Em(e){return nf(Tm,e)}var Dm=B(`ZodUnknown`,(e,t)=>{yu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Om(){return rf(Dm)}var km=B(`ZodNever`,(e,t)=>{bu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>up(e,t,n,r)});function Am(e){return af(km,e)}var jm=B(`ZodArray`,(e,t)=>{Kp(),Su.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mp(e,t,n,r),e.element=t.element},{min(e,t){return this.check(ff(e,t))},nonempty(e){return this.check(ff(1,e))},max(e,t){return this.check(df(e,t))},length(e,t){return this.check(pf(e,t))},unwrap(){return this.element}});function Mm(e,t){return Ef(jm,e,t)}var Nm=B(`ZodObject`,(e,t)=>{Kp(),Ou.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gp(e,t,n,r),Us(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return Hm(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Qo(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Qo(this._zod.def,{catchall:Om()}))},loose(){return this.clone(Qo(this._zod.def,{catchall:Om()}))},strict(){return this.clone(Qo(this._zod.def,{catchall:Am()}))},strip(){return this.clone(Qo(this._zod.def,{catchall:void 0}))},extend(e){return gs(this,e)},safeExtend(e){return vs(this,e)},merge(e){return ys(this,e)},pick(e){return ps(this,e)},omit(e){return hs(this,e)},partial(...e){return bs(Gm,this,e[0])},exactPartial(...e){return bs(qm,this,e[0],`exactPartial`)},required(...e){return xs(th,this,e[0])}});function Pm(e,t){return new Nm({type:`object`,shape:e??{},...z(t)})}var Fm=B(`ZodUnion`,(e,t)=>{Au.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_p(e,t,n,r),e.options=t.options});function Im(e,t){return new Fm({type:`union`,options:e,...z(t)})}var Lm=B(`ZodIntersection`,(e,t)=>{ju.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vp(e,t,n,r)});function Rm(e,t){return new Lm({type:`intersection`,left:e,right:t})}var zm=B(`ZodTuple`,(e,t)=>{Kp(),Pu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yp(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Gm({type:`optional`,innerType:e}))})}});function Bm(e,t,n){let r=t instanceof El;return new zm({type:`tuple`,items:e,rest:r?t:null,...z(r?n:t)})}var Vm=B(`ZodEnum`,(e,t)=>{Ru.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dp(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Vm({...t,checks:[],...z(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Vm({...t,checks:[],...z(r),entries:i})}});function Hm(e,t){return new Vm({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...z(t)})}var Um=B(`ZodTransform`,(e,t)=>{Kp(),zu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pp(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Zs(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ms(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Ms(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Wm(e){return new Um({type:`transform`,transform:e})}var Gm=B(`ZodOptional`,(e,t)=>{Vu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>kp(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Km(e){return new Gm({type:`optional`,innerType:e})}var qm=B(`ZodExactOptional`,(e,t)=>{Hu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>kp(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Jm(e){return new qm({type:`optional`,innerType:e})}var Ym=B(`ZodNullable`,(e,t)=>{Uu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bp(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xm(e){return new Ym({type:`nullable`,innerType:e})}var Zm=B(`ZodDefault`,(e,t)=>{Wu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wp(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Qm(e,t){return new Zm({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():as(t)}})}var $m=B(`ZodPrefault`,(e,t)=>{Ku.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tp(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function eh(e,t){return new $m({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():as(t)}})}var th=B(`ZodNonOptional`,(e,t)=>{qu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xp(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nh(e,t){return new th({type:`nonoptional`,innerType:e,...z(t)})}var rh=B(`ZodCatch`,(e,t)=>{Xu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ep(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ih(e,t){return new rh({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Gs(t)})}var ah=B(`ZodPipe`,(e,t)=>{Zu.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Dp(e,t,n,r),e.in=t.in,e.out=t.out});function oh(e,t){return new ah({type:`pipe`,in:e,out:t})}var sh=B(`ZodReadonly`,(e,t)=>{$u.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Op(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ch(e){return new sh({type:`readonly`,innerType:e})}var lh=B(`ZodCustom`,(e,t)=>{td.init(e,t),qp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fp(e,t,n,r)});function uh(e,t={}){return Df(lh,e,t)}function dh(e,t){return Of(e,t)}var fh=`inline`;function ph(e){if(e.type===void 0||e.type===`inline`)return e.data}function mh(e){let t=e.initDataList;if(!t||t.length===0)return;let n=new Map;for(let e of t)n.has(e.id)||n.set(e.id,e);for(let t of e.tracks){if(t.initData!==void 0||!t.initRef)continue;let e=n.get(t.initRef),r=e===void 0?void 0:ph(e);r!==void 0&&(t.initData=r)}}function hh(e){let t=(e.initDataList??[]).map(e=>({...e})),n=new Set(t.map(e=>e.id)),r=new Map,i=new Map;for(let e of t){r.has(e.id)||r.set(e.id,e);let t=ph(e);t!==void 0&&!i.has(t)&&i.set(t,e.id)}let a=e=>{if(!n.has(e))return e;for(let t=2;;t++){let r=`${e}-${t}`;if(!n.has(r))return r}},o=e.tracks.map(e=>{if(e.initData===void 0)return e.initRef||void 0;if(e.initRef){let t=r.get(e.initRef);if(t!==void 0&&ph(t)===e.initData)return e.initRef}let o=i.get(e.initData);if(o!==void 0)return o;let s=e.initRef||void 0,c=s!==void 0&&!r.has(s)?s:a(s??(e.name||`init`)),l={id:c,type:fh,data:e.initData};return t.push(l),n.add(c),r.set(c,l),i.set(e.initData,c),c});return{initDataList:t.length>0?t:void 0,initRefs:o}}var gh=class extends Error{problems;constructor(e){super(e.length===0?`msf: validation failed`:`msf: validation failed: ${e.join(`; `)}`),this.name=`ValidationError`,this.problems=e}},_h=new Set(`namespace.name.packaging.eventType.role.isLive.targetLatency.label.renderGroup.altGroup.initData.initRef.depends.temporalId.spatialId.codec.mimeType.framerate.timescale.bitrate.width.height.samplerate.channelConfig.displayWidth.displayHeight.lang.trackDuration`.split(`.`)),vh=Pm({namespace:Xp().optional(),name:Xp().optional(),packaging:Xp().optional(),eventType:Xp().optional(),role:Xp().optional(),isLive:Em().optional(),targetLatency:Sm().optional(),label:Xp().optional(),renderGroup:Sm().optional(),altGroup:Sm().optional(),initData:Xp().optional(),initRef:Xp().optional(),depends:Mm(Xp()).optional(),temporalId:Sm().optional(),spatialId:Sm().optional(),codec:Xp().optional(),mimeType:Xp().optional(),framerate:Sm().optional(),timescale:Sm().optional(),bitrate:Sm().optional(),width:Sm().optional(),height:Sm().optional(),samplerate:Sm().optional(),channelConfig:Xp().optional(),displayWidth:Sm().optional(),displayHeight:Sm().optional(),lang:Xp().optional(),trackDuration:Sm().optional()}).catchall(Om()),yh=Pm({defaultNamespace:Xp().optional(),version:Sm().optional(),generatedAt:Sm().optional(),isComplete:Em().optional(),tracks:Mm(vh).optional(),initDataList:Mm(Om()).optional()}).catchall(Om()),bh=Pm({id:Xp(),type:Xp().optional(),data:Xp().optional()}).catchall(Om());function xh(e,t){let n=t.issues[0];if(!n)return Error(e);let r=n.path.length>0?` at ${n.path.join(`.`)}`:``;return Error(`${e}${r}: ${n.message}`)}function Sh(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function Ch(e){return typeof e==`string`?e:new TextDecoder().decode(e)}function wh(e){return{...e,depends:e.depends?[...e.depends]:void 0,extraFields:e.extraFields?{...e.extraFields}:void 0}}function Th(e){return{...e,tracks:e.tracks.map(wh),initDataList:e.initDataList?.map(e=>({...e,extraFields:e.extraFields?{...e.extraFields}:void 0})),extraFields:e.extraFields?{...e.extraFields}:void 0}}function Eh(e){let t={};for(let[n,r]of Object.entries(e))_h.has(n)||(t[n]=r);return t}function Dh(e){let t=Sh(e,`msf: track must be a JSON object`),n=vh.safeParse(t);if(!n.success)throw xh(`msf: track must be a JSON object`,n.error);let r=n.data,i=Eh(r);return{namespace:r.namespace,name:r.name,packaging:r.packaging,eventType:r.eventType,role:r.role,isLive:r.isLive,targetLatency:r.targetLatency,label:r.label,renderGroup:r.renderGroup,altGroup:r.altGroup,initData:r.initData,initRef:r.initRef,depends:r.depends,temporalId:r.temporalId,spatialId:r.spatialId,codec:r.codec,mimeType:r.mimeType,framerate:r.framerate,timescale:r.timescale,bitrate:r.bitrate,width:r.width,height:r.height,samplerate:r.samplerate,channelConfig:r.channelConfig,displayWidth:r.displayWidth,displayHeight:r.displayHeight,lang:r.lang,trackDuration:r.trackDuration,extraFields:Object.keys(i).length>0?i:void 0}}function Oh(e,t){let n=`msf: initDataList[${t}] must be a JSON object with a string id`,r=bh.safeParse(Sh(e,n));if(!r.success)throw xh(n,r.error);let i=r.data,a={};for(let[e,t]of Object.entries(i))e!==`id`&&e!==`type`&&e!==`data`&&(a[e]=t);return{id:i.id,type:i.type,data:i.data,extraFields:Object.keys(a).length>0?a:void 0}}function kh(e){let t=yh.safeParse(JSON.parse(Ch(e)));if(!t.success)throw xh(`msf: expected JSON object`,t.error);let n=t.data;if(`deltaUpdate`in n||`addTracks`in n||`removeTracks`in n||`cloneTracks`in n)throw Error(`msf: delta catalog fields are not allowed in an independent catalog`);let r=Array.isArray(n.tracks)?n.tracks:[],i={};for(let[e,t]of Object.entries(n))e!==`defaultNamespace`&&e!==`version`&&e!==`generatedAt`&&e!==`isComplete`&&e!==`tracks`&&e!==`initDataList`&&(i[e]=t);let a={defaultNamespace:n.defaultNamespace,version:n.version??0,generatedAt:n.generatedAt,isComplete:n.isComplete===!0,tracks:r.map(Dh),initDataList:Array.isArray(n.initDataList)?n.initDataList.map(Oh):void 0,extraFields:Object.keys(i).length>0?i:void 0};return mh(a),a}function Ah(e,t){return e.namespace&&e.namespace.length>0?e.namespace:t&&t.length>0?t:`\0catalog`}function jh(e,t){return`${Ah(e,t)}|${e.name??``}`}function Mh(e,t){let n=[];switch(e.name||n.push(`${t}: name is required`),e.packaging||n.push(`${t}: packaging is required`),e.trackDuration!==void 0&&e.isLive===!0&&n.push(`${t}: trackDuration must not be present when isLive is true`),e.packaging){case`eventtimeline`:e.eventType||n.push(`${t}: eventType is required for eventtimeline tracks`),e.mimeType!==`application/json`&&n.push(`${t}: eventtimeline tracks must use mimeType application/json`),(!e.depends||e.depends.length===0)&&n.push(`${t}: eventtimeline tracks must declare depends`);break;case`mediatimeline`:e.eventType&&n.push(`${t}: eventType must not be set for mediatimeline tracks`),e.mimeType!==`application/json`&&n.push(`${t}: mediatimeline tracks must use mimeType application/json`),(!e.depends||e.depends.length===0)&&n.push(`${t}: mediatimeline tracks must declare depends`);break;case`loc`:e.eventType&&n.push(`${t}: eventType must not be set for loc tracks`),e.isLive===void 0&&n.push(`${t}: isLive is required for loc tracks`);break;default:e.eventType&&n.push(`${t}: eventType must only be set for eventtimeline tracks`)}return n}function Nh(e){let t=[];e.version||t.push(`catalog version is required`);for(let n=0;n0)throw new gh(t)}function Ph(e){let t=[],n=new Set,r=e.initDataList??[];for(let e=0;e({...e??{},...t}))),e.tracks.length>0&&(t.tracks=e.tracks.map(({extraFields:e,initData:t,...n},i)=>({...e??{},...n,initRef:r[i]}))),JSON.stringify(t)}Pm({namespace:Xp().optional(),name:Xp().optional()}).catchall(Om()),Pm({parentName:Xp().optional(),parentNamespace:Xp().optional()}).catchall(Om()),Pm({deltaUpdate:Mm(Pm({op:Xp(),tracks:Mm(Om())}).catchall(Om())),defaultNamespace:Xp().optional(),generatedAt:Sm().optional(),isComplete:Em().optional()}).catchall(Om());var Ih=Bm([Sm(),Sm()]);Bm([Sm(),Ih,Sm()]),Pm({t:Sm().optional(),l:Ih.optional(),m:Sm().optional(),data:Om().optional()}).catchall(Om());var Lh=`catalog`,Rh=class{#e;#t;#n;#r=Vh();#i=!1;#a=new zr;constructor(e,t=Lh){this.#e=t,this.#t=Gh(e,this.#e)}get catalogTrackName(){return this.#e}catalog(){return Th(this.#t)}catalogBytes(){return this.#s().slice()}async setCatalog(e){let t=Gh(e,this.#e),n=Wh(this.#t,t);this.#t=t,this.#o(),await Promise.allSettled(n.map(e=>this.#a.remove(e)))}async registerTrack(e,t){if(t==null)throw Error(`msf: track handler cannot be nil`);if(!e.name)throw Error(`msf: track name is required`);if(e.name===this.#e)throw Error(`msf: \"${e.name}\" is reserved for the catalog track`);let n=e.name,r=wh(e);Uh(this.#t,r,this.#e),await this.#a.register(n,t);let i;try{i=Uh(this.#t,r,this.#e)}catch(e){throw await this.#a.remove(n),e}this.#t=i,this.#o()}async removeTrack(e){if(e===``||e===this.#e)return!1;let t=Th(this.#t),n=t.tracks.length;t.tracks=t.tracks.filter(t=>t.name!==e);let r=t.tracks.length!==n;r&&(this.#t=t,this.#o());let i=await this.#a.remove(e);return r||i}handler(e){return e===this.#e?{serveTrack:this.#c.bind(this)}:this.#a.handler(e)}async serveTrack(e){await this.handler(e.trackName).serveTrack(e)}async close(){this.#i||(this.#i=!0,this.#r.resolve()),await this.#a.close()}#o(){this.#n=void 0,!this.#i&&(this.#r.resolve(),this.#r=Vh())}#s(){return this.#n??=new TextEncoder().encode(Fh(this.#t)),this.#n}async#c(e){let t=!1,n=Bh(e).then(()=>{t=!0}),r;for(;;){let i=this.#s(),a=this.#r.promise,o=this.#i;if(r===void 0||!Hh(i,r)){if(await zh(e,i)){!t&&e.context.err()===void 0&&await e.closeWithError(Gn.InternalError);return}r=i}if(o||await Promise.race([a.then(()=>!1),n.then(()=>!0)])){await e.close();return}}}};async function zh(e,t){let[n,r]=await e.openGroup();if(r||!n)return Error(`msf: open catalog group`,{cause:r});let i=await n.writeFrame(t);if(i)return await n.cancel(Kn.InternalError),Error(`msf: write catalog group`,{cause:i});await n.close()}function Bh(e){let t=(async()=>{try{for(;;){let[,t]=await e.readUpdate();if(t)return}}catch{}})();return Promise.race([e.context.done(),t]).then(()=>{})}function Vh(){let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}}function Hh(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;ne.name===t.name),o=r.tracks[a];if(o===void 0)r.tracks.push(t);else if(jh(o,r.defaultNamespace)!==i)throw Error(`msf: broadcast requires unique track names across namespaces; duplicate name ${JSON.stringify(t.name)} found`);else r.tracks[a]=t;return Nh(r),Kh(r,n),r}function Wh(e,t){if(e.tracks.length===0)return[];let n=new Set(t.tracks.map(e=>e.name).filter(e=>!!e));return e.tracks.map(e=>e.name).filter(e=>!!e&&!n.has(e))}function Gh(e,t){let n=Th(e);return Nh(n),Kh(n,t),n}function Kh(e,t){let n=new Map;for(let r of e.tracks){if(!r.name)continue;if(r.name===t)throw Error(`msf: catalog contains reserved track name \"${t}\"`);let i=jh(r,e.defaultNamespace),a=n.get(r.name);if(a!==void 0&&a!==i)throw Error(`msf: broadcast requires unique track names across namespaces; duplicate name ${JSON.stringify(r.name)} found`);n.set(r.name,i)}}var qh=class extends Error{constructor(){super(`no supported audio codec`),this.name=`NoAudioCodecError`}},Jh=64e3;function Yh(e,t){return{codec:`opus`,sampleRate:e,numberOfChannels:t,bitrate:Jh,bitrateMode:`variable`,opus:t===1?{application:`voip`,signal:`voice`}:{application:`audio`,signal:`music`}}}async function Xh(e,t,n=e=>AudioEncoder.isConfigSupported(e)){let{supported:r,config:i}=await n(Yh(e,t));if(r&&i!==void 0)return i;throw new qh}var Zh=class{#e;#t=-1;at(e,t){return this.#e??=t-e,this.#t=Math.max(Math.round(e+this.#e),this.#t+1),this.#t}},Qh=class e{static#e=.4;#t;#n;constructor(e){this.#t=1e6/e}takes(t){let n=this.#n??t;return tthis.#t?t:n)+this.#t,!0)}},$h=class{#e;#t;constructor(e){this.#e=e}isKey(e){return this.#t!==void 0&&e-this.#tthis.#e.reset()}process(e){return this.#e.push(e[0]??[],e=>{this.port.postMessage(e,[e.buffer])}),!0}}registerProcessor(tg,e)}var rg=`/assets/worklet-wqJSe3hJ.js`,ig=Na(za.audio),ag=48e3,og=2,sg=5,cg=class{onchunk;#e;#t;#n;#r=!1;constructor(){this.#e=new AudioContext({sampleRate:ag}),this.#t=this.#e.audioWorklet.addModule(String(rg)).then(()=>{let e={channels:og},t=new AudioWorkletNode(this.#e,tg,{numberOfInputs:1,numberOfOutputs:1,channelCount:og,channelCountMode:`explicit`,processorOptions:e});return t.port.onmessage=({data:e})=>this.#i(e),t}),this.#t.catch(()=>{})}get sampleRate(){return this.#e.sampleRate}get channels(){return og}async start(e,t,n){this.stop();let r=new AudioEncoder({output:e=>this.onchunk?.(e),error:e=>ig.error(`audio encoder error`,{err:e})});r.configure(t);let i={encoder:r,source:this.#e.createMediaStreamSource(e),rebase:new Zh,clock:n,samples:0};this.#n=i;try{let e=await this.#t;if(this.#n!==i)return;this.#e.resume().catch(e=>{ig.warn(`audio capture could not be resumed`,{err:e})}),e.port.postMessage({type:`reset`}),i.source.connect(e)}catch(e){throw this.#n===i&&this.stop(),e}}stop(){let e=this.#n;e!==void 0&&(this.#n=void 0,e.source.disconnect(),e.encoder.state!==`closed`&&e.encoder.close(),!this.#r&&this.#e.suspend().catch(()=>{}))}close(){this.#r||(this.#r=!0,this.stop(),this.#e.close().catch(()=>{}))}#i(e){let t=this.#n;if(t===void 0||t.encoder.state!==`configured`)return;let n=e.length/og,r=t.rebase.at(t.samples*1e6/this.sampleRate,t.clock()-2e4);if(t.samples+=n,t.encoder.encodeQueueSize>sg){ig.warn(`audio block dropped: the encoder is behind`,{queue:t.encoder.encodeQueueSize});return}let i=new AudioData({format:`f32-planar`,sampleRate:this.sampleRate,numberOfChannels:og,numberOfFrames:n,timestamp:r,data:e});try{t.encoder.encode(i)}finally{i.close()}}},lg=64,ug=class{#e;#t;#n;#r;#i=new Map;constructor(e){this.#e=e.grouping,this.#t=e.observer,this.#n=e.onerror,this.#r=e.maxPending??lg}get size(){return this.#i.size}add(e,t){this.#i.set(t,{name:e,sink:t,group:void 0,tail:Promise.resolve(),pending:0,needsKey:!1,torn:!1,removed:!1}),this.#t?.markSent(e)}remove(e){let t=this.#i.get(e);t!==void 0&&(this.#i.delete(e),t.removed=!0,t.group!==void 0&&(this.#t?.groupEnded(t.name,t.group.sequence,`stopped`),t.group=void 0))}send(e,t){let n=[...this.#i.values()].map(n=>n.pending>=this.#r?(n.needsKey||(n.needsKey=!0,t.key||(n.tail=n.tail.then(()=>{n.torn=!0}))),n.tail):(n.needsKey&&!t.key||(n.needsKey=!1,n.pending++,n.tail=n.tail.then(()=>this.#a(n,e,t)).catch(e=>{this.#n?.(n.name,e instanceof Error?e:Error(String(e)))}).finally(()=>{n.pending--})),n.tail));return Promise.all(n).then(()=>{})}async#a(e,t,n){if(e.removed)return;let{name:r}=e;if(n.key){this.#o(e,e.torn?`aborted`:`complete`),e.torn=!1;let[t,n]=await e.sink.openGroup();if(n!==void 0)throw n;if(e.removed){t.close();return}e.group=t,this.#t?.groupArrived(r,t.sequence)}let i=e.group;if(i===void 0)return;let a=await i.writeFrame(t);if(a!==void 0)throw e.group===i&&this.#o(e,`aborted`),a;this.#t?.frameArrived(r,i.sequence,n.timestamp,n.bytes),this.#e===`frame`&&e.group===i&&this.#o(e,`complete`)}#o(e,t){let n=e.group;n!==void 0&&(e.group=void 0,n.close().catch(()=>{}),this.#t?.groupEnded(e.name,n.sequence,t))}},dg=class{timestamp;source;constructor(e){this.timestamp=e.timestamp,this.source=e}get byteLength(){return gg(this.timestamp)+gg(this.source.byteLength)+this.source.byteLength}copyTo(e){let t=0,n;if(n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n.byteLength>8|64,n[1]=e&255):e<=hg?(n=new Uint8Array(4),n[0]=e>>24|128,n[1]=e>>16&255,n[2]=e>>8&255,n[3]=e&255):(n=new Uint8Array(8),n[0]=Math.floor(e/72057594037927940)|192,n[1]=Math.floor(e/281474976710656)&255,n[2]=Math.floor(e/1099511627776)&255,n[3]=Math.floor(e/4294967296)&255,n[4]=Math.floor(e/16777216)&255,n[5]=Math.floor(e/65536)&255,n[6]=Math.floor(e/256)&255,n[7]=e&255),t.set(n,0),n.length}var pg=63,mg=16383,hg=(1<<30)-1;function gg(e){return e=e<0?BigInt(e)+(1n<<64n):BigInt(e),e<=pg?1:e<=mg?2:e<=hg?4:8}function _g(e,t){if(t>=e.length)throw RangeError(`Buffer overflow while reading varint`);let n=e[t],r=n>>6,i=0;switch(r){case 0:i=n&63;break;case 1:if(t+1>=e.length)throw RangeError(`Buffer overflow while reading varint`);i=(n&63)<<8|e[t+1];break;case 2:if(t+3>=e.length)throw RangeError(`Buffer overflow while reading varint`);i=(n&63)<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];break;case 3:if(t+7>=e.length)throw RangeError(`Buffer overflow while reading varint`);i=(n&63)*72057594037927940+e[t+1]*281474976710656+e[t+2]*1099511627776+e[t+3]*4294967296+e[t+4]*16777216+e[t+5]*65536+e[t+6]*256+e[t+7]}return i}function vg(e){let t=0,n=_g(e,t);t+=gg(n);let r=_g(e,t);if(t+=gg(r),t+r>e.length)throw RangeError(`Buffer overflow: not enough bytes for frame data`);return{timestamp:n,data:e.slice(t,t+r)}}var yg=class extends Error{constructor(){super(`no supported video codec`),this.name=`NoVideoCodecError`}},bg=[`vp09.00.10.08`,`vp09`,`avc1.640028`,`avc1.4D401F`,`avc1.42E01E`,`avc1`,`av01.0.08M.08`,`av01`,`hev1.1.6.L93.B0`,`hev1`,`vp8`],xg=[`avc1.640028`,`avc1.4D401F`,`avc1.42E01E`,`avc1`,`vp8`,`vp09.00.10.08`,`vp09`,`hev1.1.6.L93.B0`,`hev1`,`av01.0.08M.08`,`av01`];function Sg(e){return e.startsWith(`vp09`)?.8:e.startsWith(`av01`)?.6:e===`vp8`?1.1:1}function Cg(e,t){let n=(t,n)=>({codec:t,width:e.width,height:e.height,framerate:e.framerate,bitrate:Math.round(e.bitrate*Sg(t)),latencyMode:`realtime`,...n?{hardwareAcceleration:`prefer-hardware`}:{},...t.startsWith(`avc1`)?{avc:{format:`annexb`}}:{},...t.startsWith(`hev1`)?{hevc:{format:`annexb`}}:{}});return[...t?bg.map(e=>n(e,!0)):[],...xg.map(e=>n(e,!1))]}async function wg(e,t=e=>VideoEncoder.isConfigSupported(e)){for(let n of e){let{supported:e,config:r}=await t(n);if(e&&r!==void 0)return r}throw new yg}var Tg=Na(za.encoder),Eg=1e6,Dg=4,Og=class extends Error{constructor(){super(`the video source ended before producing a frame`),this.name=`NoVideoFrameError`}};function kg(e){if(typeof MediaStreamTrackProcessor<`u`)return new MediaStreamTrackProcessor({track:e}).readable;let t=document.createElement(`video`);t.muted=!0;let n=new Promise(t=>{e.addEventListener(`ended`,()=>t(void 0),{once:!0})});return new ReadableStream({async start(){t.srcObject=new MediaStream([e]),await t.play()},async pull(r){if(e.readyState===`ended`){r.close();return}let i=await Promise.race([new Promise(e=>{t.requestVideoFrameCallback(t=>e(t))}),n]);i===void 0?r.close():r.enqueue(new VideoFrame(t,{timestamp:i*1e3}))},cancel(){t.srcObject=null}})}var Ag=class e{onchunk;onended;onerror;config;#e;#t;#n;#r;#i=new Zh;#a;#o=new $h(Eg);#s;#c;#l;#u;#d=!1;static async open(t,n,r,i){let a=kg(t).getReader(),o;try{let{value:t}=await a.read();if(t===void 0)throw new Og;o=t;let s=i(),c=await wg(Cg({width:o.displayWidth,height:o.displayHeight,...r},!navigator.userAgent.includes(`Firefox`)));return new e(n,a,o,s,c,r.framerate,i)}catch(e){throw o?.close(),a.cancel().catch(()=>{}),e}}constructor(e,t,n,r,i,a,o){this.#e=e,this.#t=t,this.#s=n,this.#c=r,this.config=i,this.#a=new Qh(a),this.#r=o,this.#n=new VideoEncoder({output:(e,t)=>this.onchunk?.(e,t?.decoderConfig),error:e=>{Tg.error(`video encoder error`,{err:e}),this.#d||this.onerror?.(e)}}),this.#n.configure(i)}get encodeQueueSize(){return this.#n.state===`configured`?this.#n.encodeQueueSize:0}start(){let e=this.#s;e===void 0||this.#d||(this.#s=void 0,this.#f(e).catch(e=>{this.#d||(Tg.error(`video capture ended`,{err:e}),this.onerror?.(e))}))}close(){this.#d||(this.#d=!0,this.#s?.close(),this.#s=void 0,this.#l?.close(),this.#l=void 0,this.#u!==void 0&&cancelAnimationFrame(this.#u),this.#u=void 0,this.#t.cancel().catch(()=>{}),this.#n.state!==`closed`&&this.#n.close())}async#f(e){for(this.#p(e,this.#c);!this.#d;){let{value:e}=await this.#t.read();if(e===void 0)break;if(this.#d){e.close();return}this.#p(e,this.#r())}this.#d||this.onended?.()}#p(e,t){let n=this.#i.at(e.timestamp,t);if(!this.#a.takes(n))e.close();else{if(this.encodeQueueSize>Dg)Tg.warn(`video frame dropped: the encoder is behind`,{queue:this.encodeQueueSize});else if(this.#n.state===`configured`){let t=new VideoFrame(e,{timestamp:n});try{this.#n.encode(t,{keyFrame:this.#o.isKey(n)})}finally{t.close()}}this.#m(e)}}#m(e){this.#l?.close(),this.#l=e,this.#u??=requestAnimationFrame(()=>{this.#u=void 0;let e=this.#l;if(this.#l=void 0,e!==void 0)try{this.#h(e)}finally{e.close()}})}#h(e){let t=this.#e.getContext(`2d`);if(t===null)return;let{width:n,height:r}=this.#e,i=Math.min(n/e.displayWidth,r/e.displayHeight),a={width:e.displayWidth*i,height:e.displayHeight*i};t.clearRect(0,0,n,r),t.drawImage(e,(n-a.width)/2,(r-a.height)/2,a.width,a.height)}},jg=Ja(za.encoder),Mg=jg.meter.fps(`encode`),Ng=jg.meter.bitrate(`egress`),Pg=class extends Error{constructor(){super(`the media stream has no video track`),this.name=`NoVideoTrackError`}},Fg=class extends Error{constructor(e){let t=e instanceof Error?e.message:String(e);super(`the video could not be captured or encoded: ${t}`,{cause:e}),this.name=`VideoFailedError`}},Ig=`/.hls`;function Lg(e){return`${e.trackName} sent #${e.subscribeId}`}function Rg(e){let t=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}var zg=class{onencoded;onerror;onended;#e;#t;#n;constructor(e){this.#e=e}get encodeQueueSize(){return this.#n?.video?.encodeQueueSize??0}async start(e,t){this.stop();let[n,r]=Pn(Mn()),i={stream:e,cancel:r,release:()=>{},video:void 0,stopped:!1};this.#n=i;let a=performance.now(),o=()=>(performance.now()-a)*1e3;try{let r=e.getVideoTracks()[0];if(r===void 0)throw new Pg;let a=await Ag.open(r,this.#e.canvas,t,o);if(i.stopped){a.close();return}i.video=a,jg.info(`publish: video encoder`,{config:a.config}),a.onended=()=>{this.#a(i),this.onended?.()};let s,c=!1;a.onerror=e=>{i.stopped||(s=new Fg(e),this.#a(i),c&&this.onerror?.(s))};let l=()=>{if(s!==void 0)throw s;return i.stopped},u=await this.#r(i,o);if(l())return;let d={name:`video`,role:`video`,packaging:`loc`,isLive:!0,codec:a.config.codec,width:a.config.width,height:a.config.height},f=e=>u===void 0?[e]:[e,u],p=new Rh({version:1,tracks:f(d)}),m=(e,t)=>{jg.error(`publish frame failed`,{track:e,err:t})},h=this.#e.observer,g=new ug({grouping:`keyframe`,observer:h,onerror:m}),_=new ug({grouping:`frame`,observer:h,onerror:m}),v=new Promise(e=>{i.release=e}),y=!1,b=!1;a.onchunk=(e,t)=>{if(t?.description!==void 0&&!y){y=!0;let e=Rg(t.description),n=this.#i(p,f({...d,initData:e}));b||(b=!0,n.then(i.release))}else e.type===`key`&&!b&&(b=!0,i.release());this.onencoded?.(e.byteLength),Mg.mark(),Ng.mark(e.byteLength),g.send(new dg(e),{key:e.type===`key`,timestamp:e.timestamp,bytes:e.byteLength})},u!==void 0&&this.#t!==void 0&&(this.#t.onchunk=e=>{_.send(new dg(e),{key:!0,timestamp:e.timestamp,bytes:e.byteLength})});let x=e=>({async serveTrack(t){e.add(Lg(t),t),jg.info(`publish: subscriber attached`,{track:t.trackName,subscribers:e.size});try{await Promise.race([n.done(),t.context.done()])}finally{e.remove(t)}}});if(await p.registerTrack(d,x(g)),u!==void 0&&await p.registerTrack(u,x(_)),l()||(a.start(),await v,l()))return;if(jg.info(`publish: announcing broadcast`,{path:t.path}),this.#e.mux.publish(n.done(),t.path,p).catch(e=>{i.stopped||(jg.error(`publish: the broadcast was not announced`,{err:e}),this.#a(i),this.onerror?.(e))}),c=!0,t.hls===!0){let e=`${Ig}${t.path}`;jg.info(`publish: opting into the HLS egress`,{path:e}),this.#e.mux.publish(n.done(),e,{async serveTrack(e){await e.redirect({broadcastPath:t.path})!==void 0&&await Br(e)}}).catch(e=>{i.stopped||jg.error(`publish: the HLS opt-in was not announced`,{err:e})})}return{width:a.config.width,height:a.config.height}}catch(e){throw this.#a(i),e}}stop(){this.#n!==void 0&&this.#a(this.#n)}close(){this.stop(),this.#t?.close(),this.#t=void 0}async#r(e,t){if(e.stream.getAudioTracks().length!==0)try{this.#t??=new cg;let n=this.#t,r=await Xh(n.sampleRate,n.channels);return e.stopped?void 0:(await n.start(e.stream,r,t),jg.info(`publish: audio encoder`,{config:r}),{name:`audio`,role:`audio`,packaging:`loc`,isLive:!0,codec:r.codec,samplerate:r.sampleRate,channelConfig:String(r.numberOfChannels)})}catch(e){jg.warn(`audio setup failed, continuing without audio`,{err:e});return}}async#i(e,t){try{await e.setCatalog({version:1,tracks:t}),jg.info(`publish: codec config in catalog`)}catch(e){jg.error(`publish: the catalog could not be updated`,{err:e})}}#a(e){if(!e.stopped){e.stopped=!0,this.#n===e&&(this.#n=void 0),e.cancel(),e.release(),e.video?.close(),this.#t!==void 0&&(this.#t.stop(),this.#t.onchunk=void 0);for(let t of e.stream.getTracks())t.stop()}}},Bg=I(`