2
0

EncoderValidator.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using Microsoft.Extensions.Logging;
  9. namespace MediaBrowser.MediaEncoding.Encoder
  10. {
  11. public class EncoderValidator
  12. {
  13. private const string DefaultEncoderPath = "ffmpeg";
  14. private static readonly string[] _requiredDecoders = new[]
  15. {
  16. "h264",
  17. "hevc",
  18. "mpeg2video",
  19. "mpeg4",
  20. "msmpeg4",
  21. "dts",
  22. "ac3",
  23. "aac",
  24. "mp3",
  25. "flac",
  26. "h264_qsv",
  27. "hevc_qsv",
  28. "mpeg2_qsv",
  29. "vc1_qsv",
  30. "vp8_qsv",
  31. "vp9_qsv",
  32. "h264_cuvid",
  33. "hevc_cuvid",
  34. "mpeg2_cuvid",
  35. "vc1_cuvid",
  36. "mpeg4_cuvid",
  37. "vp8_cuvid",
  38. "vp9_cuvid",
  39. "h264_mmal",
  40. "mpeg2_mmal",
  41. "mpeg4_mmal",
  42. "vc1_mmal",
  43. "h264_mediacodec",
  44. "hevc_mediacodec",
  45. "mpeg2_mediacodec",
  46. "mpeg4_mediacodec",
  47. "vp8_mediacodec",
  48. "vp9_mediacodec",
  49. "h264_opencl",
  50. "hevc_opencl",
  51. "mpeg2_opencl",
  52. "mpeg4_opencl",
  53. "vp8_opencl",
  54. "vp9_opencl",
  55. "vc1_opencl"
  56. };
  57. private static readonly string[] _requiredEncoders = new[]
  58. {
  59. "libx264",
  60. "libx265",
  61. "mpeg4",
  62. "msmpeg4",
  63. "libvpx",
  64. "libvpx-vp9",
  65. "aac",
  66. "libfdk_aac",
  67. "ac3",
  68. "libmp3lame",
  69. "libopus",
  70. "libvorbis",
  71. "flac",
  72. "srt",
  73. "h264_amf",
  74. "hevc_amf",
  75. "h264_qsv",
  76. "hevc_qsv",
  77. "h264_nvenc",
  78. "hevc_nvenc",
  79. "h264_vaapi",
  80. "hevc_vaapi",
  81. "h264_omx",
  82. "hevc_omx",
  83. "h264_v4l2m2m",
  84. "h264_videotoolbox",
  85. "hevc_videotoolbox"
  86. };
  87. // These are the library versions that corresponds to our minimum ffmpeg version 4.x according to the version table below
  88. private static readonly IReadOnlyDictionary<string, Version> _ffmpegMinimumLibraryVersions = new Dictionary<string, Version>
  89. {
  90. { "libavutil", new Version(56, 14) },
  91. { "libavcodec", new Version(58, 18) },
  92. { "libavformat", new Version(58, 12) },
  93. { "libavdevice", new Version(58, 3) },
  94. { "libavfilter", new Version(7, 16) },
  95. { "libswscale", new Version(5, 1) },
  96. { "libswresample", new Version(3, 1) },
  97. { "libpostproc", new Version(55, 1) }
  98. };
  99. private readonly ILogger _logger;
  100. private readonly string _encoderPath;
  101. public EncoderValidator(ILogger logger, string encoderPath = DefaultEncoderPath)
  102. {
  103. _logger = logger;
  104. _encoderPath = encoderPath;
  105. }
  106. private enum Codec
  107. {
  108. Encoder,
  109. Decoder
  110. }
  111. // When changing this, also change the minimum library versions in _ffmpegMinimumLibraryVersions
  112. public static Version MinVersion { get; } = new Version(4, 0);
  113. public static Version? MaxVersion { get; } = null;
  114. public bool ValidateVersion()
  115. {
  116. string output;
  117. try
  118. {
  119. output = GetProcessOutput(_encoderPath, "-version");
  120. }
  121. catch (Exception ex)
  122. {
  123. _logger.LogError(ex, "Error validating encoder");
  124. return false;
  125. }
  126. if (string.IsNullOrWhiteSpace(output))
  127. {
  128. _logger.LogError("FFmpeg validation: The process returned no result");
  129. return false;
  130. }
  131. _logger.LogDebug("ffmpeg output: {Output}", output);
  132. return ValidateVersionInternal(output);
  133. }
  134. internal bool ValidateVersionInternal(string versionOutput)
  135. {
  136. if (versionOutput.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
  137. {
  138. _logger.LogError("FFmpeg validation: avconv instead of ffmpeg is not supported");
  139. return false;
  140. }
  141. // Work out what the version under test is
  142. var version = GetFFmpegVersion(versionOutput);
  143. _logger.LogInformation("Found ffmpeg version {Version}", version != null ? version.ToString() : "unknown");
  144. if (version == null)
  145. {
  146. if (MaxVersion != null) // Version is unknown
  147. {
  148. if (MinVersion == MaxVersion)
  149. {
  150. _logger.LogWarning("FFmpeg validation: We recommend version {MinVersion}", MinVersion);
  151. }
  152. else
  153. {
  154. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {MinVersion} and maximum of {MaxVersion}", MinVersion, MaxVersion);
  155. }
  156. }
  157. else
  158. {
  159. _logger.LogWarning("FFmpeg validation: We recommend minimum version {MinVersion}", MinVersion);
  160. }
  161. return false;
  162. }
  163. else if (version < MinVersion) // Version is below what we recommend
  164. {
  165. _logger.LogWarning("FFmpeg validation: The minimum recommended version is {MinVersion}", MinVersion);
  166. return false;
  167. }
  168. else if (MaxVersion != null && version > MaxVersion) // Version is above what we recommend
  169. {
  170. _logger.LogWarning("FFmpeg validation: The maximum recommended version is {MaxVersion}", MaxVersion);
  171. return false;
  172. }
  173. return true;
  174. }
  175. public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
  176. public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
  177. public IEnumerable<string> GetHwaccels() => GetHwaccelTypes();
  178. /// <summary>
  179. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  180. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  181. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  182. /// If that fails then we test the libraries to determine if they're newer than our minimum versions.
  183. /// </summary>
  184. /// <param name="output">The output from "ffmpeg -version".</param>
  185. /// <returns>The FFmpeg version.</returns>
  186. internal Version? GetFFmpegVersion(string output)
  187. {
  188. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  189. var match = Regex.Match(output, @"^ffmpeg version n?((?:[0-9]+\.?)+)");
  190. if (match.Success)
  191. {
  192. if (Version.TryParse(match.Groups[1].Value, out var result))
  193. {
  194. return result;
  195. }
  196. }
  197. var versionMap = GetFFmpegLibraryVersions(output);
  198. var allVersionsValidated = true;
  199. foreach (var minimumVersion in _ffmpegMinimumLibraryVersions)
  200. {
  201. if (versionMap.TryGetValue(minimumVersion.Key, out var foundVersion))
  202. {
  203. if (foundVersion >= minimumVersion.Value)
  204. {
  205. _logger.LogInformation("Found {Library} version {FoundVersion} ({MinimumVersion})", minimumVersion.Key, foundVersion, minimumVersion.Value);
  206. }
  207. else
  208. {
  209. _logger.LogWarning("Found {Library} version {FoundVersion} lower than recommended version {MinimumVersion}", minimumVersion.Key, foundVersion, minimumVersion.Value);
  210. allVersionsValidated = false;
  211. }
  212. }
  213. else
  214. {
  215. _logger.LogError("{Library} version not found", minimumVersion.Key);
  216. allVersionsValidated = false;
  217. }
  218. }
  219. return allVersionsValidated ? MinVersion : null;
  220. }
  221. /// <summary>
  222. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  223. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc.".
  224. /// </summary>
  225. /// <param name="output">The 'ffmpeg -version' output.</param>
  226. /// <returns>The library names and major.minor version numbers.</returns>
  227. private static IReadOnlyDictionary<string, Version> GetFFmpegLibraryVersions(string output)
  228. {
  229. var map = new Dictionary<string, Version>();
  230. foreach (Match match in Regex.Matches(
  231. output,
  232. @"((?<name>lib\w+)\s+(?<major>[0-9]+)\.\s*(?<minor>[0-9]+))",
  233. RegexOptions.Multiline))
  234. {
  235. var version = new Version(
  236. int.Parse(match.Groups["major"].Value, CultureInfo.InvariantCulture),
  237. int.Parse(match.Groups["minor"].Value, CultureInfo.InvariantCulture));
  238. map.Add(match.Groups["name"].Value, version);
  239. }
  240. return map;
  241. }
  242. private IEnumerable<string> GetHwaccelTypes()
  243. {
  244. string? output = null;
  245. try
  246. {
  247. output = GetProcessOutput(_encoderPath, "-hwaccels");
  248. }
  249. catch (Exception ex)
  250. {
  251. _logger.LogError(ex, "Error detecting available hwaccel types");
  252. }
  253. if (string.IsNullOrWhiteSpace(output))
  254. {
  255. return Enumerable.Empty<string>();
  256. }
  257. var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
  258. _logger.LogInformation("Available hwaccel types: {Types}", found);
  259. return found;
  260. }
  261. public bool CheckFilter(string filter, string option)
  262. {
  263. if (string.IsNullOrEmpty(filter))
  264. {
  265. return false;
  266. }
  267. string output;
  268. try
  269. {
  270. output = GetProcessOutput(_encoderPath, "-h filter=" + filter);
  271. }
  272. catch (Exception ex)
  273. {
  274. _logger.LogError(ex, "Error detecting the given filter");
  275. return false;
  276. }
  277. if (output.Contains("Filter " + filter, StringComparison.Ordinal))
  278. {
  279. if (string.IsNullOrEmpty(option))
  280. {
  281. return true;
  282. }
  283. return output.Contains(option, StringComparison.Ordinal);
  284. }
  285. _logger.LogWarning("Filter: {Name} with option {Option} is not available", filter, option);
  286. return false;
  287. }
  288. private IEnumerable<string> GetCodecs(Codec codec)
  289. {
  290. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  291. string output;
  292. try
  293. {
  294. output = GetProcessOutput(_encoderPath, "-" + codecstr);
  295. }
  296. catch (Exception ex)
  297. {
  298. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  299. return Enumerable.Empty<string>();
  300. }
  301. if (string.IsNullOrWhiteSpace(output))
  302. {
  303. return Enumerable.Empty<string>();
  304. }
  305. var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
  306. var found = Regex
  307. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  308. .Cast<Match>()
  309. .Select(x => x.Groups["codec"].Value)
  310. .Where(x => required.Contains(x));
  311. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  312. return found;
  313. }
  314. private string GetProcessOutput(string path, string arguments)
  315. {
  316. using (var process = new Process()
  317. {
  318. StartInfo = new ProcessStartInfo(path, arguments)
  319. {
  320. CreateNoWindow = true,
  321. UseShellExecute = false,
  322. WindowStyle = ProcessWindowStyle.Hidden,
  323. ErrorDialog = false,
  324. RedirectStandardOutput = true,
  325. // ffmpeg uses stderr to log info, don't show this
  326. RedirectStandardError = true
  327. }
  328. })
  329. {
  330. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  331. process.Start();
  332. return process.StandardOutput.ReadToEnd();
  333. }
  334. }
  335. }
  336. }