mediamtx/internal/core/hls_remuxer.go

498 lines
10 KiB
Go
Raw Normal View History

package core
2021-04-11 17:05:08 +00:00
import (
"bytes"
2021-05-09 14:57:26 +00:00
"context"
2021-04-11 17:05:08 +00:00
"fmt"
"io"
2021-04-11 17:05:08 +00:00
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/aler9/gortsplib"
"github.com/aler9/gortsplib/pkg/ringbuffer"
"github.com/aler9/gortsplib/pkg/rtpaac"
"github.com/aler9/gortsplib/pkg/rtph264"
"github.com/pion/rtp"
2021-04-11 17:05:08 +00:00
"github.com/aler9/rtsp-simple-server/internal/h264"
"github.com/aler9/rtsp-simple-server/internal/hls"
2021-04-11 17:05:08 +00:00
"github.com/aler9/rtsp-simple-server/internal/logger"
)
const (
closeCheckPeriod = 1 * time.Second
closeAfterInactivity = 60 * time.Second
)
const index = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#video {
width: 600px;
height: 600px;
background: black;
}
</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.0.0"></script>
<video id="video" muted controls></video>
<script>
const create = () => {
const video = document.getElementById('video');
const hls = new Hls({
progressive: false,
});
hls.on(Hls.Events.ERROR, (evt, data) => {
if (data.fatal) {
hls.destroy();
setTimeout(() => {
create();
}, 2000);
}
});
hls.loadSource('stream.m3u8');
hls.attachMedia(video);
video.play();
}
create();
</script>
</body>
</html>
`
2021-07-29 10:16:06 +00:00
type hlsRemuxerRequest struct {
2021-07-04 14:03:24 +00:00
Dir string
File string
Req *http.Request
W http.ResponseWriter
Res chan io.Reader
}
2021-07-29 10:16:06 +00:00
type hlsRemuxerTrackIDPayloadPair struct {
2021-04-11 17:05:08 +00:00
trackID int
buf []byte
}
2021-07-29 10:16:06 +00:00
type hlsRemuxerParent interface {
2021-04-11 17:05:08 +00:00
Log(logger.Level, string, ...interface{})
2021-07-29 10:16:06 +00:00
OnRemuxerClose(*hlsRemuxer)
2021-04-11 17:05:08 +00:00
}
2021-07-29 10:16:06 +00:00
type hlsRemuxer struct {
hlsAlwaysRemux bool
2021-04-11 17:05:08 +00:00
hlsSegmentCount int
hlsSegmentDuration time.Duration
readBufferCount int
wg *sync.WaitGroup
stats *stats
2021-04-11 17:05:08 +00:00
pathName string
pathManager *pathManager
2021-07-29 10:16:06 +00:00
parent hlsRemuxerParent
2021-07-24 16:31:54 +00:00
ctx context.Context
ctxCancel func()
2021-07-31 16:25:47 +00:00
path *path
2021-07-24 16:31:54 +00:00
ringBuffer *ringbuffer.RingBuffer
lastRequestTime *int64
muxer *hls.Muxer
2021-04-11 17:05:08 +00:00
// in
2021-07-29 10:16:06 +00:00
request chan hlsRemuxerRequest
2021-04-11 17:05:08 +00:00
}
2021-07-29 10:16:06 +00:00
func newHLSRemuxer(
parentCtx context.Context,
hlsAlwaysRemux bool,
2021-04-11 17:05:08 +00:00
hlsSegmentCount int,
hlsSegmentDuration time.Duration,
readBufferCount int,
wg *sync.WaitGroup,
stats *stats,
2021-04-11 17:05:08 +00:00
pathName string,
pathManager *pathManager,
2021-07-29 10:16:06 +00:00
parent hlsRemuxerParent) *hlsRemuxer {
ctx, ctxCancel := context.WithCancel(parentCtx)
2021-05-10 19:32:59 +00:00
r := &hlsRemuxer{
hlsAlwaysRemux: hlsAlwaysRemux,
2021-04-11 17:05:08 +00:00
hlsSegmentCount: hlsSegmentCount,
hlsSegmentDuration: hlsSegmentDuration,
readBufferCount: readBufferCount,
wg: wg,
stats: stats,
pathName: pathName,
pathManager: pathManager,
2021-04-11 17:05:08 +00:00
parent: parent,
2021-05-10 19:32:59 +00:00
ctx: ctx,
ctxCancel: ctxCancel,
2021-07-24 16:31:54 +00:00
lastRequestTime: func() *int64 {
2021-07-03 10:19:03 +00:00
v := time.Now().Unix()
return &v
}(),
2021-07-29 10:16:06 +00:00
request: make(chan hlsRemuxerRequest),
2021-04-11 17:05:08 +00:00
}
r.log(logger.Info, "created")
2021-04-11 17:05:08 +00:00
r.wg.Add(1)
go r.run()
2021-04-11 17:05:08 +00:00
return r
2021-04-11 17:05:08 +00:00
}
2021-07-29 10:16:06 +00:00
// ParentClose closes a Remuxer.
func (r *hlsRemuxer) ParentClose() {
r.log(logger.Info, "destroyed")
2021-04-11 17:05:08 +00:00
}
func (r *hlsRemuxer) Close() {
r.ctxCancel()
2021-04-27 11:43:15 +00:00
}
func (r *hlsRemuxer) log(level logger.Level, format string, args ...interface{}) {
r.parent.Log(level, "[remuxer %s] "+format, append([]interface{}{r.pathName}, args...)...)
2021-04-11 17:05:08 +00:00
}
// PathName returns the path name.
func (r *hlsRemuxer) PathName() string {
return r.pathName
2021-04-11 17:05:08 +00:00
}
func (r *hlsRemuxer) run() {
defer r.wg.Done()
2021-04-11 17:05:08 +00:00
2021-05-10 19:32:59 +00:00
innerCtx, innerCtxCancel := context.WithCancel(context.Background())
2021-05-09 14:57:26 +00:00
runErr := make(chan error)
go func() {
runErr <- r.runInner(innerCtx)
2021-05-09 14:57:26 +00:00
}()
select {
case err := <-runErr:
2021-05-10 19:32:59 +00:00
innerCtxCancel()
if err != nil {
r.log(logger.Info, "ERR: %s", err)
}
2021-05-09 14:57:26 +00:00
case <-r.ctx.Done():
2021-05-10 19:32:59 +00:00
innerCtxCancel()
2021-05-09 14:57:26 +00:00
<-runErr
}
r.ctxCancel()
2021-05-09 14:57:26 +00:00
r.parent.OnRemuxerClose(r)
2021-05-09 14:57:26 +00:00
}
func (r *hlsRemuxer) runInner(innerCtx context.Context) error {
res := r.pathManager.OnReaderSetupPlay(pathReaderSetupPlayReq{
Author: r,
PathName: r.pathName,
2021-05-09 14:57:26 +00:00
IP: nil,
ValidateCredentials: nil,
})
if res.Err != nil {
return res.Err
}
r.path = res.Path
defer func() {
r.path.OnReaderRemove(pathReaderRemoveReq{Author: r})
}()
2021-04-11 17:05:08 +00:00
var videoTrack *gortsplib.Track
videoTrackID := -1
2021-04-11 17:05:08 +00:00
var h264SPS []byte
var h264PPS []byte
var h264Decoder *rtph264.Decoder
var audioTrack *gortsplib.Track
audioTrackID := -1
2021-04-11 17:05:08 +00:00
var aacConfig rtpaac.MPEG4AudioConfig
var aacDecoder *rtpaac.Decoder
for i, t := range res.Stream.Tracks() {
2021-05-09 14:57:26 +00:00
if t.IsH264() {
if videoTrack != nil {
return fmt.Errorf("can't read track %d with HLS: too many tracks", i+1)
}
2021-05-09 14:57:26 +00:00
videoTrack = t
videoTrackID = i
2021-04-11 17:05:08 +00:00
2021-05-09 14:57:26 +00:00
var err error
h264SPS, h264PPS, err = t.ExtractDataH264()
if err != nil {
return err
}
2021-04-11 17:05:08 +00:00
2021-05-09 14:57:26 +00:00
h264Decoder = rtph264.NewDecoder()
2021-04-11 17:05:08 +00:00
2021-05-09 14:57:26 +00:00
} else if t.IsAAC() {
if audioTrack != nil {
return fmt.Errorf("can't read track %d with HLS: too many tracks", i+1)
2021-04-11 17:05:08 +00:00
}
2021-05-09 14:57:26 +00:00
audioTrack = t
audioTrackID = i
2021-04-11 17:05:08 +00:00
2021-05-09 14:57:26 +00:00
byts, err := t.ExtractDataAAC()
if err != nil {
return err
}
2021-04-11 17:05:08 +00:00
2021-05-09 14:57:26 +00:00
err = aacConfig.Decode(byts)
if err != nil {
return err
2021-04-11 17:05:08 +00:00
}
2021-05-09 14:57:26 +00:00
aacDecoder = rtpaac.NewDecoder(aacConfig.SampleRate)
2021-04-11 17:05:08 +00:00
}
2021-05-09 14:57:26 +00:00
}
2021-04-11 17:05:08 +00:00
2021-05-09 14:57:26 +00:00
if videoTrack == nil && audioTrack == nil {
return fmt.Errorf("unable to find a video or audio track")
2021-04-11 17:05:08 +00:00
}
2021-07-24 16:31:54 +00:00
var err error
r.muxer, err = hls.NewMuxer(
r.hlsSegmentCount,
r.hlsSegmentDuration,
2021-07-24 16:31:54 +00:00
videoTrack,
audioTrack,
)
if err != nil {
return err
}
defer r.muxer.Close()
2021-04-11 17:05:08 +00:00
2021-07-24 16:31:54 +00:00
// start request handler only after muxer has been inizialized
2021-05-09 14:57:26 +00:00
requestHandlerTerminate := make(chan struct{})
requestHandlerDone := make(chan struct{})
go r.runRequestHandler(requestHandlerTerminate, requestHandlerDone)
2021-04-11 17:05:08 +00:00
defer func() {
2021-05-09 14:57:26 +00:00
close(requestHandlerTerminate)
<-requestHandlerDone
2021-04-11 17:05:08 +00:00
}()
r.ringBuffer = ringbuffer.New(uint64(r.readBufferCount))
2021-04-11 17:05:08 +00:00
r.path.OnReaderPlay(pathReaderPlayReq{
Author: r,
})
2021-04-11 17:05:08 +00:00
writerDone := make(chan error)
go func() {
writerDone <- func() error {
var videoBuf [][]byte
for {
data, ok := r.ringBuffer.Pull()
2021-04-11 17:05:08 +00:00
if !ok {
return fmt.Errorf("terminated")
}
2021-07-29 10:16:06 +00:00
pair := data.(hlsRemuxerTrackIDPayloadPair)
2021-04-11 17:05:08 +00:00
if videoTrack != nil && pair.trackID == videoTrackID {
var pkt rtp.Packet
err := pkt.Unmarshal(pair.buf)
if err != nil {
r.log(logger.Warn, "unable to decode RTP packet: %v", err)
continue
}
nalus, pts, err := h264Decoder.DecodeRTP(&pkt)
2021-04-11 17:05:08 +00:00
if err != nil {
2021-07-24 16:31:54 +00:00
if err != rtph264.ErrMorePacketsNeeded && err != rtph264.ErrNonStartingPacketAndNoPrevious {
r.log(logger.Warn, "unable to decode video track: %v", err)
2021-04-11 17:05:08 +00:00
}
continue
}
for _, nalu := range nalus {
// remove SPS, PPS, AUD
typ := h264.NALUType(nalu[0] & 0x1F)
switch typ {
case h264.NALUTypeSPS, h264.NALUTypePPS, h264.NALUTypeAccessUnitDelimiter:
continue
}
// add SPS and PPS before IDR
if typ == h264.NALUTypeIDR {
videoBuf = append(videoBuf, h264SPS)
videoBuf = append(videoBuf, h264PPS)
}
videoBuf = append(videoBuf, nalu)
}
// RTP marker means that all the NALUs with the same PTS have been received.
// send them together.
2021-07-24 16:31:54 +00:00
if pkt.Marker {
err := r.muxer.WriteH264(pts, videoBuf)
2021-04-11 17:05:08 +00:00
if err != nil {
return err
}
2021-07-24 16:31:54 +00:00
videoBuf = nil
2021-04-11 17:05:08 +00:00
}
} else if audioTrack != nil && pair.trackID == audioTrackID {
2021-07-24 16:31:54 +00:00
var pkt rtp.Packet
err := pkt.Unmarshal(pair.buf)
if err != nil {
r.log(logger.Warn, "unable to decode RTP packet: %v", err)
2021-07-24 16:31:54 +00:00
continue
}
aus, pts, err := aacDecoder.DecodeRTP(&pkt)
2021-04-11 17:05:08 +00:00
if err != nil {
if err != rtpaac.ErrMorePacketsNeeded {
r.log(logger.Warn, "unable to decode audio track: %v", err)
2021-04-11 17:05:08 +00:00
}
continue
}
err = r.muxer.WriteAAC(pts, aus)
if err != nil {
return err
2021-04-11 17:05:08 +00:00
}
}
}
}()
}()
closeCheckTicker := time.NewTicker(closeCheckPeriod)
defer closeCheckTicker.Stop()
for {
select {
case <-closeCheckTicker.C:
t := time.Unix(atomic.LoadInt64(r.lastRequestTime), 0)
if !r.hlsAlwaysRemux && time.Since(t) >= closeAfterInactivity {
r.ringBuffer.Close()
2021-04-11 17:05:08 +00:00
<-writerDone
2021-05-09 15:22:24 +00:00
return nil
2021-04-11 17:05:08 +00:00
}
case err := <-writerDone:
2021-05-09 14:57:26 +00:00
return err
2021-04-11 17:05:08 +00:00
2021-05-10 19:32:59 +00:00
case <-innerCtx.Done():
r.ringBuffer.Close()
2021-05-11 15:20:32 +00:00
<-writerDone
2021-05-09 15:22:24 +00:00
return nil
2021-04-11 17:05:08 +00:00
}
}
}
func (r *hlsRemuxer) runRequestHandler(terminate chan struct{}, done chan struct{}) {
2021-04-11 17:05:08 +00:00
defer close(done)
2021-05-09 14:57:26 +00:00
for {
select {
case <-terminate:
return
case preq := <-r.request:
2021-05-09 14:57:26 +00:00
req := preq
2021-04-11 17:05:08 +00:00
atomic.StoreInt64(r.lastRequestTime, time.Now().Unix())
2021-04-11 17:05:08 +00:00
conf := r.path.Conf()
2021-04-11 17:05:08 +00:00
2021-05-09 14:57:26 +00:00
if conf.ReadIPsParsed != nil {
tmp, _, _ := net.SplitHostPort(req.Req.RemoteAddr)
ip := net.ParseIP(tmp)
if !ipEqualOrInRange(ip, conf.ReadIPsParsed) {
r.log(logger.Info, "ERR: ip '%s' not allowed", ip)
2021-05-09 14:57:26 +00:00
req.W.WriteHeader(http.StatusUnauthorized)
req.Res <- nil
continue
}
2021-04-11 17:05:08 +00:00
}
2021-05-09 14:57:26 +00:00
if conf.ReadUser != "" {
user, pass, ok := req.Req.BasicAuth()
if !ok || user != conf.ReadUser || pass != conf.ReadPass {
req.W.Header().Set("WWW-Authenticate", `Basic realm="rtsp-simple-server"`)
req.W.WriteHeader(http.StatusUnauthorized)
req.Res <- nil
continue
}
2021-04-11 17:05:08 +00:00
}
2021-05-09 14:57:26 +00:00
switch {
2021-07-04 14:03:24 +00:00
case req.File == "stream.m3u8":
r := r.muxer.Playlist()
2021-07-24 16:31:54 +00:00
if r == nil {
req.W.WriteHeader(http.StatusNotFound)
req.Res <- nil
continue
}
2021-07-24 16:31:54 +00:00
req.W.Header().Set("Content-Type", `application/x-mpegURL`)
req.Res <- r
2021-05-09 14:57:26 +00:00
2021-07-04 14:03:24 +00:00
case strings.HasSuffix(req.File, ".ts"):
r := r.muxer.TSFile(req.File)
2021-07-24 16:31:54 +00:00
if r == nil {
2021-04-11 17:05:08 +00:00
req.W.WriteHeader(http.StatusNotFound)
req.Res <- nil
2021-05-09 14:57:26 +00:00
continue
2021-04-11 17:05:08 +00:00
}
2021-07-03 21:52:12 +00:00
req.W.Header().Set("Content-Type", `video/MP2T`)
2021-07-24 16:31:54 +00:00
req.Res <- r
2021-04-11 17:05:08 +00:00
2021-07-04 14:03:24 +00:00
case req.File == "":
2021-05-09 14:57:26 +00:00
req.Res <- bytes.NewReader([]byte(index))
2021-04-11 17:05:08 +00:00
2021-05-09 14:57:26 +00:00
default:
2021-04-11 17:05:08 +00:00
req.W.WriteHeader(http.StatusNotFound)
req.Res <- nil
}
}
}
}
// OnRequest is called by hlsserver.Server (forwarded from ServeHTTP).
func (r *hlsRemuxer) OnRequest(req hlsRemuxerRequest) {
2021-05-10 19:32:59 +00:00
select {
case r.request <- req:
case <-r.ctx.Done():
2021-05-10 19:32:59 +00:00
req.W.WriteHeader(http.StatusNotFound)
req.Res <- nil
}
2021-04-11 17:05:08 +00:00
}
// OnReaderAccepted implements reader.
func (r *hlsRemuxer) OnReaderAccepted() {
r.log(logger.Info, "is remuxing into HLS")
}
// OnReaderFrame implements reader.
func (r *hlsRemuxer) OnReaderFrame(trackID int, streamType gortsplib.StreamType, payload []byte) {
2021-04-11 17:05:08 +00:00
if streamType == gortsplib.StreamTypeRTP {
r.ringBuffer.Push(hlsRemuxerTrackIDPayloadPair{trackID, payload})
2021-04-11 17:05:08 +00:00
}
}