-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
319 lines (282 loc) · 7.88 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
package main
import (
"context"
"encoding/json"
"flag"
"io"
"log"
"net"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/go-chi/chi"
"github.com/gobuffalo/packr"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v2"
"nhooyr.io/websocket"
)
func main() {
pliInterval := flag.Int64("pli-interval", 0, "If set to X, enables sending on PLI packet every X seconds")
flag.Parse()
router := chi.NewRouter()
h := NewMainHandler(*pliInterval)
router.Mount("/ws", h)
router.Handle("/*", static("/", packr.NewBox("./static")))
port := "3000"
l, err := net.Listen("tcp", net.JoinHostPort("", port))
addr := l.Addr().(*net.TCPAddr)
log.Printf("Listening on: %s", addr.String())
server := &http.Server{Handler: router}
err = server.Serve(l)
chkErr(err)
}
func static(prefix string, box packr.Box) http.Handler {
fileServer := http.FileServer(http.FileSystem(box))
return http.StripPrefix(prefix, fileServer)
}
func chkErr(err error) {
if err != nil {
panic(err)
}
}
type MainHandler struct {
pliInterval int64
peerIds uint32
api *webrtc.API
peers map[uint32]*Peer
}
type Message struct {
Type string `json:"type"`
Payload json.RawMessage `json:"payload"`
}
type Peer struct {
id uint32
pc *webrtc.PeerConnection
localTracks []*webrtc.Track
negotiate func()
mu sync.Mutex
}
func NewPeer(id uint32, pc *webrtc.PeerConnection, negotiate func()) *Peer {
return &Peer{
id: id,
pc: pc,
negotiate: negotiate,
localTracks: make([]*webrtc.Track, 0),
}
}
type TrackReceiver struct {
track *webrtc.Track
sourcePeer Peer
}
func NewMainHandler(pliInterval int64) *MainHandler {
var mediaEngine webrtc.MediaEngine
var settingEngine webrtc.SettingEngine
settingEngine.SetTrickle(false)
mediaEngine.RegisterCodec(webrtc.NewRTPOpusCodec(webrtc.DefaultPayloadTypeOpus, 48000))
rtcpfb := []webrtc.RTCPFeedback{
webrtc.RTCPFeedback{
Type: webrtc.TypeRTCPFBNACK,
},
webrtc.RTCPFeedback{
Type: webrtc.TypeRTCPFBNACK,
Parameter: "pli",
},
}
mediaEngine.RegisterCodec(webrtc.NewRTPVP8CodecExt(webrtc.DefaultPayloadTypeVP8, 90000, rtcpfb, ""))
api := webrtc.NewAPI(
webrtc.WithMediaEngine(mediaEngine),
webrtc.WithSettingEngine(settingEngine),
)
return &MainHandler{
api: api,
peers: map[uint32]*Peer{},
pliInterval: pliInterval,
}
}
func deserialize(b []byte) (m Message) {
err := json.Unmarshal(b, &m)
chkErr(err)
return
}
func serializeMessage(typ string, payload interface{}) []byte {
b, err := json.Marshal(payload)
chkErr(err)
m := Message{typ, b}
return serialize(m)
}
func serialize(m Message) []byte {
b, err := json.Marshal(m)
chkErr(err)
return b
}
func (m *MainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
CompressionMode: websocket.CompressionDisabled,
})
chkErr(err)
id := atomic.AddUint32(&m.peerIds, 1)
log.Printf("[%d] ws connected", id)
defer func() {
c.Close(websocket.StatusInternalError, "")
}()
webrtcConfig := webrtc.Configuration{
ICEServers: []webrtc.ICEServer{{
URLs: []string{"stun:stun.l.google.com:19302"},
}},
}
pc, err := m.api.NewPeerConnection(webrtcConfig)
chkErr(err)
pc.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
log.Printf("[%d] ice connection state change: %s", id, state)
})
pc.OnSignalingStateChange(func(state webrtc.SignalingState) {
log.Printf("[%d] signaling state change: %s", id, state)
})
_, err = pc.CreateDataChannel("data", nil)
chkErr(err)
send := func(typ string, payload interface{}) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = c.Write(ctx, websocket.MessageText, serializeMessage(typ, payload))
chkErr(err)
}
negotiate := func() {
offer, err := pc.CreateOffer(nil)
chkErr(err)
// log.Printf("[%d] negotiate create offer: %s", id, offer.SDP)
err = pc.SetLocalDescription(offer)
chkErr(err)
send("offer", offer)
}
peer := NewPeer(id, pc, negotiate)
tracksChan := make(chan *webrtc.Track)
pc.OnTrack(func(remoteTrack *webrtc.Track, receiver *webrtc.RTPReceiver) {
log.Printf("[%d] OnTrack ssrc: %d", id, remoteTrack.SSRC())
peer.mu.Lock()
defer peer.mu.Unlock()
localTrack, err := pc.NewTrack(remoteTrack.PayloadType(), remoteTrack.SSRC(), "copy:"+remoteTrack.ID(), "copy:"+remoteTrack.Label())
peer.localTracks = append(peer.localTracks, localTrack)
chkErr(err)
var ticker *time.Ticker
if m.pliInterval > 0 {
log.Printf("[%d] Starting PLI ticker every %d seconds for track: %d", id, m.pliInterval, remoteTrack.SSRC())
ticker = time.NewTicker(time.Duration(m.pliInterval) * time.Second)
go func() {
for range ticker.C {
log.Printf("[%d] Sending PLI packet for track (interval): %d", id, remoteTrack.SSRC())
err := pc.WriteRTCP([]rtcp.Packet{
&rtcp.PictureLossIndication{
MediaSSRC: remoteTrack.SSRC(),
},
})
if err != nil {
log.Printf("[%d] Error sending PLI on interval: %s", id, err)
}
}
}()
}
go func() {
if ticker != nil {
defer ticker.Stop()
}
for {
rtp, err := remoteTrack.ReadRTP()
if err != nil {
log.Printf("[%d] Error reading from remote track: %d: %s", id, remoteTrack.SSRC(), err)
return
}
err = localTrack.WriteRTP(rtp)
if err != nil && err != io.ErrClosedPipe {
log.Printf("[%d] Error writing to local track: %d: %s", id, localTrack.SSRC(), err)
return
}
}
}()
tracksChan <- localTrack
})
addTrack := func(recvPeer *Peer, srcPeer *Peer, track *webrtc.Track) {
log.Printf("[%d] Add track ssrc %d to peer", recvPeer.id, track.SSRC())
sender, err := recvPeer.pc.AddTrack(track)
chkErr(err)
go func() {
for {
pkts, err := sender.ReadRTCP()
if err != nil {
log.Printf("[%d] Error reading rtcp from sender: %d: %s", recvPeer.id, track.SSRC(), err)
return
}
for _, pkt := range pkts {
// log.Printf("[%d] rtcp packet for track ssrc %d: %T", recvPeer.id, track.SSRC(), pkt)
switch pkt.(type) {
case *rtcp.PictureLossIndication:
log.Printf("[%d] rtcp packet for track ssrc %d: %T", recvPeer.id, track.SSRC(), pkt)
err := srcPeer.pc.WriteRTCP([]rtcp.Packet{pkt})
if err != nil {
log.Printf("[%d] error writing rtcp packet for track ssrc %d: %s", recvPeer.id, track.SSRC(), err)
return
}
case *rtcp.ReceiverEstimatedMaximumBitrate:
case *rtcp.SourceDescription:
case *rtcp.ReceiverReport:
case *rtcp.SenderReport:
default:
log.Printf("[%d] rtcp packet for track ssrc %d: %T", recvPeer.id, track.SSRC(), pkt)
}
}
}
}()
go recvPeer.negotiate()
}
msgChan := make(chan Message)
go func() {
for {
select {
case msg := <-msgChan:
switch msg.Type {
case "ready":
for _, otherPeer := range m.peers {
for _, track := range otherPeer.localTracks {
addTrack(peer, otherPeer, track)
}
}
m.peers[id] = peer
negotiate()
case "answer":
var answer webrtc.SessionDescription
err := json.Unmarshal(msg.Payload, &answer)
chkErr(err)
// log.Printf("[%d] Got answer: %s", id, answer.SDP)
err = pc.SetRemoteDescription(answer)
chkErr(err)
case "pub":
pc.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo, webrtc.RtpTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionRecvonly,
})
negotiate()
default:
// log.Printf("[%d] Unhandled websocket message type: %s", id, msg.Type)
}
case track := <-tracksChan:
for _, otherPeer := range m.peers {
if otherPeer.pc != pc {
addTrack(otherPeer, peer, track)
}
}
}
}
}()
for {
ctx := context.Background()
typ, m, err := c.Read(ctx)
if err != nil {
log.Printf("[%d] Websocket read error: %s", id, err)
break
}
if typ != websocket.MessageText {
continue
}
msg := deserialize(m)
msgChan <- msg
}
}