Documentation
¶
Overview ¶
Stages 1-6 wiring shared with PoC #1. Gathers everything into a Session the rest of poc2a can pull from (signal client, both peer wrappers, the publisher tracks, the goloom IDs we negotiated).
Index ¶
- Constants
- Variables
- func Handshake(ctx context.Context, lg *log.Logger, sess *Session, sender *tunnel.Sender, ...) (string, error)
- func InitiatorLabel(b bool) string
- func InjectBandwidthAttribute(sdp string, kind string, kbps int) string
- func MakeKeyframePusher(track *webrtc.TrackLocalStaticSample, lg *log.Logger, cooldown time.Duration, ...) func()
- func NewPublisherStatsProvider(sender *tunnel.Sender, id PublisherIdent) func() *goloom.Telemetry
- func RunKeyframeRefresh(ctx context.Context, lg *log.Logger, track *webrtc.TrackLocalStaticSample, ...)
- func RunKeyframeRefreshFast(ctx context.Context, lg *log.Logger, track *webrtc.TrackLocalStaticSample, ...)
- func RunOpusSilenceLoop(ctx context.Context, lg *log.Logger, track *webrtc.TrackLocalStaticSample)
- func SendInitialKeyframes(lg *log.Logger, track *webrtc.TrackLocalStaticSample, n int) error
- func StartRTCPLoop(ctx context.Context, lg *log.Logger, tag string, pc *webrtc.PeerConnection, ...)
- type ParsedSlot
- type ParsedSlotsConfig
- type PublisherIdent
- type Session
- func (s *Session) Close()
- func (s *Session) DefaultDataChannel() *webrtc.DataChannel
- func (s *Session) KnownPeers() map[string]string
- func (s *Session) NewVideoTracks() <-chan *webrtc.TrackRemote
- func (s *Session) Publisher() PublisherIdent
- func (s *Session) RebindSlots(ctx context.Context, key int) error
- func (s *Session) ResetHandshakeState()
- func (s *Session) RunSlotKeepalive(ctx context.Context, firstKey int)
- func (s *Session) ServerHello() *goloom.ServerHello
- func (s *Session) SetupScreenShare(ctx context.Context) error
- func (s *Session) WaitForPeer(ctx context.Context, timeout time.Duration) (string, error)
- func (s *Session) WaitForPeerScreenShareBinding(ctx context.Context, peerID string, timeout time.Duration) (string, error)
- func (s *Session) WaitForSubRenegotiation(ctx context.Context, timeout time.Duration) bool
Constants ¶
const HandshakeInterval = 500 * time.Millisecond
const HandshakeTimeout = 20 * time.Second
HandshakeTimeout bounds one pairing attempt. It used to be 120 s, on the assumption that a slow peer just needed time. Measured 2026-09-26: when the SFU leaves our slot bound with an empty mid it NEVER resolves on its own — the peer's video simply never arrives, and nothing we send changes that (a setSlots re-ask during pairing makes it worse, see RunSlotKeepalive). Every observed recovery came from tearing the session down and joining again, which the supervisor does. So a short deadline is strictly better: it converts a two-minute dead wait into a retry that usually lands a working binding within seconds. Still comfortably above the 1-3 s a healthy pairing takes.
Variables ¶
var ErrHandshakeTimeout = errors.New("handshake timeout")
ErrHandshakeTimeout is returned when a pairing attempt runs out of time. Callers use it to decide whether rejoining is worth trying: it is the signature of a peer whose video the SFU never bound, which a fresh session usually fixes.
Functions ¶
func InitiatorLabel ¶
func InjectBandwidthAttribute ¶ added in v1.1.4
InjectBandwidthAttribute scans an SDP string and inserts a bandwidth declaration line ("b=AS:<kbps>") immediately after every matching m-section header. Existing b=AS lines for that m-section are stripped.
SFUs that respect SDP-declared bandwidth (most do, per RFC 4566 §5.8) allocate forwarding/encoding budgets up to this cap. Default behaviour without b=AS is the SFU's own per-publisher default (which Yandex Telemost appears to clamp to ~3 Mbps).
kind is the m-line kind ("video", "audio", "application") — only that kind's m-sections are touched.
func MakeKeyframePusher ¶
func NewPublisherStatsProvider ¶ added in v1.2.0
func NewPublisherStatsProvider(sender *tunnel.Sender, id PublisherIdent) func() *goloom.Telemetry
NewPublisherStatsProvider returns a telemetry callback that mirrors what a real Telemost web client emits every ~20 s: a getStats() dump proving a live encoder sits behind our published video track. It is driven by the Sender's real wire counters (TxSamples → framesEncoded, TxBytes → bytesSent) so the numbers stay consistent with the RTP the SFU actually receives, plus a framesPerSecond computed from the delta between calls.
This is a SIGNALLING-layer message only; it never touches the fake-VP9 media pipeline that carries the HELLO/HELLO_ACK handshake, so it cannot break pairing. id names our tracks as the SFU knows them (see Session.Publisher); a zero VideoSSRC omits the ssrc field.
func RunKeyframeRefresh ¶
func RunKeyframeRefreshFast ¶
func RunOpusSilenceLoop ¶
func SendInitialKeyframes ¶
func StartRTCPLoop ¶
func StartRTCPLoop(ctx context.Context, lg *log.Logger, tag string, pc *webrtc.PeerConnection, onPLI func(), onTWCC func(delivered, lost int))
startRTCPLoop reads RTCP from every RTPSender on the supplied PC. SFU feedback like PLI / FIR / REMB lands here for our publisher track. Returns immediately; per-sender goroutines run until ctx is done.
onPLI is called (in the read goroutine) whenever a PLI or FIR arrives on the video sender — caller should respond by pushing a fresh keyframe down the same track ASAP so the SFU stops dropping our frames. onTWCC, when non-nil, is invoked for every TransportLayerCC feedback packet with (delivered, lost) packet counts from that window — the closed-loop signal a congestion controller consumes to pace the sender.
Types ¶
type ParsedSlot ¶
type ParsedSlotsConfig ¶
type ParsedSlotsConfig struct {
Key int
Slots []ParsedSlot
}
ParsedSlotsConfig is what SetupScreenShare waits on — it carries the full snapshot so the consumer can pick out the peer's screen-share mid binding.
type PublisherIdent ¶ added in v1.2.0
PublisherIdent names the publisher's own tracks the way the SFU sees them in the publisherSdpOffer, so telemetry can be attributed to the right m-lines.
type Session ¶
type Session struct {
Logger *log.Logger
Conn *api.ConnectionResponse
Client *goloom.Client
Pub *peer.Wrapper
Sub *peer.Wrapper
AudioTrack *webrtc.TrackLocalStaticSample
VideoTrack *webrtc.TrackLocalStaticSample
DisplayAudioTrack *webrtc.TrackLocalStaticSample // populated by SetupScreenShare
DisplayVideoTrack *webrtc.TrackLocalStaticSample // populated by SetupScreenShare
// contains filtered or unexported fields
}
Session holds everything the test phases need after connect.
func SetupSession ¶
func SetupSession(ctx context.Context, lg *log.Logger, meeting, displayName string) (*Session, error)
SetupSession runs Stage 1-4 + creates both PCs, exchanges SDP, waits for connected, sends initial sized setSlots. After it returns the caller can use Session to drive tunnel sender / receiver.
func (*Session) Close ¶
func (s *Session) Close()
Close tears the Telemost session down properly: closes both PeerConnections (so DTLS sends a close_notify and ICE goes "failed" fast on the SFU side) AND closes the signalling WebSocket with a "bye" reason. The SFU drops the participant from the room as soon as the WebSocket goes away — without this step our restart cycles leave "zombie" peers that linger for ~30s on ICE timeout.
Safe to call multiple times. Best-effort: errors are logged, never returned, since at this point the caller is already tearing down.
Close order matters for "no zombie peer" behaviour:
- Say leave, so the SFU drops our participant right away rather than keeping it as a ghost publisher for minutes (a subscriber can bind its slot to a ghost and then receive nothing).
- Close the WebSocket — the signalling channel the SFU tracks presence on — BEFORE waiting for ICE/DTLS timeouts on the media side.
- Then close PeerConnections (DTLS close_notify). ICE state will converge to "closed" on its own; without WS bye first the SFU would keep our peer slot warm for the full ICE timeout (~30s).
func (*Session) DefaultDataChannel ¶
func (s *Session) DefaultDataChannel() *webrtc.DataChannel
func (*Session) KnownPeers ¶
KnownPeers returns participantId -> name for everyone the SFU has told us about (us + others). Caller filters out self.
func (*Session) NewVideoTracks ¶
func (s *Session) NewVideoTracks() <-chan *webrtc.TrackRemote
NewVideoTracks returns a channel that yields every remote video track as it arrives via OnTrack. The channel is buffered (size 8) — under normal conditions the consumer drains immediately so it never blocks the SUB PC callback thread.
func (*Session) Publisher ¶ added in v1.2.0
func (s *Session) Publisher() PublisherIdent
Publisher returns the SSRC and mids of our published tracks. The mids must be read from the live transceivers rather than assumed: SetupSession adds audio before video, so pion assigns mid "0" to AUDIO and "1" to VIDEO, and swapping them in telemetry would report a video encoder behind the audio m-line. Zero values mean the local description has not been set yet.
func (*Session) RebindSlots ¶
RebindSlots re-sends setSlots to force SFU to re-evaluate participant bindings. Called after both peers have completed SetupScreenShare so the later-renegotiated peer gets proper screen-share binding (not just participant binding to whoever was active when its setSlots first arrived).
func (*Session) ResetHandshakeState ¶
func (s *Session) ResetHandshakeState()
ResetHandshakeState is a no-op placeholder — handshake() is stateless and reads from the merged channel. Any leftover frames from the camera handshake are HELLO/HELLO_ACK frames which will be re-processed correctly (idempotent).
func (*Session) RunSlotKeepalive ¶ added in v1.2.0
RunSlotKeepalive renews the slot subscription for the life of ctx: setSlots is re-sent after 3, 8 and 15 s, then every slotKeepaliveEvery. Keys climb from firstKey so the SFU treats each message as the newest layout. It only re-sends setSlots on the existing session: no re-join, no room churn.
func (*Session) ServerHello ¶
func (s *Session) ServerHello() *goloom.ServerHello
func (*Session) SetupScreenShare ¶
SetupScreenShare adds DISPLAY_AUDIO + DISPLAY_VIDEO transceivers, drives a renegotiation round (publisherSdpOffer pcSeq=1 with all 4 tracks -> publisherSdpAnswer -> SetRemoteDescription), pushes updatePublisherTrackDescription, and finally sends an updated setSlots asking the SFU to forward peer's screen-share. Returns when both transceivers are wired up and the answer is applied. Caller is responsible for waiting on Session.slotsCh for the actual peer-binding (peer may not have renegotiated yet at this point).
pcSeq stays at 1 — same PeerConnection instance, just renegotiation.
func (*Session) WaitForPeer ¶
WaitForPeer blocks until we discover another participant (via updateDescription / upsertDescription). Returns the first non-self participantId. Times out after timeout.
func (*Session) WaitForPeerScreenShareBinding ¶
func (s *Session) WaitForPeerScreenShareBinding(ctx context.Context, peerID string, timeout time.Duration) (string, error)
WaitForPeerScreenShareBinding consumes slotsCh until it sees a slot with participantScreenSharingByMid for peerID. Returns the bound mid (e.g. "video_AA"). Times out after timeout.
func (*Session) WaitForSubRenegotiation ¶
WaitForSubRenegotiation blocks until the subscriber renegotiation loop processes at least one new subscriberSdpOffer. This is the signal that the SFU pushed us new tracks (e.g. the peer's screen-share). Returns true if a renegotiation happened, false on timeout.