forked from bluenviron/mediamtx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-udp.go
101 lines (84 loc) · 1.82 KB
/
server-udp.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
package main
import (
"net"
"time"
"github.com/aler9/gortsplib"
)
type udpAddrBufPair struct {
addr *net.UDPAddr
buf []byte
}
type serverUdp struct {
p *program
nconn *net.UDPConn
streamType gortsplib.StreamType
readBuf *doubleBuffer
writeBuf *doubleBuffer
writeChan chan *udpAddrBufPair
done chan struct{}
}
func newServerUdp(p *program, port int, streamType gortsplib.StreamType) (*serverUdp, error) {
nconn, err := net.ListenUDP("udp", &net.UDPAddr{
Port: port,
})
if err != nil {
return nil, err
}
l := &serverUdp{
p: p,
nconn: nconn,
streamType: streamType,
readBuf: newDoubleBuffer(clientUdpReadBufferSize),
writeBuf: newDoubleBuffer(clientUdpWriteBufferSize),
writeChan: make(chan *udpAddrBufPair),
done: make(chan struct{}),
}
l.log("opened on :%d", port)
return l, nil
}
func (l *serverUdp) log(format string, args ...interface{}) {
var label string
if l.streamType == gortsplib.StreamTypeRtp {
label = "RTP"
} else {
label = "RTCP"
}
l.p.log("[UDP/"+label+" listener] "+format, args...)
}
func (l *serverUdp) run() {
writeDone := make(chan struct{})
go func() {
defer close(writeDone)
for w := range l.writeChan {
l.nconn.SetWriteDeadline(time.Now().Add(l.p.conf.WriteTimeout))
l.nconn.WriteTo(w.buf, w.addr)
}
}()
for {
buf := l.readBuf.swap()
n, addr, err := l.nconn.ReadFromUDP(buf)
if err != nil {
break
}
l.p.events <- programEventClientFrameUdp{
addr,
l.streamType,
buf[:n],
}
}
close(l.writeChan)
<-writeDone
close(l.done)
}
func (l *serverUdp) close() {
l.nconn.Close()
<-l.done
}
func (l *serverUdp) write(pair *udpAddrBufPair) {
// replace input buffer with write buffer
buf := l.writeBuf.swap()
buf = buf[:len(pair.buf)]
copy(buf, pair.buf)
pair.buf = buf
l.writeChan <- pair
}