streamd: preview quality picker, dashboard polish, C4 wrap keys
- 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:
parent
b3955bd81e
commit
066e018749
113 changed files with 19002 additions and 1541 deletions
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue