package db import ( "encoding/json" "strings" ) // Output formats. These are the muxers the packager can be asked to emit for // each enabled variant. They are orthogonal to the resolution ladder: the set // actually published is variants x outputs. const ( // FormatHLS is mpegts HLS — the original and only output, kept as the // default so an upgraded install publishes exactly what it did before. FormatHLS = "hls" // FormatCMAF is fMP4/CMAF HLS: init.mp4 plus .m4s segments. FormatCMAF = "hls_fmp4" // FormatDASH is MPEG-DASH. FormatDASH = "dash" // FormatTS is a progressive, endless MPEG-TS stream served from a shared // ring buffer rather than from disk. FormatTS = "mpegts" ) // OutputSpec is one configured output format for a stream. type OutputSpec struct { ID string `json:"id"` Label string `json:"label"` Format string `json:"format"` Enabled bool `json:"enabled"` // SegmentDuration and ListSize override the stream's packager settings for // this output only. Zero means "inherit". SegmentDuration int `json:"segment_duration,omitempty"` ListSize int `json:"list_size,omitempty"` } // OutputStatus is an OutputSpec as reported by the API. type OutputStatus struct { OutputSpec } // PublishLink is one playable endpoint: a variant crossed with an output // format, or the ABR master playlist. The dashboard renders one row per link. type PublishLink struct { VariantID string `json:"variant_id"` VariantLabel string `json:"variant_label"` OutputID string `json:"output_id"` OutputLabel string `json:"output_label"` Format string `json:"format"` PlayPath string `json:"play_path"` Health string `json:"health,omitempty"` PlaylistAgeS float64 `json:"playlist_age_s,omitempty"` // Master marks the ABR master playlist, which spans every variant. Master bool `json:"master,omitempty"` } // DefaultOutputs is the output set for a new stream: mpegts HLS only. The // other formats exist but stay off, so turning one on is always a deliberate // act and an upgraded install does not silently start transcoding more. func DefaultOutputs() []OutputSpec { return []OutputSpec{ {ID: "hls", Label: "HLS", Format: FormatHLS, Enabled: true}, {ID: "cmaf", Label: "CMAF", Format: FormatCMAF, Enabled: false}, {ID: "dash", Label: "DASH", Format: FormatDASH, Enabled: false}, {ID: "ts", Label: "TS", Format: FormatTS, Enabled: false}, } } // knownFormats maps a format to its default id and label. var knownFormats = map[string]struct{ id, label, container string }{ FormatHLS: {"hls", "HLS", "mpegts"}, FormatCMAF: {"cmaf", "CMAF", "fmp4"}, FormatDASH: {"dash", "DASH", "fmp4"}, FormatTS: {"ts", "TS", "mpegts"}, } // normalizeFormat maps user input onto a known format, tolerating the shorter // aliases the UI and API are likely to send. func normalizeFormat(f string) string { switch strings.ToLower(strings.TrimSpace(f)) { case FormatHLS, "m3u8", "hls_mpegts", "hls-ts": return FormatHLS case FormatCMAF, "cmaf", "fmp4", "hls-fmp4": return FormatCMAF case FormatDASH, "mpd": return FormatDASH case FormatTS, "ts", "progressive": return FormatTS } return "" } // ParseOutputsJSON reads outputs_json. Empty or unparseable falls back to the // defaults, matching how the variant ladder behaves. func ParseOutputsJSON(raw string) []OutputSpec { raw = strings.TrimSpace(raw) if raw == "" || raw == "[]" || raw == "null" { return DefaultOutputs() } var list []OutputSpec if err := json.Unmarshal([]byte(raw), &list); err != nil || len(list) == 0 { return DefaultOutputs() } return NormalizeOutputs(list) } // NormalizeOutputs fills ids and labels, drops unknown formats, de-duplicates // by format, and guarantees every known format has an entry so a client can // toggle one without having to know the full list. func NormalizeOutputs(in []OutputSpec) []OutputSpec { byFormat := map[string]OutputSpec{} for _, o := range in { f := normalizeFormat(o.Format) if f == "" { // Allow a client to identify an output by id alone. f = normalizeFormat(o.ID) } if f == "" { continue } meta := knownFormats[f] o.Format = f if o.ID = slug(o.ID); o.ID == "" { o.ID = meta.id } if strings.TrimSpace(o.Label) == "" { o.Label = meta.label } if o.SegmentDuration < 0 { o.SegmentDuration = 0 } if o.ListSize < 0 { o.ListSize = 0 } // A later entry for the same format wins, so a partial patch applies // cleanly over the defaults. byFormat[f] = o } out := make([]OutputSpec, 0, len(knownFormats)) for _, def := range DefaultOutputs() { if got, ok := byFormat[def.Format]; ok { out = append(out, got) continue } out = append(out, def) } // An output set with nothing enabled would publish nothing at all and // leave the stream unreachable; fall back to HLS. anyOn := false for _, o := range out { if o.Enabled { anyOn = true break } } if !anyOn { for i := range out { if out[i].Format == FormatHLS { out[i].Enabled = true } } } return out } func EncodeOutputsJSON(list []OutputSpec) (string, error) { list = NormalizeOutputs(list) b, err := json.Marshal(list) if err != nil { return "[]", err } return string(b), nil } // EnabledOutputs returns the outputs that should be muxed. func EnabledOutputs(list []OutputSpec) []OutputSpec { var out []OutputSpec for _, o := range list { if o.Enabled { out = append(out, o) } } return out } // AttachOutputStatuses builds the outputs array for API responses. func AttachOutputStatuses(streamName, outputsJSON string) []OutputStatus { specs := ParseOutputsJSON(outputsJSON) out := make([]OutputStatus, 0, len(specs)) for _, o := range specs { out = append(out, OutputStatus{OutputSpec: o}) } return out } // VariantDir is the www subdirectory for one variant: the stream name for the // source rung, and "-" for every other rung. This is the single // definition of that layout; the HLS gate parses it back. func VariantDir(streamName, variantID string, height int, audioOnly bool) string { variantID = slug(variantID) if !audioOnly && (height <= 0 || variantID == "" || variantID == SourceVariantID) { return streamName } return streamName + "-" + variantID } // OutputSubPath is the path of an output's playlist relative to its variant // directory. The mpegts HLS playlist stays at the root of the directory so // existing /hls//index.m3u8 URLs never move. func OutputSubPath(format string) string { switch normalizeFormat(format) { case FormatHLS: return "index.m3u8" case FormatCMAF: return "cmaf/index.m3u8" case FormatDASH: return "dash/index.mpd" } return "" } // OutputPlayPath is the URL for one variant x output pair. Progressive TS is // served from /live/ because it is a live pipe, not a file on disk. func OutputPlayPath(streamName, variantID string, height int, audioOnly bool, format string) string { dir := VariantDir(streamName, variantID, height, audioOnly) if normalizeFormat(format) == FormatTS { return "/live/" + dir + ".ts" } sub := OutputSubPath(format) if sub == "" { return "" } return "/hls/" + dir + "/" + sub } // MasterPlayPath is the ABR master playlist spanning every enabled variant. func MasterPlayPath(streamName string) string { return "/hls/" + streamName + "/master.m3u8" } // BuildPublishLinks is the cross product of enabled variants and enabled // outputs, with the ABR master first when there is more than one rung to // choose between. Health is left empty here and filled by the API layer, which // is the part that can see the files on disk. func BuildPublishLinks(streamName, variantsJSON, outputsJSON string) []PublishLink { variants := EnabledVariants(ParseVariantsJSON(variantsJSON)) outputs := EnabledOutputs(ParseOutputsJSON(outputsJSON)) links := make([]PublishLink, 0, len(variants)*len(outputs)+1) // The master is only meaningful when HLS is on and there is a real choice. hlsOn := false for _, o := range outputs { if o.Format == FormatHLS || o.Format == FormatCMAF { hlsOn = true break } } if hlsOn && len(variants) > 1 { links = append(links, PublishLink{ VariantID: "all", VariantLabel: "ABR", OutputID: "master", OutputLabel: "Master", Format: FormatHLS, PlayPath: MasterPlayPath(streamName), Master: true, }) } for _, v := range variants { for _, o := range outputs { p := OutputPlayPath(streamName, v.ID, v.Height, v.AudioOnly, o.Format) if p == "" { continue } links = append(links, PublishLink{ VariantID: v.ID, VariantLabel: v.Label, OutputID: o.ID, OutputLabel: o.Label, Format: o.Format, PlayPath: p, }) } } return links }