package service import "github.com/noderunners/dlbot/internal/media" // fitOrder is the order "best that fits my limit" tries the qualities in. var fitOrder = []media.Profile{media.Best, media.P1080, media.P720, media.P480} // BestFit picks the highest quality whose estimated size is within // maxSize (0 means no limit), from the sizes yt-dlp reported (filesize or // filesize_approx, else bitrate times duration). // // Only qualities the source has are considered. A quality with no size // estimate counts as fitting only when no quality has one, since then // there is nothing to judge by and the worker enforces the cap on the real // file. When even the smallest quality is too big, the smallest is // returned with fits false, so the caller can refuse it with the usual // over-limit flow. func BestFit(info *CardInfo, maxSize int64) (p media.Profile, fits bool) { var avail []media.Profile anySize := false for _, q := range fitOrder { if h := q.Height(); h > 0 && info.MaxHeight > 0 && info.MaxHeight < h { continue // the source is smaller than this quality } avail = append(avail, q) if info.Sizes[string(q)] > 0 { anySize = true } } if !anySize || maxSize <= 0 { return media.Best, true } smallest := avail[len(avail)-1] for _, q := range avail { size := info.Sizes[string(q)] if size > 0 && size <= maxSize { return q, true } } // Prefer the smallest quality that has a size, so the refusal can say // how big it is. for i := len(avail) - 1; i >= 0; i-- { if info.Sizes[string(avail[i])] > 0 { return avail[i], false } } return smallest, false }