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
- Variables
- func CertFingerprint(c tls.Certificate) [32]byte
- func ClientTLSConfig(cert tls.Certificate, verify HostVerifier) (*tls.Config, error)
- func ClosedByPeer(err error) bool
- func Fingerprint(der []byte) [32]byte
- func InsecureClientTLS() *tls.Config
- func Mono() int64
- func NewIdentity(name string) (tls.Certificate, error)
- func PacketBufLen(shardSize int) int
- func ParsePing(b []byte) (seq uint32, ts int64, ok bool)
- func PutPing(b []byte, kind byte, seq uint32, ts int64) []byte
- func QUICConfig() *quic.Config
- func SelfSignedServerTLS() (*tls.Config, error)
- func ServerTLSConfig(cert tls.Certificate) *tls.Config
- func SleepUntilMono(deadline int64)
- type Ack
- type AdaptiveParity
- type AuthInfo
- type ClientConfig
- type ClockEstimator
- type DirectionKey
- type Exporter
- type FixedParity
- type FrameStats
- type Handlers
- type HandshakeError
- type HostVerifier
- type Impairer
- type Impairment
- type MediaHeader
- type MediaKeys
- type Opener
- type Pacer
- type Pacing
- type Packetizer
- type ParityPolicy
- type ParityProfile
- type ProbeSpec
- type ProbeTrain
- type PushResult
- type Reassembler
- type ReceiveQueue
- type ReplayWindow
- type ResolveRequest
- type ResolveResult
- type Sealer
- type Server
- type ServerConfig
- type Session
- func (s *Session) Clock() *ClockEstimator
- func (s *Session) Close() error
- func (s *Session) Config() wire.SessionConfig
- func (s *Session) Done() <-chan struct{}
- func (s *Session) Err() error
- func (s *Session) FECLoss() float64
- func (s *Session) FirstArrival(id uint32) int64
- func (s *Session) ID() uint64
- func (s *Session) Identity() string
- func (s *Session) KeyframeRequested() bool
- func (s *Session) MaxDatagram() int
- func (s *Session) PeerCapabilities() []byte
- func (s *Session) PeerFeatures() uint32
- func (s *Session) PeerFingerprint() [32]byte
- func (s *Session) PeerName() string
- func (s *Session) PeerState() wire.PeerState
- func (s *Session) Ping(ctx context.Context, n int, every time.Duration) ([]time.Duration, error)
- func (s *Session) Probe(ctx context.Context, spec ProbeSpec) (ProbeTrain, error)
- func (s *Session) Profile() []byte
- func (s *Session) RTT() time.Duration
- func (s *Session) RefInvalidation() bool
- func (s *Session) RemoteControlAddr() net.Addr
- func (s *Session) SendAudio(seq uint32, ts int64, opus []byte) error
- func (s *Session) SendChunkedFrame(info wire.VideoInfo, frame []byte, ends []int, critical int) error
- func (s *Session) SendClipboard(ctx context.Context, c *wire.Clip) error
- func (s *Session) SendControl(m wire.Message) error
- func (s *Session) SendInput(in wire.Input) error
- func (s *Session) SendMic(h wire.AudioHeader, payload []byte) error
- func (s *Session) SendRumble(r wire.Rumble) error
- func (s *Session) SendVideoFrame(info wire.VideoInfo, frame []byte) error
- func (s *Session) SendVideoSlice(info wire.VideoInfo, slice int, data []byte) error
- func (s *Session) SetPacing(p Pacing)
- func (s *Session) SetPath(p ratectl.Path)
- func (s *Session) SetStream(cfg wire.SessionConfig, startKbps, maxKbps int, parity ParityProfile)
- func (s *Session) ShardSize() int
- func (s *Session) SocketBuffers() SocketBuffers
- func (s *Session) Stats() SessionStats
- func (s *Session) TargetBitrateKbps() int
- type SessionStats
- type SocketBuffers
- type Suite
- type VideoSlice
Constants ¶
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 )
const ( MaxSlices = 16 MaxShardsPerSlice = 255 )
const ( KindMedia byte = 1 KindAck byte = 2 KindPing byte = 3 KindPong byte = 4 )
Packet kinds carried in the first plaintext byte.
const ALPN = "planck-spike-v0"
const AckLen = 20
const ControlALPN = "planck-v1"
ControlALPN is the ALPN protocol of the production control connection.
const MediaExporterLabel = "EXPORTER-planck-media-v0"
MediaExporterLabel is the RFC 8446 §7.5 exporter label for media keys.
const MediaHeaderLen = 20
MediaHeaderLen is the size of the plaintext header that precedes each shard.
const PingLen = 16
PingLen is the size of ping and pong packets: kind, pad, sequence, and the sender's timestamp echoed back unchanged.
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 ¶
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") )
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") )
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") )
var DefaultPacing = Pacing{Share: 0.35, KeyShare: 0.8, MinRate: 1.5, BurstDatagrams: 16}
DefaultPacing adds a P frame at most a third of its interval (2.8 ms at 120 fps), most of it hidden behind the next frame's encode; a 16 datagram train is about 23 KB, under 0.2 ms at 1 Gbit/s.
var ErrAuthDenied = errors.New("transport: authentication denied")
var ErrBadHeader = errors.New("transport: bad media header")
var ErrCalibrationUnsupported = errors.New("transport: the host cannot calibrate; update Planck on it")
ErrCalibrationUnsupported is a calibration dial to a host whose Hello does not carry wire.FeatureCalibration: an older Planck.
var ErrHostNotTrusted = errors.New("transport: host certificate not trusted")
var ErrHostPINMismatch = errors.New("transport: host could not prove the pairing PIN")
var ErrProbeBusy = errors.New("transport: a probe train is already running")
ErrProbeBusy is a probe while another of the session's runs.
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.
var MacReceiveQueue = ReceiveQueue{Bytes: 112 * 1452, DrainMbps: 175}
MacReceiveQueue is a macOS client on wired Ethernet: a Thunderbolt Intel I225 (DriverKit) on an M5 Pro kept the first 127 to 158 datagrams of a burst and dropped the rest when its drain fell behind, and frames over it were lost at 2 Gbit/s but not when the excess came at about 15 datagrams a millisecond (docs/perf/live-5k120-loss.md). 112 datagrams of 1452 bytes leave a margin.
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 ¶
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 ¶
Fingerprint is the SHA-256 of a DER certificate.
func InsecureClientTLS ¶
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 ¶
PacketBufLen returns the buffer size for one packet of shardSize bytes, with headroom for the AEAD header in front and the tag behind.
func QUICConfig ¶
QUICConfig is the control/datagram connection config shared by both peers.
func SelfSignedServerTLS ¶
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.
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
// RefInvalidation offers wire.FeatureRefInvalidate: the application
// sends wire.RefInvalidate for each lost frame and skips frames up to
// the next Recovery one. With a host that offers it too, the session
// sends no PLI for a lost frame.
RefInvalidation bool
// Calibration dials for a calibration session: a host whose Hello
// lacks wire.FeatureCalibration is refused with
// ErrCalibrationUnsupported before any stream is asked for.
Calibration 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 ¶
DirectionKey is the key material for one direction of a media session.
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 ¶
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 ¶
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 ¶
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
type Impairment ¶
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 ¶
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.
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)
type Pacer ¶
type Pacer struct {
// contains filtered or unexported fields
}
Pacer spaces packets at a byte rate, letting up to a burst of bytes go back to back. A zero rate sends every packet immediately. Not safe for concurrent use; it does not allocate.
func (*Pacer) Reserve ¶ added in v0.2.0
Reserve is Wait without the sleep: it books n bytes and returns the Mono time to sleep until before they go, or 0 to send now. A sender that batches packets flushes its batch before it sleeps.
func (*Pacer) SetRate ¶ added in v0.2.0
SetRate changes the rate and the burst; packets already sent keep their place.
func (*Pacer) Wait ¶
Wait blocks until a packet of n bytes may go out. Past a burst it sleeps until half a burst is due, so packets leave in short trains a few tens of microseconds apart: one per packet would spin a core for the whole frame, as no OS sleeps that briefly. A sender that fell behind (a late wake, a gap between frames) starts again from now, not with a catch-up burst.
type Pacing ¶ added in v0.2.0
type Pacing struct {
Pacing spreads each video frame's datagrams over a share of the frame interval, so a frame does not reach the NIC, the switch and the receiver's socket as one burst at line rate. The zero value sends unpaced.
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 ¶
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 ProbeSpec ¶ added in v0.2.0
ProbeSpec asks the host for Count datagrams of Size bytes, AEAD sealing included, paced at RateKbps or back to back at 0.
type ProbeTrain ¶ added in v0.2.0
ProbeTrain is what a probe train did: Sent datagrams went out SendNs from the first to the last, and Arrivals holds each one's arrival on the client's Mono clock, 0 for one lost.
func (ProbeTrain) Prefix ¶ added in v0.2.0
func (t ProbeTrain) Prefix() int
Prefix counts the datagrams that arrived before the first one lost.
func (ProbeTrain) Received ¶ added in v0.2.0
func (t ProbeTrain) Received() int
Received counts the datagrams that arrived.
func (ProbeTrain) Span ¶ added in v0.2.0
func (t ProbeTrain) Span() time.Duration
Span is from the first arrival to the last.
type PushResult ¶
type PushResult struct {
FrameID uint32
SliceReady bool
SliceIndex int
SliceRecovered bool
FrameComplete bool
}
PushResult says what one packet completed.
type Reassembler ¶
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) PartialFrame ¶
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).
type ReceiveQueue ¶ added in v0.2.0
type ReceiveQueue struct {
Bytes, DrainMbps int
}
ReceiveQueue is a receiver whose path below the socket holds Bytes and at times drains them at no more than DrainMbps: a frame of Bytes plus x is spread over at least the time DrainMbps takes to carry x, or what does not fit is dropped.
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)
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 ¶
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.
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
// RefInvalidation offers wire.FeatureRefInvalidate: the Control
// handler takes wire.RefInvalidate and marks the frame encoded after it
// Recovery.
RefInvalidation bool
// DisplayPhase offers wire.FeatureDisplayPhase: the Control handler
// takes wire.DisplayPhase.
DisplayPhase bool
// Calibration offers wire.FeatureCalibration: sessions answer a
// client's ProbeRequest with a probe train.
Calibration 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 ¶
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 ¶
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) FirstArrival ¶
FirstArrival is when the first datagram of a recent frame was read (client only). Call it from a media handler.
func (*Session) KeyframeRequested ¶
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 (*Session) PeerCapabilities ¶
PeerCapabilities is the JSON the peer sent in wire.Capabilities, or nil when one end does not have wire.FeatureCapabilities.
func (*Session) PeerFeatures ¶
func (*Session) PeerFingerprint ¶
func (*Session) Ping ¶ added in v0.2.0
Ping sends n pings every apart and returns the round trips of the pongs that came back by the time the last one is due (client only).
func (*Session) Probe ¶ added in v0.2.0
Probe asks a host with wire.FeatureCalibration for a train of probe datagrams and returns what arrived (client only). One train runs at a time; ctx ends the wait.
func (*Session) RefInvalidation ¶ added in v0.2.0
RefInvalidation reports whether both ends offered wire.FeatureRefInvalidate: lost frames are recovered with RefInvalidate and Recovery frames, not keyframes.
func (*Session) RemoteControlAddr ¶
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 ¶
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 ¶
SendControl queues a control message. It does not block.
func (*Session) SendInput ¶
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 ¶
SendRumble sends a gamepad rumble command (host only).
func (*Session) SendVideoFrame ¶
SendVideoFrame sends a whole encoded frame, split into info.SliceCount slices (the session's configured count if zero).
func (*Session) SendVideoSlice ¶
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) SetPacing ¶ added in v0.2.0
SetPacing changes how video datagrams are spread over each frame's interval (host only); the zero Pacing sends them unpaced.
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) SocketBuffers ¶ added in v0.2.0
func (s *Session) SocketBuffers() SocketBuffers
SocketBuffers are the media socket's buffer sizes the kernel granted.
func (*Session) Stats ¶
func (s *Session) Stats() SessionStats
func (*Session) TargetBitrateKbps ¶
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
// ShardsExpected and ShardsReceived count a client's video shards
// before FEC, as each frame leaves the reassembly window: the loss the
// host's parity is sized for.
ShardsExpected, ShardsReceived uint64
}
SessionStats are cumulative counters.
type SocketBuffers ¶ added in v0.2.0
type SocketBuffers struct {
Recv, Send int
}
SocketBuffers are the receive and send buffer sizes the kernel granted a media socket, as getsockopt reads them back (Linux reports twice the size asked for, its bookkeeping included).