Null-DRM-Official/apps/streamd/internal/hlsgate/hlsgate.go
404errordeveloper da8e1123ec
All checks were successful
release / build-and-upload (push) Successful in 7m5s
Streamd v0.2.0: rename, modules panel, stable/beta channels
- Rename product/host binary to streamd (drm compat copy still shipped)
- Go module path streamd; STREAMD_* env aliases; agent UA streamd-agent
- Panel Modules store + agent pull sync (modstore / modsync)
- Rolling stable + beta download tags; README/docs channel curl blocks
- Release notes in docs/releases/v0.2.0.md attached by Forgejo Actions
2026-10-10 15:58:26 +02:00

675 lines
18 KiB
Go

// Package hlsgate serves the published media and, for streams marked
// on-demand, starts them when a viewer first asks for a playlist.
//
// It replaces a plain http.FileServer over data/www, which could only serve
// what was already running, listed directories, and told nobody anything about
// who was watching.
package hlsgate
import (
"errors"
"log/slog"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"streamd/apps/streamd/internal/auth"
"streamd/apps/streamd/internal/db"
"streamd/apps/streamd/internal/httpx"
"streamd/apps/streamd/internal/tsfanout"
)
// Supervisor is the subset of the media supervisor the gate needs.
type Supervisor interface {
Start(id int64) error
Stop(id int64) error
Running(id int64) bool
}
// CaptureRequester asks connected agents for fresh credentials now.
type CaptureRequester interface {
RequestCapture(st db.Stream, reason string) int
}
// Defaults.
const (
// DefaultWait is how long a viewer's request is held while a stream
// starts. Long enough for ffmpeg to produce a first segment, short enough
// that a browser does not give up on its own.
DefaultWait = 30 * time.Second
// DefaultCaptureWait applies when credentials must be captured first,
// which involves a real phone and takes far longer.
DefaultCaptureWait = 120 * time.Second
// viewerWindow is how long a client counts as watching after its last
// request. A player fetches a segment every few seconds, so a minute is
// generous without being stale.
viewerWindow = 60 * time.Second
idleCheckTick = 30 * time.Second
pollInterval = 250 * time.Millisecond
)
// Config is the gate's settings. It is separate from Gate so it can be passed
// by value without copying the gate's mutex.
type Config struct {
Store *db.Store
WWWRoot string
Sup Supervisor
Fanout *tsfanout.Set
Capture CaptureRequester
Trust httpx.Trust
Log *slog.Logger
// Wait and CaptureWait bound how long a request is held.
Wait time.Duration
CaptureWait time.Duration
}
type Gate struct {
Config
mu sync.Mutex
tracks map[string]*track
waking map[int64]*wake
// wakeLimiter bounds how often an anonymous caller can trigger a start.
// Waking a stream spawns processes, so it is the one unauthenticated
// action here with real cost.
wakeLimiter *auth.Limiter
}
// track is the live request picture for one stream.
type track struct {
lastRequest time.Time
requests int64
// clients maps a client address to its last request time, giving a
// distinct-viewer count over the window rather than a request count.
clients map[string]time.Time
}
// wake is the single-flight state for one stream being started.
type wake struct {
done chan struct{}
err error
started time.Time
}
func New(cfg Config) *Gate {
out := &Gate{Config: cfg}
if out.Wait <= 0 {
out.Wait = DefaultWait
}
if out.CaptureWait <= 0 {
out.CaptureWait = DefaultCaptureWait
}
if out.Log == nil {
out.Log = slog.Default()
}
out.tracks = map[string]*track{}
out.waking = map[int64]*wake{}
// Eight wakes per client, refilling slowly: enough for a person opening a
// few channels, not enough to be used as a process-spawning amplifier.
out.wakeLimiter = auth.NewLimiter(8, 0.1)
return out
}
func (g *Gate) Mount(mux *http.ServeMux) {
mux.Handle("/hls/", http.HandlerFunc(g.serveHLS))
mux.Handle("/live/", http.HandlerFunc(g.serveLive))
}
// target is a resolved request: which stream, which rung, which file.
type target struct {
stream db.Stream
variant db.VariantSpec
// dir is the www subdirectory, i.e. the stream or variant directory name.
dir string
// rel is the file path within dir ("index.m3u8", "cmaf/index.m3u8", ...).
rel string
// isPlaylist marks the requests that may wake a stream.
isPlaylist bool
}
var errNotFound = errors.New("no such stream")
// resolve maps a www directory name onto a stream and rung.
//
// The layout is "<name>" for the source rung and "<name>-<variant>" for the
// others, and a stream name may itself contain a dash — so an exact match is
// tried first, and only then a split at the last dash whose suffix is a real
// rung of the stream that remains.
func (g *Gate) resolve(dir string) (db.Stream, db.VariantSpec, error) {
if dir == "" {
return db.Stream{}, db.VariantSpec{}, errNotFound
}
if st, err := g.Store.GetStreamByName(dir); err == nil {
return st, sourceRung(st), nil
}
// Try progressively earlier dashes, so "a-b-hd" resolves against a stream
// called "a-b" even though "a" also exists.
for i := strings.LastIndex(dir, "-"); i > 0; i = strings.LastIndex(dir[:i], "-") {
name, variantID := dir[:i], dir[i+1:]
st, err := g.Store.GetStreamByName(name)
if err != nil {
continue
}
for _, v := range db.ParseVariantsJSON(st.VariantsJSON) {
if v.ID == variantID {
return st, v, nil
}
}
}
return db.Stream{}, db.VariantSpec{}, errNotFound
}
func sourceRung(st db.Stream) db.VariantSpec {
for _, v := range db.ParseVariantsJSON(st.VariantsJSON) {
if v.IsSource() {
return v
}
}
return db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true}
}
// serveHLS handles /hls/<dir>/<file...>.
func (g *Gate) serveHLS(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
rest := strings.TrimPrefix(r.URL.Path, "/hls/")
// A trailing slash or a bare /hls/ used to produce a directory listing,
// which enumerated every stream on the server.
if rest == "" || strings.HasSuffix(rest, "/") {
http.NotFound(w, r)
return
}
dir, rel, ok := strings.Cut(rest, "/")
if !ok || rel == "" {
http.NotFound(w, r)
return
}
st, variant, err := g.resolve(dir)
if err != nil {
http.NotFound(w, r)
return
}
// Reject anything that tries to climb out of the stream's directory
// before it is ever joined to a filesystem path.
clean := path.Clean("/" + rel)
if clean == "/" || strings.Contains(clean, "..") {
http.NotFound(w, r)
return
}
rel = strings.TrimPrefix(clean, "/")
t := target{
stream: st,
variant: variant,
dir: dir,
rel: rel,
isPlaylist: isPlaylist(rel),
}
if !g.authorise(w, r, st) {
return
}
g.note(st.Name, g.Trust.ClientIP(r))
full := filepath.Join(g.WWWRoot, filepath.FromSlash(dir), filepath.FromSlash(rel))
if _, err := os.Stat(full); err != nil {
// Only a playlist request may wake a stream. A segment request for a
// stream that is not running is simply a 404: starting a stream would
// not produce that particular segment anyway.
if !t.isPlaylist || !g.shouldWake(st) {
http.NotFound(w, r)
return
}
if !g.waitForStart(w, r, t, full) {
return
}
}
g.serveFile(w, r, full, rel)
}
// serveLive handles /live/<dir>.ts, the progressive MPEG-TS output.
func (g *Gate) serveLive(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
name := strings.TrimPrefix(r.URL.Path, "/live/")
if !strings.HasSuffix(name, ".ts") {
http.NotFound(w, r)
return
}
dir := strings.TrimSuffix(name, ".ts")
if dir == "" || strings.ContainsAny(dir, "/\\") {
http.NotFound(w, r)
return
}
st, _, err := g.resolve(dir)
if err != nil {
http.NotFound(w, r)
return
}
if !tsEnabled(st) {
http.Error(w, "this stream does not publish a progressive MPEG-TS output", http.StatusNotFound)
return
}
if !g.authorise(w, r, st) {
return
}
g.note(st.Name, g.Trust.ClientIP(r))
ring, ok := g.Fanout.Get(dir)
if !ok {
// Nothing is publishing yet: wake it if we may, then wait for a ring.
if !g.shouldWake(st) {
http.Error(w, "stream is not running", http.StatusServiceUnavailable)
return
}
if !g.wakeAndWaitRing(w, r, st, dir) {
return
}
ring, ok = g.Fanout.Get(dir)
if !ok {
g.retryLater(w, "stream did not start in time")
return
}
}
if r.Method == http.MethodHead {
w.Header().Set("Content-Type", "video/mp2t")
w.WriteHeader(http.StatusOK)
return
}
reader := ring.NewReader()
defer reader.Close()
h := w.Header()
h.Set("Content-Type", "video/mp2t")
h.Set("Cache-Control", "no-store")
// Defeat proxy buffering, or the viewer waits for a buffer to fill.
h.Set("X-Accel-Buffering", "no")
w.WriteHeader(http.StatusOK)
flusher, _ := w.(http.Flusher)
buf := make([]byte, 64<<10)
ctx := r.Context()
for {
select {
case <-ctx.Done():
return
default:
}
n, err := reader.Read(buf)
if n > 0 {
if _, werr := w.Write(buf[:n]); werr != nil {
return
}
if flusher != nil {
flusher.Flush()
}
// A request that is actively pulling bytes is a live viewer, but
// re-noting on every chunk would be pointless work; the ring's
// own reader count covers the fine grain.
}
if err != nil {
if errors.Is(err, tsfanout.ErrLagged) {
g.Log.Info("dropped a progressive-TS client that fell behind",
"stream", st.Name, "ip", g.Trust.ClientIP(r))
}
return
}
}
}
func tsEnabled(st db.Stream) bool {
for _, o := range db.EnabledOutputs(db.ParseOutputsJSON(st.OutputsJSON)) {
if o.Format == db.FormatTS {
return true
}
}
return false
}
func isPlaylist(rel string) bool {
l := strings.ToLower(rel)
return strings.HasSuffix(l, ".m3u8") || strings.HasSuffix(l, ".mpd")
}
// authorise enforces the per-stream public flag. A public stream is readable
// by anyone, which is what makes on-demand work; a private one needs a
// principal.
func (g *Gate) authorise(w http.ResponseWriter, r *http.Request, st db.Stream) bool {
if st.Public {
return true
}
if p := auth.From(r); p != nil {
return true
}
w.Header().Set("WWW-Authenticate", `Bearer realm="streamd"`)
http.Error(w, "this stream is not public", http.StatusUnauthorized)
return false
}
// shouldWake reports whether this request may start the stream.
// Deliberately NOT conditioned on the stream being stopped: when twenty
// viewers arrive together, the first one starts it and the rest must wait for
// the same playlist. Checking Running() here meant everyone after the first
// got a 404 while the stream was still starting. startOnce is what makes sure
// only one start actually happens.
func (g *Gate) shouldWake(st db.Stream) bool {
if !st.OnDemand || !st.Enabled {
return false
}
// Nothing to start from: no manifest, and no agent able to fetch one.
if strings.TrimSpace(st.MPD) == "" && !st.NeedsCapture {
return false
}
return true
}
// waitForStart holds the request while the stream comes up. Returns true when
// the file now exists and may be served.
func (g *Gate) waitForStart(w http.ResponseWriter, r *http.Request, t target, full string) bool {
ip := g.Trust.ClientIP(r)
if !g.wakeLimiter.Allow(ip) {
g.retryLater(w, "too many start requests from this client")
return false
}
st := t.stream
deadline := g.Wait
// Credentials have to be captured first, which involves a real phone and
// is far slower than starting a packager.
if st.NeedsCapture {
deadline = g.CaptureWait
}
if err := g.startOnce(st); err != nil {
g.Log.Error("on-demand start failed", "stream", st.Name, "err", err)
g.retryLater(w, "stream could not be started")
return false
}
ctx := r.Context()
give := time.Now().Add(deadline)
for time.Now().Before(give) {
select {
case <-ctx.Done():
// The viewer gave up; the stream stays up for the idle timeout so
// their retry is instant.
return false
case <-time.After(pollInterval):
}
if fi, err := os.Stat(full); err == nil && fi.Size() > 0 {
// A playlist exists; make sure it lists at least one segment, or
// the player gets an empty playlist and stops.
if !t.isPlaylist || playlistHasSegment(full) {
g.note(st.Name, ip)
return true
}
}
}
g.retryLater(w, "stream is still starting")
return false
}
// wakeAndWaitRing starts a stream and waits for its progressive-TS ring.
func (g *Gate) wakeAndWaitRing(w http.ResponseWriter, r *http.Request, st db.Stream, dir string) bool {
ip := g.Trust.ClientIP(r)
if !g.wakeLimiter.Allow(ip) {
g.retryLater(w, "too many start requests from this client")
return false
}
deadline := g.Wait
if st.NeedsCapture {
deadline = g.CaptureWait
}
if err := g.startOnce(st); err != nil {
g.retryLater(w, "stream could not be started")
return false
}
ctx := r.Context()
give := time.Now().Add(deadline)
for time.Now().Before(give) {
select {
case <-ctx.Done():
return false
case <-time.After(pollInterval):
}
if _, ok := g.Fanout.Get(dir); ok {
return true
}
}
g.retryLater(w, "stream is still starting")
return false
}
// startOnce starts a stream under a per-stream single flight, so twenty
// viewers arriving together produce one start, not twenty.
func (g *Gate) startOnce(st db.Stream) error {
g.mu.Lock()
if wk, ok := g.waking[st.ID]; ok {
g.mu.Unlock()
// Someone else is already starting it; wait for their result.
<-wk.done
return wk.err
}
if g.Sup.Running(st.ID) {
// Already up, or already coming up from an earlier request: there is
// nothing to start, only a playlist to wait for. Calling Start again
// would restart a healthy stream and cut off its current viewers.
g.noteLocked(st.Name, "")
g.mu.Unlock()
return nil
}
wk := &wake{done: make(chan struct{}), started: time.Now()}
g.waking[st.ID] = wk
// Count the wake as activity straight away, so the idle sweep cannot stop
// the stream before the first viewer has been served.
g.noteLocked(st.Name, "")
g.mu.Unlock()
g.Log.Info("waking on-demand stream", "stream", st.Name, "needs_capture", st.NeedsCapture)
g.Store.AddEvent(db.StreamEvent{
StreamID: st.ID, Kind: db.EventOnDemandWake, Severity: db.SevInfo,
Message: "a viewer requested this stream, starting it",
})
// Credentials may be stale. Ask any connected agent to refresh now rather
// than on its next poll, with a viewer already waiting.
if st.NeedsCapture && g.Capture != nil {
if n := g.Capture.RequestCapture(st, "ondemand_wake"); n > 0 {
g.Log.Info("asked agents for fresh credentials", "stream", st.Name, "agents", n)
}
}
err := g.Sup.Start(st.ID)
g.mu.Lock()
wk.err = err
delete(g.waking, st.ID)
g.mu.Unlock()
close(wk.done)
return err
}
// playlistHasSegment reports whether a media playlist lists at least one
// segment. A freshly created but empty playlist makes a player give up.
func playlistHasSegment(p string) bool {
b, err := os.ReadFile(p)
if err != nil {
return false
}
body := string(b)
if strings.HasSuffix(strings.ToLower(p), ".mpd") {
// A DASH manifest is self-describing; its presence is enough.
return strings.Contains(body, "<MPD")
}
// A master playlist lists other playlists, not segments.
if strings.Contains(body, "#EXT-X-STREAM-INF") {
return true
}
return strings.Contains(body, "#EXTINF")
}
func (g *Gate) retryLater(w http.ResponseWriter, msg string) {
w.Header().Set("Retry-After", "5")
http.Error(w, msg, http.StatusServiceUnavailable)
}
// serveFile sends one media file with cache headers appropriate to its kind.
func (g *Gate) serveFile(w http.ResponseWriter, r *http.Request, full, rel string) {
f, err := os.Open(full)
if err != nil {
http.NotFound(w, r)
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil || fi.IsDir() {
http.NotFound(w, r)
return
}
h := w.Header()
low := strings.ToLower(rel)
switch {
case strings.HasSuffix(low, ".m3u8"):
h.Set("Content-Type", "application/vnd.apple.mpegurl")
// A live playlist changes every few seconds.
h.Set("Cache-Control", "no-cache, max-age=1")
case strings.HasSuffix(low, ".mpd"):
h.Set("Content-Type", "application/dash+xml")
h.Set("Cache-Control", "no-cache, max-age=1")
case strings.HasSuffix(low, ".ts"):
h.Set("Content-Type", "video/mp2t")
h.Set("Cache-Control", "public, max-age=31536000, immutable")
case strings.HasSuffix(low, ".m4s"), strings.HasSuffix(low, ".mp4"):
h.Set("Content-Type", "video/mp4")
h.Set("Cache-Control", "public, max-age=31536000, immutable")
default:
h.Set("Cache-Control", "no-cache")
}
http.ServeContent(w, r, filepath.Base(rel), fi.ModTime(), f)
}
// ---------- viewer tracking ----------
// note records a request against a stream.
func (g *Gate) note(name, ip string) {
g.mu.Lock()
g.noteLocked(name, ip)
g.mu.Unlock()
}
func (g *Gate) noteLocked(name, ip string) {
t, ok := g.tracks[name]
if !ok {
t = &track{clients: map[string]time.Time{}}
g.tracks[name] = t
}
nowT := time.Now()
t.lastRequest = nowT
t.requests++
if ip != "" {
t.clients[ip] = nowT
// Expire stale clients here rather than on a timer; the map only
// grows while requests are arriving.
if len(t.clients) > 1 {
for k, seen := range t.clients {
if nowT.Sub(seen) > viewerWindow {
delete(t.clients, k)
}
}
}
}
}
// ViewersFor is the number of distinct clients seen in the last minute, plus
// any progressive-TS readers currently attached.
func (g *Gate) ViewersFor(name string) int {
g.mu.Lock()
t, ok := g.tracks[name]
n := 0
if ok {
nowT := time.Now()
for _, seen := range t.clients {
if nowT.Sub(seen) <= viewerWindow {
n++
}
}
}
g.mu.Unlock()
if g.Fanout != nil {
n += g.Fanout.Readers(name)
}
return n
}
// RunIdleLoop stops on-demand streams nobody is watching.
func (g *Gate) RunIdleLoop(stop <-chan struct{}) {
t := time.NewTicker(idleCheckTick)
defer t.Stop()
for {
select {
case <-stop:
return
case <-t.C:
g.sweepIdle()
}
}
}
func (g *Gate) sweepIdle() {
list, err := g.Store.ListStreams()
if err != nil {
return
}
for _, st := range list {
if !st.OnDemand || !g.Sup.Running(st.ID) {
continue
}
idle := time.Duration(st.IdleTimeoutS) * time.Second
if idle <= 0 {
idle = db.DefaultIdleTimeoutS * time.Second
}
// A progressive-TS client holds an open connection rather than
// polling, so it would otherwise look idle the whole time it watched.
if g.Fanout != nil && g.Fanout.Readers(st.Name) > 0 {
g.note(st.Name, "")
continue
}
g.mu.Lock()
t, seen := g.tracks[st.Name]
var last time.Time
if seen {
last = t.lastRequest
}
g.mu.Unlock()
if !seen || last.IsZero() {
// Running but never requested through the gate: it was started by
// hand or by a schedule, so leave it alone.
continue
}
if time.Since(last) < idle {
continue
}
g.Log.Info("stopping idle on-demand stream",
"stream", st.Name, "idle_s", int(time.Since(last).Seconds()))
g.Store.AddEvent(db.StreamEvent{
StreamID: st.ID, Kind: db.EventIdleStop, Severity: db.SevInfo,
Message: "no viewers for " + idle.String() + ", stopping until the next request",
})
if err := g.Sup.Stop(st.ID); err != nil {
g.Log.Error("idle stop failed", "stream", st.Name, "err", err)
continue
}
g.mu.Lock()
delete(g.tracks, st.Name)
g.mu.Unlock()
}
}