engine

package
v0.36.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package engine publishes encoded media to the relay using the same publisher protocol the browser broadcaster speaks — byte for byte, via the shared gawk-server/wire package. It was the Go Linux broadcaster's engine (R14, docs/19); since that app's removal (R56 LX9, docs/58 D15) its one consumer is gawk-pubsim, which feeds it a committed fixture.

The surface deliberately mirrors the TypeScript BroadcastSessionLike (start/stop) and BroadcastCallbacks (onBroadcastId/onStats/onError/onEnded) from gawk-app/src/transport/broadcaster.ts. Same idea, same names, other language: a second broadcaster only stays survivable if the two remain legible to each other.

No package globals, no os.Exit, no direct stdio anywhere in this package: the shells that consume it own all of that.

Index

Constants

View Source
const (
	// AudioCodec is the WebCodecs codec string the viewer configures from.
	AudioCodec = "opus"
	// AudioSampleRate and AudioChannels are forced in the capture caps rather
	// than accepted from the source: a 5.1 monitor's 6-channel Opus would be
	// channel-mapping family 1 (multistream), which WebCodecs cannot decode
	// without an OpusHead description — and docs/20 sends an empty description
	// by design.
	AudioSampleRate = 48000
	AudioChannels   = 2
	// AudioBitrateBps matches the browser lane's AUDIO_BITRATE_BPS.
	AudioBitrateBps = 128_000
	// AudioFrameMs is the Opus frame duration. 20 ms ≈ 320 B at 128 kbps,
	// which is what makes "one Opus packet per datagram, never chunked" true.
	AudioFrameMs = 20
	// AudioConfigResendMs mirrors the browser's AUDIO_CONFIG_RESEND_MS: audio
	// has no keyframe to anchor config re-emits to, so the config rides the
	// packet flow at 1 Hz (docs/20 Decision 5). 50 packets/s is already a
	// scheduler; there is no separate timer.
	AudioConfigResendMs = 1000
)

The audio format is a set of constants, not settings (docs/28 Decision 3, following docs/20's "bitrate is a named constant, not a setting, in v1"). They mirror gawk-app/src/media/audio-lane.ts so both broadcasters describe the same stream to the same viewer.

View Source
const (
	// TimeSyncInterval is how often we ping. It mirrors the TS constant and
	// must stay a constant, not a flag: the relay rate-caps TimeSync replies
	// at 5/s per session (also a constant, transport/server.go), and a knob
	// here would let a user silently configure their own measurements into
	// being dropped.
	TimeSyncInterval = 2 * time.Second
	// TimeSyncSampleWindow is the rolling sample count (TS: TIME_SYNC_SAMPLE_WINDOW).
	TimeSyncSampleWindow = 8
	// ClockMappingInterval is how often the broadcaster re-publishes its
	// ClockMapping (TS: CLOCK_MAPPING_INTERVAL_MS).
	ClockMappingInterval = 5 * time.Second
)

The TimeSync client, mirroring gawk-app/src/transport/time-sync.ts. Both broadcasters run one over their existing session: ping the relay, and from each echoed reply take an NTP-style sample mapping this machine's clock onto the relay's monotonic clock:

rtt      = t1 − t0
offsetUs = serverTimeUs − (t0 + rtt/2)      (relayUs ≈ localUs + offsetUs)

The lowest-RTT sample in a rolling window wins: queuing delay is what makes the out/back asymmetry (the one unmeasurable error) large, so the fastest exchange is the most symmetric one, and that sample's rtt/2 bounds the error.

View Source
const DefaultNickname = "gawk-broadcast"

DefaultNickname is the roster name a native broadcaster joins with when the profile sets none.

View Source
const DefaultOrigin = "gawk-broadcast://native"

DefaultOrigin is the Origin header the native broadcaster sends on its CONNECT dial.

The browser sends the frontend's origin automatically and cannot change it (JS cannot set request headers — the same limitation that puts the publish secret in a query param). A native client is the mirror image: it can set any header, but webtransport-go sends none by default. A relay configured with -allowed-origins / GAWK_ALLOWED_ORIGINS then rejects the native broadcaster, because an empty Origin matches nothing in the whitelist — the field bug this exists to fix.

So we send a fixed, self-identifying origin that the relay operator adds to GAWK_ALLOWED_ORIGINS exactly as they already add the frontend's. The custom scheme makes it unmistakable in the relay's access and "origin rejected" logs. Override via Config.Origin (-origin / GAWK_ORIGIN) to reuse an already-allowed origin instead of adding a whitelist entry.

Variables

View Source
var ErrCaptureFormat = errors.New("screen capture format negotiation failed")

ErrCaptureFormat is returned when every live pipeline died inside pipewiresrc — the compositor's screencast stream and the GStreamer chain could not agree on a frame format, so no frame ever reached an encoder. Distinct from ErrNoHardwareEncoder for the same reason ErrNoLaunchBinary is: reporting it as "no working hardware encoder" would send the user chasing GPU drivers over a portal/compositor negotiation problem.

View Source
var ErrNoHardwareEncoder = errors.New("no working hardware H.264 encoder found")

ErrNoHardwareEncoder is returned when no candidate in the cascade actually encodes on this machine (docs/19 Decision 4). It is deliberately terminal: hardware encode is the entire reason this app exists, and the browser broadcaster already covers software encode on Linux, so the engine refuses and points there instead of quietly degrading.

Functions

func HasBSlices

func HasBSlices(au []byte) bool

HasBSlices reports whether an access unit contains any B slice.

This exists to be asserted, not consulted: no-B-frames is a hard encoder invariant (docs/19 Decision 13), because the entire viewer pipeline assumes decode order == presentation order — frameId ordering, the reorder buffer, and every piece of live-edge and pacing math. A B-frame would not fail loudly; it would produce subtly wrong playback. So the cascade pins b-frames=0 per candidate, and the fixture test proves the assertion can actually detect a violation.

func HasIDR

func HasIDR(au []byte) bool

HasIDR reports whether an access unit contains an IDR slice — the engine's definition of a keyframe (docs/19 Decision 7), and what routes it onto a reliable uni stream instead of datagrams.

func ParseCodecString

func ParseCodecString(au []byte) (string, bool)

ParseCodecString derives the WebCodecs codec string ("avc1.42E02A") from the first SPS in an Annex-B access unit.

Parsed from the bitstream, never assumed (docs/19 Decision 8): the encoder may pick a different level than we asked for — level is a function of resolution, framerate and bitrate, and hardware encoders round it up — and on the Annex-B path this string is the *only* thing telling the viewer's decoder what it is about to get. The viewer's extradata-derived correction runs only for AVCC, which this path deliberately never produces.

The three bytes are profile_idc, constraint_flags+reserved, level_idc, and they sit immediately after the 1-byte NAL header, before any position where an emulation-prevention byte can legally occur (an EPB requires two preceding zero bytes, and the earliest it can appear is the fourth byte of the RBSP). So reading them raw — without unescaping — is safe here, and only here; anything deeper into the SPS would need real EPB removal.

func PublishURL

func PublishURL(relayURL, broadcastID, secret, resumeToken string) (string, error)

PublishURL builds the CONNECT URL for a broadcast.

The secret travels as a query parameter, not a header. That is not a shortcut: it is how the secret already travels for the browser broadcaster, because the WebTransport JS API cannot set request headers (R2, docs/07), and the relay reads r.URL.Query().Get("secret"). A native client could send a header, but then the two broadcasters would authenticate differently and the relay would need two paths.

func RoomNewURL

func RoomNewURL(relayURL, broadcastID, resumeTokenHex, label, createSecret string) (string, error)

RoomNewURL builds the CONNECT URL that mints a dynamic room from a live broadcast (docs/44 §4.4 step 1): the broadcast ID and its resume token (hex, the relay's query-param encoding) are the proof of ownership; the label names the tile; the create secret is the fleet's -room-create-secret when it has one.

func RoomURL

func RoomURL(relayURL, code, attachSecret, creatorToken string) (string, error)

RoomURL builds the CONNECT URL that joins a room (docs/44 §4.2): the code or slug as the path, the attach secret and creator token as query params.

The attach param is only set when non-empty: the relay verifies it whenever it is *present*, so an empty one would turn "no secret given" into "wrong secret" (403) on every static room that has one.

Types

type AccessUnit

type AccessUnit struct {
	// Data is the access unit's Annex-B bytes, valid until the next receive.
	Data []byte
	// Keyframe is true when the AU contains an IDR slice (NAL type 5). Thanks
	// to h264parse config-interval=-1 such an AU also carries its SPS/PPS
	// in-band, which is what makes it self-sufficient for the relay's
	// cached-keyframe priming of late joiners.
	Keyframe bool
	// TimestampUs is the AU's presentation time on the engine's Clock — the
	// same clock TimeSync reads (Decision 6). Since 2026-07-17 it is the PES
	// PTS mapped onto that clock by ptsAnchor (internal/gst/pts.go), so stamps
	// carry the capture cadence instead of the pipe's delivery pattern; it
	// falls back to the pipe-arrival time only when the container carried no
	// PTS. See docs/19 deviation 11.
	TimestampUs uint64
	// PTSUs is the raw PES presentation timestamp, if the container carried
	// one. Carried for diagnostics only — the value actually shipped is the
	// clock-anchored TimestampUs above (ptsAnchor consumes the PTS directly);
	// nothing downstream reads this field.
	PTSUs  uint64
	HasPTS bool
	// EncoderRestarted marks the first access unit produced by a rebuilt
	// capture pipeline — a source that survived its encoder dying mid-session
	// (internal/gst's mid-session restart) rather than ending the broadcast.
	//
	// It exists because the DecoderConfig is derived once and then cached for
	// the whole session, which is correct while one child owns the encode and
	// wrong across a rebuild: the new pipeline may have landed on a different
	// ladder rung or a different encoder, and on this Annex-B path the codec
	// string is the only thing telling a viewer's decoder what it is about to
	// get. Sources that cannot rebuild never set it, and for them nothing
	// changes.
	EncoderRestarted bool
}

AccessUnit is one encoded frame, already compressed, as it comes off the child's pipe.

The engine never sees a pixel: by the time anything reaches this struct it is H.264, which is why the whole app can be a byte pump. Data is raw Annex-B, and stays that way — the viewer's isAnnexB start-code sniff routes it into the Annex-B branch, so the engine never builds an avcC record and the DecoderConfig extradata is empty. That designs out the nastiest interop risk in the whole idea (docs/19).

type AppAudioSource

type AppAudioSource interface {
	// AudioApp is the captured application's binary
	// (`application.process.binary`), or "" for system audio.
	AudioApp() string
}

AppAudioSource is implemented by sources that can capture one application's audio rather than the whole system's (R35, docs/39 D3). Stats-only, and optional exactly like GeometrySource: a source with no notion of app audio simply reports none, which reads as "system audio" everywhere.

type AudioFormat

type AudioFormat struct {
	// Codec is the WebCodecs codec string ("opus").
	Codec string
	// SampleRate in Hz (48000) and Channels (2), as forced in the caps.
	SampleRate int
	Channels   int
	// BitrateBps is the encoder's target. Reported for stats only; it is not
	// on the wire (AudioConfig carries codec, rate, channels, description).
	BitrateBps int
	// Source names the winning cascade candidate, for stats and the GUI.
	Source string
}

AudioFormat describes the stream the lane is producing. It is what the AudioConfig datagram is built from, so it must describe the bitstream rather than the request — see the TOC check in sender.sendAudio (Decision 10).

func DefaultAudioFormat

func DefaultAudioFormat(source string) AudioFormat

DefaultAudioFormat is the format Decision 3's caps filter forces.

type AudioPacket

type AudioPacket struct {
	// Data is one Opus packet, valid until the next receive.
	Data []byte
	// TimestampUs is the packet's presentation time on the engine's Clock —
	// the same clock video access units are stamped on, mapped by the *same*
	// ptsAnchor instance (Decision 5). That shared anchor is the whole A/V
	// sync design: one PTS timeline through one affine function makes the
	// relative skew zero by construction. Giving audio its own anchor would
	// look tidier and would silently reintroduce a constant lip-sync bias the
	// viewer can neither detect nor remove.
	TimestampUs uint64
}

AudioPacket is one encoded Opus packet, already compressed, as it comes off the child's pipe — the audio twin of AccessUnit, and just as opaque.

type AudioSource

type AudioSource interface {
	// Audio returns the packet channel. It closes when capture ends, like the
	// access-unit channel. Nil when this source has no audio to give.
	Audio() <-chan AudioPacket
	// AudioFormat describes what Audio() will carry. ok is false when no
	// source passed the pre-flight trial, which is the "publish video and say
	// so" path, not an error.
	AudioFormat() (AudioFormat, bool)
}

AudioSource is implemented by media sources that carry audio (Decision 8).

It is deliberately a *separate, optional* interface rather than three more methods on MediaSource: widening MediaSource would force audio semantics onto every implementation — the test fakes and internal/pubsim — that has nothing to say about it, and would erode video-only as a first-class shape. That shape is not merely tidy: R20 tier-1 continuously asserts the no-audio path, and that assertion is only meaningful while a video-only source is a real thing rather than an audio source returning nil.

The engine type-asserts; a source that does not implement this is video-only.

type AudioState

type AudioState string

AudioState mirrors the browser's BroadcastStats.audioState vocabulary (gawk-app/src/transport/broadcaster.ts) so a native diagnostics dump and a browser one mean the same thing side by side. The native lane can reach four of its six values; 'no-track' and 'unsupported' are browser-picker concepts with no analogue here (docs/28 Decision 1: the share picker stays video-only).

const (
	// AudioOff: the broadcaster asked for silence (-audio=false).
	AudioOff AudioState = "off"
	// AudioUnavailable: audio was wanted and no source could produce it.
	// Never an error — the broadcast publishes video and says so (Decision 6).
	AudioUnavailable AudioState = "unavailable"
	// AudioActive: packets are flowing.
	AudioActive AudioState = "active"
	// AudioError: the lane produced something we refuse to ship — today only
	// a bitstream that disagrees with the advertised config (Decision 10).
	AudioError AudioState = "error"
)

type AudioTarget

type AudioTarget struct {
	Mode AudioTargetMode
	// Binary is the application's `application.process.binary` (AD2), set only
	// for AudioTargetApp.
	Binary string
}

AudioTarget is the answer to "whose audio?".

type AudioTargetMode

type AudioTargetMode string

AudioTargetMode is what the broadcaster chose in the whose-audio step (R35, docs/39 D5). It exists in the engine rather than in the capture package so both shells can express a choice without importing GStreamer.

const (
	// AudioTargetSystem is today's behavior: the whole machine's output.
	// It is the default for every path that does not ask, which is what keeps
	// the whole-screen flow byte-identical to pre-R35.
	AudioTargetSystem AudioTargetMode = "system"
	// AudioTargetApp captures one application's streams and nothing else.
	AudioTargetApp AudioTargetMode = "app"
	// AudioTargetNone is silence, chosen deliberately.
	AudioTargetNone AudioTargetMode = "none"
)

type Callbacks

type Callbacks struct {
	// OnBroadcastID fires once, when the relay announces the code.
	OnBroadcastID func(id string)
	// OnResumeToken fires when the relay hands over the broadcast's resume
	// token (hex — the relay's own query-param encoding). The shell must
	// persist it beside the broadcast ID: without it an R17 relay refuses
	// the reclaim. Pre-R17 relays never send one.
	OnResumeToken func(token string)
	// OnStats fires on the stats cadence while live.
	OnStats func(Stats)
	// OnError reports a session-fatal problem. Always followed by OnEnded.
	OnError func(error)
	// OnEnded fires exactly once per successful Start, when the session is
	// over — whether by Stop, an unrecoverable relay loss, or child death.
	//
	// A *recoverable* relay loss does not reach here: auto-resume reclaims the
	// broadcast and the session continues (OnResuming → OnResumed).
	OnEnded func()
	// OnResuming fires before each reclaim attempt after the transport
	// dropped. attempt counts from 1; lastErr is why the previous attempt
	// failed, nil on the first. Capture and encode are still running — this is
	// a transport-only interruption, and the shell should say so rather than
	// present the broadcast as ended.
	OnResuming func(attempt int, lastErr error)
	// OnResumed fires when a reclaim succeeds and frames are flowing again.
	OnResumed func()
	// OnEncoderChosen fires once the cascade settles on a candidate
	// (Decision 4: the chosen encoder is reported at startup and in stats).
	OnEncoderChosen func(encoder string)
	// OnTelemetryHello fires once per relay session with this session's
	// telemetry identity (R28, wire 0x0D): the ingest token, the obfuscated
	// broadcast key, and whether the fleet collects at all. Absent on a relay
	// predating R28 or with telemetry off — which is exactly the same thing
	// as a shell that installs no callback: nothing is collected or sent.
	OnTelemetryHello func(hello wire.TelemetryHello)
	// OnTelemetryEndpoint fires when the relay advertises its fleet's
	// telemetry ingest URL (R37, wire 0x12, docs/40 §4.10). The URL has
	// already passed wire validation (absolute https, length-capped). Its
	// precedence — an advertised URL wins over the configured one, and an
	// explicit "off" still means off — is the shell's business, exactly like
	// the hello above. A relay that advertises nothing (every pre-R37 relay)
	// never fires it.
	OnTelemetryEndpoint func(ingestURL string)
	// OnViewerCount fires whenever the relay pushes the live "N watching"
	// number (R18, docs/23 — the SubscriberCount R14 deferred as Decision
	// 18; the wire message exists now, TypeViewerCount 0x0B). The count is
	// fleet-global in cluster mode; ~1 s cadence, change-driven. The "first
	// viewer joined" moment is the 0 → ≥1 transition, derived by the shell.
	OnViewerCount func(count uint32)

	// OnRoomCreated fires once per NewRoom/Config.RoomNew, when the relay
	// has minted the room: the display code and the creator token (hex —
	// the grant "Open room view" hands to the SPA, docs/44 §4.8).
	OnRoomCreated func(code, creatorTokenHex string)
	// OnRoomState fires on every full snapshot (after each connect and
	// resync). Replace, never merge.
	OnRoomState func(state wire.RoomState)
	// OnRoomEvent fires per delta, CommandRejected included (which also
	// reaches OnRoomError as a *RoomRejectError).
	OnRoomEvent func(event wire.RoomEvent)
	// OnRoomEnded fires when the room is over (close code 4007, or the room
	// ended before the join completed). reason is the RoomEndReason* from
	// the preceding RoomEnding event, 0 when there was none. The room
	// session is not reconnected; the broadcast is untouched.
	OnRoomEnded func(reason uint8)
	// OnRoomError reports a room failure: a *RoomError for a dial the relay
	// refused for good or a protocol failure (the room session is then
	// gone), or a *RoomRejectError for one refused command (the session
	// stays up).
	OnRoomError func(error)
}

Callbacks mirror the browser's BroadcastCallbacks. All are optional; all are invoked from engine goroutines, so a GUI shell must marshal them onto its own loop.

type Clock

type Clock interface {
	// NowUs returns microseconds since an arbitrary, fixed origin. Only
	// differences are meaningful.
	NowUs() uint64
}

Clock is the engine's single time source. Everything that produces a timestamp — frame arrival stamps and the TimeSync t0 alike — reads it.

That sharing is load-bearing, not tidiness (docs/19 Decision 6). The broadcaster publishes a ClockMapping saying

relayClockUs = frameTimestampUs + offsetUs

where offsetUs comes from TimeSync samples taken against the relay's clock. If frames were stamped on a different timeline than the pings, that equation would relate two unrelated clocks: every viewer's absolute capture→render latency would be wrong, while still looking entirely plausible. There is no test the viewer could run to notice. So the engine takes one clock and threads it everywhere, and TestOneClockFeedsFramesAndTimeSync guards it.

Monotonic on purpose, mirroring the relay's own processStart/relayNowUs and the browser broadcaster's performance.now(): a wall-clock step mid-session (NTP, a laptop waking) must not jump the mapping.

func NewClock

func NewClock() Clock

NewClock returns a Clock anchored at the moment of the call. time.Since reads the monotonic reading embedded in the time.Time, so it is immune to wall-clock adjustments.

type Config

type Config struct {
	// RelayURL is the relay's https:// origin.
	RelayURL string
	// BroadcastID empty mints a new broadcast; non-empty reclaims that ID
	// (the Resume path).
	BroadcastID string
	// PublishSecret is R2's pre-shared publish secret, sent as a query param.
	PublishSecret string
	// ResumeToken is the hex token the relay minted at first publish (R17
	// W2, wire 0x09), sent as the `resume` query param. An R17 relay refuses
	// every /publish/{id} claim without it, so Resume needs the token
	// persisted beside the broadcast ID. Ignored when BroadcastID is empty.
	ResumeToken string
	// Origin is the Origin header sent on the CONNECT dial. Empty uses
	// DefaultOrigin. A relay configured with -allowed-origins must whitelist
	// whichever value is sent.
	Origin string
	// Insecure skips TLS verification (the dev cert only).
	Insecure bool
	// Media is the capture/encode configuration.
	Media MediaConfig

	// Room (R42, docs/44 §4.8) names a room to attach the broadcast to on
	// publish: a 6-character dynamic code or a static slug. Empty means no
	// room. Ignored when RoomNew is set.
	Room string
	// RoomNew mints a new dynamic room from this broadcast once its ID and
	// resume token are known, and joins it as creator (OnRoomCreated).
	RoomNew bool
	// RoomAttachSecret is a static room's attach key, presented on the join
	// dial. Dynamic rooms need none.
	RoomAttachSecret string
	// RoomCreateSecret is the fleet's -room-create-secret, presented on a
	// mint when the relay requires one.
	RoomCreateSecret string
	// Nickname is the one name the broadcaster carries in a room — the
	// roster entry and the tile label alike (the web broadcaster page's
	// rule; docs/44 §4.9). Empty uses DefaultNickname. SetNickname changes
	// it while live.
	Nickname string
}

Config is a session's fixed configuration. Everything here is decided before Start and never changes during a session (Decision 9: no ladder, no mid-session rung changes in v1).

type DialFunc

type DialFunc func(ctx context.Context, rawURL, origin string, insecure bool) (sess RelaySession, status int, err error)

DialFunc dials the relay. Injectable so tests can supply a fake session without a QUIC stack; the default is dialRelay below.

It returns the HTTP status separately from the error because that is the whole point of Decision 10: webtransport-go surfaces the status the browser cannot see. Status is 0 when the failure never reached HTTP.

type FakeClock

type FakeClock struct{ Us uint64 }

FakeClock is a Clock tests advance by hand. The engine's cadences (ping interval, mapping interval) are time-driven, so every test that asserts one drives this instead of sleeping.

func (*FakeClock) Advance

func (c *FakeClock) Advance(d time.Duration)

Advance moves the clock forward by d.

func (*FakeClock) NowUs

func (c *FakeClock) NowUs() uint64

type GeometrySource

type GeometrySource interface {
	// EncodeSize is the width and height actually asked of the encoder — the
	// configured box fitted to the source's aspect. ok is false before the
	// source knows (i.e. before the portal has answered).
	EncodeSize() (width, height int, ok bool)
}

GeometrySource is implemented by media sources whose encode dimensions are not simply the configured ones (R35, docs/39 D2).

Optional for the same reason AudioSource is: the fakes and internal/pubsim have nothing to say about geometry, and widening MediaSource would make them answer a question they cannot. A source that does not implement it reports the configured rung, which is what every source did before R35.

type MediaConfig

type MediaConfig struct {
	Width, Height int
	Fps           int
	BitrateBps    int
	// GOPMs is the keyframe interval in milliseconds (item 11's
	// keyframeIntervalMs: 500 ms so a lost frame self-heals in ≤0.5 s).
	GOPMs int
	// Encoder, when set, forces one cascade candidate and skips probing.
	Encoder string

	// DisableAudio turns the system-audio lane off entirely (R25, docs/28
	// Decision 11). The zero value means *on*, deliberately: a broadcaster who
	// wanted silence would not have installed a screen-sharing app, and
	// Decision 6 makes "on" safe on machines where audio cannot work. This
	// flag is for the broadcaster who genuinely wants silence, not a
	// workaround for breakage — breakage needs no user involvement.
	DisableAudio bool
	// AudioDevice pins one capture device by name (pulsesrc's device
	// property). Empty probes the cascade; set, it is the only candidate
	// tried — the same rule as Encoder, and for the same reason: silently
	// capturing something other than what the user named would be worse than
	// failing.
	AudioDevice string
}

MediaConfig is the session's fixed rung (Decision 9: no ladder, no auto-fallback, no mid-session changes in v1).

The defaults are 1080p60 with a 500 ms GOP. 60 fps tracks R13's framerate-first rule rather than build-order item 11's 30 fps fan-out default: item 11 capped at 30 because a browser broadcaster might be software-encoding, and this engine is hardware-encode by construction (Decision 4) — so 1080p60 is coherent here rather than aspirational.

R4's FallbackController is deliberately not ported. Its trigger is encodeQueueSize growth, and R4's own hardware finding (2026-07-13) was that hardware encoders drain frames without that signal ever firing — porting it would carry the complexity and faithfully reproduce the under-fire.

func DefaultMediaConfig

func DefaultMediaConfig() MediaConfig

DefaultMediaConfig is the shipped rung.

16 Mbps: 1080p60 game content over H.264 with a 500 ms GOP spends a third of its budget on keyframes, and the field test (2026-07-17) put the default-8 picture at "garbage" while 24 was clean — 16 is the comfortable middle that still leaves 15 viewers at ~240 Mbps on the homelab's 1 Gbps uplink. Local-streaming peers land in the same range (Sunshine defaults to 20). The GUI and -bitrate override it per broadcast.

type MediaSource

type MediaSource interface {
	// Start begins capture and returns the AU channel. The channel closes
	// when capture ends for any reason; Err then says why.
	Start(ctx context.Context) (<-chan AccessUnit, error)
	// Stop ends capture and reaps the child.
	Stop() error
	// Encoder names the cascade candidate in use, or "" before Start.
	Encoder() string
	// CapturePath says how frames cross the capture boundary ("zero-copy",
	// "system-memory"), or "" before capture starts. Stats-only — nothing
	// branches on it; it exists so a broadcaster can see which rung of the
	// capture ladder actually won without reading child logs.
	CapturePath() string
	// Err returns the failure that ended capture, or nil for a clean stop.
	Err() error
}

MediaSource produces access units. It is the seam between "bytes on a pipe" and "frames on the wire": everything above it (the session, the send policy) is testable without a GPU, a portal or a child process.

type MediaSourceFactory

type MediaSourceFactory func(cfg MediaConfig, clock Clock, log *slog.Logger) (MediaSource, error)

MediaSourceFactory builds a MediaSource. It exists so the engine can hand the source *its own* Clock rather than trusting the source to pick a compatible one: Decision 6's whole correctness argument is that frame stamps and TimeSync t0 read one clock, and a factory makes that structural instead of a convention someone can forget. (It mirrors the browser's BroadcastMediaSourceFactory seam, added for R11.)

type Options

type Options struct {
	// Clock defaults to NewClock(). Tests inject FakeClock.
	Clock Clock
	// Dial defaults to dialRelay. Tests inject a fake session.
	Dial DialFunc
	// RoomDial defaults to dialRoom (R42). Tests inject a fake room session.
	RoomDial RoomDialFunc
	// MediaFactory defaults to the portal+GStreamer source. Tests inject a
	// fake. The engine always calls it with its own Clock (Decision 6).
	MediaFactory MediaSourceFactory
	// Log defaults to a discard logger — the engine never writes to stdio of
	// its own accord (a GUI has no stderr worth speaking of).
	Log *slog.Logger
	// StatsInterval defaults to 1s.
	StatsInterval time.Duration
}

Options are the injection points. Zero values give the production wiring.

type ReceiveStream

type ReceiveStream interface {
	io.Reader
	SetReadDeadline(t time.Time) error
}

ReceiveStream is one incoming unidirectional stream (the announce).

type RelaySession

type RelaySession interface {
	SendDatagram(b []byte) error
	ReceiveDatagram(ctx context.Context) ([]byte, error)
	OpenUniStream() (SendStream, error)
	AcceptUniStream(ctx context.Context) (ReceiveStream, error)
	CloseWithError(code webtransport.SessionErrorCode, msg string) error
	// Context is cancelled when the session ends, for any reason.
	Context() context.Context
}

RelaySession is the slice of a WebTransport session the engine uses. It is a seam, not an abstraction for its own sake: the send policy (docs/19 Decision 12) is defined by what happens when sends *fail* — a queue-full datagram, a stream that stalls past the next keyframe, a DatagramTooLargeError — and a real relay will not produce those on demand. Every one of those paths is a unit test against a fake implementing this.

type RestartingSource

type RestartingSource interface {
	// CaptureRestarts counts rebuilds completed during this session.
	CaptureRestarts() uint64
}

RestartingSource is implemented by media sources that can lose their capture backend mid-session and rebuild it without ending the broadcast.

Stats-only, and it is the counter that makes the recovery honest: a rebuild is deliberately quiet — no error, no OnEnded, a freeze the viewer reads as a stall — so without this number a machine renegotiating its screencast every few minutes is indistinguishable from one that never misses a beat. Same reasoning as Stats.Resumes on the transport side.

type RoomDialFunc

type RoomDialFunc func(ctx context.Context, rawURL, origin string, insecure bool) (sess RoomSession, status int, err error)

RoomDialFunc dials a room control session. Same shape as DialFunc, and for the same reason: the HTTP status is the whole point (403 wrong attach secret, 404 unknown code, 409 already in a room, 429 full).

type RoomError

type RoomError struct {
	// Op is "join" or "new".
	Op     string
	Status int
	Err    error
}

RoomError is a room control session failure the shells can act on: the dial the relay refused (Status set), or a protocol failure (Status 0). Distinct from StartError because it is not session-fatal — the broadcast keeps publishing whatever happens to the room.

func AsRoomError

func AsRoomError(err error) (*RoomError, bool)

AsRoomError extracts a *RoomError from err, if there is one.

func (*RoomError) Error

func (e *RoomError) Error() string

func (*RoomError) Message

func (e *RoomError) Message() string

Message renders the failure as a sentence. The statuses are the ones the relay's handleRoom / handleRoomNew actually return (docs/44 §4.2, §4.4); keep this in step with gawk-server/internal/transport/room.go.

func (*RoomError) Unwrap

func (e *RoomError) Unwrap() error

type RoomRejectError

type RoomRejectError struct {
	Command uint8
	Reason  uint8
	Detail  string
}

RoomRejectError is a CommandRejected from the relay: the room session is still up, but one command was refused.

func (*RoomRejectError) Error

func (e *RoomRejectError) Error() string

func (*RoomRejectError) Message

func (e *RoomRejectError) Message() string

Message renders the rejection as a sentence, one per wire reason.

type RoomSession

type RoomSession interface {
	// OpenStreamSync opens the one bidirectional control stream. On a closed
	// session it hands back the close error before touching the connection,
	// which is how roomCloseCode reads the code (sessionCloseCode's trick).
	OpenStreamSync(ctx context.Context) (RoomStream, error)
	CloseWithError(code webtransport.SessionErrorCode, msg string) error
	// Context is cancelled when the session ends, for any reason.
	Context() context.Context
}

RoomSession is the slice of a WebTransport session a room control session uses — a seam in the RelaySession mould. The policies worth testing are again the failure ones (a relay that never sends RoomState, a 4007 mid session, a token that arrives after the state), and a real relay will not produce those on demand.

type RoomStream

type RoomStream interface {
	io.Reader
	io.Writer
	io.Closer
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

RoomStream is the control stream: records in both directions.

type SendStream

type SendStream interface {
	io.Writer
	io.Closer
	// CancelWrite abandons the stream. This is how a superseded keyframe dies
	// (Decision 12: ≤1 in flight).
	CancelWrite(code webtransport.StreamErrorCode)
}

SendStream is one outgoing unidirectional stream (a keyframe).

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is one broadcast. Start/Stop mirror BroadcastSessionLike.

Deliberately absent: SetLadder/SetEncoderSettings (Decision 9). A rung change means restarting the GStreamer child, and keeping a dead-code setter "for symmetry" is a footgun. The restore token makes a restart-based SetRung cheap to add later, as its own task.

func New

func New(cfg Config, cb Callbacks, opts Options) *Session

New builds a Session. It performs no I/O; Start does.

func (*Session) BroadcastID

func (s *Session) BroadcastID() string

BroadcastID returns the session's code once announced.

func (*Session) Start

func (s *Session) Start(ctx context.Context) error

Start connects, then captures. It returns a *StartError on failure.

The order is not incidental (Decision 10 / connect-before-picker, mirroring the browser): dial first, so that if the relay refuses — wrong secret, ID taken, at capacity — no share dialog ever appears. Being asked to pick a screen and only then told "someone is already publishing" is the exact experience this ordering exists to prevent.

func (*Session) Stats

func (s *Session) Stats() Stats

Stats snapshots the session. The fps figures are windowed over the interval since the previous call, exactly as the browser derives encoderFps/sentFps from encodedSinceStats/dt — so a native diagnostics dump and a browser one mean the same thing when read side by side.

func (*Session) Stop

func (s *Session) Stop() error

Stop ends the session. Idempotent, and safe to call before Start.

type ShareModeSource

type ShareModeSource interface {
	// ShareMode is "screen", "window", or "" before the picker has answered.
	ShareMode() string
}

ShareModeSource is implemented by media sources that know whether the broadcaster shared a screen or a single window (R35, docs/39 D1). Stats-only, like CapturePath: nothing in the engine branches on it.

type StartError

type StartError struct {
	Phase  StartPhase
	Status int
	Err    error
}

StartError is returned by Session.Start.

Status carries the relay's HTTP status when the dial produced one. This is a genuine advantage over the browser broadcaster rather than a nicety: the JS WebTransport API surfaces an opaque WebTransportError with no status, so the browser cannot tell a bad secret from a full relay from a typo'd URL — docs/06 records exactly that limitation. webtransport-go's Dial returns the *http.Response even on rejection, so here 401/404/409/429 become sentences a friend can act on. Zero when the failure never reached HTTP (DNS, TLS, connection refused) — which is itself informative.

func AsStartError

func AsStartError(err error) (*StartError, bool)

AsStartError extracts a *StartError from err, if there is one.

func (*StartError) Error

func (e *StartError) Error() string

func (*StartError) Message

func (e *StartError) Message() string

Message renders a StartError as a sentence for a human — the GUI and CLI both surface this rather than a Go error string (V5's acceptance criterion: "errors surface as sentences, not Go error strings").

The statuses are the ones the relay's handlePublish actually returns; keep this in step with gawk-server/internal/transport/server.go.

func (*StartError) Unwrap

func (e *StartError) Unwrap() error

type StartPhase

type StartPhase string

StartPhase says where Start failed. It exists because callers must behave differently depending on the answer, and messages are not a contract (CODE-REVIEW.md, "Type your failure phases").

This mirrors the browser's BroadcastStartError.phase exactly, and for the same reason: R1's reclaim fallback treated "the relay rejected the dial" and "capture failed" identically, and silently minted a new broadcast ID out from under a live publisher session.

const (
	// PhaseConnect: the dial itself failed, so no publisher session was ever
	// established. Safe to retry against a different broadcast ID — this is
	// the only phase in which a failed reclaim may fall back to minting.
	PhaseConnect StartPhase = "connect"
	// PhaseCapture: the relay accepted us and a publisher session existed;
	// capture or encode then failed. The session has already been torn down
	// (no zombie publisher), but falling back to a different broadcast ID
	// here would be wrong: the ID we hold is live and ours.
	PhaseCapture StartPhase = "capture"
)

type Stats

type Stats struct {
	// Encoder is the cascade candidate actually in use ("vulkanh264enc",
	// "nvh264enc", "vah264enc"), or "" before one is chosen.
	Encoder string `json:"encoder,omitempty"`
	// Codec is the SPS-derived codec string sent to viewers ("avc1.42E02A").
	Codec string `json:"codec,omitempty"`
	// Width/Height/Fps/BitrateBps are the session's fixed rung (Decision 9),
	// and they are what R28's D17 target rules read — hence the `target*`
	// names, which are the browser's for the same quantities.
	Width      int `json:"targetWidth,omitempty"`
	Height     int `json:"targetHeight,omitempty"`
	Fps        int `json:"targetFps,omitempty"`
	BitrateBps int `json:"targetBitrateBps,omitempty"`

	// CaptureFpsAvailable is always false: see Decision 20 above. The field
	// exists so the gap is explicit in the JSON rather than an absent key a
	// reader might mistake for zero.
	CaptureFpsAvailable bool `json:"captureFpsAvailable"`

	// CapturePath says how frames cross the pipewiresrc boundary:
	// "zero-copy" (DMA-BUF stays on the GPU) or "system-memory" (one CPU
	// copy per frame); "" before capture starts.
	CapturePath string `json:"capturePath,omitempty"`

	// EncodedFrames counts access units demuxed from the child.
	EncodedFrames uint64 `json:"encodedFrames"`
	Keyframes     uint64 `json:"keyframes"`

	// KeyframeIntervalMs is an EMA of the wall-clock spacing between
	// keyframes leaving the encoder, measured on AU arrival stamps.
	// GOPMs is the *target*; the encoders take a frame count derived from
	// the nominal fps, so damage-driven capture running under that rate
	// stretches the real cadence proportionally — this stat is what makes
	// that visible. Available is false until two keyframes have arrived.
	KeyframeIntervalAvailable bool    `json:"keyframeIntervalAvailable"`
	KeyframeIntervalMs        float64 `json:"keyframeIntervalMs"`

	// ParityLevel is how many R29 forward-parity symbols this producer emits
	// per delta frame (docs/34). It mirrors the browser's
	// BroadcastStats.parityLevel: the level the RELAY advertised, not a local
	// preference — a producer cannot choose to protect a stream the fleet has
	// not asked it to, because the relay is what filters symbols per
	// subscriber. 0 against a relay predating R29 or configured off.
	ParityLevel      int    `json:"parityLevel"`
	ParityChunksSent uint64 `json:"parityChunksSent"`
	ParityBytesSent  uint64 `json:"parityBytesSent"`
	// SentFrames counts frames whose bytes reached the transport without
	// error — R9's funnel stage 4, "actually sent".
	SentFrames uint64 `json:"sentFrames"`
	// EncoderFps is the rate access units leave the child, and SentFps the
	// rate they actually leave the machine. Both are windowed over the stats
	// interval (the browser computes them the same way). A gap between them
	// localizes the bottleneck to the uplink rather than the encoder.
	EncoderFps float64 `json:"encoderFps"`
	SentFps    float64 `json:"sentFps"`

	DatagramsSent uint64 `json:"datagramsSent"`
	BytesSent     uint64 `json:"bytesSent"`
	ConfigsSent   uint64 `json:"configsSent"`

	// Keyframe uni streams (R8 discipline, applied at the source by
	// Decision 12).
	KeyframeStreamsSent       uint64 `json:"keyframeStreamsSent"`
	KeyframeStreamsFailed     uint64 `json:"keyframeStreamsFailed"`
	KeyframeStreamsSuperseded uint64 `json:"keyframeStreamsSuperseded"`
	KeyframeBytesSent         uint64 `json:"keyframeBytesSent"`

	// FramesDroppedAtSend counts frames abandoned mid-chunking after a
	// datagram send failure (Decision 12): the remainder is dead weight the
	// viewer's reassembler would discard anyway.
	FramesDroppedAtSend uint64 `json:"framesDroppedAtSend"`

	// TimeSyncRttMs is the self-owned broadcaster↔relay RTT, and
	// TimeSyncOffsetUs the relay-clock offset published as ClockMapping.
	// Available is false until the first pong lands.
	TimeSyncAvailable bool    `json:"timeSyncAvailable"`
	TimeSyncRttMs     float64 `json:"timeSyncRttMs"`
	TimeSyncOffsetUs  int64   `json:"timeSyncOffsetUs"`

	// ViewerCount is the live "N watching" number the relay pushes (R18,
	// docs/23 — fleet-global in cluster mode). Available is false until the
	// first push lands (an old relay never sends one).
	ViewerCountAvailable bool   `json:"viewerCountAvailable"`
	ViewerCount          uint32 `json:"viewerCount"`

	// Resumes counts how many times auto-resume has reclaimed this broadcast
	// on a fresh relay session, and Resuming says whether a reclaim is in
	// flight right now (capture and encode still running, nothing reaching
	// viewers). A broadcast that quietly resumes every few minutes is a
	// working broadcast on a failing path, and only this counter says so.
	Resumes  uint64 `json:"resumes"`
	Resuming bool   `json:"resuming"`

	// CaptureRestarts counts how many times the capture pipeline died
	// mid-session and was rebuilt without ending the broadcast (RestartingSource
	// — the native path's compositor-renegotiation recovery). It is the capture
	// side of Resumes and reads the same way: a broadcast that rebuilds every
	// few minutes is a working broadcast on a failing path, and the viewer's
	// only symptom is a freeze they cannot attribute.
	CaptureRestarts uint64 `json:"captureRestarts"`

	// System audio (R25, docs/28), mirroring the browser lane's audio stats
	// so the two dumps read alike.
	//
	// AudioState is the honest summary: "off" when the broadcaster asked for
	// silence, "unavailable" when audio was wanted and no source could give
	// it, "active" when packets are flowing, "error" when the bitstream
	// disagreed with the config we advertise (Decision 10). A machine with no
	// usable audio source is *not* an error, and this vocabulary says so.
	AudioState AudioState `json:"audioState,omitempty"`
	// AudioSource names the winning cascade candidate ("pipewire-monitor"),
	// which is the first thing to know when audio is present but wrong.
	AudioSource string `json:"audioSource,omitempty"`
	// The format actually advertised to viewers. Empty until a lane starts.
	AudioCodec      string `json:"audioCodec,omitempty"`
	AudioSampleRate int    `json:"audioSampleRate,omitempty"`
	AudioChannels   int    `json:"audioChannels,omitempty"`
	AudioBitrateBps int    `json:"audioBitrateBps,omitempty"`

	AudioPacketsSent uint64 `json:"audioPacketsSent"`
	AudioBytesSent   uint64 `json:"audioBytesSent"`
	AudioConfigsSent uint64 `json:"audioConfigsSent"`
	// AudioPacketsDropped counts packets lost at the send path — oversize, or
	// a datagram the transport refused. Deliberately its own counter: audio
	// never touches FramesDroppedAtSend, so a glance at the two separates a
	// saturated uplink from an audio-only problem.
	AudioPacketsDropped uint64 `json:"audioPacketsDropped"`

	// Single-app sharing (R35, docs/39). Both are empty on a whole-screen
	// broadcast, which is what makes them worth reporting: a viewer complaint
	// about the wrong sound is answered by these two fields plus AudioState,
	// without an ssh session.
	//
	// ShareMode is "screen" or "window" — what the desktop's picker returned
	// (D1), in the user's vocabulary rather than the portal's.
	ShareMode string `json:"shareMode,omitempty"`
	// AudioApp is the captured application's binary
	// (`application.process.binary`, AD2) in app mode. Empty means system
	// audio, which is also what "window video, whole-system sound" looks
	// like — a legal and explicitly offered combination.
	AudioApp string `json:"audioApp,omitempty"`
}

Stats is what the engine can honestly see, mirroring the browser's BroadcastStats where the two overlap so a native diagnostics dump can be read next to a browser one (R9, docs/13).

Decision 20 governs the gaps: report what we can see, mark what we cannot, fabricate nothing. The GStreamer child owns capture, so pre-encode capture fps is genuinely unavailable here — CaptureFpsAvailable is false and the shells print "n/a". Deriving it from the *requested* rate would be a plausible-looking number that answers the exact question ("is the source keeping up?") wrongly, which is worse than a gap. Every field carries an explicit JSON tag, and the tags are the browser's lowerCamelCase spelling rather than Go's exported names. That is load-bearing rather than cosmetic: this struct is serialized directly into an R28 telemetry batch, and everything downstream — schema.BroadcasterFields, the rollup's curated series, diagnose()'s rules, the dip detector, the dashboard — matches on the browser's names. Untagged, the native broadcaster reported `EncoderFps` where every reader looked for `encoderFps`: stored faithfully, readable by nothing. See stats_test.go, which pins the key set.

Fields the two producers genuinely share take the browser's name outright (the funnel, the D17 target trio, the audio lane). Fields only this engine has keep their own name in the same case (`encoder`, `capturePath`, `audioSource`) rather than being forced into a browser field whose values mean something else — one column, one vocabulary.

type TimeSyncClient

type TimeSyncClient struct {
	// contains filtered or unexported fields
}

TimeSyncClient owns the estimator and the ping encoding. The caller drives the cadence (Session runs a ticker) and feeds every received datagram through HandleDatagram.

func NewTimeSyncClient

func NewTimeSyncClient(send func([]byte) error, clock Clock) *TimeSyncClient

func (*TimeSyncClient) HandleDatagram

func (c *TimeSyncClient) HandleDatagram(dgram []byte) bool

HandleDatagram reports whether the datagram was a TimeSync message. True means "consumed here" — well-formed or not — so it never reaches the video path. False means "not mine, route it on".

func (*TimeSyncClient) Ping

func (c *TimeSyncClient) Ping()

Ping sends one TimeSync request. Send failures are swallowed: a ping must never take the pipeline down — the session's own lifecycle owns that.

func (*TimeSyncClient) Reset

func (c *TimeSyncClient) Reset()

Reset discards every sample.

Mandatory when auto-resume reclaims the broadcast on a new relay session: the reference these samples measure against is the relay's *process* monotonic clock (transport/server.go's processStart), so a reclaim that lands on a different pod — the normal case behind a load balancer — is measuring a different origin entirely. Carrying the old offset over would put every viewer's absolute capture→render latency out by the difference between two pods' uptimes, with nothing in the numbers to say so.

func (*TimeSyncClient) Sample

func (c *TimeSyncClient) Sample() (TimeSyncStats, bool)

Sample returns the current best estimate, if any pong has landed.

type TimeSyncEstimator

type TimeSyncEstimator struct {
	// contains filtered or unexported fields
}

TimeSyncEstimator is the pure half: samples in, best out. Mirrors the TS class of the same name so the two implementations can be compared on identical sample sequences.

func (*TimeSyncEstimator) Best

func (e *TimeSyncEstimator) Best() (TimeSyncStats, bool)

Best returns the lowest-RTT sample in the window, and whether there is one.

func (*TimeSyncEstimator) Record

func (e *TimeSyncEstimator) Record(t0Us, serverTimeUs, t1Us uint64)

Record adds a sample. t0Us is when we sent, serverTimeUs is the relay's clock as echoed, t1Us is when the reply landed.

type TimeSyncStats

type TimeSyncStats struct {
	// OffsetUs: relayClockUs ≈ localClockUs + OffsetUs (signed).
	OffsetUs int64
	// RttMs is the round-trip of the winning sample — also a self-owned RTT
	// for this leg, independent of any getStats() (which no browser ships
	// today; docs/13 D7 — the native path never had it either).
	RttMs float64
}

TimeSyncStats is the winning sample.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL