mediamtx/internal/core/rtsp_server.go

442 lines
11 KiB
Go
Raw Normal View History

package core
2020-10-19 20:17:48 +00:00
import (
2021-05-10 19:32:59 +00:00
"context"
"crypto/rand"
2021-03-06 08:11:46 +00:00
"crypto/tls"
"fmt"
"strconv"
"strings"
2021-04-27 11:43:15 +00:00
"sync"
2021-03-06 08:11:46 +00:00
"time"
2020-12-06 17:01:10 +00:00
"github.com/aler9/gortsplib"
2021-04-27 11:43:15 +00:00
"github.com/aler9/gortsplib/pkg/base"
"github.com/aler9/gortsplib/pkg/headers"
"github.com/aler9/gortsplib/pkg/liberrors"
"github.com/aler9/rtsp-simple-server/internal/conf"
"github.com/aler9/rtsp-simple-server/internal/externalcmd"
"github.com/aler9/rtsp-simple-server/internal/logger"
2020-10-19 20:17:48 +00:00
)
type rtspServerAPISessionsListItem struct {
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State string `json:"state"`
}
type rtspServerAPISessionsListData struct {
Items map[string]rtspServerAPISessionsListItem `json:"items"`
}
type rtspServerAPISessionsListRes struct {
2022-01-14 22:42:41 +00:00
data *rtspServerAPISessionsListData
err error
}
type rtspServerAPISessionsListReq struct{}
type rtspServerAPISessionsKickRes struct {
2022-01-14 22:42:41 +00:00
err error
}
type rtspServerAPISessionsKickReq struct {
2022-01-14 22:42:41 +00:00
id string
}
type rtspServerParent interface {
Log(logger.Level, string, ...interface{})
2020-10-19 20:17:48 +00:00
}
2022-08-16 11:53:04 +00:00
func printAddresses(srv *gortsplib.Server) string {
var ret []string
ret = append(ret, fmt.Sprintf("%s (TCP)", srv.RTSPAddress))
if srv.UDPRTPAddress != "" {
ret = append(ret, fmt.Sprintf("%s (UDP/RTP)", srv.UDPRTPAddress))
}
if srv.UDPRTCPAddress != "" {
ret = append(ret, fmt.Sprintf("%s (UDP/RTCP)", srv.UDPRTCPAddress))
}
return strings.Join(ret, ", ")
}
type rtspServer struct {
externalAuthenticationURL string
authMethods []headers.AuthMethod
readTimeout conf.StringDuration
isTLS bool
rtspAddress string
protocols map[conf.Protocol]struct{}
runOnConnect string
runOnConnectRestart bool
externalCmdPool *externalcmd.Pool
metrics *metrics
pathManager *pathManager
parent rtspServerParent
2021-04-27 11:43:15 +00:00
2021-05-10 19:32:59 +00:00
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
srv *gortsplib.Server
mutex sync.RWMutex
conns map[*gortsplib.ServerConn]*rtspConn
sessions map[*gortsplib.ServerSession]*rtspSession
2020-10-19 20:17:48 +00:00
}
func newRTSPServer(
parentCtx context.Context,
externalAuthenticationURL string,
address string,
authMethods []headers.AuthMethod,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
2021-03-06 08:11:46 +00:00
readBufferCount int,
useUDP bool,
useMulticast bool,
rtpAddress string,
rtcpAddress string,
multicastIPRange string,
multicastRTPPort int,
multicastRTCPPort int,
2021-04-27 11:43:15 +00:00
isTLS bool,
2021-03-06 08:11:46 +00:00
serverCert string,
serverKey string,
2021-04-27 11:43:15 +00:00
rtspAddress string,
protocols map[conf.Protocol]struct{},
2021-04-27 11:43:15 +00:00
runOnConnect string,
runOnConnectRestart bool,
externalCmdPool *externalcmd.Pool,
metrics *metrics,
pathManager *pathManager,
2022-04-07 10:50:35 +00:00
parent rtspServerParent,
) (*rtspServer, error) {
ctx, ctxCancel := context.WithCancel(parentCtx)
2021-05-10 19:32:59 +00:00
s := &rtspServer{
externalAuthenticationURL: externalAuthenticationURL,
authMethods: authMethods,
readTimeout: readTimeout,
isTLS: isTLS,
rtspAddress: rtspAddress,
protocols: protocols,
externalCmdPool: externalCmdPool,
metrics: metrics,
pathManager: pathManager,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
conns: make(map[*gortsplib.ServerConn]*rtspConn),
sessions: make(map[*gortsplib.ServerSession]*rtspSession),
2021-05-07 21:07:31 +00:00
}
s.srv = &gortsplib.Server{
2022-02-19 15:08:10 +00:00
Handler: s,
ReadTimeout: time.Duration(readTimeout),
WriteTimeout: time.Duration(writeTimeout),
ReadBufferCount: readBufferCount,
WriteBufferCount: readBufferCount,
RTSPAddress: address,
2021-03-06 08:11:46 +00:00
}
if useUDP {
2021-05-07 21:07:31 +00:00
s.srv.UDPRTPAddress = rtpAddress
s.srv.UDPRTCPAddress = rtcpAddress
2021-03-06 08:11:46 +00:00
}
if useMulticast {
s.srv.MulticastIPRange = multicastIPRange
s.srv.MulticastRTPPort = multicastRTPPort
s.srv.MulticastRTCPPort = multicastRTCPPort
}
2021-04-27 11:43:15 +00:00
if isTLS {
2021-03-06 08:11:46 +00:00
cert, err := tls.LoadX509KeyPair(serverCert, serverKey)
if err != nil {
return nil, err
}
2021-05-07 21:07:31 +00:00
s.srv.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
2021-03-06 08:11:46 +00:00
}
2021-11-12 21:29:56 +00:00
err := s.srv.Start()
2020-10-19 20:17:48 +00:00
if err != nil {
return nil, err
}
2022-08-16 11:53:04 +00:00
s.log(logger.Info, "listener opened on %s", printAddresses(s.srv))
if s.metrics != nil {
if !isTLS {
s.metrics.rtspServerSet(s)
} else {
s.metrics.rtspsServerSet(s)
}
}
2021-05-10 19:32:59 +00:00
s.wg.Add(1)
go s.run()
return s, nil
}
2021-10-27 19:01:00 +00:00
func (s *rtspServer) log(level logger.Level, format string, args ...interface{}) {
label := func() string {
2021-04-27 11:43:15 +00:00
if s.isTLS {
return "RTSPS"
}
2021-04-27 11:43:15 +00:00
return "RTSP"
}()
2021-04-27 11:43:15 +00:00
s.parent.Log(level, "[%s] "+format, append([]interface{}{label}, args...)...)
2020-10-19 20:17:48 +00:00
}
func (s *rtspServer) close() {
s.log(logger.Info, "listener is closing")
2021-05-10 19:32:59 +00:00
s.ctxCancel()
s.wg.Wait()
2020-10-19 20:17:48 +00:00
}
func (s *rtspServer) run() {
2021-05-10 19:32:59 +00:00
defer s.wg.Done()
2020-10-19 20:17:48 +00:00
2021-05-07 21:07:31 +00:00
serverErr := make(chan error)
2021-04-27 11:43:15 +00:00
go func() {
2021-10-30 11:55:05 +00:00
serverErr <- s.srv.Wait()
2021-04-27 11:43:15 +00:00
}()
outer:
2021-05-07 21:07:31 +00:00
select {
case err := <-serverErr:
2021-10-30 11:56:59 +00:00
s.log(logger.Error, "%s", err)
2021-05-07 21:07:31 +00:00
break outer
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
2021-10-30 11:55:05 +00:00
s.srv.Close()
<-serverErr
2021-05-07 21:07:31 +00:00
break outer
2021-04-27 11:43:15 +00:00
}
2021-05-10 19:32:59 +00:00
s.ctxCancel()
2020-10-19 20:17:48 +00:00
if s.metrics != nil {
if !s.isTLS {
s.metrics.rtspServerSet(nil)
} else {
s.metrics.rtspsServerSet(nil)
}
}
2021-05-07 21:07:31 +00:00
}
func (s *rtspServer) newSessionID() (string, error) {
for {
b := make([]byte, 4)
_, err := rand.Read(b)
if err != nil {
return "", err
}
u := uint32(b[3])<<24 | uint32(b[2])<<16 | uint32(b[1])<<8 | uint32(b[0])
u %= 899999999
u += 100000000
id := strconv.FormatUint(uint64(u), 10)
alreadyPresent := func() bool {
for _, s := range s.sessions {
if s.id == id {
return true
}
}
return false
}()
if !alreadyPresent {
return id, nil
}
}
}
// OnConnOpen implements gortsplib.ServerHandlerOnConnOpen.
func (s *rtspServer) OnConnOpen(ctx *gortsplib.ServerHandlerOnConnOpenCtx) {
c := newRTSPConn(
s.externalAuthenticationURL,
2021-05-07 21:07:31 +00:00
s.rtspAddress,
s.authMethods,
2021-05-07 21:07:31 +00:00
s.readTimeout,
s.runOnConnect,
s.runOnConnectRestart,
s.externalCmdPool,
s.pathManager,
ctx.Conn,
2021-05-07 21:07:31 +00:00
s)
s.mutex.Lock()
2021-05-09 12:41:18 +00:00
s.conns[ctx.Conn] = c
2021-05-07 21:07:31 +00:00
s.mutex.Unlock()
2022-11-03 14:27:21 +00:00
ctx.Conn.SetUserData(c)
2021-05-07 21:07:31 +00:00
}
// OnConnClose implements gortsplib.ServerHandlerOnConnClose.
func (s *rtspServer) OnConnClose(ctx *gortsplib.ServerHandlerOnConnCloseCtx) {
2021-05-07 21:07:31 +00:00
s.mutex.Lock()
2021-05-09 12:41:18 +00:00
c := s.conns[ctx.Conn]
delete(s.conns, ctx.Conn)
2021-05-07 21:07:31 +00:00
s.mutex.Unlock()
2021-10-27 19:01:00 +00:00
c.onClose(ctx.Error)
2021-05-07 21:07:31 +00:00
}
// OnRequest implements gortsplib.ServerHandlerOnRequest.
func (s *rtspServer) OnRequest(sc *gortsplib.ServerConn, req *base.Request) {
2022-11-03 14:27:21 +00:00
c := sc.UserData().(*rtspConn)
2021-10-27 19:01:00 +00:00
c.onRequest(req)
2021-05-07 21:07:31 +00:00
}
// OnResponse implements gortsplib.ServerHandlerOnResponse.
func (s *rtspServer) OnResponse(sc *gortsplib.ServerConn, res *base.Response) {
2022-11-03 14:27:21 +00:00
c := sc.UserData().(*rtspConn)
2021-05-07 21:07:31 +00:00
c.OnResponse(res)
}
// OnSessionOpen implements gortsplib.ServerHandlerOnSessionOpen.
func (s *rtspServer) OnSessionOpen(ctx *gortsplib.ServerHandlerOnSessionOpenCtx) {
s.mutex.Lock()
id, _ := s.newSessionID()
se := newRTSPSession(
s.isTLS,
2021-05-07 21:07:31 +00:00
s.protocols,
id,
ctx.Session,
ctx.Conn,
s.externalCmdPool,
s.pathManager,
2021-05-07 21:07:31 +00:00
s)
s.sessions[ctx.Session] = se
2021-05-07 21:07:31 +00:00
s.mutex.Unlock()
2022-11-03 14:27:21 +00:00
ctx.Session.SetUserData(se)
2021-05-07 21:07:31 +00:00
}
// OnSessionClose implements gortsplib.ServerHandlerOnSessionClose.
func (s *rtspServer) OnSessionClose(ctx *gortsplib.ServerHandlerOnSessionCloseCtx) {
2021-05-07 21:07:31 +00:00
s.mutex.Lock()
se := s.sessions[ctx.Session]
delete(s.sessions, ctx.Session)
2021-05-07 21:07:31 +00:00
s.mutex.Unlock()
2020-10-19 20:17:48 +00:00
if se != nil {
2021-10-27 19:01:00 +00:00
se.onClose(ctx.Error)
}
2021-05-07 21:07:31 +00:00
}
// OnDescribe implements gortsplib.ServerHandlerOnDescribe.
2021-09-09 21:05:54 +00:00
func (s *rtspServer) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
2022-11-03 14:27:21 +00:00
c := ctx.Conn.UserData().(*rtspConn)
2021-10-27 19:01:00 +00:00
return c.onDescribe(ctx)
2021-05-07 21:07:31 +00:00
}
// OnAnnounce implements gortsplib.ServerHandlerOnAnnounce.
func (s *rtspServer) OnAnnounce(ctx *gortsplib.ServerHandlerOnAnnounceCtx) (*base.Response, error) {
2022-11-03 14:27:21 +00:00
c := ctx.Conn.UserData().(*rtspConn)
se := ctx.Session.UserData().(*rtspSession)
2021-10-27 19:01:00 +00:00
return se.onAnnounce(c, ctx)
2021-05-07 21:07:31 +00:00
}
// OnSetup implements gortsplib.ServerHandlerOnSetup.
func (s *rtspServer) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
2022-11-03 14:27:21 +00:00
c := ctx.Conn.UserData().(*rtspConn)
se := ctx.Session.UserData().(*rtspSession)
2021-10-27 19:01:00 +00:00
return se.onSetup(c, ctx)
2021-05-07 21:07:31 +00:00
}
// OnPlay implements gortsplib.ServerHandlerOnPlay.
func (s *rtspServer) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
2022-11-03 14:27:21 +00:00
se := ctx.Session.UserData().(*rtspSession)
2021-10-27 19:01:00 +00:00
return se.onPlay(ctx)
2021-05-07 21:07:31 +00:00
}
2021-04-27 11:43:15 +00:00
// OnRecord implements gortsplib.ServerHandlerOnRecord.
func (s *rtspServer) OnRecord(ctx *gortsplib.ServerHandlerOnRecordCtx) (*base.Response, error) {
2022-11-03 14:27:21 +00:00
se := ctx.Session.UserData().(*rtspSession)
2021-10-27 19:01:00 +00:00
return se.onRecord(ctx)
2021-04-27 11:43:15 +00:00
}
// OnPause implements gortsplib.ServerHandlerOnPause.
func (s *rtspServer) OnPause(ctx *gortsplib.ServerHandlerOnPauseCtx) (*base.Response, error) {
2022-11-03 14:27:21 +00:00
se := ctx.Session.UserData().(*rtspSession)
2021-10-27 19:01:00 +00:00
return se.onPause(ctx)
2020-10-19 20:17:48 +00:00
}
2022-10-31 18:16:13 +00:00
// OnPacketRTP implements gortsplib.ServerHandlerOnPacketRTP.
2021-11-12 21:29:56 +00:00
func (s *rtspServer) OnPacketRTP(ctx *gortsplib.ServerHandlerOnPacketRTPCtx) {
2022-11-03 14:27:21 +00:00
se := ctx.Session.UserData().(*rtspSession)
2021-11-12 21:29:56 +00:00
se.onPacketRTP(ctx)
}
2022-10-31 18:16:13 +00:00
// OnDecodeError implements gortsplib.ServerHandlerOnOnDecodeError.
func (s *rtspServer) OnDecodeError(ctx *gortsplib.ServerHandlerOnDecodeErrorCtx) {
2022-11-03 14:27:21 +00:00
se := ctx.Session.UserData().(*rtspSession)
2022-10-31 18:16:13 +00:00
se.onDecodeError(ctx)
}
// apiSessionsList is called by api and metrics.
func (s *rtspServer) apiSessionsList(req rtspServerAPISessionsListReq) rtspServerAPISessionsListRes {
select {
case <-s.ctx.Done():
2022-01-14 22:42:41 +00:00
return rtspServerAPISessionsListRes{err: fmt.Errorf("terminated")}
default:
}
s.mutex.RLock()
defer s.mutex.RUnlock()
data := &rtspServerAPISessionsListData{
Items: make(map[string]rtspServerAPISessionsListItem),
}
for _, s := range s.sessions {
data.Items[s.id] = rtspServerAPISessionsListItem{
Created: s.created,
RemoteAddr: s.remoteAddr().String(),
State: func() string {
switch s.safeState() {
2022-02-18 09:21:04 +00:00
case gortsplib.ServerSessionStatePrePlay,
gortsplib.ServerSessionStatePlay:
return "read"
2022-02-18 09:21:04 +00:00
case gortsplib.ServerSessionStatePreRecord,
gortsplib.ServerSessionStateRecord:
return "publish"
}
return "idle"
}(),
2021-08-07 14:07:08 +00:00
}
}
2022-01-14 22:42:41 +00:00
return rtspServerAPISessionsListRes{data: data}
}
// apiSessionsKick is called by api.
func (s *rtspServer) apiSessionsKick(req rtspServerAPISessionsKickReq) rtspServerAPISessionsKickRes {
select {
case <-s.ctx.Done():
2022-01-14 22:42:41 +00:00
return rtspServerAPISessionsKickRes{err: fmt.Errorf("terminated")}
default:
}
s.mutex.RLock()
defer s.mutex.RUnlock()
for key, se := range s.sessions {
if se.id == req.id {
2021-10-27 19:01:00 +00:00
se.close()
delete(s.sessions, key)
2021-10-27 19:01:00 +00:00
se.onClose(liberrors.ErrServerTerminated{})
return rtspServerAPISessionsKickRes{}
}
}
2022-01-14 22:42:41 +00:00
return rtspServerAPISessionsKickRes{err: fmt.Errorf("not found")}
2020-10-19 20:17:48 +00:00
}