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

@ -2,12 +2,15 @@ package supervisor
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/logfile"
)
type variantProc struct {
@ -15,8 +18,8 @@ type variantProc struct {
wwwDir string
index string
cmd *exec.Cmd
outLog *os.File
errLog *os.File
outLog *logfile.Writer
errLog *logfile.Writer
dead bool
}
@ -43,12 +46,16 @@ func (m *Media) startVariantPackagers(sp *streamProc, specs []db.VariantSpec) {
for _, spec := range scaled {
vp, err := m.spawnVariantFFmpeg(sp, spec)
if err != nil {
m.logf("stream %s variant %s: %v", sp.name, spec.ID, err)
m.Log.Error("variant packager failed to start",
"stream", sp.name, "variant", spec.ID, "err", err)
m.Store.Eventf(sp.id, db.EventVariantDown, db.SevError,
"variant %s failed to start: %v", spec.ID, err)
continue
}
started = append(started, vp)
m.logf("stream %s: variant %s (%dp) pid=%d → %s",
sp.name, spec.ID, spec.Height, vp.cmd.Process.Pid, vp.index)
m.Log.Info("variant packager started", "stream", sp.name, "variant", spec.ID,
"height", spec.Height, "audio_only", spec.AudioOnly,
"pid", vp.cmd.Process.Pid, "index", vp.index)
}
m.mu.Lock()
@ -65,84 +72,76 @@ func (m *Media) startVariantPackagers(sp *streamProc, specs []db.VariantSpec) {
}
func (m *Media) spawnVariantFFmpeg(sp *streamProc, spec db.VariantSpec) (*variantProc, error) {
dirName := sp.name + "-" + spec.ID
dirName := db.VariantDir(sp.name, spec.ID, spec.Height, spec.AudioOnly)
wwwDir := filepath.Join(m.DataDir, "www", dirName)
_ = os.RemoveAll(wwwDir)
if err := os.MkdirAll(wwwDir, 0o755); err != nil {
return nil, err
}
index := filepath.Join(wwwDir, "index.m3u8")
outPath := filepath.Join(m.DataDir, "logs", dirName+"-ffmpeg.out.log")
errPath := filepath.Join(m.DataDir, "logs", dirName+"-ffmpeg.err.log")
outF, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
plan := buildOutputPlan(sp.outputSpecs, wwwDir, sp.cfg, spec)
for _, d := range plan.Dirs {
if err := os.MkdirAll(d, 0o755); err != nil {
return nil, err
}
}
// One encoder, N muxers: the codec args appear once and the tee fans the
// encoded frames out. Listing several plain outputs instead would run
// libx264 once per format.
args := append(inputArgs(sp.tsPath), variantCodecArgs(spec)...)
args = append(args, plan.Args...)
errLog, err := logfile.OpenWithBanner(
filepath.Join(m.logsDir(), dirName+"-ffmpeg.err.log"),
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "ffmpeg")
if err != nil {
return nil, err
}
errF, err := os.OpenFile(errPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
_ = outF.Close()
return nil, err
ffCmd := exec.Command(m.FFmpeg, args...)
ffCmd.Stderr = errLog
var outLog *logfile.Writer
if plan.WantsTS {
// stdout is this variant's live TS, fanned out to its own ring.
ring := m.Fanout.Create(dirName)
pipe, err := ffCmd.StdoutPipe()
if err != nil {
_ = errLog.Close()
return nil, err
}
go func() {
_, _ = io.Copy(ring, pipe)
_ = ring.Close()
}()
} else {
outLog, err = logfile.Open(
filepath.Join(m.logsDir(), dirName+"-ffmpeg.out.log"),
logfile.DefaultMaxBytes, logfile.DefaultGenerations)
if err != nil {
_ = errLog.Close()
return nil, err
}
ffCmd.Stdout = outLog
}
vBitrate := spec.VideoBitrate
if vBitrate == "" {
vBitrate = "2800k"
}
aBitrate := spec.AudioBitrate
if aBitrate == "" {
aBitrate = "128k"
}
scale := fmt.Sprintf("scale=-2:%d", spec.Height)
ffArgs := []string{
"-hide_banner", "-loglevel", "warning", "-y",
"-follow", "1",
"-analyzeduration", "20M",
"-probesize", "10M",
"-fflags", "+genpts",
"-i", sp.tsPath,
"-map", "0:v:0",
"-map", "0:a:0?",
"-vf", scale,
"-c:v", "libx264",
"-preset", "veryfast",
"-tune", "zerolatency",
"-b:v", vBitrate,
"-maxrate", vBitrate,
"-bufsize", doubleBitrate(vBitrate),
"-g", "48",
"-keyint_min", "48",
"-sc_threshold", "0",
"-c:a", "aac",
"-b:a", aBitrate,
"-ac", "2",
"-f", "hls",
"-hls_time", "4",
"-hls_list_size", "15",
"-hls_flags", "delete_segments+append_list+omit_endlist+independent_segments",
"-hls_segment_type", "mpegts",
"-hls_segment_filename", filepath.Join(wwwDir, "seg_%05d.ts"),
index,
}
ffCmd := exec.Command(m.FFmpeg, ffArgs...)
ffCmd.Stdout = outF
ffCmd.Stderr = errF
hideWindow(ffCmd)
if err := ffCmd.Start(); err != nil {
_ = outF.Close()
_ = errF.Close()
_ = errLog.Close()
if outLog != nil {
_ = outLog.Close()
}
return nil, err
}
vp := &variantProc{
spec: spec,
wwwDir: wwwDir,
index: index,
index: filepath.Join(wwwDir, "index.m3u8"),
cmd: ffCmd,
outLog: outF,
errLog: errF,
outLog: outLog,
errLog: errLog,
}
go func() {
_ = ffCmd.Wait()
@ -159,24 +158,13 @@ func (m *Media) spawnVariantFFmpeg(sp *streamProc, spec db.VariantSpec) (*varian
return vp, nil
}
// doubleBitrate is the -bufsize that pairs with a -maxrate.
func doubleBitrate(b string) string {
b = strings.TrimSpace(b)
if b == "" {
n := db.BitrateBps(b)
if n <= 0 {
return "5600k"
}
num := 0
unit := ""
for i, r := range b {
if r < '0' || r > '9' {
unit = b[i:]
break
}
num = num*10 + int(r-'0')
}
if num <= 0 {
return "5600k"
}
return fmt.Sprintf("%d%s", num*2, unit)
return fmt.Sprintf("%dk", n*2/1000)
}
func (m *Media) stopVariant(vp *variantProc) {
@ -186,11 +174,10 @@ func (m *Media) stopVariant(vp *variantProc) {
if vp.cmd != nil && vp.cmd.Process != nil {
_ = killProcess(vp.cmd)
}
if vp.outLog != nil {
_ = vp.outLog.Close()
}
if vp.errLog != nil {
_ = vp.errLog.Close()
for _, w := range []*logfile.Writer{vp.outLog, vp.errLog} {
if w != nil {
_ = w.Close()
}
}
}
@ -225,9 +212,11 @@ func (m *Media) restartDeadVariants(sp *streamProc) {
for _, vp := range dead {
m.stopVariant(vp)
m.Store.Eventf(sp.id, db.EventVariantDown, db.SevWarn,
"variant %s exited; restarting it", vp.spec.ID)
fresh, err := m.spawnVariantFFmpeg(sp, vp.spec)
if err != nil {
m.logf("stream %s variant %s restart: %v", sp.name, vp.spec.ID, err)
m.Log.Error("variant restart failed", "stream", sp.name, "variant", vp.spec.ID, "err", err)
continue
}
m.mu.Lock()
@ -239,7 +228,103 @@ func (m *Media) restartDeadVariants(sp *streamProc) {
return
}
m.mu.Unlock()
m.logf("stream %s: restarted variant %s", sp.name, vp.spec.ID)
m.Log.Info("variant restarted", "stream", sp.name, "variant", vp.spec.ID)
m.Store.Eventf(sp.id, db.EventVariantUp, db.SevInfo, "variant %s back up", vp.spec.ID)
}
}
// writeMasterPlaylist publishes the ABR master listing every enabled rung.
//
// streamd writes this itself rather than asking ffmpeg to: each rung is a
// separate process writing its own playlist, so nothing but the supervisor
// knows the whole ladder. Without a master, the rung playlists are independent
// URLs and no player can switch between them.
func (m *Media) writeMasterPlaylist(sp *streamProc) {
enabled := db.EnabledVariants(sp.variantSpecs)
// With one rung there is nothing to switch between.
if len(enabled) < 2 {
return
}
// Only meaningful when an HLS-family output is actually published.
hls := false
for _, o := range db.EnabledOutputs(sp.outputSpecs) {
if o.Format == db.FormatHLS || o.Format == db.FormatCMAF {
hls = true
break
}
}
if !hls {
return
}
bw := make(map[string]int, len(enabled))
for _, v := range enabled {
bw[v.ID] = m.variantBandwidth(sp, v)
}
// Highest bandwidth first is conventional, and gives a player a sensible
// default before it has measured the connection.
sort.SliceStable(enabled, func(i, j int) bool {
return bw[enabled[i].ID] > bw[enabled[j].ID]
})
var b strings.Builder
b.WriteString("#EXTM3U\n#EXT-X-VERSION:3\n")
b.WriteString("## generated by streamd - do not edit\n")
for _, v := range enabled {
dir := db.VariantDir(sp.name, v.ID, v.Height, v.AudioOnly)
// Relative to the master's own directory, so the playlist keeps
// working behind whatever path prefix a reverse proxy adds.
rel := "index.m3u8"
if dir != sp.name {
rel = "../" + dir + "/index.m3u8"
}
switch {
case v.AudioOnly:
fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d,CODECS=\"mp4a.40.2\"\n%s\n", bw[v.ID], rel)
case v.Height > 0:
fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d,RESOLUTION=%dx%d\n%s\n",
bw[v.ID], db.VariantWidth(v.Height), v.Height, rel)
default:
// The source rung's real resolution is whatever the origin sends,
// so advertise it by bandwidth alone rather than by a guess.
fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d\n%s\n", bw[v.ID], rel)
}
}
path := filepath.Join(sp.wwwDir, "master.m3u8")
tmp := path + ".tmp"
if err := os.WriteFile(tmp, []byte(b.String()), 0o644); err != nil {
m.Log.Error("write master playlist", "stream", sp.name, "err", err)
return
}
// Rename so a player never reads a half-written master.
if err := os.Rename(tmp, path); err != nil {
_ = os.Remove(tmp)
m.Log.Error("publish master playlist", "stream", sp.name, "err", err)
return
}
m.Log.Info("master playlist published", "stream", sp.name, "rungs", len(enabled))
}
// variantBandwidth estimates a rung's peak bitrate for the master playlist.
// A scaled rung is capped by its configured bitrates; the source rung has none,
// so the measured value is used with a conservative estimate standing in until
// the stream has actually run.
func (m *Media) variantBandwidth(sp *streamProc, v db.VariantSpec) int {
if v.AudioOnly {
if bps := db.BitrateBps(v.AudioBitrate); bps > 0 {
return bps
}
return 96000
}
if v.Height > 0 {
if bps := db.BitrateBps(v.VideoBitrate) + db.BitrateBps(v.AudioBitrate); bps > 0 {
return bps
}
return 2800000
}
if st, err := m.Store.GetStream(sp.id); err == nil && st.BitrateMbps > 0.1 {
return int(st.BitrateMbps * 1e6)
}
return 6000000
}