webrtc

package
v0.0.0-...-a93fa22 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Module

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

Module implements the WebRTC WHIP/WHEP module.

func NewModule

func NewModule() *Module

NewModule creates a new WebRTC module.

func (*Module) Addr

func (m *Module) Addr() net.Addr

Addr returns the listener address (useful for tests).

func (*Module) Close

func (m *Module) Close() error

Close shuts down all sessions and the HTTP server.

func (*Module) Hooks

func (m *Module) Hooks() []core.HookRegistration

Hooks returns the module's event hooks (none for WebRTC).

func (*Module) Init

func (m *Module) Init(s *core.Server) error

Init sets up the pion WebRTC API and starts the HTTP signaling server.

func (*Module) Name

func (m *Module) Name() string

Name returns the module name.

func (*Module) OnReload

func (m *Module) OnReload(s *core.Server) error

OnReload makes updated GCC bitrate bounds and ICE server credentials available to new sessions. GCC enablement, listener, ICE mode, candidates, and port ranges remain restart-required because they shape the Pion API.

type Session

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

Session represents an active WebRTC peer connection for WHIP or WHEP.

func (*Session) Close

func (s *Session) Close()

Close shuts down the session, closing the PeerConnection and cleaning up resources.

func (*Session) FeedStatus

func (s *Session) FeedStatus() (WHEPFeedStatus, bool)

type TrackSender

type TrackSender struct {
	Stats TrackSenderStats
	// contains filtered or unexported fields
}

TrackSender wraps a pion RTPSender and its TrackLocalStaticSample. It runs a dedicated RTCP read loop that parses incoming RTCP packets and dispatches them to registered handlers, decoupling RTCP processing from application-layer protocol code (WHEP, future SIP, etc.).

Supported RTCP types:

  • PLI / FIR → sets needsKeyframe flag + onPLI callback
  • NACK → onNACK callback + stats (retransmission request)
  • ReceiverReport → onReceiverReport callback + stats (quality metrics)

PLI/FIR handling: Instead of writing media directly from the RTCP goroutine, TrackSender sets an atomic needsKeyframe flag. The feed loop checks this flag and skips inter-frames until the next keyframe arrives, ensuring only one goroutine ever writes media samples. This eliminates timestamp interleaving between the RTCP goroutine and the feed loop.

Note: pion's default interceptors handle NACK retransmission and TWCC automatically. TrackSender monitors these for observability; it does NOT replace the interceptor-level handling.

Usage:

ts := NewTrackSender(sessionID, track, sender)
ts.SetPLIHandler(func() { /* log/stats */ })
ts.SetNACKHandler(func(nack *rtcp.TransportLayerNack) { /* log/stats */ })
ts.Start()
ts.WriteSample(media.Sample{...})

func NewTrackSender

func NewTrackSender(sessionID string, track *webrtc.TrackLocalStaticSample, sender *webrtc.RTPSender) *TrackSender

NewTrackSender creates a TrackSender. Call Start() to begin RTCP processing.

func (*TrackSender) ClearNeedsKeyframe

func (ts *TrackSender) ClearNeedsKeyframe()

ClearNeedsKeyframe resets the flag after the feed loop has sent a keyframe.

func (*TrackSender) NeedsKeyframe

func (ts *TrackSender) NeedsKeyframe() bool

NeedsKeyframe returns true if a PLI/FIR has been received and the feed loop should skip inter-frames until the next keyframe.

func (*TrackSender) RequestKeyframe

func (ts *TrackSender) RequestKeyframe()

RequestKeyframe enters the same local keyframe gate used for PLI/FIR. The feed loop will discard interframes until it sends a keyframe.

func (*TrackSender) SetNACKHandler

func (ts *TrackSender) SetNACKHandler(fn func(nack *rtcp.TransportLayerNack))

SetNACKHandler registers a callback invoked when a NACK packet is received. Note: pion's NACK responder interceptor handles the actual retransmission; this callback is for monitoring/logging purposes.

func (*TrackSender) SetPLIHandler

func (ts *TrackSender) SetPLIHandler(fn func())

SetPLIHandler registers a callback invoked when the remote peer sends a PLI (Picture Loss Indication) or FIR (Full Intra Request) RTCP packet. The callback is for logging/monitoring only — keyframe recovery is handled automatically via the needsKeyframe flag: the feed loop skips inter-frames until the next keyframe arrives, ensuring a clean decoder resync.

The callback is invoked from the RTCP goroutine; it must be goroutine-safe.

func (*TrackSender) SetREMBHandler

func (ts *TrackSender) SetREMBHandler(fn func(bitrate uint64, ssrcs []uint32))

SetREMBHandler registers a callback invoked when a REMB (Receiver Estimated Maximum Bitrate) packet is received.

func (*TrackSender) SetReceiverReportHandler

func (ts *TrackSender) SetReceiverReportHandler(fn func(report *rtcp.ReceiverReport))

SetReceiverReportHandler registers a callback invoked when a ReceiverReport is received. Useful for monitoring packet loss, jitter, and RTT.

func (*TrackSender) Start

func (ts *TrackSender) Start()

Start launches the RTCP read loop in a goroutine. The loop exits when ReadRTCP returns an error (peer connection closed or session torn down).

func (*TrackSender) Track

Track returns the underlying local track (useful for codec/MIME inspection).

func (*TrackSender) WriteSample

func (ts *TrackSender) WriteSample(s media.Sample) error

WriteSample encodes a raw media sample as RTP packets and sends them to the peer. It serializes concurrent callers (feed loop + PLI handler) so that all RTP packets for a single sample are sent contiguously, preventing interleaved packet corruption.

type TrackSenderStats

type TrackSenderStats struct {
	PLICount            atomic.Uint64 // total PLI/FIR requests received
	NACKCount           atomic.Uint64 // total NACK packets received (may be 0 if pion interceptor consumes them)
	RTCPPacketsReceived atomic.Uint64 // total RTCP packets delivered to this sender

	// From ReceiverReport
	PacketsLost    atomic.Int64  // cumulative packets lost reported by receiver
	FractionLost   atomic.Uint32 // last reported fraction lost (0-255, where 255 = 100%)
	Jitter         atomic.Uint32 // last reported interarrival jitter (in RTP timestamp units)
	LastSenderSSRC atomic.Uint32 // SSRC of the sender this report applies to
}

TrackSenderStats holds cumulative RTCP statistics for a track. All fields are updated atomically from the RTCP goroutine.

type WHEPFeedState

type WHEPFeedState string

WHEPFeedState describes the part of the playback startup lifecycle that is useful to a browser and to an operator diagnosing a stalled session.

const (
	WHEPFeedWaitingKeyframe   WHEPFeedState = "waiting_keyframe"
	WHEPFeedPlaying           WHEPFeedState = "playing"
	WHEPFeedNoMediaInput      WHEPFeedState = "no_media_input"
	WHEPFeedMediaStalled      WHEPFeedState = "media_stalled"
	WHEPFeedCodecMismatch     WHEPFeedState = "codec_mismatch"
	WHEPFeedSampleWriteFailed WHEPFeedState = "sample_write_failed"
	WHEPFeedTargetAudioFailed WHEPFeedState = "target_audio_failed"
	WHEPFeedGenerationEnded   WHEPFeedState = "generation_ended"
	WHEPFeedClosed            WHEPFeedState = "closed"
)

type WHEPFeedStatus

type WHEPFeedStatus struct {
	Generation          uint64        `json:"generation"`
	Cursor              int64         `json:"cursor"`
	Mode                string        `json:"mode"`
	State               WHEPFeedState `json:"state"`
	FirstMediaAt        time.Time     `json:"first_media_at,omitempty"`
	FirstMediaWaitMS    int64         `json:"first_media_wait_ms"`
	LastVideoAt         time.Time     `json:"last_video_at,omitempty"`
	LastAudioAt         time.Time     `json:"last_audio_at,omitempty"`
	UpdatedAt           time.Time     `json:"updated_at"`
	ExpectedVideo       bool          `json:"expected_video"`
	ExpectedAudio       bool          `json:"expected_audio"`
	VideoFrames         uint64        `json:"video_frames"`
	AudioFrames         uint64        `json:"audio_frames"`
	DroppedVideo        uint64        `json:"dropped_video"`
	DroppedAudio        uint64        `json:"dropped_audio"`
	SourceOverwrites    uint64        `json:"source_overwrites"`
	RTPPacketsSent      uint64        `json:"rtp_packets_sent"`
	RTPBytesSent        uint64        `json:"rtp_bytes_sent"`
	RTCPPacketsReceived uint64        `json:"rtcp_packets_received"`
	LastError           string        `json:"last_error,omitempty"`
}

WHEPFeedStatus is a point-in-time diagnostic snapshot. Counters are intentionally session-local so one stalled subscriber can be diagnosed without turning stream metrics into high-cardinality labels.

type WHIPPublisher

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

WHIPPublisher implements core.Publisher for WebRTC WHIP ingest.

MediaInfo is stored behind an atomic pointer: OnTrack callbacks publish updated snapshots while subscriber goroutines read concurrently.

func (*WHIPPublisher) Close

func (p *WHIPPublisher) Close() error

func (*WHIPPublisher) ID

func (p *WHIPPublisher) ID() string

func (*WHIPPublisher) MediaInfo

func (p *WHIPPublisher) MediaInfo() *avframe.MediaInfo

Jump to

Keyboard shortcuts

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