transport

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 31 Imported by: ? 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 transport carries Planck sessions. Listen and Dial run the production session layer: a pinned-certificate QUIC control stream (ALPN planck-v1) and an AEAD-sealed raw UDP media plane with adaptive FEC, rate control and clock sync. Under it are the primitives: AEAD packet framing keyed from a TLS 1.3 exporter, pacing, network impairment, and the Phase 0 spike packetizer and reassembler used by cmd/spike-transport.

Index

Constants

View Source
const (

	// AEADHeaderLen is the cleartext prefix of every sealed packet:
	// one marker byte and a 64-bit big-endian sequence number.
	AEADHeaderLen = 1 + 8
	AEADTagLen    = 16
	// AEADOverhead is the number of bytes sealing adds to a plaintext.
	AEADOverhead = AEADHeaderLen + AEADTagLen
)
View Source
const (
	MaxSlices         = 16
	MaxShardsPerSlice = 255
)
View Source
const (
	KindMedia byte = 1
	KindAck   byte = 2
	KindPing  byte = 3
	KindPong  byte = 4
)

Packet kinds carried in the first plaintext byte.

View Source
const ALPN = "planck-spike-v0"
View Source
const AckLen = 20
View Source
const ControlALPN = "planck-v1"

ControlALPN is the ALPN protocol of the production control connection.

View Source
const MediaExporterLabel = "EXPORTER-planck-media-v0"

MediaExporterLabel is the RFC 8446 §7.5 exporter label for media keys.

View Source
const MediaHeaderLen = 20

MediaHeaderLen is the size of the plaintext header that precedes each shard.

View Source
const PingLen = 16

PingLen is the size of ping and pong packets: kind, pad, sequence, and the sender's timestamp echoed back unchanged.

View Source
const ReassemblyWindow = 8

ReassemblyWindow is how many frames stay open for late shards. When a frame newer than id+ReassemblyWindow arrives, frame id is finalized.

Variables

View Source
var (
	ErrShortPacket = errors.New("transport: packet too short")
	ErrBadMarker   = errors.New("transport: bad packet marker")
	ErrReplay      = errors.New("transport: replayed or stale packet")
	ErrAuth        = errors.New("transport: packet authentication failed")
)
View Source
var (
	// ErrServerClosed is what Accept returns once Close was called.
	ErrServerClosed = errors.New("transport: server closed")
	// ErrHandshakeBusy refuses a connection while maxHandshakes run.
	ErrHandshakeBusy = errors.New("transport: too many handshakes in flight")
)
View Source
var (
	ErrWrongRole      = errors.New("transport: not allowed in this session role")
	ErrNoPeer         = errors.New("transport: media peer address not known yet")
	ErrClosed         = errors.New("transport: session closed")
	ErrTooBig         = errors.New("transport: payload does not fit one media datagram")
	ErrControlBacklog = errors.New("transport: control send queue full")
	// ErrPeerUnsupported: the peer's Hello did not offer the feature.
	ErrPeerUnsupported = errors.New("transport: peer does not support this")
)
View Source
var ErrAuthDenied = errors.New("transport: authentication denied")
View Source
var ErrBadHeader = errors.New("transport: bad media header")
View Source
var ErrHostNotTrusted = errors.New("transport: host certificate not trusted")
View Source
var ErrHostPINMismatch = errors.New("transport: host could not prove the pairing PIN")
View Source
var ErrUnanswered = errors.New("transport: the host did not answer")

ErrUnanswered is a Dial whose QUIC handshake timed out: nothing answered on that address, and another route to the host may.

Functions

func CertFingerprint

func CertFingerprint(c tls.Certificate) [32]byte

CertFingerprint is the fingerprint of a certificate's leaf.

func ClientTLSConfig

func ClientTLSConfig(cert tls.Certificate, verify HostVerifier) (*tls.Config, error)

ClientTLSConfig is the client's control-connection TLS config. Hosts use self-signed certificates, so CA chain verification is replaced, not skipped: Go only allows that through InsecureSkipVerify, and VerifyConnection, which runs regardless, enforces verify on every handshake.

func ClosedByPeer

func ClosedByPeer(err error) bool

ClosedByPeer reports whether err, a session's Err, is the peer closing the session on purpose. A goodbye can be lost with the close that follows it, which still tells an orderly end from a lost connection.

func Fingerprint

func Fingerprint(der []byte) [32]byte

Fingerprint is the SHA-256 of a DER certificate.

func InsecureClientTLS

func InsecureClientTLS() *tls.Config

InsecureClientTLS skips certificate verification. Spike use only: a real client pins the host certificate learned at pairing.

func Mono

func Mono() int64

Mono returns monotonic nanoseconds since a process-local epoch. On Windows it reads QueryPerformanceCounter, because Go's monotonic clock there advances in timer-interrupt steps (about 0.5 ms), too coarse for packet pacing and latency measurement.

func NewIdentity

func NewIdentity(name string) (tls.Certificate, error)

NewIdentity creates a long-lived self-signed ECDSA P-256 certificate that identifies a host or client. Peers trust it by its SHA-256 fingerprint, learned at pairing, not by a CA.

func PacketBufLen

func PacketBufLen(shardSize int) int

PacketBufLen returns the buffer size for one packet of shardSize bytes, with headroom for the AEAD header in front and the tag behind.

func ParsePing

func ParsePing(b []byte) (seq uint32, ts int64, ok bool)

func PutPing

func PutPing(b []byte, kind byte, seq uint32, ts int64) []byte

func QUICConfig

func QUICConfig() *quic.Config

QUICConfig is the control/datagram connection config shared by both peers.

func SelfSignedServerTLS

func SelfSignedServerTLS() (*tls.Config, error)

SelfSignedServerTLS returns a TLS 1.3 server config with a fresh ephemeral ECDSA P-256 certificate.

func ServerTLSConfig

func ServerTLSConfig(cert tls.Certificate) *tls.Config

ServerTLSConfig is the host's control-connection TLS config. Clients must present a certificate; its fingerprint is their identity.

func SleepUntilMono

func SleepUntilMono(deadline int64)

SleepUntilMono sleeps coarsely, then spins for the last spinThreshold.

Types

type Ack

type Ack struct {
	FrameID          uint32
	FirstSliceLeadUs uint32
	FinalFrameID     uint32
	FinalRecvShards  uint16
	FinalSentShards  uint16
	FinalFrameOK     bool
	HasFinal         bool
}

Ack is the receiver's per-frame report. It also carries the final shard counts of an older frame so the sender can estimate loss for adaptive FEC.

func (*Ack) Parse

func (a *Ack) Parse(b []byte) error

func (*Ack) Put

func (a *Ack) Put(b []byte) []byte

type AdaptiveParity

type AdaptiveParity struct {
	Target  float64
	MinLoss float64
	// contains filtered or unexported fields
}

AdaptiveParity sizes parity from the observed loss rate: the smallest k such that, with independent loss at that rate, a slice of data+k shards loses more than k with probability below Target. Safe for concurrent SetLoss.

func (*AdaptiveParity) Loss

func (a *AdaptiveParity) Loss() float64

func (*AdaptiveParity) Parity

func (a *AdaptiveParity) Parity(data int) int

func (*AdaptiveParity) SetLoss

func (a *AdaptiveParity) SetLoss(p float64)

type AuthInfo

type AuthInfo struct {
	Method            wire.AuthMethod
	DeviceName        string
	ClientFingerprint [32]byte
	RemoteAddr        netip.AddrPort
	// PINVerified is true when Method is AuthPIN and the client proved it
	// knows the host's current PIN on this TLS session.
	PINVerified bool
}

AuthInfo is what the host knows about a connecting client when it decides whether to let it stream.

type ClientConfig

type ClientConfig struct {
	Certificate tls.Certificate
	Name        string
	// VerifyHost decides whether to trust the host's certificate
	// fingerprint. Required.
	VerifyHost HostVerifier
	Auth       wire.AuthMethod
	// PIN is the pairing PIN the user read off the host, for AuthPIN.
	PIN              string
	Session          wire.SessionConfig
	Handlers         Handlers
	PingInterval     time.Duration
	HandshakeTimeout time.Duration
	// SimulateLoss drops this fraction of outgoing media datagrams, for
	// tests and diagnostics.
	SimulateLoss float64
	// LANPath says the host was reached LAN direct. The client then offers
	// wire.MaxLANDatagram when its route to the host has a 1500-byte MTU.
	LANPath bool
	// Capabilities, when set, offers wire.FeatureCapabilities: this JSON
	// goes to a host that offers it too, and the host's Capabilities and
	// Profile come back (Session.PeerCapabilities, Session.Profile).
	Capabilities []byte
	// StreamSwitch offers wire.FeatureStreamSwitch: the Control handler
	// takes wire.Stream and moves the session with SetStream.
	StreamSwitch bool
	// CursorShape offers wire.FeatureCursorShape: the Control handler
	// takes wire.CursorShape.
	CursorShape bool
}

type ClockEstimator

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

ClockEstimator turns ping/pong exchanges into a round-trip time and the offset of the peer's monotonic clock from ours. The offset comes from the lowest-RTT sample of the last 16, which has the least queueing asymmetry. Add must be called from one goroutine; the readers are safe from any.

func (*ClockEstimator) Add

func (c *ClockEstimator) Add(p wire.Pong, t3 int64)

Add folds in a pong received at local time t3.

func (*ClockEstimator) MinRTT

func (c *ClockEstimator) MinRTT() time.Duration

MinRTT is the lowest RTT in the recent window.

func (*ClockEstimator) Offset

func (c *ClockEstimator) Offset() int64

Offset is the peer's clock minus ours, in nanoseconds.

func (*ClockEstimator) RTT

func (c *ClockEstimator) RTT() time.Duration

RTT is the smoothed round-trip time, or 0 before the first pong.

func (*ClockEstimator) Samples

func (c *ClockEstimator) Samples() uint64

Samples is the number of pongs folded in so far.

func (*ClockEstimator) ToLocal

func (c *ClockEstimator) ToLocal(peerTS int64) int64

ToLocal maps a peer monotonic timestamp to our clock.

type DirectionKey

type DirectionKey struct {
	Suite Suite
	Key   []byte
	IV    [ivLen]byte
}

DirectionKey is the key material for one direction of a media session.

type Exporter

type Exporter func(label string, context []byte, length int) ([]byte, error)

Exporter matches tls.ConnectionState.ExportKeyingMaterial.

type FixedParity

type FixedParity int

FixedParity is a parity percentage, rounded up so any non-zero percentage yields at least one parity shard.

func (FixedParity) Parity

func (f FixedParity) Parity(data int) int

type FrameStats

type FrameStats struct {
	FrameID         uint32
	Complete        bool
	RecvShards      int
	SentShards      int
	Slices          int
	SlicesRecovered int
	SlicesLost      int
}

FrameStats is reported once per frame when it leaves the window.

type Handlers

type Handlers struct {
	VideoSlice func(VideoSlice)
	VideoFrame func(info wire.VideoInfo, frame []byte)
	Audio      func(h wire.AudioHeader, opus []byte)
	// Mic receives the client's microphone (host only). Setting it offers
	// wire.FeatureMic.
	Mic func(h wire.AudioHeader, payload []byte)
	// Input receives the client's input (host only), with the session it
	// came on.
	Input   func(s *Session, in wire.Input)
	Rumble  func(r wire.Rumble)
	Control func(m wire.Message)
	// Clipboard receives the peer's clipboard items on their own goroutine;
	// the item is the handler's to keep. Setting it offers
	// wire.FeatureClipboard.
	Clipboard func(c *wire.Clip)
}

Handlers receive media and control messages. Media handlers run on the session's receive goroutine and Control on its control goroutine; byte slices are valid only during the call. Handlers must not call Close synchronously. Nil handlers are skipped.

type HandshakeError

type HandshakeError struct {
	Remote net.Addr
	Err    error
}

HandshakeError is a failed handshake of one connection; the server keeps listening.

func (*HandshakeError) Error

func (e *HandshakeError) Error() string

func (*HandshakeError) Unwrap

func (e *HandshakeError) Unwrap() error

type HostVerifier

type HostVerifier func(fingerprint [32]byte) error

HostVerifier decides whether to trust a host by its certificate fingerprint. It replaces CA verification on the client.

func PinnedHost

func PinnedHost(want [32]byte) HostVerifier

PinnedHost trusts exactly one host certificate.

type Impairer

type Impairer struct {
	Dropped uint64
	Sent    uint64
	// contains filtered or unexported fields
}

Impairer drops packets at random and, when Jitter is set, delays the rest by up to Jitter in FIFO order. With jitter, send runs on the Impairer's own goroutine; without it, on the caller's.

func NewImpairer

func NewImpairer(cfg Impairment, bufLen int, send func([]byte) error) *Impairer

func (*Impairer) Close

func (im *Impairer) Close() error

Close drains the delay line and returns the first delayed send error.

func (*Impairer) Send

func (im *Impairer) Send(pkt []byte) error

Send forwards pkt, drops it, or queues a copy for delayed delivery.

type Impairment

type Impairment struct {
	Loss   float64
	Jitter time.Duration
	Seed   uint64
}

Impairment simulates a lossy, jittery path in front of a send function.

type MediaHeader

type MediaHeader struct {
	SliceIndex   uint8
	SliceCount   uint8
	ShardIndex   uint8
	DataShards   uint8
	ParityShards uint8
	ShardLen     uint16
	FrameID      uint32
	SliceLen     uint32
	FrameShards  uint16
}

MediaHeader describes one FEC shard of one slice of one frame.

func (*MediaHeader) Parse

func (h *MediaHeader) Parse(b []byte) error

Parse decodes a media header and validates it against the payload length.

func (*MediaHeader) Put

func (h *MediaHeader) Put(b []byte)

type MediaKeys

type MediaKeys struct {
	ClientToServer DirectionKey
	ServerToClient DirectionKey
}

MediaKeys holds one key per direction. Client is the peer that dialed the control connection (the streaming host).

func DeriveMediaKeys

func DeriveMediaKeys(export Exporter, suite Suite) (MediaKeys, error)

DeriveMediaKeys derives directional media keys from the TLS 1.3 exporter of the control connection. Both peers derive identical keys; the suite is bound into the exporter context so a suite mismatch yields unrelated keys.

func MediaKeysFromConn

func MediaKeysFromConn(c *quic.Conn, suite Suite) (MediaKeys, error)

MediaKeysFromConn derives media keys from a QUIC connection's TLS exporter.

type Opener

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

Opener authenticates and decrypts incoming packets, rejecting replays with a 64-packet sliding window. It is not safe for concurrent use.

func NewOpener

func NewOpener(k DirectionKey) (*Opener, error)

func (*Opener) Open

func (o *Opener) Open(pkt []byte) ([]byte, error)

Open decrypts pkt in place and returns the plaintext, which aliases pkt.

type Pacer

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

Pacer spaces packets at a fixed byte rate. A zero rate sends every packet immediately (burst). Not safe for concurrent use.

func NewPacer

func NewPacer(bytesPerSec float64) *Pacer

func (*Pacer) Wait

func (p *Pacer) Wait(n int)

Wait blocks until a packet of n bytes may go out.

type Packetizer

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

Packetizer splits frames into slices and each slice into fixed-size data shards plus Reed-Solomon parity shards. Buffers are reused between calls, so after warm-up it does not allocate. Not safe for concurrent use.

func NewPacketizer

func NewPacketizer(shardSize int) *Packetizer

func (*Packetizer) Layout

func (p *Packetizer) Layout(frameLen, slices int, policy ParityPolicy) (data, parity, total int, err error)

Layout reports the per-slice shard counts for a frame without sending it.

func (*Packetizer) Packetize

func (p *Packetizer) Packetize(frameID uint32, frame []byte, slices int, policy ParityPolicy, emit func(pkt []byte) error) error

Packetize emits every packet of frame, slice by slice, data shards before parity. emit receives a buffer of PacketBufLen(shardSize) bytes whose plaintext (media header and shard) starts at AEADHeaderLen; the buffer is reused after emit returns.

type ParityPolicy

type ParityPolicy interface {
	Parity(data int) int
}

ParityPolicy chooses the parity shard count for a slice of data shards.

type ParityProfile

type ParityProfile struct {
	MinPercent      int
	KeyframePercent int
	// CriticalPercent covers the leading slices SendChunkedFrame is told
	// are critical, with at least two parity shards.
	CriticalPercent int
}

ParityProfile puts floors under the adaptive parity, in percent of a block's data shards.

type PushResult

type PushResult struct {
	FrameID        uint32
	SliceReady     bool
	SliceIndex     int
	SliceRecovered bool
	FrameComplete  bool
}

PushResult says what one packet completed.

type Reassembler

type Reassembler struct {
	Late    uint64
	Invalid uint64
	// contains filtered or unexported fields
}

Reassembler rebuilds slices and frames from shards, using Reed-Solomon reconstruction when data shards are missing. Slice bytes are stored contiguously, so SliceData needs no copy. Not safe for concurrent use.

func NewReassembler

func NewReassembler(shardSize int, onFinal func(FrameStats)) *Reassembler

NewReassembler returns a Reassembler for shards of shardSize bytes. onFinal, if set, is called for each frame as it leaves the window.

func (*Reassembler) Flush

func (r *Reassembler) Flush()

Flush finalizes every open frame.

func (*Reassembler) PartialFrame

func (r *Reassembler) PartialFrame(frameID uint32, dst []byte) (au []byte, missing int, ok bool)

PartialFrame appends frame frameID's slices to dst as far as they are known: ready slices whole, and other slices with the data shards that arrived and zeros for the rest. Slices with no shard seen are left out (PyroWave chunks are self-describing, so offsets do not matter). missing counts the zeroed data shards. ok is false once the frame has left the window or when no shard of it arrived.

func (*Reassembler) Push

func (r *Reassembler) Push(plain []byte) (PushResult, error)

Push consumes one plaintext media packet (media header and shard).

func (*Reassembler) SliceData

func (r *Reassembler) SliceData(frameID uint32, slice int) []byte

SliceData returns the reassembled bytes of a ready slice, or nil. The slice is valid until the frame leaves the window.

type ReplayWindow

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

ReplayWindow tracks the highest accepted sequence number and a bitmap of the 64 numbers below it. Sequence 0 is never valid.

func (*ReplayWindow) Accept

func (w *ReplayWindow) Accept(seq uint64)

Accept records seq; call it only after the packet authenticated.

func (*ReplayWindow) Check

func (w *ReplayWindow) Check(seq uint64) bool

type ResolveRequest

type ResolveRequest struct {
	Request    wire.SessionConfig
	ClientCaps []byte
	Path       ratectl.Path
	// LANDatagram is true when the session uses wire.MaxLANDatagram.
	LANDatagram bool
	Remote      netip.AddrPort
}

ResolveRequest is what the host knows when it settles a session with a client that sent wire.Capabilities.

type ResolveResult

type ResolveResult struct {
	Config  wire.SessionConfig
	Profile []byte
	// StartKbps and MaxKbps seed and cap the rate controller; zero keeps
	// the defaults, capped by Config.BitrateKbps.
	StartKbps, MaxKbps int
	Parity             ParityProfile
}

ResolveResult is the settled session: Config goes out in SessionReady and Profile in wire.Profile right after it.

type Sealer

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

Sealer encrypts outgoing packets. It is not safe for concurrent use.

func NewSealer

func NewSealer(k DirectionKey) (*Sealer, error)

func (*Sealer) Seal

func (s *Sealer) Seal(dst, plaintext []byte) []byte

Seal writes header || ciphertext || tag for plaintext into dst and returns the sealed packet. dst must have capacity for len(plaintext)+AEADOverhead; plaintext may alias dst[AEADHeaderLen:].

type Server

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

Server accepts client sessions on a QUIC control listener. Each connection's handshake runs on its own goroutine, so a peer that stalls cannot hold up the others.

func Listen

func Listen(addr string, cfg ServerConfig) (*Server, error)

Listen starts a host control listener on addr.

func (*Server) Accept

func (sv *Server) Accept(ctx context.Context) (*Session, error)

Accept waits for the next finished handshake. A failed handshake returns a *HandshakeError; ErrServerClosed follows Close; any other error means the listener died and accepts nothing more.

func (*Server) Addr

func (sv *Server) Addr() net.Addr

func (*Server) Close

func (sv *Server) Close() error

Close stops accepting and ends the handshakes in flight. A session that finished its handshake but was never accepted is closed.

func (*Server) SetName

func (sv *Server) SetName(name string)

SetName changes the host name later handshakes send.

type ServerConfig

type ServerConfig struct {
	Certificate tls.Certificate
	Name        string
	// Authorize returns the client's identity, or an error to refuse it.
	// A host typically accepts a stored fingerprint for AuthPaired, stores
	// the fingerprint when PINVerified, and asks Tailscale WhoIs about
	// RemoteAddr for AuthTailscale. Required.
	Authorize func(ctx context.Context, info AuthInfo) (identity string, err error)
	// PIN returns the pairing PIN currently shown to the user, or "" when
	// pairing is closed.
	PIN func() string
	// Negotiate turns the client's requested config into the accepted one.
	// Nil accepts the request unchanged.
	Negotiate func(req wire.SessionConfig) (wire.SessionConfig, error)
	// Capabilities, when set, offers wire.FeatureCapabilities. With a
	// client that offers it too, the host sends this JSON after AuthOK,
	// reads the client's, and settles the session with Resolve instead of
	// Negotiate.
	Capabilities func() []byte
	Resolve      func(ResolveRequest) (ResolveResult, error)
	// Resize offers wire.FeatureResize: the Control handler takes
	// wire.Resize.
	Resize bool
	// SwitchDisplay offers wire.FeatureSwitchDisplay: the Control handler
	// takes wire.SwitchDisplay.
	SwitchDisplay bool
	// MediaAddr is the local address for media sockets; default ":0".
	MediaAddr string
	// MaxDatagram caps sealed media datagrams. Zero takes
	// wire.MaxLANDatagram on a LAN path both ends route over a 1500-byte
	// MTU (the client says so with wire.FeatureLANDatagram), and
	// wire.MaxDatagram otherwise.
	MaxDatagram int
	// Rate configures the bitrate controller. Zero fields take
	// ratectl.DefaultConfig values; MaxKbps is further capped by the
	// session's BitrateKbps.
	Rate ratectl.Config
	// Path overrides the path guessed from the client's address.
	Path ratectl.Path
	// FECMinLoss keeps parity for at least this loss rate on clean paths.
	FECMinLoss       float64
	Handlers         Handlers
	PingInterval     time.Duration
	HandshakeTimeout time.Duration
	// SimulateLoss drops this fraction of outgoing media datagrams, for
	// tests and diagnostics.
	SimulateLoss float64
}

type Session

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

Session is one authenticated host-client stream: a QUIC control stream plus an AEAD-sealed UDP media socket. The host sends video, audio and rumble and receives input and feedback; the client the reverse.

func Dial

func Dial(ctx context.Context, addr string, cfg ClientConfig) (*Session, error)

Dial connects to a host, authenticates, negotiates the session and brings up the media path.

func (*Session) Clock

func (s *Session) Clock() *ClockEstimator

func (*Session) Close

func (s *Session) Close() error

Close says goodbye to the peer, tears the session down and waits for its goroutines.

func (*Session) Config

func (s *Session) Config() wire.SessionConfig

func (*Session) Done

func (s *Session) Done() <-chan struct{}

func (*Session) Err

func (s *Session) Err() error

Err is why the session ended, or nil while it runs.

func (*Session) FECLoss

func (s *Session) FECLoss() float64

FECLoss is the smoothed pre-FEC loss estimate driving parity (host only).

func (*Session) FirstArrival

func (s *Session) FirstArrival(id uint32) int64

FirstArrival is when the first datagram of a recent frame was read (client only). Call it from a media handler.

func (*Session) ID

func (s *Session) ID() uint64

func (*Session) Identity

func (s *Session) Identity() string

func (*Session) KeyframeRequested

func (s *Session) KeyframeRequested() bool

KeyframeRequested reports and clears a pending keyframe request, raised by a client PLI or by the rate controller after a lost frame (host only).

func (*Session) MaxDatagram

func (s *Session) MaxDatagram() int

func (*Session) PeerCapabilities

func (s *Session) PeerCapabilities() []byte

PeerCapabilities is the JSON the peer sent in wire.Capabilities, or nil when one end does not have wire.FeatureCapabilities.

func (*Session) PeerFeatures

func (s *Session) PeerFeatures() uint32

func (*Session) PeerFingerprint

func (s *Session) PeerFingerprint() [32]byte

func (*Session) PeerName

func (s *Session) PeerName() string

func (*Session) PeerState

func (s *Session) PeerState() wire.PeerState

PeerState is the last wire.PeerState the peer sent, or the zero value.

func (*Session) Profile

func (s *Session) Profile() []byte

Profile is the JSON of the host's wire.Profile, or nil without one.

func (*Session) RTT

func (s *Session) RTT() time.Duration

func (*Session) RemoteControlAddr

func (s *Session) RemoteControlAddr() net.Addr

func (*Session) SendAudio

func (s *Session) SendAudio(seq uint32, ts int64, opus []byte) error

SendAudio sends one Opus packet (host only).

func (*Session) SendChunkedFrame

func (s *Session) SendChunkedFrame(info wire.VideoInfo, frame []byte, ends []int, critical int) error

SendChunkedFrame sends a frame already cut into slices ending at ends, such as PyroWave's packetizer output. The first critical slices get the critical parity floor. Keyframe parity does not apply: every such frame is intra.

func (*Session) SendClipboard

func (s *Session) SendClipboard(ctx context.Context, c *wire.Clip) error

SendClipboard writes one clipboard item on this side's clipboard stream, opening it on first use, to a peer with wire.FeatureClipboard. It blocks until the item is handed to QUIC; video and input do not wait on it.

func (*Session) SendControl

func (s *Session) SendControl(m wire.Message) error

SendControl queues a control message. It does not block.

func (*Session) SendInput

func (s *Session) SendInput(in wire.Input) error

SendInput sends one input event (client only). For two seconds after a frame missed a datagram, and when the host drops duplicate Seqs, the previous event goes out again just ahead of it, so one lost datagram does not lose an event.

func (*Session) SendMic

func (s *Session) SendMic(h wire.AudioHeader, payload []byte) error

SendMic sends one packet of the client's microphone (client only, to a host with wire.FeatureMic). h.Flow is set to wire.FlowMic.

func (*Session) SendRumble

func (s *Session) SendRumble(r wire.Rumble) error

SendRumble sends a gamepad rumble command (host only).

func (*Session) SendVideoFrame

func (s *Session) SendVideoFrame(info wire.VideoInfo, frame []byte) error

SendVideoFrame sends a whole encoded frame, split into info.SliceCount slices (the session's configured count if zero).

func (*Session) SendVideoSlice

func (s *Session) SendVideoSlice(info wire.VideoInfo, slice int, data []byte) error

SendVideoSlice sends one slice as soon as the encoder produces it, for sub-frame streaming. info.SliceCount must be the frame's final count.

func (*Session) SetPath

func (s *Session) SetPath(p ratectl.Path)

SetPath applies a new path's bitrate ceiling (host only).

func (*Session) SetStream

func (s *Session) SetStream(cfg wire.SessionConfig, startKbps, maxKbps int, parity ParityProfile)

SetStream moves the session to a stream settled mid-session: Config says what it carries from now on. On a host, the rate controller takes its cap and start rate (zero keeps the old ones, as for ResolveResult) and the parity its floors.

func (*Session) ShardSize

func (s *Session) ShardSize() int

func (*Session) Stats

func (s *Session) Stats() SessionStats

func (*Session) TargetBitrateKbps

func (s *Session) TargetBitrateKbps() int

TargetBitrateKbps is the rate controller's current target (host only).

type SessionStats

type SessionStats struct {
	PacketsSent      uint64
	PacketsReceived  uint64
	AuthFailures     uint64
	SimulatedDrops   uint64
	FramesComplete   uint64
	FramesLost       uint64
	SlicesRecovered  uint64
	PLIsSent         uint64
	PLIsReceived     uint64
	FeedbackReceived uint64
	// InputResent counts the client's redundant input copies, and
	// InputDuplicates the copies the host dropped.
	InputResent     uint64
	InputDuplicates uint64
	// FramesPartial counts intra frames handed on with chunks missing.
	FramesPartial uint64
	// ClipboardSent and ClipboardReceived count clipboard items;
	// ClipboardRefused counts received items dropped for their size, hash
	// or format.
	ClipboardSent     uint64
	ClipboardReceived uint64
	ClipboardRefused  uint64
}

SessionStats are cumulative counters.

type Suite

type Suite uint8
const (
	SuiteAES128GCM Suite = iota + 1
	SuiteChaCha20Poly1305
)

func ParseSuite

func ParseSuite(name string) (Suite, error)

func (Suite) String

func (s Suite) String() string

type VideoSlice

type VideoSlice struct {
	Info      wire.VideoInfo
	Index     int
	Data      []byte
	Recovered bool
}

VideoSlice is one rebuilt slice. Data is valid only during the callback.

Jump to

Keyboard shortcuts

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