Documentation
¶
Overview ¶
Package srt provides an interface for network I/O using the SRT protocol (https://github.com/Haivision/srt).
The package gives access to the basic interface provided by the Dial, Listen, and Accept functions and the associated Conn and Listener interfaces.
The Dial function connects to a server:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
conn, err := srt.Dial(ctx, "srt", "golang.org:6000", srt.Config{
StreamId: "...",
}, &wg)
if err != nil {
// handle error
}
buffer := make([]byte, 2048)
for {
n, err := conn.Read(buffer)
if err != nil {
// handle error
}
// handle received data
}
conn.Close()
The Listen function creates servers:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
ln, err := srt.Listen(ctx, "srt", ":6000", srt.Config{...}, &wg)
if err != nil {
// handle error
}
for {
conn, mode, err := ln.Accept(handleConnect)
if err != nil {
// handle error
}
if mode == srt.REJECT {
// rejected connection, ignore
continue
}
if mode == srt.PUBLISH {
go handlePublish(conn)
} else {
go handleSubscribe(conn)
}
}
The ln.Accept function expects a function that takes a srt.ConnRequest and returns a srt.ConnType. The srt.ConnRequest lets you retrieve the streamid with on which you can decide what mode (srt.ConnType) to return.
Check out the Server type that wraps the Listen and Accept into a convenient framework for your own SRT server.
Index ¶
- Constants
- Variables
- func DialControl(config Config) func(network string, address string, c syscall.RawConn) error
- func GetAckEntry() *ackEntry
- func GetBuffer() *[]byte
- func GetRecvBufferPool() *sync.Pool
- func IoUringAvailable() (bool, error)
- func IoUringKernelVersion() (*giouring.KernelVersion, error)
- func ListenControl(config Config) func(network, address string, c syscall.RawConn) error
- func PutAckEntries(entries []*ackEntry)
- func PutAckEntry(e *ackEntry)
- func PutBuffer(buf *[]byte)
- func ValidateBufferSize(size int) bool
- type AcceptFunc
- type Config
- type Conn
- type ConnRequest
- type ConnType
- type ExtendedStatistics
- type Listener
- type Log
- type Logger
- type PubSub
- type PubSubConfig
- type RTOMode
- type RejectionReason
- type Server
- type ServerConfig
- type Statistics
- type StatisticsAccumulated
- type StatisticsInstantaneous
- type StatisticsInterval
Constants ¶
const ( UDP_HEADER_SIZE = 28 SRT_HEADER_SIZE = 16 MIN_MSS_SIZE = 76 MAX_MSS_SIZE = 1500 MIN_PAYLOAD_SIZE = MIN_MSS_SIZE - UDP_HEADER_SIZE - SRT_HEADER_SIZE MAX_PAYLOAD_SIZE = MAX_MSS_SIZE - UDP_HEADER_SIZE - SRT_HEADER_SIZE MIN_PASSPHRASE_SIZE = 10 MAX_PASSPHRASE_SIZE = 80 MAX_STREAMID_SIZE = 512 SRT_VERSION = 0x010401 )
const MaxPayloadBufferSize = 1500
MaxPayloadBufferSize is the standard MTU size for Ethernet. All receive buffers are this size to ensure they can hold any valid SRT packet. Exported so applications can validate payload sizes before sending.
Reference: lockless_sender_design.md Section 6.2
Variables ¶
var ErrClientClosed = errors.New("srt: client closed")
ErrClientClosed is returned when the client connection has been voluntarily closed.
var ErrListenerClosed = errors.New("srt: listener closed")
ErrListenerClosed is returned when the listener is about to shutdown.
var ErrServerClosed = errors.New("srt: server closed")
ErrServerClosed is returned when the server is about to shutdown.
var PayloadBufferPool = &sync.Pool{ New: func() any { buf := make([]byte, MaxPayloadBufferSize) return &buf }, }
PayloadBufferPool is the shared pool for all receive AND send buffers. This single pool serves ALL listeners, dialers, and senders in the process, enabling maximum buffer reuse across connections.
Design rationale:
- Single pool = maximum sharing between all connections
- Fixed 1500-byte size = standard Ethernet MTU, fits all SRT packets
- Buffers flow freely between listeners, dialers, senders, and connections
- Reduces GC pressure by reusing allocations
- Sender zero-copy: application acquires buffer, fills it, sends, ACK returns to pool
Usage (receive):
bufPtr := GetRecvBufferPool().Get().(*[]byte) n, addr, _ := conn.ReadFrom(*bufPtr) // ... use buffer ... GetRecvBufferPool().Put(bufPtr)
Usage (send - zero-copy):
bufPtr := GetBuffer() copy((*bufPtr)[:payloadLen], data) packet.SetPayload(bufPtr) // Packet now owns buffer sender.Push(packet) // Buffer returned to pool when ACK'd
Reference: lockless_sender_design.md Section 6.2
Functions ¶
func DialControl ¶
func GetAckEntry ¶
func GetAckEntry() *ackEntry
GetAckEntry retrieves an ackEntry from the pool. The entry is reset to zero values.
func GetBuffer ¶
func GetBuffer() *[]byte
GetBuffer acquires a buffer from the global pool. The buffer is 1500 bytes (MaxPayloadBufferSize). Caller is responsible for returning it via PutBuffer() or packet.Decommission().
For zero-copy sending:
- Call GetBuffer() to acquire a buffer
- Fill the buffer with payload data (up to MaxPayloadSize bytes)
- Create a packet with the buffer
- Call sender.Push(packet)
- Buffer is automatically returned to pool when ACK'd or dropped
Reference: lockless_sender_design.md Section 6.2
func GetRecvBufferPool ¶
GetRecvBufferPool returns the shared receive buffer pool. All listeners and dialers should use this single pool for receive operations.
The returned pool contains *[]byte pointers to 1500-byte buffers.
func IoUringAvailable ¶
IoUringAvailable checks if io_uring is available on the system. Returns true if the kernel version is >= 5.1 (minimum required for io_uring). Returns an error if kernel version cannot be determined.
func IoUringKernelVersion ¶
func IoUringKernelVersion() (*giouring.KernelVersion, error)
IoUringKernelVersion returns the current kernel version information. Returns an error if kernel version cannot be determined.
func ListenControl ¶
func PutAckEntries ¶
func PutAckEntries(entries []*ackEntry)
PutAckEntries returns multiple ackEntry objects to the pool.
func PutBuffer ¶
func PutBuffer(buf *[]byte)
PutBuffer returns a buffer to the global pool. Use this only if you acquired a buffer but didn't use it for a packet. For packets, use packet.Decommission() instead (handles both packet and buffer).
func ValidateBufferSize ¶
ValidateBufferSize checks if a size fits in the buffer pool. This is more permissive than ValidatePayloadSize - allows up to full MTU.
Types ¶
type AcceptFunc ¶
type AcceptFunc func(req ConnRequest) ConnType
AcceptFunc receives a connection request and returns the type of connection and is required by the Listener for each Accept of a new connection.
type Config ¶
type Config struct {
// Type of congestion control. 'live' or 'file'
// SRTO_CONGESTION
Congestion string
// Connection timeout.
// SRTO_CONNTIMEO
ConnectionTimeout time.Duration
// Enable drift tracer.
// SRTO_DRIFTTRACER
DriftTracer bool
// Reject connection if parties set different passphrase.
// SRTO_ENFORCEDENCRYPTION
EnforcedEncryption bool
// Flow control window size. Packets.
// SRTO_FC
FC uint32
// Accept group connections.
// SRTO_GROUPCONNECT
GroupConnect bool
// Group stability timeout.
// SRTO_GROUPSTABTIMEO
GroupStabilityTimeout time.Duration
// Input bandwidth. Bytes.
// SRTO_INPUTBW
InputBW int64
// IP socket type of service
// SRTO_IPTOS
IPTOS int
// Defines IP socket "time to live" option.
// SRTO_IPTTL
IPTTL int
// Allow only IPv6.
// SRTO_IPV6ONLY
IPv6Only int
// Duration of Stream Encryption key switchover. Packets.
// SRTO_KMPREANNOUNCE
KMPreAnnounce uint64
// Stream encryption key refresh rate. Packets.
// SRTO_KMREFRESHRATE
KMRefreshRate uint64
// Defines the maximum accepted transmission latency.
// SRTO_LATENCY
Latency time.Duration
// Packet reorder tolerance.
// SRTO_LOSSMAXTTL
LossMaxTTL uint32
// Bandwidth limit in bytes/s.
// SRTO_MAXBW
MaxBW int64
// Enable SRT message mode.
// SRTO_MESSAGEAPI
MessageAPI bool
// Minimum input bandwidth
// This option is effective only if both SRTO_MAXBW and SRTO_INPUTBW are set to 0. It controls the minimum allowed value of the input bitrate estimate.
// SRTO_MININPUTBW
MinInputBW int64
// Minimum SRT library version of a peer.
// SRTO_MINVERSION
MinVersion uint32
// MTU size
// SRTO_MSS
MSS uint32
// Enable periodic NAK reports
// SRTO_NAKREPORT
NAKReport bool
// Limit bandwidth overhead, percents
// SRTO_OHEADBW
OverheadBW int64
// Set up the packet filter.
// SRTO_PACKETFILTER
PacketFilter string
// Password for the encrypted transmission.
// SRTO_PASSPHRASE
Passphrase string
// Maximum payload size. Bytes.
// SRTO_PAYLOADSIZE
PayloadSize uint32
// Crypto key length in bytes.
// SRTO_PBKEYLEN
PBKeylen int
// Peer idle timeout.
// SRTO_PEERIDLETIMEO
PeerIdleTimeout time.Duration
// KeepaliveThreshold is the fraction of PeerIdleTimeout at which to send
// proactive keepalive packets. This keeps connections alive during idle periods.
// Default: 0.75 (75% of PeerIdleTimeout).
// Set to 0 or negative to disable proactive keepalives.
// Valid range: 0.0 to 1.0 (0 = disabled, values >= 1.0 are treated as disabled)
KeepaliveThreshold float64
// Minimum receiver latency to be requested by sender.
// SRTO_PEERLATENCY
PeerLatency time.Duration
// Receiver buffer size. Bytes.
// SRTO_RCVBUF
ReceiverBufferSize uint32
// Receiver-side latency.
// SRTO_RCVLATENCY
ReceiverLatency time.Duration
// Sender buffer size. Bytes.
// SRTO_SNDBUF
SendBufferSize uint32
// Sender's delay before dropping packets.
// SRTO_SNDDROPDELAY
SendDropDelay time.Duration
// Stream ID (settable in caller mode only, visible on the listener peer)
// SRTO_STREAMID
StreamId string
// InstanceName is a user-defined label for this connection/server instance
// Used in logging, metrics labels, and JSON statistics output
// Default: "" (empty = not set)
InstanceName string
// Drop too late packets.
// SRTO_TLPKTDROP
TooLatePacketDrop bool
// Transmission type. 'live' or 'file'.
// SRTO_TRANSTYPE
TransmissionType string
// Timestamp-based packet delivery mode.
// SRTO_TSBPDMODE
TSBPDMode bool
// An implementation of the Logger interface
Logger Logger
// if a new IP starts sending data on an existing socket id, allow it
AllowPeerIpChange bool
// Enable io_uring for per-connection send queues (requires Linux kernel 5.1+)
// When enabled, each connection uses its own io_uring ring for asynchronous sends
IoUringEnabled bool
// Size of the io_uring ring for per-connection send queues (must be power of 2, 16-1024)
// Default: 64. Smaller rings use less memory but may limit throughput per connection
IoUringSendRingSize int
// Size of the network queue channel buffer (packets from network)
// Default: 1024. Larger buffers reduce packet drops but use more memory
NetworkQueueSize int
// Size of the write queue channel buffer (packets from application writes)
// Default: 1024. Larger buffers reduce write blocking but use more memory
WriteQueueSize int
// Size of the read queue channel buffer (packets ready for application reads)
// Default: 1024. Larger buffers reduce read blocking but use more memory
ReadQueueSize int
// Size of the receive queue channel buffer (packets from network before routing to connections)
// Used by listener and dialer. Default: 2048. Larger buffers reduce packet drops but use more memory
ReceiveQueueSize int
// Packet reordering algorithm for congestion control receiver
// "list" (default) uses container/list.List - simpler, O(n) insertions
// "btree" uses github.com/google/btree - better for large buffers/high reordering, O(log n) operations
PacketReorderAlgorithm string
// B-tree degree for packet reordering (only used if PacketReorderAlgorithm == "btree")
// Default: 32. Higher values use more memory but may reduce tree height
BTreeDegree int
// Enable io_uring for receive operations (requires Linux kernel 5.1+)
// When enabled, replaces blocking ReadFrom() with asynchronous io_uring RecvMsg
IoUringRecvEnabled bool
// Size of the io_uring receive ring (must be power of 2, 64-32768)
// Default: 512. Larger rings allow more pending receives but use more memory
IoUringRecvRingSize int
// Initial number of pending receive requests at startup
// Default: ring size (full ring). Must be <= IoUringRecvRingSize
IoUringRecvInitialPending int
// Batch size for resubmitting receive requests after completions
// Default: 256. Larger batches reduce syscall overhead but increase latency
IoUringRecvBatchSize int
// Number of io_uring receive rings to create (default: 1)
// Multiple rings allow parallel completion processing
// Valid values: 1-16 (power of 2 recommended)
// Reference: multi_iouring_design.md Phase 1
IoUringRecvRingCount int
// Number of io_uring send rings per connection (default: 1)
// Multiple rings allow parallel send completion processing
// Valid values: 1-8 (power of 2 recommended)
// Reference: multi_iouring_design.md Phase 1
IoUringSendRingCount int
// Statistics print interval for server connections
// If > 0, server will periodically print statistics for all active connections
// Default: 0 (disabled). Set to e.g. 10s to print statistics every 10 seconds
StatisticsPrintInterval time.Duration
// Metrics configuration
// Enable metrics collection and expose /metrics endpoint
MetricsEnabled bool
// HTTP address for /metrics endpoint (e.g., ":9090")
// If empty, metrics server is not started
// Default: "" (disabled)
MetricsListenAddr string
// Handshake timeout for complete handshake exchange (induction + conclusion)
// Must be less than PeerIdleTimeout
// Default: 1.5 seconds (SRT is designed for low loss/low RTT networks)
HandshakeTimeout time.Duration
// Shutdown delay - time to wait for graceful shutdown after signal before application exit
// Default: 5 seconds
ShutdownDelay time.Duration
// Local address to bind to when dialing (client only)
// Format: "IP" or "IP:port" (e.g., "127.0.0.20" or "127.0.0.20:0")
// If empty, the system chooses an ephemeral address
// Only used by Dial(), not Listen()
LocalAddr string
// Timer intervals (replaces hardcoded 10ms/20ms values)
// TickIntervalMs is the TSBPD delivery tick interval in milliseconds
// Default: 10. Lower = lower latency but higher CPU. Higher = higher latency but lower CPU.
TickIntervalMs uint64
// PeriodicNakIntervalMs is the periodic NAK timer interval in milliseconds
// Default: 20. Lower = faster loss recovery but more NAK overhead.
PeriodicNakIntervalMs uint64
// PeriodicAckIntervalMs is the periodic ACK timer interval in milliseconds
// Default: 10.
PeriodicAckIntervalMs uint64
// SendDropIntervalMs is the sender drop ticker interval in milliseconds
// Controls how often the sender checks for and drops too-old packets.
// Default: 100. Higher values reduce CPU but may delay dropping stale packets.
SendDropIntervalMs uint64
// EventLoopRateIntervalMs is the rate calculation interval in milliseconds
// Controls how often throughput/rate statistics are calculated in EventLoop mode.
// Default: 1000 (1 second).
EventLoopRateIntervalMs uint64
// UseNakBtree enables the NAK btree for efficient gap detection
// Auto-set to true when IoUringRecvEnabled=true
UseNakBtree bool
// SuppressImmediateNak prevents immediate NAK on gap detection
// Auto-set to true when IoUringRecvEnabled=true (required to handle io_uring reordering)
SuppressImmediateNak bool
// NakRecentPercent is the percentage of TSBPD delay for "too recent" threshold
// Packets within this threshold won't be added to NAK btree yet
// Default: 0.10 (10% of TSBPD delay)
NakRecentPercent float64
// NakMergeGap is the maximum sequence gap to merge in NAK consolidation
// Adjacent missing sequences within this gap are merged into ranges
// Default: 3
NakMergeGap uint32
// NakConsolidationBudgetUs is the max time for NAK consolidation in microseconds
// Default: 2000 (2ms)
NakConsolidationBudgetUs uint64
// FastNakEnabled enables the FastNAK optimization
// When enabled, NAK is triggered immediately after silent period ends
// Default: true when NAK btree is enabled
FastNakEnabled bool
// FastNakThresholdMs is the silent period to trigger FastNAK in milliseconds
// Default: 50ms (typical Starlink outage is ~60ms)
FastNakThresholdMs uint64
// FastNakRecentEnabled adds recent gap immediately on FastNAK trigger
// Detects sequence jump after outage and adds missing range to NAK btree
// Default: true
FastNakRecentEnabled bool
// HonorNakOrder makes sender retransmit packets in NAK packet order
// When enabled, oldest/most-urgent packets are retransmitted first
// Default: false (existing behavior: newest-first)
HonorNakOrder bool
// RTOMode controls how RTO is calculated for NAK/retransmit suppression.
// Options:
// RTORttRttVar (0, default): RTT + RTTVar (balanced)
// RTORtt4RttVar (1): RTT + 4*RTTVar (RFC 6298 conservative)
// RTORttRttVarMargin (2): (RTT + RTTVar) * (1 + ExtraRTTMargin)
// Default: RTORttRttVar
RTOMode RTOMode
// ExtraRTTMargin is the extra margin for RTORttRttVarMargin mode.
// Specified as a multiplier (0.1 = 10% extra margin).
// Only used when RTOMode = RTORttRttVarMargin.
// Default: 0.10 (10%)
ExtraRTTMargin float64
// NakExpiryMargin adds extra margin when expiring NAK btree entries.
// Specified as a percentage (0.1 = 10% extra margin).
//
// Formula: expiryThreshold = now + (RTO * (1 + NakExpiryMargin))
//
// Higher values = more conservative (keep NAK entries longer, favor recovery).
// Lower values = more aggressive (expire entries earlier, reduce phantom NAKs).
//
// Values:
// 0.0: Baseline - expire at exactly now + RTO
// 0.05: 5% margin - slightly conservative
// 0.10: 10% margin (default) - moderately conservative
// 0.25: 25% margin - more conservative
// 0.50: 50% margin - very conservative (high-jitter networks)
//
// Default: 0.10 (10% - prefer potential repair over phantom NAK reduction)
NakExpiryMargin float64
// EWMAWarmupThreshold is the minimum number of packets needed before
// inter-packet interval EWMA is considered "warm" (reliable).
//
// Rationale:
// - EWMA with α=0.125 reaches ~95% of true value after ~24 samples
// - Default of 32 provides safety margin for variance
// - At 1000 pps, this is only 32ms of data
// - At 100 pps (low bitrate), this is 320ms
//
// Values:
// 0: Disable warm-up check (always use EWMA, even if cold)
// 16: Fast warm-up (high-rate streams, less accuracy)
// 32: Default (balanced)
// 64: Slow warm-up (low-rate streams, more accuracy)
//
// During warm-up (sampleCount < threshold), we use conservative
// fallback estimation (tsbpdDelay as worst-case estimate).
//
// Default: 32
EWMAWarmupThreshold uint32
// UseSendBtree enables btree for sender packet storage.
// When enabled, replaces linked lists with O(log n) btree operations.
// Provides faster NAK lookup and ACK processing.
// Default: false (use linked lists)
UseSendBtree bool
// SendBtreeDegree is the B-tree degree for sender packet storage.
// Higher values use more memory but may reduce tree height.
// Default: 32 (same as receiver btree)
SendBtreeDegree int
// UseSendRing enables lock-free ring for sender Push() operations.
// When enabled, Push() writes to ring (lock-free), Tick()/EventLoop drains to btree.
// REQUIRES: UseSendBtree=true
// Default: false
UseSendRing bool
// SendRingSize is the ring capacity per shard.
// Will be rounded to power of 2 by the ring library.
// Default: 1024
SendRingSize int
// SendRingShards is the number of ring shards.
// - 1 shard: strict FIFO ordering (default, suitable for single producer)
// - N shards: higher throughput with multiple producers (btree sorts by seq#)
// Default: 1 (preserves strict ordering)
SendRingShards int
// UseSendControlRing enables lock-free ring for ACK/NAK routing.
// When enabled, control packets are queued to EventLoop via ring.
// CRITICAL: Required for lock-free sender EventLoop.
// REQUIRES: UseSendRing=true
// Default: false
UseSendControlRing bool
// SendControlRingSize is the control ring capacity per shard.
// Will be rounded to power of 2 by the ring library.
// Default: 256
SendControlRingSize int
// SendControlRingShards is the number of control ring shards.
// Default: 1 (unified with receiver)
SendControlRingShards int
// UseRecvControlRing enables lock-free ring for ACKACK/KEEPALIVE routing.
// When enabled with UseEventLoop, the receiver is completely lock-free.
// Default: false (for backward compatibility)
UseRecvControlRing bool
// RecvControlRingSize is the receiver control ring capacity per shard.
// Will be rounded to power of 2 by the ring library.
// Default: 128
RecvControlRingSize int
// RecvControlRingShards is the number of receiver control ring shards.
// Default: 1
RecvControlRingShards int
// UseSendEventLoop enables continuous event loop for sender.
// When enabled, replaces Tick() with continuous EventLoop.
// REQUIRES: UseSendBtree, UseSendRing, UseSendControlRing all enabled.
// Default: false
UseSendEventLoop bool
// SendEventLoopBackoffMinSleep is minimum sleep during idle periods.
// Default: 100µs
SendEventLoopBackoffMinSleep time.Duration
// SendEventLoopBackoffMaxSleep is maximum sleep during idle periods.
// Default: 1ms
SendEventLoopBackoffMaxSleep time.Duration
// SendTsbpdSleepFactor is the multiplier for TSBPD-aware sleep.
// Sleep = nextDeliveryIn * SendTsbpdSleepFactor
// Default: 0.9 (wake up slightly before next packet is due)
SendTsbpdSleepFactor float64
// SendDropThresholdUs is the threshold for dropping old packets (microseconds).
// Packets older than this are dropped.
// Default: 1000000 (1 second)
SendDropThresholdUs uint64
// UseAdaptiveBackoff enables adaptive Yield/Sleep mode switching in EventLoop.
// When true (default with EventLoop), starts in Yield mode (~6M ops/sec) for
// high throughput, automatically switches to Sleep mode (~1K ops/sec) when idle.
// Default: true when EventLoop is enabled
UseAdaptiveBackoff bool
// AdaptiveBackoffIdleThreshold is the duration without activity before switching to Sleep.
// Only used when UseAdaptiveBackoff is true.
// Default: 1 second
AdaptiveBackoffIdleThreshold time.Duration
// EventLoopMaxDataPerIteration caps data packets processed per EventLoop iteration.
// When > 0, enables "tight loop" mode: control ring is checked after EVERY data packet.
// This provides minimum control latency (~500ns) at negligible overhead (~0.006%).
// When 0, uses legacy unbounded drain (control latency can be 1-2ms).
// Default: 512 (tight loop enabled)
EventLoopMaxDataPerIteration int
// ValidateSendPayloadSize enables payload size validation in Push().
// When enabled, payloads exceeding MaxPayloadSize (1316 bytes) are rejected.
// This prevents buffer overflows when using pooled buffers.
// Default: false (no validation for backward compatibility)
ValidateSendPayloadSize bool
// SendFilter is an optional function called before each packet is sent.
// If set and returns false, the packet is dropped (not sent).
// This is primarily for testing (e.g., simulating packet loss).
// Must be set BEFORE Dial()/Accept() - cannot be modified after connection starts.
// Default: nil (no filtering)
SendFilter func(p packet.Packet) bool `json:"-"` // Not serializable
// UsePacketRing enables lock-free ring buffer for packet handoff between
// io_uring completion handlers and the receiver Tick() event loop.
// When enabled, Push() writes to the ring (lock-free), and Tick() drains
// the ring before processing (single-threaded, no locks needed).
// Default: false (use legacy locked path)
UsePacketRing bool
// PacketRingSize is the capacity of the lock-free ring buffer (per shard).
// Total ring capacity = PacketRingSize * PacketRingShards
// Must be a power of 2. Default: 1024
PacketRingSize int
// PacketRingShards is the number of shards for the lock-free ring.
// More shards reduce contention between concurrent producers.
// Must be a power of 2. Default: 4
PacketRingShards int
// PacketRingMaxRetries is the maximum number of immediate retries
// before starting backoff when the ring is full.
// Default: 10
PacketRingMaxRetries int
// PacketRingBackoffDuration is the delay between backoff retries
// when the ring is full.
// Default: 100µs
PacketRingBackoffDuration time.Duration
// PacketRingMaxBackoffs is the maximum number of backoff iterations
// before giving up and dropping the packet.
// 0 = unlimited (keep retrying until success)
// Default: 0
PacketRingMaxBackoffs int
// PacketRingRetryStrategy determines how ring writes handle full shards.
// Options:
// "" or "sleep" - SleepBackoff: retry same shard, then sleep (default)
// "next" - NextShard: try all shards before sleeping
// "random" - RandomShard: try random shards (best load distribution)
// "adaptive" - AdaptiveBackoff: exponential backoff with jitter
// "spin" - SpinThenYield: yield CPU instead of sleep (lowest latency)
// "hybrid" - Hybrid: NextShard + AdaptiveBackoff
// "autoadaptive" or "auto" - AutoAdaptive: Yield when active, Sleep when idle
// ⭐ RECOMMENDED for high-throughput (>300 Mb/s) scenarios
// Default: "" (uses SleepBackoff)
PacketRingRetryStrategy string
// UseEventLoop enables continuous event loop processing instead of
// timer-driven Tick() for lower latency and smoother CPU utilization.
// When enabled, packets are processed immediately as they arrive from
// the ring buffer, and delivered as soon as TSBPD allows.
// REQUIRES: UsePacketRing=true (event loop consumes from ring)
// Default: false (use timer-driven Tick())
UseEventLoop bool
// EventLoopRateInterval is the interval for rate metric calculation
// in the event loop. Uses a separate ticker from ACK/NAK.
// Default: 1s
EventLoopRateInterval time.Duration
// BackoffColdStartPkts is the number of packets to receive before
// the adaptive backoff engages. During cold start, minimum sleep
// is used to ensure responsiveness during connection establishment.
// Default: 1000
BackoffColdStartPkts int
// BackoffMinSleep is the minimum sleep duration during idle periods
// in the event loop. Lower values = more responsive, higher CPU.
// Default: 10µs
BackoffMinSleep time.Duration
// BackoffMaxSleep is the maximum sleep duration during idle periods
// in the event loop. Higher values = lower CPU, less responsive.
// Default: 1ms
BackoffMaxSleep time.Duration
// LightACKDifference controls how often Light ACK packets are sent.
// A Light ACK is sent when the contiguous sequence has advanced by
// at least this many packets since the last Light ACK.
// RFC recommends 64, but higher values reduce overhead at high bitrates.
// Default: 64 (RFC recommendation)
// Suggested for high bitrate (200Mb/s+): 256
// Range: 1-5000
LightACKDifference uint32
// ReceiverDebug enables debug logging in the receiver for investigation.
// When enabled, receiver logs NAK dispatch decisions, ring buffer operations,
// and gap detection events. Uses the connection's logging function.
// Default: false (no debug logging)
ReceiverDebug bool
}
Config is the configuration for a SRT connection
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the default configuration for Dial and Listen.
func (*Config) ApplyAutoConfiguration ¶
func (c *Config) ApplyAutoConfiguration()
ApplyAutoConfiguration sets internal configuration based on other settings. Call this after user configuration is applied but before connection creation. This ensures that when io_uring recv is enabled, the NAK btree and related features are automatically configured.
func (*Config) MarshalQuery ¶
MarshalQuery returns the corresponding query string for a configuration.
func (*Config) MarshalURL ¶
MarshalURL returns the SRT URL for this config and the given address (host:port).
func (*Config) UnmarshalQuery ¶
UnmarshalQuery parses a query string and interprets it as a configuration for a SRT connection. The key in each key/value pair corresponds to the respective field in the Config type, but with only lower case letters. Bool values can be represented as "true"/"false", "on"/"off", "yes"/"no", or "0"/"1".
func (*Config) UnmarshalURL ¶
UnmarshalURL takes a SRT URL and parses out the configuration. A SRT URL is srt://[host]:[port]?[key1]=[value1]&[key2]=[value2]... It returns the host:port of the URL.
type Conn ¶
type Conn interface {
// Read reads data from the connection.
// Read can be made to time out and return an error after a fixed
// time limit; see SetDeadline and SetReadDeadline.
Read(p []byte) (int, error)
// ReadPacket reads a packet from the queue of received packets. It blocks
// if the queue is empty. Only data packets are returned. Using ReadPacket
// and Read at the same time may lead to data loss.
ReadPacket() (packet.Packet, error)
// Write writes data to the connection.
// Write can be made to time out and return an error after a fixed
// time limit; see SetDeadline and SetWriteDeadline.
Write(p []byte) (int, error)
// WritePacket writes a packet to the write queue. Packets on the write queue
// will be sent to the peer of the connection. Only data packets will be sent.
WritePacket(p packet.Packet) error
// Close closes the connection.
// Any blocked Read or Write operations will be unblocked and return errors.
Close() error
// LocalAddr returns the local network address. The returned net.Addr is not shared by other invocations of LocalAddr.
LocalAddr() net.Addr
// RemoteAddr returns the remote network address. The returned net.Addr is not shared by other invocations of RemoteAddr.
RemoteAddr() net.Addr
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
// SocketId return the socketid of the connection.
SocketId() uint32
// PeerSocketId returns the socketid of the peer of the connection.
PeerSocketId() uint32
// StreamId returns the streamid use for the connection.
StreamId() string
// Stats returns accumulated and instantaneous statistics of the connection.
Stats(s *Statistics)
// Version returns the connection version, either 4 or 5. With version 4, the streamid is not available
Version() uint32
// GetExtendedStatistics returns extended statistics that are not part of the standard SRT Statistics struct.
// This includes ACKACK packet counts and retransmissions triggered by NAKs.
// Returns nil if extended statistics are not available.
GetExtendedStatistics() *ExtendedStatistics
// GetPeerIdleTimeoutRemaining returns the remaining time until the peer idle timeout fires.
// Returns 0 if the timer is not active or has already fired.
GetPeerIdleTimeoutRemaining() time.Duration
}
Conn is a SRT network connection.
func Dial ¶
func Dial(ctx context.Context, network, address string, config Config, shutdownWg *sync.WaitGroup) (Conn, error)
Dial connects to the address using the SRT protocol with the given config and returns a Conn interface.
The address is of the form "host:port".
Example:
Dial(ctx, "srt", "127.0.0.1:3000", DefaultConfig(), shutdownWg)
In case of an error the returned Conn is nil and the error is non-nil.
type ConnRequest ¶
type ConnRequest interface {
// RemoteAddr returns the address of the peer. The returned net.Addr
// is a copy and can be used at will.
RemoteAddr() net.Addr
// Version returns the handshake version of the incoming request. Currently
// known versions are 4 and 5. With version 4 the StreamId will always be
// empty and IsEncrypted will always return false. An incoming version 4
// connection will always be publishing.
Version() uint32
// StreamId returns the streamid of the requesting connection. Use this
// to decide what to do with the connection.
StreamId() string
// SocketId return the socketid of the connection.
SocketId() uint32
// PeerSocketId returns the socketid of the peer of the connection.
PeerSocketId() uint32
// IsEncrypted returns whether the connection is encrypted. If it is
// encrypted, use SetPassphrase to set the passphrase for decrypting.
IsEncrypted() bool
// SetPassphrase sets the passphrase in order to decrypt the incoming
// data. Returns an error if the passphrase did not work or the connection
// is not encrypted.
SetPassphrase(p string) error
// SetRejectionReason sets the rejection reason for the connection. If
// no set, REJ_PEER will be used.
//
// Deprecated: replaced by Reject().
SetRejectionReason(r RejectionReason)
// Accept accepts the request and returns a connection.
Accept() (Conn, error)
// Reject rejects the request.
Reject(r RejectionReason)
}
ConnRequest is an incoming connection request
type ConnType ¶
type ConnType int
ConnType represents the kind of connection as returned from the AcceptFunc. It is one of REJECT, PUBLISH, or SUBSCRIBE.
type ExtendedStatistics ¶
type ExtendedStatistics struct {
PktSentACKACK uint64 // Number of ACKACK packets sent
PktRecvACKACK uint64 // Number of ACKACK packets received
PktRetransFromNAK uint64 // Number of packets retransmitted in response to NAKs
}
ExtendedStatistics contains statistics that are not part of the standard SRT Statistics struct. These are retrieved in a single call to minimize lock contention.
type Listener ¶
type Listener interface {
// Accept2 waits for new connections.
// On closing the err will be ErrListenerClosed.
Accept2() (ConnRequest, error)
// Accept waits for new connections. For each new connection the AcceptFunc
// gets called. Conn is a new connection if AcceptFunc is PUBLISH or SUBSCRIBE.
// If AcceptFunc returns REJECT, Conn is nil. In case of failure error is not
// nil, Conn is nil and ConnType is REJECT. On closing the listener err will
// be ErrListenerClosed and ConnType is REJECT.
//
// Deprecated: replaced by Accept2().
Accept(AcceptFunc) (Conn, ConnType, error)
// Close closes the listener. It will stop accepting new connections and
// close all currently established connections.
Close()
// Addr returns the address of the listener.
Addr() net.Addr
}
Listener waits for new connections
func Listen ¶
func Listen(ctx context.Context, network, address string, config Config, shutdownWg *sync.WaitGroup) (Listener, error)
Listen returns a new listener on the SRT protocol on the address with the provided config. The network parameter needs to be "srt".
The address has the form "host:port".
Examples:
Listen(ctx, "srt", "127.0.0.1:3000", DefaultConfig(), shutdownWg)
In case of an error, the returned Listener is nil and the error is non-nil.
type Log ¶
type Log struct {
Time time.Time // Time of when this message has been logged
SocketId uint32 // The socketid if connection related, 0 otherwise
Topic string // The topic of this message
Message string // The message itself
File string // The file in which this message has been dispatched
Line int // The line number in the file in which this message has been dispatched
}
Log represents a log message
type Logger ¶
type Logger interface {
// HasTopic returns whether this Logger is logging messages of that topic.
HasTopic(topic string) bool
// Print adds a new message to the message queue. The message itself is
// a function that returns the string to be logges. It will only be
// executed if HasTopic returns true on the given topic.
Print(topic string, socketId uint32, skip int, message func() string)
// Listen returns a read channel for Log messages.
Listen() <-chan Log
// Close closes the logger. No more messages will be logged.
Close()
}
Logger is for logging debug messages.
type PubSub ¶
type PubSub interface {
// Publish accepts a SRT connection where it reads from. It blocks
// until the connection closes. The returned error indicates why it
// stopped. There can be only one publisher.
Publish(c Conn) error
// Subscribe accepts a SRT connection where it writes the data from
// the publisher to. It blocks until an error happens. If the publisher
// disconnects, io.EOF is returned. There can be an arbitrary number
// of subscribers.
Subscribe(c Conn) error
}
PubSub is a publish/subscriber service for SRT connections.
func NewPubSub ¶
func NewPubSub(config PubSubConfig) PubSub
NewPubSub returns a PubSub. After the publishing connection closed this PubSub can't be used anymore.
type PubSubConfig ¶
type PubSubConfig struct {
Logger Logger // Optional logger
}
PubSubConfig is for configuring a new PubSub
type RTOMode ¶
type RTOMode uint8
RTOMode defines the RTO calculation strategy for NAK/retransmit suppression. Used for both NAK suppression (full RTO) and retransmit suppression (RTO/2).
type RejectionReason ¶
type RejectionReason uint32
RejectionReason are the rejection reasons that can be returned from the AcceptFunc in order to send another reason than the default one (REJ_PEER) to the client.
const ( REJ_UNKNOWN RejectionReason = 1000 // unknown reason REJ_SYSTEM RejectionReason = 1001 // system function error REJ_PEER RejectionReason = 1002 // rejected by peer REJ_RESOURCE RejectionReason = 1003 // resource allocation problem REJ_ROGUE RejectionReason = 1004 // incorrect data in handshake REJ_BACKLOG RejectionReason = 1005 // listener's backlog exceeded REJ_IPE RejectionReason = 1006 // internal program error REJ_CLOSE RejectionReason = 1007 // socket is closing REJ_VERSION RejectionReason = 1008 // peer is older version than agent's min REJ_RDVCOOKIE RejectionReason = 1009 // rendezvous cookie collision REJ_BADSECRET RejectionReason = 1010 // wrong password REJ_UNSECURE RejectionReason = 1011 // password required or unexpected REJ_MESSAGEAPI RejectionReason = 1012 // stream flag collision REJ_CONGESTION RejectionReason = 1013 // incompatible congestion-controller type REJ_FILTER RejectionReason = 1014 // incompatible packet filter REJ_GROUP RejectionReason = 1015 // incompatible group )
Table 7: Handshake Rejection Reason Codes
const ( REJX_BAD_REQUEST RejectionReason = 1400 // General syntax error in the SocketID specification (also a fallback code for undefined cases) REJX_UNAUTHORIZED RejectionReason = 1401 // Authentication failed, provided that the user was correctly identified and access to the required resource would be granted REJX_OVERLOAD RejectionReason = 1402 // The server is too heavily loaded, or you have exceeded credits for accessing the service and the resource. REJX_FORBIDDEN RejectionReason = 1403 // Access denied to the resource by any kind of reason. REJX_NOTFOUND RejectionReason = 1404 // Resource not found at this time. REJX_BAD_MODE RejectionReason = 1405 // The mode specified in `m` key in StreamID is not supported for this request. REJX_UNACCEPTABLE RejectionReason = 1406 // The requested parameters specified in SocketID cannot be satisfied for the requested resource. Also when m=publish and the data format is not acceptable. REJX_CONFLICT RejectionReason = 1407 // The resource being accessed is already locked for modification. This is in case of m=publish and the specified resource is currently read-only. REJX_NOTSUP_MEDIA RejectionReason = 1415 // The media type is not supported by the application. This is the `t` key that specifies the media type as stream, file and auth, possibly extended by the application. REJX_LOCKED RejectionReason = 1423 // The resource being accessed is locked for any access. REJX_FAILED_DEPEND RejectionReason = 1424 // The request failed because it specified a dependent session ID that has been disconnected. REJX_ISE RejectionReason = 1500 // Unexpected internal server error REJX_UNIMPLEMENTED RejectionReason = 1501 // The request was recognized, but the current version doesn't support it. REJX_GW RejectionReason = 1502 // The server acts as a gateway and the target endpoint rejected the connection. REJX_DOWN RejectionReason = 1503 // The service has been temporarily taken over by a stub reporting this error. The real service can be down for maintenance or crashed. REJX_VERSION RejectionReason = 1505 // SRT version not supported. This might be either unsupported backward compatibility, or an upper value of a version. REJX_NOROOM RejectionReason = 1507 // The data stream cannot be archived due to lacking storage space. This is in case when the request type was to send a file or the live stream to be archived. )
These are the extended rejection reasons that may be less well supported Codes & their meanings taken from https://github.com/Haivision/srt/blob/f477af533562505abf5295f059cf2156b17be740/srtcore/access_control.h
type Server ¶
type Server struct {
// The address the SRT server should listen on, e.g. ":6001".
Addr string
// Config is the configuration for a SRT listener.
Config *Config
// HandleConnect will be called for each incoming connection. This
// allows you to implement your own interpretation of the streamid
// and authorization. If this is nil, all connections will be
// rejected.
HandleConnect AcceptFunc
// HandlePublish will be called for a publishing connection.
HandlePublish func(conn Conn)
// HandleSubscribe will be called for a subscribing connection.
HandleSubscribe func(conn Conn)
// Context is the root context for the server. When cancelled, the server will shutdown gracefully.
Context context.Context
// ShutdownWg is the root waitgroup for tracking all shutdown operations.
// When this waitgroup reaches zero, all shutdown operations are complete.
ShutdownWg *sync.WaitGroup
// contains filtered or unexported fields
}
Server is a framework for a SRT server
func NewServer ¶
NewServer creates a new SRT server with the given context and configuration. The context should be the root context that, when cancelled, triggers graceful shutdown. The waitgroup is used to track when the server has fully shutdown.
Example:
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
var wg sync.WaitGroup
server := srt.NewServer(ctx, &wg, srt.ServerConfig{
Addr: ":6001",
Config: &config,
HandleConnect: handleConnect,
HandlePublish: handlePublish,
HandleSubscribe: handleSubscribe,
})
wg.Add(1)
go func() {
defer wg.Done()
if err := server.ListenAndServe(); err != nil && err != srt.ErrServerClosed {
log.Printf("SRT Server: %s", err)
}
}()
func (*Server) GetConnections ¶
GetConnections returns all active connections from the listener. This is safe to call concurrently and returns a snapshot of connections.
func (*Server) Listen ¶
Listen opens the server listener. It returns immediately after the listener is ready.
func (*Server) ListenAndServe ¶
ListenAndServe starts the SRT server. It blocks until an error happens. If the error is ErrServerClosed the server has shutdown normally.
func (*Server) Serve ¶
Serve starts accepting connections. It must be called after Listen(). It blocks until an error happens. If the error is ErrServerClosed the server has shutdown normally. Option 3: Context-Driven Shutdown - Serve() watches context and automatically calls Shutdown() when cancelled.
type ServerConfig ¶
type ServerConfig struct {
// Addr is the address the SRT server should listen on, e.g. ":6001".
Addr string
// Config is the SRT connection configuration.
Config *Config
// HandleConnect will be called for each incoming connection.
// This allows you to implement your own interpretation of the streamid
// and authorization. If nil, all connections will be rejected.
HandleConnect AcceptFunc
// HandlePublish will be called for a publishing connection.
// If nil, a default handler that closes the connection will be used.
HandlePublish func(conn Conn)
// HandleSubscribe will be called for a subscribing connection.
// If nil, a default handler that closes the connection will be used.
HandleSubscribe func(conn Conn)
}
ServerConfig contains configuration for creating a new SRT server.
type Statistics ¶
type Statistics struct {
MsTimeStamp uint64 // The time elapsed, in milliseconds, since the SRT socket has been created
// Accumulated
Accumulated StatisticsAccumulated
// Interval
Interval StatisticsInterval
// Instantaneous
Instantaneous StatisticsInstantaneous
}
Statistics represents the statistics for a connection
type StatisticsAccumulated ¶
type StatisticsAccumulated struct {
PktSent uint64 // The total number of sent DATA packets, including retransmitted packets
PktRecv uint64 // The total number of received DATA packets, including retransmitted packets
PktSentUnique uint64 // The total number of unique DATA packets sent by the SRT sender
PktRecvUnique uint64 // The total number of unique original, retransmitted or recovered by the packet filter DATA packets received in time, decrypted without errors and, as a result, scheduled for delivery to the upstream application by the SRT receiver.
PktSendLoss uint64 // The total number of data packets considered or reported as lost at the sender side. Does not correspond to the packets detected as lost at the receiver side.
PktRecvLoss uint64 // The total number of SRT DATA packets detected as presently missing (either reordered or lost) at the receiver side
PktRetrans uint64 // The total number of retransmitted packets sent by the SRT sender
PktRecvRetrans uint64 // The total number of retransmitted packets registered at the receiver side
PktSentACK uint64 // The total number of sent ACK (Acknowledgement) control packets
PktRecvACK uint64 // The total number of received ACK (Acknowledgement) control packets
PktSentNAK uint64 // The total number of sent NAK (Negative Acknowledgement) control packets
PktRecvNAK uint64 // The total number of received NAK (Negative Acknowledgement) control packets
PktSentKM uint64 // The total number of sent KM (Key Material) control packets
PktRecvKM uint64 // The total number of received KM (Key Material) control packets
UsSndDuration uint64 // The total accumulated time in microseconds, during which the SRT sender has some data to transmit, including packets that have been sent, but not yet acknowledged
PktRecvBelated uint64
PktSendDrop uint64 // The total number of dropped by the SRT sender DATA packets that have no chance to be delivered in time
PktRecvDrop uint64 // The total number of dropped by the SRT receiver and, as a result, not delivered to the upstream application DATA packets
PktRecvUndecrypt uint64 // The total number of packets that failed to be decrypted at the receiver side
ByteSent uint64 // Same as pktSent, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecv uint64 // Same as pktRecv, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteSentUnique uint64 // Same as pktSentUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvUnique uint64 // Same as pktRecvUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvLoss uint64 // Same as pktRecvLoss, but expressed in bytes, including payload and all the headers (IP, TCP, SRT), bytes for the presently missing (either reordered or lost) packets' payloads are estimated based on the average packet size
ByteRetrans uint64 // Same as pktRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvRetrans uint64 // Same as pktRecvRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvBelated uint64
ByteSendDrop uint64 // Same as pktSendDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvDrop uint64 // Same as pktRecvDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvUndecrypt uint64 // Same as pktRecvUndecrypt, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
}
type StatisticsInstantaneous ¶
type StatisticsInstantaneous struct {
UsPktSendPeriod float64 // Current minimum time interval between which consecutive packets are sent, in microseconds
PktFlowWindow uint64 // The maximum number of packets that can be "in flight"
PktFlightSize uint64 // The number of packets in flight
MsRTT float64 // Smoothed round-trip time (SRTT), an exponentially-weighted moving average (EWMA) of an endpoint's RTT samples, in milliseconds
MbpsSentRate float64 // Current transmission bandwidth, in Mbps
MbpsRecvRate float64 // Current receiving bandwidth, in Mbps
MbpsLinkCapacity float64 // Estimated capacity of the network link, in Mbps
ByteAvailSendBuf uint64 // The available space in the sender's buffer, in bytes
ByteAvailRecvBuf uint64 // The available space in the receiver's buffer, in bytes
MbpsMaxBW float64 // Transmission bandwidth limit, in Mbps
ByteMSS uint64 // Maximum Segment Size (MSS), in bytes
PktSendBuf uint64 // The number of packets in the sender's buffer that are already scheduled for sending or even possibly sent, but not yet acknowledged
ByteSendBuf uint64 // Instantaneous (current) value of pktSndBuf, but expressed in bytes, including payload and all headers (IP, TCP, SRT)
MsSendBuf uint64 // The timespan (msec) of packets in the sender's buffer (unacknowledged packets)
MsSendTsbPdDelay uint64 // Timestamp-based Packet Delivery Delay value of the peer
PktRecvBuf uint64 // The number of acknowledged packets in receiver's buffer
ByteRecvBuf uint64 // Instantaneous (current) value of pktRcvBuf, expressed in bytes, including payload and all headers (IP, TCP, SRT)
MsRecvBuf uint64 // The timespan (msec) of acknowledged packets in the receiver's buffer
MsRecvTsbPdDelay uint64 // Timestamp-based Packet Delivery Delay value set on the socket via SRTO_RCVLATENCY or SRTO_LATENCY
PktReorderTolerance uint64 // Instant value of the packet reorder tolerance
PktRecvAvgBelatedTime uint64 // Accumulated difference between the current time and the time-to-play of a packet that is received late
PktSendRetransRate float64 // Retransmission rate: bytesRetrans/bytesSent * 100 (NOT loss rate)
PktRecvRetransRate float64 // Retransmission rate: bytesRetrans/bytesRecv * 100 (NOT loss rate)
}
type StatisticsInterval ¶
type StatisticsInterval struct {
MsInterval uint64 // Length of the interval, in milliseconds
PktSent uint64 // Number of sent DATA packets, including retransmitted packets
PktRecv uint64 // Number of received DATA packets, including retransmitted packets
PktSentUnique uint64 // Number of unique DATA packets sent by the SRT sender
PktRecvUnique uint64 // Number of unique original, retransmitted or recovered by the packet filter DATA packets received in time, decrypted without errors and, as a result, scheduled for delivery to the upstream application by the SRT receiver.
PktSendLoss uint64 // Number of data packets considered or reported as lost at the sender side. Does not correspond to the packets detected as lost at the receiver side.
PktRecvLoss uint64 // Number of SRT DATA packets detected as presently missing (either reordered or lost) at the receiver side
PktRetrans uint64 // Number of retransmitted packets sent by the SRT sender
PktRecvRetrans uint64 // Number of retransmitted packets registered at the receiver side
PktSentACK uint64 // Number of sent ACK (Acknowledgement) control packets
PktRecvACK uint64 // Number of received ACK (Acknowledgement) control packets
PktSentNAK uint64 // Number of sent NAK (Negative Acknowledgement) control packets
PktRecvNAK uint64 // Number of received NAK (Negative Acknowledgement) control packets
MbpsSendRate float64 // Sending rate, in Mbps
MbpsRecvRate float64 // Receiving rate, in Mbps
UsSndDuration uint64 // Accumulated time in microseconds, during which the SRT sender has some data to transmit, including packets that have been sent, but not yet acknowledged
PktReorderDistance uint64
PktRecvBelated uint64 // Number of packets that arrive too late
PktSndDrop uint64 // Number of dropped by the SRT sender DATA packets that have no chance to be delivered in time
PktRecvDrop uint64 // Number of dropped by the SRT receiver and, as a result, not delivered to the upstream application DATA packets
PktRecvUndecrypt uint64 // Number of packets that failed to be decrypted at the receiver side
ByteSent uint64 // Same as pktSent, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecv uint64 // Same as pktRecv, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteSentUnique uint64 // Same as pktSentUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvUnique uint64 // Same as pktRecvUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvLoss uint64 // Same as pktRecvLoss, but expressed in bytes, including payload and all the headers (IP, TCP, SRT), bytes for the presently missing (either reordered or lost) packets' payloads are estimated based on the average packet size
ByteRetrans uint64 // Same as pktRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvRetrans uint64 // Same as pktRecvRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvBelated uint64 // Same as pktRecvBelated, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteSendDrop uint64 // Same as pktSendDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvDrop uint64 // Same as pktRecvDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
ByteRecvUndecrypt uint64 // Same as pktRecvUndecrypt, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
}
Source Files
¶
- ack_btree.go
- buffers.go
- config.go
- config_marshal.go
- config_validate.go
- conn_request.go
- connection.go
- connection_debug_stub.go
- connection_handlers.go
- connection_handshake.go
- connection_io.go
- connection_keymgmt.go
- connection_lifecycle.go
- connection_linux.go
- connection_rtt.go
- connection_send.go
- connection_stats.go
- dial.go
- dial_handshake.go
- dial_io.go
- dial_linux.go
- doc.go
- io_uring_check.go
- listen.go
- listen_accept.go
- listen_io.go
- listen_lifecycle.go
- listen_linux.go
- log.go
- net.go
- pubsub.go
- server.go
- sockaddr.go
- statistics.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package circular implements "circular numbers".
|
Package circular implements "circular numbers". |
|
Package congestions provides interfaces and types congestion control implementations for SRT
|
Package congestions provides interfaces and types congestion control implementations for SRT |
|
live
Package live provides implementations of the Sender and Receiver interfaces for live congestion control
|
Package live provides implementations of the Sender and Receiver interfaces for live congestion control |
|
live/common
Package common provides shared infrastructure for sender and receiver congestion control implementations.
|
Package common provides shared infrastructure for sender and receiver congestion control implementations. |
|
live/receive
Package receive implements the receiver-side congestion control for SRT live mode.
|
Package receive implements the receiver-side congestion control for SRT live mode. |
|
live/send
Package send implements the sender-side congestion control for SRT live mode.
|
Package send implements the sender-side congestion control for SRT live mode. |
|
contrib
|
|
|
client
command
|
|
|
client-generator
command
|
|
|
client-seeker
command
client-seeker is a controllable SRT data generator for performance testing.
|
client-seeker is a controllable SRT data generator for performance testing. |
|
common
Package common provides shared utilities for SRT client applications.
|
Package common provides shared utilities for SRT client applications. |
|
integration_testing
command
|
|
|
performance
command
performance is an automated performance testing orchestrator for gosrt.
|
performance is an automated performance testing orchestrator for gosrt. |
|
server
command
|
|
|
udp_echo
command
|
|
|
Package crypto provides SRT cryptography
|
Package crypto provides SRT cryptography |
|
Package packet provides types and implementations for the different SRT packet types
|
Package packet provides types and implementations for the different SRT packet types |
|
tools
|
|
|
code-audit
command
code-audit is a unified AST analysis tool for comprehensive code quality.
|
code-audit is a unified AST analysis tool for comprehensive code quality. |
|
lock-requirements-analyzer
command
lock-requirements-analyzer is a static analysis tool that identifies operations that MUST be protected by locks in the GoSRT codebase.
|
lock-requirements-analyzer is a static analysis tool that identifies operations that MUST be protected by locks in the GoSRT codebase. |
|
metrics-audit
command
metrics-audit is a static analysis tool that verifies alignment between: 1.
|
metrics-audit is a static analysis tool that verifies alignment between: 1. |
|
metrics-lock-analyzer
command
metrics-lock-analyzer is a static analysis tool that identifies metrics incremented within lock-protected critical sections and proposes transformations to move atomic operations outside of locks.
|
metrics-lock-analyzer is a static analysis tool that identifies metrics incremented within lock-protected critical sections and proposes transformations to move atomic operations outside of locks. |
|
seq-audit
command
seq-audit is a type-aware AST analyzer for finding unsafe sequence arithmetic.
|
seq-audit is a type-aware AST analyzer for finding unsafe sequence arithmetic. |
|
test-audit
command
test-audit is a unified tool for analyzing and improving table-driven tests.
|
test-audit is a unified tool for analyzing and improving table-driven tests. |