srt

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2024 License: MIT Imports: 23 Imported by: 5

README

GoSRT

Implementation of the SRT protocol in pure Go with minimal dependencies.

SRT

Tests codecov Go Report Card PkgGoDev

Implementations

This implementation of the SRT protocol has live streaming of video/audio in mind. Because of this, the buffer mode and File Transfer Congestion Control (FileCC) are not implemented.

Handshake v4 and v5
Message mode
Caller-Listener Handshake
Timestamp-Based Packet Delivery (TSBPD)
Too-Late Packet Drop (TLPKTDROP)
Live Congestion Control (LiveCC)
NAK and Peridoc NAK
Encryption
Buffer mode
Rendezvous Handshake
File Transfer Congestion Control (FileCC)
Connection Bonding

The parts that are implemented are based on what has been published in the SRT RFC.

Requirements

A Go version of 1.18+ is required.

Installation

go get github.com/datarhei/gosrt

Caller example

import "github.com/datarhei/gosrt"

conn, err := srt.Dial("srt", "golang.org:6000", srt.Config{
    StreamId: "...",
})
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()

In the contrib/client directory you'll find a complete example of a SRT client.

Listener example

import "github.com/datarhei/gosrt"

ln, err := srt.Listen("srt", ":6000", srt.Config{...})
if err != nil {
    // handle error
}

for {
    conn, mode, err := ln.Accept(func(req ConnRequest) ConnType {
        // check connection request
        return srt.REJECT
    })
    if err != nil {
        // handle error
    }

    if mode == srt.REJECT {
        // rejected connection, ignore
        continue
    }

    if mode == srt.PUBLISH {
        go handlePublish(conn)
    } else { // srt.SUBSCRIBE
        go handleSubscribe(conn)
    }
}

In the contrib/server directory you'll find a complete example of a SRT server. For your convenience this modules provides the Server type which is a light framework for creating your own SRT server. The example server is based on this type.

PUBLISH / SUBSCRIBE

The Accept function from the Listener expects a function that handles the connection requests. It can return 3 different values: srt.PUBLISH, srt.SUBSCRIBE, and srt.REJECT. srt.PUBLISH means that the server expects the caller to send data, whereas srt.SUBSCRIBE means that the server will send data to the caller. This is opiniated towards a streaming server, however in your implementation of a listener you are free to handle connections requests to your liking.

Contributed client

In the contrib/client directory you'll find an example implementation of a SRT client.

Build the client application with

cd contrib/client && go build

The application requires only two options:

Option Description
-from Address to read from
-to Address to write to

Both options accept an address. Valid addresses are: - for stdin, resp. stdout, a srt:// address, or an udp:// address.

SRT URL

A SRT URL is of the form srt://[host]:[port]/?[options] where options are in the form of a HTTP query string. These are the known options (similar to srt-live-transmit):

Option Values Description
mode listener or caller Enforce listener or caller mode.
congestion live Congestion control. Currently only live is supported.
conntimeo ms Connection timeout.
drifttracer bool Enable drift tracer. Not implemented.
enforcedencryption bool Accept connection only if both parties have encryption enabled.
fc bytes Flow control window size.
inputbw bytes Input bandwidth. Ignored.
iptos 0...255 IP socket type of service. Broken.
ipttl 1...255 Defines IP socket "time to live" option. Broken.
ipv6only bool Use IPv6 only. Not implemented.
kmpreannounce packets Duration of Stream Encryption key switchover.
kmrefreshrate packets Stream encryption key refresh rate.
latency ms Maximum accepted transmission latency.
lossmaxttl ms Packet reorder tolerance. Not implemented.
maxbw bytes Bandwidth limit. Ignored.
mininputbw bytes Minimum allowed estimate of inputbw.
messageapi bool Enable SRT message mode. Must be false.
mss 76... MTU size.
nakreport bool Enable periodic NAK reports.
oheadbw 10...100 Limits bandwidth overhead. Percents. Ignored.
packetfilter string Set up the packet filter. Not implemented.
passphrase string Password for the encrypted transmission.
payloadsize bytes Maximum payload size.
pbkeylen 16, 24, or 32 Crypto key length in bytes.
peeridletimeo ms Peer idle timeout.
peerlatency ms Minimum receiver latency to be requested by sender.
rcvbuf bytes Receiver buffer size.
rcvlatency ms Receiver-side latency.
sndbuf bytes Sender buffer size.
snddropdelay ms Sender's delay before dropping packets.
streamid string Stream ID (settable in caller mode only, visible on the listener peer).
tlpktdrop bool Drop too late packets.
transtype live Transmission type. Must be live.
tsbpdmode bool Enable timestamp-based packet delivery mode.
Usage

Reading from a SRT sender and play with ffplay:

./client -from "srt://127.0.0.1:6001/?mode=listener&streamid=..." -to - | ffplay -f mpegts -i -

Reading from UDP and sending to a SRT server:

./client -from udp://:6000 -to "srt://127.0.0.1:6001/?mode=caller&streamid=..."

Simulate point-to-point transfer on localhost. Open one console and start ffmpeg (you need at least version 4.3.2, built with SRT enabled) to send to an UDP address:

ffmpeg \
    -f lavfi \
    -re \
    -i testsrc2=rate=25:size=640x360 \
    -codec:v libx264 \
    -b:v 1024k \
    -maxrate:v 1024k \
    -bufsize:v 1024k \
    -preset ultrafast \
    -r 25 \
    -g 50 \
    -pix_fmt yuv420p \
    -flags2 local_header \
    -f mpegts \
    "udp://127.0.0.1:6000?pkt_size=1316"

In another console read from the UDP and start a SRT listenr:

./client -from udp://:6000 -to "srt://127.0.0.1:6001/?mode=listener&streamid=foobar"

In the third console connect to that stream and play the video with ffplay:

./client -from "srt://127.0.0.1:6001/?mode=caller&streamid=foobar" -to - | ffplay -f mpegts -i -

Contributed server

In the contrib/server directory you'll find an example implementation of a SRT server. This server allows you to publish a stream that can be read by many clients.

Build the client application with

cd contrib/server && go build

The application has these options:

Option Default Description
-addr required Address to listen on
-app / Path prefix for streamid
-token (not set) Token query param for streamid
-passphrase (not set) Passphrase for de- and enrcypting the data
-logtopics (not set) Topics for the log output
-profile false Enable profiling

This example server expects the streamID (without any prefix) to be an URL path with optional query parameter, e.g. /live/stream. If the -app option is used, then the path must start with that path, e.g. the value is /live then the streamID must start with that value. The -token option can be used to define a token for that stream as some kind of access control, e.g. with -token foobar the streamID might look like /live/stream?token=foobar.

Use -passphrase in order to enable and enforce encryption.

Use -logtopics in order to write debug output. The value are a comma separated list of topics you want to be written to stderr, e.g. connection,listen. Check the Logging section in order to find out more about the different topics.

Use -profile in order to write a CPU profile.

StreamID

In SRT the StreamID is used to transport somewhat arbitrary information from the caller to the listener. The provided example server uses this machanism to decide who is the sender and who is the receiver. The server must know if the connecting client wants to publish a stream or if it wants to subscribe to a stream.

The example server looks for the publish: prefix in the StreamID. If this prefix is present, the server assumes that it is the receiver and the client will send the data. The subcribing clients must use the same StreamID (withouth the publish: prefix) in order to be able to receive data.

If you implement your own server you are free to interpret the streamID as you wish.

Usage

Running a server listening on port 6001 with defaults:

./server -addr ":6001"

Now you can use the contributed client to publish a stream:

./client -from ... -to "srt://127.0.0.1:6001/?mode=caller&streamid=publish:/live/stream"

or directly from ffmpeg:

ffmpeg \
    -f lavfi \
    -re \
    -i testsrc2=rate=25:size=640x360 \
    -codec:v libx264 \
    -b:v 1024k \
    -maxrate:v 1024k \
    -bufsize:v 1024k \
    -preset ultrafast \
    -r 25 \
    -g 50 \
    -pix_fmt yuv420p \
    -flags2 local_header \
    -f mpegts \
    -transtype live \
    "srt://127.0.0.1:6001?streamid=publish:/live/stream"

If the server is not on localhost, you might adjust the peerlatency in order to avoid packet loss: -peerlatency 1000000.

Now you can play the stream:

ffplay -f mpegts -transtype live -i "srt://127.0.0.1:6001?streamid=/live/stream"

You will most likely first see some error messages from ffplay because it tries to make sense of the received data until a keyframe arrives. If you get more errors during playback, you might increase the receive buffer by adding e.g. -rcvlatency 1000000 to the command line.

Encryption

The stream can be encrypted with a passphrase. First start the server with a passphrase. If you are using srt-live-transmit, the passphrase has to be at least 10 characters long otherwise it will not be accepted.

./server -addr :6001 -passphrase foobarfoobar

Send an encrpyted stream to the server:

ffmpeg \
    -f lavfi \
    -re \
    -i testsrc2=rate=25:size=640x360 \
    -codec:v libx264 \
    -b:v 1024k \
    -maxrate:v 1024k \
    -bufsize:v 1024k \
    -preset ultrafast \
    -r 25 \
    -g 50 \
    -pix_fmt yuv420p \
    -flags2 local_header \
    -f mpegts \
    -transtype live \
    "srt://127.0.0.1:6001?streamid=publish:/live/stream&passphrase=foobarfoobar"

Receive an encrypted stream from the server:

ffplay -f mpegts -transtype live -i "srt://127.0.0.1:6001?streamid=/live/stream&passphrase=foobarfoobar"

You will most likely first see some error messages from ffplay because it tries to make sense of the received data until a keyframe arrives. If you get more errors during playback, you might increase the receive buffer by adding e.g. -rcvlatency 1000000 to the command line.

Logging

This SRT module has a built-in logging facility for debugging purposes. Check the Logger interface and the NewLogger(topics []string) function. Because logging everything would be too much output if you wonly want to debug something specific, you have the possibility to limit the logging to specific areas like everything regarding a connection or only the handshake. That's why there are various topics.

In the contributed server you see an example of how logging is used. Here's the essence:

logger := srt.NewLogger([]string{"connection", "handshake"})

config := srt.DefaultConfig
config.Logger = logger

ln, err := srt.Listen("udp", ":6000", config)
if err != nil {
    // handle error
}

go func() {
    for m := range logger.Listen() {
        fmt.Fprintf(os.Stderr, "%#08x %s (in %s:%d)\n%s \n", m.SocketId, m.Topic, m.File, m.Line, m.Message)
    }
}()

for {
    conn, mode, err := ln.Accept(acceptFn)
    ...
}

Currently known topics are:

connection:close
connection:error
connection:filter
connection:new
connection:rtt
connection:tsbpd
control:recv:ACK:cif
control:recv:ACK:dump
control:recv:ACK:error
control:recv:ACKACK:dump
control:recv:ACKACK:error
control:recv:KM:cif
control:recv:KM:dump
control:recv:KM:error
control:recv:NAK:cif
control:recv:NAK:dump
control:recv:NAK:error
control:recv:keepalive:dump
control:recv:shutdown:dump
control:send:ACK:cif
control:send:ACK:dump
control:send:ACKACK:dump
control:send:KM:cif
control:send:KM:dump
control:send:KM:error
control:send:NAK:cif
control:send:NAK:dump
control:send:keepalive:dump
control:send:shutdown:cif
control:send:shutdown:dump
data:recv:dump
data:send:dump
dial
handshake:recv:cif
handshake:recv:dump
handshake:recv:error
handshake:send:cif
handshake:send:dump
listen
packet:recv:dump
packet:send:dump

You can run make logtopics in order to extract the list of topics.

Docker

The docker image you can build with docker build -t srt . provides the example SRT client and server as mentioned in the paragraph above. E.g. run the server with docker run -it --rm -p 6001:6001/udp srt srt-server -addr :6001.

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:

conn, err := srt.Dial("srt", "golang.org:6000", srt.Config{
	StreamId: "...",
})
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:

ln, err := srt.Listen("srt", ":6000", srt.Config{...})
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

View Source
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 = 79
	MAX_STREAMID_SIZE   = 512
	SRT_VERSION         = 0x010401
)

Variables

View Source
var ErrClientClosed = errors.New("srt: client closed")

ErrClientClosed is returned when the client connection has been voluntarily closed.

View Source
var ErrListenerClosed = errors.New("srt: listener closed")

ErrListenerClosed is returned when the listener is about to shutdown.

View Source
var ErrServerClosed = errors.New("srt: server closed")

ErrServerClosed is returned when the server is about to shutdown.

Functions

func DialControl added in v0.5.1

func DialControl(config Config) func(network string, address string, c syscall.RawConn) error

func ListenControl added in v0.5.1

func ListenControl(config Config) func(network, address string, c syscall.RawConn) error

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

	// 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

	// 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
}

Config is the configuration for a SRT connection

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration for Dial and Listen.

func (*Config) MarshalQuery

func (c *Config) MarshalQuery() string

MarshalQuery returns the corresponding query string for a configuration.

func (*Config) MarshalURL

func (c *Config) MarshalURL(address string) string

MarshalURL returns the SRT URL for this config and the given address (host:port).

func (*Config) UnmarshalQuery

func (c *Config) UnmarshalQuery(query string) error

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

func (c *Config) UnmarshalURL(srturl string) (string, error)

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.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates a configuration, returns an error if a field has an invalid value.

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
}

Conn is a SRT network connection.

func Dial

func Dial(network, address string, config Config) (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("srt", "127.0.0.1:3000", DefaultConfig())

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

	// 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.
	SetRejectionReason(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.

const (
	REJECT    ConnType = ConnType(1 << iota) // Reject a connection
	PUBLISH                                  // This connection is meant to write data to the server
	SUBSCRIBE                                // This connection is meant to read data from a PUBLISHed stream
)

func (ConnType) String

func (c ConnType) String() string

String returns a string representation of the ConnType.

type Listener

type Listener interface {
	// 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.
	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(network, address string, config Config) (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("srt", "127.0.0.1:3000", DefaultConfig())

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.

func NewLogger

func NewLogger(topics []string) Logger

NewLogger returns a Logger that only listens on the given list of topics.

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 RejectionReason added in v0.5.6

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)

	// HandlePublish will be called for a subscribing connection.
	HandleSubscribe func(conn Conn)
	// contains filtered or unexported fields
}

Server is a framework for a SRT server

func (*Server) Listen added in v0.5.4

func (s *Server) Listen() error

Listen opens the server listener. It returns immediately after the listener is ready.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the SRT server. It blocks until an error happens. If the error is ErrServerClosed the server has shutdown normally.

func (*Server) Serve added in v0.5.4

func (s *Server) Serve() error

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.

func (*Server) Shutdown

func (s *Server) Shutdown()

Shutdown will shutdown the server. ListenAndServe will return a ErrServerClosed

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 added in v0.3.0

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 added in v0.3.0

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
	PktSendLossRate       float64 // Percentage of resent data vs. sent data
	PktRecvLossRate       float64 // Percentage of retransmitted data vs. received data
}

type StatisticsInterval added in v0.3.0

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)
}

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
contrib
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

Jump to

Keyboard shortcuts

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