mediamtx/server-tcpl.go

109 lines
2.1 KiB
Go
Raw Normal View History

2019-12-28 21:07:03 +00:00
package main
import (
"log"
"net"
"sync"
"github.com/aler9/gortsplib"
2019-12-28 21:07:03 +00:00
)
2020-01-20 14:22:01 +00:00
type serverTcpListener struct {
p *program
2020-05-10 14:08:41 +00:00
nconn *net.TCPListener
mutex sync.RWMutex
clients map[*serverClient]struct{}
publishers map[string]*serverClient
2020-05-10 14:23:57 +00:00
done chan struct{}
2019-12-28 21:07:03 +00:00
}
2020-01-20 14:22:01 +00:00
func newServerTcpListener(p *program) (*serverTcpListener, error) {
2020-05-10 14:08:41 +00:00
nconn, err := net.ListenTCP("tcp", &net.TCPAddr{
2020-05-10 13:33:42 +00:00
Port: p.args.rtspPort,
2019-12-28 21:07:03 +00:00
})
if err != nil {
return nil, err
}
2020-05-10 14:23:57 +00:00
l := &serverTcpListener{
p: p,
2020-05-10 14:08:41 +00:00
nconn: nconn,
clients: make(map[*serverClient]struct{}),
publishers: make(map[string]*serverClient),
2020-05-10 14:23:57 +00:00
done: make(chan struct{}),
2019-12-28 21:07:03 +00:00
}
2020-05-10 14:23:57 +00:00
l.log("opened on :%d", p.args.rtspPort)
return l, nil
2019-12-28 21:07:03 +00:00
}
2020-01-20 14:22:01 +00:00
func (l *serverTcpListener) log(format string, args ...interface{}) {
log.Printf("[TCP listener] "+format, args...)
2019-12-28 21:07:03 +00:00
}
2020-01-20 14:22:01 +00:00
func (l *serverTcpListener) run() {
2019-12-28 21:07:03 +00:00
for {
2020-05-10 14:08:41 +00:00
nconn, err := l.nconn.AcceptTCP()
2019-12-28 21:07:03 +00:00
if err != nil {
break
}
2020-05-10 14:23:57 +00:00
newServerClient(l.p, nconn)
2019-12-28 21:07:03 +00:00
}
2020-05-10 14:23:57 +00:00
// close clients
var doneChans []chan struct{}
func() {
l.mutex.Lock()
defer l.mutex.Unlock()
for c := range l.clients {
c.close()
doneChans = append(doneChans, c.done)
}
}()
for _, c := range doneChans {
<-c
}
close(l.done)
}
func (l *serverTcpListener) close() {
l.nconn.Close()
<-l.done
2019-12-28 21:07:03 +00:00
}
func (l *serverTcpListener) forwardTrack(path string, id int, flow trackFlow, frame []byte) {
for c := range l.clients {
if c.path == path && c.state == _CLIENT_STATE_PLAY {
if c.streamProtocol == _STREAM_PROTOCOL_UDP {
if flow == _TRACK_FLOW_RTP {
2020-05-10 14:08:41 +00:00
l.p.udplRtp.write <- &udpWrite{
addr: &net.UDPAddr{
IP: c.ip(),
Zone: c.zone(),
Port: c.streamTracks[id].rtpPort,
},
buf: frame,
}
} else {
2020-05-10 14:08:41 +00:00
l.p.udplRtcp.write <- &udpWrite{
addr: &net.UDPAddr{
IP: c.ip(),
Zone: c.zone(),
Port: c.streamTracks[id].rtcpPort,
},
buf: frame,
}
}
} else {
c.write <- &gortsplib.InterleavedFrame{
Channel: trackToInterleavedChannel(id, flow),
Content: frame,
}
}
}
}
}