mediamtx/server-udp.go

94 lines
1.6 KiB
Go
Raw Normal View History

2019-12-31 12:48:17 +00:00
package main
import (
"net"
2020-01-26 17:08:15 +00:00
"time"
2020-07-12 20:53:22 +00:00
"github.com/aler9/gortsplib"
2019-12-31 12:48:17 +00:00
)
2020-07-11 14:40:19 +00:00
type udpAddrBufPair struct {
2020-01-26 17:08:15 +00:00
addr *net.UDPAddr
buf []byte
}
type serverUdp struct {
2020-07-12 20:53:22 +00:00
p *program
2020-08-31 22:01:17 +00:00
conn *net.UDPConn
2020-07-12 20:53:22 +00:00
streamType gortsplib.StreamType
readBuf *multiBuffer
2020-06-27 11:38:35 +00:00
2020-07-11 14:40:19 +00:00
writeChan chan *udpAddrBufPair
done chan struct{}
2019-12-31 12:48:17 +00:00
}
func newServerUdp(p *program, port int, streamType gortsplib.StreamType) (*serverUdp, error) {
2020-08-31 22:01:17 +00:00
conn, err := net.ListenUDP("udp", &net.UDPAddr{
2019-12-31 12:48:17 +00:00
Port: port,
})
if err != nil {
return nil, err
}
l := &serverUdp{
2020-07-12 20:53:22 +00:00
p: p,
2020-08-31 22:01:17 +00:00
conn: conn,
2020-07-12 20:53:22 +00:00
streamType: streamType,
readBuf: newMultiBuffer(3, clientUdpReadBufferSize),
2020-07-12 20:53:22 +00:00
writeChan: make(chan *udpAddrBufPair),
done: make(chan struct{}),
2019-12-31 12:48:17 +00:00
}
l.log("opened on :%d", port)
return l, nil
}
func (l *serverUdp) log(format string, args ...interface{}) {
2019-12-31 12:48:17 +00:00
var label string
2020-07-12 20:53:22 +00:00
if l.streamType == gortsplib.StreamTypeRtp {
2019-12-31 12:48:17 +00:00
label = "RTP"
} else {
label = "RTCP"
}
2020-06-27 12:18:16 +00:00
l.p.log("[UDP/"+label+" listener] "+format, args...)
2019-12-31 12:48:17 +00:00
}
func (l *serverUdp) run() {
writeDone := make(chan struct{})
2020-01-26 17:08:15 +00:00
go func() {
defer close(writeDone)
for w := range l.writeChan {
2020-08-31 22:01:17 +00:00
l.conn.SetWriteDeadline(time.Now().Add(l.p.conf.WriteTimeout))
l.conn.WriteTo(w.buf, w.addr)
2020-05-10 13:38:01 +00:00
}
}()
for {
buf := l.readBuf.next()
2020-08-31 22:01:17 +00:00
n, addr, err := l.conn.ReadFromUDP(buf)
2020-05-10 13:38:01 +00:00
if err != nil {
break
}
2019-12-31 12:48:17 +00:00
2020-08-31 22:01:17 +00:00
l.p.clientFrameUdp <- clientFrameUdpReq{
2020-06-27 11:38:35 +00:00
addr,
2020-07-12 20:53:22 +00:00
l.streamType,
2020-06-27 11:38:35 +00:00
buf[:n],
}
2020-05-10 13:38:01 +00:00
}
close(l.writeChan)
<-writeDone
2020-05-10 13:38:01 +00:00
2020-05-10 14:23:57 +00:00
close(l.done)
2020-05-10 13:38:01 +00:00
}
func (l *serverUdp) close() {
2020-08-31 22:01:17 +00:00
l.conn.Close()
2020-05-10 13:38:01 +00:00
<-l.done
2019-12-31 12:48:17 +00:00
}
func (l *serverUdp) write(pair *udpAddrBufPair) {
2020-07-11 14:40:19 +00:00
l.writeChan <- pair
}