streamd: preview quality picker, dashboard polish, C4 wrap keys
All checks were successful
release / build-and-upload (push) Successful in 6m18s
modules-release / build-and-upload (push) Successful in 5m18s

- Preview player can select FHD/HD/SD (or ABR master) from publish links
- Embed dashboard screenshots in README; Linux streamd+agent setup guide
- C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH
- Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate
This commit is contained in:
404errordeveloper 2026-10-09 20:57:43 +02:00
parent b3955bd81e
commit 066e018749
113 changed files with 19002 additions and 1541 deletions

View file

@ -0,0 +1,675 @@
// 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"
"drmdecryption/apps/streamd/internal/auth"
"drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/httpx"
"drmdecryption/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()
}
}

View file

@ -0,0 +1,642 @@
package hlsgate
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
"drmdecryption/apps/streamd/internal/auth"
"drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/tsfanout"
)
// fakeSup records what the gate asked for, and can pretend a stream comes up.
type fakeSup struct {
mu sync.Mutex
starts int32
stops int32
running map[int64]bool
onStart func(id int64)
startErr error
}
func newFakeSup() *fakeSup {
return &fakeSup{running: map[int64]bool{}}
}
func (f *fakeSup) Start(id int64) error {
atomic.AddInt32(&f.starts, 1)
if f.startErr != nil {
return f.startErr
}
f.mu.Lock()
f.running[id] = true
cb := f.onStart
f.mu.Unlock()
if cb != nil {
cb(id)
}
return nil
}
func (f *fakeSup) Stop(id int64) error {
atomic.AddInt32(&f.stops, 1)
f.mu.Lock()
f.running[id] = false
f.mu.Unlock()
return nil
}
func (f *fakeSup) Running(id int64) bool {
f.mu.Lock()
defer f.mu.Unlock()
return f.running[id]
}
type fakeCapture struct{ n int32 }
func (c *fakeCapture) RequestCapture(st db.Stream, reason string) int {
atomic.AddInt32(&c.n, 1)
return 1
}
func newTestGate(t *testing.T) (*Gate, *db.Store, *fakeSup, string) {
t.Helper()
dir := t.TempDir()
store, err := db.Open(filepath.Join(dir, "db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = store.Close() })
www := filepath.Join(dir, "www")
if err := os.MkdirAll(www, 0o755); err != nil {
t.Fatal(err)
}
sup := newFakeSup()
g := New(Config{
Store: store,
WWWRoot: www,
Sup: sup,
Fanout: tsfanout.NewSet(1 << 16),
Wait: 2 * time.Second,
})
return g, store, sup, www
}
func mkStream(t *testing.T, store *db.Store, in db.CreateStream) db.Stream {
t.Helper()
st, err := store.CreateStream(in)
if err != nil {
t.Fatal(err)
}
return st
}
func writeFile(t *testing.T, path, body string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
const livePlaylist = "#EXTM3U\n#EXT-X-VERSION:3\n#EXTINF:4.0,\nseg_00001.ts\n"
// ---------- path resolution ----------
// A stream name may contain a dash, so "city-news-hd" must resolve as the
// "hd" rung of "city-news", while "city-news" resolves as its own source rung.
func TestResolveStreamNamesContainingDashes(t *testing.T) {
g, store, _, _ := newTestGate(t)
variants, err := db.EncodeVariantsJSON([]db.VariantSpec{
{ID: db.SourceVariantID, Enabled: true},
{ID: "hd", Enabled: true, Height: 720},
})
if err != nil {
t.Fatal(err)
}
mkStream(t, store, db.CreateStream{Name: "city-news", VariantsJSON: variants})
mkStream(t, store, db.CreateStream{Name: "city", VariantsJSON: variants})
// A stream whose literal name ends in -hd must win over being read as a
// rung of another stream.
mkStream(t, store, db.CreateStream{Name: "sport-hd"})
cases := []struct {
dir string
wantStream string
wantVariant string
}{
{"city-news", "city-news", db.SourceVariantID},
{"city-news-hd", "city-news", "hd"},
{"city", "city", db.SourceVariantID},
{"city-hd", "city", "hd"},
{"sport-hd", "sport-hd", db.SourceVariantID},
}
for _, c := range cases {
st, v, err := g.resolve(c.dir)
if err != nil {
t.Errorf("resolve(%q) failed: %v", c.dir, err)
continue
}
if st.Name != c.wantStream || v.ID != c.wantVariant {
t.Errorf("resolve(%q) = %s/%s, want %s/%s",
c.dir, st.Name, v.ID, c.wantStream, c.wantVariant)
}
}
for _, bad := range []string{"", "nope", "city-news-4k", "city-news-hd-extra"} {
if _, _, err := g.resolve(bad); err == nil {
t.Errorf("resolve(%q) should have failed", bad)
}
}
}
// ---------- traversal ----------
func TestPathTraversalRejected(t *testing.T) {
g, store, _, www := newTestGate(t)
mkStream(t, store, db.CreateStream{Name: "news"})
// A secret outside the media root, as a credible target.
writeFile(t, filepath.Join(filepath.Dir(www), "streamd.db"), "SECRET")
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
srv := httptest.NewServer(http.HandlerFunc(g.serveHLS))
defer srv.Close()
for _, p := range []string{
"/hls/news/../../streamd.db",
"/hls/news/..%2f..%2fstreamd.db",
"/hls/news/%2e%2e/%2e%2e/streamd.db",
"/hls/news/....//....//streamd.db",
"/hls/../streamd.db",
} {
req, err := http.NewRequest(http.MethodGet, srv.URL+p, nil)
if err != nil {
t.Fatal(err)
}
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
continue
}
body := make([]byte, 64)
n, _ := resp.Body.Read(body)
_ = resp.Body.Close()
if resp.StatusCode == http.StatusOK && string(body[:n]) == "SECRET" {
t.Errorf("traversal succeeded for %q", p)
}
}
}
func TestDirectoryListingRefused(t *testing.T) {
g, store, _, www := newTestGate(t)
mkStream(t, store, db.CreateStream{Name: "news"})
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
for _, p := range []string{"/hls/", "/hls/news/", "/hls/news"} {
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, p, nil))
if rec.Code == http.StatusOK {
t.Errorf("%s returned 200; a listing would enumerate every stream", p)
}
}
}
// ---------- serving ----------
func TestServesExistingPlaylistWithCacheHeaders(t *testing.T) {
g, store, _, www := newTestGate(t)
mkStream(t, store, db.CreateStream{Name: "news"})
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
writeFile(t, filepath.Join(www, "news", "seg_00001.ts"), "mediabytes")
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
if rec.Code != http.StatusOK {
t.Fatalf("playlist: %d %s", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); ct != "application/vnd.apple.mpegurl" {
t.Errorf("playlist content type = %q", ct)
}
// A live playlist must not be cached, or viewers stick on a stale window.
if cc := rec.Header().Get("Cache-Control"); cc == "" || !contains(cc, "no-cache") {
t.Errorf("playlist cache-control = %q, want no-cache", cc)
}
rec = httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/seg_00001.ts", nil))
if rec.Code != http.StatusOK {
t.Fatalf("segment: %d", rec.Code)
}
// A segment never changes under its name, so it is cacheable forever.
if cc := rec.Header().Get("Cache-Control"); !contains(cc, "immutable") {
t.Errorf("segment cache-control = %q, want immutable", cc)
}
}
func contains(h, needle string) bool {
return len(h) >= len(needle) && (h == needle || indexOf(h, needle) >= 0)
}
func indexOf(h, needle string) int {
for i := 0; i+len(needle) <= len(h); i++ {
if h[i:i+len(needle)] == needle {
return i
}
}
return -1
}
// ---------- on-demand wake ----------
func TestWakeStartsStreamAndServesOnceReady(t *testing.T) {
g, store, sup, www := newTestGate(t)
on := true
st := mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
})
// The supervisor "starts" by producing a playlist, as the real one does.
sup.onStart = func(id int64) {
go func() {
time.Sleep(150 * time.Millisecond)
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
}()
}
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
if rec.Code != http.StatusOK {
t.Fatalf("want the request held until ready, got %d %s", rec.Code, rec.Body.String())
}
if got := atomic.LoadInt32(&sup.starts); got != 1 {
t.Errorf("starts = %d, want 1", got)
}
// The wake must be on the stream's timeline.
_ = store.FlushHistory()
events, err := store.ListEvents(st.ID, 20, db.EventOnDemandWake, "")
if err != nil || len(events) == 0 {
t.Errorf("expected an ondemand_wake event, got %v (%v)", events, err)
}
}
// Twenty viewers arriving together must produce one start, not twenty.
func TestWakeIsSingleFlight(t *testing.T) {
g, store, sup, www := newTestGate(t)
on := true
mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
})
var once sync.Once
sup.onStart = func(id int64) {
once.Do(func() {
go func() {
time.Sleep(200 * time.Millisecond)
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
}()
})
}
const clients = 20
var wg sync.WaitGroup
codes := make([]int, clients)
for i := 0; i < clients; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
// Distinct client addresses, so the per-IP wake limiter does not
// mask the single-flight behaviour being tested.
req.RemoteAddr = fmt.Sprintf("10.0.0.%d:1234", i+1)
g.serveHLS(rec, req)
codes[i] = rec.Code
}(i)
}
wg.Wait()
if got := atomic.LoadInt32(&sup.starts); got != 1 {
t.Errorf("concurrent wakes started the stream %d times, want exactly 1", got)
}
for i, c := range codes {
if c != http.StatusOK {
t.Errorf("client %d got %d, want 200", i, c)
}
}
}
func TestWakeTimesOutWithRetryAfter(t *testing.T) {
g, store, sup, _ := newTestGate(t)
g.Wait = 300 * time.Millisecond
on := true
mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
})
// Starts, but never produces media.
sup.onStart = func(id int64) {}
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
if rec.Code != http.StatusServiceUnavailable {
t.Errorf("want 503 when the stream does not come up, got %d", rec.Code)
}
if ra := rec.Header().Get("Retry-After"); ra == "" {
t.Error("a 503 should carry Retry-After so players back off sensibly")
}
}
// A stream that is not marked on-demand must never be started by a request.
func TestNonOnDemandStreamIsNotWoken(t *testing.T) {
g, store, sup, _ := newTestGate(t)
yes := true
no := false
mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &no, Enabled: &yes,
})
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
if rec.Code != http.StatusNotFound {
t.Errorf("want 404, got %d", rec.Code)
}
if got := atomic.LoadInt32(&sup.starts); got != 0 {
t.Errorf("a non-on-demand stream was started %d times", got)
}
}
// Only a playlist may wake a stream. Starting one to serve a specific old
// segment would not produce that segment anyway.
func TestSegmentRequestDoesNotWake(t *testing.T) {
g, store, sup, _ := newTestGate(t)
on := true
mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
})
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/seg_00042.ts", nil))
if rec.Code != http.StatusNotFound {
t.Errorf("want 404 for a segment on a stopped stream, got %d", rec.Code)
}
if got := atomic.LoadInt32(&sup.starts); got != 0 {
t.Errorf("a segment request woke the stream %d times", got)
}
}
// An empty playlist makes a player give up, so the gate must keep waiting
// until a segment is listed.
func TestWakeWaitsForASegmentNotJustAFile(t *testing.T) {
g, store, sup, www := newTestGate(t)
g.Wait = 2 * time.Second
on := true
mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
})
sup.onStart = func(id int64) {
go func() {
// First an empty playlist, as ffmpeg briefly writes...
writeFile(t, filepath.Join(www, "news", "index.m3u8"), "#EXTM3U\n#EXT-X-VERSION:3\n")
time.Sleep(300 * time.Millisecond)
// ...then one with a segment.
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
}()
}
start := time.Now()
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
if rec.Code != http.StatusOK {
t.Fatalf("got %d", rec.Code)
}
if time.Since(start) < 250*time.Millisecond {
t.Error("served an empty playlist instead of waiting for a segment")
}
if !contains(rec.Body.String(), "#EXTINF") {
t.Error("served playlist has no segment")
}
}
// A woken stream with stale credentials must trigger a capture push, not wait
// for the agent's next poll.
func TestWakeRequestsCaptureWhenCredentialsAreStale(t *testing.T) {
g, store, sup, _ := newTestGate(t)
capReq := &fakeCapture{}
g.Capture = capReq
g.Wait = 200 * time.Millisecond
// needs_capture switches the gate to the longer CaptureWait deadline, so
// that is the one this test has to shorten.
g.CaptureWait = 300 * time.Millisecond
on := true
// Enabled, on-demand, DRM required but no key: needs_capture is true.
mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
DRMMode: db.DRMYes,
})
sup.onStart = func(id int64) {}
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
if got := atomic.LoadInt32(&capReq.n); got != 1 {
t.Errorf("capture requests = %d, want 1", got)
}
_ = rec
}
// ---------- access control ----------
func TestPrivateStreamNeedsAPrincipal(t *testing.T) {
g, store, _, www := newTestGate(t)
no := false
mkStream(t, store, db.CreateStream{Name: "internal", Public: &no})
writeFile(t, filepath.Join(www, "internal", "index.m3u8"), livePlaylist)
rec := httptest.NewRecorder()
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/internal/index.m3u8", nil))
if rec.Code != http.StatusUnauthorized {
t.Errorf("a private stream should need auth, got %d", rec.Code)
}
// With a principal attached it is served.
req := httptest.NewRequest(http.MethodGet, "/hls/internal/index.m3u8", nil)
req = req.WithContext(auth.WithPrincipal(req.Context(),
&auth.Principal{Kind: auth.ActorUser, Role: auth.RoleViewer, Name: "op"}))
rec = httptest.NewRecorder()
g.serveHLS(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("an authenticated request should be served, got %d", rec.Code)
}
}
// ---------- viewers ----------
func TestViewerCountIsDistinctClientsNotRequests(t *testing.T) {
g, store, _, www := newTestGate(t)
mkStream(t, store, db.CreateStream{Name: "news"})
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
// One client, many requests: still one viewer.
for i := 0; i < 10; i++ {
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
req.RemoteAddr = "198.51.100.7:4000"
g.serveHLS(httptest.NewRecorder(), req)
}
if got := g.ViewersFor("news"); got != 1 {
t.Errorf("viewers = %d after 10 requests from one client, want 1", got)
}
// Three clients: three viewers.
for _, ip := range []string{"198.51.100.8:1", "198.51.100.9:1"} {
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
req.RemoteAddr = ip
g.serveHLS(httptest.NewRecorder(), req)
}
if got := g.ViewersFor("news"); got != 3 {
t.Errorf("viewers = %d, want 3", got)
}
if got := g.ViewersFor("nosuchstream"); got != 0 {
t.Errorf("unknown stream viewers = %d, want 0", got)
}
}
// ---------- idle stop ----------
func TestIdleSweepStopsUnwatchedOnDemandStream(t *testing.T) {
g, store, sup, www := newTestGate(t)
on := true
idle := 1 // one second
st := mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd",
OnDemand: &on, Enabled: &on, IdleTimeoutS: &idle,
})
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
sup.running[st.ID] = true
// A viewer arrives, so it is not idle yet.
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
req.RemoteAddr = "203.0.113.5:9"
g.serveHLS(httptest.NewRecorder(), req)
g.sweepIdle()
if got := atomic.LoadInt32(&sup.stops); got != 0 {
t.Fatalf("stopped a stream that was just requested (%d stops)", got)
}
// Let the idle window pass.
time.Sleep(1100 * time.Millisecond)
g.sweepIdle()
if got := atomic.LoadInt32(&sup.stops); got != 1 {
t.Errorf("stops = %d, want 1 after the idle window", got)
}
_ = store.FlushHistory()
events, _ := store.ListEvents(st.ID, 20, db.EventIdleStop, "")
if len(events) == 0 {
t.Error("expected an idle_stop event on the timeline")
}
}
// A stream started by hand or by a schedule must not be stopped by the idle
// sweep just because nobody has pulled it through the gate.
func TestIdleSweepLeavesManuallyStartedStreams(t *testing.T) {
g, store, sup, _ := newTestGate(t)
on := true
idle := 1
st := mkStream(t, store, db.CreateStream{
Name: "council", MPD: "https://origin.test/a.mpd",
OnDemand: &on, Enabled: &on, IdleTimeoutS: &idle,
})
sup.running[st.ID] = true
time.Sleep(1100 * time.Millisecond)
g.sweepIdle()
if got := atomic.LoadInt32(&sup.stops); got != 0 {
t.Errorf("stopped a stream that was never requested through the gate (%d stops)", got)
}
}
// An always-on stream is never stopped for being idle.
func TestIdleSweepIgnoresAlwaysOnStreams(t *testing.T) {
g, store, sup, www := newTestGate(t)
yes := true
no := false
idle := 1
st := mkStream(t, store, db.CreateStream{
Name: "news", MPD: "https://origin.test/a.mpd",
OnDemand: &no, Enabled: &yes, IdleTimeoutS: &idle,
})
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
sup.running[st.ID] = true
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
req.RemoteAddr = "203.0.113.6:9"
g.serveHLS(httptest.NewRecorder(), req)
time.Sleep(1100 * time.Millisecond)
g.sweepIdle()
if got := atomic.LoadInt32(&sup.stops); got != 0 {
t.Errorf("an always-on stream was idle-stopped (%d stops)", got)
}
}
// ---------- progressive TS ----------
func TestLiveTSRequiresTheOutputToBeEnabled(t *testing.T) {
g, store, _, _ := newTestGate(t)
// Default outputs are HLS only, so /live/ must refuse.
mkStream(t, store, db.CreateStream{Name: "news"})
rec := httptest.NewRecorder()
g.serveLive(rec, httptest.NewRequest(http.MethodGet, "/live/news.ts", nil))
if rec.Code != http.StatusNotFound {
t.Errorf("want 404 when the TS output is off, got %d", rec.Code)
}
}
func TestLiveTSServesFromTheRing(t *testing.T) {
g, store, _, _ := newTestGate(t)
outputs, err := db.EncodeOutputsJSON([]db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
{ID: "ts", Format: db.FormatTS, Enabled: true},
})
if err != nil {
t.Fatal(err)
}
mkStream(t, store, db.CreateStream{Name: "news", OutputsJSON: outputs})
ring := g.Fanout.Create("news")
// A PAT packet so a joining reader has a decodable starting point.
pkt := make([]byte, 188)
pkt[0] = 0x47
pkt[3] = 0x10
for i := 4; i < 188; i++ {
pkt[i] = 0xAB
}
_, _ = ring.Write(pkt)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/live/news.ts", nil)
// Close the ring shortly so the handler returns rather than streaming
// forever.
go func() {
time.Sleep(100 * time.Millisecond)
_ = ring.Close()
}()
g.serveLive(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("got %d: %s", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); ct != "video/mp2t" {
t.Errorf("content type = %q, want video/mp2t", ct)
}
if rec.Body.Len() == 0 {
t.Error("no media was written to the client")
}
}
func TestLiveTSRejectsOddPaths(t *testing.T) {
g, store, _, _ := newTestGate(t)
mkStream(t, store, db.CreateStream{Name: "news"})
for _, p := range []string{"/live/", "/live/news", "/live/news.m3u8", "/live/../x.ts", "/live/a/b.ts"} {
rec := httptest.NewRecorder()
g.serveLive(rec, httptest.NewRequest(http.MethodGet, p, nil))
if rec.Code == http.StatusOK {
t.Errorf("%s returned 200", p)
}
}
}