forked from bluenviron/gortsplib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
474 lines (414 loc) · 11.2 KB
/
server.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package gortsplib
import (
"context"
"crypto/tls"
"fmt"
"net"
"strconv"
"sync"
"time"
"github.com/bluenviron/gortsplib/v3/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/liberrors"
)
func extractPort(address string) (int, error) {
_, tmp, err := net.SplitHostPort(address)
if err != nil {
return 0, err
}
tmp2, err := strconv.ParseUint(tmp, 10, 16)
if err != nil {
return 0, err
}
return int(tmp2), nil
}
type sessionRequestRes struct {
ss *ServerSession
res *base.Response
err error
}
type sessionRequestReq struct {
sc *ServerConn
req *base.Request
id string
create bool
res chan sessionRequestRes
}
type streamMulticastIPReq struct {
res chan net.IP
}
// Server is a RTSP server.
type Server struct {
//
// RTSP parameters (all optional except RTSPAddress)
//
// the RTSP address of the server, to accept connections and send and receive
// packets with the TCP transport.
RTSPAddress string
// a port to send and receive RTP packets with the UDP transport.
// If UDPRTPAddress and UDPRTCPAddress are filled, the server can support the UDP transport.
UDPRTPAddress string
// a port to send and receive RTCP packets with the UDP transport.
// If UDPRTPAddress and UDPRTCPAddress are filled, the server can support the UDP transport.
UDPRTCPAddress string
// a range of multicast IPs to use with the UDP-multicast transport.
// If MulticastIPRange, MulticastRTPPort, MulticastRTCPPort are filled, the server
// can support the UDP-multicast transport.
MulticastIPRange string
// a port to send RTP packets with the UDP-multicast transport.
// If MulticastIPRange, MulticastRTPPort, MulticastRTCPPort are filled, the server
// can support the UDP-multicast transport.
MulticastRTPPort int
// a port to send RTCP packets with the UDP-multicast transport.
// If MulticastIPRange, MulticastRTPPort, MulticastRTCPPort are filled, the server
// can support the UDP-multicast transport.
MulticastRTCPPort int
// timeout of read operations.
// It defaults to 10 seconds
ReadTimeout time.Duration
// timeout of write operations.
// It defaults to 10 seconds
WriteTimeout time.Duration
// a TLS configuration to accept TLS (RTSPS) connections.
TLSConfig *tls.Config
// read buffer count.
// If greater than 1, allows to pass buffers to routines different than the one
// that is reading frames.
// It also allows to buffer routed frames and mitigate network fluctuations
// that are particularly relevant when using UDP.
// It defaults to 256.
ReadBufferCount int
// write buffer count.
// It allows to queue packets before sending them.
// It defaults to 256.
WriteBufferCount int
// disable automatic RTCP sender reports.
DisableRTCPSenderReports bool
//
// handler (optional)
//
// an handler to handle server events.
// It may implement one or more of the ServerHandler* interfaces.
Handler ServerHandler
//
// system functions (all optional)
//
// function used to initialize the TCP listener.
// It defaults to net.Listen.
Listen func(network string, address string) (net.Listener, error)
// function used to initialize UDP listeners.
// It defaults to net.ListenPacket.
ListenPacket func(network, address string) (net.PacketConn, error)
//
// private
//
udpReceiverReportPeriod time.Duration
senderReportPeriod time.Duration
sessionTimeout time.Duration
checkStreamPeriod time.Duration
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
multicastNet *net.IPNet
multicastNextIP net.IP
tcpListener net.Listener
udpRTPListener *serverUDPListener
udpRTCPListener *serverUDPListener
sessions map[string]*ServerSession
conns map[*ServerConn]struct{}
closeError error
// in
connClose chan *ServerConn
sessionRequest chan sessionRequestReq
sessionClose chan *ServerSession
streamMulticastIP chan streamMulticastIPReq
}
// Start starts the server.
func (s *Server) Start() error {
// RTSP parameters
if s.ReadTimeout == 0 {
s.ReadTimeout = 10 * time.Second
}
if s.WriteTimeout == 0 {
s.WriteTimeout = 10 * time.Second
}
if s.ReadBufferCount == 0 {
s.ReadBufferCount = 256
}
if s.WriteBufferCount == 0 {
s.WriteBufferCount = 256
}
if (s.WriteBufferCount & (s.WriteBufferCount - 1)) != 0 {
return fmt.Errorf("WriteBufferCount must be a power of two")
}
// system functions
if s.Listen == nil {
s.Listen = net.Listen
}
if s.ListenPacket == nil {
s.ListenPacket = net.ListenPacket
}
// private
if s.udpReceiverReportPeriod == 0 {
s.udpReceiverReportPeriod = 10 * time.Second
}
if s.senderReportPeriod == 0 {
s.senderReportPeriod = 10 * time.Second
}
if s.sessionTimeout == 0 {
s.sessionTimeout = 1 * 60 * time.Second
}
if s.checkStreamPeriod == 0 {
s.checkStreamPeriod = 1 * time.Second
}
if s.TLSConfig != nil && s.UDPRTPAddress != "" {
return fmt.Errorf("TLS can't be used with UDP")
}
if s.TLSConfig != nil && s.MulticastIPRange != "" {
return fmt.Errorf("TLS can't be used with UDP-multicast")
}
if s.RTSPAddress == "" {
return fmt.Errorf("RTSPAddress not provided")
}
if (s.UDPRTPAddress != "" && s.UDPRTCPAddress == "") ||
(s.UDPRTPAddress == "" && s.UDPRTCPAddress != "") {
return fmt.Errorf("UDPRTPAddress and UDPRTCPAddress must be used together")
}
if s.UDPRTPAddress != "" {
rtpPort, err := extractPort(s.UDPRTPAddress)
if err != nil {
return err
}
rtcpPort, err := extractPort(s.UDPRTCPAddress)
if err != nil {
return err
}
if (rtpPort % 2) != 0 {
return fmt.Errorf("RTP port must be even")
}
if rtcpPort != (rtpPort + 1) {
return fmt.Errorf("RTP and RTCP ports must be consecutive")
}
s.udpRTPListener, err = newServerUDPListener(
s.ListenPacket,
s.WriteTimeout,
false,
s.UDPRTPAddress,
true,
)
if err != nil {
return err
}
s.udpRTCPListener, err = newServerUDPListener(
s.ListenPacket,
s.WriteTimeout,
false,
s.UDPRTCPAddress,
false,
)
if err != nil {
s.udpRTPListener.close()
return err
}
}
if s.MulticastIPRange != "" && (s.MulticastRTPPort == 0 || s.MulticastRTCPPort == 0) ||
(s.MulticastRTPPort != 0 && (s.MulticastRTCPPort == 0 || s.MulticastIPRange == "")) ||
s.MulticastRTCPPort != 0 && (s.MulticastRTPPort == 0 || s.MulticastIPRange == "") {
if s.udpRTPListener != nil {
s.udpRTPListener.close()
}
if s.udpRTCPListener != nil {
s.udpRTCPListener.close()
}
return fmt.Errorf("MulticastIPRange, MulticastRTPPort and MulticastRTCPPort must be used together")
}
if s.MulticastIPRange != "" {
if (s.MulticastRTPPort % 2) != 0 {
if s.udpRTPListener != nil {
s.udpRTPListener.close()
}
if s.udpRTCPListener != nil {
s.udpRTCPListener.close()
}
return fmt.Errorf("RTP port must be even")
}
if s.MulticastRTCPPort != (s.MulticastRTPPort + 1) {
if s.udpRTPListener != nil {
s.udpRTPListener.close()
}
if s.udpRTCPListener != nil {
s.udpRTCPListener.close()
}
return fmt.Errorf("RTP and RTCP ports must be consecutive")
}
var err error
_, s.multicastNet, err = net.ParseCIDR(s.MulticastIPRange)
if err != nil {
if s.udpRTPListener != nil {
s.udpRTPListener.close()
}
if s.udpRTCPListener != nil {
s.udpRTCPListener.close()
}
return err
}
s.multicastNextIP = s.multicastNet.IP
}
var err error
s.tcpListener, err = s.Listen(restrictNetwork("tcp", s.RTSPAddress))
if err != nil {
if s.udpRTPListener != nil {
s.udpRTPListener.close()
}
if s.udpRTCPListener != nil {
s.udpRTCPListener.close()
}
return err
}
s.ctx, s.ctxCancel = context.WithCancel(context.Background())
s.wg.Add(1)
go s.run()
return nil
}
// Close closes all the server resources and waits for them to close.
func (s *Server) Close() error {
s.ctxCancel()
s.wg.Wait()
return s.closeError
}
// Wait waits until all server resources are closed.
// This can happen when a fatal error occurs or when Close() is called.
func (s *Server) Wait() error {
s.wg.Wait()
return s.closeError
}
func (s *Server) run() {
defer s.wg.Done()
s.sessions = make(map[string]*ServerSession)
s.conns = make(map[*ServerConn]struct{})
s.connClose = make(chan *ServerConn)
s.sessionRequest = make(chan sessionRequestReq)
s.sessionClose = make(chan *ServerSession)
s.streamMulticastIP = make(chan streamMulticastIPReq)
s.wg.Add(1)
connNew := make(chan net.Conn)
acceptErr := make(chan error)
go func() {
defer s.wg.Done()
err := func() error {
for {
nconn, err := s.tcpListener.Accept()
if err != nil {
return err
}
select {
case connNew <- nconn:
case <-s.ctx.Done():
nconn.Close()
}
}
}()
select {
case acceptErr <- err:
case <-s.ctx.Done():
}
}()
s.closeError = func() error {
for {
select {
case err := <-acceptErr:
return err
case nconn := <-connNew:
sc := newServerConn(s, nconn)
s.conns[sc] = struct{}{}
case sc := <-s.connClose:
if _, ok := s.conns[sc]; !ok {
continue
}
delete(s.conns, sc)
sc.Close()
case req := <-s.sessionRequest:
if ss, ok := s.sessions[req.id]; ok {
if !req.sc.ip().Equal(ss.author.ip()) ||
req.sc.zone() != ss.author.zone() {
req.res <- sessionRequestRes{
res: &base.Response{
StatusCode: base.StatusBadRequest,
},
err: liberrors.ErrServerCannotUseSessionCreatedByOtherIP{},
}
continue
}
select {
case ss.request <- req:
case <-ss.ctx.Done():
req.res <- sessionRequestRes{
res: &base.Response{
StatusCode: base.StatusBadRequest,
},
err: liberrors.ErrServerTerminated{},
}
}
} else {
if !req.create {
req.res <- sessionRequestRes{
res: &base.Response{
StatusCode: base.StatusSessionNotFound,
},
err: liberrors.ErrServerSessionNotFound{},
}
continue
}
ss := newServerSession(s, req.sc)
s.sessions[ss.secretID] = ss
select {
case ss.request <- req:
case <-ss.ctx.Done():
req.res <- sessionRequestRes{
res: &base.Response{
StatusCode: base.StatusBadRequest,
},
err: liberrors.ErrServerTerminated{},
}
}
}
case ss := <-s.sessionClose:
if sss, ok := s.sessions[ss.secretID]; !ok || sss != ss {
continue
}
delete(s.sessions, ss.secretID)
ss.Close()
case req := <-s.streamMulticastIP:
ip32 := uint32(s.multicastNextIP[0])<<24 | uint32(s.multicastNextIP[1])<<16 |
uint32(s.multicastNextIP[2])<<8 | uint32(s.multicastNextIP[3])
mask := uint32(s.multicastNet.Mask[0])<<24 | uint32(s.multicastNet.Mask[1])<<16 |
uint32(s.multicastNet.Mask[2])<<8 | uint32(s.multicastNet.Mask[3])
ip32 = (ip32 & mask) | ((ip32 + 1) & ^mask)
ip := make(net.IP, 4)
ip[0] = byte(ip32 >> 24)
ip[1] = byte(ip32 >> 16)
ip[2] = byte(ip32 >> 8)
ip[3] = byte(ip32)
s.multicastNextIP = ip
req.res <- ip
case <-s.ctx.Done():
return liberrors.ErrServerTerminated{}
}
}
}()
s.ctxCancel()
if s.udpRTCPListener != nil {
s.udpRTCPListener.close()
}
if s.udpRTPListener != nil {
s.udpRTPListener.close()
}
s.tcpListener.Close()
}
// StartAndWait starts the server and waits until a fatal error.
func (s *Server) StartAndWait() error {
err := s.Start()
if err != nil {
return err
}
return s.Wait()
}