mediamtx/internal/core/hls_muxer.go

560 lines
12 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-10-27 17:49:57 +00:00
"errors"
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/conf"
"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>
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.1.1"></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: true,
2021-08-14 14:30:41 +00:00
});
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-10-17 14:49:49 +00:00
type hlsMuxerResponse struct {
2022-01-14 22:42:41 +00:00
status int
header map[string]string
body io.Reader
2021-10-17 14:49:49 +00:00
}
2021-08-18 13:49:12 +00:00
type hlsMuxerRequest struct {
2022-01-14 22:42:41 +00:00
dir string
file string
req *http.Request
res chan hlsMuxerResponse
}
2021-08-18 13:49:12 +00:00
type hlsMuxerTrackIDPayloadPair struct {
2021-04-11 17:05:08 +00:00
trackID int
packet *rtp.Packet
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
type hlsMuxerPathManager interface {
2021-10-27 19:01:00 +00:00
onReaderSetupPlay(req pathReaderSetupPlayReq) pathReaderSetupPlayRes
2021-08-11 10:45:53 +00:00
}
2021-08-18 13:49:12 +00:00
type hlsMuxerParent interface {
2021-10-27 19:01:00 +00:00
log(logger.Level, string, ...interface{})
onMuxerClose(*hlsMuxer)
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
type hlsMuxer struct {
name string
externalAuthenticationURL string
hlsAlwaysRemux bool
hlsSegmentCount int
hlsSegmentDuration conf.StringDuration
hlsSegmentMaxSize conf.StringSize
readBufferCount int
wg *sync.WaitGroup
pathName string
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-11-06 11:52:12 +00:00
request chan hlsMuxerRequest
hlsServerAPIMuxersList chan hlsServerAPIMuxersListSubReq
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
func newHLSMuxer(
parentCtx context.Context,
2021-11-05 16:14:31 +00:00
name string,
externalAuthenticationURL string,
hlsAlwaysRemux bool,
2021-04-11 17:05:08 +00:00
hlsSegmentCount int,
hlsSegmentDuration conf.StringDuration,
hlsSegmentMaxSize conf.StringSize,
2021-04-11 17:05:08 +00:00
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-11-05 15:55:00 +00:00
m := &hlsMuxer{
name: name,
externalAuthenticationURL: externalAuthenticationURL,
hlsAlwaysRemux: hlsAlwaysRemux,
hlsSegmentCount: hlsSegmentCount,
hlsSegmentDuration: hlsSegmentDuration,
hlsSegmentMaxSize: hlsSegmentMaxSize,
readBufferCount: readBufferCount,
wg: wg,
pathName: pathName,
pathManager: pathManager,
parent: parent,
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-11-06 11:52:12 +00:00
request: make(chan hlsMuxerRequest),
hlsServerAPIMuxersList: make(chan hlsServerAPIMuxersListSubReq),
2021-04-11 17:05:08 +00:00
}
2022-02-19 21:15:37 +00:00
m.log(logger.Info, "created")
2021-04-11 17:05:08 +00:00
2021-11-05 15:55:00 +00:00
m.wg.Add(1)
go m.run()
2021-04-11 17:05:08 +00:00
2021-11-05 15:55:00 +00:00
return m
2021-04-11 17:05:08 +00:00
}
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) close() {
m.ctxCancel()
2021-04-27 11:43:15 +00:00
}
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) log(level logger.Level, format string, args ...interface{}) {
m.parent.log(level, "[muxer %s] "+format, append([]interface{}{m.pathName}, args...)...)
2021-04-11 17:05:08 +00:00
}
// PathName returns the path name.
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) PathName() string {
return m.pathName
2021-04-11 17:05:08 +00:00
}
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) run() {
defer m.wg.Done()
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-11-05 15:55:00 +00:00
innerErr <- m.runInner(innerCtx, innerReady)
2021-05-09 14:57:26 +00:00
}()
isReady := false
2021-05-09 14:57:26 +00:00
2021-10-27 17:49:57 +00:00
err := func() error {
for {
select {
2021-11-05 15:55:00 +00:00
case <-m.ctx.Done():
2021-10-27 17:49:57 +00:00
innerCtxCancel()
<-innerErr
return errors.New("terminated")
2021-11-05 15:55:00 +00:00
case req := <-m.request:
2021-10-27 17:49:57 +00:00
if isReady {
2022-01-14 22:42:41 +00:00
req.res <- m.handleRequest(req)
2021-10-27 17:49:57 +00:00
} else {
2021-11-05 15:55:00 +00:00
m.requests = append(m.requests, req)
2021-10-27 17:49:57 +00:00
}
2021-11-06 11:52:12 +00:00
case req := <-m.hlsServerAPIMuxersList:
2022-01-14 22:42:41 +00:00
req.data.Items[m.name] = hlsServerAPIMuxersListItem{
2021-11-05 16:14:31 +00:00
LastRequest: time.Unix(atomic.LoadInt64(m.lastRequestTime), 0).String(),
}
2022-01-14 22:42:41 +00:00
close(req.res)
2021-11-05 16:14:31 +00:00
2021-10-27 17:49:57 +00:00
case <-innerReady:
isReady = true
2021-11-05 15:55:00 +00:00
for _, req := range m.requests {
2022-01-14 22:42:41 +00:00
req.res <- m.handleRequest(req)
2021-10-27 17:49:57 +00:00
}
2021-11-05 15:55:00 +00:00
m.requests = nil
2021-10-27 17:49:57 +00:00
case err := <-innerErr:
innerCtxCancel()
return err
}
}
2021-10-27 17:49:57 +00:00
}()
2021-05-09 14:57:26 +00:00
2021-11-05 15:55:00 +00:00
m.ctxCancel()
2021-05-09 14:57:26 +00:00
2021-11-05 15:55:00 +00:00
for _, req := range m.requests {
2022-01-14 22:42:41 +00:00
req.res <- hlsMuxerResponse{status: http.StatusNotFound}
}
2021-11-05 15:55:00 +00:00
m.parent.onMuxerClose(m)
2021-10-27 17:49:57 +00:00
2022-02-19 21:15:37 +00:00
m.log(logger.Info, "destroyed (%v)", err)
2021-05-09 14:57:26 +00:00
}
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) runInner(innerCtx context.Context, innerReady chan struct{}) error {
res := m.pathManager.onReaderSetupPlay(pathReaderSetupPlayReq{
2022-01-14 22:42:41 +00:00
author: m,
pathName: m.pathName,
authenticate: nil,
2021-05-09 14:57:26 +00:00
})
2022-01-14 22:42:41 +00:00
if res.err != nil {
return res.err
2021-05-09 14:57:26 +00:00
}
2022-01-14 22:42:41 +00:00
m.path = res.path
defer func() {
2022-01-14 22:42:41 +00:00
m.path.onReaderRemove(pathReaderRemoveReq{author: m})
}()
2022-01-30 16:36:42 +00:00
var videoTrack *gortsplib.TrackH264
videoTrackID := -1
2021-04-11 17:05:08 +00:00
var h264Decoder *rtph264.Decoder
2022-01-30 16:36:42 +00:00
var audioTrack *gortsplib.TrackAAC
audioTrackID := -1
2021-04-11 17:05:08 +00:00
var aacDecoder *rtpaac.Decoder
2022-01-30 16:36:42 +00:00
for i, track := range res.stream.tracks() {
switch tt := track.(type) {
case *gortsplib.TrackH264:
2021-05-09 14:57:26 +00:00
if videoTrack != nil {
2022-01-30 16:36:42 +00:00
return fmt.Errorf("can't encode track %d with HLS: too many tracks", i+1)
2021-05-09 14:57:26 +00:00
}
2022-01-30 16:36:42 +00:00
videoTrack = tt
videoTrackID = i
2022-03-24 11:59:22 +00:00
h264Decoder = &rtph264.Decoder{}
h264Decoder.Init()
2022-01-30 16:36:42 +00:00
case *gortsplib.TrackAAC:
2021-05-09 14:57:26 +00:00
if audioTrack != nil {
2022-01-30 16:36:42 +00:00
return fmt.Errorf("can't encode track %d with HLS: too many tracks", i+1)
2021-04-11 17:05:08 +00:00
}
2022-01-30 16:36:42 +00:00
audioTrack = tt
audioTrackID = i
2022-03-24 11:59:22 +00:00
aacDecoder = &rtpaac.Decoder{SampleRate: track.ClockRate()}
aacDecoder.Init()
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
2021-11-05 15:55:00 +00:00
m.muxer, err = hls.NewMuxer(
m.hlsSegmentCount,
time.Duration(m.hlsSegmentDuration),
uint64(m.hlsSegmentMaxSize),
2021-07-24 16:31:54 +00:00
videoTrack,
audioTrack,
)
if err != nil {
return err
}
2021-11-05 15:55:00 +00:00
defer m.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
2021-11-05 15:55:00 +00:00
m.ringBuffer = ringbuffer.New(uint64(m.readBufferCount))
2021-04-11 17:05:08 +00:00
2022-01-14 22:42:41 +00:00
m.path.onReaderPlay(pathReaderPlayReq{author: m})
2021-04-11 17:05:08 +00:00
writerDone := make(chan error)
go func() {
writerDone <- func() error {
for {
2021-11-05 15:55:00 +00:00
data, ok := m.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 {
nalus, pts, err := h264Decoder.DecodeUntilMarker(pair.packet)
2021-04-11 17:05:08 +00:00
if err != nil {
2021-09-28 13:44:59 +00:00
if err != rtph264.ErrMorePacketsNeeded &&
err != rtph264.ErrNonStartingPacketAndNoPrevious {
2021-11-05 15:55:00 +00:00
m.log(logger.Warn, "unable to decode video track: %v", err)
2021-04-11 17:05:08 +00:00
}
continue
}
2021-11-05 15:55:00 +00:00
err = m.muxer.WriteH264(pts, nalus)
2021-09-28 13:44:59 +00:00
if err != nil {
m.log(logger.Warn, "unable to write segment: %v", err)
continue
2021-04-11 17:05:08 +00:00
}
} else if audioTrack != nil && pair.trackID == audioTrackID {
aus, pts, err := aacDecoder.Decode(pair.packet)
2021-04-11 17:05:08 +00:00
if err != nil {
if err != rtpaac.ErrMorePacketsNeeded {
2021-11-05 15:55:00 +00:00
m.log(logger.Warn, "unable to decode audio track: %v", err)
2021-04-11 17:05:08 +00:00
}
continue
}
2021-11-05 15:55:00 +00:00
err = m.muxer.WriteAAC(pts, aus)
if err != nil {
m.log(logger.Warn, "unable to write segment: %v", err)
continue
2021-04-11 17:05:08 +00:00
}
}
}
}()
}()
closeCheckTicker := time.NewTicker(closeCheckPeriod)
defer closeCheckTicker.Stop()
for {
select {
case <-closeCheckTicker.C:
2021-11-05 15:55:00 +00:00
t := time.Unix(atomic.LoadInt64(m.lastRequestTime), 0)
if !m.hlsAlwaysRemux && time.Since(t) >= closeAfterInactivity {
m.ringBuffer.Close()
2021-04-11 17:05:08 +00:00
<-writerDone
return fmt.Errorf("not used anymore")
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():
2021-11-05 15:55:00 +00:00
m.ringBuffer.Close()
2021-05-11 15:20:32 +00:00
<-writerDone
return fmt.Errorf("terminated")
2021-04-11 17:05:08 +00:00
}
}
}
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) handleRequest(req hlsMuxerRequest) hlsMuxerResponse {
atomic.StoreInt64(m.lastRequestTime, time.Now().Unix())
2021-04-11 17:05:08 +00:00
2022-01-14 22:42:41 +00:00
err := m.authenticate(req.req)
if err != nil {
if terr, ok := err.(pathErrAuthCritical); ok {
2022-01-14 22:42:41 +00:00
m.log(logger.Info, "authentication error: %s", terr.message)
2021-10-17 14:49:49 +00:00
return hlsMuxerResponse{
2022-01-14 22:42:41 +00:00
status: http.StatusUnauthorized,
2021-10-17 14:49:49 +00:00
}
}
return hlsMuxerResponse{
2022-01-14 22:42:41 +00:00
status: http.StatusUnauthorized,
header: map[string]string{
"WWW-Authenticate": `Basic realm="rtsp-simple-server"`,
},
}
}
2021-04-11 17:05:08 +00:00
switch {
2022-01-14 22:42:41 +00:00
case req.file == "index.m3u8":
2021-10-17 14:49:49 +00:00
return hlsMuxerResponse{
2022-01-14 22:42:41 +00:00
status: http.StatusOK,
header: map[string]string{
2021-10-17 14:49:49 +00:00
"Content-Type": `application/x-mpegURL`,
},
2022-01-14 22:42:41 +00:00
body: m.muxer.PrimaryPlaylist(),
2021-10-17 14:49:49 +00:00
}
2021-08-16 16:07:10 +00:00
2022-01-14 22:42:41 +00:00
case req.file == "stream.m3u8":
2021-10-17 14:49:49 +00:00
return hlsMuxerResponse{
2022-01-14 22:42:41 +00:00
status: http.StatusOK,
header: map[string]string{
2021-10-17 14:49:49 +00:00
"Content-Type": `application/x-mpegURL`,
},
2022-01-14 22:42:41 +00:00
body: m.muxer.StreamPlaylist(),
2021-10-17 14:49:49 +00:00
}
2021-05-09 14:57:26 +00:00
2022-01-14 22:42:41 +00:00
case strings.HasSuffix(req.file, ".ts"):
r := m.muxer.Segment(req.file)
if r == nil {
2022-01-14 22:42:41 +00:00
return hlsMuxerResponse{status: http.StatusNotFound}
}
2021-04-11 17:05:08 +00:00
2021-10-17 14:49:49 +00:00
return hlsMuxerResponse{
2022-01-14 22:42:41 +00:00
status: http.StatusOK,
header: map[string]string{
2021-10-17 14:49:49 +00:00
"Content-Type": `video/MP2T`,
},
2022-01-14 22:42:41 +00:00
body: r,
2021-10-17 14:49:49 +00:00
}
2021-04-11 17:05:08 +00:00
2022-01-14 22:42:41 +00:00
case req.file == "":
2021-10-17 14:49:49 +00:00
return hlsMuxerResponse{
2022-01-14 22:42:41 +00:00
status: http.StatusOK,
header: map[string]string{
2021-10-17 14:49:49 +00:00
"Content-Type": `text/html`,
},
2022-01-14 22:42:41 +00:00
body: bytes.NewReader([]byte(index)),
2021-10-17 14:49:49 +00:00
}
2021-04-11 17:05:08 +00:00
default:
2022-01-14 22:42:41 +00:00
return hlsMuxerResponse{status: http.StatusNotFound}
2021-04-11 17:05:08 +00:00
}
}
func (m *hlsMuxer) authenticate(req *http.Request) error {
pathConf := m.path.Conf()
pathIPs := pathConf.ReadIPs
pathUser := pathConf.ReadUser
pathPass := pathConf.ReadPass
if m.externalAuthenticationURL != "" {
tmp, _, _ := net.SplitHostPort(req.RemoteAddr)
ip := net.ParseIP(tmp)
user, pass, _ := req.BasicAuth()
err := externalAuth(
m.externalAuthenticationURL,
ip.String(),
user,
pass,
m.pathName,
"read",
req.URL.RawQuery)
if err != nil {
return pathErrAuthCritical{
2022-01-14 22:42:41 +00:00
message: fmt.Sprintf("external authentication failed: %s", err),
}
}
}
if pathIPs != nil {
tmp, _, _ := net.SplitHostPort(req.RemoteAddr)
ip := net.ParseIP(tmp)
if !ipEqualOrInRange(ip, pathIPs) {
return pathErrAuthCritical{
2022-01-14 22:42:41 +00:00
message: fmt.Sprintf("IP '%s' not allowed", ip),
}
}
}
if pathUser != "" {
user, pass, ok := req.BasicAuth()
if !ok {
return pathErrAuthNotCritical{}
}
if user != string(pathUser) || pass != string(pathPass) {
return pathErrAuthCritical{
2022-01-14 22:42:41 +00:00
message: "invalid credentials",
}
}
}
return nil
}
2021-10-27 19:01:00 +00:00
// onRequest is called by hlsserver.Server (forwarded from ServeHTTP).
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) onRequest(req hlsMuxerRequest) {
2021-05-10 19:32:59 +00:00
select {
2021-11-05 15:55:00 +00:00
case m.request <- req:
case <-m.ctx.Done():
2022-01-14 22:42:41 +00:00
req.res <- hlsMuxerResponse{status: http.StatusNotFound}
2021-05-10 19:32:59 +00:00
}
2021-04-11 17:05:08 +00:00
}
2021-10-27 19:01:00 +00:00
// onReaderAccepted implements reader.
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) onReaderAccepted() {
m.log(logger.Info, "is converting into HLS")
}
2021-11-12 21:29:56 +00:00
// onReaderPacketRTP implements reader.
func (m *hlsMuxer) onReaderPacketRTP(trackID int, pkt *rtp.Packet) {
m.ringBuffer.Push(hlsMuxerTrackIDPayloadPair{trackID, pkt})
2021-11-12 21:29:56 +00:00
}
2021-10-27 19:01:00 +00:00
// onReaderAPIDescribe implements reader.
2021-11-05 15:55:00 +00:00
func (m *hlsMuxer) onReaderAPIDescribe() interface{} {
return struct {
Type string `json:"type"`
2021-08-18 13:49:12 +00:00
}{"hlsMuxer"}
}
2021-11-05 16:14:31 +00:00
// onAPIHLSMuxersList is called by api.
2021-11-06 11:52:12 +00:00
func (m *hlsMuxer) onAPIHLSMuxersList(req hlsServerAPIMuxersListSubReq) {
2022-01-14 22:42:41 +00:00
req.res = make(chan struct{})
2021-11-05 16:14:31 +00:00
select {
2021-11-06 11:52:12 +00:00
case m.hlsServerAPIMuxersList <- req:
2022-01-14 22:42:41 +00:00
<-req.res
2021-11-05 16:14:31 +00:00
case <-m.ctx.Done():
}
}