mediamtx/internal/core/hls_server.go

321 lines
6.8 KiB
Go
Raw Normal View History

package core
2021-04-11 17:05:08 +00:00
import (
"context"
2021-11-05 16:14:31 +00:00
"fmt"
2021-04-11 17:05:08 +00:00
"io"
"net"
"net/http"
"net/http/httputil"
gopath "path"
2021-04-11 17:05:08 +00:00
"strings"
"sync"
2021-04-11 17:05:08 +00:00
2021-10-17 14:49:49 +00:00
"github.com/gin-gonic/gin"
"github.com/aler9/rtsp-simple-server/internal/conf"
2021-04-11 17:05:08 +00:00
"github.com/aler9/rtsp-simple-server/internal/logger"
)
2021-11-06 11:52:12 +00:00
type hlsServerAPIMuxersListItem struct {
LastRequest string `json:"lastRequest"`
}
2021-11-06 11:52:12 +00:00
type hlsServerAPIMuxersListData struct {
Items map[string]hlsServerAPIMuxersListItem `json:"items"`
}
2021-11-06 11:52:12 +00:00
type hlsServerAPIMuxersListRes struct {
Data *hlsServerAPIMuxersListData
Muxers map[string]*hlsMuxer
Err error
}
2021-11-06 11:52:12 +00:00
type hlsServerAPIMuxersListReq struct {
Res chan hlsServerAPIMuxersListRes
}
2021-11-06 11:52:12 +00:00
type hlsServerAPIMuxersListSubReq struct {
Data *hlsServerAPIMuxersListData
Res chan struct{}
}
type hlsServerParent interface {
2021-04-11 17:05:08 +00:00
Log(logger.Level, string, ...interface{})
}
type hlsServer struct {
hlsAlwaysRemux bool
hlsSegmentCount int
hlsSegmentDuration conf.StringDuration
hlsAllowOrigin string
readBufferCount int
pathManager *pathManager
2021-11-05 16:29:13 +00:00
metrics *metrics
parent hlsServerParent
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
ln net.Listener
2021-08-18 13:49:12 +00:00
muxers map[string]*hlsMuxer
// in
pathSourceReady chan *path
request chan hlsMuxerRequest
muxerClose chan *hlsMuxer
2021-11-06 11:52:12 +00:00
apiMuxersList chan hlsServerAPIMuxersListReq
2021-04-11 17:05:08 +00:00
}
func newHLSServer(
parentCtx context.Context,
address string,
hlsAlwaysRemux bool,
hlsSegmentCount int,
hlsSegmentDuration conf.StringDuration,
hlsAllowOrigin string,
readBufferCount int,
pathManager *pathManager,
2021-11-05 16:29:13 +00:00
metrics *metrics,
parent hlsServerParent,
) (*hlsServer, error) {
2021-04-11 17:05:08 +00:00
ln, err := net.Listen("tcp", address)
if err != nil {
return nil, err
}
ctx, ctxCancel := context.WithCancel(parentCtx)
2021-05-10 19:32:59 +00:00
s := &hlsServer{
hlsAlwaysRemux: hlsAlwaysRemux,
hlsSegmentCount: hlsSegmentCount,
hlsSegmentDuration: hlsSegmentDuration,
hlsAllowOrigin: hlsAllowOrigin,
readBufferCount: readBufferCount,
pathManager: pathManager,
parent: parent,
2021-11-05 16:29:13 +00:00
metrics: metrics,
2021-05-10 19:32:59 +00:00
ctx: ctx,
ctxCancel: ctxCancel,
ln: ln,
2021-08-18 13:49:12 +00:00
muxers: make(map[string]*hlsMuxer),
pathSourceReady: make(chan *path),
2021-08-18 13:49:12 +00:00
request: make(chan hlsMuxerRequest),
muxerClose: make(chan *hlsMuxer),
2021-11-06 11:52:12 +00:00
apiMuxersList: make(chan hlsServerAPIMuxersListReq),
2021-04-11 17:05:08 +00:00
}
2021-10-27 19:01:00 +00:00
s.log(logger.Info, "listener opened on "+address)
2021-04-11 17:05:08 +00:00
2021-10-27 19:01:00 +00:00
s.pathManager.onHLSServerSet(s)
2021-11-05 16:29:13 +00:00
if s.metrics != nil {
s.metrics.onHLSServerSet(s)
}
2021-05-10 19:32:59 +00:00
s.wg.Add(1)
go s.run()
2021-04-11 17:05:08 +00:00
return s, nil
}
// Log is the main logging function.
2021-10-27 19:01:00 +00:00
func (s *hlsServer) log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[HLS] "+format, append([]interface{}{}, args...)...)
2021-04-11 17:05:08 +00:00
}
func (s *hlsServer) close() {
2021-05-10 19:32:59 +00:00
s.ctxCancel()
s.wg.Wait()
s.log(logger.Info, "listener closed")
}
func (s *hlsServer) run() {
2021-05-10 19:32:59 +00:00
defer s.wg.Done()
2021-10-17 14:49:49 +00:00
router := gin.New()
router.NoRoute(s.onRequest)
hs := &http.Server{Handler: router}
go hs.Serve(s.ln)
outer:
for {
select {
case pa := <-s.pathSourceReady:
if s.hlsAlwaysRemux {
2021-08-18 13:49:12 +00:00
s.findOrCreateMuxer(pa.Name())
}
case req := <-s.request:
2021-08-18 13:49:12 +00:00
r := s.findOrCreateMuxer(req.Dir)
2021-10-27 19:01:00 +00:00
r.onRequest(req)
2021-08-18 13:49:12 +00:00
case c := <-s.muxerClose:
if c2, ok := s.muxers[c.PathName()]; !ok || c2 != c {
continue
}
2021-08-18 13:49:12 +00:00
delete(s.muxers, c.PathName())
case req := <-s.apiMuxersList:
2021-11-05 16:14:31 +00:00
muxers := make(map[string]*hlsMuxer)
for name, m := range s.muxers {
muxers[name] = m
}
2021-11-06 11:52:12 +00:00
req.Res <- hlsServerAPIMuxersListRes{
2021-11-05 16:14:31 +00:00
Muxers: muxers,
}
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
break outer
}
}
2021-05-10 19:32:59 +00:00
s.ctxCancel()
hs.Shutdown(context.Background())
2021-10-27 19:01:00 +00:00
s.pathManager.onHLSServerSet(nil)
2021-11-05 16:29:13 +00:00
if s.metrics != nil {
s.metrics.onHLSServerSet(nil)
}
2021-04-11 17:05:08 +00:00
}
2021-10-17 14:49:49 +00:00
func (s *hlsServer) onRequest(ctx *gin.Context) {
2021-10-27 19:01:00 +00:00
s.log(logger.Info, "[conn %v] %s %s", ctx.Request.RemoteAddr, ctx.Request.Method, ctx.Request.URL.Path)
2021-04-11 17:05:08 +00:00
byts, _ := httputil.DumpRequest(ctx.Request, true)
2021-10-27 19:01:00 +00:00
s.log(logger.Debug, "[conn %v] [c->s] %s", ctx.Request.RemoteAddr, string(byts))
logw := &httpLogWriter{ResponseWriter: ctx.Writer}
ctx.Writer = logw
2021-04-11 17:05:08 +00:00
2021-10-17 14:51:35 +00:00
ctx.Writer.Header().Set("Server", "rtsp-simple-server")
ctx.Writer.Header().Set("Access-Control-Allow-Origin", s.hlsAllowOrigin)
ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
2021-10-17 14:49:49 +00:00
switch ctx.Request.Method {
case http.MethodGet:
case http.MethodOptions:
2021-10-17 14:51:35 +00:00
ctx.Writer.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
ctx.Writer.Header().Set("Access-Control-Allow-Headers", ctx.Request.Header.Get("Access-Control-Request-Headers"))
2021-10-17 14:49:49 +00:00
ctx.Writer.WriteHeader(http.StatusOK)
return
default:
2021-10-17 14:49:49 +00:00
ctx.Writer.WriteHeader(http.StatusNotFound)
return
}
// remove leading prefix
pa := ctx.Request.URL.Path[1:]
switch pa {
case "", "favicon.ico":
2021-10-17 14:49:49 +00:00
ctx.Writer.WriteHeader(http.StatusNotFound)
2021-04-11 17:05:08 +00:00
return
}
2021-07-04 14:03:24 +00:00
dir, fname := func() (string, string) {
2021-05-29 14:05:44 +00:00
if strings.HasSuffix(pa, ".ts") || strings.HasSuffix(pa, ".m3u8") {
return gopath.Dir(pa), gopath.Base(pa)
2021-05-29 14:05:44 +00:00
}
return pa, ""
}()
2021-07-04 14:03:24 +00:00
if fname == "" && !strings.HasSuffix(dir, "/") {
2021-10-17 14:51:35 +00:00
ctx.Writer.Header().Set("Location", "/"+dir+"/")
2021-10-17 14:49:49 +00:00
ctx.Writer.WriteHeader(http.StatusMovedPermanently)
2021-04-11 17:05:08 +00:00
return
}
2021-07-04 14:03:24 +00:00
dir = strings.TrimSuffix(dir, "/")
2021-05-29 14:05:44 +00:00
2021-10-17 14:49:49 +00:00
cres := make(chan hlsMuxerResponse)
2021-08-18 13:49:12 +00:00
hreq := hlsMuxerRequest{
2021-07-04 14:03:24 +00:00
Dir: dir,
File: fname,
2021-10-17 14:49:49 +00:00
Req: ctx.Request,
2021-07-04 14:03:24 +00:00
Res: cres,
2021-04-11 17:05:08 +00:00
}
2021-05-10 19:32:59 +00:00
select {
case s.request <- hreq:
res := <-cres
2021-10-17 14:49:49 +00:00
for k, v := range res.Header {
ctx.Writer.Header().Set(k, v)
}
ctx.Writer.WriteHeader(res.Status)
if res.Body != nil {
io.Copy(ctx.Writer, res.Body)
}
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
2021-04-11 17:05:08 +00:00
}
2021-10-27 19:01:00 +00:00
s.log(logger.Debug, "[conn %v] [s->c] %s", ctx.Request.RemoteAddr, logw.dump())
2021-04-11 17:05:08 +00:00
}
2021-08-18 13:49:12 +00:00
func (s *hlsServer) findOrCreateMuxer(pathName string) *hlsMuxer {
r, ok := s.muxers[pathName]
if !ok {
2021-08-18 13:49:12 +00:00
r = newHLSMuxer(
s.ctx,
2021-11-05 16:14:31 +00:00
pathName,
s.hlsAlwaysRemux,
s.hlsSegmentCount,
s.hlsSegmentDuration,
s.readBufferCount,
&s.wg,
pathName,
s.pathManager,
s)
2021-08-18 13:49:12 +00:00
s.muxers[pathName] = r
}
return r
}
2021-10-27 19:01:00 +00:00
// onMuxerClose is called by hlsMuxer.
func (s *hlsServer) onMuxerClose(c *hlsMuxer) {
2021-05-10 19:32:59 +00:00
select {
2021-08-18 13:49:12 +00:00
case s.muxerClose <- c:
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
}
2021-04-11 17:05:08 +00:00
}
2021-10-27 19:01:00 +00:00
// onPathSourceReady is called by core.
func (s *hlsServer) onPathSourceReady(pa *path) {
select {
case s.pathSourceReady <- pa:
case <-s.ctx.Done():
}
}
2021-11-05 16:14:31 +00:00
// onAPIHLSMuxersList is called by api.
2021-11-06 11:52:12 +00:00
func (s *hlsServer) onAPIHLSMuxersList(req hlsServerAPIMuxersListReq) hlsServerAPIMuxersListRes {
req.Res = make(chan hlsServerAPIMuxersListRes)
2021-11-05 16:14:31 +00:00
select {
case s.apiMuxersList <- req:
2021-11-05 16:14:31 +00:00
res := <-req.Res
2021-11-06 11:52:12 +00:00
res.Data = &hlsServerAPIMuxersListData{
Items: make(map[string]hlsServerAPIMuxersListItem),
2021-11-05 16:14:31 +00:00
}
for _, pa := range res.Muxers {
2021-11-06 11:52:12 +00:00
pa.onAPIHLSMuxersList(hlsServerAPIMuxersListSubReq{Data: res.Data})
2021-11-05 16:14:31 +00:00
}
return res
case <-s.ctx.Done():
2021-11-06 11:52:12 +00:00
return hlsServerAPIMuxersListRes{Err: fmt.Errorf("terminated")}
2021-11-05 16:14:31 +00:00
}
}