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

@ -9,15 +9,19 @@ import (
"drmdecryption/repo"
)
// streamSettings are the downloader knobs for one stream. They come from the
// stream's app module when it declares them, so the supervisor never has to
// guess from an app name or a stream name.
// streamSettings are the downloader and packager knobs for one stream. They
// come from the stream row first, then the stream's app module, then the
// installation-wide settings, then neutral defaults — so the supervisor never
// has to guess from an app name or a stream name.
type streamSettings struct {
VideoSelect string
AudioSelect string
Rewriter string
LiveWait int
TSReadyBytes int64
// HLSTime and HLSListSize shape every output's segmenting.
HLSTime int
HLSListSize int
// IsHLS drives packaging choices that depend on the manifest format.
IsHLS bool
}
@ -31,15 +35,20 @@ const (
hlsLiveWait = 6
)
// settingsFor resolves a stream's downloader settings: the app module's
// declarations first, then the stream row, then neutral defaults.
func settingsFor(st db.Stream) streamSettings {
// settingsFor resolves a stream's settings. globals is the installation-wide
// layer, read from the settings table; pass the zero value when there is none.
func settingsFor(st db.Stream, globals db.PackagerSettings) streamSettings {
// Per-stream overrides win over everything.
own := db.ParsePackagerSettings(st.SettingsJSON)
s := streamSettings{
VideoSelect: strings.TrimSpace(st.VideoSelect),
AudioSelect: strings.TrimSpace(st.AudioSelect),
Rewriter: strings.TrimSpace(st.Rewriter),
LiveWait: defaultLiveWait,
TSReadyBytes: defaultTSReadyBytes,
LiveWait: own.LiveWait,
TSReadyBytes: int64(own.TSReadyBytes),
HLSTime: own.HLSTime,
HLSListSize: own.HLSListSize,
IsHLS: isHLS(st),
}
if sd := streamDefaultsFor(st.App); sd != nil {
@ -52,21 +61,53 @@ func settingsFor(st db.Stream) streamSettings {
if s.Rewriter == "" {
s.Rewriter = sd.RewriterName()
}
if n := sd.LiveWaitSeconds(); n > 0 {
s.LiveWait = n
if s.LiveWait == 0 {
if n := sd.LiveWaitSeconds(); n > 0 {
s.LiveWait = n
}
}
if n := sd.TSReadyBytes(); n > 0 {
s.TSReadyBytes = n
if s.TSReadyBytes == 0 {
if n := sd.TSReadyBytes(); n > 0 {
s.TSReadyBytes = n
}
}
}
// Installation-wide settings.
if s.LiveWait == 0 {
s.LiveWait = globals.LiveWait
}
if s.TSReadyBytes == 0 {
s.TSReadyBytes = int64(globals.TSReadyBytes)
}
if s.HLSTime == 0 {
s.HLSTime = globals.HLSTime
}
if s.HLSListSize == 0 {
s.HLSListSize = globals.HLSListSize
}
// An HLS source needs a longer wait and a bigger buffer before probing,
// but only when nothing more specific asked otherwise.
if s.IsHLS {
if s.LiveWait == defaultLiveWait {
if s.LiveWait == 0 {
s.LiveWait = hlsLiveWait
}
if s.TSReadyBytes == defaultTSReadyBytes {
if s.TSReadyBytes == 0 {
s.TSReadyBytes = hlsTSReadyBytes
}
}
// Neutral defaults.
if s.LiveWait == 0 {
s.LiveWait = defaultLiveWait
}
if s.TSReadyBytes == 0 {
s.TSReadyBytes = defaultTSReadyBytes
}
if s.HLSTime == 0 {
s.HLSTime = defaultHLSTime
}
if s.HLSListSize == 0 {
s.HLSListSize = defaultHLSListSize
}
if s.VideoSelect == "" {
s.VideoSelect = "for=best"
}

View file

@ -44,7 +44,7 @@ func register(t *testing.T, f *fakeApp) {
func TestSettingsComeFromTheAppModule(t *testing.T) {
register(t, &fakeApp{name: "fakedash", rewriter: "fakedash", liveWait: 3, tsBytes: 111})
got := settingsFor(db.Stream{App: "fakedash", MPD: "https://origin.test/manifest.mpd"})
got := settingsFor(db.Stream{App: "fakedash", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
if got.Rewriter != "fakedash" {
t.Errorf("rewriter = %q, want fakedash", got.Rewriter)
}
@ -67,7 +67,7 @@ func TestStoredSettingsOverrideTheModule(t *testing.T) {
MPD: "https://origin.test/manifest.mpd",
VideoSelect: "res=1920x1080:for=best",
Rewriter: "none",
})
}, db.PackagerSettings{})
if got.VideoSelect != "res=1920x1080:for=best" {
t.Errorf("video select = %q, want the stored value", got.VideoSelect)
}
@ -78,7 +78,7 @@ func TestStoredSettingsOverrideTheModule(t *testing.T) {
// An unknown app must not inherit any provider's preferences.
func TestUnknownAppGetsNeutralDefaults(t *testing.T) {
got := settingsFor(db.Stream{App: "nosuchapp", MPD: "https://origin.test/manifest.mpd"})
got := settingsFor(db.Stream{App: "nosuchapp", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
if got.VideoSelect != "for=best" || got.AudioSelect != "for=best" {
t.Errorf("selectors = %q / %q, want for=best", got.VideoSelect, got.AudioSelect)
}
@ -93,7 +93,7 @@ func TestUnknownAppGetsNeutralDefaults(t *testing.T) {
// HLS gets more buffering and a longer live wait, by manifest shape and not by
// matching a stream name.
func TestHLSDetectionByManifestShape(t *testing.T) {
got := settingsFor(db.Stream{App: "", MPD: "https://cdn.test/x/playlist-hls-dvr.m3u8"})
got := settingsFor(db.Stream{App: "", MPD: "https://cdn.test/x/playlist-hls-dvr.m3u8"}, db.PackagerSettings{})
if !got.IsHLS {
t.Fatal("an .m3u8 manifest should be detected as HLS")
}
@ -104,7 +104,7 @@ func TestHLSDetectionByManifestShape(t *testing.T) {
t.Errorf("tsReadyBytes = %d, want %d", got.TSReadyBytes, hlsTSReadyBytes)
}
// The old code keyed this off stream names like "tg4"/"cula"/"plus".
named := settingsFor(db.Stream{Name: "tg4-ioi", MPD: "https://origin.test/manifest.mpd"})
named := settingsFor(db.Stream{Name: "tg4-ioi", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
if named.TSReadyBytes != defaultTSReadyBytes {
t.Error("buffering must not be chosen by stream name any more")
}
@ -113,7 +113,7 @@ func TestHLSDetectionByManifestShape(t *testing.T) {
// A module's rewriter is only used if it registered one under that name.
func TestRewriterLookupGatesTheRewrite(t *testing.T) {
register(t, &fakeApp{name: "fakeunregistered", rewriter: "fakeunregistered"})
cfg := settingsFor(db.Stream{App: "fakeunregistered", MPD: "https://origin.test/manifest.mpd"})
cfg := settingsFor(db.Stream{App: "fakeunregistered", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
if _, needed := mpd.Lookup(cfg.Rewriter); needed {
t.Error("an unregistered rewriter name must not trigger a rewrite")
}
@ -127,3 +127,63 @@ type stubRewriter struct{}
func (stubRewriter) Name() string { return "fakeunregistered" }
func (stubRewriter) Rewrite(in []byte, _ string) ([]byte, error) { return in, nil }
// The resolution chain is: stream row, then app module, then the
// installation-wide settings, then the compiled-in defaults.
func TestGlobalSettingsSitBelowTheModule(t *testing.T) {
globals := db.PackagerSettings{HLSTime: 6, HLSListSize: 30, LiveWait: 9, TSReadyBytes: 999}
// Nothing more specific: the global layer applies.
got := settingsFor(db.Stream{MPD: "https://origin.test/manifest.mpd"}, globals)
if got.HLSTime != 6 || got.HLSListSize != 30 {
t.Errorf("hls_time=%d list_size=%d, want the global values", got.HLSTime, got.HLSListSize)
}
if got.LiveWait != 9 || got.TSReadyBytes != 999 {
t.Errorf("liveWait=%d tsReady=%d, want the global values", got.LiveWait, got.TSReadyBytes)
}
// A module declaration beats the global layer.
register(t, &fakeApp{name: "fakeglobals", rewriter: "none", liveWait: 4, tsBytes: 222})
got = settingsFor(db.Stream{App: "fakeglobals", MPD: "https://origin.test/manifest.mpd"}, globals)
if got.LiveWait != 4 || got.TSReadyBytes != 222 {
t.Errorf("liveWait=%d tsReady=%d, want the module values", got.LiveWait, got.TSReadyBytes)
}
// ...but the global packager knobs still apply, since no module declares them.
if got.HLSTime != 6 {
t.Errorf("hls_time = %d, want the global 6", got.HLSTime)
}
}
// A per-stream settings_json override beats everything else.
func TestPerStreamSettingsWinOverAllLayers(t *testing.T) {
register(t, &fakeApp{name: "fakeperstream", rewriter: "none", liveWait: 4, tsBytes: 222})
globals := db.PackagerSettings{HLSTime: 6, HLSListSize: 30, LiveWait: 9}
got := settingsFor(db.Stream{
App: "fakeperstream",
MPD: "https://origin.test/manifest.mpd",
SettingsJSON: `{"hls_time":2,"hls_list_size":8,"live_wait":1}`,
}, globals)
if got.HLSTime != 2 || got.HLSListSize != 8 || got.LiveWait != 1 {
t.Errorf("got hls_time=%d list_size=%d live_wait=%d, want the per-stream 2/8/1",
got.HLSTime, got.HLSListSize, got.LiveWait)
}
}
// Nonsense in settings_json must be ignored rather than handed to ffmpeg,
// where a zero segment duration would produce an unplayable stream.
func TestInsaneSettingsAreIgnored(t *testing.T) {
for _, raw := range []string{
`{"hls_time":0}`, `{"hls_time":-5}`, `{"hls_time":9999}`,
`{"hls_list_size":0}`, `not json at all`, ``,
} {
got := settingsFor(db.Stream{
MPD: "https://origin.test/manifest.mpd", SettingsJSON: raw,
}, db.PackagerSettings{})
if got.HLSTime != defaultHLSTime {
t.Errorf("settings_json %q gave hls_time=%d, want the default %d", raw, got.HLSTime, defaultHLSTime)
}
if got.HLSListSize != defaultHLSListSize {
t.Errorf("settings_json %q gave list_size=%d, want the default %d", raw, got.HLSListSize, defaultHLSListSize)
}
}
}

View file

@ -0,0 +1,218 @@
package supervisor
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"drmdecryption/apps/streamd/internal/db"
)
// These tests run the real ffmpeg against the real generated command line.
// The unit tests prove the arguments look right; only ffmpeg can prove it
// accepts them — tee's escaping rules in particular are easy to get subtly
// wrong in a way no amount of string assertion would catch.
//
// Skipped when ffmpeg is not installed, and under -short.
func ffmpegPath(t *testing.T) string {
t.Helper()
if testing.Short() {
t.Skip("skipping ffmpeg integration test in short mode")
}
for _, cand := range []string{os.Getenv("FFMPEG_PATH"), "ffmpeg"} {
if cand == "" {
continue
}
if p, err := exec.LookPath(cand); err == nil {
return p
}
}
t.Skip("ffmpeg not found on PATH; skipping integration test")
return ""
}
// makeTestTS renders a few seconds of synthetic audio and video to an MPEG-TS
// file, standing in for what the downloader produces.
func makeTestTS(t *testing.T, ff, dir string, seconds int) string {
t.Helper()
out := filepath.Join(dir, "source.ts")
cmd := exec.Command(ff,
"-hide_banner", "-loglevel", "error", "-y",
"-f", "lavfi", "-i", "testsrc2=size=640x360:rate=25",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000",
"-t", strconv.Itoa(seconds),
"-c:v", "libx264", "-preset", "ultrafast", "-g", "25", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "96k",
"-f", "mpegts", out,
)
if b, err := cmd.CombinedOutput(); err != nil {
t.Skipf("could not render a test source (%v): %s", err, b)
}
return out
}
// runPlan runs one variant's full generated command against src and returns
// the process's CPU time.
func runPlan(t *testing.T, ff, src, wwwDir string, spec db.VariantSpec, outputs []db.OutputSpec) (time.Duration, string) {
t.Helper()
if err := os.MkdirAll(wwwDir, 0o755); err != nil {
t.Fatal(err)
}
cfg := streamSettings{HLSTime: 2, HLSListSize: 5}
plan := buildOutputPlan(outputs, wwwDir, cfg, spec)
for _, d := range plan.Dirs {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
// The real supervisor passes "-follow 1" to track a growing file; here the
// source is complete, so read it once and exit.
args := []string{"-hide_banner", "-loglevel", "error", "-y", "-i", src}
args = append(args, variantCodecArgs(spec)...)
args = append(args, plan.Args...)
cmd := exec.Command(ff, args...)
// Capture stderr explicitly rather than with CombinedOutput: when the TS
// output is on, stdout carries media and cannot also collect diagnostics.
var stderr bytes.Buffer
cmd.Stderr = &stderr
if plan.WantsTS {
sink, err := os.Create(filepath.Join(wwwDir, "pipe.ts"))
if err != nil {
t.Fatal(err)
}
defer sink.Close()
cmd.Stdout = sink
}
err := cmd.Run()
out := stderr.String()
if err != nil {
t.Fatalf("ffmpeg rejected the generated command: %v\nargs: %q\nstderr: %s", err, args, out)
}
var cpu time.Duration
if cmd.ProcessState != nil {
cpu = cmd.ProcessState.UserTime() + cmd.ProcessState.SystemTime()
}
return cpu, out
}
// A single HLS output must work: this is the command streamd has always run.
func TestFFmpegAcceptsSingleHLSOutput(t *testing.T) {
ff := ffmpegPath(t)
dir := t.TempDir()
src := makeTestTS(t, ff, dir, 4)
www := filepath.Join(dir, "www", "news")
_, _ = runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
})
mustExist(t, filepath.Join(www, "index.m3u8"))
mustGlob(t, filepath.Join(www, "seg_*.ts"))
}
// The real test of the tee spec: ffmpeg must accept it and every output must
// actually be written.
func TestFFmpegAcceptsTeeWithEveryFormat(t *testing.T) {
ff := ffmpegPath(t)
dir := t.TempDir()
src := makeTestTS(t, ff, dir, 4)
www := filepath.Join(dir, "www", "news")
_, out := runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
{ID: "dash", Format: db.FormatDASH, Enabled: true},
{ID: "ts", Format: db.FormatTS, Enabled: true},
})
// onfail=ignore means a broken leg is silent, so check the files rather
// than trusting the exit status.
mustExist(t, filepath.Join(www, "index.m3u8"))
mustGlob(t, filepath.Join(www, "seg_*.ts"))
mustExist(t, filepath.Join(www, "cmaf", "index.m3u8"))
mustGlob(t, filepath.Join(www, "cmaf", "*.m4s"))
mustExist(t, filepath.Join(www, "cmaf", "init.mp4"))
mustExist(t, filepath.Join(www, "dash", "index.mpd"))
mustNonEmpty(t, filepath.Join(www, "pipe.ts"))
if strings.Contains(strings.ToLower(out), "invalid argument") {
t.Errorf("ffmpeg complained about the tee spec: %s", out)
}
}
// A path with a drive letter and a space is where tee escaping actually bites.
func TestFFmpegAcceptsTeeWithAwkwardPath(t *testing.T) {
ff := ffmpegPath(t)
dir := t.TempDir()
src := makeTestTS(t, ff, dir, 3)
// A space in a directory name, which is ordinary on Windows.
www := filepath.Join(dir, "www root", "city news")
_, _ = runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
{ID: "dash", Format: db.FormatDASH, Enabled: true},
})
mustExist(t, filepath.Join(www, "index.m3u8"))
mustExist(t, filepath.Join(www, "dash", "index.mpd"))
}
// The headline efficiency claim: adding formats to a transcoded rung must
// share one encode. Three formats through tee should cost far less than three
// times a single format — if it is ~3x, the encoder is running per output.
func TestTeeEncodesOnceNotPerOutput(t *testing.T) {
ff := ffmpegPath(t)
dir := t.TempDir()
// Long enough that encoding dominates process start-up cost.
src := makeTestTS(t, ff, dir, 8)
hd := db.VariantSpec{ID: "hd", Label: "HD", Enabled: true, Height: 720,
VideoBitrate: "2800k", AudioBitrate: "128k"}
oneCPU, _ := runPlan(t, ff, src, filepath.Join(dir, "one"), hd, []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
})
threeCPU, _ := runPlan(t, ff, src, filepath.Join(dir, "three"), hd, []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
{ID: "dash", Format: db.FormatDASH, Enabled: true},
})
if oneCPU <= 0 || threeCPU <= 0 {
t.Skipf("no CPU accounting available (one=%v three=%v)", oneCPU, threeCPU)
}
ratio := float64(threeCPU) / float64(oneCPU)
t.Logf("CPU: 1 format = %v, 3 formats = %v (ratio %.2fx)", oneCPU, threeCPU, ratio)
// Muxing three times instead of once is not free, but it is nothing like
// encoding three times. Anything approaching 3x means tee is not in use.
if ratio > 2.0 {
t.Errorf("3 formats cost %.2fx the CPU of 1 — the encoder appears to be running "+
"per output rather than once through tee", ratio)
}
}
func mustExist(t *testing.T, path string) {
t.Helper()
st, err := os.Stat(path)
if err != nil {
t.Errorf("expected %s to exist: %v", path, err)
return
}
if st.Size() == 0 {
t.Errorf("%s is empty", path)
}
}
func mustNonEmpty(t *testing.T, path string) {
t.Helper()
st, err := os.Stat(path)
if err != nil || st.Size() == 0 {
t.Errorf("expected %s to have content (err=%v)", path, err)
}
}
func mustGlob(t *testing.T, pattern string) {
t.Helper()
m, err := filepath.Glob(pattern)
if err != nil || len(m) == 0 {
t.Errorf("expected files matching %s (err=%v)", pattern, err)
}
}

View file

@ -4,7 +4,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"log/slog"
"os"
"os/exec"
"path/filepath"
@ -15,45 +15,69 @@ import (
"time"
"drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/logfile"
"drmdecryption/apps/streamd/internal/tsfanout"
"drmdecryption/mpd"
)
// Media runs N_m3u8DL-RE + ffmpeg HLS packager per stream into DataDir/www/<name>/.
// Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into
// DataDir/www/<name>/ and, when the progressive TS output is on, into a
// shared in-memory ring.
type Media struct {
Store *db.Store
DataDir string
NRE string
FFmpeg string
MP4Decrypt string
Log *log.Logger
Log *slog.Logger
// Fanout holds the live progressive-TS rings, when that output is on.
Fanout *tsfanout.Set
// Notifier pushes health changes to the dashboard. Optional.
Notifier Notifier
// ViewersFn reports the live client count for a stream, for the metrics
// series. Optional.
ViewersFn func(streamName string) int
mu sync.Mutex
procs map[int64]*streamProc
stopMon chan struct{}
}
// Notifier is the subset of the websocket hub the supervisor needs.
type Notifier interface {
NotifyRuntime(name, health string)
NotifyStreamChanged(name, reason string)
}
type streamProc struct {
id int64
name string
nre *exec.Cmd
ffmpeg *exec.Cmd
started time.Time
workDir string
wwwDir string
tsPath string
hlsIndex string
nreLog *os.File
ffOutLog *os.File
ffErrLog *os.File
stopping bool
mpdProxy *mpd.LocalServer
nreDead bool
ffDead bool
variants []*variantProc
id int64
name string
nre *exec.Cmd
ffmpeg *exec.Cmd
started time.Time
workDir string
wwwDir string
tsPath string
hlsIndex string
nreLog *logfile.Writer
ffOutLog *logfile.Writer
ffErrLog *logfile.Writer
stopping bool
mpdProxy *mpd.LocalServer
nreDead bool
ffDead bool
variants []*variantProc
variantSpecs []db.VariantSpec
outputSpecs []db.OutputSpec
cfg streamSettings
// tsReadyBytes is how much muxed output to buffer before probing, from the
// stream's app module.
tsReadyBytes int64
// lastHealth lets the supervisor report only health transitions.
lastHealth string
// lastTSSize / lastTSAt back the bitrate estimate.
lastTSSize int64
lastTSAt time.Time
}
// Options for constructing the media supervisor.
@ -63,13 +87,20 @@ type Options struct {
NRE string
FFmpeg string
MP4Decrypt string
Log *log.Logger
Log *slog.Logger
Fanout *tsfanout.Set
Notifier Notifier
ViewersFn func(streamName string) int
}
func NewMedia(opt Options) *Media {
lg := opt.Log
if lg == nil {
lg = log.Default()
lg = slog.Default()
}
fan := opt.Fanout
if fan == nil {
fan = tsfanout.NewSet(tsfanout.DefaultBufferBytes)
}
m := &Media{
Store: opt.Store,
@ -78,6 +109,9 @@ func NewMedia(opt Options) *Media {
FFmpeg: opt.FFmpeg,
MP4Decrypt: opt.MP4Decrypt,
Log: lg,
Fanout: fan,
Notifier: opt.Notifier,
ViewersFn: opt.ViewersFn,
procs: map[int64]*streamProc{},
stopMon: make(chan struct{}),
}
@ -98,34 +132,33 @@ func (m *Media) Close() {
}
}
// Running reports whether a stream currently has a live worker. The HLS gate
// uses this to decide whether a request needs to wake the stream.
func (m *Media) Running(id int64) bool {
m.mu.Lock()
defer m.mu.Unlock()
sp, ok := m.procs[id]
return ok && !sp.stopping
}
func (m *Media) logsDir() string { return filepath.Join(m.DataDir, "logs") }
func (m *Media) Start(id int64) error {
st, err := m.Store.GetStream(id)
if err != nil {
return err
}
if strings.TrimSpace(st.MPD) == "" {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + st.Name + "/index.m3u8",
LastError: "missing mpd — paste a manifest URL (keys optional for clear streams)",
})
m.fail(id, st.Name, "missing mpd — paste a manifest URL (keys optional for clear streams)")
return fmt.Errorf("missing mpd")
}
mpdURL := strings.TrimSpace(st.MPD)
if !strings.HasPrefix(strings.ToLower(mpdURL), "http://") && !strings.HasPrefix(strings.ToLower(mpdURL), "https://") {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + st.Name + "/index.m3u8",
LastError: "mpd must be an http(s) URL",
})
m.fail(id, st.Name, "mpd must be an http(s) URL")
return fmt.Errorf("invalid mpd url")
}
if m.NRE == "" || m.FFmpeg == "" {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + st.Name + "/index.m3u8",
LastError: "NRE or ffmpeg binary not configured",
})
m.fail(id, st.Name, "NRE or ffmpeg binary not configured")
return fmt.Errorf("NRE or ffmpeg not configured")
}
@ -144,13 +177,14 @@ func (m *Media) Start(id int64) error {
workDir := filepath.Join(m.DataDir, "work", st.Name)
wwwDir := filepath.Join(m.DataDir, "www", st.Name)
variantSpecs := db.ParseVariantsJSON(st.VariantsJSON)
outputSpecs := db.ParseOutputsJSON(st.OutputsJSON)
// Fresh dirs each start — leftover decrypted segments make NRE File.Move fail.
_ = os.RemoveAll(wwwDir)
_ = os.RemoveAll(workDir)
for _, v := range db.ScaledVariants(variantSpecs) {
_ = os.RemoveAll(filepath.Join(m.DataDir, "www", st.Name+"-"+v.ID))
_ = os.RemoveAll(filepath.Join(m.DataDir, "www", db.VariantDir(st.Name, v.ID, v.Height, v.AudioOnly)))
}
for _, d := range []string{workDir, wwwDir, filepath.Join(m.DataDir, "logs")} {
for _, d := range []string{workDir, wwwDir, m.logsDir()} {
if err := os.MkdirAll(d, 0o755); err != nil {
return err
}
@ -160,39 +194,34 @@ func (m *Media) Start(id int64) error {
hasKeys := strings.TrimSpace(st.Key) != ""
if hasKeys {
keysBody := normalizeKeysFile(st.Key)
if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil {
// 0600: this file holds the content keys.
if err := os.WriteFile(keysFile, []byte(keysBody), 0o600); err != nil {
return err
}
}
saveName := st.Name
tsPath := filepath.Join(workDir, saveName+".ts")
_ = os.Remove(tsPath)
headers := headerMap(st.HeadersJSON)
cfg := settingsFor(st, m.Store.GlobalPackagerSettings())
manifestURL := st.MPD
cfg := settingsFor(st)
var mpdProxy *mpd.LocalServer
// The rewriter is named by the stream row or its app module and looked up in
// the mpd registry, so streamd needs no knowledge of any provider.
if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS {
srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy)
if err != nil {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down", PlayPath: "/hls/" + st.Name + "/index.m3u8",
LastError: "mpd rewrite server: " + err.Error(),
})
m.fail(id, st.Name, "mpd rewrite server: "+err.Error())
return err
}
mpdProxy = srv
manifestURL = srv.URL
m.logf("stream %s: rewritten MPD %s", st.Name, manifestURL)
m.Log.Info("rewritten MPD in use", "stream", st.Name, "url", manifestURL)
}
// Ad-stitched manifest rewrite + live pipe mux.
nreTmp := filepath.Join(workDir, "nre")
_ = os.MkdirAll(nreTmp, 0o755)
tsPath = filepath.Join(nreTmp, saveName+".ts")
tsPath := filepath.Join(nreTmp, saveName+".ts")
_ = os.Remove(tsPath)
liveWait := strconv.Itoa(cfg.LiveWait)
@ -219,8 +248,9 @@ func (m *Media) Start(id int64) error {
}
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
// NRE prefers --custom-proxy over the system proxy when both are set.
// The proxy may carry credentials, so it is not logged.
nreArgs = append(nreArgs, "--custom-proxy", proxy)
m.logf("stream %s: origin proxy %s", st.Name, proxy)
m.Log.Info("origin proxy in use", "stream", st.Name)
}
// A synthetic manifest publishes exactly one video + audio pair, and an HLS
// master's variants rarely match a resolution/language filter, so in both
@ -242,10 +272,13 @@ func (m *Media) Start(id int64) error {
nreArgs = append(nreArgs, "-H", h)
}
}
_ = keysFile // kept on disk for debugging
nreLogPath := filepath.Join(m.DataDir, "logs", st.Name+"-nre.log")
nreLog, err := os.OpenFile(nreLogPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
// A rotating log opened with a start banner, rather than truncated. The
// previous run's output is exactly what you need when working out why
// this run is happening.
nreLog, err := logfile.OpenWithBanner(
filepath.Join(m.logsDir(), st.Name+"-nre.log"),
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre")
if err != nil {
return err
}
@ -278,10 +311,10 @@ func (m *Media) Start(id int64) error {
if mpdProxy != nil {
mpdProxy.Close()
}
_ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "down", LastError: err.Error(), PlayPath: "/hls/" + st.Name + "/index.m3u8"})
m.fail(id, st.Name, err.Error())
return err
}
m.logf("stream %s: NRE pid=%d", st.Name, nreCmd.Process.Pid)
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
sp := &streamProc{
id: id,
@ -296,6 +329,8 @@ func (m *Media) Start(id int64) error {
mpdProxy: mpdProxy,
variantSpecs: variantSpecs,
outputSpecs: outputSpecs,
cfg: cfg,
tsReadyBytes: cfg.TSReadyBytes,
}
@ -303,6 +338,12 @@ func (m *Media) Start(id int64) error {
m.procs[id] = sp
m.mu.Unlock()
m.Store.AddEvent(db.StreamEvent{
StreamID: id, Kind: db.EventStarted, Severity: db.SevInfo,
Message: fmt.Sprintf("downloader started (pid %d), publishing %s",
nreCmd.Process.Pid, outputSummary(outputSpecs)),
})
go func() {
_ = nreCmd.Wait()
m.mu.Lock()
@ -316,6 +357,34 @@ func (m *Media) Start(id int64) error {
return nil
}
// fail records a start-up failure in one place: runtime row, timeline, log and
// dashboard push.
func (m *Media) fail(id int64, name, msg string) {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + name + "/index.m3u8",
LastError: msg,
})
m.Store.AddEvent(db.StreamEvent{
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError, Message: msg,
})
m.Log.Error("stream failed to start", "stream", name, "err", msg)
if m.Notifier != nil {
m.Notifier.NotifyRuntime(name, "down")
}
}
func outputSummary(outputs []db.OutputSpec) string {
var on []string
for _, o := range db.EnabledOutputs(outputs) {
on = append(on, o.Label)
}
if len(on) == 0 {
return "nothing"
}
return strings.Join(on, "+")
}
func (m *Media) bootstrapHLS(sp *streamProc) {
deadline := time.Now().Add(3 * time.Minute)
nreDir := filepath.Dir(sp.tsPath)
@ -344,6 +413,10 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
PlayPath: "/hls/" + sp.name + "/index.m3u8",
LastError: "NRE exited before TS was ready — see logs/" + sp.name + "-nre.log",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log",
})
m.cleanupProc(sp.id)
return
}
@ -355,17 +428,26 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
PlayPath: "/hls/" + sp.name + "/index.m3u8",
LastError: "timed out waiting for growing TS",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
Message: "timed out waiting for the downloader to produce media",
})
_ = m.Stop(sp.id)
return
}
if err := m.startFFmpegHLS(sp); err != nil {
if err := m.startPackager(sp); err != nil {
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
Health: "down", LastError: err.Error(), PlayPath: "/hls/" + sp.name + "/index.m3u8",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
Message: "packager failed to start: " + err.Error(),
})
return
}
m.startVariantPackagers(sp, sp.variantSpecs)
m.writeMasterPlaylist(sp)
pid := int64(0)
if sp.nre != nil && sp.nre.Process != nil {
pid = int64(sp.nre.Process.Pid)
@ -377,46 +459,67 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
})
}
func (m *Media) startFFmpegHLS(sp *streamProc) error {
ffOut := filepath.Join(m.DataDir, "logs", sp.name+"-ffmpeg.out.log")
ffErr := filepath.Join(m.DataDir, "logs", sp.name+"-ffmpeg.err.log")
outF, err := os.OpenFile(ffOut, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
// startPackager runs the ffmpeg that publishes the source rung's outputs.
// The source rung is a stream copy, so additional output formats here are
// nearly free; the tee muxer still keeps it to one process.
func (m *Media) startPackager(sp *streamProc) error {
sourceSpec := db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true, Height: 0}
plan := buildOutputPlan(sp.outputSpecs, sp.wwwDir, sp.cfg, sourceSpec)
// ffmpeg will not create an output's directory, and under tee's
// onfail=ignore a missing one fails that output silently.
for _, d := range plan.Dirs {
if err := os.MkdirAll(d, 0o755); err != nil {
return err
}
}
args := append(inputArgs(sp.tsPath), variantCodecArgs(sourceSpec)...)
args = append(args, plan.Args...)
errLog, err := logfile.OpenWithBanner(
filepath.Join(m.logsDir(), sp.name+"-ffmpeg.err.log"),
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "ffmpeg")
if err != nil {
return err
}
errF, err := os.OpenFile(ffErr, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
_ = outF.Close()
return err
ffCmd := exec.Command(m.FFmpeg, args...)
ffCmd.Stderr = errLog
var outLog *logfile.Writer
if plan.WantsTS {
// stdout carries the live media, so it cannot also be a log file.
// ffmpeg writes diagnostics to stderr, so nothing is lost.
ring := m.Fanout.Create(sp.name)
pipe, err := ffCmd.StdoutPipe()
if err != nil {
_ = errLog.Close()
return err
}
go func() {
_, _ = io.Copy(ring, pipe)
_ = ring.Close()
}()
} else {
outLog, err = logfile.Open(
filepath.Join(m.logsDir(), sp.name+"-ffmpeg.out.log"),
logfile.DefaultMaxBytes, logfile.DefaultGenerations)
if err != nil {
_ = errLog.Close()
return err
}
ffCmd.Stdout = outLog
}
ffArgs := []string{
"-hide_banner", "-loglevel", "warning", "-y",
"-follow", "1",
// Large probe: early pipe-mux bytes often lack clean audio config.
"-analyzeduration", "20M",
"-probesize", "10M",
"-fflags", "+genpts",
"-i", sp.tsPath,
"-map", "0",
"-c", "copy",
"-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(sp.wwwDir, "seg_%05d.ts"),
sp.hlsIndex,
}
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 err
}
m.logf("stream %s: ffmpeg HLS pid=%d → %s", sp.name, ffCmd.Process.Pid, sp.hlsIndex)
m.Log.Info("packager started", "stream", sp.name, "pid", ffCmd.Process.Pid,
"outputs", outputSummary(sp.outputSpecs))
m.mu.Lock()
if cur, ok := m.procs[sp.id]; ok && !cur.stopping {
@ -427,14 +530,16 @@ func (m *Media) startFFmpegHLS(sp *streamProc) error {
_ = cur.ffErrLog.Close()
}
cur.ffmpeg = ffCmd
cur.ffOutLog = outF
cur.ffErrLog = errF
cur.ffOutLog = outLog
cur.ffErrLog = errLog
cur.ffDead = false
} else {
m.mu.Unlock()
_ = killProcess(ffCmd)
_ = outF.Close()
_ = errF.Close()
_ = errLog.Close()
if outLog != nil {
_ = outLog.Close()
}
return fmt.Errorf("stream stopped before ffmpeg attach")
}
m.mu.Unlock()
@ -480,21 +585,33 @@ func (m *Media) Stop(id int64) error {
sp.mpdProxy.Close()
sp.mpdProxy = nil
}
// Drops every progressive-TS client of this stream and its variants.
m.Fanout.RemovePrefix(sp.name)
waitPIDsGone([]int{nrePID, ffPID}, 5*time.Second)
m.cleanupProc(id)
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "stopped",
PlayPath: "/hls/" + sp.name + "/index.m3u8",
})
m.logf("stream %s: stopped", sp.name)
m.Store.AddEvent(db.StreamEvent{
StreamID: id, Kind: db.EventStopped, Severity: db.SevInfo, Message: "worker stopped",
})
m.Log.Info("stream stopped", "stream", sp.name)
if m.Notifier != nil {
m.Notifier.NotifyRuntime(sp.name, "stopped")
}
return nil
}
func (m *Media) Restart(id int64) error {
m.logf("stream id=%d: hard restart (kill worker, fresh start)", id)
m.Log.Info("hard restart", "stream_id", id)
_ = m.Stop(id)
// Give Windows time to release file locks on work/www before Start wipes them.
time.Sleep(1 * time.Second)
m.Store.AddEvent(db.StreamEvent{
StreamID: id, Kind: db.EventRestarted, Severity: db.SevInfo,
Message: "restarting worker",
})
return m.Start(id)
}
@ -505,14 +622,10 @@ func (m *Media) cleanupProc(id int64) {
if !ok {
return
}
if sp.nreLog != nil {
_ = sp.nreLog.Close()
}
if sp.ffOutLog != nil {
_ = sp.ffOutLog.Close()
}
if sp.ffErrLog != nil {
_ = sp.ffErrLog.Close()
for _, w := range []*logfile.Writer{sp.nreLog, sp.ffOutLog, sp.ffErrLog} {
if w != nil {
_ = w.Close()
}
}
delete(m.procs, id)
}
@ -563,6 +676,12 @@ func (m *Media) refreshHealth(id int64) {
Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime,
LastError: "NRE process exited — see logs/" + sp.name + "-nre.log",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError,
Message: fmt.Sprintf("downloader exited after %.0fs — see logs/%s-nre.log", uptime, sp.name),
})
m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
m.report(sp, "down")
m.cleanupProc(id)
return
}
@ -573,6 +692,7 @@ func (m *Media) refreshHealth(id int64) {
Health: "starting", PID: pid, PlayPath: playPath, UptimeS: uptime,
LastError: "waiting for HLS playlist",
})
m.sample(sp, "starting", 0, 0)
if ffDead {
// restart ffmpeg packager if TS still growing
go m.restartFFmpeg(sp)
@ -586,16 +706,88 @@ func (m *Media) refreshHealth(id int64) {
health = "down"
lastErr = fmt.Sprintf("playlist stale (%.0fs)", age)
}
bitrate := m.estimateBitrate(sp)
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: health, PID: pid, PlayPath: playPath, UptimeS: uptime,
PlaylistAgeS: age, LastError: lastErr,
PlaylistAgeS: age, LastError: lastErr, BitrateMbps: bitrate,
})
m.sample(sp, health, bitrate, age)
m.report(sp, health)
if ffDead && health != "down" {
go m.restartFFmpeg(sp)
}
go m.restartDeadVariants(sp)
}
// report pushes a health change to the dashboard, only on a transition, so an
// idle stream does not generate traffic every five seconds.
func (m *Media) report(sp *streamProc, health string) {
m.mu.Lock()
cur, ok := m.procs[sp.id]
if !ok {
m.mu.Unlock()
return
}
prev := cur.lastHealth
changed := prev != health
cur.lastHealth = health
m.mu.Unlock()
if !changed {
return
}
if prev != "" {
sev := db.SevInfo
if health == "down" {
sev = db.SevError
}
m.Store.Eventf(sp.id, db.EventVariantUp, sev, "health %s to %s", prev, health)
}
if m.Notifier != nil {
m.Notifier.NotifyRuntime(sp.name, health)
}
}
// sample records one point on the stream's health series.
func (m *Media) sample(sp *streamProc, health string, bitrate, age float64) {
viewers := 0
if m.ViewersFn != nil {
viewers = m.ViewersFn(sp.name)
}
m.Store.AddMetric(sp.id, db.MetricPoint{
Health: health,
BitrateMbps: bitrate,
PlaylistAgeS: age,
Viewers: viewers,
})
}
// estimateBitrate derives Mbps from how fast the muxed TS is growing, which is
// all the dashboard sparkline needs.
func (m *Media) estimateBitrate(sp *streamProc) float64 {
fi, err := os.Stat(sp.tsPath)
if err != nil {
return 0
}
size := fi.Size()
nowT := time.Now()
m.mu.Lock()
defer m.mu.Unlock()
cur, ok := m.procs[sp.id]
if !ok {
return 0
}
prevSize, prevAt := cur.lastTSSize, cur.lastTSAt
cur.lastTSSize, cur.lastTSAt = size, nowT
if prevAt.IsZero() || size <= prevSize {
return 0
}
elapsed := nowT.Sub(prevAt).Seconds()
if elapsed <= 0 {
return 0
}
return float64(size-prevSize) * 8 / elapsed / 1e6
}
func (m *Media) restartFFmpeg(sp *streamProc) {
m.mu.Lock()
cur, ok := m.procs[sp.id]
@ -620,9 +812,13 @@ func (m *Media) restartFFmpeg(sp *streamProc) {
m.mu.Unlock()
return
}
m.logf("stream %s: restarting ffmpeg HLS packager", sp.name)
if err := m.startFFmpegHLS(sp); err != nil {
m.logf("stream %s: ffmpeg restart failed: %v", sp.name, err)
m.Log.Warn("restarting packager", "stream", sp.name)
m.Store.AddEvent(db.StreamEvent{
StreamID: sp.id, Kind: db.EventFFRestart, Severity: db.SevWarn,
Message: "packager exited; restarting it",
})
if err := m.startPackager(sp); err != nil {
m.Log.Error("packager restart failed", "stream", sp.name, "err", err)
m.mu.Lock()
if cur, ok := m.procs[sp.id]; ok {
cur.ffDead = true
@ -637,10 +833,7 @@ func (m *Media) restartFFmpeg(sp *streamProc) {
}
m.mu.Unlock()
m.startVariantPackagers(sp, specs)
}
func (m *Media) logf(format string, args ...any) {
m.Log.Printf("supervisor: "+format, args...)
m.writeMasterPlaylist(sp)
}
func headerMap(headersJSON string) map[string]string {
@ -675,25 +868,19 @@ func headerFlags(headersJSON string) []string {
// normalizeKeysFile turns a DB key field (one or many KID:KEY lines, or
// comma/semicolon separated) into an NRE --key-text-file body.
func normalizeKeysFile(raw string) string {
raw = strings.ReplaceAll(raw, ",", "\n")
raw = strings.ReplaceAll(raw, ";", "\n")
var lines []string
var out []string
seen := map[string]bool{}
for _, line := range strings.Split(raw, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.Count(line, ":") != 1 {
continue
}
if seen[line] {
for _, line := range db.SplitKeyLines(raw) {
if strings.Count(line, ":") != 1 || seen[line] {
continue
}
seen[line] = true
lines = append(lines, line)
out = append(out, line)
}
if len(lines) == 0 {
if len(out) == 0 {
return strings.TrimSpace(raw) + "\n"
}
return strings.Join(lines, "\n") + "\n"
return strings.Join(out, "\n") + "\n"
}
func killProcess(cmd *exec.Cmd) error {
@ -702,8 +889,7 @@ func killProcess(cmd *exec.Cmd) error {
}
pid := cmd.Process.Pid
if runtime.GOOS == "windows" {
_ = exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
return nil
return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
}
return cmd.Process.Kill()
}
@ -745,8 +931,6 @@ func copyFile(src, dst string) error {
return out.Close()
}
// findGrowingTS locates NRE's live-pipe-mux output. Depending on version/flags
// it may be saveName.ts or saveName.<lang>.ts (e.g. test.en.ts).
func waitPIDsGone(pids []int, timeout time.Duration) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
@ -767,10 +951,8 @@ func waitPIDsGone(pids []int, timeout time.Duration) {
}
}
func findGrowingTS(dir, saveName string) string {
return findGrowingTSMin(dir, saveName, 256*1024)
}
// findGrowingTSMin locates NRE's live-pipe-mux output. Depending on
// version/flags it may be saveName.ts or saveName.<lang>.ts (e.g. test.en.ts).
func findGrowingTSMin(dir, saveName string, minSize int64) string {
if minSize <= 0 {
minSize = 256 * 1024

View file

@ -0,0 +1,299 @@
package supervisor
import (
"fmt"
"path/filepath"
"strconv"
"strings"
"drmdecryption/apps/streamd/internal/db"
)
// Packager defaults. These were literals in the ffmpeg command line before
// they became per-stream settings.
const (
defaultHLSTime = 4
defaultHLSListSize = 15
hlsFlags = "delete_segments+append_list+omit_endlist+independent_segments"
)
// outputPlan is the resolved publishing plan for one variant.
type outputPlan struct {
// Args are the ffmpeg output arguments, appended after the input.
Args []string
// WantsTS is true when one of the outputs is the progressive MPEG-TS
// pipe, which means the process's stdout is media and must not also be
// used for logging.
WantsTS bool
// Dirs must exist before ffmpeg starts: it will not create them, and
// under tee's onfail=ignore a missing one fails that output silently.
Dirs []string
// Playlists maps an output format to the file it writes, for health
// checks and the master playlist.
Playlists map[string]string
}
// buildOutputPlan turns a variant's enabled outputs into ffmpeg arguments.
//
// With a single output it emits a plain "-f <muxer> ... <url>", which keeps
// the common HLS-only case the same shape streamd has always run. With
// several it emits one tee muxer, so the frames are encoded once and muxed N
// times — listing several plain outputs would instead run the encoder once per
// output, roughly tripling CPU for a 720p rung publishing HLS+CMAF+DASH.
func buildOutputPlan(outputs []db.OutputSpec, wwwDir string, cfg streamSettings, spec db.VariantSpec) outputPlan {
plan := outputPlan{Playlists: map[string]string{}}
enabled := db.EnabledOutputs(outputs)
if len(enabled) == 0 {
// Never publish nothing: that would leave the stream unreachable.
enabled = []db.OutputSpec{{ID: "hls", Format: db.FormatHLS, Enabled: true}}
}
// The source rung is a stream copy from the downloader's MPEG-TS. Copying
// that into an fMP4 container needs two fixes that re-encoding would not:
// the AAC has to be converted from ADTS to ASC, and the H.264 codec tag
// carried from TS is rejected by the MP4 muxer. Both were found by running
// the real ffmpeg; see ffmpeg_integration_test.go.
copying := spec.IsSource()
type target struct {
format string
options []kv
url string
// fmp4 marks an output whose container is ISO-BMFF.
fmp4 bool
}
var targets []target
for _, o := range enabled {
segDur := o.SegmentDuration
if segDur <= 0 {
segDur = cfg.HLSTime
}
listSize := o.ListSize
if listSize <= 0 {
listSize = cfg.HLSListSize
}
switch o.Format {
case db.FormatHLS:
index := filepath.Join(wwwDir, "index.m3u8")
targets = append(targets, target{
format: "hls",
options: []kv{
{"hls_time", strconv.Itoa(segDur)},
{"hls_list_size", strconv.Itoa(listSize)},
{"hls_flags", hlsFlags},
{"hls_segment_type", "mpegts"},
{"hls_segment_filename", filepath.Join(wwwDir, "seg_%05d.ts")},
},
url: index,
})
plan.Playlists[db.FormatHLS] = index
case db.FormatCMAF:
dir := filepath.Join(wwwDir, "cmaf")
index := filepath.Join(dir, "index.m3u8")
targets = append(targets, target{
format: "hls",
fmp4: true,
options: []kv{
{"hls_time", strconv.Itoa(segDur)},
{"hls_list_size", strconv.Itoa(listSize)},
{"hls_flags", hlsFlags},
{"hls_segment_type", "fmp4"},
{"hls_fmp4_init_filename", "init.mp4"},
{"hls_segment_filename", filepath.Join(dir, "seg_%05d.m4s")},
},
url: index,
})
plan.Dirs = append(plan.Dirs, dir)
plan.Playlists[db.FormatCMAF] = index
case db.FormatDASH:
dir := filepath.Join(wwwDir, "dash")
index := filepath.Join(dir, "index.mpd")
targets = append(targets, target{
format: "dash",
fmp4: true,
options: []kv{
{"seg_duration", strconv.Itoa(segDur)},
{"window_size", strconv.Itoa(listSize)},
{"extra_window_size", "2"},
{"use_template", "1"},
{"use_timeline", "1"},
{"streaming", "1"},
},
url: index,
})
plan.Dirs = append(plan.Dirs, dir)
plan.Playlists[db.FormatDASH] = index
case db.FormatTS:
targets = append(targets, target{format: "mpegts", url: "pipe:1"})
plan.WantsTS = true
}
}
// An fMP4 output from a copied source needs an MP4-compatible codec tag.
// This is a stream option rather than a muxer option, so it applies to the
// whole output; it is harmless to the MPEG-TS legs, which ignore it.
var pre []string
needsFMP4Fixes := false
for _, t := range targets {
if t.fmp4 {
needsFMP4Fixes = true
break
}
}
if copying && needsFMP4Fixes {
pre = append(pre, "-tag:v", "avc1", "-tag:a", "mp4a")
}
if len(targets) == 1 {
t := targets[0]
args := append([]string{}, pre...)
// With one output there is no tee, so a bitstream filter is set the
// ordinary way.
if copying && t.fmp4 {
args = append(args, "-bsf:a", "aac_adtstoasc")
}
args = append(args, "-f", t.format)
for _, o := range t.options {
args = append(args, "-"+o.k, o.v)
}
plan.Args = append(args, t.url)
return plan
}
// Several outputs: one tee, one encode.
specs := make([]string, 0, len(targets))
for _, t := range targets {
opts := make([]string, 0, len(t.options)+3)
opts = append(opts, "f="+t.format)
// onfail=ignore on every leg is essential. Without it, a reader
// disconnecting from the progressive TS pipe, or a full disk under one
// output directory, tears down the whole ffmpeg process and takes the
// healthy outputs with it.
opts = append(opts, "onfail=ignore")
// The ADTS-to-ASC conversion has to be per-leg: applying it globally
// would also rewrite the audio going into the MPEG-TS outputs, which
// need ADTS.
if copying && t.fmp4 {
opts = append(opts, "bsfs/a=aac_adtstoasc")
}
for _, o := range t.options {
opts = append(opts, teeEscapeKey(o.k)+"="+teeEscapeValue(o.v))
}
specs = append(specs, "["+strings.Join(opts, ":")+"]"+teeEscapeURL(t.url))
}
plan.Args = append(pre, "-f", "tee", strings.Join(specs, "|"))
return plan
}
type kv struct{ k, v string }
// teeEscapeKey escapes a tee option name. Names are fixed identifiers, so
// this only guards against a stray separator reaching the parser.
func teeEscapeKey(s string) string {
return strings.NewReplacer(
`\`, `\\`,
`:`, `\:`,
`|`, `\|`,
`[`, `\[`,
`]`, `\]`,
`=`, `\=`,
).Replace(s)
}
// teeEscapeValue escapes a tee option value.
//
// This needs two layers at once, which is not obvious and was established by
// testing against the real ffmpeg (see ffmpeg_integration_test.go): the value
// is wrapped in single quotes AND its colons are backslash-escaped. Quoting
// alone is not enough, and escaping alone is not enough.
//
// A Windows path is what makes it matter. Unescaped,
// "hls_segment_filename=C:/data/seg.ts" is split at the drive letter, ffmpeg
// rejects that slave, and under onfail=ignore the output silently never
// appears — a failure mode that looks like "CMAF just doesn't work".
func teeEscapeValue(s string) string {
// Forward slashes throughout: a backslash is itself an escape character
// here, so a Windows path written with them is a second problem.
s = filepath.ToSlash(s)
// A literal single quote cannot appear inside a single-quoted run: close
// the quote, emit an escaped one, reopen.
s = strings.ReplaceAll(s, `'`, `'\''`)
s = strings.ReplaceAll(s, `:`, `\:`)
return `'` + s + `'`
}
// teeEscapeURL escapes the destination URL of one tee output. The URL runs
// from after "]" to the next unescaped "|", so only the separator and bracket
// characters need escaping — a colon is safe here, and escaping it would
// corrupt the path.
func teeEscapeURL(s string) string {
s = filepath.ToSlash(s)
return strings.NewReplacer(
`|`, `\|`,
`[`, `\[`,
`]`, `\]`,
).Replace(s)
}
// variantCodecArgs builds the encoder arguments for one rung. The source rung
// is a stream copy; a scaled rung re-encodes; an audio-only rung drops video.
func variantCodecArgs(v db.VariantSpec) []string {
if v.IsSource() {
return []string{"-map", "0", "-c", "copy"}
}
if v.AudioOnly {
abr := v.AudioBitrate
if abr == "" {
abr = "96k"
}
return []string{
"-map", "0:a:0?",
"-vn",
"-c:a", "aac",
"-b:a", abr,
"-ac", "2",
}
}
vbr := v.VideoBitrate
if vbr == "" {
vbr = "2800k"
}
abr := v.AudioBitrate
if abr == "" {
abr = "128k"
}
return []string{
"-map", "0:v:0",
"-map", "0:a:0?",
"-vf", fmt.Sprintf("scale=-2:%d", v.Height),
"-c:v", "libx264",
"-preset", "veryfast",
"-tune", "zerolatency",
"-b:v", vbr,
"-maxrate", vbr,
"-bufsize", doubleBitrate(vbr),
"-g", "48",
"-keyint_min", "48",
"-sc_threshold", "0",
"-c:a", "aac",
"-b:a", abr,
"-ac", "2",
}
}
// inputArgs are the demuxer options for reading the growing TS the downloader
// is writing. The large probe is deliberate: the first bytes of a pipe-mux
// often lack a clean audio configuration.
func inputArgs(tsPath string) []string {
return []string{
"-hide_banner", "-loglevel", "warning", "-y",
"-follow", "1",
"-analyzeduration", "20M",
"-probesize", "10M",
"-fflags", "+genpts",
"-i", tsPath,
}
}

View file

@ -0,0 +1,389 @@
package supervisor
import (
"strings"
"testing"
"drmdecryption/apps/streamd/internal/db"
)
// quote and backslash as values, so the test source stays readable where it
// asserts on ffmpeg's escaping.
const (
q = "'"
bs = `\`
)
func testCfg() streamSettings {
return streamSettings{HLSTime: defaultHLSTime, HLSListSize: defaultHLSListSize}
}
func only(format string) []db.OutputSpec {
return []db.OutputSpec{{ID: "x", Format: format, Enabled: true}}
}
func sourceSpecForTest() db.VariantSpec {
return db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true, Height: 0}
}
func normalize(s string) string { return strings.ReplaceAll(s, `\`, "/") }
// findFormat returns the muxer named by -f, without assuming a position: a
// stream-copied rung publishing fMP4 carries -tag options first.
func findFormat(args []string) string {
for i := 0; i < len(args)-1; i++ {
if args[i] == "-f" {
return args[i+1]
}
}
return ""
}
// teeSpec returns the single tee specification argument.
func teeSpec(t *testing.T, args []string) string {
t.Helper()
for i := 0; i < len(args)-1; i++ {
if args[i] == "-f" && args[i+1] == "tee" {
if i+2 >= len(args) {
t.Fatalf("-f tee with no spec: %v", args)
}
return args[i+2]
}
}
t.Fatalf("no tee muxer in %v", args)
return ""
}
// With a single mpegts HLS output the command must stay the plain form
// streamd has always run. media.go is the least-exercised code in the project,
// so the common path deliberately does not change shape.
func TestSingleHLSOutputMatchesTheOriginalCommand(t *testing.T) {
plan := buildOutputPlan(only(db.FormatHLS), "/data/www/news", testCfg(), sourceSpecForTest())
want := []string{
"-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", "/data/www/news/seg_%05d.ts",
"/data/www/news/index.m3u8",
}
if len(plan.Args) != len(want) {
t.Fatalf("arg count %d, want %d\ngot: %v\nwant: %v", len(plan.Args), len(want), plan.Args, want)
}
for i := range want {
// Separators are normalised, since filepath.Join is platform-specific.
if normalize(plan.Args[i]) != normalize(want[i]) {
t.Errorf("arg %d = %q, want %q", i, plan.Args[i], want[i])
}
}
if plan.WantsTS {
t.Error("an HLS-only plan must not claim stdout")
}
for _, a := range plan.Args {
if a == "tee" {
t.Error("a single output must not use the tee muxer")
}
}
}
func TestSingleOutputPerFormat(t *testing.T) {
cases := []struct {
format string
wantMux string
wantPath string
}{
{db.FormatHLS, "hls", "/data/www/news/index.m3u8"},
{db.FormatCMAF, "hls", "/data/www/news/cmaf/index.m3u8"},
{db.FormatDASH, "dash", "/data/www/news/dash/index.mpd"},
{db.FormatTS, "mpegts", "pipe:1"},
}
for _, c := range cases {
plan := buildOutputPlan(only(c.format), "/data/www/news", testCfg(), sourceSpecForTest())
if mux := findFormat(plan.Args); mux != c.wantMux {
t.Errorf("%s: muxer = %q, want %s (args %v)", c.format, mux, c.wantMux, plan.Args)
}
if last := normalize(plan.Args[len(plan.Args)-1]); last != c.wantPath {
t.Errorf("%s: output = %q, want %q", c.format, last, c.wantPath)
}
if (c.format == db.FormatTS) != plan.WantsTS {
t.Errorf("%s: WantsTS = %v", c.format, plan.WantsTS)
}
}
}
// The headline requirement: several outputs must share ONE encode via tee. If
// this regresses into several plain outputs, ffmpeg runs the encoder once per
// format and CPU triples for a transcoded rung.
func TestMultipleOutputsUseOneTee(t *testing.T) {
outputs := []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
{ID: "dash", Format: db.FormatDASH, Enabled: true},
{ID: "ts", Format: db.FormatTS, Enabled: true},
}
plan := buildOutputPlan(outputs, "/data/www/news", testCfg(), sourceSpecForTest())
spec := teeSpec(t, plan.Args)
fCount := 0
for _, a := range plan.Args {
if a == "-f" {
fCount++
}
}
if fCount != 1 {
t.Errorf("want a single -f (the tee), got %d: %v", fCount, plan.Args)
}
legs := strings.Split(spec, "|")
if len(legs) != 4 {
t.Fatalf("want 4 tee legs, got %d: %s", len(legs), spec)
}
// Every leg must carry onfail=ignore: without it one dead output (a
// disconnected TS reader, a full disk) kills the whole process and takes
// the healthy outputs with it.
for i, leg := range legs {
if !strings.Contains(leg, "onfail=ignore") {
t.Errorf("leg %d has no onfail=ignore: %s", i, leg)
}
if !strings.HasPrefix(leg, "[") || !strings.Contains(leg, "]") {
t.Errorf("leg %d is not a bracketed tee spec: %s", i, leg)
}
}
if n := strings.Count(spec, "f=hls"); n != 2 {
t.Errorf("want two hls legs (mpegts + fmp4), got %d", n)
}
if !strings.Contains(spec, "f=dash") || !strings.Contains(spec, "f=mpegts") {
t.Errorf("missing a format in the tee spec: %s", spec)
}
if !plan.WantsTS {
t.Error("a plan including the TS output must claim stdout")
}
// CMAF and DASH write into subdirectories ffmpeg will not create.
if len(plan.Dirs) != 2 {
t.Errorf("want 2 directories to pre-create, got %v", plan.Dirs)
}
}
// Windows paths contain a colon, which is also the tee option separator.
// Unescaped, hls_segment_filename=C:/... is split at the drive letter, that
// slave is rejected, and under onfail=ignore the output silently never
// appears.
func TestTeeEscapesColonsInPaths(t *testing.T) {
outputs := []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
{ID: "dash", Format: db.FormatDASH, Enabled: true},
}
plan := buildOutputPlan(outputs, `C:\data\www\city news`, testCfg(), sourceSpecForTest())
spec := teeSpec(t, plan.Args)
if strings.Contains(spec, "hls_segment_filename=C:") {
t.Errorf("drive-letter colon is unescaped in the option value: %s", spec)
}
// Real ffmpeg needs BOTH: the value quoted and its colon escaped.
if !strings.Contains(spec, "hls_segment_filename="+q+"C"+bs+":") {
t.Errorf("want the value quoted with its colon escaped, got: %s", spec)
}
// A space is fine: this is one argv element, not a shell word.
if !strings.Contains(spec, "city news") {
t.Errorf("path with a space was mangled: %s", spec)
}
// The URL after ] keeps its colon, which is not special there.
if !strings.Contains(spec, "]C:/data/www/city news/index.m3u8") {
t.Errorf("output URL should keep its drive colon: %s", spec)
}
}
func TestTeeEscapeKey(t *testing.T) {
for in, want := range map[string]string{
"plain": "plain",
"a:b": "a" + bs + ":b",
"a|b": "a" + bs + "|b",
"a[b]": "a" + bs + "[b" + bs + "]",
"k=v": "k" + bs + "=v",
"bsfs/a": "bsfs/a",
} {
if got := teeEscapeKey(in); got != want {
t.Errorf("teeEscapeKey(%q) = %q, want %q", in, got, want)
}
}
}
func TestTeeEscapeValue(t *testing.T) {
// Both layers, in this order: quote the whole value, escape its colons.
// Established against the real ffmpeg; neither alone is accepted.
if got := teeEscapeValue("C:/data/seg_%05d.ts"); got != q+"C"+bs+":/data/seg_%05d.ts"+q {
t.Errorf("got %q", got)
}
// Backslashes become forward slashes rather than being doubled, because a
// backslash is itself an escape character in a tee spec.
if got := teeEscapeValue(`C:\data\x.ts`); got != q+"C"+bs+":/data/x.ts"+q {
t.Errorf("got %q", got)
}
// A space needs nothing special once the value is quoted.
if got := teeEscapeValue("/srv/city news/seg.ts"); got != q+"/srv/city news/seg.ts"+q {
t.Errorf("got %q", got)
}
// A plain value is quoted too, which is harmless and keeps one rule.
if got := teeEscapeValue("mpegts"); got != q+"mpegts"+q {
t.Errorf("got %q", got)
}
// A literal quote must not end the quoted run.
if got := teeEscapeValue("/srv/o" + q + "brien/seg.ts"); !strings.Contains(got, q+bs+q) {
t.Errorf("apostrophe was not escaped: %q", got)
}
}
func TestTeeEscapeURL(t *testing.T) {
// Backslashes become forward slashes, and only the separator characters
// are escaped — a colon must survive untouched in a URL.
if got := teeEscapeURL(`C:\data\x.m3u8`); got != "C:/data/x.m3u8" {
t.Errorf("got %q", got)
}
if got := teeEscapeURL("a|b"); got != "a"+bs+"|b" {
t.Errorf("pipe must be escaped in a URL, got %q", got)
}
if got := teeEscapeURL("pipe:1"); got != "pipe:1" {
t.Errorf("pipe:1 must pass through unchanged, got %q", got)
}
}
// A copied source rung into an fMP4 container needs the ADTS-to-ASC filter on
// that leg only, plus an MP4 codec tag. A re-encoded rung needs neither,
// because ffmpeg then produces the right bitstream for each muxer itself.
func TestFMP4CopyFixesOnlyWhenCopying(t *testing.T) {
outputs := []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
}
src := buildOutputPlan(outputs, "/w", testCfg(), sourceSpecForTest())
if !strings.Contains(strings.Join(src.Args, " "), "-tag:v avc1") {
t.Error("a copied rung publishing fMP4 needs an MP4 codec tag")
}
for _, leg := range strings.Split(teeSpec(t, src.Args), "|") {
isFMP4 := strings.Contains(leg, "fmp4")
hasBSF := strings.Contains(leg, "aac_adtstoasc")
if isFMP4 != hasBSF {
t.Errorf("aac_adtstoasc belongs on the fMP4 leg and only there: %s", leg)
}
}
hd := db.VariantSpec{ID: "hd", Enabled: true, Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k"}
enc := strings.Join(buildOutputPlan(outputs, "/w", testCfg(), hd).Args, " ")
if strings.Contains(enc, "-tag:v avc1") {
t.Error("a re-encoded rung should not need a codec tag override")
}
if strings.Contains(enc, "aac_adtstoasc") {
t.Error("a re-encoded rung should not need the ADTS filter")
}
}
// A single fMP4 output has no tee, so the bitstream filter is set the
// ordinary way.
func TestSingleFMP4OutputUsesPlainBSF(t *testing.T) {
plan := buildOutputPlan(only(db.FormatCMAF), "/w", testCfg(), sourceSpecForTest())
joined := strings.Join(plan.Args, " ")
if !strings.Contains(joined, "-bsf:a aac_adtstoasc") {
t.Errorf("want a plain -bsf:a, got %s", joined)
}
if strings.Contains(joined, "bsfs/a") {
t.Errorf("tee syntax leaked into a single-output command: %s", joined)
}
}
// Publishing nothing would leave the stream unreachable.
func TestNoEnabledOutputsFallsBackToHLS(t *testing.T) {
plan := buildOutputPlan([]db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: false},
}, "/data/www/news", testCfg(), sourceSpecForTest())
if findFormat(plan.Args) != "hls" {
t.Errorf("want an HLS fallback, got %v", plan.Args)
}
}
func TestPerOutputSegmentOverrides(t *testing.T) {
outputs := []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true, SegmentDuration: 2, ListSize: 6},
}
plan := buildOutputPlan(outputs, "/data/www/news", testCfg(), sourceSpecForTest())
joined := strings.Join(plan.Args, " ")
if !strings.Contains(joined, "-hls_time 2") || !strings.Contains(joined, "-hls_list_size 6") {
t.Errorf("per-output overrides were ignored: %s", joined)
}
// An output that does not override inherits the stream's settings.
cfg := testCfg()
cfg.HLSTime, cfg.HLSListSize = 8, 40
plan = buildOutputPlan(only(db.FormatHLS), "/data/www/news", cfg, sourceSpecForTest())
joined = strings.Join(plan.Args, " ")
if !strings.Contains(joined, "-hls_time 8") || !strings.Contains(joined, "-hls_list_size 40") {
t.Errorf("stream settings were not inherited: %s", joined)
}
}
func TestVariantCodecArgs(t *testing.T) {
// The source rung is a pass-through copy: no encoder at all.
src := strings.Join(variantCodecArgs(sourceSpecForTest()), " ")
if !strings.Contains(src, "-c copy") {
t.Errorf("source rung must stream-copy, got %q", src)
}
if strings.Contains(src, "libx264") {
t.Error("source rung must not re-encode")
}
// A scaled rung encodes video and audio.
hd := strings.Join(variantCodecArgs(db.VariantSpec{
ID: "hd", Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k",
}), " ")
for _, want := range []string{"scale=-2:720", "libx264", "-b:v 2800k", "-b:a 128k", "-bufsize 5600k"} {
if !strings.Contains(hd, want) {
t.Errorf("scaled rung missing %q in %q", want, hd)
}
}
// An audio-only rung drops video entirely.
au := strings.Join(variantCodecArgs(db.VariantSpec{
ID: "audio", AudioOnly: true, AudioBitrate: "96k",
}), " ")
if !strings.Contains(au, "-vn") {
t.Errorf("audio rung must pass -vn, got %q", au)
}
if strings.Contains(au, "libx264") || strings.Contains(au, "scale=") {
t.Errorf("audio rung must not touch video, got %q", au)
}
if !strings.Contains(au, "-b:a 96k") {
t.Errorf("audio rung missing its bitrate, got %q", au)
}
}
func TestDoubleBitrate(t *testing.T) {
for in, want := range map[string]string{
"2800k": "5600k",
"1200k": "2400k",
"5M": "10000k",
"": "5600k",
"junk": "5600k",
} {
if got := doubleBitrate(in); got != want {
t.Errorf("doubleBitrate(%q) = %q, want %q", in, got, want)
}
}
}
func TestPlaylistsRecorded(t *testing.T) {
outputs := []db.OutputSpec{
{ID: "hls", Format: db.FormatHLS, Enabled: true},
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
{ID: "dash", Format: db.FormatDASH, Enabled: true},
{ID: "ts", Format: db.FormatTS, Enabled: true},
}
plan := buildOutputPlan(outputs, "/w", testCfg(), sourceSpecForTest())
for _, f := range []string{db.FormatHLS, db.FormatCMAF, db.FormatDASH} {
if plan.Playlists[f] == "" {
t.Errorf("no playlist recorded for %s", f)
}
}
// The progressive TS has no file on disk, so no playlist entry.
if plan.Playlists[db.FormatTS] != "" {
t.Error("the TS output should not record a playlist file")
}
}

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
}