forked from ionorg/ion-sfu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
353 lines (302 loc) · 8.46 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
// Package cmd contains an entrypoint for running an ion-sfu instance.
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net"
"os"
sfu "github.com/pion/ion-sfu/pkg"
"github.com/pion/ion-sfu/pkg/log"
"github.com/pion/webrtc/v3"
"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/pion/ion-sfu/cmd/server/grpc/proto"
)
type grpcConfig struct {
Port string `mapstructure:"port"`
}
// Config defines parameters for configuring the sfu instance
type Config struct {
sfu.Config `mapstructure:",squash"`
GRPC grpcConfig `mapstructure:"grpc"`
}
var (
conf = Config{}
file string
addr string
errNoPeer = errors.New("no peer exists")
)
type server struct {
pb.UnimplementedSFUServer
sfu *sfu.SFU
}
const (
portRangeLimit = 100
)
func showHelp() {
fmt.Printf("Usage:%s {params}\n", os.Args[0])
fmt.Println(" -c {config file}")
fmt.Println(" -a {listen addr}")
fmt.Println(" -h (show help info)")
}
func load() bool {
_, err := os.Stat(file)
if err != nil {
return false
}
viper.SetConfigFile(file)
viper.SetConfigType("toml")
err = viper.ReadInConfig()
if err != nil {
fmt.Printf("config file %s read failed. %v\n", file, err)
return false
}
err = viper.GetViper().Unmarshal(&conf)
if err != nil {
fmt.Printf("sfu config file %s loaded failed. %v\n", file, err)
return false
}
if len(conf.WebRTC.ICEPortRange) > 2 {
fmt.Printf("config file %s loaded failed. range port must be [min,max]\n", file)
return false
}
if len(conf.WebRTC.ICEPortRange) != 0 && conf.WebRTC.ICEPortRange[1]-conf.WebRTC.ICEPortRange[0] < portRangeLimit {
fmt.Printf("config file %s loaded failed. range port must be [min, max] and max - min >= %d\n", file, portRangeLimit)
return false
}
fmt.Printf("config %s load ok!\n", file)
return true
}
func parse() bool {
flag.StringVar(&file, "c", "config.toml", "config file")
flag.StringVar(&addr, "a", ":50051", "address to use")
help := flag.Bool("h", false, "help info")
flag.Parse()
if !load() {
return false
}
if *help {
showHelp()
return false
}
return true
}
func main() {
if !parse() {
showHelp()
os.Exit(-1)
}
log.Infof("--- Starting SFU Node ---")
lis, err := net.Listen("tcp", addr)
if err != nil {
log.Panicf("failed to listen: %v", err)
}
log.Infof("SFU Listening at %s", addr)
s := grpc.NewServer()
pb.RegisterSFUServer(s, &server{
sfu: sfu.NewSFU(conf.Config),
})
if err := s.Serve(lis); err != nil {
log.Panicf("failed to serve: %v", err)
}
select {}
}
// Publish a stream to the sfu. Publish creates a bidirectional
// streaming rpc connection between the client and sfu.
//
// The sfu will respond with a message containing the stream pid
// and one of two different payload types:
// 1. `Connect` containing the session answer description. This
// message is *always* returned first.
// 2. `Trickle` containing candidate information for Trickle ICE.
//
// If the webrtc connection is closed, the server will close this stream.
//
// The client should send a message containing the session id
// and one of two different payload types:
// 1. `Connect` containing the session offer description. This
// message must *always* be sent first.
// 2. `Trickle` containing candidate information for Trickle ICE.
//
// If the client closes this stream, the webrtc stream will be closed.
func (s *server) Signal(stream pb.SFU_SignalServer) error {
var pid string
var peer *sfu.WebRTCTransport
for {
in, err := stream.Recv()
if err != nil {
if peer != nil {
peer.Close()
}
if err == io.EOF {
return nil
}
errStatus, _ := status.FromError(err)
if errStatus.Code() == codes.Canceled {
return nil
}
log.Errorf("signal error %v %v", errStatus.Message(), errStatus.Code())
return err
}
switch payload := in.Payload.(type) {
case *pb.SignalRequest_Join:
var answer webrtc.SessionDescription
log.Infof("signal->join called:\n%v", string(payload.Join.Offer.Sdp))
if peer != nil {
// already joined
log.Errorf("peer already exists")
return status.Errorf(codes.FailedPrecondition, "peer already exists")
}
offer := webrtc.SessionDescription{
Type: webrtc.SDPTypeOffer,
SDP: string(payload.Join.Offer.Sdp),
}
me := sfu.MediaEngine{}
err := me.PopulateFromSDP(offer)
if err != nil {
log.Errorf("join error: %v", err)
return status.Errorf(codes.InvalidArgument, "join error %s", err)
}
peer, err = s.sfu.NewWebRTCTransport(payload.Join.Sid, me)
if err != nil {
log.Errorf("join error: %v", err)
return status.Errorf(codes.InvalidArgument, "join error %s", err)
}
log.Infof("peer %s join session %s", peer.ID(), payload.Join.Sid)
err = peer.SetRemoteDescription(offer)
if err != nil {
log.Errorf("join error: %v", err)
return status.Errorf(codes.Internal, "join error %s", err)
}
answer, err = peer.CreateAnswer()
if err != nil {
log.Errorf("join error: %v", err)
return status.Errorf(codes.Internal, "join error %s", err)
}
err = peer.SetLocalDescription(answer)
if err != nil {
log.Errorf("join error: %v", err)
return status.Errorf(codes.Internal, "join error %s", err)
}
// Notify user of trickle candidates
peer.OnICECandidate(func(c *webrtc.ICECandidate) {
if c == nil {
// Gathering done
return
}
bytes, err := json.Marshal(c.ToJSON())
if err != nil {
log.Errorf("OnIceCandidate error %s", err)
}
err = stream.Send(&pb.SignalReply{
Payload: &pb.SignalReply_Trickle{
Trickle: &pb.Trickle{
Init: string(bytes),
},
},
})
if err != nil {
log.Errorf("OnIceCandidate error %s", err)
}
})
peer.OnNegotiationNeeded(func() {
log.Debugf("on negotiation needed called for pc %s", peer.ID())
offer, err := peer.CreateOffer()
if err != nil {
log.Errorf("CreateOffer error: %v", err)
return
}
err = peer.SetLocalDescription(offer)
if err != nil {
log.Errorf("SetLocalDescription error: %v", err)
return
}
err = stream.Send(&pb.SignalReply{
Payload: &pb.SignalReply_Negotiate{
Negotiate: &pb.SessionDescription{
Type: offer.Type.String(),
Sdp: []byte(offer.SDP),
},
},
})
if err != nil {
log.Errorf("negotiation error %s", err)
}
})
err = stream.Send(&pb.SignalReply{
Payload: &pb.SignalReply_Join{
Join: &pb.JoinReply{
Pid: pid,
Answer: &pb.SessionDescription{
Type: answer.Type.String(),
Sdp: []byte(answer.SDP),
},
},
},
})
if err != nil {
log.Errorf("error sending join response %s", err)
return status.Errorf(codes.Internal, "join error %s", err)
}
case *pb.SignalRequest_Negotiate:
if peer == nil {
return status.Errorf(codes.FailedPrecondition, "%s", errNoPeer)
}
if payload.Negotiate.Type == webrtc.SDPTypeOffer.String() {
offer := webrtc.SessionDescription{
Type: webrtc.SDPTypeOffer,
SDP: string(payload.Negotiate.Sdp),
}
// Peer exists, renegotiating existing peer
err = peer.SetRemoteDescription(offer)
if err != nil {
return status.Errorf(codes.Internal, "%s", err)
}
answer, err := peer.CreateAnswer()
if err != nil {
return status.Errorf(codes.Internal, "%s", err)
}
err = peer.SetLocalDescription(answer)
if err != nil {
return status.Errorf(codes.Internal, "%s", err)
}
err = stream.Send(&pb.SignalReply{
Payload: &pb.SignalReply_Negotiate{
Negotiate: &pb.SessionDescription{
Type: answer.Type.String(),
Sdp: []byte(answer.SDP),
},
},
})
if err != nil {
return status.Errorf(codes.Internal, "%s", err)
}
} else if payload.Negotiate.Type == webrtc.SDPTypeAnswer.String() {
err = peer.SetRemoteDescription(webrtc.SessionDescription{
Type: webrtc.SDPTypeAnswer,
SDP: string(payload.Negotiate.Sdp),
})
if err != nil {
return status.Errorf(codes.Internal, "%s", err)
}
}
case *pb.SignalRequest_Trickle:
if peer == nil {
return status.Errorf(codes.FailedPrecondition, "%s", errNoPeer)
}
var candidate webrtc.ICECandidateInit
err := json.Unmarshal([]byte(payload.Trickle.Init), &candidate)
if err != nil {
log.Errorf("error parsing ice candidate: %v", err)
}
if err := peer.AddICECandidate(candidate); err != nil {
return status.Errorf(codes.Internal, "error adding ice candidate")
}
}
}
}