mediamtx/main.go

620 lines
13 KiB
Go
Raw Normal View History

2019-12-28 21:07:03 +00:00
package main
import (
"fmt"
"io"
2019-12-28 21:07:03 +00:00
"log"
"net"
2019-12-28 21:07:03 +00:00
"os"
"time"
2019-12-28 21:07:03 +00:00
"github.com/aler9/gortsplib"
"github.com/aler9/sdp/v3"
2019-12-28 21:07:03 +00:00
"gopkg.in/alecthomas/kingpin.v2"
)
2020-06-26 09:00:10 +00:00
var Version = "v0.0.0"
2019-12-28 21:07:03 +00:00
2020-08-30 13:27:03 +00:00
const (
checkPathPeriod = 5 * time.Second
)
type logDestination int
const (
logDestinationStdout logDestination = iota
logDestinationFile
)
2020-06-27 11:38:35 +00:00
type programEvent interface {
isProgramEvent()
}
2020-07-30 15:30:50 +00:00
type programEventMetrics struct {
res chan *metricsData
}
func (programEventMetrics) isProgramEvent() {}
2020-06-27 11:38:35 +00:00
type programEventClientNew struct {
nconn net.Conn
}
func (programEventClientNew) isProgramEvent() {}
type programEventClientClose struct {
done chan struct{}
client *client
2020-06-27 11:38:35 +00:00
}
func (programEventClientClose) isProgramEvent() {}
type programEventClientDescribe struct {
client *client
path string
2020-06-27 11:38:35 +00:00
}
func (programEventClientDescribe) isProgramEvent() {}
2020-06-27 11:38:35 +00:00
type programEventClientAnnounce struct {
res chan error
client *client
path string
sdpText []byte
sdpParsed *sdp.SessionDescription
2020-06-27 11:38:35 +00:00
}
func (programEventClientAnnounce) isProgramEvent() {}
type programEventClientSetupPlay struct {
2020-08-03 15:35:34 +00:00
res chan error
client *client
path string
trackId int
2020-06-27 11:38:35 +00:00
}
func (programEventClientSetupPlay) isProgramEvent() {}
type programEventClientSetupRecord struct {
2020-08-03 15:35:34 +00:00
res chan error
client *client
2020-06-27 11:38:35 +00:00
}
func (programEventClientSetupRecord) isProgramEvent() {}
type programEventClientPlay1 struct {
res chan error
client *client
2020-06-27 11:38:35 +00:00
}
func (programEventClientPlay1) isProgramEvent() {}
type programEventClientPlay2 struct {
2020-07-13 09:12:20 +00:00
done chan struct{}
client *client
2020-06-27 11:38:35 +00:00
}
func (programEventClientPlay2) isProgramEvent() {}
2020-07-13 09:12:20 +00:00
type programEventClientPlayStop struct {
done chan struct{}
client *client
2020-07-13 09:12:20 +00:00
}
func (programEventClientPlayStop) isProgramEvent() {}
2020-06-27 11:38:35 +00:00
type programEventClientRecord struct {
2020-07-13 09:12:20 +00:00
done chan struct{}
client *client
2020-06-27 11:38:35 +00:00
}
func (programEventClientRecord) isProgramEvent() {}
2020-07-13 09:12:20 +00:00
type programEventClientRecordStop struct {
done chan struct{}
client *client
2020-07-13 09:12:20 +00:00
}
func (programEventClientRecordStop) isProgramEvent() {}
type programEventClientFrameUdp struct {
2020-07-12 20:53:22 +00:00
addr *net.UDPAddr
streamType gortsplib.StreamType
buf []byte
2020-06-27 11:38:35 +00:00
}
func (programEventClientFrameUdp) isProgramEvent() {}
2020-06-27 11:38:35 +00:00
type programEventClientFrameTcp struct {
2020-07-12 20:53:22 +00:00
path string
trackId int
streamType gortsplib.StreamType
buf []byte
2020-06-27 11:38:35 +00:00
}
func (programEventClientFrameTcp) isProgramEvent() {}
type programEventSourceReady struct {
2020-07-14 07:19:07 +00:00
source *source
}
func (programEventSourceReady) isProgramEvent() {}
type programEventSourceNotReady struct {
2020-07-14 07:19:07 +00:00
source *source
}
func (programEventSourceNotReady) isProgramEvent() {}
type programEventSourceFrame struct {
2020-07-14 07:19:07 +00:00
source *source
2020-07-12 20:53:22 +00:00
trackId int
streamType gortsplib.StreamType
buf []byte
}
func (programEventSourceFrame) isProgramEvent() {}
2020-06-27 11:38:35 +00:00
type programEventTerminate struct{}
func (programEventTerminate) isProgramEvent() {}
2020-05-10 13:33:42 +00:00
type program struct {
conf *conf
logFile *os.File
metrics *metrics
pprof *pprof
2020-08-30 12:15:00 +00:00
paths map[string]*path
serverRtp *serverUdp
serverRtcp *serverUdp
2020-08-30 12:15:00 +00:00
serverRtsp *serverTcp
clients map[*client]struct{}
udpClientsByAddr map[udpClientAddr]*udpClient
publisherCount int
readerCount int
2020-06-27 11:38:35 +00:00
events chan programEvent
done chan struct{}
2020-05-10 13:33:42 +00:00
}
func newProgram(args []string, stdin io.Reader) (*program, error) {
2020-06-27 19:22:50 +00:00
k := kingpin.New("rtsp-simple-server",
"rtsp-simple-server "+Version+"\n\nRTSP server.")
2020-05-11 07:31:56 +00:00
2020-06-27 19:22:50 +00:00
argVersion := k.Flag("version", "print version").Bool()
argConfPath := k.Arg("confpath", "path to a config file. The default is rtsp-simple-server.yml. Use 'stdin' to read config from stdin").Default("rtsp-simple-server.yml").String()
2020-05-11 07:31:56 +00:00
kingpin.MustParse(k.Parse(args))
2020-05-11 07:31:56 +00:00
if *argVersion == true {
2020-05-11 07:39:49 +00:00
fmt.Println(Version)
2020-05-10 19:32:40 +00:00
os.Exit(0)
2020-01-26 11:58:56 +00:00
}
conf, err := loadConf(*argConfPath, stdin)
if err != nil {
return nil, err
}
p := &program{
conf: conf,
2020-08-30 12:15:00 +00:00
paths: make(map[string]*path),
clients: make(map[*client]struct{}),
udpClientsByAddr: make(map[udpClientAddr]*udpClient),
events: make(chan programEvent),
done: make(chan struct{}),
}
if _, ok := p.conf.logDestinationsParsed[logDestinationFile]; ok {
p.logFile, err = os.OpenFile(p.conf.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
}
p.log("rtsp-simple-server %s", Version)
2020-07-30 15:30:50 +00:00
if conf.Metrics {
p.metrics, err = newMetrics(p)
if err != nil {
return nil, err
}
2020-07-30 15:30:50 +00:00
}
if conf.Pprof {
p.pprof, err = newPprof(p)
if err != nil {
return nil, err
}
2020-06-27 13:42:54 +00:00
}
2020-08-30 12:15:00 +00:00
for name, confp := range conf.Paths {
if name == "all" {
continue
}
p.paths[name] = newPath(p, name, confp, true)
}
if _, ok := conf.protocolsParsed[gortsplib.StreamProtocolUdp]; ok {
2020-08-29 17:48:41 +00:00
p.serverRtp, err = newServerUdp(p, conf.RtpPort, gortsplib.StreamTypeRtp)
if err != nil {
return nil, err
}
2019-12-28 21:07:03 +00:00
2020-08-29 17:48:41 +00:00
p.serverRtcp, err = newServerUdp(p, conf.RtcpPort, gortsplib.StreamTypeRtcp)
if err != nil {
return nil, err
}
2019-12-28 21:07:03 +00:00
}
2020-08-29 17:48:41 +00:00
p.serverRtsp, err = newServerTcp(p)
if err != nil {
return nil, err
}
2020-06-27 11:38:35 +00:00
go p.run()
2019-12-28 21:07:03 +00:00
2020-05-10 13:33:42 +00:00
return p, nil
2019-12-28 21:07:03 +00:00
}
2020-06-27 12:18:16 +00:00
func (p *program) log(format string, args ...interface{}) {
line := fmt.Sprintf("[%d/%d/%d] "+format, append([]interface{}{len(p.clients),
p.publisherCount, p.readerCount}, args...)...)
if _, ok := p.conf.logDestinationsParsed[logDestinationStdout]; ok {
log.Println(line)
}
2020-08-30 13:27:03 +00:00
if _, ok := p.conf.logDestinationsParsed[logDestinationFile]; ok {
p.logFile.WriteString(line + "\n")
}
2020-06-27 12:18:16 +00:00
}
2020-06-27 11:38:35 +00:00
func (p *program) run() {
2020-08-30 12:27:26 +00:00
if p.metrics != nil {
go p.metrics.run()
}
if p.pprof != nil {
go p.pprof.run()
}
if p.serverRtp != nil {
go p.serverRtp.run()
}
if p.serverRtcp != nil {
go p.serverRtcp.run()
}
go p.serverRtsp.run()
for _, p := range p.paths {
p.onInit()
}
2020-08-30 13:27:03 +00:00
checkPathsTicker := time.NewTicker(checkPathPeriod)
defer checkPathsTicker.Stop()
2020-06-27 11:38:35 +00:00
outer:
for {
select {
case <-checkPathsTicker.C:
for _, path := range p.paths {
path.onCheck()
2020-06-27 11:38:35 +00:00
}
case rawEvt := <-p.events:
switch evt := rawEvt.(type) {
2020-07-30 15:30:50 +00:00
case programEventMetrics:
evt.res <- &metricsData{
clientCount: len(p.clients),
publisherCount: p.publisherCount,
readerCount: p.readerCount,
}
case programEventClientNew:
2020-07-30 11:31:18 +00:00
c := newClient(p, evt.nconn)
p.clients[c] = struct{}{}
c.log("connected")
2020-06-27 11:38:35 +00:00
case programEventClientClose:
delete(p.clients, evt.client)
2020-08-05 09:49:36 +00:00
if evt.client.pathName != "" {
if path, ok := p.paths[evt.client.pathName]; ok {
if path.publisher == evt.client {
2020-08-30 13:27:03 +00:00
path.onPublisherRemove()
}
}
2020-06-27 11:38:35 +00:00
}
evt.client.log("disconnected")
close(evt.done)
2020-06-27 11:38:35 +00:00
case programEventClientDescribe:
2020-08-30 13:27:03 +00:00
// create path if not exist
if _, ok := p.paths[evt.path]; !ok {
p.paths[evt.path] = newPath(p, evt.path, p.findConfForPathName(evt.path), false)
}
2020-06-27 11:38:35 +00:00
2020-08-30 13:27:03 +00:00
p.paths[evt.path].onDescribe(evt.client)
2020-06-27 11:38:35 +00:00
case programEventClientAnnounce:
2020-08-30 13:27:03 +00:00
// create path if not exist
if path, ok := p.paths[evt.path]; !ok {
p.paths[evt.path] = newPath(p, evt.path, p.findConfForPathName(evt.path), false)
} else {
2020-07-30 11:31:18 +00:00
if path.publisher != nil {
evt.res <- fmt.Errorf("someone is already publishing on path '%s'", evt.path)
continue
}
}
2020-08-30 13:27:03 +00:00
p.paths[evt.path].onPublisherNew(evt.client, evt.sdpText, evt.sdpParsed)
evt.res <- nil
2020-06-27 11:38:35 +00:00
case programEventClientSetupPlay:
path, ok := p.paths[evt.path]
if !ok || !path.publisherReady {
evt.res <- fmt.Errorf("no one is publishing on path '%s'", evt.path)
continue
}
2020-06-27 11:38:35 +00:00
2020-08-03 15:35:34 +00:00
if evt.trackId >= len(path.publisherSdpParsed.MediaDescriptions) {
evt.res <- fmt.Errorf("track %d does not exist", evt.trackId)
continue
}
2020-08-05 09:49:36 +00:00
evt.client.pathName = evt.path
evt.client.state = clientStatePrePlay
evt.res <- nil
2020-06-27 11:38:35 +00:00
case programEventClientSetupRecord:
evt.client.state = clientStatePreRecord
evt.res <- nil
2020-06-27 11:38:35 +00:00
case programEventClientPlay1:
2020-08-05 09:49:36 +00:00
path, ok := p.paths[evt.client.pathName]
if !ok || !path.publisherReady {
2020-08-05 09:49:36 +00:00
evt.res <- fmt.Errorf("no one is publishing on path '%s'", evt.client.pathName)
continue
}
2020-07-13 09:12:20 +00:00
2020-08-03 15:35:34 +00:00
if len(evt.client.streamTracks) == 0 {
evt.res <- fmt.Errorf("no tracks have been setup")
continue
}
2020-06-27 11:38:35 +00:00
evt.res <- nil
2020-07-13 09:12:20 +00:00
case programEventClientPlay2:
p.readerCount += 1
evt.client.state = clientStatePlay
close(evt.done)
2020-07-13 09:12:20 +00:00
case programEventClientPlayStop:
p.readerCount -= 1
evt.client.state = clientStatePrePlay
close(evt.done)
case programEventClientRecord:
p.publisherCount += 1
evt.client.state = clientStateRecord
if evt.client.streamProtocol == gortsplib.StreamProtocolUdp {
for trackId, track := range evt.client.streamTracks {
key := makeUdpClientAddr(evt.client.ip(), track.rtpPort)
p.udpClientsByAddr[key] = &udpClient{
client: evt.client,
trackId: trackId,
streamType: gortsplib.StreamTypeRtp,
}
key = makeUdpClientAddr(evt.client.ip(), track.rtcpPort)
p.udpClientsByAddr[key] = &udpClient{
client: evt.client,
trackId: trackId,
streamType: gortsplib.StreamTypeRtcp,
}
}
}
2020-08-30 13:27:03 +00:00
p.paths[evt.client.pathName].onPublisherSetReady()
close(evt.done)
2020-07-13 09:12:20 +00:00
case programEventClientRecordStop:
p.publisherCount -= 1
evt.client.state = clientStatePreRecord
if evt.client.streamProtocol == gortsplib.StreamProtocolUdp {
for _, track := range evt.client.streamTracks {
key := makeUdpClientAddr(evt.client.ip(), track.rtpPort)
delete(p.udpClientsByAddr, key)
key = makeUdpClientAddr(evt.client.ip(), track.rtcpPort)
delete(p.udpClientsByAddr, key)
}
}
2020-08-30 13:27:03 +00:00
p.paths[evt.client.pathName].onPublisherSetNotReady()
close(evt.done)
2020-06-27 11:38:35 +00:00
case programEventClientFrameUdp:
pub, ok := p.udpClientsByAddr[makeUdpClientAddr(evt.addr.IP, evt.addr.Port)]
if !ok {
continue
}
// client sent RTP on RTCP port or vice-versa
if pub.streamType != evt.streamType {
continue
}
2020-06-27 11:38:35 +00:00
pub.client.rtcpReceivers[pub.trackId].OnFrame(evt.streamType, evt.buf)
p.forwardFrame(pub.client.pathName, pub.trackId, evt.streamType, evt.buf)
2020-06-27 11:38:35 +00:00
case programEventClientFrameTcp:
p.forwardFrame(evt.path, evt.trackId, evt.streamType, evt.buf)
2020-06-27 11:38:35 +00:00
case programEventSourceReady:
evt.source.log("ready")
2020-08-30 13:27:03 +00:00
p.paths[evt.source.pathName].onPublisherSetReady()
case programEventSourceNotReady:
evt.source.log("not ready")
2020-08-30 13:27:03 +00:00
p.paths[evt.source.pathName].onPublisherSetNotReady()
case programEventSourceFrame:
2020-08-05 09:49:36 +00:00
p.forwardFrame(evt.source.pathName, evt.trackId, evt.streamType, evt.buf)
case programEventTerminate:
break outer
}
2020-06-27 11:38:35 +00:00
}
}
go func() {
for rawEvt := range p.events {
switch evt := rawEvt.(type) {
2020-07-30 15:30:50 +00:00
case programEventMetrics:
evt.res <- nil
2020-06-27 11:38:35 +00:00
case programEventClientClose:
close(evt.done)
case programEventClientDescribe:
2020-07-30 11:31:18 +00:00
evt.client.describeRes <- describeRes{nil, fmt.Errorf("terminated")}
2020-06-27 11:38:35 +00:00
case programEventClientAnnounce:
evt.res <- fmt.Errorf("terminated")
case programEventClientSetupPlay:
evt.res <- fmt.Errorf("terminated")
case programEventClientSetupRecord:
evt.res <- fmt.Errorf("terminated")
case programEventClientPlay1:
evt.res <- fmt.Errorf("terminated")
case programEventClientPlay2:
2020-07-13 09:12:20 +00:00
close(evt.done)
case programEventClientPlayStop:
close(evt.done)
2020-06-27 11:38:35 +00:00
case programEventClientRecord:
2020-07-13 09:12:20 +00:00
close(evt.done)
case programEventClientRecordStop:
close(evt.done)
2020-06-27 11:38:35 +00:00
}
}
}()
2020-08-30 11:31:46 +00:00
for _, p := range p.paths {
p.onClose()
}
2020-08-29 17:48:41 +00:00
p.serverRtsp.close()
2020-08-30 12:27:26 +00:00
if p.serverRtcp != nil {
p.serverRtcp.close()
2020-08-30 12:27:26 +00:00
}
if p.serverRtp != nil {
p.serverRtp.close()
}
2020-06-27 11:38:35 +00:00
for c := range p.clients {
c.conn.NetConn().Close()
<-c.done
2020-06-27 11:38:35 +00:00
}
2020-07-30 15:30:50 +00:00
if p.metrics != nil {
p.metrics.close()
}
2020-08-30 12:27:26 +00:00
if p.pprof != nil {
p.pprof.close()
}
if p.logFile != nil {
p.logFile.Close()
}
2020-06-27 11:38:35 +00:00
close(p.events)
close(p.done)
}
func (p *program) close() {
p.events <- programEventTerminate{}
<-p.done
}
2020-08-30 11:20:18 +00:00
func (p *program) findConfForPathName(name string) *confPath {
2020-08-05 09:49:36 +00:00
if confp, ok := p.conf.Paths[name]; ok {
2020-07-30 11:31:18 +00:00
return confp
}
2020-07-30 11:31:18 +00:00
if confp, ok := p.conf.Paths["all"]; ok {
return confp
}
return nil
}
2020-07-12 20:53:22 +00:00
func (p *program) forwardFrame(path string, trackId int, streamType gortsplib.StreamType, frame []byte) {
2020-07-30 11:31:18 +00:00
for c := range p.clients {
2020-08-05 09:49:36 +00:00
if c.pathName != path ||
2020-08-03 15:35:34 +00:00
c.state != clientStatePlay {
continue
}
2020-06-27 11:38:35 +00:00
2020-08-03 15:35:34 +00:00
track, ok := c.streamTracks[trackId]
if !ok {
continue
}
if c.streamProtocol == gortsplib.StreamProtocolUdp {
if streamType == gortsplib.StreamTypeRtp {
p.serverRtp.write(&udpAddrBufPair{
addr: &net.UDPAddr{
IP: c.ip(),
Zone: c.zone(),
Port: track.rtpPort,
},
buf: frame,
})
2020-06-27 11:38:35 +00:00
} else {
2020-08-03 15:35:34 +00:00
p.serverRtcp.write(&udpAddrBufPair{
addr: &net.UDPAddr{
IP: c.ip(),
Zone: c.zone(),
Port: track.rtcpPort,
},
2020-08-03 15:35:34 +00:00
buf: frame,
})
}
} else {
c.events <- clientEventFrameTcp{
frame: &gortsplib.InterleavedFrame{
TrackId: trackId,
StreamType: streamType,
Content: frame,
2020-08-03 15:35:34 +00:00
},
2020-06-27 11:38:35 +00:00
}
}
}
2020-05-10 14:33:20 +00:00
}
2019-12-28 21:07:03 +00:00
func main() {
_, err := newProgram(os.Args[1:], os.Stdin)
2019-12-28 21:07:03 +00:00
if err != nil {
log.Fatal("ERR: ", err)
2019-12-28 21:07:03 +00:00
}
2020-06-24 20:42:39 +00:00
select {}
2019-12-28 21:07:03 +00:00
}