mediamtx/internal/core/hls_server.go

257 lines
5.0 KiB
Go
Raw Normal View History

package core
2021-04-11 17:05:08 +00:00
import (
"context"
"io"
"net"
"net/http"
gopath "path"
2021-04-11 17:05:08 +00:00
"strings"
"sync"
"time"
2021-04-11 17:05:08 +00:00
"github.com/aler9/rtsp-simple-server/internal/logger"
)
type hlsServerParent interface {
2021-04-11 17:05:08 +00:00
Log(logger.Level, string, ...interface{})
}
type hlsServer struct {
hlsAlwaysRemux bool
hlsSegmentCount int
hlsSegmentDuration time.Duration
hlsAllowOrigin string
readBufferCount int
stats *stats
pathManager *pathManager
parent hlsServerParent
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
ln net.Listener
remuxers map[string]*hlsRemuxer
// in
pathSourceReady chan *path
request chan hlsRemuxerRequest
connClose chan *hlsRemuxer
2021-04-11 17:05:08 +00:00
}
func newHLSServer(
parentCtx context.Context,
address string,
hlsAlwaysRemux bool,
hlsSegmentCount int,
hlsSegmentDuration time.Duration,
hlsAllowOrigin string,
readBufferCount int,
stats *stats,
pathManager *pathManager,
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,
stats: stats,
pathManager: pathManager,
parent: parent,
2021-05-10 19:32:59 +00:00
ctx: ctx,
ctxCancel: ctxCancel,
ln: ln,
remuxers: make(map[string]*hlsRemuxer),
pathSourceReady: make(chan *path),
2021-07-29 10:16:06 +00:00
request: make(chan hlsRemuxerRequest),
connClose: make(chan *hlsRemuxer),
2021-04-11 17:05:08 +00:00
}
s.Log(logger.Info, "listener opened on "+address)
2021-04-11 17:05:08 +00:00
2021-05-10 19:32:59 +00:00
s.wg.Add(1)
go s.run()
2021-04-11 17:05:08 +00:00
s.pathManager.OnHLSServer(s)
2021-04-11 17:05:08 +00:00
return s, nil
}
// Log is the main logging function.
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()
}
func (s *hlsServer) run() {
2021-05-10 19:32:59 +00:00
defer s.wg.Done()
hs := &http.Server{Handler: s}
go hs.Serve(s.ln)
outer:
for {
select {
case pa := <-s.pathSourceReady:
if s.hlsAlwaysRemux {
s.findOrCreateRemuxer(pa.Name())
}
case req := <-s.request:
r := s.findOrCreateRemuxer(req.Dir)
r.OnRequest(req)
2021-05-09 12:41:18 +00:00
case c := <-s.connClose:
if c2, ok := s.remuxers[c.PathName()]; !ok || c2 != c {
continue
}
2021-07-29 10:16:06 +00:00
s.doRemuxerClose(c)
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
break outer
}
}
2021-05-10 19:32:59 +00:00
s.ctxCancel()
for _, c := range s.remuxers {
2021-07-29 10:16:06 +00:00
s.doRemuxerClose(c)
}
hs.Shutdown(context.Background())
s.pathManager.OnHLSServer(nil)
2021-04-11 17:05:08 +00:00
}
// ServeHTTP implements http.Handler.
func (s *hlsServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2021-05-09 12:41:18 +00:00
s.Log(logger.Info, "[conn %v] %s %s", r.RemoteAddr, r.Method, r.URL.Path)
2021-04-11 17:05:08 +00:00
// remove leading prefix
2021-05-29 14:05:44 +00:00
pa := r.URL.Path[1:]
2021-04-11 17:05:08 +00:00
w.Header().Add("Access-Control-Allow-Origin", s.hlsAllowOrigin)
w.Header().Add("Access-Control-Allow-Credentials", "true")
switch r.Method {
case http.MethodGet:
case http.MethodOptions:
w.Header().Add("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Add("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
w.WriteHeader(http.StatusOK)
return
default:
w.WriteHeader(http.StatusNotFound)
return
}
switch pa {
case "", "favicon.ico":
2021-04-11 17:05:08 +00:00
w.WriteHeader(http.StatusNotFound)
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, "/") {
w.Header().Add("Location", "/"+dir+"/")
2021-04-11 17:05:08 +00:00
w.WriteHeader(http.StatusMovedPermanently)
return
}
2021-07-04 14:03:24 +00:00
dir = strings.TrimSuffix(dir, "/")
2021-05-29 14:05:44 +00:00
2021-04-11 17:05:08 +00:00
cres := make(chan io.Reader)
2021-07-29 10:16:06 +00:00
hreq := hlsRemuxerRequest{
2021-07-04 14:03:24 +00:00
Dir: dir,
File: fname,
Req: r,
W: w,
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
if res != nil {
buf := make([]byte, 4096)
for {
n, err := res.Read(buf)
if err != nil {
2021-05-10 19:32:59 +00:00
return
}
2021-05-10 19:32:59 +00:00
_, err = w.Write(buf[:n])
if err != nil {
return
}
w.(http.Flusher).Flush()
}
}
2021-05-10 19:32:59 +00:00
case <-s.ctx.Done():
2021-04-11 17:05:08 +00:00
}
}
func (s *hlsServer) findOrCreateRemuxer(pathName string) *hlsRemuxer {
r, ok := s.remuxers[pathName]
if !ok {
r = newHLSRemuxer(
s.ctx,
s.hlsAlwaysRemux,
s.hlsSegmentCount,
s.hlsSegmentDuration,
s.readBufferCount,
&s.wg,
s.stats,
pathName,
s.pathManager,
s)
s.remuxers[pathName] = r
}
return r
}
2021-07-29 10:16:06 +00:00
func (s *hlsServer) doRemuxerClose(c *hlsRemuxer) {
delete(s.remuxers, c.PathName())
2021-05-09 14:12:15 +00:00
c.ParentClose()
}
// OnRemuxerClose is called by hlsRemuxer.
2021-07-29 10:16:06 +00:00
func (s *hlsServer) OnRemuxerClose(c *hlsRemuxer) {
2021-05-10 19:32:59 +00:00
select {
case s.connClose <- c:
case <-s.ctx.Done():
}
2021-04-11 17:05:08 +00:00
}
// OnPathSourceReady is called by core.
func (s *hlsServer) OnPathSourceReady(pa *path) {
select {
case s.pathSourceReady <- pa:
case <-s.ctx.Done():
}
}