forked from inlivedev/sfu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroom.go
278 lines (222 loc) · 6.38 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
package sfu
import (
"context"
"errors"
"log"
"sync"
"time"
"github.com/pion/webrtc/v3"
)
const (
StateRoomOpen = "open"
StateRoomClosed = "closed"
EventRoomClosed = "room_closed"
EventRoomClientLeft = "room_client_left"
)
var (
ErrClientExists = errors.New("client already exists")
ErrRoomIsClosed = errors.New("room is closed")
ErrRoomIsNotEmpty = errors.New("room is not empty")
ErrDecodingData = errors.New("error decoding data")
ErrEncodingData = errors.New("error encoding data")
ErrNotFound = errors.New("not found")
)
type Options struct {
WebRTCPort int
ConnectRemoteRoomTimeout time.Duration
EnableBridging bool
}
func DefaultOptions() Options {
return Options{
WebRTCPort: 50005,
ConnectRemoteRoomTimeout: 30 * time.Second,
}
}
type Event struct {
Type string
Time time.Time
Data map[string]interface{}
}
type Room struct {
answerChans map[string]chan webrtc.SessionDescription
candidateChans map[string]chan webrtc.ICECandidate
callbacksClientRemoved []func(id string)
callbacksRoomClosed []func(id string)
Context context.Context
cancelContext context.CancelFunc
eventChan chan Event
ID string `json:"id"`
offerChans map[string]chan webrtc.SessionDescription
RenegotiationChan map[string]chan bool
Name string `json:"name"`
mutex *sync.Mutex
sfu *SFU
State string
Type string
extensions []IExtension
}
func newRoom(ctx context.Context, id, name string, sfu *SFU, roomType string) *Room {
localContext, cancel := context.WithCancel(ctx)
room := &Room{
ID: id,
Context: localContext,
cancelContext: cancel,
sfu: sfu,
State: StateRoomOpen,
answerChans: make(map[string]chan webrtc.SessionDescription),
offerChans: make(map[string]chan webrtc.SessionDescription),
candidateChans: make(map[string]chan webrtc.ICECandidate),
Name: name,
mutex: &sync.Mutex{},
extensions: make([]IExtension, 0),
Type: roomType,
}
return room
}
func (r *Room) AddExtension(extension IExtension) {
r.extensions = append(r.extensions, extension)
}
// room should not close manually, it will be close once no client is in the room automatically
// this is to prevent recursive close callback
// use StopAllClients() to close room manually that will triggered this callback once all clients are closed
func (r *Room) close() error {
if r.State == StateRoomClosed {
return ErrRoomIsClosed
}
if len(r.sfu.Clients) > 0 {
return ErrRoomIsNotEmpty
}
r.cancelContext()
r.sfu.Stop()
for _, callback := range r.callbacksRoomClosed {
callback(r.ID)
}
r.State = StateRoomClosed
r.sendEvent(EventRoomClosed, nil)
return nil
}
func (r *Room) StopClient(id string) error {
client, ok := r.sfu.Clients[id]
if !ok {
return ErrNotFound
}
return client.PeerConnection.Close()
}
func (r *Room) StopAllClients() {
for _, client := range r.sfu.Clients {
client.PeerConnection.Close()
}
}
func (r *Room) AddClient(id string, opts ClientOptions) (*Client, error) {
r.mutex.Lock()
defer r.mutex.Unlock()
if r.State == StateRoomClosed {
return nil, ErrRoomIsClosed
}
_, ok := r.offerChans[id]
if ok {
return nil, ErrClientExists
}
client := r.sfu.NewClient(id, opts)
offerChan := make(chan webrtc.SessionDescription, 10)
answerChan := make(chan webrtc.SessionDescription, 10)
candidateChan := make(chan webrtc.ICECandidate, 50)
r.offerChans[client.ID] = offerChan
r.answerChans[client.ID] = answerChan
r.candidateChans[client.ID] = candidateChan
client.OnStopped(func() {
log.Println("client stopped ", client.ID)
r.RemoveClient(client.ID)
})
client.OnRenegotiation = func(ctx context.Context, offer webrtc.SessionDescription) webrtc.SessionDescription {
// send offer to SSE, the client should respond with the answer
offerChan <- offer
ctxTimeout, cancelTimeout := context.WithTimeout(client.Context, 30*time.Second)
defer cancelTimeout()
// this will wait for answer from client in 30 seconds or timeout
select {
case <-ctxTimeout.Done():
log.Println("timeout on renegotiation")
return webrtc.SessionDescription{}
case answer := <-answerChan:
log.Println("received answer from client ", client.GetType(), client.ID)
return answer
}
}
client.OnIceCandidate = func(ctx context.Context, candidate *webrtc.ICECandidate) {
candidateChan <- *candidate
}
for _, ext := range r.extensions {
ext.OnClientAdded(client)
}
return client, nil
}
func (r *Room) CreateClientID(id int) string {
if id == 0 {
return GenerateID([]int{r.sfu.Counter})
}
return GenerateID([]int{r.sfu.Counter, id})
}
func (r *Room) RemoveClient(id string) {
delete(r.offerChans, id)
delete(r.answerChans, id)
delete(r.candidateChans, id)
r.onClientRemoved(id)
}
func (r *Room) OnRoomClosed(callback func(id string)) {
r.callbacksRoomClosed = append(r.callbacksRoomClosed, callback)
}
func (r *Room) OnClientRemoved(callback func(id string)) {
r.callbacksClientRemoved = append(r.callbacksClientRemoved, callback)
}
func (r *Room) onClientRemoved(clientid string) {
for _, callback := range r.callbacksClientRemoved {
callback(clientid)
}
r.sendEvent(EventRoomClientLeft, map[string]interface{}{
"clientid": clientid,
})
if len(r.sfu.Clients) == 0 {
r.close()
}
}
func (r *Room) sendEvent(eventType string, data map[string]interface{}) {
r.eventChan <- Event{
Type: eventType,
Time: time.Now(),
Data: data,
}
}
func (r *Room) GetSFU() *SFU {
return r.sfu
}
func (r *Room) GetID() string {
return r.ID
}
func (r *Room) GetName() string {
return r.Name
}
func (r *Room) GetAnswerChan(clientid string) (chan webrtc.SessionDescription, error) {
chanAnswer, ok := r.answerChans[clientid]
if !ok {
return nil, ErrNotFound
}
return chanAnswer, nil
}
func (r *Room) GetOfferChan(clientid string) (chan webrtc.SessionDescription, error) {
offerChan, ok := r.offerChans[clientid]
if !ok {
return nil, ErrNotFound
}
return offerChan, nil
}
func (r *Room) GetCandidateChan(clientid string) (chan webrtc.ICECandidate, error) {
candidateChan, ok := r.candidateChans[clientid]
if !ok {
return nil, ErrNotFound
}
return candidateChan, nil
}
func (r *Room) GetEventChan() chan Event {
return r.eventChan
}