/
room.go
321 lines (280 loc) · 7.71 KB
/
room.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
package lksdk
import (
"sort"
"strings"
"sync"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/pion/webrtc/v3"
"github.com/thoas/go-funk"
)
type TrackPubCallback func(track Track, pub TrackPublication, participant *RemoteParticipant)
type PubCallback func(pub TrackPublication, participant *RemoteParticipant)
type ConnectInfo struct {
APIKey string
APISecret string
RoomName string
ParticipantIdentity string
ParticipantMetadata string
}
type ConnectParams struct {
AutoSubscribe bool
}
type ConnectOption func(*ConnectParams)
func WithAutoSubscribe(val bool) ConnectOption {
return func(p *ConnectParams) {
p.AutoSubscribe = val
}
}
type Room struct {
engine *RTCEngine
SID string
Name string
LocalParticipant *LocalParticipant
Callback *RoomCallback
participants *sync.Map
metadata string
activeSpeakers []Participant
lock sync.RWMutex
}
func ConnectToRoom(url string, info ConnectInfo, opts ...ConnectOption) (*Room, error) {
// generate token
at := auth.NewAccessToken(info.APIKey, info.APISecret)
grant := &auth.VideoGrant{
RoomJoin: true,
Room: info.RoomName,
}
at.AddGrant(grant).
SetIdentity(info.ParticipantIdentity).
SetMetadata(info.ParticipantMetadata)
token, err := at.ToJWT()
if err != nil {
return nil, err
}
return ConnectToRoomWithToken(url, token, opts...)
}
func ConnectToRoomWithToken(url, token string, opts ...ConnectOption) (*Room, error) {
params := &ConnectParams{
AutoSubscribe: true,
}
for _, opt := range opts {
opt(params)
}
engine := NewRTCEngine()
r := &Room{
engine: engine,
participants: &sync.Map{},
Callback: NewRoomCallback(),
}
r.LocalParticipant = newLocalParticipant(engine, r.Callback)
// callbacks from engine
engine.OnMediaTrack = r.handleMediaTrack
engine.OnDisconnected = r.handleDisconnect
engine.OnParticipantUpdate = r.handleParticipantUpdate
engine.OnActiveSpeakersChanged = r.handleActiveSpeakerChange
engine.OnSpeakersChanged = r.handleSpeakersChange
engine.OnDataReceived = r.handleDataReceived
engine.OnConnectionQuality = r.handleConnectionQualityUpdate
engine.OnRoomUpdate = r.handleRoomUpdate
joinRes, err := engine.Join(url, token, params)
if err != nil {
return nil, err
}
r.LocalParticipant.updateInfo(joinRes.Participant)
for _, pi := range joinRes.OtherParticipants {
r.addRemoteParticipant(pi)
}
return r, nil
}
func (r *Room) Disconnect() {
_ = r.engine.client.SendLeave()
r.engine.Close()
}
func (r *Room) GetParticipant(sid string) *RemoteParticipant {
partRaw, ok := r.participants.Load(sid)
if !ok || partRaw == nil {
return nil
}
return partRaw.(*RemoteParticipant)
}
func (r *Room) GetParticipants() []*RemoteParticipant {
var participants []*RemoteParticipant
r.participants.Range(func(_, value interface{}) bool {
participants = append(participants, value.(*RemoteParticipant))
return true
})
return participants
}
func (r *Room) ActiveSpeakers() []Participant {
r.lock.RLock()
defer r.lock.RUnlock()
return r.activeSpeakers
}
func (r *Room) Metadata() string {
r.lock.RLock()
defer r.lock.RUnlock()
return r.metadata
}
func (r *Room) addRemoteParticipant(pi *livekit.ParticipantInfo) *RemoteParticipant {
pRaw, ok := r.participants.Load(pi.Sid)
if ok {
return pRaw.(*RemoteParticipant)
}
p := newRemoteParticipant(pi, r.Callback)
r.participants.Store(pi.Sid, p)
return p
}
func (r *Room) handleMediaTrack(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
// ensure we have the participant
participantID, trackID := unpackStreamID(track.StreamID())
if trackID == "" {
trackID = track.ID()
}
p := r.GetParticipant(participantID)
if p == nil {
p = r.addRemoteParticipant(&livekit.ParticipantInfo{
Sid: participantID,
})
}
p.addSubscribedMediaTrack(track, trackID, receiver)
}
func (r *Room) handleDisconnect() {
r.Callback.OnDisconnected()
r.engine.Close()
}
func (r *Room) handleDataReceived(userPacket *livekit.UserPacket) {
if userPacket.ParticipantSid == r.LocalParticipant.sid {
// if sent by itself, do not handle data
return
}
p := r.GetParticipant(userPacket.ParticipantSid)
if p == nil {
return
}
p.Callback.OnDataReceived(userPacket.Payload, p)
r.Callback.OnDataReceived(userPacket.Payload, p)
}
func (r *Room) handleParticipantUpdate(participants []*livekit.ParticipantInfo) {
for _, pi := range participants {
p := r.GetParticipant(pi.Sid)
isNew := p == nil
if pi.State == livekit.ParticipantInfo_DISCONNECTED {
// remove
if p != nil {
r.handleParticipantDisconnect(p)
}
} else if isNew {
p = r.addRemoteParticipant(pi)
r.Callback.OnParticipantConnected(p)
} else {
p.updateInfo(pi)
}
}
}
func (r *Room) handleParticipantDisconnect(p *RemoteParticipant) {
r.participants.Delete(p.SID())
p.unpublishAllTracks()
r.Callback.OnParticipantDisconnected(p)
}
func (r *Room) handleActiveSpeakerChange(speakers []*livekit.SpeakerInfo) {
var activeSpeakers []Participant
seenSids := make(map[string]bool)
for _, s := range speakers {
seenSids[s.Sid] = true
if s.Sid == r.LocalParticipant.sid {
r.LocalParticipant.setAudioLevel(s.Level)
r.LocalParticipant.setIsSpeaking(true)
activeSpeakers = append(activeSpeakers, r.LocalParticipant)
} else {
p := r.GetParticipant(s.Sid)
if p == nil {
continue
}
p.setAudioLevel(s.Level)
p.setIsSpeaking(true)
activeSpeakers = append(activeSpeakers, p)
}
}
if !seenSids[r.LocalParticipant.sid] {
r.LocalParticipant.setAudioLevel(0)
}
r.participants.Range(func(_, value interface{}) bool {
p := value.(*RemoteParticipant)
if !seenSids[p.sid] {
p.setAudioLevel(0)
p.setIsSpeaking(false)
}
return true
})
r.lock.Lock()
r.activeSpeakers = activeSpeakers
r.lock.Unlock()
r.Callback.OnActiveSpeakersChanged(activeSpeakers)
}
func (r *Room) handleSpeakersChange(speakerUpdates []*livekit.SpeakerInfo) {
speakerMap := make(map[string]Participant)
for _, p := range r.ActiveSpeakers() {
speakerMap[p.SID()] = p
}
for _, info := range speakerUpdates {
var participant Participant
if info.Sid == r.LocalParticipant.SID() {
participant = r.LocalParticipant
} else {
if obj, ok := r.participants.Load(info.Sid); ok {
if p, ok := obj.(Participant); ok {
participant = p
}
}
}
if participant == nil {
break
}
participant.setAudioLevel(info.Level)
participant.setIsSpeaking(info.Active)
if info.Active {
speakerMap[info.Sid] = participant
} else {
delete(speakerMap, info.Sid)
}
}
activeSpeakers := funk.Values(speakerMap).([]Participant)
sort.Slice(activeSpeakers, func(i, j int) bool {
return activeSpeakers[i].AudioLevel() > activeSpeakers[j].AudioLevel()
})
r.lock.Lock()
r.activeSpeakers = activeSpeakers
r.lock.Unlock()
r.Callback.OnActiveSpeakersChanged(activeSpeakers)
}
func (r *Room) handleConnectionQualityUpdate(updates []*livekit.ConnectionQualityInfo) {
for _, update := range updates {
if update.ParticipantSid == r.LocalParticipant.SID() {
r.LocalParticipant.setConnectionQualityInfo(update)
} else {
p := r.GetParticipant(update.ParticipantSid)
if p != nil {
p.setConnectionQualityInfo(update)
} else {
logger.Info("could not find participant", "sid", update.ParticipantSid,
"localParticipant", r.LocalParticipant.SID())
}
}
}
}
func (r *Room) handleRoomUpdate(room *livekit.Room) {
if r.Metadata() == room.Metadata {
return
}
r.lock.Lock()
r.metadata = room.Metadata
r.lock.Unlock()
r.Callback.OnRoomMetadataChanged(room.Metadata)
}
func unpackStreamID(packed string) (participantId string, trackId string) {
parts := strings.Split(packed, "|")
if len(parts) > 1 {
return parts[0], packed[len(parts[0])+1:]
}
return packed, ""
}