mediamtx/internal/core/rtmp_source.go

272 lines
6.0 KiB
Go
Raw Normal View History

package core
2020-10-03 19:10:41 +00:00
import (
"context"
2020-10-03 19:10:41 +00:00
"fmt"
"sync"
2020-10-03 19:10:41 +00:00
"sync/atomic"
"time"
"github.com/aler9/gortsplib"
2020-11-15 16:56:54 +00:00
"github.com/aler9/gortsplib/pkg/rtpaac"
"github.com/aler9/gortsplib/pkg/rtph264"
2020-10-03 19:10:41 +00:00
"github.com/notedit/rtmp/av"
2021-04-03 09:02:06 +00:00
"github.com/aler9/rtsp-simple-server/internal/h264"
"github.com/aler9/rtsp-simple-server/internal/logger"
"github.com/aler9/rtsp-simple-server/internal/rtcpsenderset"
2021-04-03 09:39:19 +00:00
"github.com/aler9/rtsp-simple-server/internal/rtmp"
2020-10-03 19:10:41 +00:00
)
const (
rtmpSourceRetryPause = 5 * time.Second
2020-10-03 19:10:41 +00:00
)
type rtmpSourceParent interface {
Log(logger.Level, string, ...interface{})
OnSourceStaticSetReady(req pathSourceStaticSetReadyReq)
OnSourceStaticSetNotReady(req pathSourceStaticSetNotReadyReq)
OnSourceFrame(int, gortsplib.StreamType, []byte)
2020-10-19 20:17:48 +00:00
}
type rtmpSource struct {
ur string
readTimeout time.Duration
writeTimeout time.Duration
wg *sync.WaitGroup
stats *stats
parent rtmpSourceParent
2020-10-19 20:17:48 +00:00
2021-05-10 19:32:59 +00:00
ctx context.Context
ctxCancel func()
2020-10-03 19:10:41 +00:00
}
func newRTMPSource(
parentCtx context.Context,
2021-05-11 15:20:32 +00:00
ur string,
2021-01-31 15:24:58 +00:00
readTimeout time.Duration,
writeTimeout time.Duration,
wg *sync.WaitGroup,
stats *stats,
parent rtmpSourceParent) *rtmpSource {
ctx, ctxCancel := context.WithCancel(parentCtx)
2021-05-10 19:32:59 +00:00
s := &rtmpSource{
ur: ur,
readTimeout: readTimeout,
writeTimeout: writeTimeout,
wg: wg,
stats: stats,
parent: parent,
2021-05-10 19:32:59 +00:00
ctx: ctx,
ctxCancel: ctxCancel,
2020-10-03 19:10:41 +00:00
}
2021-04-25 14:44:10 +00:00
atomic.AddInt64(s.stats.CountSourcesRTMP, +1)
s.log(logger.Info, "started")
s.wg.Add(1)
go s.run()
2021-05-23 16:43:49 +00:00
2020-10-19 20:17:48 +00:00
return s
}
2020-10-03 19:10:41 +00:00
2020-11-05 11:30:25 +00:00
// Close closes a Source.
func (s *rtmpSource) Close() {
2021-04-25 14:44:10 +00:00
atomic.AddInt64(s.stats.CountSourcesRTMPRunning, -1)
s.log(logger.Info, "stopped")
2021-05-10 19:32:59 +00:00
s.ctxCancel()
2020-10-19 20:17:48 +00:00
}
2020-10-03 19:10:41 +00:00
// IsSource implements source.
func (s *rtmpSource) IsSource() {}
2020-10-19 20:17:48 +00:00
// IsSourceStatic implements sourceStatic.
func (s *rtmpSource) IsSourceStatic() {}
2020-10-03 19:10:41 +00:00
func (s *rtmpSource) log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[rtmp source] "+format, args...)
}
func (s *rtmpSource) run() {
defer s.wg.Done()
2020-10-03 19:10:41 +00:00
for {
2020-10-31 16:03:03 +00:00
ok := func() bool {
ok := s.runInner()
2020-10-31 16:03:03 +00:00
if !ok {
return false
}
2020-10-03 19:10:41 +00:00
2020-10-31 16:03:03 +00:00
select {
case <-time.After(rtmpSourceRetryPause):
2020-10-31 16:03:03 +00:00
return true
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
2020-10-31 16:03:03 +00:00
return false
}
}()
if !ok {
break
2020-10-03 19:10:41 +00:00
}
}
2021-05-10 19:32:59 +00:00
s.ctxCancel()
2020-10-03 19:10:41 +00:00
}
func (s *rtmpSource) runInner() bool {
2021-05-11 15:20:32 +00:00
innerCtx, innerCtxCancel := context.WithCancel(s.ctx)
2020-10-03 19:10:41 +00:00
2021-05-09 14:57:26 +00:00
runErr := make(chan error)
2020-10-03 19:10:41 +00:00
go func() {
2021-05-09 14:57:26 +00:00
runErr <- func() error {
s.log(logger.Debug, "connecting")
2020-10-03 19:10:41 +00:00
2021-05-11 15:20:32 +00:00
ctx2, cancel2 := context.WithTimeout(innerCtx, s.readTimeout)
defer cancel2()
conn, err := rtmp.DialContext(ctx2, s.ur)
if err != nil {
return err
}
readDone := make(chan error)
go func() {
readDone <- func() error {
conn.NetConn().SetReadDeadline(time.Now().Add(s.readTimeout))
conn.NetConn().SetWriteDeadline(time.Now().Add(s.writeTimeout))
err = conn.ClientHandshake()
if err != nil {
return err
2021-01-30 20:19:50 +00:00
}
2020-10-03 19:10:41 +00:00
conn.NetConn().SetWriteDeadline(time.Time{})
conn.NetConn().SetReadDeadline(time.Now().Add(s.readTimeout))
videoTrack, audioTrack, err := conn.ReadMetadata()
2021-04-03 09:02:06 +00:00
if err != nil {
return err
2021-01-30 20:19:50 +00:00
}
2020-10-03 19:10:41 +00:00
var tracks gortsplib.Tracks
videoTrackID := -1
audioTrackID := -1
var h264Encoder *rtph264.Encoder
if videoTrack != nil {
h264Encoder = rtph264.NewEncoder(96, nil, nil, nil)
videoTrackID = len(tracks)
tracks = append(tracks, videoTrack)
}
2021-03-10 14:06:45 +00:00
var aacEncoder *rtpaac.Encoder
if audioTrack != nil {
clockRate, _ := audioTrack.ClockRate()
aacEncoder = rtpaac.NewEncoder(96, clockRate, nil, nil, nil)
audioTrackID = len(tracks)
tracks = append(tracks, audioTrack)
}
s.log(logger.Info, "ready")
s.parent.OnSourceStaticSetReady(pathSourceStaticSetReadyReq{
Tracks: tracks,
})
defer func() {
2021-08-03 20:40:47 +00:00
s.parent.OnSourceStaticSetNotReady(pathSourceStaticSetNotReadyReq{Source: s})
}()
rtcpSenders := rtcpsenderset.New(tracks, s.parent.OnSourceFrame)
defer rtcpSenders.Close()
onFrame := func(trackID int, payload []byte) {
rtcpSenders.OnFrame(trackID, gortsplib.StreamTypeRTP, payload)
s.parent.OnSourceFrame(trackID, gortsplib.StreamTypeRTP, payload)
2021-01-30 20:19:50 +00:00
}
2020-10-05 19:07:34 +00:00
for {
conn.NetConn().SetReadDeadline(time.Now().Add(s.readTimeout))
pkt, err := conn.ReadPacket()
if err != nil {
return err
}
2020-10-05 19:07:34 +00:00
switch pkt.Type {
case av.H264:
if videoTrack == nil {
return fmt.Errorf("ERR: received an H264 frame, but track is not set up")
}
nalus, err := h264.DecodeAVCC(pkt.Data)
if err != nil {
return err
}
var outNALUs [][]byte
for _, nalu := range nalus {
// remove SPS, PPS and AUD, not needed by RTSP / RTMP
typ := h264.NALUType(nalu[0] & 0x1F)
switch typ {
case h264.NALUTypeSPS, h264.NALUTypePPS, h264.NALUTypeAccessUnitDelimiter:
continue
}
outNALUs = append(outNALUs, nalu)
}
pkts, err := h264Encoder.Encode(outNALUs, pkt.Time+pkt.CTime)
if err != nil {
return fmt.Errorf("ERR while encoding H264: %v", err)
}
for _, pkt := range pkts {
onFrame(videoTrackID, pkt)
}
case av.AAC:
if audioTrack == nil {
return fmt.Errorf("ERR: received an AAC frame, but track is not set up")
}
pkts, err := aacEncoder.Encode([][]byte{pkt.Data}, pkt.Time+pkt.CTime)
if err != nil {
return fmt.Errorf("ERR while encoding AAC: %v", err)
}
for _, pkt := range pkts {
onFrame(audioTrackID, pkt)
}
default:
return fmt.Errorf("ERR: unexpected packet: %v", pkt.Type)
}
}
}()
}()
2021-01-30 20:19:50 +00:00
select {
case err := <-readDone:
conn.NetConn().Close()
return err
2021-05-11 15:20:32 +00:00
case <-innerCtx.Done():
conn.NetConn().Close()
<-readDone
return nil
2020-10-03 19:10:41 +00:00
}
2021-01-30 20:19:50 +00:00
}()
2020-10-03 19:10:41 +00:00
}()
select {
2021-05-09 14:57:26 +00:00
case err := <-runErr:
2021-05-11 15:20:32 +00:00
innerCtxCancel()
s.log(logger.Info, "ERR: %s", err)
return true
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
2021-05-11 15:20:32 +00:00
innerCtxCancel()
2021-05-09 14:57:26 +00:00
<-runErr
return false
2020-10-03 19:10:41 +00:00
}
}