mediamtx/internal/hlsserver/server.go

215 lines
4.2 KiB
Go
Raw Normal View History

2021-05-09 15:02:14 +00:00
package hlsserver
2021-04-11 17:05:08 +00:00
import (
"context"
"io"
"net"
"net/http"
2021-05-29 14:05:44 +00:00
"path"
2021-04-11 17:05:08 +00:00
"strings"
"sync"
"time"
2021-04-11 17:05:08 +00:00
2021-05-09 15:02:14 +00:00
"github.com/aler9/rtsp-simple-server/internal/hlsconverter"
2021-04-11 17:05:08 +00:00
"github.com/aler9/rtsp-simple-server/internal/logger"
"github.com/aler9/rtsp-simple-server/internal/pathman"
"github.com/aler9/rtsp-simple-server/internal/stats"
2021-04-11 17:05:08 +00:00
)
// Parent is implemented by program.
type Parent interface {
Log(logger.Level, string, ...interface{})
}
// Server is an HLS server.
type Server struct {
hlsSegmentCount int
hlsSegmentDuration time.Duration
readBufferCount int
stats *stats.Stats
pathMan *pathman.PathManager
parent Parent
2021-05-10 19:32:59 +00:00
ctx context.Context
ctxCancel func()
2021-04-27 17:29:43 +00:00
wg sync.WaitGroup
2021-05-10 19:32:59 +00:00
ln net.Listener
2021-05-09 15:02:14 +00:00
converters map[string]*hlsconverter.Converter
// in
2021-05-09 15:02:14 +00:00
request chan hlsconverter.Request
connClose chan *hlsconverter.Converter
2021-04-11 17:05:08 +00:00
}
// New allocates a Server.
func New(
2021-05-11 15:20:32 +00:00
ctxParent context.Context,
address string,
hlsSegmentCount int,
hlsSegmentDuration time.Duration,
readBufferCount int,
stats *stats.Stats,
pathMan *pathman.PathManager,
2021-04-11 17:05:08 +00:00
parent Parent,
) (*Server, error) {
ln, err := net.Listen("tcp", address)
if err != nil {
return nil, err
}
2021-05-11 15:20:32 +00:00
ctx, ctxCancel := context.WithCancel(ctxParent)
2021-05-10 19:32:59 +00:00
2021-04-11 17:05:08 +00:00
s := &Server{
hlsSegmentCount: hlsSegmentCount,
hlsSegmentDuration: hlsSegmentDuration,
readBufferCount: readBufferCount,
stats: stats,
pathMan: pathMan,
parent: parent,
2021-05-10 19:32:59 +00:00
ctx: ctx,
ctxCancel: ctxCancel,
ln: ln,
2021-05-09 15:02:14 +00:00
converters: make(map[string]*hlsconverter.Converter),
request: make(chan hlsconverter.Request),
connClose: make(chan *hlsconverter.Converter),
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
return s, nil
}
// Log is the main logging function.
func (s *Server) 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
}
// Close closes all the server resources.
func (s *Server) Close() {
2021-05-10 19:32:59 +00:00
s.ctxCancel()
s.wg.Wait()
}
func (s *Server) 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 req := <-s.request:
2021-04-27 17:29:43 +00:00
c, ok := s.converters[req.Path]
if !ok {
2021-05-09 15:02:14 +00:00
c = hlsconverter.New(
2021-05-11 15:20:32 +00:00
s.ctx,
s.hlsSegmentCount,
s.hlsSegmentDuration,
s.readBufferCount,
&s.wg,
s.stats,
req.Path,
s.pathMan,
s)
2021-04-27 17:29:43 +00:00
s.converters[req.Path] = c
}
c.OnRequest(req)
2021-05-09 12:41:18 +00:00
case c := <-s.connClose:
2021-04-27 17:29:43 +00:00
if c2, ok := s.converters[c.PathName()]; !ok || c2 != c {
continue
}
2021-04-27 17:29:43 +00:00
s.doConverterClose(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()
2021-04-27 17:29:43 +00:00
for _, c := range s.converters {
s.doConverterClose(c)
}
hs.Shutdown(context.Background())
2021-04-11 17:05:08 +00:00
}
// ServeHTTP implements http.Handler.
func (s *Server) 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
2021-05-29 14:05:44 +00:00
if pa == "" || pa == "favicon.ico" {
2021-04-11 17:05:08 +00:00
w.WriteHeader(http.StatusNotFound)
return
}
2021-05-29 14:05:44 +00:00
pa, fname := func() (string, string) {
if strings.HasSuffix(pa, ".ts") || strings.HasSuffix(pa, ".m3u8") {
return path.Dir(pa), path.Base(pa)
}
return pa, ""
}()
if fname == "" && !strings.HasSuffix(pa, "/") {
w.Header().Add("Location", "/"+pa+"/")
2021-04-11 17:05:08 +00:00
w.WriteHeader(http.StatusMovedPermanently)
return
}
2021-05-29 14:05:44 +00:00
pa = strings.TrimSuffix(pa, "/")
2021-04-11 17:05:08 +00:00
cres := make(chan io.Reader)
2021-05-10 19:32:59 +00:00
hreq := hlsconverter.Request{
2021-05-29 14:05:44 +00:00
Path: pa,
FileName: 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 {
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
}
}
2021-05-09 15:02:14 +00:00
func (s *Server) doConverterClose(c *hlsconverter.Converter) {
2021-04-27 17:29:43 +00:00
delete(s.converters, c.PathName())
2021-05-09 14:12:15 +00:00
c.ParentClose()
}
2021-05-09 15:02:14 +00:00
// OnConverterClose is called by hlsconverter.Converter.
func (s *Server) OnConverterClose(c *hlsconverter.Converter) {
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
}