From aab6cf61bbbcc3ef74b173d64d942b0e13310956 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 12:07:12 +0000 Subject: [PATCH 01/24] feat(abr): transcode broadcasts into an ABR ladder beside their source Add `qumo abr`, a relay client that, for every broadcast announced beneath ABR_PREFIX, publishes an ABR broadcast at the same path with ABR_SUFFIX appended (/live/cam1 -> /live/cam1.abr). It carries the source's tracks as they are plus one rendition per ladder rung shorter than the source video, encoded by ffmpeg. - Every video track is in one MSF alternate group (altGroup 1) with its width, height, bitrate, codec and initRef; the source's bitrate is measured from its first groups. - Every rendition numbers its groups as the source does and opens each with a keyframe at the same frame (-force_key_frames source), so a player can switch tracks at any group boundary. - Rendition frames keep the exact LOC timestamp of the source frame they were encoded from: outputs are matched back to source frames by order, confirmed by timestamp. - One ffmpeg decodes the source once for all renditions. Frames go in as fragmented MP4 (one fragment per frame) and come out as FLV (one pipe per rendition): both are read and written frame by frame, so neither adds a frame of delay. Encoding uses a microsecond time base, as the default frame-rate time base snaps live timestamps to a grid. - The source track is forwarded without re-encoding and never waits on the encoder; a lagging encoder drops frames up to the next group. Tested by unit tests (ladder, FLV reader, matcher, track buffer, bitrate meter), an encoder test against real ffmpeg with off-grid timestamps, and an integration test: ffmpeg -> RTMP ingest -> relay -> abr -> relay -> viewer, checking the catalog and group-by-group alignment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPWMJL7PH3rPhK5UTGavaB --- README.md | 1 + docs/site/content/en/docs/cli/_index.md | 4 +- docs/site/content/en/docs/cli/abr.md | 98 ++++++ internal/abr/bitrate.go | 46 +++ internal/abr/bitrate_test.go | 27 ++ internal/abr/cmd.go | 193 +++++++++++ internal/abr/encoder.go | 324 ++++++++++++++++++ internal/abr/encoder_test.go | 130 +++++++ internal/abr/flv.go | 126 +++++++ internal/abr/flv_test.go | 70 ++++ internal/abr/ladder.go | 87 +++++ internal/abr/ladder_test.go | 77 +++++ internal/abr/match.go | 92 +++++ internal/abr/match_test.go | 44 +++ internal/abr/output.go | 114 +++++++ internal/abr/pipeline.go | 430 ++++++++++++++++++++++++ internal/abr/track.go | 227 +++++++++++++ internal/abr/track_test.go | 94 ++++++ internal/integration/abr_test.go | 221 ++++++++++++ main.go | 5 + 20 files changed, 2409 insertions(+), 1 deletion(-) create mode 100644 docs/site/content/en/docs/cli/abr.md create mode 100644 internal/abr/bitrate.go create mode 100644 internal/abr/bitrate_test.go create mode 100644 internal/abr/cmd.go create mode 100644 internal/abr/encoder.go create mode 100644 internal/abr/encoder_test.go create mode 100644 internal/abr/flv.go create mode 100644 internal/abr/flv_test.go create mode 100644 internal/abr/ladder.go create mode 100644 internal/abr/ladder_test.go create mode 100644 internal/abr/match.go create mode 100644 internal/abr/match_test.go create mode 100644 internal/abr/output.go create mode 100644 internal/abr/pipeline.go create mode 100644 internal/abr/track.go create mode 100644 internal/abr/track_test.go create mode 100644 internal/integration/abr_test.go diff --git a/README.md b/README.md index c95a5a9f..079b553a 100644 --- a/README.md +++ b/README.md @@ -71,6 +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 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/docs/site/content/en/docs/cli/_index.md b/docs/site/content/en/docs/cli/_index.md index 7a8ee61c..069e8891 100644 --- a/docs/site/content/en/docs/cli/_index.md +++ b/docs/site/content/en/docs/cli/_index.md @@ -1,6 +1,6 @@ --- title: CLI reference -description: qumo's subcommands — relay, rtmp, rtsp, rtsp-push, hls, funnel, dns, playground, doctor, loadgen, update, version. +description: qumo's subcommands — relay, rtmp, rtsp, rtsp-push, hls, abr, funnel, dns, playground, doctor, loadgen, update, version. weight: 5 cascade: type: docs @@ -15,6 +15,7 @@ Commands: rtsp Pull from an RTSP source (e.g. IP camera) and republish as MoQT rtsp-push Start the RTSP push ingest server (ANNOUNCE/RECORD) hls Start the HLS/DASH egress server + abr Transcode broadcasts into ABR renditions (ffmpeg) and republish them funnel Funnel many HTTP senders into one MoQT track (announce/record over POST) dns Answer one DNS name with the region nearest the client (authoritative GeoDNS) playground Start a local demo (relay + web UI) on http://127.0.0.1:8080 @@ -33,6 +34,7 @@ All commands are configured via environment variables — see {{< card link="rtsp" title="rtsp" icon="cloud-download" subtitle="Pull an RTSP source (IP camera) into MoQT." >}} {{< card link="rtsp-push" title="rtsp-push" icon="cloud-upload" subtitle="Standalone RTSP push ingest server." >}} {{< card link="hls" title="hls" icon="globe-alt" subtitle="Serve a MoQ stream as HLS/DASH." >}} + {{< card link="abr" title="abr" icon="adjustments" subtitle="Transcode broadcasts into an ABR ladder." >}} {{< card link="funnel" title="funnel" icon="filter" subtitle="Funnel many HTTP senders into one MoQT track." >}} {{< card link="dns" title="dns" icon="globe" subtitle="Send clients to the nearest region with one hostname." >}} {{< card link="playground" title="playground" icon="lightning-bolt" subtitle="One-command local demo." >}} diff --git a/docs/site/content/en/docs/cli/abr.md b/docs/site/content/en/docs/cli/abr.md new file mode 100644 index 00000000..e2942511 --- /dev/null +++ b/docs/site/content/en/docs/cli/abr.md @@ -0,0 +1,98 @@ +--- +title: abr +description: Transcode broadcasts into an adaptive-bitrate ladder and republish them through the relay. +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/). + +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 +never decodes media. + +## Usage + +``` +qumo abr +``` + +Takes no flags or arguments — configured entirely through environment +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 +INFO abr: connected to the relay +INFO abr: transcoding source=/live/cam1 abr=/live/cam1.abr +``` + +A 1080p source at `/live/cam1` then has `/live/cam1.abr` beside it, whose +catalog lists: + +| Track | Picture | Bitrate | From | +|---|---|---|---| +| `video` | 1080p | measured from the source's first groups | the source, forwarded as is | +| `video-720p` | 720p | 2.5 Mbit/s | encoded | +| `video-360p` | 360p | 800 kbit/s | encoded | +| `audio` | — | — | the source, forwarded as is | + +## What a player receives + +- **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. +- **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 + without a gap or a decoder reset beyond the new track's configuration. +- **Unchanged timestamps.** Each rendition frame carries the exact LOC + timestamp (microseconds) of the source frame it was encoded from. + +The source track is forwarded without re-encoding, so the top rendition has +the source's quality and latency. The renditions add the encoder's latency, +about 10 ms per frame with `libx264` `veryfast` on a modern CPU. + +## How it encodes + +One ffmpeg process per source decodes the source once and encodes every +rendition from it. Frames go to ffmpeg as fragmented MP4, one fragment per +frame, and come back as FLV, one pipe per rendition. Both are formats ffmpeg +reads and writes frame by frame, so neither adds a frame of delay. On Windows +each rendition has an ffmpeg of its own, because Windows cannot pass a process +the extra pipes. + +When the encoder falls behind, source frames are dropped up to the next group, +where it picks up again from a keyframe. The forwarded source track is never +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. +- `ABR_CODEC` must be an H.264 encoder, so browsers decode every rendition + with the same decoder. + +## Configuration + +| 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_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. | +| `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. | +| `ABR_PRESET` | `veryfast` | The encoder's `-preset`; set it to one the encoder knows (e.g. `p1` for `h264_nvenc`), or empty for none. | +| `QUIC_*` | | QUIC transport settings of the session to the relay; see [Configuration]({{< relref "../configuration" >}}). | diff --git a/internal/abr/bitrate.go b/internal/abr/bitrate.go new file mode 100644 index 00000000..8600f1a5 --- /dev/null +++ b/internal/abr/bitrate.go @@ -0,0 +1,46 @@ +package abr + +// bitrateGroups is how many groups a bitrateMeter measures before it states +// a bitrate. +const bitrateGroups = 3 + +// A bitrateMeter measures a video track's bitrate from its first few groups, +// to state the source's bitrate in the catalog alongside the renditions' +// target bitrates. A player choosing between them needs every alternative's. +// +// It states the highest group bitrate it saw, as MSF's bitrate is a maximum +// (draft-ietf-moq-msf-01 §5.2.22), once. +type bitrateMeter struct { + groups int // groups measured + start uint64 // timestamp of the group being measured, in µs + bytes int64 // bytes of the group being measured + max int64 // highest group bitrate, in bit/s + done bool +} + +func newBitrateMeter() *bitrateMeter { + return &bitrateMeter{} +} + +// add counts a frame of n bytes stamped ts microseconds; first reports that +// it opens a group. When the meter has measured enough groups it returns the +// bitrate to state, and true, once. +func (m *bitrateMeter) add(ts uint64, n int, first bool) (int64, bool) { + if m.done { + return 0, false + } + if first { + if m.bytes > 0 && ts > m.start { + bps := m.bytes * 8 * 1_000_000 / int64(ts-m.start) + m.max = max(m.max, bps) + m.groups++ + } + m.start, m.bytes = ts, 0 + if m.groups == bitrateGroups { + m.done = true + return m.max, true + } + } + m.bytes += int64(n) + return 0, false +} diff --git a/internal/abr/bitrate_test.go b/internal/abr/bitrate_test.go new file mode 100644 index 00000000..ea54d596 --- /dev/null +++ b/internal/abr/bitrate_test.go @@ -0,0 +1,27 @@ +package abr + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestBitrateMeter(t *testing.T) { + m := newBitrateMeter() + // Groups of one second; the second is the largest, at 2 Mbit/s. + sizes := []int{125_000, 250_000, 200_000} + var ts uint64 = 7_000_000 + for _, size := range sizes { + for i := range 25 { + _, ok := m.add(ts+uint64(i)*40_000, size/25, i == 0) + assert.False(t, ok) + } + ts += 1_000_000 + } + bps, ok := m.add(ts, 1000, true) + assert.True(t, ok) + assert.Equal(t, int64(2_000_000), bps) + + _, ok = m.add(ts+1_000_000, 1000, true) + assert.False(t, ok, "stated once") +} diff --git a/internal/abr/cmd.go b/internal/abr/cmd.go new file mode 100644 index 00000000..aa975fd3 --- /dev/null +++ b/internal/abr/cmd.go @@ -0,0 +1,193 @@ +package abr + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "log/slog" + "os" + "os/exec" + "os/signal" + "strings" + "sync" + "syscall" + "time" + + "github.com/qumo-dev/gomoqt/moqt" + + "github.com/qumo-dev/qumo/internal/envconfig" + "github.com/qumo-dev/qumo/internal/quicconfig" + "github.com/qumo-dev/qumo/internal/tlsclient" + "github.com/qumo-dev/qumo/internal/upstream" +) + +// retryInterval is how long to wait before dialing the relay again, or +// restarting a pipeline that failed while its source is still announced. +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. +// +// 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 +// 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 +// 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") +// ABR_PRESET - the encoder preset (default "veryfast"; empty for none) +// 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. +func Run(_ []string) error { + ladder, err := ParseLadder(envconfig.String("ABR_LADDER", DefaultLadder)) + if err != nil { + return err + } + cfg := Config{ + Ladder: ladder, + Encoder: EncoderConfig{ + FFmpeg: envconfig.String("ABR_FFMPEG", "ffmpeg"), + Codec: envconfig.String("ABR_CODEC", "libx264"), + Preset: os.Getenv("ABR_PRESET"), + }, + } + if _, ok := os.LookupEnv("ABR_PRESET"); !ok { + cfg.Encoder.Preset = "veryfast" + } + 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") + } + + quicConfig, err := quicconfig.FromEnv(nil) + if err != nil { + return fmt.Errorf("abr: %w", err) + } + quicconfig.LogEnvSet("abr") + relayURL := envconfig.String("RELAY_URL", "https://localhost:4433") + tc := &tls.Config{MinVersion: tls.VersionTLS13} + 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) + } + + 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, + "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) + if err == nil { + slog.Info("abr: connected to the relay") + err = t.Serve(ctx, sess, mux) + // not actionable: the session is over either way + _ = sess.CloseWithError(moqt.NoError, "abr stopping") + } + if ctx.Err() != nil { + return nil + } + slog.Warn("abr: relay session ended, dialing again", "error", err) + select { + case <-ctx.Done(): + return nil + case <-time.After(retryInterval): + } + } +} + +// A Transcoder publishes an ABR broadcast for every broadcast announced +// beneath Prefix. +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. +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) + if err != nil { + return fmt.Errorf("abr: accept announcements: %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 + } + dst := moqt.BroadcastPath(string(src) + t.Suffix) + wg.Go(func() { + annCtx, cancel := context.WithCancel(ctx) + defer cancel() + stop := ann.AfterFunc(cancel) + defer stop() + t.transcode(annCtx, sess, mux, 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) { + for { + slog.Info("abr: transcoding", "source", src, "abr", dst) + err := run(ctx, sess, mux, src, dst, t.Config) + if ctx.Err() != nil { + slog.Info("abr: source ended", "source", src) + return + } + if err == nil { + // The source ended its catalog while still announced; it is + // restarting, or about to be unannounced. + err = errors.New("source catalog ended") + } + slog.Warn("abr: pipeline stopped, restarting", "source", src, "error", err) + select { + case <-ctx.Done(): + return + case <-time.After(retryInterval): + } + } +} diff --git a/internal/abr/encoder.go b/internal/abr/encoder.go new file mode 100644 index 00000000..613c7364 --- /dev/null +++ b/internal/abr/encoder.go @@ -0,0 +1,324 @@ +package abr + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "log/slog" + "os" + "os/exec" + "strconv" + "sync" + + "github.com/qumo-dev/qumo/internal/cmaf" +) + +// EncoderConfig is how renditions are encoded. +type EncoderConfig struct { + // FFmpeg is the ffmpeg executable: a path, or a name looked up in PATH. + FFmpeg string + // Codec is the ffmpeg video encoder, such as "libx264" or "h264_nvenc". + // It must produce H.264: browsers decode the renditions with the codec + // string and decoder configuration the encoder outputs. + Codec string + // Preset is the encoder's speed preset, passed as -preset; empty passes + // none. libx264 is also tuned for zero latency. + Preset string +} + +// sourceConfig describes the source video track an encoder decodes. +type sourceConfig struct { + // Codec is the WebCodecs codec string, such as "avc1.64001f". + Codec string + // Width and Height are the coded picture size. + Width, Height int + // Description is the AVCDecoderConfigurationRecord. + Description []byte +} + +// output is one rendition an encoder produces. +type output struct { + Rung Rung + Width, Height int +} + +// sourceFrame is one frame of the source video track, fed to an encoder. +type sourceFrame struct { + frameInfo + // Data is the frame: AVCC length-prefixed NAL units. + Data []byte +} + +// renditionFrame is one frame an encoder outputs. +type renditionFrame struct { + frameInfo + // Keyframe reports whether the encoder coded the frame as a keyframe. + Keyframe bool + // Data is the frame: AVCC length-prefixed NAL units. + Data []byte +} + +// renditionSink receives what an encoder outputs for each of its renditions, +// indexed as the encoder's outputs are. Its methods are called from one +// goroutine per rendition. +type renditionSink interface { + // Configure delivers the rendition's AVCDecoderConfigurationRecord, before + // its first frame and whenever it changes. + Configure(rendition int, record []byte) + // WriteFrame delivers a frame of the rendition. + WriteFrame(rendition int, f renditionFrame) +} + +// An encoder transcodes the source video track into renditions with one ffmpeg +// process, which decodes the source once and encodes every rendition from it. +// +// Frames go in as fragmented MP4, one fragment per frame, whose box sizes let +// ffmpeg read each frame the moment it arrives and whose microsecond timescale +// carries LOC timestamps unrounded. Renditions come out as FLV, one pipe each, +// which ffmpeg writes frame by frame without waiting for the next frame (its +// MP4 muxer holds every frame back by one, to learn its duration). +type encoder struct { + cfg EncoderConfig + outputs []output + sink renditionSink + packager *cmaf.Packager + + cmd *exec.Cmd + stdin io.WriteCloser + readers []io.ReadCloser + match []matcher + done sync.WaitGroup + + // Input state, owned by the goroutine calling encode. + started bool + sequence uint32 + last uint64 // timestamp of the last frame fed + gap uint32 // gap between the last two frames fed +} + +// defaultFrameGap is the duration stated for a fragment before two frames have +// been seen: a frame at 30 fps. ffmpeg places frames by their decode time, so +// a duration only fills the sample table. +const defaultFrameGap = 1_000_000 / 30 + +func newEncoder(cfg EncoderConfig, src sourceConfig, outputs []output, sink renditionSink) (*encoder, error) { + if len(outputs) == 0 { + return nil, errors.New("abr: encoder needs an output") + } + if src.Width <= 0 || src.Width > 0xffff || src.Height <= 0 || src.Height > 0xffff { + return nil, fmt.Errorf("abr: source picture size %dx%d", src.Width, src.Height) + } + p, err := cmaf.NewPackager(cmaf.VideoConfig{ + Codec: src.Codec, + Width: uint16(src.Width), + Height: uint16(src.Height), + Description: src.Description, + }) + if err != nil { + return nil, fmt.Errorf("abr: source init segment: %w", err) + } + return &encoder{ + cfg: cfg, + outputs: outputs, + sink: sink, + packager: p, + match: make([]matcher, len(outputs)), + gap: defaultFrameGap, + }, nil +} + +// args returns ffmpeg's arguments. The first output is written to stdout +// (pipe:1), and output i after it to file descriptor 2+i (pipe:3, pipe:4, …), +// which [encoder.start] passes as extra files. +func (e *encoder) args() []string { + args := []string{ + "-hide_banner", "-loglevel", "error", "-nostats", + // Read frames as they arrive. -fflags nobuffer must not be added: it + // discards the packets read while probing, which here is the first + // GOP. + "-probesize", "32", "-analyzeduration", "0", "-flags", "low_delay", + // Keep the source timestamps, so outputs can be matched to the + // source frames they were encoded from. + "-copyts", + "-f", "mp4", "-i", "pipe:0", + } + for i, o := range e.outputs { + rate := strconv.FormatInt(o.Rung.Bitrate, 10) + args = append(args, "-map", "0:v", "-c:v", e.cfg.Codec) + if e.cfg.Preset != "" { + args = append(args, "-preset", e.cfg.Preset) + } + if e.cfg.Codec == "libx264" { + args = append(args, "-tune", "zerolatency") + } + args = append(args, + "-b:v", rate, "-maxrate", rate, "-bufsize", strconv.FormatInt(o.Rung.Bitrate/2, 10), + "-pix_fmt", "yuv420p", + // No B-frames, so frames come out in the order they went in, one + // for one, and a keyframe wherever the source has one, so every + // source group opens with a keyframe in every rendition. + "-bf", "0", "-force_key_frames", "source", "-sc_threshold", "0", + "-fps_mode", "passthrough", + // Encode in microseconds. The default time base is the inverse + // of the frame rate ffmpeg guesses, which snaps every timestamp + // to that grid, while a live source's frames fall off it. + "-enc_time_base", "1:1000000", + "-vf", fmt.Sprintf("scale=%d:%d", o.Width, o.Height), + "-flush_packets", "1", + "-f", "flv", "pipe:"+strconv.Itoa(outputFD(i)), + ) + } + return args +} + +// outputFD is the file descriptor ffmpeg writes output i to. +func outputFD(i int) int { + if i == 0 { + return 1 + } + return 2 + i +} + +// start starts ffmpeg. It stops when ctx ends, or when [encoder.close] closes +// its input. +func (e *encoder) start(ctx context.Context) error { + cmd := exec.CommandContext(ctx, e.cfg.FFmpeg, e.args()...) + stdin, err := cmd.StdinPipe() + if err != nil { + return err + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return err + } + readers := []io.ReadCloser{stdout} + var writers []*os.File + for range e.outputs[1:] { + r, w, err := os.Pipe() + if err != nil { + closeAll(readers[1:]) + closeAll(writers) + return err + } + readers = append(readers, r) + writers = append(writers, w) + } + cmd.ExtraFiles = writers + stderr, err := cmd.StderrPipe() + if err != nil { + return err + } + if err := cmd.Start(); err != nil { + closeAll(readers[1:]) + closeAll(writers) + return fmt.Errorf("abr: start ffmpeg: %w", err) + } + // The child holds its own copies of the write ends. + closeAll(writers) + + e.cmd, e.stdin, e.readers = cmd, stdin, readers + e.done.Add(1) + go func() { + defer e.done.Done() + logLines(stderr) + }() + for i, r := range readers { + e.done.Add(1) + go func() { + defer e.done.Done() + if err := e.read(i, r); err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, os.ErrClosed) { + slog.Warn("abr: read rendition", "rendition", e.outputs[i].Rung.TrackName(), "error", err) + } + }() + } + return nil +} + +func closeAll[T io.Closer](cs []T) { + for _, c := range cs { + _ = c.Close() // not actionable: cleaning up after a failed start + } +} + +// logLines logs what ffmpeg writes to stderr, a line at a time. +func logLines(r io.Reader) { + sc := bufio.NewScanner(r) + for sc.Scan() { + slog.Warn("abr: ffmpeg", "message", sc.Text()) + } +} + +// read reads output i's FLV stream and hands its frames to the sink. +func (e *encoder) read(i int, r io.Reader) error { + fr := newFLVReader(r) + for { + tag, err := fr.Next() + if err != nil { + return err + } + switch { + case tag.isSequenceHeader(): + e.sink.Configure(i, tag.payload()) + case tag.isFrame(): + info, ok := e.match[i].match(tag.Timestamp) + if !ok { + next, _ := e.match[i].head() + slog.Warn("abr: encoder output matches no source frame", + "rendition", e.outputs[i].Rung.TrackName(), "timestamp_ms", tag.Timestamp, "next_source_us", next) + continue + } + e.sink.WriteFrame(i, renditionFrame{frameInfo: info, Keyframe: tag.isKeyframe(), Data: tag.payload()}) + } + } +} + +// encode feeds a source frame to the encoder. It must not be called +// concurrently. A frame whose timestamp does not advance on the last one fed +// is skipped: fragmented MP4 places frames by decode time, which LOC does not +// carry, so the source must not reorder frames (no B-frames). +func (e *encoder) encode(f sourceFrame) error { + if !e.started { + if _, err := e.stdin.Write(e.packager.Init()); err != nil { + return fmt.Errorf("abr: write init segment: %w", err) + } + e.started = true + } else { + if f.Timestamp <= e.last { + slog.Warn("abr: source timestamp does not advance; skipping frame (B-frames in the source?)", + "timestamp", f.Timestamp, "last", e.last) + return nil + } + if gap := f.Timestamp - e.last; gap <= 10*cmaf.Timescale { + e.gap = uint32(gap) + } + } + e.sequence++ + frag, _, err := e.packager.Fragment(e.sequence, + []cmaf.Frame{{Timestamp: f.Timestamp, Sync: f.First, Data: f.Data}}, f.Timestamp, e.gap) + if err != nil { + return fmt.Errorf("abr: package frame: %w", err) + } + e.last = f.Timestamp + for i := range e.match { + e.match[i].push(f.frameInfo) + } + if _, err := e.stdin.Write(frag); err != nil { + return fmt.Errorf("abr: write frame: %w", err) + } + return nil +} + +// close closes the encoder's input, waits for ffmpeg to flush and exit and for +// every output to be read, and returns how ffmpeg exited. +func (e *encoder) close() error { + if e.cmd == nil { + return nil + } + _ = e.stdin.Close() // not actionable: ffmpeg sees end of input either way + // Every pipe is read to its end before Wait, which closes them. + e.done.Wait() + closeAll(e.readers[1:]) + return e.cmd.Wait() +} diff --git a/internal/abr/encoder_test.go b/internal/abr/encoder_test.go new file mode 100644 index 00000000..071f16e0 --- /dev/null +++ b/internal/abr/encoder_test.go @@ -0,0 +1,130 @@ +package abr + +import ( + "bytes" + "context" + "os/exec" + "strconv" + "sync" + "testing" + "time" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/qumo-dev/qumo/internal/ingest" +) + +// recordingSink records what an encoder outputs. +type recordingSink struct { + mu sync.Mutex + configs map[int][]byte + frames map[int][]renditionFrame + early bool // a frame arrived before its rendition's configuration +} + +func newRecordingSink() *recordingSink { + return &recordingSink{configs: map[int][]byte{}, frames: map[int][]renditionFrame{}} +} + +func (s *recordingSink) Configure(i int, record []byte) { + s.mu.Lock() + defer s.mu.Unlock() + s.configs[i] = bytes.Clone(record) +} + +func (s *recordingSink) WriteFrame(i int, f renditionFrame) { + s.mu.Lock() + defer s.mu.Unlock() + if s.configs[i] == nil { + s.early = true + } + s.frames[i] = append(s.frames[i], f) +} + +// testSource encodes a synthetic H.264 source with ffmpeg and returns its +// decoder configuration record and frames, grouped at keyframes and stamped +// about 30 fps apart, in microseconds off any frame-rate grid and not whole +// milliseconds, as a live source's are. +func testSource(t *testing.T, width, height, frames, gop int) ([]byte, []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", "libx264", "-preset", "ultrafast", "-bf", "0", + "-g", strconv.Itoa(gop), "-sc_threshold", "0", "-pix_fmt", "yuv420p", "-f", "flv", "pipe:1").Output() + require.NoError(t, err) + + fr := newFLVReader(bytes.NewReader(out)) + var record []byte + var src []sourceFrame + var group moqt.GroupSequence + for { + tag, err := fr.Next() + if err != nil { + break + } + switch { + case tag.isSequenceHeader(): + record = bytes.Clone(tag.payload()) + case tag.isFrame(): + first := tag.isKeyframe() + if first { + group++ + } + ts := uint64(5_021_017 + len(src)*33_367) + src = append(src, sourceFrame{ + frameInfo: frameInfo{Group: group, First: first, Timestamp: ts, WireTimestamp: ts}, + Data: bytes.Clone(tag.payload()), + }) + } + } + require.NotNil(t, record) + require.Len(t, src, frames) + return record, src +} + +func TestEncoderRenditionsMatchSource(t *testing.T) { + record, src := testSource(t, 1280, 720, 90, 30) + cfg, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, record...)) + require.NoError(t, err) + + outputs := []output{{Rung: Rung{Height: 360, Bitrate: 800_000}}, {Rung: Rung{Height: 240, Bitrate: 400_000}}} + for i := range outputs { + outputs[i].Width, outputs[i].Height = outputs[i].Rung.Size(1280, 720) + } + sink := newRecordingSink() + enc, err := newEncoder(EncoderConfig{FFmpeg: "ffmpeg", Codec: "libx264", Preset: "ultrafast"}, + sourceConfig{Codec: cfg.CodecString(), Width: cfg.Width, Height: cfg.Height, Description: record}, + 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()) + + assert.False(t, sink.early, "a frame arrived before its rendition's configuration") + for i, o := range outputs { + got := sink.frames[i] + require.Len(t, got, len(src), o.Rung.TrackName()) + + oc, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, sink.configs[i]...)) + require.NoError(t, err) + assert.Equal(t, o.Width, oc.Width, o.Rung.TrackName()) + assert.Equal(t, o.Height, oc.Height, 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 opens group %d but is not a keyframe", o.Rung.TrackName(), k, f.Group) + } + } + } +} diff --git a/internal/abr/flv.go b/internal/abr/flv.go new file mode 100644 index 00000000..c8c912e5 --- /dev/null +++ b/internal/abr/flv.go @@ -0,0 +1,126 @@ +package abr + +import ( + "bufio" + "encoding/binary" + "errors" + "fmt" + "io" +) + +// FLV tag types (FLV specification v10.1, E.4.1). +const ( + flvTagAudio = 8 + flvTagVideo = 9 + flvTagScript = 18 +) + +// AVC video tag fields (E.4.3.1). +const ( + flvCodecAVC = 7 + flvFrameKey = 1 + flvAVCSeqHeader = 0 + flvAVCNALU = 1 + flvVideoHeaderLen = 5 // FrameType|CodecID, AVCPacketType, CompositionTime(3) +) + +// flvTag is one tag of an FLV stream. +type flvTag struct { + // Type is the tag type: audio, video or script data. + Type byte + // Timestamp is the tag's timestamp in milliseconds. + Timestamp uint32 + // Data is the tag body. + Data []byte +} + +// flvReader reads the tags of an FLV stream, as ffmpeg's flv muxer writes it +// to a pipe. +type flvReader struct { + r *bufio.Reader + header bool + buf [11]byte +} + +func newFLVReader(r io.Reader) *flvReader { + return &flvReader{r: bufio.NewReader(r)} +} + +// Next returns the next tag. It returns io.EOF at a clean end of stream, +// between tags. +func (fr *flvReader) Next() (flvTag, error) { + if !fr.header { + // FLV header (9 bytes) and PreviousTagSize0 (4 bytes). + if _, err := io.ReadFull(fr.r, fr.buf[:9]); err != nil { + return flvTag{}, err + } + if string(fr.buf[:3]) != "FLV" { + return flvTag{}, errors.New("abr: flv: bad signature") + } + offset := binary.BigEndian.Uint32(fr.buf[5:9]) + if offset < 9 { + return flvTag{}, fmt.Errorf("abr: flv: header size %d", offset) + } + if _, err := fr.r.Discard(int(offset-9) + 4); err != nil { + return flvTag{}, noEOF(err) + } + fr.header = true + } + + // io.ReadFull returns io.EOF only when no byte of the tag header was read, + // that is, at a clean end between tags. + if _, err := io.ReadFull(fr.r, fr.buf[:11]); err != nil { + return flvTag{}, err + } + tag := flvTag{ + Type: fr.buf[0] & 0x1f, + // Timestamp (24 bits) then TimestampExtended, the upper 8 bits. + Timestamp: uint32(fr.buf[4])<<16 | uint32(fr.buf[5])<<8 | uint32(fr.buf[6]) | uint32(fr.buf[7])<<24, + } + size := int(fr.buf[1])<<16 | int(fr.buf[2])<<8 | int(fr.buf[3]) + tag.Data = make([]byte, size) + if _, err := io.ReadFull(fr.r, tag.Data); err != nil { + return flvTag{}, noEOF(err) + } + // PreviousTagSize. + if _, err := fr.r.Discard(4); err != nil { + return flvTag{}, noEOF(err) + } + return tag, nil +} + +// noEOF turns an io.EOF in the middle of a tag into io.ErrUnexpectedEOF. +func noEOF(err error) error { + if errors.Is(err, io.EOF) { + return io.ErrUnexpectedEOF + } + return err +} + +// isAVC reports whether t is an AVC video tag. +func (t flvTag) isAVC() bool { + return t.Type == flvTagVideo && len(t.Data) >= flvVideoHeaderLen && t.Data[0]&0x0f == flvCodecAVC +} + +// isSequenceHeader reports whether t is an AVC sequence header: the tag that +// carries the AVCDecoderConfigurationRecord. +func (t flvTag) isSequenceHeader() bool { + return t.isAVC() && t.Data[1] == flvAVCSeqHeader +} + +// isFrame reports whether t carries a coded AVC frame. +func (t flvTag) isFrame() bool { + return t.isAVC() && t.Data[1] == flvAVCNALU +} + +// isKeyframe reports whether t is a keyframe tag. +func (t flvTag) isKeyframe() bool { + return t.isAVC() && t.Data[0]>>4 == flvFrameKey +} + +// payload returns the tag body past the AVC video tag header: the +// AVCDecoderConfigurationRecord of a sequence header, or the length-prefixed +// NAL units of a frame. +func (t flvTag) payload() []byte { + return t.Data[flvVideoHeaderLen:] +} diff --git a/internal/abr/flv_test.go b/internal/abr/flv_test.go new file mode 100644 index 00000000..1b1aac42 --- /dev/null +++ b/internal/abr/flv_test.go @@ -0,0 +1,70 @@ +package abr + +import ( + "bytes" + "encoding/binary" + "io" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// flvStream builds an FLV stream of tags. +func flvStream(tags ...flvTag) []byte { + var b bytes.Buffer + b.Write([]byte{'F', 'L', 'V', 1, 1, 0, 0, 0, 9}) + b.Write([]byte{0, 0, 0, 0}) // PreviousTagSize0 + for _, t := range tags { + n := len(t.Data) + b.Write([]byte{t.Type, byte(n >> 16), byte(n >> 8), byte(n), + byte(t.Timestamp >> 16), byte(t.Timestamp >> 8), byte(t.Timestamp), byte(t.Timestamp >> 24), + 0, 0, 0}) + b.Write(t.Data) + _ = binary.Write(&b, binary.BigEndian, uint32(11+n)) + } + return b.Bytes() +} + +func TestFLVReader(t *testing.T) { + seq := flvTag{Type: flvTagVideo, Timestamp: 0, Data: []byte{0x17, 0, 0, 0, 0, 0x01, 0x64}} + key := flvTag{Type: flvTagVideo, Timestamp: 5_000, Data: []byte{0x17, 1, 0, 0, 0, 0, 0, 0, 1, 0x65}} + inter := flvTag{Type: flvTagVideo, Timestamp: 0x01_02_03_04, Data: []byte{0x27, 1, 0, 0, 0, 0, 0, 0, 1, 0x41}} + script := flvTag{Type: flvTagScript, Data: []byte{2, 0, 0}} + + fr := newFLVReader(bytes.NewReader(flvStream(script, seq, key, inter))) + var got []flvTag + for { + tag, err := fr.Next() + if err == io.EOF { + break + } + require.NoError(t, err) + got = append(got, tag) + } + require.Len(t, got, 4) + assert.Equal(t, []flvTag{script, seq, key, inter}, got) + + assert.False(t, got[0].isAVC()) + assert.True(t, got[1].isSequenceHeader()) + assert.False(t, got[1].isFrame()) + assert.Equal(t, []byte{0x01, 0x64}, got[1].payload()) + assert.True(t, got[2].isFrame()) + assert.True(t, got[2].isKeyframe()) + assert.True(t, got[3].isFrame()) + assert.False(t, got[3].isKeyframe()) + assert.Equal(t, uint32(0x01_02_03_04), got[3].Timestamp, "the extended byte is the timestamp's top 8 bits") +} + +func TestFLVReaderTruncated(t *testing.T) { + stream := flvStream(flvTag{Type: flvTagVideo, Data: []byte{0x17, 1, 0, 0, 0, 1, 2, 3}}) + for _, cut := range []int{len(stream) - 1, len(stream) - 6, 13 + 5} { + _, err := newFLVReader(bytes.NewReader(stream[:cut])).Next() + assert.ErrorIs(t, err, io.ErrUnexpectedEOF, "cut at %d", cut) + } +} + +func TestFLVReaderBadSignature(t *testing.T) { + _, err := newFLVReader(bytes.NewReader([]byte("NOTFLV\x00\x00\x00\x09\x00\x00\x00\x00"))).Next() + assert.Error(t, err) +} diff --git a/internal/abr/ladder.go b/internal/abr/ladder.go new file mode 100644 index 00000000..5df33c25 --- /dev/null +++ b/internal/abr/ladder.go @@ -0,0 +1,87 @@ +package abr + +import ( + "cmp" + "errors" + "fmt" + "slices" + "strconv" + "strings" +) + +// DefaultLadder is the rendition ladder used when ABR_LADDER is unset: 720p at +// 2.5 Mbit/s and 360p at 800 kbit/s, below a source that is typically 1080p. +const DefaultLadder = "720:2500,360:800" + +// A Rung is one rendition of the ladder: a picture height and the bitrate the +// encoder targets for it. +type Rung struct { + // Height is the picture height in pixels. The width follows from the + // source's aspect ratio. + Height int + // Bitrate is the target bitrate in bits per second. + Bitrate int64 +} + +// TrackName is the name of the rung's track in the output broadcast, such as +// "video-720p". +func (r Rung) TrackName() string { + return "video-" + strconv.Itoa(r.Height) + "p" +} + +// Size returns the rung's picture size for a source of srcWidth×srcHeight, +// keeping the source's aspect ratio. Both dimensions are even, as 4:2:0 +// chroma subsampling requires. +func (r Rung) Size(srcWidth, srcHeight int) (width, height int) { + height = r.Height &^ 1 + // The nearest even width: twice the nearest whole half-width. + width = 2 * ((srcWidth*height + srcHeight) / (2 * srcHeight)) + return width, height +} + +// ParseLadder parses a ladder description: comma-separated rungs, each a +// height and a bitrate in kbit/s joined by a colon, such as "720:2500,360:800". +// The result is ordered from the tallest rung down. +func ParseLadder(s string) ([]Rung, error) { + var ladder []Rung + for part := range strings.SplitSeq(s, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + h, kbps, ok := strings.Cut(part, ":") + if !ok { + return nil, fmt.Errorf("abr: ladder rung %q: want height:kbps", part) + } + height, err := strconv.Atoi(h) + if err != nil || height < 2 { + return nil, fmt.Errorf("abr: ladder rung %q: bad height", part) + } + rate, err := strconv.ParseInt(kbps, 10, 64) + if err != nil || rate <= 0 { + return nil, fmt.Errorf("abr: ladder rung %q: bad bitrate", part) + } + if slices.ContainsFunc(ladder, func(r Rung) bool { return r.Height == height }) { + return nil, fmt.Errorf("abr: ladder rung %q: height %d appears twice", part, height) + } + ladder = append(ladder, Rung{Height: height, Bitrate: rate * 1000}) + } + if len(ladder) == 0 { + return nil, errors.New("abr: empty ladder") + } + slices.SortFunc(ladder, func(a, b Rung) int { return cmp.Compare(b.Height, a.Height) }) + return ladder, nil +} + +// below returns the rungs of ladder shorter than a source srcHeight tall. A +// rung as tall as the source or taller would only spend bits re-encoding what +// the source track already carries. +func below(ladder []Rung, srcHeight int) []Rung { + var out []Rung + for _, r := range ladder { + if r.Height < srcHeight { + out = append(out, r) + } + } + return out +} diff --git a/internal/abr/ladder_test.go b/internal/abr/ladder_test.go new file mode 100644 index 00000000..a861d422 --- /dev/null +++ b/internal/abr/ladder_test.go @@ -0,0 +1,77 @@ +package abr + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseLadder(t *testing.T) { + tests := map[string]struct { + in string + want []Rung + wantErr bool + }{ + "default": {in: DefaultLadder, want: []Rung{{720, 2_500_000}, {360, 800_000}}}, + "sorted tallest first": { + in: "360:800, 1080:6000,720:2500", + want: []Rung{{1080, 6_000_000}, {720, 2_500_000}, {360, 800_000}}, + }, + "trailing comma": {in: "480:1200,", want: []Rung{{480, 1_200_000}}}, + "empty": {in: " ", wantErr: true}, + "no bitrate": {in: "720", wantErr: true}, + "bad height": {in: "x:100", wantErr: true}, + "zero bitrate": {in: "720:0", wantErr: true}, + "duplicate height": {in: "720:2500,720:2000", wantErr: true}, + "negative bitrate": {in: "720:-1", wantErr: true}, + "height too small": {in: "1:100", wantErr: true}, + "non-numeric kbps": {in: "720:fast", wantErr: true}, + "missing separator": {in: "720-2500", wantErr: true}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + got, err := ParseLadder(tt.in) + if tt.wantErr { + assert.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestRungSize(t *testing.T) { + tests := map[string]struct { + rung Rung + srcW, srcH int + wantW, wantH int + }{ + "16:9 to 720p": {Rung{Height: 720}, 1920, 1080, 1280, 720}, + "16:9 to 360p": {Rung{Height: 360}, 1920, 1080, 640, 360}, + "16:9 to 240p, even": {Rung{Height: 240}, 1280, 720, 426, 240}, + "4:3 to 480p": {Rung{Height: 480}, 1440, 1080, 640, 480}, + "odd height rounded": {Rung{Height: 361}, 1920, 1080, 640, 360}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + w, h := tt.rung.Size(tt.srcW, tt.srcH) + assert.Equal(t, tt.wantW, w) + assert.Equal(t, tt.wantH, h) + assert.Zero(t, w%2) + assert.Zero(t, h%2) + }) + } +} + +func TestBelow(t *testing.T) { + ladder := []Rung{{1080, 6_000_000}, {720, 2_500_000}, {360, 800_000}} + assert.Equal(t, []Rung{{360, 800_000}}, below(ladder, 720), "a rung as tall as the source is not encoded") + assert.Equal(t, ladder, below(ladder, 2160)) + assert.Empty(t, below(ladder, 360)) +} + +func TestRungTrackName(t *testing.T) { + assert.Equal(t, "video-720p", Rung{Height: 720}.TrackName()) +} diff --git a/internal/abr/match.go b/internal/abr/match.go new file mode 100644 index 00000000..20db3666 --- /dev/null +++ b/internal/abr/match.go @@ -0,0 +1,92 @@ +package abr + +import ( + "sync" + + "github.com/qumo-dev/gomoqt/moqt" +) + +// frameInfo is what a rendition frame inherits from the source frame it was +// encoded from: where the source frame sits in its track, and its timestamps. +type frameInfo struct { + // Group is the sequence of the source group the frame belongs to. + Group moqt.GroupSequence + // First reports whether the frame opens its group. + First bool + // Timestamp is the frame's LOC timestamp, in microseconds. + Timestamp uint64 + // WireTimestamp is the moqt frame timestamp, in the track's timescale. + WireTimestamp uint64 +} + +// matchTolerance is how far apart, in microseconds, an encoder output +// timestamp and a source timestamp may be and still name the same frame. FLV +// carries milliseconds, which ffmpeg rounds to the nearest, so a match is +// never more than half a millisecond off; frames are tens of milliseconds +// apart, so a millisecond cannot name the wrong one. +const matchTolerance = 1000 + +// maxPending bounds the frames a matcher remembers. An encoder that falls +// this far behind has stopped; the oldest are forgotten rather than kept +// without bound. +const maxPending = 1024 + +// A matcher pairs the frames an encoder outputs with the source frames they +// were encoded from. +// +// The encoder passes frames through one for one (no B-frames, no frame rate +// conversion), so outputs come back in the order frames were fed, and +// matching is by order. The output's timestamp, in milliseconds, confirms +// each match, and lets the matcher step over a source frame the encoder +// dropped instead of shifting every later frame onto the wrong source. +type matcher struct { + mu sync.Mutex + pending []frameInfo +} + +// push records a source frame about to be fed to the encoder. +func (m *matcher) push(f frameInfo) { + m.mu.Lock() + defer m.mu.Unlock() + if len(m.pending) == maxPending { + m.pending = m.pending[1:] + } + m.pending = append(m.pending, f) +} + +// head returns the timestamp of the oldest source frame remembered, for +// diagnostics, and false when none is. +func (m *matcher) head() (uint64, bool) { + m.mu.Lock() + defer m.mu.Unlock() + if len(m.pending) == 0 { + return 0, false + } + return m.pending[0].Timestamp, true +} + +// match returns the source frame an output frame stamped ms milliseconds was +// encoded from, and forgets it and any older source frame the encoder +// skipped. It reports false when no remembered source frame matches. +func (m *matcher) match(ms uint32) (frameInfo, bool) { + m.mu.Lock() + defer m.mu.Unlock() + out := int64(ms) * 1000 + for len(m.pending) > 0 { + head := m.pending[0] + d := out - int64(head.Timestamp) + switch { + case d >= matchTolerance: + // The output is later than this source frame: the encoder + // dropped it. + m.pending = m.pending[1:] + case d <= -matchTolerance: + // The output is earlier than every source frame remembered. + return frameInfo{}, false + default: + m.pending = m.pending[1:] + return head, true + } + } + return frameInfo{}, false +} diff --git a/internal/abr/match_test.go b/internal/abr/match_test.go new file mode 100644 index 00000000..f91e77f7 --- /dev/null +++ b/internal/abr/match_test.go @@ -0,0 +1,44 @@ +package abr + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestMatcher(t *testing.T) { + var m matcher + for i, ts := range []uint64{1_000_400, 1_033_733, 1_067_066, 1_100_399} { + m.push(frameInfo{Group: 1, First: i == 0, Timestamp: ts}) + } + + got, ok := m.match(1000) // 1_000_400 rounded to ms + assert.True(t, ok) + assert.Equal(t, uint64(1_000_400), got.Timestamp) + assert.True(t, got.First) + + // The encoder dropped 1_033_733: the next output matches the frame after. + got, ok = m.match(1067) + assert.True(t, ok) + assert.Equal(t, uint64(1_067_066), got.Timestamp) + + // An output earlier than every remembered frame matches none, and + // forgets none. + _, ok = m.match(900) + assert.False(t, ok) + got, ok = m.match(1100) + assert.True(t, ok) + assert.Equal(t, uint64(1_100_399), got.Timestamp) + + _, ok = m.match(1133) + assert.False(t, ok, "nothing left to match") +} + +func TestMatcherBounded(t *testing.T) { + var m matcher + for i := range maxPending + 10 { + m.push(frameInfo{Timestamp: uint64(i) * 33_333}) + } + assert.Len(t, m.pending, maxPending) + assert.Equal(t, uint64(10*33_333), m.pending[0].Timestamp, "the oldest are forgotten") +} diff --git a/internal/abr/output.go b/internal/abr/output.go new file mode 100644 index 00000000..96731233 --- /dev/null +++ b/internal/abr/output.go @@ -0,0 +1,114 @@ +package abr + +import ( + "encoding/base64" + "fmt" + "sync" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/qumo-dev/gomoqt/msf" +) + +// videoAltGroup is the MSF alternate group every video track of an output +// broadcast belongs to: the source and its renditions are alternatives of one +// picture, of which a player decodes one at a time (draft-ietf-moq-msf-01 +// §5.2.11). +const videoAltGroup = 1 + +// Publisher properties of tracks whose publisher states none. +var ( + defaultVideoInfo = moqt.PublishInfo{Priority: 128, Ordered: true, MaxLatency: 2000, Timescale: 1_000_000} + defaultAudioInfo = moqt.PublishInfo{Priority: 128, Ordered: false, MaxLatency: 2000, Timescale: 1_000_000} + catalogInfo = moqt.PublishInfo{Priority: 255, Ordered: true, Timescale: 1000} +) + +var ( + _ moqt.TrackHandler = (*outputBroadcast)(nil) + _ moqt.TrackInfoProvider = (*outputBroadcast)(nil) +) + +// outputBroadcast is the broadcast an ABR pipeline publishes: the source's +// tracks, forwarded, and the renditions, behind one MSF catalog. +type outputBroadcast struct { + b *msf.Broadcast + + mu sync.Mutex // serializes catalog changes, guards info + info map[moqt.TrackName]moqt.PublishInfo +} + +func newOutputBroadcast() (*outputBroadcast, error) { + b, err := msf.NewBroadcast(msf.Catalog{Version: 1}) + if err != nil { + return nil, fmt.Errorf("abr: output broadcast: %w", err) + } + return &outputBroadcast{b: b, info: map[moqt.TrackName]moqt.PublishInfo{}}, nil +} + +// ServeTrack serves a subscriber of any track of the broadcast. +func (o *outputBroadcast) ServeTrack(tw *moqt.TrackWriter) { + o.b.ServeTrack(tw) +} + +// TrackInfo answers TRACK_INFO with the publisher properties each track was +// added with. +func (o *outputBroadcast) TrackInfo(name moqt.TrackName) (moqt.PublishInfo, bool) { + if name == o.b.CatalogTrackName() { + return catalogInfo, true + } + o.mu.Lock() + defer o.mu.Unlock() + info, ok := o.info[name] + return info, ok +} + +// addTrack adds t to the catalog, or replaces the track of its name, served by +// tr. init, when not empty, is the track's decoder configuration, listed in +// the catalog's InitDataList under the track's name. +func (o *outputBroadcast) addTrack(t msf.Track, init []byte, info moqt.PublishInfo, tr *track) error { + o.mu.Lock() + defer o.mu.Unlock() + if len(init) > 0 { + catalog := o.b.Catalog() + entry := msf.InitDataRef{ID: t.Name, Type: "inline", Data: base64.StdEncoding.EncodeToString(init)} + replaced := false + for i := range catalog.InitDataList { + if catalog.InitDataList[i].ID == entry.ID { + catalog.InitDataList[i] = entry + replaced = true + } + } + if !replaced { + catalog.InitDataList = append(catalog.InitDataList, entry) + } + if err := o.b.SetCatalog(catalog); err != nil { + return fmt.Errorf("abr: init data of %s: %w", t.Name, err) + } + t.InitRef = entry.ID + } + o.info[moqt.TrackName(t.Name)] = info + if err := o.b.RegisterTrack(t, moqt.TrackHandlerFunc(func(tw *moqt.TrackWriter) { + tr.serve(tw.Context(), tw) + })); err != nil { + return fmt.Errorf("abr: add track %s: %w", t.Name, err) + } + return nil +} + +// setBitrate states the bitrate of the track named name in the catalog. +func (o *outputBroadcast) setBitrate(name string, bitrate int64) 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) + return o.b.SetCatalog(catalog) + } + } + return fmt.Errorf("abr: no track %s", name) +} + +// close ends the broadcast's catalog track for its subscribers. +func (o *outputBroadcast) close() { + o.b.Close() +} diff --git a/internal/abr/pipeline.go b/internal/abr/pipeline.go new file mode 100644 index 00000000..249621e4 --- /dev/null +++ b/internal/abr/pipeline.go @@ -0,0 +1,430 @@ +package abr + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "log/slog" + "runtime" + "strings" + "sync" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/qumo-dev/gomoqt/msf" + "golang.org/x/sync/errgroup" + + "github.com/qumo-dev/qumo/internal/cmaf" + "github.com/qumo-dev/qumo/internal/ingest" +) + +// Config is what an ABR pipeline makes of a source broadcast. +type Config struct { + // Ladder lists the renditions to encode, tallest first. Only the rungs + // shorter than the source are encoded. + Ladder []Rung + // Encoder is how they are encoded. + Encoder EncoderConfig +} + +// encodeQueue is how many source frames may wait for the encoder. Past it the +// encoder is behind, and frames are dropped up to the next group, where the +// encoder can pick up again from a keyframe. +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 + + // started names the source tracks being handled, and transcoding + // reports that one of them is being transcoded. Only the catalog + // follower touches them. + started map[string]bool + 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 { + out, err := newOutputBroadcast() + if err != nil { + return err + } + defer out.close() + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + 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) }) + 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}) + if err != nil { + return fmt.Errorf("abr: subscribe catalog: %w", err) + } + defer tr.Close() // not actionable: the pipeline is ending + f := moqt.NewFrame(0) + for { + gr, err := tr.AcceptGroup(ctx) + if err != nil { + if errors.Is(err, io.EOF) { + return nil // the source ended + } + return fmt.Errorf("abr: read catalog: %w", err) + } + if err := gr.ReadFrame(f); err != nil { + gr.CancelRead(moqt.InternalGroupErrorCode) + continue + } + gr.CancelRead(moqt.InternalGroupErrorCode) // one frame per catalog group + catalog, err := msf.ParseCatalog(f.Body()) + if err != nil { + slog.Warn("abr: source catalog does not parse", "broadcast", p.src, "error", err) + continue + } + for _, t := range catalog.Tracks { + if t.Namespace != "" && t.Namespace != string(p.src) { + continue // a track of another broadcast + } + if p.started[t.Name] { + continue + } + p.started[t.Name] = true + init, err := initData(catalog, t) + 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 { + p.transcoding = true + g.Go(func() error { return p.transcode(ctx, t, init) }) + } else { + g.Go(func() error { return p.forward(ctx, t, init) }) + } + } + } +} + +func isAVC(codec string) bool { + return strings.HasPrefix(codec, "avc1.") +} + +// initData returns the decoder configuration the catalog lists for t, or nil +// when it lists none. +func initData(c msf.Catalog, t msf.Track) ([]byte, error) { + if t.InitRef == "" { + return nil, nil + } + for _, e := range c.InitDataList { + if e.ID == t.InitRef { + if e.Type != "" && e.Type != "inline" { + return nil, fmt.Errorf("init data %q is %q, not inline", e.ID, e.Type) + } + return base64.StdEncoding.DecodeString(e.Data) + } + } + return nil, fmt.Errorf("no init data %q", t.InitRef) +} + +// publishInfo returns the source track's publisher properties, or def when +// the source does not state them. +func (p *pipeline) publishInfo(ctx context.Context, name string, def moqt.PublishInfo) moqt.PublishInfo { + info, err := p.sess.TrackInfo(ctx, p.src, moqt.TrackName(name)) + if err != nil || info == nil { + return def + } + return *info +} + +// outputTrack returns the catalog entry of a forwarded source track: the +// source's, in the output broadcast's namespace. +func outputTrack(t msf.Track) msf.Track { + t.Namespace = "" + t.InitRef = "" + return t +} + +// 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 + if t.Role == msf.RoleVideo { + def = defaultVideoInfo + } + out := newTrack() + defer out.close() + if err := p.out.addTrack(outputTrack(t), init, p.publishInfo(ctx, t.Name, def), out); err != nil { + return err + } + return p.readTrack(ctx, t.Name, func(seq moqt.GroupSequence) bool { + return out.openGroup(seq) + }, func(_ moqt.GroupSequence, _ int, f *moqt.Frame) { + out.writeFrame(f) + }, out.endGroup) +} + +// readTrack subscribes to the source track name and reads its groups in +// sequence order, skipping any that arrive after a later one. For each group +// it calls open, then frame for each frame (a copy the callee may keep), then +// end. open may refuse the group, which is then skipped. +func (p *pipeline) readTrack(ctx context.Context, name string, + open func(moqt.GroupSequence) bool, frame func(moqt.GroupSequence, int, *moqt.Frame), end func()) error { + tr, err := p.sess.Subscribe(ctx, p.src, moqt.TrackName(name), &moqt.SubscribeConfig{Ordered: true}) + if err != nil { + return fmt.Errorf("abr: subscribe %s: %w", name, err) + } + defer tr.Close() // not actionable: the pipeline is ending + + var last moqt.GroupSequence + buf := moqt.NewFrame(0) + for { + gr, err := tr.AcceptGroup(ctx) + if err != nil { + if errors.Is(err, io.EOF) { + return nil // the source ended the track + } + return fmt.Errorf("abr: read %s: %w", name, err) + } + seq := gr.GroupSequence() + if seq <= last || !open(seq) { + gr.CancelRead(moqt.InternalGroupErrorCode) + continue + } + last = seq + for i := 0; ; i++ { + if err := gr.ReadFrame(buf); err != nil { + break // the group ended, or was reset + } + frame(seq, i, buf.Clone()) + } + end() + } +} + +// 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...)) + 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) + } + 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) + } + srcOut := newTrack() + defer srcOut.close() + if err := p.out.addTrack(src, init, info, srcOut); err != nil { + return err + } + + var outputs []output + for _, r := range below(p.cfg.Ladder, height) { + w, h := r.Size(width, height) + outputs = append(outputs, output{Rung: r, Width: w, Height: h}) + } + if len(outputs) == 0 { + slog.Info("abr: source is no taller than any rung; forwarding it alone", "broadcast", p.src, "height", height) + } + 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 + // hand a process the extra pipes that takes, so there each rendition has + // an ffmpeg of its own. + groups := [][]int{} + if runtime.GOOS == "windows" { + for i := range outputs { + groups = append(groups, []int{i}) + } + } else if len(outputs) > 0 { + all := make([]int, len(outputs)) + for i := range all { + all[i] = i + } + groups = append(groups, all) + } + sc := sourceConfig{Codec: t.Codec, Width: cfg.Width, Height: cfg.Height, Description: init} + var encoders []*encoder + for _, idx := range groups { + outs := make([]output, len(idx)) + for k, i := range idx { + outs[k] = outputs[i] + } + enc, err := newEncoder(p.cfg.Encoder, sc, outs, remap{r, idx}) + if err != nil { + return err + } + if err := enc.start(ctx); err != nil { + return err + } + encoders = append(encoders, enc) + } + + // 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) + go func() { + fed <- feed(queue, encoders) + }() + + 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 + } + return err +} + +// feed feeds the frames of queue to every encoder, then closes them. +func feed(queue <-chan sourceFrame, encoders []*encoder) error { + var errs []error + failed := false + for f := range queue { + if failed { + continue // drain, so the reader never blocks + } + for _, enc := range encoders { + if err := enc.encode(f); err != nil { + errs = append(errs, err) + failed = true + } + } + } + for _, enc := range encoders { + if err := enc.close(); err != nil && !failed { + errs = append(errs, fmt.Errorf("abr: ffmpeg: %w", err)) + } + } + return errors.Join(errs...) +} + +// remap is the sink of an encoder producing a subset of the renditions: it +// maps the encoder's output indexes onto the renditions'. +type remap struct { + r *renditions + idx []int +} + +func (m remap) Configure(i int, record []byte) { m.r.Configure(m.idx[i], record) } +func (m remap) WriteFrame(i int, f renditionFrame) { m.r.WriteFrame(m.idx[i], f) } + +// renditions publishes what the encoders output, one track per rendition. +type renditions struct { + out *outputBroadcast + outputs []output + info moqt.PublishInfo + tracks []*track + + mu sync.Mutex + configured []bool +} + +// Configure adds rendition i's track to the catalog with its decoder +// configuration, or updates the configuration of a track already added. +func (r *renditions) Configure(i int, record []byte) { + cfg, err := ingest.ParseAVCConfig(append([]byte{0x17, 0, 0, 0, 0}, record...)) + if err != nil { + slog.Warn("abr: rendition decoder configuration does not parse", "rendition", r.outputs[i].Rung.TrackName(), "error", err) + return + } + o := r.outputs[i] + t := msf.Track{ + Name: o.Rung.TrackName(), + Packaging: msf.PackagingLOC, + Role: msf.RoleVideo, + IsLive: new(true), + Label: fmt.Sprintf("%dp", o.Height), + AltGroup: new(int64(videoAltGroup)), + Codec: cfg.CodecString(), + Width: new(int64(o.Width)), + Height: new(int64(o.Height)), + Bitrate: new(o.Rung.Bitrate), + } + if err := r.out.addTrack(t, record, r.info, r.tracks[i]); err != nil { + slog.Warn("abr: add rendition", "rendition", t.Name, "error", err) + return + } + r.mu.Lock() + r.configured[i] = true + r.mu.Unlock() +} + +// WriteFrame adds a frame to rendition i's track, opening a group wherever the +// source opened one, so the rendition's groups are numbered as the source's +// and start at the same frames. +func (r *renditions) WriteFrame(i int, f renditionFrame) { + r.mu.Lock() + configured := r.configured[i] + r.mu.Unlock() + if !configured { + return + } + tr := r.tracks[i] + if f.First { + if !f.Keyframe { + // Not a decode point: a subscriber joining here could not + // decode it, so the group continues the previous one. + slog.Warn("abr: rendition frame opening a group is not a keyframe", "rendition", r.outputs[i].Rung.TrackName(), "group", f.Group) + } else { + tr.openGroup(f.Group) + } + } + loc := cmaf.EncodeLOC(f.Timestamp, f.Data) + mf := moqt.NewFrame(len(loc)) + mf.Timestamp = f.WireTimestamp + _, _ = mf.Write(loc) // not actionable: a Frame grows to fit + tr.writeFrame(mf) // refused before the first group opens: frames that cannot be decoded +} diff --git a/internal/abr/track.go b/internal/abr/track.go new file mode 100644 index 00000000..74950e47 --- /dev/null +++ b/internal/abr/track.go @@ -0,0 +1,227 @@ +package abr + +import ( + "context" + "sync" + + "github.com/qumo-dev/gomoqt/moqt" +) + +// ringSize is how many groups a track keeps for subscribers. A subscriber is +// served from the newest group on, so only one that falls behind reads older +// ones, and a few seconds of video is plenty. +const ringSize = 4 + +// A track holds the recent groups of one published track and serves them to +// subscribers, under the group sequences its writer gives them. +// +// The sequences are what make the output broadcast switchable: every rendition +// numbers its groups as the source does, so group N of each track starts at +// the same frame, and a subscriber can leave one track after group N and join +// another at group N+1. +type track struct { + mu sync.Mutex + groups []*group // oldest first, at most ringSize + changed chan struct{} // closed, and replaced, on every change + closed bool +} + +// A group is one group of a track. +type group struct { + seq moqt.GroupSequence + frames []*moqt.Frame + done bool // no more frames will be added +} + +func newTrack() *track { + return &track{changed: make(chan struct{})} +} + +// notifyLocked wakes every subscriber waiting for a change. +func (t *track) notifyLocked() { + close(t.changed) + t.changed = make(chan struct{}) +} + +// openGroup ends the current group and starts group seq. A seq that does not +// advance on the current group's is refused: subscribers are served in +// sequence order, and would never be served it. +func (t *track) openGroup(seq moqt.GroupSequence) bool { + t.mu.Lock() + defer t.mu.Unlock() + if t.closed { + return false + } + if n := len(t.groups); n > 0 { + cur := t.groups[n-1] + if seq <= cur.seq { + return false + } + cur.done = true + } + if len(t.groups) == ringSize { + t.groups = append(t.groups[:0], t.groups[1:]...) + } + t.groups = append(t.groups, &group{seq: seq}) + t.notifyLocked() + return true +} + +// writeFrame adds f to the current group. It reports false when there is no +// group open. +func (t *track) writeFrame(f *moqt.Frame) bool { + t.mu.Lock() + defer t.mu.Unlock() + n := len(t.groups) + if t.closed || n == 0 || t.groups[n-1].done { + return false + } + t.groups[n-1].frames = append(t.groups[n-1].frames, f) + t.notifyLocked() + return true +} + +// endGroup ends the current group, so subscribers finish its stream rather +// than wait for frames that will not come. +func (t *track) endGroup() { + t.mu.Lock() + defer t.mu.Unlock() + if n := len(t.groups); n > 0 && !t.groups[n-1].done { + t.groups[n-1].done = true + t.notifyLocked() + } +} + +// close ends the track: subscribers are served what it holds, then their +// subscriptions end. +func (t *track) close() { + t.mu.Lock() + defer t.mu.Unlock() + if t.closed { + return + } + if n := len(t.groups); n > 0 { + t.groups[n-1].done = true + } + t.closed = true + t.notifyLocked() +} + +// view is what a subscriber is to serve next, read under the track's lock. +type view struct { + seq moqt.GroupSequence + frames []*moqt.Frame // frames from the subscriber's position on + done bool // the group has no more frames to come + found bool // there is a group to serve + closed bool // the track has ended + changed <-chan struct{} +} + +// next returns what to serve a subscriber that has been served groups up to +// after (zero for none), and frames of group seq up to from. A subscriber with +// nothing served yet starts at the newest group; one whose next group has left +// the ring skips to the oldest still held. +func (t *track) next(after moqt.GroupSequence, current moqt.GroupSequence, from int) view { + t.mu.Lock() + defer t.mu.Unlock() + v := view{closed: t.closed, changed: t.changed} + if len(t.groups) == 0 { + return v + } + var g *group + switch { + case current != 0: + g = t.find(current) + if g == nil { + // The group being served left the ring: end it where it is. + v.seq, v.done, v.found = current, true, true + return v + } + case after == 0: + g = t.groups[len(t.groups)-1] + default: + for _, c := range t.groups { + if c.seq > after { + g = c + break + } + } + if g == nil { + return v + } + from = 0 + } + v.seq, v.done, v.found = g.seq, g.done, true + if from < len(g.frames) { + v.frames = g.frames[from:len(g.frames):len(g.frames)] + } + return v +} + +func (t *track) find(seq moqt.GroupSequence) *group { + for _, g := range t.groups { + if g.seq == seq { + return g + } + } + return nil +} + +// serve serves tw from the newest group on, until the subscriber leaves, ctx +// ends, or the track is closed and fully served. +func (t *track) serve(ctx context.Context, tw *moqt.TrackWriter) { + defer tw.Close() // not actionable: the subscription is over either way + var ( + served moqt.GroupSequence // last group fully served + gw *moqt.GroupWriter // group being served + sent int // frames of it sent + ) + defer func() { + if gw != nil { + _ = gw.Close() // not actionable: the subscriber is leaving + } + }() + for { + var current moqt.GroupSequence + if gw != nil { + current = gw.GroupSequence() + } + v := t.next(served, current, sent) + if v.found { + if gw == nil { + var err error + gw, err = tw.OpenGroupAt(ctx, v.seq) + if err != nil { + return + } + sent = 0 + } + for _, f := range v.frames { + if err := gw.WriteFrame(f); err != nil { + gw.CancelWrite(moqt.InternalGroupErrorCode) + gw = nil + served = v.seq + break + } + sent++ + } + if gw != nil && v.done { + _ = gw.Close() // not actionable: the next group follows either way + gw = nil + served = v.seq + } + if gw == nil { + continue // look for the next group straight away + } + } else if v.closed { + return + } + select { + case <-v.changed: + case <-ctx.Done(): + return + case <-tw.Context().Done(): + return + } + } +} diff --git a/internal/abr/track_test.go b/internal/abr/track_test.go new file mode 100644 index 00000000..40ecb1e5 --- /dev/null +++ b/internal/abr/track_test.go @@ -0,0 +1,94 @@ +package abr + +import ( + "testing" + + "github.com/qumo-dev/gomoqt/moqt" + "github.com/stretchr/testify/assert" +) + +func frame(b byte) *moqt.Frame { + f := moqt.NewFrame(1) + _, _ = f.Write([]byte{b}) + return f +} + +func TestTrackGroups(t *testing.T) { + tr := newTrack() + assert.False(t, tr.writeFrame(frame(0)), "no group open") + assert.True(t, tr.openGroup(5)) + assert.True(t, tr.writeFrame(frame(1))) + assert.False(t, tr.openGroup(5), "a sequence that does not advance is refused") + assert.False(t, tr.openGroup(4)) + assert.True(t, tr.openGroup(7), "sequences may skip, as the source's do") + + // A new subscriber starts at the newest group. + v := tr.next(0, 0, 0) + assert.True(t, v.found) + assert.Equal(t, moqt.GroupSequence(7), v.seq) + assert.False(t, v.done) + assert.Empty(t, v.frames) + + // One that served group 5 moves on to 7 from its start. + tr.writeFrame(frame(2)) + v = tr.next(5, 0, 0) + assert.Equal(t, moqt.GroupSequence(7), v.seq) + assert.Len(t, v.frames, 1) + + // Serving group 5 resumes where it left off, and it is done. + v = tr.next(0, 5, 1) + assert.Equal(t, moqt.GroupSequence(5), v.seq) + assert.True(t, v.done) + assert.Empty(t, v.frames) + + tr.endGroup() + v = tr.next(0, 7, 1) + assert.True(t, v.done) + assert.False(t, tr.writeFrame(frame(3)), "an ended group takes no frames") + + // Nothing after 7 yet. + v = tr.next(7, 0, 0) + assert.False(t, v.found) + assert.False(t, v.closed) +} + +func TestTrackRing(t *testing.T) { + tr := newTrack() + for seq := range moqt.GroupSequence(ringSize + 2) { + tr.openGroup(seq + 1) + } + // Groups 1 and 2 left the ring: a subscriber after 1 skips to 3. + v := tr.next(1, 0, 0) + assert.Equal(t, moqt.GroupSequence(3), v.seq) + + // A group being served that left the ring is ended where it is. + v = tr.next(0, 2, 4) + assert.True(t, v.found) + assert.True(t, v.done) + assert.Equal(t, moqt.GroupSequence(2), v.seq) + assert.Empty(t, v.frames) +} + +func TestTrackChangedAndClosed(t *testing.T) { + tr := newTrack() + v := tr.next(0, 0, 0) + assert.False(t, v.found) + select { + case <-v.changed: + t.Fatal("changed before any change") + default: + } + tr.openGroup(1) + select { + case <-v.changed: + default: + t.Fatal("not woken by a new group") + } + + tr.close() + v = tr.next(1, 0, 0) + assert.True(t, v.closed) + assert.False(t, v.found) + assert.False(t, tr.openGroup(2), "a closed track takes no groups") + tr.close() // idempotent +} diff --git a/internal/integration/abr_test.go b/internal/integration/abr_test.go new file mode 100644 index 00000000..af90956f --- /dev/null +++ b/internal/integration/abr_test.go @@ -0,0 +1,221 @@ +//go:build integration + +package integration + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "sync" + "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/cmaf" + "github.com/qumo-dev/qumo/internal/ffpub" + "github.com/qumo-dev/qumo/internal/ingest" +) + +// 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. +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") + ) + addr, srv := startAuthRelay(t, authOff, nil) + url := "https://" + addr + "/" + + // The source: ffmpeg over RTMP into an ingest that publishes through the + // relay. + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + ingestMux := moqt.NewTrackMux(0) + rtmpLn, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + rtmpAddr := rtmpLn.Addr().String() + require.NoError(t, rtmpLn.Close()) + go func() { _ = ingest.NewRTMPServer(ingest.RTMPConfig{Addr: rtmpAddr, TrackMux: ingestMux}).ListenAndServe(ctx) }() + require.Eventually(t, func() bool { + c, err := net.DialTimeout("tcp", rtmpAddr, 200*time.Millisecond) + if err == nil { + _ = c.Close() + } + return err == nil + }, 5*time.Second, 50*time.Millisecond) + dialOver(t, url, nil, ingestMux) + + pub := ffpub.New(ffpub.Config{ + URL: fmt.Sprintf("rtmp://%s%s", rtmpAddr, src), + Audio: true, GOP: 30, Width: 1280, Height: 720, Framerate: 30, + }) + require.NoError(t, pub.Start(ctx)) + t.Cleanup(func() { + cancel() // ffmpeg publishes until its context ends + _ = pub.Wait() + }) + require.Eventually(t, routed(srv, src), 10*time.Second, 50*time.Millisecond) + + // The transcoder. + tc := &abr.Transcoder{ + Prefix: "/live/", + 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"}, + }, + } + 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) + + // The viewer. + viewer := dialOver(t, url, nil, moqt.NewTrackMux(0)) + videoTracks := []string{"video", "video-360p", "video-240p"} + catalog := waitCatalog(t, viewer, dst, append(videoTracks, "audio")) + + byName := map[string]msf.Track{} + for _, tr := range catalog.Tracks { + byName[tr.Name] = tr + } + for _, name := range videoTracks { + tr := byName[name] + require.NotNil(t, tr.AltGroup, name) + assert.EqualValues(t, 1, *tr.AltGroup, name) + assert.NotEmpty(t, tr.InitRef, name) + assert.Contains(t, tr.Codec, "avc1.", name) + require.NotNil(t, tr.Height, name) + } + assert.EqualValues(t, 720, *byName["video"].Height) + assert.EqualValues(t, 360, *byName["video-360p"].Height) + assert.EqualValues(t, 640, *byName["video-360p"].Width) + assert.EqualValues(t, 240, *byName["video-240p"].Height) + assert.Nil(t, byName["audio"].AltGroup) + + // Read each video track's groups for a while. + groups := make([]map[moqt.GroupSequence]obsGroup, len(videoTracks)) + var wg sync.WaitGroup + readCtx, stop := context.WithTimeout(ctx, 5*time.Second) + defer stop() + for i, name := range videoTracks { + wg.Go(func() { groups[i] = readGroups(readCtx, t, viewer, dst, moqt.TrackName(name)) }) + } + wg.Wait() + + // Every group the source and a rendition both delivered whole starts at + // the same timestamp, with a keyframe, and holds the same frames. + for i, name := range videoTracks[1:] { + common := 0 + for seq, want := range groups[0] { + got, ok := groups[i+1][seq] + if !ok || !want.complete || !got.complete { + continue + } + common++ + require.NotEmpty(t, got.frames, "%s group %d", name, seq) + assert.True(t, got.frames[0].keyframe, "%s group %d does not open with a keyframe", name, seq) + require.Equal(t, len(want.frames), len(got.frames), "%s group %d frame count", name, seq) + for k := range want.frames { + assert.Equal(t, want.frames[k].timestamp, got.frames[k].timestamp, "%s group %d frame %d", name, seq, k) + } + } + assert.GreaterOrEqual(t, common, 2, "%s shares too few whole groups with the source", name) + } +} + +// 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 { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + tr, err := sess.Subscribe(ctx, path, msf.DefaultCatalogTrackName, nil) + require.NoError(t, err) + defer tr.Close() + f := moqt.NewFrame(0) + for { + gr, err := tr.AcceptGroup(ctx) + require.NoError(t, err, "catalog never listed %v", want) + if err := gr.ReadFrame(f); err != nil { + continue + } + c, err := msf.ParseCatalog(f.Body()) + require.NoError(t, err) + if listsTracks(c, want) { + return c + } + } +} + +// obsFrame is a video frame as a viewer received it. +type obsFrame struct { + timestamp uint64 + keyframe bool +} + +// obsGroup is a group as a viewer received it. +type obsGroup struct { + frames []obsFrame + complete bool // read to its end +} + +// readGroups reads track name's groups until ctx ends. +func readGroups(ctx context.Context, t *testing.T, sess *moqt.Session, path moqt.BroadcastPath, name moqt.TrackName) map[moqt.GroupSequence]obsGroup { + tr, err := sess.Subscribe(ctx, path, name, &moqt.SubscribeConfig{Ordered: true}) + if err != nil { + t.Errorf("subscribe %s: %v", name, err) + return nil + } + defer tr.Close() + out := map[moqt.GroupSequence]obsGroup{} + f := moqt.NewFrame(0) + for { + gr, err := tr.AcceptGroup(ctx) + if err != nil { + return out + } + var g obsGroup + for { + if err := gr.ReadFrame(f); err != nil { + g.complete = errors.Is(err, io.EOF) + break + } + ts, data, err := cmaf.DecodeLOC(f.Body()) + require.NoError(t, err) + g.frames = append(g.frames, obsFrame{timestamp: ts, keyframe: hasIDR(data)}) + } + out[gr.GroupSequence()] = g + } +} + +// hasIDR reports whether AVCC data (4-byte lengths) holds an IDR slice. +func hasIDR(data []byte) bool { + for len(data) >= 4 { + n := int(binary.BigEndian.Uint32(data)) + data = data[4:] + if n <= 0 || n > len(data) { + return false + } + if data[0]&0x1f == 5 { + return true + } + data = data[n:] + } + return false +} diff --git a/main.go b/main.go index 12685742..43cc9743 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "io/fs" "os" + "github.com/qumo-dev/qumo/internal/abr" "github.com/qumo-dev/qumo/internal/auth" "github.com/qumo-dev/qumo/internal/doctor" "github.com/qumo-dev/qumo/internal/funnel" @@ -21,6 +22,7 @@ import ( var ( // overridable command handlers for easier unit-testing + runABR = abr.Run runFunnel = funnel.Run runDNS = geodns.Run runHLS = hls.Run @@ -87,6 +89,8 @@ func run(args []string) int { var err error switch cmd { + case "abr": + err = runABR(cmdArgs) case "auth": err = runAuth(cmdArgs) case "dns": @@ -128,6 +132,7 @@ func printUsage() { fmt.Fprintf(os.Stderr, "Usage: qumo (%s)\n", version.Short()) fmt.Fprintln(os.Stderr, "") fmt.Fprintln(os.Stderr, "Commands:") + fmt.Fprintln(os.Stderr, " abr Transcode broadcasts into ABR renditions (ffmpeg) and republish them") fmt.Fprintln(os.Stderr, " auth Set up the credentials a relay verifies (keygen, token)") fmt.Fprintln(os.Stderr, " dns Answer one DNS name with the region nearest the client (authoritative GeoDNS)") fmt.Fprintln(os.Stderr, " funnel Funnel many HTTP senders into one MoQT track (announce/record over POST)") From df0545efb43d06a66f60f419a3c5f1f5d0ec4226 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 12:07:20 +0000 Subject: [PATCH 02/24] style(abr): gofmt the integration test Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPWMJL7PH3rPhK5UTGavaB --- internal/integration/abr_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/integration/abr_test.go b/internal/integration/abr_test.go index af90956f..38327c74 100644 --- a/internal/integration/abr_test.go +++ b/internal/integration/abr_test.go @@ -50,7 +50,9 @@ func TestABR_RenditionsBesideSource(t *testing.T) { require.NoError(t, err) rtmpAddr := rtmpLn.Addr().String() require.NoError(t, rtmpLn.Close()) - go func() { _ = ingest.NewRTMPServer(ingest.RTMPConfig{Addr: rtmpAddr, TrackMux: ingestMux}).ListenAndServe(ctx) }() + go func() { + _ = ingest.NewRTMPServer(ingest.RTMPConfig{Addr: rtmpAddr, TrackMux: ingestMux}).ListenAndServe(ctx) + }() require.Eventually(t, func() bool { c, err := net.DialTimeout("tcp", rtmpAddr, 200*time.Millisecond) if err == nil { From ae221e70f7daf22cf79ad079dc961fa96da30e31 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:09:12 +0000 Subject: [PATCH 03/24] feat(playground): adaptive bitrate playback of ABR broadcasts The playground viewer plays an MSF broadcast whose video tracks share an alternate group (as `qumo abr` publishes) adaptively, switching between renditions at group boundaries, and lets the user pick one by hand. - Renditions come from the catalog: the first video track and the video tracks in its altGroup, tallest first, each with its decoder config. - A SwitchingTrack merges the renditions' subscriptions into the one track the frame reader consumes. Renditions number their groups alike, so the new rendition takes over at its first group past those handed out; when it joins at a group already played, the next group is reserved for it so the old rendition cannot race it. A step up keeps the old subscription until it has sent every group before the cutoff (make before break); a step down ends it at once to free the link. - The decoder is configured for each group's rendition at its keyframe. - An AbrController steps down when frames fall behind their media time (or a group is lost), to the best rendition the receive rate since they fell behind carries with headroom; it steps up one rendition after a calm stretch, doubling the wait whenever a step up does not hold, and not past what a subscription's opening burst measured. - The subscribe board gains an Auto/rendition picker and ABR stats in the overlay. fix(relay): a subscriber stopping one group keeps its subscription deliverGroup treated any WriteFrame failure as the subscriber leaving and ended its egress, so a subscriber that stopped one group's stream (STOP_SENDING), as a player gives up a late group or one of a rendition it is leaving, lost the whole subscription. A failure while the subscription is still open now abandons only that group. Verified in headless Chromium against playground + rtmp + abr: playback climbs 360p -> 720p -> 1080p; a 3 Mbit/s limit on the relay-to-browser link drops it to 360p within ~2.5 s, and it climbs back once lifted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPWMJL7PH3rPhK5UTGavaB --- internal/integration/relay_subscribe_test.go | 57 ++++ internal/relay/handler.go | 17 +- playground/dist/assets/index-B2Q5waeK.css | 1 + playground/dist/assets/index-BmLZ_U0I.css | 1 - .../{index-BjGBUIfN.js => index-DYHhcMqy.js} | 46 +-- playground/dist/index.html | 4 +- playground/src/App.css | 10 + playground/src/player/abr/controller.ts | 281 ++++++++++++++++++ playground/src/player/abr/controller_test.ts | 155 ++++++++++ playground/src/player/abr/switching_track.ts | 277 +++++++++++++++++ .../src/player/abr/switching_track_test.ts | 238 +++++++++++++++ playground/src/player/catalog.ts | 79 ++++- playground/src/player/catalog_test.ts | 95 +++++- playground/src/player/viewer.ts | 182 ++++++++++-- playground/src/subscribe/SubscribeBoard.tsx | 49 ++- 15 files changed, 1435 insertions(+), 57 deletions(-) create mode 100644 playground/dist/assets/index-B2Q5waeK.css delete mode 100644 playground/dist/assets/index-BmLZ_U0I.css rename playground/dist/assets/{index-BjGBUIfN.js => index-DYHhcMqy.js} (78%) create mode 100644 playground/src/player/abr/controller.ts create mode 100644 playground/src/player/abr/controller_test.ts create mode 100644 playground/src/player/abr/switching_track.ts create mode 100644 playground/src/player/abr/switching_track_test.ts diff --git a/internal/integration/relay_subscribe_test.go b/internal/integration/relay_subscribe_test.go index 6f3a317c..d83c968b 100644 --- a/internal/integration/relay_subscribe_test.go +++ b/internal/integration/relay_subscribe_test.go @@ -254,3 +254,60 @@ func isSubscribeRefused(err error, code moqt.SubscribeErrorCode) bool { } return err != nil && strings.HasSuffix(err.Error(), fmt.Sprintf("stream canceled with error code %d", code)) } + +// A subscriber that stops one group's stream, as a player gives up a late +// group or one of a rendition it is leaving, keeps its subscription: the relay +// abandons that group alone and goes on delivering the next ones. +func TestRelay_StoppedGroupKeepsSubscription(t *testing.T) { + const path = moqt.BroadcastPath("/stop/group") + addr, srv := startAuthRelay(t, authOff, nil) + url := "https://" + addr + "/" + + // Groups of 10 frames 20 ms apart, as video sends a group over its GOP: + // the relay is still writing a group when the subscriber stops it. + pubCtx, stopPub := context.WithCancel(context.Background()) + t.Cleanup(stopPub) + mux := moqt.NewTrackMux(0) + mux.PublishFunc(pubCtx, path, func(tw *moqt.TrackWriter) { + defer tw.Close() + for { + gw, err := tw.OpenGroup(pubCtx) + if err != nil { + return + } + for range 10 { + fr := moqt.NewFrame(8) + _, _ = fr.Write([]byte("frame")) + if gw.WriteFrame(fr) != nil { + break + } + select { + case <-tw.Context().Done(): + _ = gw.Close() + return + case <-time.After(20 * time.Millisecond): + } + } + _ = gw.Close() + } + }) + dialOver(t, url, nil, mux) + require.Eventually(t, routed(srv, path), 3*time.Second, 25*time.Millisecond) + + sess := dialOver(t, url, nil, moqt.NewTrackMux(0)) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + tr, err := sess.Subscribe(ctx, path, testTrack, nil) + require.NoError(t, err) + defer tr.Close() + + first, err := tr.AcceptGroup(ctx) + require.NoError(t, err) + first.CancelRead(moqt.ExpiredGroupErrorCode) + + for range 3 { + gr, err := tr.AcceptGroup(ctx) + require.NoError(t, err, "the subscription ended with the stopped group") + assert.Greater(t, gr.GroupSequence(), first.GroupSequence()) + } +} diff --git a/internal/relay/handler.go b/internal/relay/handler.go index 98c5ed48..72e3f969 100644 --- a/internal/relay/handler.go +++ b/internal/relay/handler.go @@ -794,7 +794,9 @@ func (d *trackDistributor) egress(tw *moqt.TrackWriter, fromStart bool) { EndGroup: seq, ErrorCode: moqt.SubscribeErrorCodeTimeout, }) - case groupSent: + case groupSent, groupStopped: + // A stopped group was the subscriber's own choice: it is + // not reported back to it as dropped. drops.sent(seq) drops.flush() } @@ -876,6 +878,11 @@ const ( // deliveryStopped means the subscribe stream closed, the subscriber left, // or the track ended; egress must return. deliveryStopped + // groupStopped means the subscriber stopped the group's stream part-way + // (STOP_SENDING), as a player gives up a group it no longer wants: a late + // one, or one of a rendition it is leaving. Only that group is abandoned; + // egress continues with the next. + groupStopped ) // deliverGroup writes one group (cache) to the subscriber's track writer and @@ -974,6 +981,14 @@ func (d *trackDistributor) deliverGroup(ctx context.Context, tw *moqt.TrackWrite // though the group is being abandoned. The failing frame is excluded. d.egressCounter.Add(float64(egressTotal)) d.sampler.addEgress(egressTotal) + if ctx.Err() == nil { + // The subscription is still open, so it was this group's + // stream that failed: the subscriber stopped it. A session + // that died instead fails the next group's open, which ends + // egress then. + gw.CancelWrite(moqt.InternalGroupErrorCode) + return groupStopped + } return deliveryStopped } d.stages.egressFrame(tWrite) diff --git a/playground/dist/assets/index-B2Q5waeK.css b/playground/dist/assets/index-B2Q5waeK.css new file mode 100644 index 00000000..e566216b --- /dev/null +++ b/playground/dist/assets/index-B2Q5waeK.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}.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-BmLZ_U0I.css b/playground/dist/assets/index-BmLZ_U0I.css deleted file mode 100644 index 783e8a34..00000000 --- a/playground/dist/assets/index-BmLZ_U0I.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}.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-BjGBUIfN.js b/playground/dist/assets/index-DYHhcMqy.js similarity index 78% rename from playground/dist/assets/index-BjGBUIfN.js rename to playground/dist/assets/index-DYHhcMqy.js index f04c1773..169553fb 100644 --- a/playground/dist/assets/index-BjGBUIfN.js +++ b/playground/dist/assets/index-DYHhcMqy.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(`
`);function hM(e){let[t,n]=b(!1),r=()=>St(e.scenario,e.path(),e.host),i=()=>Ct(e.scenario,e.path(),e.host),a=()=>{let e=i();e&&navigator.clipboard?.writeText(e).then(()=>{n(!0),setTimeout(()=>n(!1),1200)}).catch(()=>{})};return P(F,{get when(){return r()},get children(){var e=mM(),n=e.firstChild,o=n.firstChild,s=o.firstChild.nextSibling,c=o.nextSibling,l=n.nextSibling.firstChild;return L(s,r),c.$$click=a,L(c,()=>t()?`Copied`:`Copy`),L(l,i),e}})}Ue([`click`]);var gM=I(`