mediamtx/internal/core/rtmp_server.go

316 lines
6.5 KiB
Go
Raw Normal View History

package core
2021-01-31 15:58:57 +00:00
import (
2021-05-10 19:32:59 +00:00
"context"
2022-08-16 11:53:04 +00:00
"crypto/tls"
"fmt"
2021-01-31 15:58:57 +00:00
"net"
2021-04-27 16:32:23 +00:00
"sync"
"time"
2021-01-31 15:58:57 +00:00
"github.com/google/uuid"
"github.com/aler9/mediamtx/internal/conf"
"github.com/aler9/mediamtx/internal/externalcmd"
"github.com/aler9/mediamtx/internal/logger"
2021-01-31 15:58:57 +00:00
)
type rtmpServerAPIConnsListItem struct {
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State string `json:"state"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
type rtmpServerAPIConnsListData struct {
Items map[string]rtmpServerAPIConnsListItem `json:"items"`
}
type rtmpServerAPIConnsListRes struct {
2022-01-14 22:42:41 +00:00
data *rtmpServerAPIConnsListData
err error
}
type rtmpServerAPIConnsListReq struct {
2022-01-14 22:42:41 +00:00
res chan rtmpServerAPIConnsListRes
}
type rtmpServerAPIConnsKickRes struct {
2022-01-14 22:42:41 +00:00
err error
}
type rtmpServerAPIConnsKickReq struct {
uuid uuid.UUID
res chan rtmpServerAPIConnsKickRes
}
type rtmpServerParent interface {
logger.Writer
2021-01-31 15:58:57 +00:00
}
type rtmpServer struct {
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
readBufferCount int
isTLS bool
rtspAddress string
runOnConnect string
runOnConnectRestart bool
externalCmdPool *externalcmd.Pool
metrics *metrics
pathManager *pathManager
parent rtmpServerParent
2021-04-27 16:32:23 +00:00
2021-05-10 19:32:59 +00:00
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
2022-08-16 11:53:04 +00:00
ln net.Listener
conns map[*rtmpConn]struct{}
2021-04-27 16:32:23 +00:00
// in
chConnClose chan *rtmpConn
chAPISessionsList chan rtmpServerAPIConnsListReq
chAPIConnsKick chan rtmpServerAPIConnsKickReq
2021-01-31 15:58:57 +00:00
}
func newRTMPServer(
parentCtx context.Context,
address string,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
2021-04-27 16:32:23 +00:00
readBufferCount int,
2022-08-16 11:53:04 +00:00
isTLS bool,
serverCert string,
serverKey string,
2021-04-27 16:32:23 +00:00
rtspAddress string,
runOnConnect string,
runOnConnectRestart bool,
externalCmdPool *externalcmd.Pool,
metrics *metrics,
pathManager *pathManager,
2022-04-07 10:50:35 +00:00
parent rtmpServerParent,
) (*rtmpServer, error) {
2022-08-16 11:53:04 +00:00
ln, err := func() (net.Listener, error) {
if !isTLS {
return net.Listen(restrictNetwork("tcp", address))
2022-08-16 11:53:04 +00:00
}
cert, err := tls.LoadX509KeyPair(serverCert, serverKey)
if err != nil {
return nil, err
}
network, address := restrictNetwork("tcp", address)
return tls.Listen(network, address, &tls.Config{Certificates: []tls.Certificate{cert}})
2022-08-16 11:53:04 +00:00
}()
2021-01-31 15:58:57 +00:00
if err != nil {
return nil, err
}
ctx, ctxCancel := context.WithCancel(parentCtx)
2021-05-10 19:32:59 +00:00
s := &rtmpServer{
readTimeout: readTimeout,
writeTimeout: writeTimeout,
readBufferCount: readBufferCount,
rtspAddress: rtspAddress,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
isTLS: isTLS,
externalCmdPool: externalCmdPool,
metrics: metrics,
pathManager: pathManager,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
ln: ln,
conns: make(map[*rtmpConn]struct{}),
chConnClose: make(chan *rtmpConn),
chAPISessionsList: make(chan rtmpServerAPIConnsListReq),
chAPIConnsKick: make(chan rtmpServerAPIConnsKickReq),
2021-01-31 15:58:57 +00:00
}
s.Log(logger.Info, "listener opened on %s", address)
2021-01-31 15:58:57 +00:00
if s.metrics != nil {
s.metrics.rtmpServerSet(s)
}
2021-05-10 19:32:59 +00:00
s.wg.Add(1)
2021-01-31 15:58:57 +00:00
go s.run()
return s, nil
}
func (s *rtmpServer) Log(level logger.Level, format string, args ...interface{}) {
2022-08-16 11:53:04 +00:00
label := func() string {
if s.isTLS {
return "RTMPS"
}
return "RTMP"
}()
s.parent.Log(level, "[%s] "+format, append([]interface{}{label}, args...)...)
}
func (s *rtmpServer) close() {
s.Log(logger.Info, "listener is closing")
2021-05-10 19:32:59 +00:00
s.ctxCancel()
s.wg.Wait()
2021-01-31 15:58:57 +00:00
}
func (s *rtmpServer) run() {
2021-05-10 19:32:59 +00:00
defer s.wg.Done()
2021-01-31 15:58:57 +00:00
2021-04-27 16:32:23 +00:00
s.wg.Add(1)
connNew := make(chan net.Conn)
2021-04-27 16:32:23 +00:00
acceptErr := make(chan error)
go func() {
defer s.wg.Done()
2021-05-10 19:32:59 +00:00
err := func() error {
2021-04-27 16:32:23 +00:00
for {
2022-08-16 11:53:04 +00:00
conn, err := s.ln.Accept()
2021-04-27 16:32:23 +00:00
if err != nil {
return err
}
2021-05-10 19:32:59 +00:00
select {
case connNew <- conn:
case <-s.ctx.Done():
conn.Close()
}
2021-04-27 16:32:23 +00:00
}
}()
2021-05-10 19:32:59 +00:00
select {
case acceptErr <- err:
case <-s.ctx.Done():
}
2021-04-27 16:32:23 +00:00
}()
outer:
2021-01-31 15:58:57 +00:00
for {
2021-04-27 16:32:23 +00:00
select {
case err := <-acceptErr:
s.Log(logger.Error, "%s", err)
2021-04-27 16:32:23 +00:00
break outer
case nconn := <-connNew:
c := newRTMPConn(
2021-05-11 15:20:32 +00:00
s.ctx,
2022-08-23 11:47:48 +00:00
s.isTLS,
2021-04-27 16:32:23 +00:00
s.rtspAddress,
s.readTimeout,
s.writeTimeout,
s.readBufferCount,
s.runOnConnect,
s.runOnConnectRestart,
&s.wg,
nconn,
s.externalCmdPool,
s.pathManager,
2021-04-27 16:32:23 +00:00
s)
2021-05-09 12:41:18 +00:00
s.conns[c] = struct{}{}
2021-04-27 16:32:23 +00:00
case c := <-s.chConnClose:
delete(s.conns, c)
2021-04-27 16:32:23 +00:00
case req := <-s.chAPISessionsList:
data := &rtmpServerAPIConnsListData{
Items: make(map[string]rtmpServerAPIConnsListItem),
}
for c := range s.conns {
data.Items[c.uuid.String()] = rtmpServerAPIConnsListItem{
Created: c.created,
RemoteAddr: c.remoteAddr().String(),
State: func() string {
switch c.safeState() {
2022-02-18 09:21:04 +00:00
case rtmpConnStateRead:
return "read"
2022-02-18 09:21:04 +00:00
case rtmpConnStatePublish:
return "publish"
}
return "idle"
}(),
BytesReceived: c.conn.BytesReceived(),
BytesSent: c.conn.BytesSent(),
2021-08-07 14:07:08 +00:00
}
}
2022-01-14 22:42:41 +00:00
req.res <- rtmpServerAPIConnsListRes{data: data}
case req := <-s.chAPIConnsKick:
c := s.findConnByUUID(req.uuid)
if c == nil {
2022-01-14 22:42:41 +00:00
req.res <- rtmpServerAPIConnsKickRes{fmt.Errorf("not found")}
continue
}
delete(s.conns, c)
c.close()
req.res <- rtmpServerAPIConnsKickRes{}
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
2021-04-27 16:32:23 +00:00
break outer
2021-01-31 15:58:57 +00:00
}
2021-04-27 16:32:23 +00:00
}
2021-01-31 15:58:57 +00:00
2021-05-10 19:32:59 +00:00
s.ctxCancel()
2021-04-27 16:32:23 +00:00
2022-08-16 11:53:04 +00:00
s.ln.Close()
if s.metrics != nil {
s.metrics.rtmpServerSet(s)
}
2021-04-27 16:32:23 +00:00
}
func (s *rtmpServer) findConnByUUID(uuid uuid.UUID) *rtmpConn {
for c := range s.conns {
if c.uuid == uuid {
return c
}
}
return nil
}
// connClose is called by rtmpConn.
func (s *rtmpServer) connClose(c *rtmpConn) {
2021-05-10 19:32:59 +00:00
select {
case s.chConnClose <- c:
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
}
2021-01-31 15:58:57 +00:00
}
// apiConnsList is called by api.
func (s *rtmpServer) apiConnsList() rtmpServerAPIConnsListRes {
req := rtmpServerAPIConnsListReq{
res: make(chan rtmpServerAPIConnsListRes),
}
select {
case s.chAPISessionsList <- req:
2022-01-14 22:42:41 +00:00
return <-req.res
case <-s.ctx.Done():
2022-01-14 22:42:41 +00:00
return rtmpServerAPIConnsListRes{err: fmt.Errorf("terminated")}
}
}
// apiConnsKick is called by api.
func (s *rtmpServer) apiConnsKick(uuid uuid.UUID) rtmpServerAPIConnsKickRes {
req := rtmpServerAPIConnsKickReq{
uuid: uuid,
res: make(chan rtmpServerAPIConnsKickRes),
}
select {
case s.chAPIConnsKick <- req:
2022-01-14 22:42:41 +00:00
return <-req.res
case <-s.ctx.Done():
2022-01-14 22:42:41 +00:00
return rtmpServerAPIConnsKickRes{err: fmt.Errorf("terminated")}
}
}