package supervisor import ( "encoding/json" "fmt" "io" "log/slog" "os" "os/exec" "path/filepath" "strconv" "strings" "sync" "time" "streamd/apps/streamd/internal/db" "streamd/apps/streamd/internal/logfile" "streamd/apps/streamd/internal/tsfanout" "streamd/mpd" ) // Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into // DataDir/www// 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 *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 // ProxyResolver resolves stream.Proxy / stream.Egress to a SOCKS/HTTP URL. ProxyResolver ProxyResolver mu sync.Mutex procs map[int64]*streamProc stopMon chan struct{} } // ProxyResolver turns a stream row into an origin-fetch proxy URL. type ProxyResolver interface { ResolveProxy(st db.Stream) (string, error) } // 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 sessionID int64 // stream_sessions row opened when NRE starts workDir string wwwDir string tsPath string hlsIndex string nreLogFile *os.File // per-stream NRE log (banner + append) nrePTY io.Closer // Linux PTY master; nil on Windows / fallback 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. type Options struct { Store *db.Store DataDir string NRE string FFmpeg string MP4Decrypt string Log *slog.Logger Fanout *tsfanout.Set Notifier Notifier ViewersFn func(streamName string) int ProxyResolver ProxyResolver } func NewMedia(opt Options) *Media { lg := opt.Log if lg == nil { lg = slog.Default() } fan := opt.Fanout if fan == nil { fan = tsfanout.NewSet(tsfanout.DefaultBufferBytes) } m := &Media{ Store: opt.Store, DataDir: opt.DataDir, NRE: opt.NRE, FFmpeg: opt.FFmpeg, MP4Decrypt: opt.MP4Decrypt, Log: lg, Fanout: fan, Notifier: opt.Notifier, ViewersFn: opt.ViewersFn, ProxyResolver: opt.ProxyResolver, procs: map[int64]*streamProc{}, stopMon: make(chan struct{}), } go m.monitorLoop() return m } func (m *Media) Close() { close(m.stopMon) m.mu.Lock() ids := make([]int64, 0, len(m.procs)) for id := range m.procs { ids = append(ids, id) } m.mu.Unlock() for _, id := range ids { _ = m.Stop(id) } } // 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) effectiveProxy(st db.Stream) (string, error) { if m.ProxyResolver != nil { return m.ProxyResolver.ResolveProxy(st) } return strings.TrimSpace(st.Proxy), nil } func (m *Media) Start(id int64) error { st, err := m.Store.GetStream(id) if err != nil { return err } if strings.TrimSpace(st.MPD) == "" { 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.fail(id, st.Name, "mpd must be an http(s) URL") return fmt.Errorf("invalid mpd url") } if m.NRE == "" || m.FFmpeg == "" { m.fail(id, st.Name, "NRE or ffmpeg binary not configured") return fmt.Errorf("NRE or ffmpeg not configured") } m.mu.Lock() if _, exists := m.procs[id]; exists { m.mu.Unlock() return m.Restart(id) } m.mu.Unlock() _ = m.Store.SetRuntime(id, db.RuntimePatch{ Health: "starting", PlayPath: "/hls/" + st.Name + "/index.m3u8", }) 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", db.VariantDir(st.Name, v.ID, v.Height, v.AudioOnly))) } for _, d := range []string{workDir, wwwDir, m.logsDir()} { if err := os.MkdirAll(d, 0o755); err != nil { return err } } keysFile := filepath.Join(workDir, "keys.txt") hasKeys := strings.TrimSpace(st.Key) != "" if hasKeys { keysBody := normalizeKeysFile(st.Key) // 0600: this file holds the content keys. if err := os.WriteFile(keysFile, []byte(keysBody), 0o600); err != nil { return err } } saveName := st.Name headers := headerMap(st.HeadersJSON) cfg := settingsFor(st, m.Store.GlobalPackagerSettings()) originProxy, err := m.effectiveProxy(st) if err != nil { m.fail(id, st.Name, "egress: "+err.Error()) return err } manifestURL := st.MPD 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, originProxy) if err != nil { m.fail(id, st.Name, "mpd rewrite server: "+err.Error()) return err } mpdProxy = srv manifestURL = srv.URL 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") _ = os.Remove(tsPath) liveWait := strconv.Itoa(cfg.LiveWait) nreArgs := []string{ manifestURL, "--live-real-time-merge", "--live-pipe-mux", "--live-wait-time", liveWait, "--ffmpeg-binary-path", m.FFmpeg, "--save-name", saveName, "--save-dir", nreTmp, "--tmp-dir", nreTmp, "--no-ansi-color", "--log-level", "ERROR", // Drop every subtitle track. Live pipe-mux to TS does not need them, and // an extra Spectre progress row makes redirected-console crashes more // likely (NRE forces ANSI UI when stdout is a log file). "-ds", "for=all", } if hasKeys { // Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so // always feed every KID:KEY via --key-text-file. nreArgs = append(nreArgs, "--key-text-file", keysFile, "--mp4-real-time-decryption", ) } if proxy := strings.TrimSpace(originProxy); 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.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 // cases take the best rendition instead of the configured selectors. if mpdProxy != nil || cfg.IsHLS { nreArgs = append(nreArgs, "-sv", "for=best", "-sa", "for=best") } else { nreArgs = append(nreArgs, "-sv", cfg.VideoSelect, "-sa", cfg.AudioSelect) } if hasKeys && m.MP4Decrypt != "" { nreArgs = append(nreArgs, "--decryption-engine", "MP4DECRYPT", "--decryption-binary-path", m.MP4Decrypt, ) } // Headers only needed when hitting upstream DAI directly (non-rewritten). if mpdProxy == nil { for _, h := range headerFlags(st.HeadersJSON) { nreArgs = append(nreArgs, "-H", h) } } // Banner + rotate-on-open keep prior runs readable. On Linux, NRE runs under // a PTY (see startNRELogged): plain file/pipe redirects force Spectre live UI // with WindowWidth 0 and crash ProgressRefreshThread. nreLogFile, err := logfile.OpenCmdLog( filepath.Join(m.logsDir(), st.Name+"-nre.log"), logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre") if err != nil { return err } nreCmd := exec.Command(m.NRE, nreArgs...) hideWindow(nreCmd) // NRE (v0.6) resolves mp4decrypt via PATH / sibling of its .exe, and often // ignores --decryption-binary-path for MP4DECRYPT. Match legacy: prepend // dirs and best-effort copy beside NRE. nreEnv := os.Environ() nreEnv = setEnvDefault(nreEnv, "COLUMNS", "120") nreEnv = setEnvDefault(nreEnv, "LINES", "40") nreEnv = setEnvDefault(nreEnv, "TERM", "xterm") pathPrepend := []string{} if m.MP4Decrypt != "" { pathPrepend = append(pathPrepend, filepath.Dir(m.MP4Decrypt)) sibling := filepath.Join(filepath.Dir(m.NRE), filepath.Base(m.MP4Decrypt)) if _, err := os.Stat(sibling); err != nil { _ = copyFile(m.MP4Decrypt, sibling) } } if m.NRE != "" { pathPrepend = append(pathPrepend, filepath.Dir(m.NRE)) } if len(pathPrepend) > 0 { sep := string(os.PathListSeparator) nreEnv = prependPathEnv(nreEnv, strings.Join(pathPrepend, sep)) } nreCmd.Env = nreEnv nrePTY, keepLogFD, err := startNRELogged(nreCmd, nreLogFile) if err != nil { if keepLogFD { _ = nreLogFile.Close() } if mpdProxy != nil { mpdProxy.Close() } m.fail(id, st.Name, err.Error()) return err } ownedLog := nreLogFile if !keepLogFD { ownedLog = nil } m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid) sessionID, _ := m.Store.OpenSession(id) sp := &streamProc{ id: id, name: st.Name, nre: nreCmd, started: time.Now(), sessionID: sessionID, workDir: workDir, wwwDir: wwwDir, tsPath: tsPath, hlsIndex: filepath.Join(wwwDir, "index.m3u8"), nreLogFile: ownedLog, nrePTY: nrePTY, mpdProxy: mpdProxy, variantSpecs: variantSpecs, outputSpecs: outputSpecs, cfg: cfg, tsReadyBytes: cfg.TSReadyBytes, } m.mu.Lock() 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() if cur, ok := m.procs[id]; ok && cur.nre == nreCmd { cur.nreDead = true } m.mu.Unlock() }() go m.bootstrapHLS(sp) 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) minTS := sp.tsReadyBytes for time.Now().Before(deadline) { m.mu.Lock() cur := m.procs[sp.id] stopping := cur == nil || cur.stopping nreDead := sp.nreDead m.mu.Unlock() if stopping { return } if found := findGrowingTSMin(nreDir, sp.name, minTS); found != "" { sp.tsPath = found m.mu.Lock() if cur, ok := m.procs[sp.id]; ok { cur.tsPath = found } m.mu.Unlock() break } if nreDead || (sp.nre.ProcessState != nil && sp.nre.ProcessState.Exited()) { _ = m.Store.SetRuntime(sp.id, db.RuntimePatch{ Health: "down", PlayPath: "/hls/" + sp.name + "/index.m3u8", LastError: "NRE exited before TS was ready — see data/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 data/logs/" + sp.name + "-nre.log", }) m.closeSession(sp, db.SessionNREExit, "down") m.cleanupProc(sp.id) return } time.Sleep(500 * time.Millisecond) } if st, err := os.Stat(sp.tsPath); err != nil || st.Size() < minTS { _ = m.Store.SetRuntime(sp.id, db.RuntimePatch{ Health: "down", 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.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) } _ = m.Store.SetRuntime(sp.id, db.RuntimePatch{ Health: "starting", PID: pid, PlayPath: "/hls/" + sp.name + "/index.m3u8", }) } // 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 } 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 } hideWindow(ffCmd) if err := ffCmd.Start(); err != nil { _ = errLog.Close() if outLog != nil { _ = outLog.Close() } return err } 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 { if cur.ffOutLog != nil { _ = cur.ffOutLog.Close() } if cur.ffErrLog != nil { _ = cur.ffErrLog.Close() } cur.ffmpeg = ffCmd cur.ffOutLog = outLog cur.ffErrLog = errLog cur.ffDead = false } else { m.mu.Unlock() _ = killProcess(ffCmd) _ = errLog.Close() if outLog != nil { _ = outLog.Close() } return fmt.Errorf("stream stopped before ffmpeg attach") } m.mu.Unlock() go func() { _ = ffCmd.Wait() m.mu.Lock() if cur, ok := m.procs[sp.id]; ok && cur.ffmpeg == ffCmd { cur.ffDead = true } m.mu.Unlock() }() return nil } func (m *Media) Stop(id int64) error { m.mu.Lock() sp, ok := m.procs[id] if ok { sp.stopping = true } m.mu.Unlock() if !ok { st, _ := m.Store.GetStream(id) name := fmt.Sprintf("%d", id) if st.Name != "" { name = st.Name } _ = m.Store.CloseOpenSessions(id, db.SessionStopped, "stopped") _ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "stopped", PlayPath: "/hls/" + name + "/index.m3u8"}) return nil } m.closeSession(sp, db.SessionStopped, "stopped") m.stopAllVariants(sp) nrePID, ffPID := 0, 0 if sp.ffmpeg != nil && sp.ffmpeg.Process != nil { ffPID = sp.ffmpeg.Process.Pid _ = killProcess(sp.ffmpeg) } if sp.nre != nil && sp.nre.Process != nil { nrePID = sp.nre.Process.Pid _ = killProcess(sp.nre) } if sp.mpdProxy != nil { 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.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 } // closeSession ends the open stream_sessions row for this process, if any. func (m *Media) closeSession(sp *streamProc, reason, health string) { if sp == nil || sp.sessionID == 0 { return } _ = m.Store.CloseSession(sp.sessionID, reason, health) sp.sessionID = 0 } func (m *Media) Restart(id int64) error { 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) } func (m *Media) cleanupProc(id int64) { m.mu.Lock() defer m.mu.Unlock() sp, ok := m.procs[id] if !ok { return } if sp.nrePTY != nil { _ = sp.nrePTY.Close() sp.nrePTY = nil } if sp.nreLogFile != nil { _ = sp.nreLogFile.Close() sp.nreLogFile = nil } for _, w := range []*logfile.Writer{sp.ffOutLog, sp.ffErrLog} { if w != nil { _ = w.Close() } } delete(m.procs, id) } func (m *Media) monitorLoop() { t := time.NewTicker(5 * time.Second) defer t.Stop() for { select { case <-m.stopMon: return case <-t.C: m.mu.Lock() ids := make([]int64, 0, len(m.procs)) for id := range m.procs { ids = append(ids, id) } m.mu.Unlock() for _, id := range ids { m.refreshHealth(id) } } } } func (m *Media) refreshHealth(id int64) { m.mu.Lock() sp, ok := m.procs[id] m.mu.Unlock() if !ok || sp.stopping { return } m.mu.Lock() nreDead := sp.nreDead ffDead := sp.ffDead m.mu.Unlock() playPath := "/hls/" + sp.name + "/index.m3u8" uptime := time.Since(sp.started).Seconds() pid := int64(0) if sp.nre != nil && sp.nre.Process != nil { pid = int64(sp.nre.Process.Pid) } if nreDead { _ = m.Store.SetRuntime(id, db.RuntimePatch{ Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime, LastError: "NRE process exited — see data/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 data/logs/%s-nre.log", uptime, sp.name), }) m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime)) m.closeSession(sp, db.SessionNREExit, "down") m.report(sp, "down") m.cleanupProc(id) return } fi, err := os.Stat(sp.hlsIndex) if err != nil { _ = m.Store.SetRuntime(id, db.RuntimePatch{ 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) } return } age := time.Since(fi.ModTime()).Seconds() health := "ok" lastErr := "" if age > 45 { 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, 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] if !ok || cur.stopping || !cur.ffDead { m.mu.Unlock() return } // Claim the restart slot so monitorLoop does not spawn duplicates. cur.ffDead = false if cur.ffmpeg != nil { _ = killProcess(cur.ffmpeg) } tsPath := cur.tsPath m.mu.Unlock() minTS := sp.tsReadyBytes if st, err := os.Stat(tsPath); err != nil || st.Size() < minTS { m.mu.Lock() if cur, ok := m.procs[sp.id]; ok { cur.ffDead = true } m.mu.Unlock() return } 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 } m.mu.Unlock() return } m.mu.Lock() specs := sp.variantSpecs if cur, ok := m.procs[sp.id]; ok { specs = cur.variantSpecs } m.mu.Unlock() m.startVariantPackagers(sp, specs) m.writeMasterPlaylist(sp) } func headerMap(headersJSON string) map[string]string { headersJSON = strings.TrimSpace(headersJSON) if headersJSON == "" || headersJSON == "{}" { return nil } var m map[string]string if err := json.Unmarshal([]byte(headersJSON), &m); err != nil { return nil } out := map[string]string{} for k, v := range m { k = strings.TrimSpace(k) v = strings.TrimSpace(v) if k != "" && v != "" { out[k] = v } } return out } func headerFlags(headersJSON string) []string { m := headerMap(headersJSON) out := make([]string, 0, len(m)) for k, v := range m { out = append(out, k+": "+v) } return out } // 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 { var out []string seen := map[string]bool{} for _, line := range db.SplitKeyLines(raw) { if strings.Count(line, ":") != 1 || seen[line] { continue } seen[line] = true out = append(out, line) } if len(out) == 0 { return strings.TrimSpace(raw) + "\n" } return strings.Join(out, "\n") + "\n" } func killProcess(cmd *exec.Cmd) error { if cmd == nil || cmd.Process == nil { return nil } return killProcessTree(cmd) } func prependPathEnv(env []string, prefix string) []string { if prefix == "" { return env } out := make([]string, 0, len(env)+1) found := false for _, e := range env { if len(e) >= 5 && strings.EqualFold(e[:5], "PATH=") { out = append(out, "PATH="+prefix+string(os.PathListSeparator)+e[5:]) found = true continue } out = append(out, e) } if !found { out = append(out, "PATH="+prefix) } return out } // setEnvDefault sets KEY=value when KEY is missing or empty in env. func setEnvDefault(env []string, key, value string) []string { prefix := key + "=" for i, e := range env { if strings.HasPrefix(e, prefix) { if strings.TrimSpace(e[len(prefix):]) == "" { env[i] = prefix + value } return env } } return append(env, prefix+value) } func copyFile(src, dst string) error { in, err := os.Open(src) if err != nil { return err } defer in.Close() out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755) if err != nil { return err } defer out.Close() if _, err := io.Copy(out, in); err != nil { return err } return out.Close() } func waitPIDsGone(pids []int, timeout time.Duration) { deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { alive := false for _, pid := range pids { if pid <= 0 { continue } if !processDead(pid) { alive = true break } } if !alive { return } time.Sleep(100 * time.Millisecond) } } // findGrowingTSMin locates NRE's live-pipe-mux output. Depending on // version/flags it may be saveName.ts or saveName..ts (e.g. test.en.ts). func findGrowingTSMin(dir, saveName string, minSize int64) string { if minSize <= 0 { minSize = 256 * 1024 } candidates := []string{ filepath.Join(dir, saveName+".ts"), } if ents, err := os.ReadDir(dir); err == nil { prefix := saveName + "." for _, e := range ents { if e.IsDir() { continue } name := e.Name() if !strings.HasSuffix(strings.ToLower(name), ".ts") { continue } if name == saveName+".ts" || strings.HasPrefix(name, prefix) { candidates = append(candidates, filepath.Join(dir, name)) } } } var best string var bestSize int64 for _, p := range candidates { st, err := os.Stat(p) if err != nil || st.Size() < minSize { continue } if st.Size() > bestSize { bestSize = st.Size() best = p } } return best }