session

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const HandshakeInterval = 500 * time.Millisecond
View Source
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

View Source
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 Handshake

func Handshake(ctx context.Context, lg *log.Logger, sess *Session, sender *tunnel.Sender, in <-chan tunnel.ReceivedFrame, round byte) (string, error)

func InitiatorLabel

func InitiatorLabel(b bool) string

func InjectBandwidthAttribute added in v1.1.4

func InjectBandwidthAttribute(sdp string, kind string, kbps int) string

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 MakeKeyframePusher(track *webrtc.TrackLocalStaticSample, lg *log.Logger, cooldown time.Duration, writeMu *sync.Mutex) func()

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 RunKeyframeRefresh(ctx context.Context, lg *log.Logger, track *webrtc.TrackLocalStaticSample, writeMu *sync.Mutex)

func RunKeyframeRefreshFast

func RunKeyframeRefreshFast(ctx context.Context, lg *log.Logger, track *webrtc.TrackLocalStaticSample, interval time.Duration)

func RunOpusSilenceLoop

func RunOpusSilenceLoop(ctx context.Context, lg *log.Logger, track *webrtc.TrackLocalStaticSample)

func SendInitialKeyframes

func SendInitialKeyframes(lg *log.Logger, track *webrtc.TrackLocalStaticSample, n int) error

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 ParsedSlot struct {
	Index         int
	Type          string // "selfView" / "participant" / "participantVideoByMid" / "participantScreenSharingByMid" / "empty"
	ParticipantID string
	Mid           string // populated for *ByMid types
}

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

type PublisherIdent struct {
	VideoSSRC uint32
	VideoMid  string
	AudioMid  string
}

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:

  1. 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).
  2. Close the WebSocket — the signalling channel the SFU tracks presence on — BEFORE waiting for ICE/DTLS timeouts on the media side.
  3. 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

func (s *Session) KnownPeers() map[string]string

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

func (s *Session) RebindSlots(ctx context.Context, key int) error

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

func (s *Session) RunSlotKeepalive(ctx context.Context, firstKey int)

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

func (s *Session) SetupScreenShare(ctx context.Context) error

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

func (s *Session) WaitForPeer(ctx context.Context, timeout time.Duration) (string, error)

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

func (s *Session) WaitForSubRenegotiation(ctx context.Context, timeout time.Duration) bool

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.

Jump to

Keyboard shortcuts

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