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

@ -5,10 +5,10 @@ package servecmd
import (
"flag"
"fmt"
"log"
"log/slog"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
@ -16,9 +16,14 @@ import (
"time"
"drmdecryption/apps/streamd/internal/api"
"drmdecryption/apps/streamd/internal/auth"
"drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/deps"
"drmdecryption/apps/streamd/internal/hlsgate"
"drmdecryption/apps/streamd/internal/httpx"
"drmdecryption/apps/streamd/internal/scheduler"
"drmdecryption/apps/streamd/internal/supervisor"
"drmdecryption/apps/streamd/internal/tsfanout"
"drmdecryption/apps/streamd/internal/ui"
"drmdecryption/apps/streamd/internal/ws"
)
@ -52,29 +57,73 @@ Usage:
streamd serve [flags]
serve flags:
--bind listen address (default 0.0.0.0:8083)
--data data dir for sqlite + www + work (default .cache/streamd)
--token shared bearer token for mutating API (or STREAMD_TOKEN)
--nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download)
--ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download)
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download)
--bin-dir where to install/look for media tools (default <repo>/bin)
--skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt
--bind listen address (default 127.0.0.1:8083)
--data data dir for sqlite + www + work (default .cache/streamd)
--nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download)
--ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download)
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download)
--bin-dir where to install/look for media tools (default <repo>/bin)
--skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt
--log-level debug | info | warn | error (default info)
access control:
--admin-user create this admin account on first run (with --admin-pass)
--admin-pass password for --admin-user (prefer STREAMD_ADMIN_PASS)
--token legacy shared bearer token, treated as an admin API key
(or STREAMD_TOKEN). Prefer per-agent keys in the dashboard.
--session-ttl how long a login lasts without activity (default 12h)
--trusted-proxies CIDRs allowed to set X-Forwarded-For/-Proto (e.g. 127.0.0.1/32)
--allowed-origins extra CORS origins, comma separated (default same-origin only)
--cookie-secure always mark cookies Secure (set this behind a TLS proxy)
--audit-retain how long to keep audit rows (default 2160h / 90d)
on-demand and scheduling:
--ondemand-wait hold a viewer request this long while a stream starts
--ondemand-capture-wait as above, when credentials must be captured first
--schedule-preroll refresh credentials this far before a scheduled start
--ts-fanout-buffer live MPEG-TS bytes buffered per stream for /live/
Bind defaults to 127.0.0.1 — put a TLS-terminating reverse proxy in front and
set --trusted-proxies to that proxy. Use --bind 0.0.0.0:8083 only deliberately.
`)
}
func serveCmd(args []string) {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
bind := fs.String("bind", "0.0.0.0:8083", "listen address")
// Loopback by default. This used to be 0.0.0.0, which published the API —
// and before redaction, the Widevine keys — to the whole network.
bind := fs.String("bind", "127.0.0.1:8083", "listen address")
data := fs.String("data", "", "data directory (sqlite, www, work, logs)")
token := fs.String("token", "", "API bearer token (default: STREAMD_TOKEN env)")
token := fs.String("token", "", "legacy admin API token (default: STREAMD_TOKEN env)")
nre := fs.String("nre", "", "N_m3u8DL-RE binary")
ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary")
mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary")
binDir := fs.String("bin-dir", "", "directory for media tool binaries (default <repo>/bin)")
skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools")
logLevel := fs.String("log-level", "info", "debug | info | warn | error")
adminUser := fs.String("admin-user", "", "create this admin account on first run")
adminPass := fs.String("admin-pass", "", "password for --admin-user (or STREAMD_ADMIN_PASS)")
sessionTTL := fs.Duration("session-ttl", auth.DefaultSessionTTL, "login lifetime without activity")
trustedProxies := fs.String("trusted-proxies", "", "CIDRs allowed to set X-Forwarded-For")
allowedOrigins := fs.String("allowed-origins", "", "extra CORS origins, comma separated")
cookieSecure := fs.Bool("cookie-secure", false, "always mark cookies Secure")
auditRetain := fs.Duration("audit-retain", 90*24*time.Hour, "how long to keep audit rows")
tsBuffer := fs.Int("ts-fanout-buffer", tsfanout.DefaultBufferBytes,
"bytes of live MPEG-TS buffered per stream for /live/<name>.ts")
ondemandWait := fs.Duration("ondemand-wait", hlsgate.DefaultWait,
"how long to hold a viewer request while an on-demand stream starts")
ondemandCaptureWait := fs.Duration("ondemand-capture-wait", hlsgate.DefaultCaptureWait,
"as --ondemand-wait, but when credentials must be captured first")
preroll := fs.Duration("schedule-preroll", scheduler.DefaultPreroll,
"how far ahead of a scheduled start to refresh credentials")
_ = fs.Parse(args)
lg := newLogger(*logLevel)
slog.SetDefault(lg)
// deps still wants a *log.Logger; bridge it onto the same handler so one
// stream of output stays coherent.
depsLog := slog.NewLogLogger(lg.Handler(), slog.LevelInfo)
dataDir := *data
if dataDir == "" {
dataDir = filepath.Join(".", ".cache", "streamd")
@ -84,159 +133,255 @@ func serveCmd(args []string) {
tok = os.Getenv("STREAMD_TOKEN")
}
trust := httpx.Trust{}
if nets, err := httpx.ParseCIDRs(*trustedProxies); err != nil {
lg.Error("invalid --trusted-proxies", "err", err)
os.Exit(2)
} else {
trust.Proxies = nets
}
origins := splitList(*allowedOrigins)
for _, sub := range []string{"www", "work", "logs"} {
if err := os.MkdirAll(filepath.Join(dataDir, sub), 0o755); err != nil {
log.Fatal(err)
lg.Error("create data dir", "err", err)
os.Exit(1)
}
}
store, err := db.Open(dataDir)
if err != nil {
log.Fatalf("db: %v", err)
lg.Error("open database", "err", err)
os.Exit(1)
}
defer store.Close()
authStore, err := auth.New(store.DB, tok)
if err != nil {
lg.Error("init auth tables", "err", err)
os.Exit(1)
}
mw := auth.NewMiddleware(authStore, trust, *cookieSecure)
mw.SessionTTL = *sessionTTL
authH := auth.NewHandler(authStore, mw, lg)
bootstrapAdmin(lg, authStore, authH, *adminUser, *adminPass)
depStatus, _ := deps.Ensure(deps.Options{
BinDir: *binDir,
SkipDownload: *skipDeps,
Log: log.Default(),
Log: depsLog,
}, *nre, *ffmpeg, *mp4decrypt)
nrePath := depStatus.NRE
ffPath := depStatus.FFmpeg
decPath := depStatus.MP4Decrypt
fanout := tsfanout.NewSet(*tsBuffer)
hub := ws.NewHub(store, lg, origins)
sup := supervisor.NewMedia(supervisor.Options{
Store: store,
DataDir: dataDir,
NRE: nrePath,
FFmpeg: ffPath,
MP4Decrypt: decPath,
Log: log.Default(),
NRE: depStatus.NRE,
FFmpeg: depStatus.FFmpeg,
MP4Decrypt: depStatus.MP4Decrypt,
Log: lg,
Fanout: fanout,
Notifier: hub,
})
defer sup.Close()
gate := hlsgate.New(hlsgate.Config{
Store: store,
WWWRoot: filepath.Join(dataDir, "www"),
Sup: sup,
Fanout: fanout,
Capture: hub,
Trust: trust,
Log: lg,
Wait: *ondemandWait,
CaptureWait: *ondemandCaptureWait,
})
// The supervisor records viewer counts in its metrics series, and the
// gate is what knows them.
sup.ViewersFn = gate.ViewersFor
sched := scheduler.New(store, sup, hub, lg, *preroll)
apiH := &api.Handler{
Store: store,
Token: tok,
Auth: authStore,
Trust: trust,
Supervisor: sup,
Capture: hub,
StartedAt: time.Now(),
Deps: depStatus,
WWWRoot: filepath.Join(dataDir, "www"),
LogRoot: filepath.Join(dataDir, "logs"),
Notifier: hub,
Viewers: gate,
Scheduler: sched,
Log: lg,
}
hub := ws.NewHub(store, tok, log.Default())
mux := http.NewServeMux()
apiH.Mount(mux)
authH.Mount(mux)
hub.Mount(mux)
// The media paths are served by the gate, not a bare FileServer: it wakes
// on-demand streams, counts viewers, sets cache headers per file kind and
// refuses directory listings.
gate.Mount(mux)
mux.Handle("/", ui.Handler())
mux.Handle("/static/", http.StripPrefix("/static/", ui.Static()))
mux.Handle("/hls/", http.StripPrefix("/hls/", http.FileServer(http.Dir(filepath.Join(dataDir, "www")))))
// Order matters: the access log wraps everything so it sees final statuses,
// then CORS and security headers, then principal resolution, then the mux.
var handler http.Handler = mux
handler = mw.Attach(handler)
handler = httpx.SecurityHeaders(trust, handler)
handler = httpx.CORS(origins, handler)
handler = httpx.AccessLog(lg, trust, handler)
srv := &http.Server{
Addr: *bind,
Handler: withCORS(mux),
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
// No WriteTimeout: HLS responses, SSE log tails and websockets are all
// long-lived and a write deadline would cut them off.
IdleTimeout: 120 * time.Second,
}
log.Printf("streamd listening on http://%s data=%s", *bind, dataDir)
log.Printf("media: nre=%s", nrePath)
log.Printf("media: ffmpeg=%s", ffPath)
log.Printf("media: mp4decrypt=%s", decPath)
log.Printf("ws: agents=/ws/agent ui=/ws/ui")
if tok == "" {
log.Printf("warning: no --token / STREAMD_TOKEN set; mutating API is open")
lg.Info("streamd listening", "addr", *bind, "data", dataDir)
lg.Info("media tools", "nre", depStatus.NRE, "ffmpeg", depStatus.FFmpeg, "mp4decrypt", depStatus.MP4Decrypt)
if len(trust.Proxies) == 0 {
lg.Info("no --trusted-proxies set: forwarded headers are ignored and client IPs come from the peer address")
}
if tok != "" {
lg.Warn("--token / STREAMD_TOKEN is in use as an admin API key; create per-agent keys in the dashboard and drop it")
}
if host, _, err := net.SplitHostPort(*bind); err == nil {
switch strings.ToLower(host) {
case "127.0.0.1", "localhost", "::1":
// Loopback is the safe default.
default:
lg.Warn("listening on a non-loopback address — the dashboard and API are reachable on the network; put a TLS reverse proxy in front, or bind 127.0.0.1",
"bind", *bind)
}
}
stopBG := make(chan struct{})
go hub.RunExpireLoop(stopBG)
// Resume enabled streams that already have credentials (staggered).
go func() {
time.Sleep(500 * time.Millisecond)
list, err := store.ListStreams()
if err != nil {
return
}
for _, st := range list {
if !st.Enabled || strings.TrimSpace(st.MPD) == "" {
continue
}
mpd := strings.ToLower(strings.TrimSpace(st.MPD))
if !strings.HasPrefix(mpd, "http://") && !strings.HasPrefix(mpd, "https://") {
log.Printf("auto-start skip %s: mpd is not an http(s) URL", st.Name)
continue
}
log.Printf("auto-start enabled stream %s", st.Name)
func(id int64, name string) {
defer func() {
if r := recover(); r != nil {
log.Printf("auto-start %s panic: %v", name, r)
}
}()
if err := sup.Start(id); err != nil {
log.Printf("auto-start %s: %v", name, err)
}
}(st.ID, st.Name)
time.Sleep(1500 * time.Millisecond)
}
}()
go authStore.RunMaintenance(stopBG, *auditRetain)
go store.RunHistoryMaintenance(stopBG)
go gate.RunIdleLoop(stopBG)
go sched.Run(stopBG)
go resumeEnabledStreams(lg, store, sup)
go func() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
<-ch
log.Printf("shutting down…")
lg.Info("shutting down")
close(stopBG)
sup.Close()
_ = authStore.FlushAudit()
_ = srv.Close()
}()
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
lg.Error("listen", "err", err)
os.Exit(1)
}
}
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Streamd-Token")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
func newLogger(level string) *slog.Logger {
var lv slog.Level
switch strings.ToLower(strings.TrimSpace(level)) {
case "debug":
lv = slog.LevelDebug
case "warn", "warning":
lv = slog.LevelWarn
case "error":
lv = slog.LevelError
default:
lv = slog.LevelInfo
}
// A text handler keeps the console output as readable as the old
// log.Printf lines while giving every record structured attributes.
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lv}))
}
// bootstrapAdmin creates the first account from flags when asked, or prints a
// one-time setup token so the dashboard can create it.
func bootstrapAdmin(lg *slog.Logger, store *auth.Store, h *auth.Handler, user, pass string) {
n, err := store.CountUsers()
if err != nil {
lg.Error("count users", "err", err)
return
}
if n > 0 {
h.SetSetupToken("")
return
}
if pass == "" {
pass = os.Getenv("STREAMD_ADMIN_PASS")
}
if user != "" && pass != "" {
if _, err := store.CreateUser(user, pass, auth.RoleAdmin); err != nil {
lg.Error("create admin account", "err", err)
} else {
lg.Info("created initial admin account", "user", strings.ToLower(strings.TrimSpace(user)))
h.SetSetupToken("")
return
}
next.ServeHTTP(w, r)
})
}
tok := auth.NewSetupToken()
h.SetSetupToken(tok)
lg.Warn("no accounts exist yet — open the dashboard and use this one-time setup token to create the first admin",
"setup_token", tok)
}
func firstExisting(explicit string, candidates ...string) string {
if explicit != "" {
if st, err := os.Stat(explicit); err == nil && !st.IsDir() {
return explicit
}
// still return explicit so exec fails clearly if user set a bad path
if filepath.IsAbs(explicit) || containsSep(explicit) {
return explicit
}
// resumeEnabledStreams restarts streams that were running before a restart.
// On-demand streams are deliberately left stopped: a viewer's first request
// starts them, which is the whole point.
func resumeEnabledStreams(lg *slog.Logger, store *db.Store, sup *supervisor.Media) {
time.Sleep(500 * time.Millisecond)
list, err := store.ListStreams()
if err != nil {
return
}
for _, c := range candidates {
if c == "" {
for _, st := range list {
if !st.Enabled || strings.TrimSpace(st.MPD) == "" {
continue
}
if st, err := os.Stat(c); err == nil && !st.IsDir() {
return c
if st.OnDemand {
lg.Info("auto-start skipped: on-demand stream waits for a viewer", "stream", st.Name)
continue
}
if p, err := execLookPath(c); err == nil {
return p
mpd := strings.ToLower(strings.TrimSpace(st.MPD))
if !strings.HasPrefix(mpd, "http://") && !strings.HasPrefix(mpd, "https://") {
lg.Warn("auto-start skipped: mpd is not an http(s) URL", "stream", st.Name)
continue
}
lg.Info("auto-starting enabled stream", "stream", st.Name)
func(id int64, name string) {
defer func() {
if r := recover(); r != nil {
lg.Error("auto-start panicked", "stream", name, "panic", r)
}
}()
if err := sup.Start(id); err != nil {
lg.Error("auto-start failed", "stream", name, "err", err)
}
}(st.ID, st.Name)
time.Sleep(1500 * time.Millisecond)
}
}
func splitList(s string) []string {
var out []string
for _, p := range strings.Split(s, ",") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return explicit
}
func containsSep(s string) bool {
return filepath.Base(s) != s
}
func execLookPath(file string) (string, error) {
return exec.LookPath(file)
return out
}