mediamtx/internal/core/rtmp_server.go

314 lines
6.7 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/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 {
2022-01-14 22:42:41 +00:00
id string
res chan rtmpServerAPIConnsKickRes
}
type rtmpServerParent interface {
2021-01-31 15:58:57 +00:00
Log(logger.Level, string, ...interface{})
}
type rtmpServer struct {
externalAuthenticationURL string
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
readBufferCount int
2022-08-16 11:53:04 +00:00
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
chAPIConnsList chan rtmpServerAPIConnsListReq
chAPIConnsKick chan rtmpServerAPIConnsKickReq
2021-01-31 15:58:57 +00:00
}
func newRTMPServer(
parentCtx context.Context,
externalAuthenticationURL string,
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("tcp", address)
}
cert, err := tls.LoadX509KeyPair(serverCert, serverKey)
if err != nil {
return nil, err
}
return tls.Listen("tcp", address, &tls.Config{Certificates: []tls.Certificate{cert}})
}()
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{
externalAuthenticationURL: externalAuthenticationURL,
readTimeout: readTimeout,
writeTimeout: writeTimeout,
readBufferCount: readBufferCount,
rtspAddress: rtspAddress,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
2022-08-16 11:53:04 +00:00
isTLS: isTLS,
externalCmdPool: externalCmdPool,
metrics: metrics,
pathManager: pathManager,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
2022-08-16 11:53:04 +00:00
ln: ln,
conns: make(map[*rtmpConn]struct{}),
chConnClose: make(chan *rtmpConn),
chAPIConnsList: make(chan rtmpServerAPIConnsListReq),
chAPIConnsKick: make(chan rtmpServerAPIConnsKickReq),
2021-01-31 15:58:57 +00:00
}
2021-10-27 19:01:00 +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
}
2021-10-27 19:01:00 +00:00
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:
2021-10-30 11:56:59 +00:00
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,
s.externalAuthenticationURL,
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.chAPIConnsList:
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:
res := func() bool {
for c := range s.conns {
if c.uuid.String() == req.id {
delete(s.conns, c)
2021-10-27 19:01:00 +00:00
c.close()
return true
}
}
return false
}()
if res {
2022-01-14 22:42:41 +00:00
req.res <- rtmpServerAPIConnsKickRes{}
} else {
2022-01-14 22:42:41 +00:00
req.res <- rtmpServerAPIConnsKickRes{fmt.Errorf("not found")}
}
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
}
// 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.chAPIConnsList <- 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(id string) rtmpServerAPIConnsKickRes {
req := rtmpServerAPIConnsKickReq{
id: id,
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")}
}
}