/// <summary> /// Selects a format from the list of available formats based on the given format specifier (single). /// Ported from _build_selector_function() in youtube_dl/YoutubeDL.py: /// https://github.com/ytdl-org/youtube-dl/blob/9c1e164e0cd77331ea4f0b474b32fd06f84bad71/youtube_dl/YoutubeDL.py#L1262-L1316. /// </summary> /// <returns>The selected format or null if not found.</returns> public static FormatData SelectSingleFormat(this VideoData videoData, string formatSpecifier) { if (new[] { "best", "worst", null }.Contains(formatSpecifier)) { var audioVideoFormats = videoData.GetAudioVideoFormats().ToList(); if (audioVideoFormats.Count > 0) { int index = formatSpecifier == "worst" ? 0 : (audioVideoFormats.Count - 1); return(audioVideoFormats[index]); } // select best video-only or audio-only format else { int index = formatSpecifier == "worst" ? 0 : (videoData.Formats.Length - 1); return(videoData.Formats[index]); } } else if (formatSpecifier == "bestaudio") { var audioFormats = videoData.GetAudioOnlyFormats().ToList(); if (audioFormats.Count > 0) { return(audioFormats[audioFormats.Count - 1]); } else { return(null); } } else if (formatSpecifier == "worstaudio") { var audioFormats = videoData.GetAudioOnlyFormats().ToList(); if (audioFormats.Count > 0) { return(audioFormats[0]); } else { return(null); } } else if (formatSpecifier == "bestvideo") { var audioFormats = videoData.GetVideoOnlyFormats().ToList(); if (audioFormats.Count > 0) { return(audioFormats[audioFormats.Count - 1]); } else { return(null); } } else if (formatSpecifier == "worstvideo") { var audioFormats = videoData.GetVideoOnlyFormats().ToList(); if (audioFormats.Count > 0) { return(audioFormats[0]); } else { return(null); } } else { string[] extensions = new[] { "mp4", "flv", "webm", "3gp", "m4a", "mp3", "ogg", "aac", "wav" }; if (extensions.Contains(formatSpecifier)) { var matches = videoData.Formats.Where(f => f.Extension == formatSpecifier); return(matches.LastOrDefault()); } else { var matches = videoData.Formats.Where(f => f.FormatId == formatSpecifier); return(matches.LastOrDefault()); } } }