mediamtx/internal/core/hls_muxer.go

655 lines
14 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"
2022-12-15 23:50:47 +00:00
_ "embed"
2021-10-27 17:49:57 +00:00
"errors"
2021-04-11 17:05:08 +00:00
"fmt"
2023-03-12 12:22:57 +00:00
"io"
2021-04-11 17:05:08 +00:00
"net"
"net/http"
"os"
"path/filepath"
2021-04-11 17:05:08 +00:00
"sync"
"sync/atomic"
"time"
2022-12-28 19:32:03 +00:00
"github.com/aler9/gortsplib/v2/pkg/codecs/mpeg4audio"
"github.com/aler9/gortsplib/v2/pkg/format"
"github.com/aler9/gortsplib/v2/pkg/media"
"github.com/aler9/gortsplib/v2/pkg/ringbuffer"
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
"github.com/gin-gonic/gin"
2021-04-11 17:05:08 +00:00
"github.com/aler9/rtsp-simple-server/internal/conf"
"github.com/aler9/rtsp-simple-server/internal/formatprocessor"
2021-04-11 17:05:08 +00:00
"github.com/aler9/rtsp-simple-server/internal/logger"
"github.com/bluenviron/gohlslib"
2021-04-11 17:05:08 +00:00
)
const (
closeCheckPeriod = 1 * time.Second
closeAfterInactivity = 60 * time.Second
hlsMuxerRecreatePause = 10 * time.Second
2021-04-11 17:05:08 +00:00
)
2022-12-15 23:50:47 +00:00
//go:embed hls_index.html
var hlsIndex []byte
2021-04-11 17:05:08 +00:00
type hlsMuxerResponse struct {
muxer *hlsMuxer
2023-03-12 15:59:04 +00:00
cb func() *gohlslib.MuxerFileResponse
}
2021-08-18 13:49:12 +00:00
type hlsMuxerRequest struct {
2023-01-08 20:16:20 +00:00
path string
2022-01-14 22:42:41 +00:00
file string
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
ctx *gin.Context
2023-01-08 20:16:20 +00:00
res chan *hlsMuxerResponse
}
2021-08-18 13:49:12 +00:00
type hlsMuxerPathManager interface {
readerAdd(req pathReaderAddReq) 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{})
muxerClose(*hlsMuxer)
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
type hlsMuxer struct {
remoteAddr string
externalAuthenticationURL string
alwaysRemux bool
variant conf.HLSVariant
segmentCount int
segmentDuration conf.StringDuration
partDuration conf.StringDuration
segmentMaxSize conf.StringSize
directory string
readBufferCount int
wg *sync.WaitGroup
pathName string
pathManager hlsMuxerPathManager
parent hlsMuxerParent
2021-07-24 16:31:54 +00:00
ctx context.Context
ctxCancel func()
created time.Time
2021-07-31 16:25:47 +00:00
path *path
2021-07-24 16:31:54 +00:00
ringBuffer *ringbuffer.RingBuffer
lastRequestTime *int64
2023-03-12 15:59:04 +00:00
muxer *gohlslib.Muxer
requests []*hlsMuxerRequest
bytesSent *uint64
2021-04-11 17:05:08 +00:00
// in
chRequest chan *hlsMuxerRequest
chAPIHLSMuxersList chan hlsServerAPIMuxersListSubReq
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
func newHLSMuxer(
parentCtx context.Context,
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
remoteAddr string,
externalAuthenticationURL string,
alwaysRemux bool,
variant conf.HLSVariant,
segmentCount int,
segmentDuration conf.StringDuration,
partDuration conf.StringDuration,
segmentMaxSize conf.StringSize,
directory string,
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,
2022-04-07 10:50:35 +00:00
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{
remoteAddr: remoteAddr,
externalAuthenticationURL: externalAuthenticationURL,
alwaysRemux: alwaysRemux,
variant: variant,
segmentCount: segmentCount,
segmentDuration: segmentDuration,
partDuration: partDuration,
segmentMaxSize: segmentMaxSize,
directory: directory,
readBufferCount: readBufferCount,
wg: wg,
pathName: pathName,
pathManager: pathManager,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
created: time.Now(),
2021-07-24 16:31:54 +00:00
lastRequestTime: func() *int64 {
v := time.Now().UnixNano()
2021-07-03 10:19:03 +00:00
return &v
}(),
bytesSent: new(uint64),
2023-01-08 20:57:15 +00:00
chRequest: make(chan *hlsMuxerRequest),
chAPIHLSMuxersList: make(chan hlsServerAPIMuxersListSubReq),
2021-04-11 17:05:08 +00:00
}
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
m.log(logger.Info, "created %s", func() string {
if remoteAddr == "" {
return "automatically"
}
return "(requested by " + remoteAddr + ")"
}())
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
err := func() error {
var innerReady chan struct{}
var innerErr chan error
var innerCtx context.Context
var innerCtxCancel func()
createInner := func() {
innerReady = make(chan struct{})
innerErr = make(chan error)
innerCtx, innerCtxCancel = context.WithCancel(context.Background())
go func() {
innerErr <- m.runInner(innerCtx, innerReady)
}()
}
2021-05-09 14:57:26 +00:00
createInner()
isReady := false
isRecreating := false
recreateTimer := newEmptyTimer()
2021-05-09 14:57:26 +00:00
2021-10-27 17:49:57 +00:00
for {
select {
2021-11-05 15:55:00 +00:00
case <-m.ctx.Done():
if !isRecreating {
innerCtxCancel()
<-innerErr
}
2021-10-27 17:49:57 +00:00
return errors.New("terminated")
case req := <-m.chRequest:
2023-01-08 20:16:20 +00:00
switch {
case isRecreating:
req.res <- nil
case isReady:
req.res <- &hlsMuxerResponse{
muxer: m,
cb: m.handleRequest(req),
}
2023-01-08 20:16:20 +00:00
default:
2021-11-05 15:55:00 +00:00
m.requests = append(m.requests, req)
2021-10-27 17:49:57 +00:00
}
case req := <-m.chAPIHLSMuxersList:
req.data.Items[m.pathName] = hlsServerAPIMuxersListItem{
Created: m.created,
LastRequest: time.Unix(0, atomic.LoadInt64(m.lastRequestTime)),
BytesSent: atomic.LoadUint64(m.bytesSent),
2021-11-05 16:14:31 +00:00
}
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 {
2023-01-08 20:16:20 +00:00
req.res <- &hlsMuxerResponse{
muxer: m,
cb: 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()
if m.alwaysRemux {
m.log(logger.Info, "ERR: %v", err)
m.clearQueuedRequests()
isReady = false
isRecreating = true
recreateTimer = time.NewTimer(hlsMuxerRecreatePause)
} else {
return err
}
case <-recreateTimer.C:
isRecreating = false
createInner()
}
}
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
m.clearQueuedRequests()
m.parent.muxerClose(m)
m.log(logger.Info, "destroyed (%v)", err)
}
func (m *hlsMuxer) clearQueuedRequests() {
2021-11-05 15:55:00 +00:00
for _, req := range m.requests {
2023-01-08 20:16:20 +00:00
req.res <- nil
}
2023-01-08 20:16:20 +00:00
m.requests = nil
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.readerAdd(pathReaderAddReq{
2022-12-15 23:50:47 +00:00
author: m,
pathName: m.pathName,
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() {
m.path.readerRemove(pathReaderRemoveReq{author: m})
}()
2022-07-05 21:45:57 +00:00
m.ringBuffer, _ = ringbuffer.New(uint64(m.readBufferCount))
2021-04-11 17:05:08 +00:00
var medias media.Medias
2021-04-11 17:05:08 +00:00
videoMedia, videoFormat := m.setupVideoMedia(res.stream)
if videoMedia != nil {
medias = append(medias, videoMedia)
}
audioMedia, audioFormat := m.setupAudioMedia(res.stream)
if audioMedia != nil {
medias = append(medias, audioMedia)
}
defer res.stream.readerRemove(m)
if medias == nil {
return fmt.Errorf(
"the stream doesn't contain any supported codec (which are currently H264, H265, MPEG4-Audio, Opus)")
}
var muxerDirectory string
if m.directory != "" {
muxerDirectory = filepath.Join(m.directory, m.pathName)
os.MkdirAll(muxerDirectory, 0o755)
defer os.Remove(muxerDirectory)
}
2023-03-12 15:59:04 +00:00
m.muxer = &gohlslib.Muxer{
Variant: gohlslib.MuxerVariant(m.variant),
SegmentCount: m.segmentCount,
SegmentDuration: time.Duration(m.segmentDuration),
PartDuration: time.Duration(m.partDuration),
SegmentMaxSize: uint64(m.segmentMaxSize),
VideoTrack: videoFormat,
AudioTrack: audioFormat,
Directory: muxerDirectory,
2023-03-12 15:59:04 +00:00
}
err := m.muxer.Start()
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
defer m.muxer.Close()
innerReady <- struct{}{}
m.log(logger.Info, "is converting into HLS, %s",
sourceMediaInfo(medias))
writerDone := make(chan error)
go func() {
writerDone <- m.runWriter()
}()
closeCheckTicker := time.NewTicker(closeCheckPeriod)
defer closeCheckTicker.Stop()
for {
select {
case <-closeCheckTicker.C:
if m.remoteAddr != "" {
t := time.Unix(0, atomic.LoadInt64(m.lastRequestTime))
if time.Since(t) >= closeAfterInactivity {
m.ringBuffer.Close()
<-writerDone
return fmt.Errorf("not used anymore")
}
}
case err := <-writerDone:
return err
case <-innerCtx.Done():
m.ringBuffer.Close()
<-writerDone
return fmt.Errorf("terminated")
}
}
}
func (m *hlsMuxer) setupVideoMedia(stream *stream) (*media.Media, format.Format) {
var videoFormatH265 *format.H265
videoMedia := stream.medias().FindFormat(&videoFormatH265)
if videoFormatH265 != nil {
2022-12-27 17:01:58 +00:00
videoStartPTSFilled := false
var videoStartPTS time.Duration
2023-03-10 11:44:59 +00:00
stream.readerAdd(m, videoMedia, videoFormatH265, func(unit formatprocessor.Unit) {
2022-12-27 17:01:58 +00:00
m.ringBuffer.Push(func() error {
2023-03-10 11:44:59 +00:00
tunit := unit.(*formatprocessor.UnitH265)
2022-12-27 17:01:58 +00:00
2023-03-10 11:44:59 +00:00
if tunit.AU == nil {
2022-12-27 17:01:58 +00:00
return nil
}
if !videoStartPTSFilled {
videoStartPTSFilled = true
2023-03-10 11:44:59 +00:00
videoStartPTS = tunit.PTS
2022-12-27 17:01:58 +00:00
}
2023-03-10 11:44:59 +00:00
pts := tunit.PTS - videoStartPTS
2022-12-27 17:01:58 +00:00
2023-03-10 11:44:59 +00:00
err := m.muxer.WriteH26x(tunit.NTP, pts, tunit.AU)
2022-12-27 17:01:58 +00:00
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
return videoMedia, videoFormatH265
}
var videoFormatH264 *format.H264
videoMedia = stream.medias().FindFormat(&videoFormatH264)
if videoFormatH264 != nil {
videoStartPTSFilled := false
var videoStartPTS time.Duration
2023-03-10 11:44:59 +00:00
stream.readerAdd(m, videoMedia, videoFormatH264, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
2023-03-10 11:44:59 +00:00
tunit := unit.(*formatprocessor.UnitH264)
2023-03-10 11:44:59 +00:00
if tunit.AU == nil {
return nil
}
if !videoStartPTSFilled {
videoStartPTSFilled = true
2023-03-10 11:44:59 +00:00
videoStartPTS = tunit.PTS
}
2023-03-10 11:44:59 +00:00
pts := tunit.PTS - videoStartPTS
2023-03-10 11:44:59 +00:00
err := m.muxer.WriteH26x(tunit.NTP, pts, tunit.AU)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
return videoMedia, videoFormatH264
}
2022-12-27 17:01:58 +00:00
return nil, nil
}
func (m *hlsMuxer) setupAudioMedia(stream *stream) (*media.Media, format.Format) {
var audioFormatMPEG4Audio *format.MPEG4Audio
audioMedia := stream.medias().FindFormat(&audioFormatMPEG4Audio)
if audioFormatMPEG4Audio != nil {
2022-12-27 17:01:58 +00:00
audioStartPTSFilled := false
var audioStartPTS time.Duration
2023-03-10 11:44:59 +00:00
stream.readerAdd(m, audioMedia, audioFormatMPEG4Audio, func(unit formatprocessor.Unit) {
2022-12-27 17:01:58 +00:00
m.ringBuffer.Push(func() error {
2023-03-10 11:44:59 +00:00
tunit := unit.(*formatprocessor.UnitMPEG4Audio)
2022-12-27 17:01:58 +00:00
2023-03-10 11:44:59 +00:00
if tunit.AUs == nil {
2022-12-27 17:01:58 +00:00
return nil
}
if !audioStartPTSFilled {
audioStartPTSFilled = true
2023-03-10 11:44:59 +00:00
audioStartPTS = tunit.PTS
2022-12-27 17:01:58 +00:00
}
2023-03-10 11:44:59 +00:00
pts := tunit.PTS - audioStartPTS
2022-12-27 17:01:58 +00:00
2023-03-10 11:44:59 +00:00
for i, au := range tunit.AUs {
err := m.muxer.WriteAudio(
2023-03-10 11:44:59 +00:00
tunit.NTP,
2022-12-27 17:01:58 +00:00
pts+time.Duration(i)*mpeg4audio.SamplesPerAccessUnit*
time.Second/time.Duration(audioFormatMPEG4Audio.ClockRate()),
2022-12-27 17:01:58 +00:00
au)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
}
return nil
})
})
return audioMedia, audioFormatMPEG4Audio
}
var audioFormatOpus *format.Opus
audioMedia = stream.medias().FindFormat(&audioFormatOpus)
if audioFormatOpus != nil {
audioStartPTSFilled := false
var audioStartPTS time.Duration
2022-08-15 11:50:03 +00:00
2023-03-10 11:44:59 +00:00
stream.readerAdd(m, audioMedia, audioFormatOpus, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
2023-03-10 11:44:59 +00:00
tunit := unit.(*formatprocessor.UnitOpus)
2021-04-11 17:05:08 +00:00
if !audioStartPTSFilled {
audioStartPTSFilled = true
2023-03-10 11:44:59 +00:00
audioStartPTS = tunit.PTS
}
2023-03-10 11:44:59 +00:00
pts := tunit.PTS - audioStartPTS
2021-04-11 17:05:08 +00:00
err := m.muxer.WriteAudio(
2023-03-10 11:44:59 +00:00
tunit.NTP,
pts,
2023-03-10 11:44:59 +00:00
tunit.Frame)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
2021-04-11 17:05:08 +00:00
return nil
})
})
2021-04-11 17:05:08 +00:00
return audioMedia, audioFormatOpus
2021-04-11 17:05:08 +00:00
}
return nil, nil
2021-04-11 17:05:08 +00:00
}
2022-12-27 17:01:58 +00:00
func (m *hlsMuxer) runWriter() error {
for {
item, ok := m.ringBuffer.Pull()
if !ok {
return fmt.Errorf("terminated")
}
2022-12-27 17:01:58 +00:00
err := item.(func() error)()
if err != nil {
return err
}
}
}
2023-03-12 15:59:04 +00:00
func (m *hlsMuxer) handleRequest(req *hlsMuxerRequest) func() *gohlslib.MuxerFileResponse {
atomic.StoreInt64(m.lastRequestTime, time.Now().UnixNano())
2021-04-11 17:05:08 +00:00
err := m.authenticate(req.ctx)
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)
2023-03-12 15:59:04 +00:00
return func() *gohlslib.MuxerFileResponse {
return &gohlslib.MuxerFileResponse{
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
Status: http.StatusUnauthorized,
Header: map[string]string{
"WWW-Authenticate": `Basic realm="rtsp-simple-server"`,
},
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
}
2021-10-17 14:49:49 +00:00
}
}
2023-03-12 15:59:04 +00:00
return func() *gohlslib.MuxerFileResponse {
return &gohlslib.MuxerFileResponse{
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
Status: http.StatusUnauthorized,
Header: map[string]string{
"WWW-Authenticate": `Basic realm="rtsp-simple-server"`,
},
}
}
}
2021-04-11 17:05:08 +00:00
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
if req.file == "" {
2023-03-12 15:59:04 +00:00
return func() *gohlslib.MuxerFileResponse {
return &gohlslib.MuxerFileResponse{
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
Status: http.StatusOK,
Header: map[string]string{
"Content-Type": `text/html`,
},
2023-03-12 12:22:57 +00:00
Body: io.NopCloser(bytes.NewReader(hlsIndex)),
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
}
2021-10-17 14:49:49 +00:00
}
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
}
2021-04-11 17:05:08 +00:00
2023-03-12 15:59:04 +00:00
return func() *gohlslib.MuxerFileResponse {
Implement Low-Latency HLS (#938) * add hlsVariant parameter * hls: split muxer into variants * hls: implement fmp4 segments * hls muxer: implement low latency mode * hls muxer: support audio with fmp4 mode * hls muxer: rewrite file router * hls muxer: implement preload hint * hls muxer: add various error codes * hls muxer: use explicit flags * hls muxer: fix error in aac pts * hls muxer: fix sudden freezes with video+audio * hls muxer: skip empty parts * hls muxer: fix video FPS * hls muxer: add parameter hlsPartDuration * hls muxer: refactor fmp4 muxer * hls muxer: fix CAN-SKIP-UNTIL * hls muxer: refactor code * hls muxer: show only parts of last 2 segments * hls muxer: implementa playlist delta updates * hls muxer: change playlist content type * hls muxer: improve video dts precision * hls muxer: fix video sample flags * hls muxer: improve iphone audio support * hls muxer: improve mp4 timestamp precision * hls muxer: add offset between pts and dts * hls muxer: close muxer in case of error * hls muxer: stop logging requests with the info level * hls muxer: rename entry into sample * hls muxer: compensate video dts error over time * hls muxer: change default segment count * hls muxer: add starting gap * hls muxer: set default part duration to 200ms * hls muxer: fix audio-only streams on ios * hls muxer: add playsinline attribute to video tag of default web page * hls muxer: keep mpegts as the default hls variant * hls muxer: implement encryption * hls muxer: rewrite dts estimation * hls muxer: improve DTS precision * hls muxer: use right SPS/PPS for each sample * hls muxer: adjust part duration dynamically * add comments * update readme * hls muxer: fix memory leak * hls muxer: decrease ram consumption
2022-05-31 17:17:26 +00:00
return m.muxer.File(
req.file,
req.ctx.Query("_HLS_msn"),
req.ctx.Query("_HLS_part"),
req.ctx.Query("_HLS_skip"))
2021-04-11 17:05:08 +00:00
}
}
func (m *hlsMuxer) authenticate(ctx *gin.Context) error {
pathConf := m.path.safeConf()
pathIPs := pathConf.ReadIPs
pathUser := pathConf.ReadUser
pathPass := pathConf.ReadPass
if m.externalAuthenticationURL != "" {
ip := net.ParseIP(ctx.ClientIP())
user, pass, ok := ctx.Request.BasicAuth()
err := externalAuth(
m.externalAuthenticationURL,
ip.String(),
user,
pass,
m.pathName,
externalAuthProtoHLS,
nil,
2022-08-22 09:24:21 +00:00
false,
ctx.Request.URL.RawQuery)
if err != nil {
if !ok {
return pathErrAuthNotCritical{}
}
return pathErrAuthCritical{
2022-01-14 22:42:41 +00:00
message: fmt.Sprintf("external authentication failed: %s", err),
}
}
}
if pathIPs != nil {
ip := net.ParseIP(ctx.ClientIP())
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 := ctx.Request.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
}
func (m *hlsMuxer) addSentBytes(n uint64) {
atomic.AddUint64(m.bytesSent, n)
}
2023-01-08 20:16:20 +00:00
// processRequest is called by hlsserver.Server (forwarded from ServeHTTP).
func (m *hlsMuxer) processRequest(req *hlsMuxerRequest) {
2021-05-10 19:32:59 +00:00
select {
case m.chRequest <- req:
2021-11-05 15:55:00 +00:00
case <-m.ctx.Done():
2023-01-08 20:16:20 +00:00
req.res <- nil
2021-05-10 19:32:59 +00:00
}
2021-04-11 17:05:08 +00:00
}
2022-12-15 23:50:47 +00:00
// apiMuxersList is called by api.
func (m *hlsMuxer) apiMuxersList(req hlsServerAPIMuxersListSubReq) {
req.res = make(chan struct{})
select {
case m.chAPIHLSMuxersList <- req:
<-req.res
case <-m.ctx.Done():
}
}
// apiReaderDescribe implements reader.
func (m *hlsMuxer) apiReaderDescribe() interface{} {
return struct {
Type string `json:"type"`
2021-08-18 13:49:12 +00:00
}{"hlsMuxer"}
}