mediamtx/internal/core/rtmp_server.go

273 lines
5.3 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"
"crypto/rand"
"encoding/binary"
"fmt"
2021-01-31 15:58:57 +00:00
"net"
"strconv"
2021-04-27 16:32:23 +00:00
"sync"
"time"
2021-01-31 15:58:57 +00:00
"github.com/aler9/gortsplib"
2021-01-31 15:58:57 +00:00
"github.com/aler9/rtsp-simple-server/internal/logger"
)
type rtmpServerParent interface {
2021-01-31 15:58:57 +00:00
Log(logger.Level, string, ...interface{})
}
type rtmpServer struct {
2021-04-27 16:32:23 +00:00
readTimeout time.Duration
writeTimeout time.Duration
readBufferCount int
rtspAddress string
runOnConnect string
runOnConnectRestart bool
stats *stats
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
l net.Listener
conns map[*rtmpConn]struct{}
2021-04-27 16:32:23 +00:00
// in
connClose chan *rtmpConn
apiRTMPConnsList chan apiRTMPConnsListReq
apiRTMPConnsKick chan apiRTMPConnsKickReq
2021-01-31 15:58:57 +00:00
}
func newRTMPServer(
parentCtx context.Context,
address string,
2021-04-27 16:32:23 +00:00
readTimeout time.Duration,
writeTimeout time.Duration,
readBufferCount int,
rtspAddress string,
runOnConnect string,
runOnConnectRestart bool,
stats *stats,
pathManager *pathManager,
parent rtmpServerParent) (*rtmpServer, error) {
2021-01-31 15:58:57 +00:00
l, err := net.Listen("tcp", address)
if err != nil {
return nil, err
}
ctx, ctxCancel := context.WithCancel(parentCtx)
2021-05-10 19:32:59 +00:00
s := &rtmpServer{
2021-04-27 16:32:23 +00:00
readTimeout: readTimeout,
writeTimeout: writeTimeout,
readBufferCount: readBufferCount,
rtspAddress: rtspAddress,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
stats: stats,
pathManager: pathManager,
2021-04-27 16:32:23 +00:00
parent: parent,
2021-05-10 19:32:59 +00:00
ctx: ctx,
ctxCancel: ctxCancel,
2021-04-27 16:32:23 +00:00
l: l,
conns: make(map[*rtmpConn]struct{}),
connClose: make(chan *rtmpConn),
apiRTMPConnsList: make(chan apiRTMPConnsListReq),
apiRTMPConnsKick: make(chan apiRTMPConnsKickReq),
2021-01-31 15:58:57 +00:00
}
2021-04-27 16:32:23 +00:00
s.Log(logger.Info, "listener opened on %s", address)
2021-01-31 15:58:57 +00:00
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{}) {
2021-04-27 16:32:23 +00:00
s.parent.Log(level, "[RTMP] "+format, append([]interface{}{}, args...)...)
}
func (s *rtmpServer) close() {
2021-05-10 19:32:59 +00:00
s.ctxCancel()
s.wg.Wait()
s.Log(logger.Info, "closed")
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 {
conn, err := s.l.Accept()
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.Warn, "ERR: %s", err)
break outer
case nconn := <-connNew:
id, _ := s.newConnID()
c := newRTMPConn(
2021-05-11 15:20:32 +00:00
s.ctx,
id,
2021-04-27 16:32:23 +00:00
s.rtspAddress,
s.readTimeout,
s.writeTimeout,
s.readBufferCount,
s.runOnConnect,
s.runOnConnectRestart,
&s.wg,
s.stats,
nconn,
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
2021-05-09 12:41:18 +00:00
case c := <-s.connClose:
if _, ok := s.conns[c]; !ok {
2021-04-27 16:32:23 +00:00
continue
}
2021-05-09 12:41:18 +00:00
s.doConnClose(c)
2021-04-27 16:32:23 +00:00
case req := <-s.apiRTMPConnsList:
for c := range s.conns {
2021-08-07 14:07:08 +00:00
req.Data.Items[c.ID()] = apiRTMPConnsListItem{
RemoteAddr: c.RemoteAddr().String(),
State: func() string {
switch c.safeState() {
case gortsplib.ServerSessionStateRead:
return "read"
case gortsplib.ServerSessionStatePublish:
return "publish"
}
return "idle"
}(),
2021-08-07 14:07:08 +00:00
}
}
req.Res <- apiRTMPConnsListRes{}
case req := <-s.apiRTMPConnsKick:
res := func() bool {
for c := range s.conns {
if c.ID() == req.ID {
c.Close()
return true
}
}
return false
}()
if res {
req.Res <- apiRTMPConnsKickRes{}
} else {
req.Res <- apiRTMPConnsKickRes{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
s.l.Close()
2021-05-09 12:41:18 +00:00
for c := range s.conns {
s.doConnClose(c)
2021-01-31 15:58:57 +00:00
}
2021-04-27 16:32:23 +00:00
}
func (s *rtmpServer) newConnID() (string, error) {
for {
b := make([]byte, 4)
_, err := rand.Read(b)
if err != nil {
return "", err
}
u := binary.LittleEndian.Uint32(b)
u %= 899999999
u += 100000000
id := strconv.FormatUint(uint64(u), 10)
alreadyPresent := func() bool {
for c := range s.conns {
if c.ID() == id {
return true
}
}
return false
}()
if !alreadyPresent {
return id, nil
}
}
}
func (s *rtmpServer) doConnClose(c *rtmpConn) {
2021-05-09 12:41:18 +00:00
delete(s.conns, c)
2021-05-09 14:12:15 +00:00
c.ParentClose()
2021-04-27 16:32:23 +00:00
c.Close()
}
2021-01-31 15:58:57 +00:00
// OnConnClose is called by rtmpConn.
func (s *rtmpServer) OnConnClose(c *rtmpConn) {
2021-05-10 19:32:59 +00:00
select {
case s.connClose <- c:
case <-s.ctx.Done():
}
2021-01-31 15:58:57 +00:00
}
// OnAPIRTMPConnsList is called by api.
func (s *rtmpServer) OnAPIRTMPConnsList(req apiRTMPConnsListReq) apiRTMPConnsListRes {
req.Res = make(chan apiRTMPConnsListRes)
select {
case s.apiRTMPConnsList <- req:
return <-req.Res
case <-s.ctx.Done():
return apiRTMPConnsListRes{Err: fmt.Errorf("terminated")}
}
}
// OnAPIRTMPConnsKick is called by api.
func (s *rtmpServer) OnAPIRTMPConnsKick(req apiRTMPConnsKickReq) apiRTMPConnsKickRes {
req.Res = make(chan apiRTMPConnsKickRes)
select {
case s.apiRTMPConnsKick <- req:
return <-req.Res
case <-s.ctx.Done():
return apiRTMPConnsKickRes{Err: fmt.Errorf("terminated")}
}
}