forked from livekit/server-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsignalclient.go
353 lines (315 loc) · 8.81 KB
/
signalclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package lksdk
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"github.com/gorilla/websocket"
"github.com/pion/webrtc/v3"
"go.uber.org/atomic"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"github.com/livekit/protocol/livekit"
)
const PROTOCOL = 8
type SignalClient struct {
conn atomic.Value // *websocket.Conn
lock sync.Mutex
isClosed atomic.Bool
isStarted atomic.Bool
pendingResponse *livekit.SignalResponse
OnClose func()
OnAnswer func(sd webrtc.SessionDescription)
OnOffer func(sd webrtc.SessionDescription)
OnTrickle func(init webrtc.ICECandidateInit, target livekit.SignalTarget)
OnParticipantUpdate func([]*livekit.ParticipantInfo)
OnLocalTrackPublished func(response *livekit.TrackPublishedResponse)
OnSpeakersChanged func([]*livekit.SpeakerInfo)
OnConnectionQuality func([]*livekit.ConnectionQualityInfo)
OnRoomUpdate func(room *livekit.Room)
OnTrackMuted func(request *livekit.MuteTrackRequest)
OnLocalTrackUnpublished func(response *livekit.TrackUnpublishedResponse)
OnTokenRefresh func(refreshToken string)
OnLeave func(*livekit.LeaveRequest)
}
func NewSignalClient() *SignalClient {
c := &SignalClient{}
return c
}
func (c *SignalClient) Start() {
if c.isStarted.Swap(true) {
return
}
go c.readWorker()
}
func (c *SignalClient) IsStarted() bool {
return c.isStarted.Load()
}
func (c *SignalClient) Join(urlPrefix string, token string, params *ConnectParams) (*livekit.JoinResponse, error) {
if urlPrefix == "" {
return nil, ErrURLNotProvided
}
urlPrefix = ToWebsocketURL(urlPrefix)
urlSuffix := fmt.Sprintf("/rtc?protocol=%d&sdk=go&version=%s", PROTOCOL, Version)
if params.AutoSubscribe {
urlSuffix += "&auto_subscribe=1"
} else {
urlSuffix += "&auto_subscribe=0"
}
if params.Reconnect {
urlSuffix += "&reconnect=1"
}
u, err := url.Parse(urlPrefix + urlSuffix)
if err != nil {
return nil, err
}
header := newHeaderWithToken(token)
conn, _, err := websocket.DefaultDialer.Dial(u.String(), header)
if err != nil {
// use validate endpoint to get the actual error
validateSuffix := strings.Replace(urlSuffix, "/rtc", "/rtc/validate", 1)
res, err := http.Get(ToHttpURL(urlPrefix) + validateSuffix)
if err != nil || res.StatusCode == http.StatusOK {
// no specific errors to return if validate succeeds
return nil, ErrCannotConnectSignal
} else {
var errString string
switch res.StatusCode {
case http.StatusUnauthorized:
errString = "unauthorized: "
case http.StatusNotFound:
errString = "not found: "
case http.StatusServiceUnavailable:
errString = "unavailable: "
}
body, err := io.ReadAll(res.Body)
if err == nil {
errString += string(body)
}
return nil, errors.New(errString)
}
}
c.isClosed.Store(false)
c.conn.Store(conn)
// server should send join as soon as connected
res, err := c.readResponse()
if err != nil {
return nil, err
}
c.pendingResponse = nil
if params.Reconnect {
logger.Debugw("reconnect received response", "response", res.String())
if res != nil {
if res.GetLeave() != nil {
return nil, fmt.Errorf("reconnect received left, reason: %s", res.GetLeave().GetReason())
}
c.pendingResponse = res
}
return nil, nil
}
join := res.GetJoin()
if join == nil {
return nil, fmt.Errorf("unexpected response: %v", res.Message)
}
return join, nil
}
func (c *SignalClient) Close() {
if c.isClosed.Swap(true) {
return
}
if conn := c.websocketConn(); conn != nil {
_ = conn.Close()
}
}
func (c *SignalClient) SendICECandidate(candidate webrtc.ICECandidateInit, target livekit.SignalTarget) error {
return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_Trickle{
Trickle: ToProtoTrickle(candidate, target),
},
})
}
func (c *SignalClient) SendOffer(sd webrtc.SessionDescription) error {
return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_Offer{
Offer: ToProtoSessionDescription(sd),
},
})
}
func (c *SignalClient) SendAnswer(sd webrtc.SessionDescription) error {
return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_Answer{
Answer: ToProtoSessionDescription(sd),
},
})
}
func (c *SignalClient) SendMuteTrack(sid string, muted bool) error {
return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_Mute{
Mute: &livekit.MuteTrackRequest{
Sid: sid,
Muted: muted,
},
},
})
}
func (c *SignalClient) SendSyncState(state *livekit.SyncState) error {
return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_SyncState{
SyncState: state,
},
})
}
func (c *SignalClient) SendLeave() error {
return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_Leave{
Leave: &livekit.LeaveRequest{},
},
})
}
func (c *SignalClient) SendRequest(req *livekit.SignalRequest) error {
conn := c.websocketConn()
if conn == nil {
return errors.New("client is not connected")
}
payload, err := proto.Marshal(req)
if err != nil {
return err
}
c.lock.Lock()
defer c.lock.Unlock()
return conn.WriteMessage(websocket.BinaryMessage, payload)
}
func (c *SignalClient) SendUpdateTrackSettings(settings *livekit.UpdateTrackSettings) error {
return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_TrackSetting{
TrackSetting: settings,
},
})
}
func (c *SignalClient) SendUpdateParticipantMetadata(metadata *livekit.UpdateParticipantMetadata) error {
return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_UpdateMetadata{
UpdateMetadata: metadata,
},
})
}
func (c *SignalClient) readResponse() (*livekit.SignalResponse, error) {
if c.isClosed.Load() {
return nil, io.EOF
}
conn := c.websocketConn()
if conn == nil {
return nil, errors.New("cannot read response before join")
}
// handle special messages and pass on the rest
messageType, payload, err := conn.ReadMessage()
if err != nil {
return nil, err
}
msg := &livekit.SignalResponse{}
switch messageType {
case websocket.BinaryMessage:
// protobuf encoded
err := proto.Unmarshal(payload, msg)
return msg, err
case websocket.TextMessage:
// json encoded
err := protojson.Unmarshal(payload, msg)
return msg, err
default:
return nil, nil
}
}
func (c *SignalClient) handleResponse(res *livekit.SignalResponse) {
switch msg := res.Message.(type) {
case *livekit.SignalResponse_Answer:
if c.OnAnswer != nil {
c.OnAnswer(FromProtoSessionDescription(msg.Answer))
}
case *livekit.SignalResponse_Offer:
if c.OnOffer != nil {
c.OnOffer(FromProtoSessionDescription(msg.Offer))
}
case *livekit.SignalResponse_Trickle:
if c.OnTrickle != nil {
c.OnTrickle(FromProtoTrickle(msg.Trickle), msg.Trickle.Target)
}
case *livekit.SignalResponse_Update:
if c.OnParticipantUpdate != nil {
c.OnParticipantUpdate(msg.Update.Participants)
}
case *livekit.SignalResponse_SpeakersChanged:
if c.OnSpeakersChanged != nil {
c.OnSpeakersChanged(msg.SpeakersChanged.Speakers)
}
case *livekit.SignalResponse_TrackPublished:
if c.OnLocalTrackPublished != nil {
c.OnLocalTrackPublished(msg.TrackPublished)
}
case *livekit.SignalResponse_Mute:
if c.OnTrackMuted != nil {
c.OnTrackMuted(msg.Mute)
}
case *livekit.SignalResponse_ConnectionQuality:
if c.OnConnectionQuality != nil {
c.OnConnectionQuality(msg.ConnectionQuality.Updates)
}
case *livekit.SignalResponse_RoomUpdate:
if c.OnRoomUpdate != nil {
c.OnRoomUpdate(msg.RoomUpdate.Room)
}
case *livekit.SignalResponse_Leave:
if c.OnLeave != nil {
c.OnLeave(msg.Leave)
}
case *livekit.SignalResponse_RefreshToken:
if c.OnTokenRefresh != nil {
c.OnTokenRefresh(msg.RefreshToken)
}
case *livekit.SignalResponse_TrackUnpublished:
if c.OnLocalTrackUnpublished != nil {
c.OnLocalTrackUnpublished(msg.TrackUnpublished)
}
}
}
func (c *SignalClient) readWorker() {
defer func() {
c.isStarted.Store(false)
if c.OnClose != nil {
c.OnClose()
}
}()
if pending := c.pendingResponse; pending != nil {
c.handleResponse(pending)
c.pendingResponse = nil
}
for !c.isClosed.Load() {
res, err := c.readResponse()
if err != nil {
if !isIgnoredWebsocketError(err) && !c.isClosed.Load() {
logger.Infow("error while reading from signal client", "err", err)
}
return
}
c.handleResponse(res)
}
}
func (c *SignalClient) websocketConn() *websocket.Conn {
obj := c.conn.Load()
if obj == nil {
return nil
}
if conn, ok := obj.(*websocket.Conn); ok {
return conn
}
return nil
}
func isIgnoredWebsocketError(err error) bool {
if err == nil || err == io.EOF {
return true
}
return websocket.IsCloseError(err, websocket.CloseAbnormalClosure, websocket.CloseGoingAway, websocket.CloseNormalClosure, websocket.CloseNoStatusReceived)
}