package supervisor import ( "fmt" "io" "os" "os/exec" "path/filepath" "sort" "strings" "streamd/apps/streamd/internal/db" "streamd/apps/streamd/internal/logfile" ) type variantProc struct { spec db.VariantSpec wwwDir string index string cmd *exec.Cmd outLog *logfile.Writer errLog *logfile.Writer dead bool } func (m *Media) startVariantPackagers(sp *streamProc, specs []db.VariantSpec) { scaled := db.ScaledVariants(specs) if len(scaled) == 0 { return } m.mu.Lock() cur, ok := m.procs[sp.id] if !ok || cur.stopping { m.mu.Unlock() return } // Drop any previous variant workers before spawning new ones. old := cur.variants cur.variants = nil m.mu.Unlock() for _, vp := range old { m.stopVariant(vp) } var started []*variantProc for _, spec := range scaled { vp, err := m.spawnVariantFFmpeg(sp, spec) if err != nil { 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.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() if cur, ok := m.procs[sp.id]; ok && !cur.stopping { cur.variants = started } else { m.mu.Unlock() for _, vp := range started { m.stopVariant(vp) } return } m.mu.Unlock() } func (m *Media) spawnVariantFFmpeg(sp *streamProc, spec db.VariantSpec) (*variantProc, error) { 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 } 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 } 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 } hideWindow(ffCmd) if err := ffCmd.Start(); err != nil { _ = errLog.Close() if outLog != nil { _ = outLog.Close() } return nil, err } vp := &variantProc{ spec: spec, wwwDir: wwwDir, index: filepath.Join(wwwDir, "index.m3u8"), cmd: ffCmd, outLog: outLog, errLog: errLog, } go func() { _ = ffCmd.Wait() m.mu.Lock() defer m.mu.Unlock() if cur, ok := m.procs[sp.id]; ok { for _, v := range cur.variants { if v == vp { v.dead = true } } } }() return vp, nil } // doubleBitrate is the -bufsize that pairs with a -maxrate. func doubleBitrate(b string) string { n := db.BitrateBps(b) if n <= 0 { return "5600k" } return fmt.Sprintf("%dk", n*2/1000) } func (m *Media) stopVariant(vp *variantProc) { if vp == nil { return } if vp.cmd != nil && vp.cmd.Process != nil { _ = killProcess(vp.cmd) } for _, w := range []*logfile.Writer{vp.outLog, vp.errLog} { if w != nil { _ = w.Close() } } } func (m *Media) stopAllVariants(sp *streamProc) { m.mu.Lock() list := sp.variants sp.variants = nil m.mu.Unlock() for _, vp := range list { m.stopVariant(vp) } } func (m *Media) restartDeadVariants(sp *streamProc) { m.mu.Lock() cur, ok := m.procs[sp.id] if !ok || cur.stopping { m.mu.Unlock() return } var dead []*variantProc var alive []*variantProc for _, vp := range cur.variants { if vp.dead { dead = append(dead, vp) } else { alive = append(alive, vp) } } cur.variants = alive m.mu.Unlock() 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.Log.Error("variant restart failed", "stream", sp.name, "variant", vp.spec.ID, "err", err) continue } m.mu.Lock() if cur, ok := m.procs[sp.id]; ok && !cur.stopping { cur.variants = append(cur.variants, fresh) } else { m.mu.Unlock() m.stopVariant(fresh) return } m.mu.Unlock() 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 }