forked from pion/example-webrtc-applications
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
368 lines (307 loc) · 8.65 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
// 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"
"log"
"net/http"
"os"
"sync"
"text/template"
"time"
"github.com/gorilla/websocket"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v3"
)
// 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
)
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
log.SetFlags(0)
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.Fatal(err)
}
})
// request a keyframe every 3 seconds
go func() {
for range time.NewTicker(time.Second * 3).C {
dispatchKeyFrame()
}
}()
// start HTTP server
log.Fatal(http.ListenAndServe(*addr, nil)) // nolint:gosec
}
// 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 {
return true
}
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.Print("upgrade:", 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.Print(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.Print(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
}
candidateString, err := json.Marshal(i.ToJSON())
if err != nil {
log.Println(err)
return
}
if writeErr := c.WriteJSON(&websocketMessage{
Event: "candidate",
Data: string(candidateString),
}); writeErr != nil {
log.Println(writeErr)
}
})
// If PeerConnection is closed remove it from global list
peerConnection.OnConnectionStateChange(func(p webrtc.PeerConnectionState) {
switch p {
case webrtc.PeerConnectionStateFailed:
if err := peerConnection.Close(); err != nil {
log.Print(err)
}
case webrtc.PeerConnectionStateClosed:
signalPeerConnections()
default:
}
})
peerConnection.OnTrack(func(t *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {
// Create a track to fan out our incoming video to all peers
trackLocal := addTrack(t)
defer removeTrack(trackLocal)
buf := make([]byte, 1500)
for {
i, _, err := t.Read(buf)
if err != nil {
return
}
if _, err = trackLocal.Write(buf[:i]); err != nil {
return
}
}
})
// Signal for the new PeerConnection
signalPeerConnections()
message := &websocketMessage{}
for {
_, raw, err := c.ReadMessage()
if err != nil {
log.Println(err)
return
} else if err := json.Unmarshal(raw, &message); err != nil {
log.Println(err)
return
}
switch message.Event {
case "candidate":
candidate := webrtc.ICECandidateInit{}
if err := json.Unmarshal([]byte(message.Data), &candidate); err != nil {
log.Println(err)
return
}
if err := peerConnection.AddICECandidate(candidate); err != nil {
log.Println(err)
return
}
case "answer":
answer := webrtc.SessionDescription{}
if err := json.Unmarshal([]byte(message.Data), &answer); err != nil {
log.Println(err)
return
}
if err := peerConnection.SetRemoteDescription(answer); err != nil {
log.Println(err)
return
}
}
}
}
// 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)
}