package media import ( "sort" "strings" youtubev2 "github.com/kkdai/youtube/v2" ) // SortYoutubeAudio returns the provided formats ordered in descending preferred // order. The ideal candidate is opus-encoded stereo audio in a webm container, // with the lowest available bitrate. func SortYoutubeAudio(inFormats youtubev2.FormatList) youtubev2.FormatList { var formats youtubev2.FormatList for _, format := range inFormats { if format.FPS == 0 && format.AudioChannels > 0 { formats = append(formats, format) } } sort.SliceStable(formats, func(i, j int) bool { isOpusI := strings.Contains(formats[i].MimeType, "opus") isOpusJ := strings.Contains(formats[j].MimeType, "opus") if isOpusI && isOpusJ { isStereoI := formats[i].AudioChannels == 2 isStereoJ := formats[j].AudioChannels == 2 if isStereoI && isStereoJ { return formats[i].ContentLength < formats[j].ContentLength } return isStereoI } return isOpusI }) return formats } // SortYoutubeVideo returns the provided formats ordered in descending preferred // order. The ideal candidate is video in an mp4 container with a low // bitrate, with audio channels (needed to allow synced playback on the // website). func SortYoutubeVideo(inFormats youtubev2.FormatList) youtubev2.FormatList { var formats youtubev2.FormatList for _, format := range inFormats { if format.FPS > 0 && format.ContentLength > 0 { formats = append(formats, format) } } sort.SliceStable(formats, func(i, j int) bool { isMP4I := strings.Contains(formats[i].MimeType, "mp4") isMP4J := strings.Contains(formats[j].MimeType, "mp4") if isMP4I && isMP4J { return formats[i].ContentLength < formats[j].ContentLength } return isMP4I }) return formats }