rtc

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultBufferSize is the default size of the jitter buffer
	DefaultBufferSize = 1024
	// MaxNackPackets is the maximum number of packets to request in a single NACK
	MaxNackPackets = 17
	// NackThreshold is the number of missing packets before sending NACK
	NackThreshold = 2
)

Variables

This section is empty.

Functions

func CreateLocalTrack

func CreateLocalTrack(codec webrtc.RTPCodecCapability, id, streamID string) (*webrtc.TrackLocalStaticRTP, error)

CreateLocalTrack creates a new local media track for sending.

func CreateNack

func CreateNack(ssrc uint32, missing []uint16) []rtcp.Packet

CreateNack builds an RTCP NACK packet for the missing sequence numbers.

Types

type BitrateEstimator

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

BitrateEstimator estimates available bandwidth using exponential moving average.

func NewBitrateEstimator

func NewBitrateEstimator() *BitrateEstimator

NewBitrateEstimator creates a new bitrate estimator.

func (*BitrateEstimator) Empty

func (be *BitrateEstimator) Empty() bool

Empty returns true if no bitrates have been recorded.

func (*BitrateEstimator) Feed

func (be *BitrateEstimator) Feed(subscriberID string, bitrate float32)

Feed adds a bitrate measurement.

func (*BitrateEstimator) GetEstimatedBitrate

func (be *BitrateEstimator) GetEstimatedBitrate() uint32

GetEstimatedBitrate returns the current estimated bitrate.

func (*BitrateEstimator) Min

func (be *BitrateEstimator) Min() float32

Min returns the minimum bitrate across all feeds.

type CallHandler

type CallHandler func(event core.CallEvent)

CallHandler handles call events.

type CallManager

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

CallManager manages active calls.

func NewCallManager

func NewCallManager() *CallManager

NewCallManager creates a new CallManager.

func (*CallManager) ActiveCallCount

func (cm *CallManager) ActiveCallCount() int

ActiveCallCount returns the number of active calls.

func (*CallManager) EndCall

func (cm *CallManager) EndCall(roomID string) error

EndCall terminates a call.

func (*CallManager) OnCallEvent

func (cm *CallManager) OnCallEvent(handler func(event core.CallEvent))

OnCallEvent registers a handler for call events.

func (*CallManager) StartCall

func (cm *CallManager) StartCall(callType core.CallType, roomID, caller, callee string) *core.CallEvent

StartCall initiates a new call.

type CongestionController

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

CongestionController manages bandwidth estimation and bitrate adaptation per subscriber.

func NewCongestionController

func NewCongestionController(min, max, start uint32, onChange func(string, uint32)) *CongestionController

NewCongestionController creates a new controller for managing subscriber bandwidth.

func (*CongestionController) AddSubscriber

func (c *CongestionController) AddSubscriber(id string)

AddSubscriber initializes congestion tracking for a new peer.

func (*CongestionController) Close

func (c *CongestionController) Close()

Close stops the congestion control loop.

func (*CongestionController) RemoveSubscriber

func (c *CongestionController) RemoveSubscriber(id string)

RemoveSubscriber cleans up tracking for a peer.

func (*CongestionController) UpdateBitrateEstimate

func (c *CongestionController) UpdateBitrateEstimate(id string, bitrate uint32)

UpdateBitrateEstimate uses an explicit REMB/TWCC estimate from the client.

func (*CongestionController) UpdateMetrics

func (c *CongestionController) UpdateMetrics(id string, rtt uint32, loss float64)

UpdateMetrics updates RTT and loss rate and re-estimates the target bitrate.

type CongestionState

type CongestionState int

CongestionState represents the bandwidth estimation state.

const (
	StateNormal CongestionState = iota
	StateWarning
	StateCongested
	StateRecovering
)

func (CongestionState) String

func (s CongestionState) String() string

type DownTrack

type DownTrack struct {
	ID     string
	PeerID string // ID of the subscriber
	Local  *webrtc.TrackLocalStaticRTP
	Sender *webrtc.RTPSender
}

DownTrack represents a media track being sent to a subscriber.

type JitterBuffer

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

JitterBuffer manages a ring buffer of RTP packets to detect packet loss and support retransmissions. Based on the Remainwith jitter buffer pattern with per-SSRC management.

func NewJitterBuffer

func NewJitterBuffer(size uint16) *JitterBuffer

NewJitterBuffer creates a new jitter buffer of the specified size.

func (*JitterBuffer) GetPacket

func (jb *JitterBuffer) GetPacket(sn uint16) *rtp.Packet

GetPacket retrieves a packet from the buffer by sequence number.

func (*JitterBuffer) Push

func (jb *JitterBuffer) Push(packet *rtp.Packet) []uint16

Push adds a packet to the buffer and returns missing sequence numbers that should trigger NACKs.

func (*JitterBuffer) Stats

func (jb *JitterBuffer) Stats() (received, lost uint64)

Stats returns buffer statistics.

type Layer

type Layer int

Layer represents a simulcast quality level.

const (
	LayerLow Layer = iota
	LayerMid
	LayerHigh
)

func (Layer) String

func (l Layer) String() string

type Manager

type Manager struct {

	// Phase 2 components
	Congestion *CongestionController
	Simulcast  *SimulcastManager
	// contains filtered or unexported fields
}

Manager manages WebRTC peer connections using pion/webrtc.

func NewManager

func NewManager(stunServers []string) *Manager

NewManager creates a new RTC Manager with configurable STUN servers.

func NewManagerWithConfig

func NewManagerWithConfig(conf webrtc.Configuration) *Manager

NewManagerWithConfig creates a Manager with custom WebRTC configuration.

func NewManagerWithICEServers

func NewManagerWithICEServers(stunServers []string, turnServers []core.ICEServerConfig, transportPolicy string) *Manager

NewManagerWithICEServers creates a new RTC Manager with configurable STUN/TURN servers.

func (*Manager) CreatePeerConnection

func (m *Manager) CreatePeerConnection(id, userID, roomID string) (*Peer, error)

CreatePeerConnection creates a new pion PeerConnection and tracks it. Uses the configured MediaEngine/interceptors API for proper codec support.

func (*Manager) GetPeer

func (m *Manager) GetPeer(id string) (*Peer, error)

GetPeer retrieves a tracked peer by ID.

func (*Manager) GetRouter

func (m *Manager) GetRouter(roomID string) *Router

GetRouter returns or creates the router for the given room.

func (*Manager) HandleAnswer

func (m *Manager) HandleAnswer(peerID string, answer webrtc.SessionDescription) error

HandleAnswer sets the remote SDP answer on an existing peer.

func (*Manager) HandleICECandidate

func (m *Manager) HandleICECandidate(peerID string, candidate webrtc.ICECandidateInit) error

HandleICECandidate adds a remote ICE candidate to a peer.

func (*Manager) HandleOffer

func (m *Manager) HandleOffer(ctx context.Context, peerID, userID, roomID string, offer webrtc.SessionDescription) (*webrtc.SessionDescription, error)

HandleOffer creates a peer from an incoming SDP offer and returns the answer.

func (*Manager) PeerCount

func (m *Manager) PeerCount() int

PeerCount returns the number of tracked peers.

func (*Manager) RemovePeer

func (m *Manager) RemovePeer(id string)

RemovePeer removes and closes a peer connection.

func (*Manager) RestartICE

func (m *Manager) RestartICE(peerID string) (*webrtc.SessionDescription, error)

RestartICE creates a new offer with ICE restart enabled for a peer.

func (*Manager) SetOnRecoveryNeeded

func (m *Manager) SetOnRecoveryNeeded(handler func(peerID, roomID, reason string))

SetOnRecoveryNeeded registers a callback for network recovery and ICE restart requests.

func (*Manager) SetOnTrack

func (m *Manager) SetOnTrack(handler func(peerID, roomID, trackID string))

SetOnTrack registers a global callback for new tracks.

func (*Manager) Subscribe

func (m *Manager) Subscribe(peerID, trackID string) error

Subscribe hooks a peer to an existing track in their room.

type Negotiator

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

Negotiator implements the "Perfect Negotiation" pattern for stable WebRTC state transitions. It ensures that offers and answers are sequenced correctly even with multiple participants. Follows the peer-calls pattern with signaling state tracking and queued transceivers.

func NewNegotiator

func NewNegotiator(isPolite bool, pc *webrtc.PeerConnection, onOffer func(webrtc.SessionDescription), onRequest func()) *Negotiator

NewNegotiator creates a new negotiator for a PeerConnection. isPolite: If true, this peer will yield to incoming offers during "SDP glare".

func (*Negotiator) AddTransceiverFromKind

func (n *Negotiator) AddTransceiverFromKind(t TransceiverRequest)

AddTransceiverFromKind queues a transceiver request and triggers negotiation.

func (*Negotiator) Done

func (n *Negotiator) Done() <-chan struct{}

Done returns a channel that's closed when negotiation is complete.

func (*Negotiator) HandleAnswer

func (n *Negotiator) HandleAnswer(answer webrtc.SessionDescription) error

HandleAnswer processes an incoming SDP answer.

func (*Negotiator) HandleOffer

func (n *Negotiator) HandleOffer(offer webrtc.SessionDescription) error

HandleOffer processes an incoming SDP offer with collision handling.

func (*Negotiator) Negotiate

func (n *Negotiator) Negotiate() (done <-chan struct{})

Negotiate triggers the negotiation process. Returns a channel that's closed when negotiation completes.

type Peer

type Peer struct {
	ID      string
	UserID  string
	RoomID  string
	State   PeerState
	PC      *webrtc.PeerConnection
	Created time.Time
	Updated time.Time

	Negotiator *Negotiator
	Router     *Router

	// JitterBuffers: SSRC -> JitterBuffer
	JitterBuffers map[uint32]*JitterBuffer
	// contains filtered or unexported fields
}

Peer wraps a pion/webrtc PeerConnection with framework metadata.

func NewPeer

func NewPeer(id, userID, roomID string, pc *webrtc.PeerConnection, onTrack func(string, string, string), onRecoveryNeeded func(string, string, string)) *Peer

NewPeer creates a new Peer wrapping the given pion PeerConnection.

func (*Peer) AddICECandidate

func (p *Peer) AddICECandidate(candidate webrtc.ICECandidateInit) error

AddICECandidate adds a remote ICE candidate to the peer connection. If the remote description is not yet set, the candidate is queued for later.

func (*Peer) AddTrack

func (p *Peer) AddTrack(track webrtc.TrackLocal) (*webrtc.RTPSender, error)

AddTrack adds a local media track to the peer connection.

func (*Peer) Close

func (p *Peer) Close() error

Close closes the peer connection.

func (*Peer) CreateAnswer

func (p *Peer) CreateAnswer() (*webrtc.SessionDescription, error)

CreateAnswer creates an SDP answer after receiving an offer.

func (*Peer) CreateOffer

func (p *Peer) CreateOffer() (*webrtc.SessionDescription, error)

CreateOffer creates an SDP offer on the peer connection. Uses the Negotiator if available, otherwise falls back to direct creation.

func (*Peer) GetState

func (p *Peer) GetState() PeerState

GetState returns the current peer state.

func (*Peer) IsInitialConnected

func (p *Peer) IsInitialConnected() bool

IsInitialConnected returns whether the initial connection has been established.

func (*Peer) ProcessPendingCandidates

func (p *Peer) ProcessPendingCandidates()

ProcessPendingCandidates processes any queued ICE candidates after remote description is set.

func (*Peer) SetOnTrack

func (p *Peer) SetOnTrack(handler func(peerID string, track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver))

SetOnTrack registers a callback for incoming media tracks.

func (*Peer) SetRemoteDescription

func (p *Peer) SetRemoteDescription(sdp webrtc.SessionDescription) error

SetRemoteDescription sets the remote SDP (offer or answer) and processes pending ICE candidates.

func (*Peer) SetState

func (p *Peer) SetState(state PeerState)

SetState updates the peer state.

type PeerState

type PeerState int

PeerState represents the state of a peer connection.

const (
	PeerStateNew PeerState = iota
	PeerStateConnecting
	PeerStateConnected
	PeerStateDisconnected
	PeerStateFailed
)

func (PeerState) String

func (s PeerState) String() string

type Router

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

Router manages the distribution of media tracks within a room. It implements a PubSub pattern where Publishers (UpTracks) are linked to Subscribers (DownTracks).

func NewRouter

func NewRouter(roomID string) *Router

NewRouter creates a new media router for a room.

func (*Router) AddSubscriber

func (r *Router) AddSubscriber(trackID, subscriberID string, local *webrtc.TrackLocalStaticRTP, sender *webrtc.RTPSender) error

AddSubscriber links a peer to a published track.

func (*Router) AddUpTrack

func (r *Router) AddUpTrack(peerID string, track *webrtc.TrackRemote, onNack func(missing []uint16))

AddUpTrack registers a new publisher track and starts its forwarding loop with jitter buffer integration for packet loss detection.

func (*Router) Close

func (r *Router) Close()

Close stops all routing activity.

func (*Router) RemoveSubscriber

func (r *Router) RemoveSubscriber(trackID, subscriberID string)

RemoveSubscriber removes a peer's subscription to a track.

func (*Router) RemoveUpTrack

func (r *Router) RemoveUpTrack(trackID string)

RemoveUpTrack stops forwarding and removes a publisher track.

type SimulcastManager

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

SimulcastManager coordinates layer selection across all subscribers in a room.

func NewSimulcastManager

func NewSimulcastManager() *SimulcastManager

NewSimulcastManager creates a new manager for a room's simulcast tracks.

func (*SimulcastManager) AddTrack

func (m *SimulcastManager) AddTrack(id, clientID string)

AddTrack registers a new simulcast track.

func (*SimulcastManager) SelectOptimalLayer

func (m *SimulcastManager) SelectOptimalLayer(subscriberID, trackID string) Layer

SelectOptimalLayer returns the best layer for a subscriber to view a track.

func (*SimulcastManager) SetBandwidth

func (m *SimulcastManager) SetBandwidth(subscriberID string, bps uint32)

SetBandwidth updates the bandwidth limit for a subscriber (from CongestionController).

func (*SimulcastManager) SetPreference

func (m *SimulcastManager) SetPreference(subscriberID, trackID string, l Layer)

SetPreference allows a user to manually pin a specific quality.

type SimulcastTrack

type SimulcastTrack struct {
	ID       string
	ClientID string

	// Bitrates for each layer (in bps)
	Bitrates map[Layer]uint32
	// Active status for each layer
	Active map[Layer]bool
	// contains filtered or unexported fields
}

SimulcastTrack wraps track metadata to manage quality layers.

func NewSimulcastTrack

func NewSimulcastTrack(id, clientID string) *SimulcastTrack

NewSimulcastTrack creates a new tracker for a simulcast track.

func (*SimulcastTrack) GetBitrateEstimator

func (t *SimulcastTrack) GetBitrateEstimator() *BitrateEstimator

GetBitrateEstimator returns the bitrate estimator for this track.

func (*SimulcastTrack) SelectLayer

func (t *SimulcastTrack) SelectLayer(bandwidth uint32) Layer

SelectLayer chooses the best active layer within the given bandwidth limit.

func (*SimulcastTrack) UpdateLayer

func (t *SimulcastTrack) UpdateLayer(l Layer, active bool, bitrate uint32)

UpdateLayer updates the state of a specific layer.

type SubscriberStats

type SubscriberStats struct {
	ID               string
	State            CongestionState
	EstimatedBitrate uint32
	RTT              uint32
	LossRate         float64 // 0.0 - 1.0
	LastUpdate       time.Time
}

SubscriberStats tracks the network metrics and estimated bandwidth for a single peer.

type TransceiverRequest

type TransceiverRequest struct {
	CodecType webrtc.RTPCodecType
	Init      webrtc.RTPTransceiverInit
}

TransceiverRequest represents a request to add a transceiver during renegotiation.

type UpTrack

type UpTrack struct {
	ID     string
	PeerID string
	Kind   webrtc.RTPCodecType
	Remote *webrtc.TrackRemote
	SSRC   webrtc.SSRC
	Done   chan struct{}
	OnNACK func(nack []uint16)
}

UpTrack represents a media track published by a peer.

Jump to

Keyboard shortcuts

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