package media import ( "encoding/json" "log" "m3u8-downloader/pkg/constants" "m3u8-downloader/pkg/logging" "m3u8-downloader/pkg/utils" "os" "sort" "strconv" "sync" ) type ManifestWriter struct { ManifestPath string Segments []ManifestItem // Index maps a sequence number to its position in Segments. It holds // positions rather than pointers because append reallocates the backing // array, which would leave previously handed-out element pointers aimed at // a stale copy. Index map[string]int // mu guards the fields above: every variant downloads concurrently, and // each reports its segments as they land. mu sync.Mutex } type ManifestItem struct { SeqNo string `json:"seqNo"` Resolution string `json:"resolution"` } func NewManifestWriter(eventName string) *ManifestWriter { cfg := constants.MustGetConfig() return &ManifestWriter{ ManifestPath: cfg.GetManifestPath(eventName), Segments: make([]ManifestItem, 0), Index: make(map[string]int), } } // AddOrUpdateSegment records that a segment was downloaded, keeping the // highest-resolution variant seen for each sequence number. func (m *ManifestWriter) AddOrUpdateSegment(seqNo string, resolution string) { m.mu.Lock() defer m.mu.Unlock() if m.Index == nil { m.Index = make(map[string]int) } if m.Segments == nil { m.Segments = make([]ManifestItem, 0) } if pos, ok := m.Index[seqNo]; ok { if ResolutionHeight(resolution) > ResolutionHeight(m.Segments[pos].Resolution) { m.Segments[pos].Resolution = resolution } return } m.Segments = append(m.Segments, ManifestItem{SeqNo: seqNo, Resolution: resolution}) m.Index[seqNo] = len(m.Segments) - 1 } // Len reports how many distinct sequence numbers have been recorded. func (m *ManifestWriter) Len() int { m.mu.Lock() defer m.mu.Unlock() return len(m.Segments) } func (m *ManifestWriter) WriteManifest() { // Sort a copy: reordering Segments in place would invalidate Index, and a // recording may still be writing into it. m.mu.Lock() segments := make([]ManifestItem, len(m.Segments)) copy(segments, m.Segments) m.mu.Unlock() sort.Slice(segments, func(i, j int) bool { return lessSeqNo(segments[i].SeqNo, segments[j].SeqNo) }) data, err := json.MarshalIndent(segments, "", " ") if err != nil { log.Printf("Failed to marshal manifest: %v", err) logging.MustGetFactory().Download.Error("failed to marshal manifest", logging.KeyError, err.Error()) return } if err := utils.ValidateWritablePath(m.ManifestPath); err != nil { log.Printf("Manifest path validation failed: %v", err) logging.MustGetFactory().Download.Error("manifest path validation failed", logging.KeyError, err.Error()) return } file, err := os.Create(m.ManifestPath) if err != nil { log.Printf("Failed to create manifest file: %v", err) logging.MustGetFactory().Download.Error("failed to create manifest file", logging.KeyError, err.Error()) return } defer file.Close() _, err = file.Write(data) if err != nil { log.Printf("Failed to write manifest file: %v", err) logging.MustGetFactory().Download.Error("failed to write manifest file", logging.KeyError, err.Error()) return } } // lessSeqNo orders sequence numbers numerically, so segment 9 precedes segment // 10 instead of sorting after it as the strings would. Values that are not // numeric fall back to lexicographic order. func lessSeqNo(a, b string) bool { ai, aErr := strconv.ParseUint(a, 10, 64) bi, bErr := strconv.ParseUint(b, 10, 64) if aErr == nil && bErr == nil { return ai < bi } return a < b }