forked from GRVYDEV/Lightspeed-webrtc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
279 lines (226 loc) · 6.35 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
// +build !js
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
"strconv"
"strings"
"github.com/GRVYDEV/lightspeed-webrtc/ws"
"github.com/gorilla/websocket"
"github.com/pion/interceptor"
"github.com/pion/rtp"
"github.com/pion/webrtc/v3"
)
var (
addr = flag.String("addr", "localhost", "http service address")
ip = flag.String("ip", "none", "IP address for webrtc")
wsPort = flag.Int("ws-port", 8080, "Port for websocket")
rtpPort = flag.Int("rtp-port", 65535, "Port for RTP")
ports = flag.String("ports", "20000-20500", "Port range for webrtc")
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
videoTrack *webrtc.TrackLocalStaticRTP
audioTrack *webrtc.TrackLocalStaticRTP
hub *ws.Hub
)
func main() {
flag.Parse()
log.SetFlags(0)
// Open a UDP Listener for RTP Packets on port 65535
listener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP(*addr), Port: *rtpPort})
if err != nil {
panic(err)
}
defer func() {
if err = listener.Close(); err != nil {
panic(err)
}
}()
fmt.Println("Waiting for RTP Packets")
// Create a video track
videoTrack, err = webrtc.NewTrackLocalStaticRTP(webrtc.RTPCodecCapability{MimeType: "video/h264"}, "video", "pion")
if err != nil {
panic(err)
}
// Create an audio track
audioTrack, err = webrtc.NewTrackLocalStaticRTP(webrtc.RTPCodecCapability{MimeType: "audio/opus"}, "video", "pion")
if err != nil {
panic(err)
}
hub = ws.NewHub()
go hub.Run()
// start HTTP server
go func() {
http.HandleFunc("/websocket", websocketHandler)
log.Fatal(http.ListenAndServe(*addr+":"+strconv.Itoa(*wsPort), nil))
}()
inboundRTPPacket := make([]byte, 4096) // UDP MTU
// Read RTP packets forever and send them to the WebRTC Client
for {
n, _, err := listener.ReadFrom(inboundRTPPacket)
if err != nil {
fmt.Printf("error during read: %s", err)
panic(err)
}
packet := &rtp.Packet{}
if err = packet.Unmarshal(inboundRTPPacket[:n]); err != nil {
//It has been found that the windows version of OBS sends us some malformed packets
//It does not effect the stream so we will disable any output here
//fmt.Printf("Error unmarshaling RTP packet %s\n", err)
}
if packet.Header.PayloadType == 96 {
if _, writeErr := videoTrack.Write(inboundRTPPacket[:n]); writeErr != nil {
panic(writeErr)
}
} else if packet.Header.PayloadType == 97 {
if _, writeErr := audioTrack.Write(inboundRTPPacket[:n]); writeErr != nil {
panic(writeErr)
}
}
}
}
// Create a new webrtc.API object that takes public IP addresses and port ranges into account.
func createWebrtcApi() *webrtc.API {
s := webrtc.SettingEngine{}
// Set a NAT IP if one is given
if *ip != "none" {
s.SetNAT1To1IPs([]string{*ip}, webrtc.ICECandidateTypeHost)
}
// Split given port range into two sides, pass them to SettingEngine
pr := strings.SplitN(*ports, "-", 2)
pr_low, err := strconv.ParseUint(pr[0], 10, 16)
if err != nil {
panic(err)
}
pr_high, err := strconv.ParseUint(pr[1], 10, 16)
if err != nil {
panic(err)
}
s.SetEphemeralUDPPortRange(uint16(pr_low), uint16(pr_high))
// Default parameters as specified in Pion's non-API NewPeerConnection call
// These are needed because CreateOffer will not function without them
m := &webrtc.MediaEngine{}
if err := m.RegisterDefaultCodecs(); err != nil {
panic(err)
}
i := &interceptor.Registry{}
if err := webrtc.RegisterDefaultInterceptors(m, i); err != nil {
panic(err)
}
return webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithInterceptorRegistry(i), webrtc.WithSettingEngine(s))
}
// Handle incoming websockets
func websocketHandler(w http.ResponseWriter, r *http.Request) {
// Upgrade HTTP request to Websocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
// When this frame returns close the Websocket
defer conn.Close() //nolint
// Create API that takes IP and port range into account
api := createWebrtcApi()
// Create new PeerConnection
peerConnection, err := api.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 Outgoing
transceiverVideo, err := peerConnection.AddTransceiverFromTrack(videoTrack,
webrtc.RTPTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionSendonly,
},
)
transceiverAudio, err := peerConnection.AddTransceiverFromTrack(audioTrack,
webrtc.RTPTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionSendonly,
},
)
if err != nil {
log.Print(err)
return
}
go func() {
rtcpBuf := make([]byte, 1500)
for {
if _, _, rtcpErr := transceiverVideo.Sender().Read(rtcpBuf); rtcpErr != nil {
return
}
if _, _, rtcpErr := transceiverAudio.Sender().Read(rtcpBuf); rtcpErr != nil {
return
}
}
}()
c := ws.NewClient(hub, conn, peerConnection)
go c.WriteLoop()
// Add to the hub
hub.Register <- c
// 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 msg, err := json.Marshal(ws.WebsocketMessage{
Event: ws.MessageTypeCandidate,
Data: candidateString,
}); err == nil {
hub.RLock()
if _, ok := hub.Clients[c]; ok {
c.Send <- msg
}
hub.RUnlock()
} else {
log.Println(err)
}
})
// 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)
}
hub.Unregister <- c
case webrtc.PeerConnectionStateClosed:
hub.Unregister <- c
}
})
offer, err := peerConnection.CreateOffer(nil)
if err != nil {
log.Print(err)
}
if err = peerConnection.SetLocalDescription(offer); err != nil {
log.Print(err)
}
offerString, err := json.Marshal(offer)
if err != nil {
log.Print(err)
}
if msg, err := json.Marshal(ws.WebsocketMessage{
Event: ws.MessageTypeOffer,
Data: offerString,
}); err == nil {
hub.RLock()
if _, ok := hub.Clients[c]; ok {
c.Send <- msg
}
hub.RUnlock()
} else {
log.Printf("could not marshal ws message: %s", err)
}
c.ReadLoop()
}