mediamtx/internal/core/rtmp_source.go

256 lines
5.6 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
"time"
"github.com/aler9/gortsplib"
2021-09-23 18:14:20 +00:00
"github.com/aler9/gortsplib/pkg/h264"
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"
"github.com/aler9/rtsp-simple-server/internal/conf"
"github.com/aler9/rtsp-simple-server/internal/logger"
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 {
2021-10-27 19:01:00 +00:00
log(logger.Level, string, ...interface{})
onSourceStaticSetReady(req pathSourceStaticSetReadyReq) pathSourceStaticSetReadyRes
2022-01-14 22:42:41 +00:00
onSourceStaticSetNotReady(req pathSourceStaticSetNotReadyReq)
2020-10-19 20:17:48 +00:00
}
type rtmpSource struct {
ur string
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
wg *sync.WaitGroup
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,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
wg *sync.WaitGroup,
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,
parent: parent,
2021-05-10 19:32:59 +00:00
ctx: ctx,
ctxCancel: ctxCancel,
2020-10-03 19:10:41 +00:00
}
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.
2021-10-27 19:01:00 +00:00
func (s *rtmpSource) close() {
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
func (s *rtmpSource) log(level logger.Level, format string, args ...interface{}) {
2021-10-27 19:01:00 +00:00
s.parent.log(level, "[rtmp source] "+format, args...)
}
func (s *rtmpSource) run() {
defer s.wg.Done()
2020-10-03 19:10:41 +00:00
2021-08-19 15:28:42 +00:00
outer:
2020-10-03 19:10:41 +00:00
for {
2021-08-19 15:28:42 +00:00
ok := s.runInner()
2020-10-31 16:03:03 +00:00
if !ok {
2021-08-19 15:28:42 +00:00
break outer
}
select {
case <-time.After(rtmpSourceRetryPause):
case <-s.ctx.Done():
break outer
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
ctx2, cancel2 := context.WithTimeout(innerCtx, time.Duration(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 {
2021-12-22 16:33:37 +00:00
conn.SetReadDeadline(time.Now().Add(time.Duration(s.readTimeout)))
conn.SetWriteDeadline(time.Now().Add(time.Duration(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
2021-12-22 16:33:37 +00:00
conn.SetWriteDeadline(time.Time{})
conn.SetReadDeadline(time.Now().Add(time.Duration(s.readTimeout)))
videoTrack, audioTrack, err := conn.ReadTracks()
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 {
2022-03-24 11:59:22 +00:00
h264Encoder = &rtph264.Encoder{PayloadType: 96}
h264Encoder.Init()
videoTrackID = len(tracks)
tracks = append(tracks, videoTrack)
}
2021-03-10 14:06:45 +00:00
var aacEncoder *rtpaac.Encoder
if audioTrack != nil {
2022-03-24 11:59:22 +00:00
aacEncoder = &rtpaac.Encoder{
PayloadType: 97,
SampleRate: audioTrack.ClockRate(),
}
aacEncoder.Init()
audioTrackID = len(tracks)
tracks = append(tracks, audioTrack)
}
2021-10-27 19:01:00 +00:00
res := s.parent.onSourceStaticSetReady(pathSourceStaticSetReadyReq{
2022-01-14 22:42:41 +00:00
source: s,
tracks: tracks,
})
2022-01-14 22:42:41 +00:00
if res.err != nil {
return res.err
}
s.log(logger.Info, "ready")
defer func() {
2022-01-14 22:42:41 +00:00
s.parent.onSourceStaticSetNotReady(pathSourceStaticSetNotReadyReq{source: s})
}()
for {
2021-12-22 16:33:37 +00:00
conn.SetReadDeadline(time.Now().Add(time.Duration(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 {
2021-11-12 21:29:56 +00:00
return fmt.Errorf("received an H264 packet, 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 {
2021-10-27 17:49:57 +00:00
return fmt.Errorf("error while encoding H264: %v", err)
}
for _, pkt := range pkts {
res.stream.writePacketRTP(videoTrackID, pkt)
}
case av.AAC:
if audioTrack == nil {
2021-11-12 21:29:56 +00:00
return fmt.Errorf("received an AAC packet, but track is not set up")
}
pkts, err := aacEncoder.Encode([][]byte{pkt.Data}, pkt.Time+pkt.CTime)
if err != nil {
2021-10-27 17:49:57 +00:00
return fmt.Errorf("error while encoding AAC: %v", err)
}
for _, pkt := range pkts {
res.stream.writePacketRTP(audioTrackID, pkt)
}
}
}
}()
}()
2021-01-30 20:19:50 +00:00
select {
case err := <-readDone:
2021-12-22 16:33:37 +00:00
conn.Close()
return err
2021-05-11 15:20:32 +00:00
case <-innerCtx.Done():
2021-12-22 16:33:37 +00:00
conn.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
}
}
2021-10-27 19:01:00 +00:00
// onSourceAPIDescribe implements source.
func (*rtmpSource) onSourceAPIDescribe() interface{} {
return struct {
Type string `json:"type"`
}{"rtmpSource"}
}