-
Notifications
You must be signed in to change notification settings - Fork 250
/
main.go
406 lines (333 loc) · 10.2 KB
/
main.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
//go:build !js
// +build !js
// sfu-ws is a many-to-many websocket based SFU
package main
import (
"encoding/json"
"flag"
"net/http"
"os"
"sync"
"text/template"
"time"
"github.com/gorilla/websocket"
"github.com/pion/logging"
"github.com/pion/rtcp"
"github.com/pion/rtp"
"github.com/pion/webrtc/v4"
)
// nolint
var (
addr = flag.String("addr", ":8080", "http service address")
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
indexTemplate = &template.Template{}
// lock for peerConnections and trackLocals
listLock sync.RWMutex
peerConnections []peerConnectionState
trackLocals map[string]*webrtc.TrackLocalStaticRTP
log = logging.NewDefaultLoggerFactory().NewLogger("sfu-ws")
)
type websocketMessage struct {
Event string `json:"event"`
Data string `json:"data"`
}
type peerConnectionState struct {
peerConnection *webrtc.PeerConnection
websocket *threadSafeWriter
}
func main() {
// Parse the flags passed to program
flag.Parse()
// Init other state
trackLocals = map[string]*webrtc.TrackLocalStaticRTP{}
// Read index.html from disk into memory, serve whenever anyone requests /
indexHTML, err := os.ReadFile("index.html")
if err != nil {
panic(err)
}
indexTemplate = template.Must(template.New("").Parse(string(indexHTML)))
// websocket handler
http.HandleFunc("/websocket", websocketHandler)
// index.html handler
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err = indexTemplate.Execute(w, "ws://"+r.Host+"/websocket"); err != nil {
log.Errorf("Failed to parse index template: %v", err)
}
})
// request a keyframe every 3 seconds
go func() {
for range time.NewTicker(time.Second * 3).C {
dispatchKeyFrame()
}
}()
// start HTTP server
if err = http.ListenAndServe(*addr, nil); err != nil { //nolint: gosec
log.Errorf("Failed to start http server: %v", err)
}
}
// Add to list of tracks and fire renegotation for all PeerConnections
func addTrack(t *webrtc.TrackRemote) *webrtc.TrackLocalStaticRTP {
listLock.Lock()
defer func() {
listLock.Unlock()
signalPeerConnections()
}()
// Create a new TrackLocal with the same codec as our incoming
trackLocal, err := webrtc.NewTrackLocalStaticRTP(t.Codec().RTPCodecCapability, t.ID(), t.StreamID())
if err != nil {
panic(err)
}
trackLocals[t.ID()] = trackLocal
return trackLocal
}
// Remove from list of tracks and fire renegotation for all PeerConnections
func removeTrack(t *webrtc.TrackLocalStaticRTP) {
listLock.Lock()
defer func() {
listLock.Unlock()
signalPeerConnections()
}()
delete(trackLocals, t.ID())
}
// signalPeerConnections updates each PeerConnection so that it is getting all the expected media tracks
func signalPeerConnections() {
listLock.Lock()
defer func() {
listLock.Unlock()
dispatchKeyFrame()
}()
attemptSync := func() (tryAgain bool) {
for i := range peerConnections {
if peerConnections[i].peerConnection.ConnectionState() == webrtc.PeerConnectionStateClosed {
peerConnections = append(peerConnections[:i], peerConnections[i+1:]...)
return true // We modified the slice, start from the beginning
}
// map of sender we already are seanding, so we don't double send
existingSenders := map[string]bool{}
for _, sender := range peerConnections[i].peerConnection.GetSenders() {
if sender.Track() == nil {
continue
}
existingSenders[sender.Track().ID()] = true
// If we have a RTPSender that doesn't map to a existing track remove and signal
if _, ok := trackLocals[sender.Track().ID()]; !ok {
if err := peerConnections[i].peerConnection.RemoveTrack(sender); err != nil {
return true
}
}
}
// Don't receive videos we are sending, make sure we don't have loopback
for _, receiver := range peerConnections[i].peerConnection.GetReceivers() {
if receiver.Track() == nil {
continue
}
existingSenders[receiver.Track().ID()] = true
}
// Add all track we aren't sending yet to the PeerConnection
for trackID := range trackLocals {
if _, ok := existingSenders[trackID]; !ok {
if _, err := peerConnections[i].peerConnection.AddTrack(trackLocals[trackID]); err != nil {
return true
}
}
}
offer, err := peerConnections[i].peerConnection.CreateOffer(nil)
if err != nil {
return true
}
if err = peerConnections[i].peerConnection.SetLocalDescription(offer); err != nil {
return true
}
offerString, err := json.Marshal(offer)
if err != nil {
log.Errorf("Failed to marshal offer to json: %v", err)
return true
}
log.Infof("Send offer to client: %v", offer)
if err = peerConnections[i].websocket.WriteJSON(&websocketMessage{
Event: "offer",
Data: string(offerString),
}); err != nil {
return true
}
}
return
}
for syncAttempt := 0; ; syncAttempt++ {
if syncAttempt == 25 {
// Release the lock and attempt a sync in 3 seconds. We might be blocking a RemoveTrack or AddTrack
go func() {
time.Sleep(time.Second * 3)
signalPeerConnections()
}()
return
}
if !attemptSync() {
break
}
}
}
// dispatchKeyFrame sends a keyframe to all PeerConnections, used everytime a new user joins the call
func dispatchKeyFrame() {
listLock.Lock()
defer listLock.Unlock()
for i := range peerConnections {
for _, receiver := range peerConnections[i].peerConnection.GetReceivers() {
if receiver.Track() == nil {
continue
}
_ = peerConnections[i].peerConnection.WriteRTCP([]rtcp.Packet{
&rtcp.PictureLossIndication{
MediaSSRC: uint32(receiver.Track().SSRC()),
},
})
}
}
}
// Handle incoming websockets
func websocketHandler(w http.ResponseWriter, r *http.Request) {
// Upgrade HTTP request to Websocket
unsafeConn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Errorf("Failed to upgrade HTTP to Websocket: ", err)
return
}
c := &threadSafeWriter{unsafeConn, sync.Mutex{}}
// When this frame returns close the Websocket
defer c.Close() //nolint
// Create new PeerConnection
peerConnection, err := webrtc.NewPeerConnection(webrtc.Configuration{})
if err != nil {
log.Errorf("Failed to creates a PeerConnection: %v", err)
return
}
// When this frame returns close the PeerConnection
defer peerConnection.Close() //nolint
// Accept one audio and one video track incoming
for _, typ := range []webrtc.RTPCodecType{webrtc.RTPCodecTypeVideo, webrtc.RTPCodecTypeAudio} {
if _, err := peerConnection.AddTransceiverFromKind(typ, webrtc.RTPTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionRecvonly,
}); err != nil {
log.Errorf("Failed to add transceiver: %v", err)
return
}
}
// Add our new PeerConnection to global list
listLock.Lock()
peerConnections = append(peerConnections, peerConnectionState{peerConnection, c})
listLock.Unlock()
// Trickle ICE. Emit server candidate to client
peerConnection.OnICECandidate(func(i *webrtc.ICECandidate) {
if i == nil {
return
}
// If you are serializing a candidate make sure to use ToJSON
// Using Marshal will result in errors around `sdpMid`
candidateString, err := json.Marshal(i.ToJSON())
if err != nil {
log.Errorf("Failed to marshal candidate to json: %v", err)
return
}
log.Infof("Send candidate to client: %s", candidateString)
if writeErr := c.WriteJSON(&websocketMessage{
Event: "candidate",
Data: string(candidateString),
}); writeErr != nil {
log.Errorf("Failed to write JSON: %v", writeErr)
}
})
// If PeerConnection is closed remove it from global list
peerConnection.OnConnectionStateChange(func(p webrtc.PeerConnectionState) {
log.Infof("Connection state change: %s", p)
switch p {
case webrtc.PeerConnectionStateFailed:
if err := peerConnection.Close(); err != nil {
log.Errorf("Failed to close PeerConnection: %v", err)
}
case webrtc.PeerConnectionStateClosed:
signalPeerConnections()
default:
}
})
peerConnection.OnTrack(func(t *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {
log.Infof("Got remote track: Kind=%s, ID=%s, PayloadType=%d", t.Kind(), t.ID(), t.PayloadType())
// Create a track to fan out our incoming video to all peers
trackLocal := addTrack(t)
defer removeTrack(trackLocal)
buf := make([]byte, 1500)
rtpPkt := &rtp.Packet{}
for {
i, _, err := t.Read(buf)
if err != nil {
return
}
if err = rtpPkt.Unmarshal(buf[:i]); err != nil {
log.Errorf("Failed to unmarshal incoming RTP packet: %v", err)
return
}
rtpPkt.Extension = false
rtpPkt.Extensions = nil
if err = trackLocal.WriteRTP(rtpPkt); err != nil {
return
}
}
})
peerConnection.OnICEConnectionStateChange(func(is webrtc.ICEConnectionState) {
log.Infof("ICE connection state changed: %s", is)
})
// Signal for the new PeerConnection
signalPeerConnections()
message := &websocketMessage{}
for {
_, raw, err := c.ReadMessage()
if err != nil {
log.Errorf("Failed to read message: %v", err)
return
}
log.Infof("Got message: %s", raw)
if err := json.Unmarshal(raw, &message); err != nil {
log.Errorf("Failed to unmarshal json to message: %v", err)
return
}
switch message.Event {
case "candidate":
candidate := webrtc.ICECandidateInit{}
if err := json.Unmarshal([]byte(message.Data), &candidate); err != nil {
log.Errorf("Failed to unmarshal json to candidate: %v", err)
return
}
log.Infof("Got candidate: %v", candidate)
if err := peerConnection.AddICECandidate(candidate); err != nil {
log.Errorf("Failed to add ICE candidate: %v", err)
return
}
case "answer":
answer := webrtc.SessionDescription{}
if err := json.Unmarshal([]byte(message.Data), &answer); err != nil {
log.Errorf("Failed to unmarshal json to answer: %v", err)
return
}
log.Infof("Got answer: %v", answer)
if err := peerConnection.SetRemoteDescription(answer); err != nil {
log.Errorf("Failed to set remote description: %v", err)
return
}
default:
log.Errorf("unknown message: %+v", message)
}
}
}
// Helper to make Gorilla Websockets threadsafe
type threadSafeWriter struct {
*websocket.Conn
sync.Mutex
}
func (t *threadSafeWriter) WriteJSON(v interface{}) error {
t.Lock()
defer t.Unlock()
return t.Conn.WriteJSON(v)
}