mediamtx/internal/core/hls_muxer.go

491 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/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>
2021-08-23 10:33:09 +00:00
html, body {
margin: 0;
padding: 0;
height: 100%;
}
2021-04-11 17:05:08 +00:00
#video {
width: 100%;
height: 100%;
2021-04-11 17:05:08 +00:00
background: black;
}
</style>
</head>
<body>
2021-08-23 10:33:09 +00:00
<video id="video" muted controls autoplay></video>
2021-04-11 17:05:08 +00:00
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.0.0"></script>
2021-04-11 17:05:08 +00:00
<script>
const create = () => {
const video = document.getElementById('video');
2021-08-14 14:30:41 +00:00
if (video.canPlayType('application/vnd.apple.mpegurl')) {
// since it's not possible to detect timeout errors in iOS,
// wait for the playlist to be available before starting the stream
fetch('stream.m3u8')
.then(() => {
video.src = 'index.m3u8';
video.play();
});
2021-08-14 14:30:41 +00:00
} else {
const hls = new Hls({
progressive: false,
});
hls.on(Hls.Events.ERROR, (evt, data) => {
if (data.fatal) {
hls.destroy();
setTimeout(create, 2000);
2021-08-14 14:30:41 +00:00
}
});
2021-08-16 16:07:10 +00:00
hls.loadSource('index.m3u8');
2021-08-14 14:30:41 +00:00
hls.attachMedia(video);
video.play();
}
};
window.addEventListener('DOMContentLoaded', create);
2021-04-11 17:05:08 +00:00
</script>
</body>
</html>
`
2021-08-18 13:49:12 +00:00
type hlsMuxerRequest struct {
2021-07-04 14:03:24 +00:00
Dir string
File string
Req *http.Request
W http.ResponseWriter
Res chan io.Reader
}
2021-08-18 13:49:12 +00:00
type hlsMuxerTrackIDPayloadPair struct {
2021-04-11 17:05:08 +00:00
trackID int
buf []byte
}
2021-08-18 13:49:12 +00:00
type hlsMuxerPathManager interface {
2021-08-11 10:45:53 +00:00
OnReaderSetupPlay(req pathReaderSetupPlayReq) pathReaderSetupPlayRes
}
2021-08-18 13:49:12 +00:00
type hlsMuxerParent interface {
2021-04-11 17:05:08 +00:00
Log(logger.Level, string, ...interface{})
2021-08-18 13:49:12 +00:00
OnMuxerClose(*hlsMuxer)
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
type hlsMuxer struct {
hlsAlwaysRemux bool
2021-04-11 17:05:08 +00:00
hlsSegmentCount int
hlsSegmentDuration time.Duration
readBufferCount int
wg *sync.WaitGroup
pathName string
2021-08-18 13:49:12 +00:00
pathManager hlsMuxerPathManager
parent hlsMuxerParent
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-08-18 13:49:12 +00:00
requests []hlsMuxerRequest
2021-04-11 17:05:08 +00:00
// in
2021-08-18 13:49:12 +00:00
request chan hlsMuxerRequest
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
func newHLSMuxer(
parentCtx context.Context,
hlsAlwaysRemux bool,
2021-04-11 17:05:08 +00:00
hlsSegmentCount int,
hlsSegmentDuration time.Duration,
readBufferCount int,
wg *sync.WaitGroup,
pathName string,
2021-08-18 13:49:12 +00:00
pathManager hlsMuxerPathManager,
parent hlsMuxerParent) *hlsMuxer {
ctx, ctxCancel := context.WithCancel(parentCtx)
2021-05-10 19:32:59 +00:00
2021-08-18 13:49:12 +00:00
r := &hlsMuxer{
hlsAlwaysRemux: hlsAlwaysRemux,
2021-04-11 17:05:08 +00:00
hlsSegmentCount: hlsSegmentCount,
hlsSegmentDuration: hlsSegmentDuration,
readBufferCount: readBufferCount,
wg: wg,
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-08-18 13:49:12 +00:00
request: make(chan hlsMuxerRequest),
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-08-18 13:49:12 +00:00
func (r *hlsMuxer) Close() {
r.ctxCancel()
2021-04-27 11:43:15 +00:00
}
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) log(level logger.Level, format string, args ...interface{}) {
r.parent.Log(level, "[muxer %s] "+format, append([]interface{}{r.pathName}, args...)...)
2021-04-11 17:05:08 +00:00
}
// PathName returns the path name.
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) PathName() string {
return r.pathName
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) run() {
defer r.wg.Done()
defer r.log(logger.Info, "destroyed")
2021-04-11 17:05:08 +00:00
2021-08-18 13:49:12 +00:00
innerCtx, innerCtxCancel := context.WithCancel(context.Background())
innerReady := make(chan struct{})
innerErr := make(chan error)
2021-05-09 14:57:26 +00:00
go func() {
2021-08-18 13:49:12 +00:00
innerErr <- r.runInner(innerCtx, innerReady)
2021-05-09 14:57:26 +00:00
}()
isReady := false
2021-05-09 14:57:26 +00:00
outer:
for {
select {
case <-r.ctx.Done():
2021-08-18 13:49:12 +00:00
innerCtxCancel()
<-innerErr
break outer
case req := <-r.request:
if isReady {
r.handleRequest(req)
} else {
r.requests = append(r.requests, req)
}
2021-08-18 13:49:12 +00:00
case <-innerReady:
isReady = true
for _, req := range r.requests {
r.handleRequest(req)
}
r.requests = nil
2021-08-18 13:49:12 +00:00
case err := <-innerErr:
innerCtxCancel()
if err != nil {
r.log(logger.Info, "ERR: %s", err)
}
break outer
}
2021-05-09 14:57:26 +00:00
}
r.ctxCancel()
2021-05-09 14:57:26 +00:00
for _, req := range r.requests {
req.W.WriteHeader(http.StatusNotFound)
req.Res <- nil
}
2021-08-18 13:49:12 +00:00
r.parent.OnMuxerClose(r)
2021-05-09 14:57:26 +00:00
}
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) runInner(innerCtx context.Context, innerReady chan struct{}) 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 h264Decoder *rtph264.Decoder
var audioTrack *gortsplib.Track
audioTrackID := -1
2021-04-11 17:05:08 +00:00
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
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-08-25 17:51:59 +00:00
conf, err := t.ExtractConfigAAC()
2021-05-09 14:57:26 +00:00
if err != nil {
return err
}
2021-04-11 17:05:08 +00:00
2021-08-25 17:51:59 +00:00
aacDecoder = rtpaac.NewDecoder(conf.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("the stream doesn't contain an H264 track or an AAC 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-08-18 13:49:12 +00:00
innerReady <- struct{}{}
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-08-18 13:49:12 +00:00
pair := data.(hlsMuxerTrackIDPayloadPair)
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
}
videoBuf = append(videoBuf, nalus...)
2021-04-11 17:05:08 +00:00
// 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-08-18 13:49:12 +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
}
}
}
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) handleRequest(req hlsMuxerRequest) {
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
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)
req.W.WriteHeader(http.StatusUnauthorized)
req.Res <- nil
return
}
}
2021-04-11 17:05:08 +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
return
}
}
2021-04-11 17:05:08 +00:00
switch {
2021-08-16 16:07:10 +00:00
case req.File == "index.m3u8":
req.W.Header().Set("Content-Type", `application/x-mpegURL`)
req.Res <- r.muxer.PrimaryPlaylist()
case req.File == "stream.m3u8":
req.W.Header().Set("Content-Type", `application/x-mpegURL`)
2021-08-16 16:07:10 +00:00
req.Res <- r.muxer.StreamPlaylist()
2021-05-09 14:57:26 +00:00
case strings.HasSuffix(req.File, ".ts"):
r := r.muxer.Segment(req.File)
if r == nil {
req.W.WriteHeader(http.StatusNotFound)
req.Res <- nil
return
}
2021-04-11 17:05:08 +00:00
req.W.Header().Set("Content-Type", `video/MP2T`)
req.Res <- r
2021-04-11 17:05:08 +00:00
case req.File == "":
req.Res <- bytes.NewReader([]byte(index))
2021-04-11 17:05:08 +00:00
default:
req.W.WriteHeader(http.StatusNotFound)
req.Res <- nil
2021-04-11 17:05:08 +00:00
}
}
// OnRequest is called by hlsserver.Server (forwarded from ServeHTTP).
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) OnRequest(req hlsMuxerRequest) {
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.
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) OnReaderAccepted() {
r.log(logger.Info, "is converting into HLS")
}
// OnReaderFrame implements reader.
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) OnReaderFrame(trackID int, streamType gortsplib.StreamType, payload []byte) {
2021-04-11 17:05:08 +00:00
if streamType == gortsplib.StreamTypeRTP {
2021-08-18 13:49:12 +00:00
r.ringBuffer.Push(hlsMuxerTrackIDPayloadPair{trackID, payload})
2021-04-11 17:05:08 +00:00
}
}
// OnReaderAPIDescribe implements reader.
2021-08-18 13:49:12 +00:00
func (r *hlsMuxer) OnReaderAPIDescribe() interface{} {
return struct {
Type string `json:"type"`
2021-08-18 13:49:12 +00:00
}{"hlsMuxer"}
}