mediamtx/internal/sourcertmp/source.go

274 lines
5.6 KiB
Go
Raw Normal View History

2020-10-19 20:17:48 +00:00
package sourcertmp
2020-10-03 19:10:41 +00:00
import (
"fmt"
"net"
"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"
"github.com/notedit/rtmp/codec/h264"
"github.com/notedit/rtmp/format/rtmp"
"github.com/aler9/rtsp-simple-server/internal/logger"
"github.com/aler9/rtsp-simple-server/internal/rtcpsenderset"
"github.com/aler9/rtsp-simple-server/internal/rtmputils"
"github.com/aler9/rtsp-simple-server/internal/source"
2020-11-01 21:56:56 +00:00
"github.com/aler9/rtsp-simple-server/internal/stats"
2020-10-03 19:10:41 +00:00
)
const (
2021-01-30 20:19:50 +00:00
retryPause = 5 * time.Second
2020-10-03 19:10:41 +00:00
)
2020-11-05 11:30:25 +00:00
// Parent is implemeneted by path.Path.
2020-10-19 20:17:48 +00:00
type Parent interface {
Log(logger.Level, string, ...interface{})
OnExtSourceSetReady(req source.ExtSetReadyReq)
OnExtSourceSetNotReady(req source.ExtSetNotReadyReq)
2020-10-19 20:17:48 +00:00
}
// Source is a RTMP external source.
2020-10-19 20:17:48 +00:00
type Source struct {
2021-01-31 15:24:58 +00:00
ur string
readTimeout time.Duration
wg *sync.WaitGroup
stats *stats.Stats
parent Parent
2020-10-19 20:17:48 +00:00
// in
terminate chan struct{}
2020-10-03 19:10:41 +00:00
}
2020-11-05 11:30:25 +00:00
// New allocates a Source.
2020-10-19 20:17:48 +00:00
func New(ur string,
2021-01-31 15:24:58 +00:00
readTimeout time.Duration,
wg *sync.WaitGroup,
stats *stats.Stats,
2020-10-19 20:17:48 +00:00
parent Parent) *Source {
s := &Source{
2021-01-31 15:24:58 +00:00
ur: ur,
readTimeout: readTimeout,
wg: wg,
stats: stats,
parent: parent,
terminate: make(chan struct{}),
2020-10-03 19:10:41 +00:00
}
atomic.AddInt64(s.stats.CountSourcesRtmp, +1)
s.log(logger.Info, "started")
s.wg.Add(1)
go s.run()
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.
2020-10-19 20:17:48 +00:00
func (s *Source) Close() {
atomic.AddInt64(s.stats.CountSourcesRtmpRunning, -1)
s.log(logger.Info, "stopped")
2020-10-19 20:17:48 +00:00
close(s.terminate)
}
2020-10-03 19:10:41 +00:00
// IsSource implements source.Source.
2020-10-19 20:17:48 +00:00
func (s *Source) IsSource() {}
2021-03-14 16:27:04 +00:00
// IsExtSource implements path.extSource.
func (s *Source) IsExtSource() {}
2020-10-03 19:10:41 +00:00
func (s *Source) log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[rtmp source] "+format, args...)
}
func (s *Source) 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 {
2021-03-14 16:27:04 +00:00
case <-time.After(retryPause):
2020-10-31 16:03:03 +00:00
return true
case <-s.terminate:
2020-10-31 16:03:03 +00:00
return false
}
}()
if !ok {
break
2020-10-03 19:10:41 +00:00
}
}
}
func (s *Source) runInner() bool {
s.log(logger.Info, "connecting")
2020-10-03 19:10:41 +00:00
2021-03-10 14:06:45 +00:00
var conn *rtmputils.Conn
2020-10-03 19:10:41 +00:00
var err error
dialDone := make(chan struct{}, 1)
go func() {
defer close(dialDone)
var rconn *rtmp.Conn
var nconn net.Conn
2021-01-31 15:44:32 +00:00
rconn, nconn, err = rtmp.NewClient().Dial(s.ur, rtmp.PrepareReading)
2021-03-10 14:06:45 +00:00
conn = rtmputils.NewConn(rconn, nconn)
2020-10-03 19:10:41 +00:00
}()
select {
2021-01-31 15:44:32 +00:00
case <-dialDone:
case <-s.terminate:
2020-10-03 19:10:41 +00:00
return false
}
if err != nil {
s.log(logger.Info, "ERR: %s", err)
2020-10-03 19:10:41 +00:00
return true
}
2021-01-30 20:19:50 +00:00
var videoTrack *gortsplib.Track
var audioTrack *gortsplib.Track
metadataDone := make(chan struct{})
2021-01-30 20:19:50 +00:00
go func() {
defer close(metadataDone)
2021-03-10 14:06:45 +00:00
conn.NetConn().SetReadDeadline(time.Now().Add(s.readTimeout))
videoTrack, audioTrack, err = rtmputils.ReadMetadata(conn)
2021-01-31 15:44:32 +00:00
}()
2020-10-05 19:07:34 +00:00
2021-01-31 15:44:32 +00:00
select {
case <-metadataDone:
2021-01-31 15:44:32 +00:00
case <-s.terminate:
2021-03-10 14:06:45 +00:00
conn.NetConn().Close()
<-metadataDone
2021-01-31 15:44:32 +00:00
return false
}
2020-11-22 14:46:16 +00:00
2021-01-31 15:44:32 +00:00
if err != nil {
s.log(logger.Info, "ERR: %s", err)
return true
}
2020-10-05 19:07:34 +00:00
2021-01-31 15:44:32 +00:00
var tracks gortsplib.Tracks
2020-10-05 19:07:34 +00:00
var h264Encoder *rtph264.Encoder
2021-01-31 15:44:32 +00:00
if videoTrack != nil {
2021-03-10 14:06:45 +00:00
h264Encoder = rtph264.NewEncoder(96, nil, nil, nil)
2021-01-31 15:44:32 +00:00
tracks = append(tracks, videoTrack)
}
2020-11-22 14:46:16 +00:00
var aacEncoder *rtpaac.Encoder
2021-01-31 15:44:32 +00:00
if audioTrack != nil {
clockRate, _ := audioTrack.ClockRate()
2021-03-10 14:06:45 +00:00
aacEncoder = rtpaac.NewEncoder(96, clockRate, nil, nil, nil)
2021-01-31 15:44:32 +00:00
tracks = append(tracks, audioTrack)
2020-10-05 19:07:34 +00:00
}
2020-11-30 14:21:01 +00:00
for i, t := range tracks {
2020-12-05 19:42:59 +00:00
t.ID = i
2020-11-30 14:21:01 +00:00
}
s.log(logger.Info, "ready")
2021-03-23 19:37:43 +00:00
cres := make(chan source.ExtSetReadyRes)
s.parent.OnExtSourceSetReady(source.ExtSetReadyReq{
2021-03-23 19:37:43 +00:00
Tracks: tracks,
Res: cres,
})
2021-03-23 19:37:43 +00:00
res := <-cres
defer func() {
res := make(chan struct{})
s.parent.OnExtSourceSetNotReady(source.ExtSetNotReadyReq{
Res: res,
})
<-res
}()
2020-10-03 19:10:41 +00:00
2020-11-15 19:15:06 +00:00
readerDone := make(chan error)
2020-10-03 19:10:41 +00:00
go func() {
2021-01-30 20:19:50 +00:00
readerDone <- func() error {
2021-03-23 19:37:43 +00:00
rtcpSenders := rtcpsenderset.New(tracks, res.SP.OnFrame)
defer rtcpSenders.Close()
onFrame := func(trackID int, payload []byte) {
rtcpSenders.OnFrame(trackID, gortsplib.StreamTypeRTP, payload)
2021-03-23 19:37:43 +00:00
res.SP.OnFrame(videoTrack.ID, gortsplib.StreamTypeRTP, payload)
}
2021-01-30 20:19:50 +00:00
for {
2021-03-10 14:06:45 +00:00
conn.NetConn().SetReadDeadline(time.Now().Add(s.readTimeout))
pkt, err := conn.ReadPacket()
2021-01-30 20:19:50 +00:00
if err != nil {
return err
2020-10-05 19:07:34 +00:00
}
2021-01-30 20:19:50 +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")
2021-01-30 20:19:50 +00:00
}
2020-10-03 19:10:41 +00:00
2021-01-30 20:19:50 +00:00
// decode from AVCC format
nalus, typ := h264.SplitNALUs(pkt.Data)
if typ != h264.NALU_AVCC {
return fmt.Errorf("invalid NALU format (%d)", typ)
}
2020-10-03 19:10:41 +00:00
2021-03-10 14:06:45 +00:00
for _, nalu := range nalus {
// encode into RTP/H264 format
frames, err := h264Encoder.Encode(&rtph264.NALUAndTimestamp{
Timestamp: pkt.Time + pkt.CTime,
NALU: nalu,
})
if err != nil {
return err
}
for _, frame := range frames {
onFrame(videoTrack.ID, frame)
2021-03-10 14:06:45 +00:00
}
2021-01-30 20:19:50 +00:00
}
2020-10-05 19:07:34 +00:00
2021-01-30 20:19:50 +00:00
case av.AAC:
if audioTrack == nil {
return fmt.Errorf("ERR: received an AAC frame, but track is not set up")
2021-01-30 20:19:50 +00:00
}
2020-10-05 19:07:34 +00:00
2021-03-10 14:06:45 +00:00
frame, err := aacEncoder.Encode(&rtpaac.AUAndTimestamp{
Timestamp: pkt.Time + pkt.CTime,
AU: pkt.Data,
})
2021-01-30 20:19:50 +00:00
if err != nil {
return err
}
2020-10-05 19:07:34 +00:00
onFrame(audioTrack.ID, frame)
2021-01-30 20:19:50 +00:00
default:
return fmt.Errorf("ERR: unexpected packet: %v", pkt.Type)
2021-01-30 20:19:50 +00:00
}
2020-10-03 19:10:41 +00:00
}
2021-01-30 20:19:50 +00:00
}()
2020-10-03 19:10:41 +00:00
}()
for {
select {
2021-01-31 15:44:32 +00:00
case err := <-readerDone:
2021-03-10 14:06:45 +00:00
conn.NetConn().Close()
2021-01-31 15:44:32 +00:00
s.log(logger.Info, "ERR: %s", err)
return true
2020-10-03 19:10:41 +00:00
2021-01-31 15:44:32 +00:00
case <-s.terminate:
2021-03-10 14:06:45 +00:00
conn.NetConn().Close()
2021-01-31 15:44:32 +00:00
<-readerDone
return false
2020-10-03 19:10:41 +00:00
}
}
}