package supervisor import ( "fmt" "path/filepath" "strconv" "strings" "streamd/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 ... ", 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, } }