Files
sing-box-extended-mirror/transport/call/livekit/client.go
T
2026-12-01 01:27:01 +03:00

859 lines
25 KiB
Go

package livekit
import (
"errors"
"fmt"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/transport/call/common"
"github.com/sagernet/sing-box/transport/call/headlessapi"
"github.com/sagernet/sing/common/logger"
N "github.com/sagernet/sing/common/network"
"sync"
"sync/atomic"
"time"
headless "github.com/kulikov0/headless-client"
"github.com/kulikov0/headless-client/webrtc"
"github.com/kulikov0/headless-client/websocket"
)
const (
ProtocolVersion = "15"
SDKName = "js"
SDKVersion = "2.7.0"
PingPeriod = 5 * time.Second
SinglePCProtocolVersion = 17
SinglePCSDKVersion = "2.22.0"
SinglePCClientProtocol = 2
TargetPublisher = signalTargetPublisher
TargetSubscriber = signalTargetSubscriber
TrackTypeAudio = trackTypeAudio
TrackTypeVideo = trackTypeVideo
TrackTypeData = trackTypeData
TrackSourceCamera = trackSourceCamera
TrackSourceScreenShare = trackSourceScreenShare
initialAudioSections = 3
initialVideoSections = 3
resumeResponseTimeout = 5 * time.Second
)
var (
errResumeRefused = errors.New("livekit: server refused resume")
resumeDelays = []time.Duration{
0,
300 * time.Millisecond,
1200 * time.Millisecond,
2700 * time.Millisecond,
4800 * time.Millisecond,
7 * time.Second,
7 * time.Second,
7 * time.Second,
7 * time.Second,
7 * time.Second,
}
)
type ICEServer = iceServer
type JoinResponse = joinResponse
type MediaSections = mediaSections
type Config struct {
ServerURL string
Token string
Origin string
UserAgent string
Codec Codec
Logger logger.ContextLogger
ConfigureSettingEngine func(*webrtc.SettingEngine)
DNSRouter adapter.DNSRouter
Dialer N.Dialer
SinglePeerConnection bool
}
type Client struct {
logger logger.ContextLogger
serverURL string
token string
origin string
userAgent string
codec Codec
configureSettingEngine func(*webrtc.SettingEngine)
dnsRouter adapter.DNSRouter
dialer N.Dialer
signalingConnection *websocket.Conn
signalingMutex sync.Mutex
join JoinResponse
publisher *webrtc.PeerConnection
subscriber *webrtc.PeerConnection
publisherMutex sync.Mutex
subscriberMutex sync.Mutex
publisherRemoteSet bool
subscriberRemoteSet bool
publisherPending []webrtc.ICECandidateInit
subscriberPending []webrtc.ICECandidateInit
singlePeerConnection bool
reliableChannel *webrtc.DataChannel
pendingInitialOffer *webrtc.SessionDescription
renegotiate bool
offerID atomic.Uint32
leaveReceived atomic.Bool
joined chan struct{}
joinedOnce sync.Once
closed atomic.Bool
OnReady func()
OnTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
OnDataChannel func(*webrtc.DataChannel)
OnPubConnected func()
OnSubConnected func()
OnParticipantUpdate func([]ParticipantInfo)
OnRemoteCandidate func(target int, candidate webrtc.ICECandidateInit)
OnRemoteSDP func(target int, sdpType, sdp string)
}
func NewClient(config Config) (*Client, error) {
if config.Codec == nil {
return nil, fmt.Errorf("livekit: no codec")
}
return &Client{
logger: config.Logger,
serverURL: config.ServerURL,
token: config.Token,
origin: config.Origin,
userAgent: config.UserAgent,
codec: config.Codec,
configureSettingEngine: config.ConfigureSettingEngine,
dnsRouter: config.DNSRouter,
dialer: config.Dialer,
singlePeerConnection: config.SinglePeerConnection,
joined: make(chan struct{}),
}, nil
}
func (c *Client) Join() JoinResponse { return c.join }
func (c *Client) PubPC() *webrtc.PeerConnection { return c.publisher }
func (c *Client) SubPC() *webrtc.PeerConnection { return c.subscriber }
func (c *Client) Joined() <-chan struct{} { return c.joined }
func (c *Client) ReliableDataChannel() *webrtc.DataChannel { return c.reliableChannel }
func (c *Client) Connect() error {
target, err := c.dialTarget()
if err != nil {
return err
}
connection, err := c.dial(target)
if err != nil {
return err
}
c.signalingMutex.Lock()
c.signalingConnection = connection
c.signalingMutex.Unlock()
c.logger.Info("[lk] signaling connected")
return nil
}
func (c *Client) ReadLoop() error {
defer c.Close()
for {
err := c.readSignals()
if c.closed.Load() {
return nil
}
if !c.singlePeerConnection || c.leaveReceived.Load() || c.join.ParticipantSID == "" {
return err
}
c.logger.Debug(fmt.Sprintf("[lk] signal lost: %v, resuming", err))
if resumeErr := c.resume(); resumeErr != nil {
c.logger.Debug(fmt.Sprintf("[lk] resume failed: %v", resumeErr))
return err
}
}
}
func (c *Client) PingLoop() {
select {
case <-c.joined:
case <-time.After(30 * time.Second):
return
}
period := PingPeriod
if c.join.PingIntervalSec > 0 {
period = time.Duration(c.join.PingIntervalSec) * time.Second
}
ticker := time.NewTicker(period)
defer ticker.Stop()
var sent int
for range ticker.C {
if c.closed.Load() {
return
}
if err := c.SendPing(); err != nil {
c.logger.Warn(fmt.Sprintf("[lk] ping send failed: %v", err))
if !c.singlePeerConnection {
return
}
continue
}
sent++
if sent <= 3 || sent%12 == 0 {
c.logger.Debug(fmt.Sprintf("[lk] ping #%d sent", sent))
}
}
}
func (c *Client) SendOffer(sdp string) error {
return c.sendSignal(c.codec.EncodeOffer(sdp, c.nextOfferID()))
}
func (c *Client) Negotiate() error {
c.publisherMutex.Lock()
defer c.publisherMutex.Unlock()
return c.negotiateLocked()
}
func (c *Client) SendAnswer(sdp string) error {
return c.sendSignal(c.codec.EncodeAnswer(sdp))
}
func (c *Client) SendTrickle(candidate webrtc.ICECandidateInit, target int) error {
return c.sendSignal(c.codec.EncodeTrickle(candidate, target))
}
func (c *Client) SendAddTrack(cid, name string, trackType, source int, width, height uint32) error {
return c.sendSignal(c.codec.EncodeAddTrack(AddTrackParams{
CID: cid,
Name: name,
Type: trackType,
Source: source,
Width: width,
Height: height,
}))
}
func (c *Client) SendLeave() error { return c.sendSignal(c.codec.EncodeLeave()) }
func (c *Client) SendPing() error {
return c.sendSignal(c.codec.EncodePing(time.Now().UnixMilli()))
}
func (c *Client) Close() {
if !c.closed.CompareAndSwap(false, true) {
return
}
c.signalingMutex.Lock()
signalingConnection := c.signalingConnection
c.signalingConnection = nil
c.signalingMutex.Unlock()
common.CloseWS(signalingConnection)
c.publisherMutex.Lock()
publisher := c.publisher
c.publisherMutex.Unlock()
c.subscriberMutex.Lock()
subscriber := c.subscriber
c.subscriberMutex.Unlock()
if publisher != nil {
_ = publisher.Close()
}
if subscriber != nil {
_ = subscriber.Close()
}
}
func (c *Client) dialTarget() (string, error) {
if !c.singlePeerConnection {
return c.codec.DialURL(c.serverURL, c.token)
}
offer, err := c.buildSinglePeerConnection()
if err != nil {
return "", err
}
request := encJoinRequest(joinRequest{
PublisherOffer: &sessionDescription{Type: "offer", SDP: offer.SDP, ID: c.nextOfferID()},
})
return c.codec.SinglePCDialURL(c.serverURL, c.token, request)
}
func (c *Client) dial(target string) (*websocket.Conn, error) {
headers := headless.ChromeWindows.Headers(headless.DestWebSocket)
if c.userAgent != "" {
headers.Set("User-Agent", c.userAgent)
}
if c.origin != "" {
headers.Set("Origin", c.origin)
}
dialContext := common.DialContext(c.dialer)
dialer := headless.ChromeWindows.WebSocketDialer(headless.TLSOptions{DialContext: dialContext})
dialer.NetDialContext = dialContext
connection, response, err := dialer.Dial(target, headers)
if err != nil {
if response != nil {
return nil, fmt.Errorf("ws dial: %w, status %d", err, response.StatusCode)
}
return nil, fmt.Errorf("ws dial: %w", err)
}
return connection, nil
}
func (c *Client) sendSignal(payload []byte) error {
if payload == nil {
return nil
}
c.signalingMutex.Lock()
defer c.signalingMutex.Unlock()
if c.signalingConnection == nil {
return fmt.Errorf("ws not connected")
}
return c.signalingConnection.WriteMessage(c.codec.MessageType(), payload)
}
func (c *Client) nextOfferID() uint32 {
if !c.singlePeerConnection {
return 0
}
return c.offerID.Add(1)
}
func (c *Client) negotiateLocked() error {
if c.publisher == nil {
return fmt.Errorf("publisher not created")
}
if c.pendingInitialOffer != nil || c.publisher.SignalingState() == webrtc.SignalingStateHaveLocalOffer {
c.renegotiate = true
return nil
}
offer, err := c.publisher.CreateOffer(nil)
if err != nil {
return fmt.Errorf("create offer: %w", err)
}
if err := c.publisher.SetLocalDescription(offer); err != nil {
return fmt.Errorf("set local offer: %w", err)
}
if err := c.SendOffer(offer.SDP); err != nil {
return fmt.Errorf("send offer: %w", err)
}
c.logger.Debug(fmt.Sprintf("[lk] sent publisher offer, %d bytes", len(offer.SDP)))
return nil
}
func (c *Client) iceServersAsWebRTC(servers []ICEServer) []webrtc.ICEServer {
resolvedServers := make([]webrtc.ICEServer, 0, len(servers))
for _, server := range servers {
urls := common.NormalizeICEURLs(server.URLs)
iceServer := webrtc.ICEServer{URLs: urls}
if server.Username != "" {
iceServer.Username = server.Username
iceServer.Credential = server.Credential
}
resolvedServers = append(resolvedServers, iceServer)
}
return resolvedServers
}
func (c *Client) webRTCAPI() (*webrtc.API, error) {
api, err := headlessapi.WebRTCAPI(headlessapi.Options{
Profile: headless.ChromeWindows,
Dialer: c.dialer,
DNSRouter: c.dnsRouter,
Configure: func(settingEngine *webrtc.SettingEngine) {
if c.configureSettingEngine != nil {
c.configureSettingEngine(settingEngine)
}
settingEngine.DetachDataChannels()
},
})
if err != nil {
return nil, fmt.Errorf("build webrtc api: %w", err)
}
return api, nil
}
func (c *Client) watchPublisher(publisher *webrtc.PeerConnection) {
publisher.OnICECandidate(func(candidate *webrtc.ICECandidate) {
if candidate == nil {
c.logger.Debug("[lk] pub ICE gathering complete")
return
}
c.logger.Debug(fmt.Sprintf("[lk] pub local cand: %s", candidate.String()))
_ = c.SendTrickle(candidate.ToJSON(), TargetPublisher)
})
publisher.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
c.logger.Debug(fmt.Sprintf("[lk] pub PC state: %s", state.String()))
if state == webrtc.PeerConnectionStateConnected && c.OnPubConnected != nil {
c.OnPubConnected()
}
})
publisher.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
c.logger.Debug(fmt.Sprintf("[lk] pub ICE state: %s", state.String()))
})
}
func (c *Client) buildPeerConnections() error {
config := webrtc.Configuration{ICEServers: c.iceServersAsWebRTC(c.join.ICEServers)}
api, err := c.webRTCAPI()
if err != nil {
return err
}
publisher, err := api.NewPeerConnection(config)
if err != nil {
return fmt.Errorf("create pub pc: %w", err)
}
subscriber, err := api.NewPeerConnection(config)
if err != nil {
_ = publisher.Close()
return fmt.Errorf("create sub pc: %w", err)
}
c.publisherMutex.Lock()
c.publisher = publisher
c.publisherMutex.Unlock()
c.subscriberMutex.Lock()
c.subscriber = subscriber
c.subscriberMutex.Unlock()
c.watchPublisher(publisher)
subscriber.OnICECandidate(func(candidate *webrtc.ICECandidate) {
if candidate == nil {
c.logger.Debug("[lk] sub ICE gathering complete")
return
}
c.logger.Debug(fmt.Sprintf("[lk] sub local cand: %s", candidate.String()))
_ = c.SendTrickle(candidate.ToJSON(), TargetSubscriber)
})
subscriber.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
c.logger.Debug(fmt.Sprintf("[lk] sub PC state: %s", state.String()))
if state == webrtc.PeerConnectionStateConnected && c.OnSubConnected != nil {
c.OnSubConnected()
}
})
subscriber.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
c.logger.Debug(fmt.Sprintf("[lk] sub ICE state: %s", state.String()))
})
subscriber.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
c.logger.Debug(fmt.Sprintf("[lk] sub remote track: %s", track.Codec().MimeType))
if c.OnTrack != nil {
c.OnTrack(track, receiver)
}
})
subscriber.OnDataChannel(func(channel *webrtc.DataChannel) {
c.logger.Debug(fmt.Sprintf("[lk] sub data channel: %s", channel.Label()))
if c.OnDataChannel != nil {
c.OnDataChannel(channel)
}
})
c.logger.Debug(fmt.Sprintf("[lk] PCs created, %d ICE servers", len(c.join.ICEServers)))
for i, server := range c.join.ICEServers {
c.logger.Debug(fmt.Sprintf("[lk] iceServer[%d]: urls=%v hasCred=%v", i, server.URLs, server.Username != ""))
}
return nil
}
func (c *Client) buildSinglePeerConnection() (webrtc.SessionDescription, error) {
api, err := c.webRTCAPI()
if err != nil {
return webrtc.SessionDescription{}, err
}
peerConnection, err := api.NewPeerConnection(webrtc.Configuration{})
if err != nil {
return webrtc.SessionDescription{}, fmt.Errorf("create pc: %w", err)
}
c.watchPublisher(peerConnection)
peerConnection.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
c.logger.Debug(fmt.Sprintf("[lk] remote track: %s", track.Codec().MimeType))
if c.OnTrack != nil {
c.OnTrack(track, receiver)
}
})
peerConnection.OnDataChannel(func(channel *webrtc.DataChannel) {
c.logger.Debug(fmt.Sprintf("[lk] remote data channel: %s", channel.Label()))
if c.OnDataChannel != nil {
c.OnDataChannel(channel)
}
})
ordered := true
unordered := false
var noRetransmits uint16
lossyChannel, err := peerConnection.CreateDataChannel("_lossy", &webrtc.DataChannelInit{
Ordered: &unordered,
MaxRetransmits: &noRetransmits,
})
if err != nil {
_ = peerConnection.Close()
return webrtc.SessionDescription{}, fmt.Errorf("create lossy DC: %w", err)
}
reliableChannel, err := peerConnection.CreateDataChannel("_reliable", &webrtc.DataChannelInit{
Ordered: &ordered,
})
if err != nil {
_ = peerConnection.Close()
return webrtc.SessionDescription{}, fmt.Errorf("create reliable DC: %w", err)
}
dataTrackChannel, err := peerConnection.CreateDataChannel("_data_track", &webrtc.DataChannelInit{
Ordered: &unordered,
MaxRetransmits: &noRetransmits,
})
if err != nil {
_ = peerConnection.Close()
return webrtc.SessionDescription{}, fmt.Errorf("create data track DC: %w", err)
}
for _, channel := range []*webrtc.DataChannel{lossyChannel, dataTrackChannel} {
channel.OnOpen(func() { go c.drainDataChannel(channel) })
}
if err := addRecvSections(peerConnection, initialAudioSections, initialVideoSections); err != nil {
_ = peerConnection.Close()
return webrtc.SessionDescription{}, err
}
offer, err := peerConnection.CreateOffer(nil)
if err != nil {
_ = peerConnection.Close()
return webrtc.SessionDescription{}, fmt.Errorf("create initial offer: %w", err)
}
c.publisherMutex.Lock()
c.publisher = peerConnection
c.reliableChannel = reliableChannel
c.pendingInitialOffer = &offer
c.publisherMutex.Unlock()
return offer, nil
}
func (c *Client) drainDataChannel(channel *webrtc.DataChannel) {
rawChannel, err := channel.Detach()
if err != nil {
c.logger.Debug(fmt.Sprintf("[lk] detach %s: %v", channel.Label(), err))
return
}
buffer := make([]byte, common.DCBufSize)
for {
if _, err := rawChannel.Read(buffer); err != nil {
return
}
}
}
func (c *Client) applyICEServers(servers []ICEServer) {
resolved := c.iceServersAsWebRTC(servers)
c.publisherMutex.Lock()
defer c.publisherMutex.Unlock()
if c.publisher == nil {
return
}
configuration := c.publisher.GetConfiguration()
configuration.ICEServers = resolved
if err := c.publisher.SetConfiguration(configuration); err != nil {
c.logger.Debug(fmt.Sprintf("[lk] set ICE servers: %v", err))
return
}
for i, server := range servers {
c.logger.Debug(fmt.Sprintf("[lk] iceServer[%d]: urls=%v hasCred=%v", i, server.URLs, server.Username != ""))
}
}
func (c *Client) addMediaSections(audioSections, videoSections int) {
c.publisherMutex.Lock()
defer c.publisherMutex.Unlock()
if c.publisher == nil {
return
}
if err := addRecvSections(c.publisher, audioSections, videoSections); err != nil {
c.logger.Debug(fmt.Sprintf("[lk] %v", err))
return
}
if err := c.negotiateLocked(); err != nil {
c.logger.Debug(fmt.Sprintf("[lk] negotiate media sections: %v", err))
}
}
func addRecvSections(peerConnection *webrtc.PeerConnection, audioSections, videoSections int) error {
receiveOnly := webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionRecvonly}
for range audioSections {
if _, err := peerConnection.AddTransceiverFromKind(webrtc.RTPCodecTypeAudio, receiveOnly); err != nil {
return fmt.Errorf("add audio section: %w", err)
}
}
for range videoSections {
if _, err := peerConnection.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo, receiveOnly); err != nil {
return fmt.Errorf("add video section: %w", err)
}
}
return nil
}
func (c *Client) handleSignal(data []byte) {
event, err := c.codec.Decode(data)
if err != nil {
c.logger.Warn(fmt.Sprintf("[lk] decode signal: %v", err))
return
}
switch event.Kind {
case EventJoin:
c.join = *event.Join
c.logger.Info(fmt.Sprintf("[lk] join: room=%s participant=%s subscriberPrimary=%v iceServers=%d pingTimeout=%ds pingInterval=%ds",
c.join.RoomName, c.join.ParticipantID, c.join.SubscriberPrimary, len(c.join.ICEServers),
c.join.PingTimeoutSec, c.join.PingIntervalSec))
if c.singlePeerConnection {
c.applyICEServers(c.join.ICEServers)
c.joinedOnce.Do(func() { close(c.joined) })
return
}
if err := c.buildPeerConnections(); err != nil {
c.logger.Error(fmt.Sprintf("[lk] %v", err))
return
}
c.joinedOnce.Do(func() { close(c.joined) })
if c.OnReady != nil {
c.OnReady()
}
case EventAnswer:
c.logger.Debug(fmt.Sprintf("[lk] pub answer received, %d bytes", len(event.SDP)))
c.applyPubAnswer(event.SDP)
case EventOffer:
if c.singlePeerConnection {
c.logger.Debug(fmt.Sprintf("[lk] ignored offer, %d bytes", len(event.SDP)))
return
}
c.logger.Debug(fmt.Sprintf("[lk] sub offer received, %d bytes", len(event.SDP)))
c.applySubOfferAndAnswer(event.SDP)
case EventTrickle:
c.logger.Debug(fmt.Sprintf("[lk] trickle target=%d", event.Trickle.Target))
c.applyRemoteTrickle(*event.Trickle)
case EventToken:
c.token = event.Token
c.logger.Debug("[lk] token refreshed")
case EventReconnect:
c.applyICEServers(event.ICEServers)
case EventMediaSections:
c.logger.Debug(fmt.Sprintf("[lk] media sections requested audio=%d video=%d", event.MediaSections.Audios, event.MediaSections.Videos))
c.addMediaSections(event.MediaSections.Audios, event.MediaSections.Videos)
case EventLeave:
if event.Leave == nil || event.Leave.Action != leaveActionResume {
c.leaveReceived.Store(true)
}
if event.Leave != nil {
c.logger.Debug(fmt.Sprintf("[lk] ignored leave reason=%s action=%s",
DisconnectReasonName(event.Leave.Reason), LeaveActionName(event.Leave.Action)))
} else {
c.logger.Debug("[lk] ignored leave")
}
case EventUpdate:
if c.OnParticipantUpdate != nil {
c.OnParticipantUpdate(event.Participants)
}
default:
c.logger.Debug(fmt.Sprintf("[lk] unhandled signal, %d bytes", len(data)))
}
}
func (c *Client) applyPubAnswer(sdp string) {
if c.OnRemoteSDP != nil {
c.OnRemoteSDP(TargetPublisher, "answer", sdp)
}
c.publisherMutex.Lock()
if c.publisher == nil {
c.publisherMutex.Unlock()
return
}
initialOffer := c.pendingInitialOffer
c.pendingInitialOffer = nil
if initialOffer != nil {
if err := c.publisher.SetLocalDescription(*initialOffer); err != nil {
c.publisherMutex.Unlock()
c.logger.Debug(fmt.Sprintf("[lk] set initial local offer: %v", err))
return
}
}
if err := c.publisher.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeAnswer, SDP: sdp}); err != nil {
c.publisherMutex.Unlock()
c.logger.Warn(fmt.Sprintf("[lk] set pub remote answer: %v", err))
return
}
c.publisherRemoteSet = true
c.drainPendingLocked(c.publisher, &c.publisherPending)
renegotiate := c.renegotiate
c.renegotiate = false
c.publisherMutex.Unlock()
if initialOffer != nil && c.OnReady != nil {
c.OnReady()
}
if renegotiate {
if err := c.Negotiate(); err != nil {
c.logger.Debug(fmt.Sprintf("[lk] renegotiate: %v", err))
}
}
}
func (c *Client) applySubOfferAndAnswer(sdp string) {
if c.OnRemoteSDP != nil {
c.OnRemoteSDP(TargetSubscriber, "offer", sdp)
}
c.subscriberMutex.Lock()
if c.subscriber == nil {
c.subscriberMutex.Unlock()
return
}
subscriber := c.subscriber
if err := subscriber.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: sdp}); err != nil {
c.subscriberMutex.Unlock()
c.logger.Warn(fmt.Sprintf("[lk] set sub remote offer: %v", err))
return
}
c.subscriberRemoteSet = true
c.drainPendingLocked(subscriber, &c.subscriberPending)
c.subscriberMutex.Unlock()
answer, err := subscriber.CreateAnswer(nil)
if err != nil {
c.logger.Warn(fmt.Sprintf("[lk] create sub answer: %v", err))
return
}
if err := subscriber.SetLocalDescription(answer); err != nil {
c.logger.Warn(fmt.Sprintf("[lk] set sub local answer: %v", err))
return
}
if err := c.SendAnswer(answer.SDP); err != nil {
c.logger.Warn(fmt.Sprintf("[lk] send answer: %v", err))
}
}
func (c *Client) drainPendingLocked(peerConnection *webrtc.PeerConnection, pending *[]webrtc.ICECandidateInit) {
for _, candidate := range *pending {
if err := peerConnection.AddICECandidate(candidate); err != nil {
c.logger.Warn(fmt.Sprintf("[lk] add pending candidate: %v", err))
}
}
*pending = nil
}
func (c *Client) applyRemoteTrickle(trickle TrickleEvent) {
if c.OnRemoteCandidate != nil {
c.OnRemoteCandidate(trickle.Target, trickle.Candidate)
}
mu := &c.subscriberMutex
peerConnection := &c.subscriber
ready := &c.subscriberRemoteSet
pending := &c.subscriberPending
if trickle.Target == TargetPublisher || c.singlePeerConnection {
mu = &c.publisherMutex
peerConnection = &c.publisher
ready = &c.publisherRemoteSet
pending = &c.publisherPending
}
mu.Lock()
defer mu.Unlock()
if *peerConnection == nil || !*ready {
*pending = append(*pending, trickle.Candidate)
return
}
if err := (*peerConnection).AddICECandidate(trickle.Candidate); err != nil {
c.logger.Warn(fmt.Sprintf("[lk] add candidate: %v", err))
}
}
func (c *Client) readSignals() error {
c.signalingMutex.Lock()
signalingConnection := c.signalingConnection
c.signalingMutex.Unlock()
if signalingConnection == nil {
return fmt.Errorf("ws not connected")
}
for {
messageType, data, err := signalingConnection.ReadMessage()
if err != nil {
return err
}
if !c.codec.Accepts(messageType) {
continue
}
c.handleSignal(data)
}
}
func (c *Client) resume() error {
var lastError error
for attempt, delay := range resumeDelays {
time.Sleep(delay)
if c.closed.Load() {
return fmt.Errorf("client closed")
}
err := c.resumeSignal()
if err == nil {
c.logger.Debug(fmt.Sprintf("[lk] signal resumed, attempt %d", attempt+1))
return c.resumePublisher()
}
if errors.Is(err, errResumeRefused) {
return err
}
c.logger.Debug(fmt.Sprintf("[lk] resume attempt %d: %v", attempt+1, err))
lastError = err
}
return lastError
}
func (c *Client) resumeSignal() error {
c.signalingMutex.Lock()
previous := c.signalingConnection
c.signalingConnection = nil
c.signalingMutex.Unlock()
common.CloseWS(previous)
request := encJoinRequest(joinRequest{Reconnect: true, ParticipantSID: c.join.ParticipantSID})
target, err := c.codec.SinglePCDialURL(c.serverURL, c.token, request)
if err != nil {
return err
}
connection, err := c.dial(target)
if err != nil {
return err
}
if err := connection.SetReadDeadline(time.Now().Add(resumeResponseTimeout)); err != nil {
common.CloseWS(connection)
return err
}
_, data, err := connection.ReadMessage()
if err != nil {
common.CloseWS(connection)
return fmt.Errorf("read first message: %w", err)
}
if err := connection.SetReadDeadline(time.Time{}); err != nil {
common.CloseWS(connection)
return err
}
first, err := c.codec.Decode(data)
if err != nil {
common.CloseWS(connection)
return err
}
if first.Kind == EventLeave {
common.CloseWS(connection)
if first.Leave != nil {
return fmt.Errorf("%w: reason=%s", errResumeRefused, DisconnectReasonName(first.Leave.Reason))
}
return errResumeRefused
}
c.signalingMutex.Lock()
if c.closed.Load() {
c.signalingMutex.Unlock()
common.CloseWS(connection)
return fmt.Errorf("client closed")
}
c.signalingConnection = connection
c.signalingMutex.Unlock()
c.handleSignal(data)
return nil
}
func (c *Client) resumePublisher() error {
c.publisherMutex.Lock()
defer c.publisherMutex.Unlock()
if c.publisher == nil || c.pendingInitialOffer != nil {
return fmt.Errorf("publisher was never negotiated")
}
offerPending := c.publisher.SignalingState() == webrtc.SignalingStateHaveLocalOffer
if !offerPending && !c.renegotiate {
return nil
}
if offerPending {
if err := c.publisher.SetLocalDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeRollback}); err != nil {
return fmt.Errorf("roll back pending offer: %w", err)
}
}
c.renegotiate = false
return c.negotiateLocked()
}