EncoderValidator.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 static readonly string[] _requiredDecoders = new[]
  14. {
  15. "h264",
  16. "hevc",
  17. "vp8",
  18. "libvpx",
  19. "vp9",
  20. "libvpx-vp9",
  21. "av1",
  22. "libdav1d",
  23. "mpeg2video",
  24. "mpeg4",
  25. "msmpeg4",
  26. "dts",
  27. "ac3",
  28. "aac",
  29. "mp3",
  30. "flac",
  31. "h264_qsv",
  32. "hevc_qsv",
  33. "mpeg2_qsv",
  34. "vc1_qsv",
  35. "vp8_qsv",
  36. "vp9_qsv",
  37. "av1_qsv",
  38. "h264_cuvid",
  39. "hevc_cuvid",
  40. "mpeg2_cuvid",
  41. "vc1_cuvid",
  42. "mpeg4_cuvid",
  43. "vp8_cuvid",
  44. "vp9_cuvid",
  45. "av1_cuvid"
  46. };
  47. private static readonly string[] _requiredEncoders = new[]
  48. {
  49. "libx264",
  50. "libx265",
  51. "mpeg4",
  52. "msmpeg4",
  53. "libvpx",
  54. "libvpx-vp9",
  55. "aac",
  56. "libfdk_aac",
  57. "ac3",
  58. "libmp3lame",
  59. "libopus",
  60. "libvorbis",
  61. "flac",
  62. "srt",
  63. "h264_amf",
  64. "hevc_amf",
  65. "h264_qsv",
  66. "hevc_qsv",
  67. "h264_nvenc",
  68. "hevc_nvenc",
  69. "h264_vaapi",
  70. "hevc_vaapi",
  71. "h264_v4l2m2m",
  72. "h264_videotoolbox",
  73. "hevc_videotoolbox"
  74. };
  75. private static readonly string[] _requiredFilters = new[]
  76. {
  77. // sw
  78. "alphasrc",
  79. "zscale",
  80. // qsv
  81. "scale_qsv",
  82. "vpp_qsv",
  83. "deinterlace_qsv",
  84. "overlay_qsv",
  85. // cuda
  86. "scale_cuda",
  87. "yadif_cuda",
  88. "tonemap_cuda",
  89. "overlay_cuda",
  90. "hwupload_cuda",
  91. // opencl
  92. "scale_opencl",
  93. "tonemap_opencl",
  94. "overlay_opencl",
  95. // vaapi
  96. "scale_vaapi",
  97. "deinterlace_vaapi",
  98. "tonemap_vaapi",
  99. "overlay_vaapi",
  100. "hwupload_vaapi"
  101. };
  102. private static readonly IReadOnlyDictionary<int, string[]> _filterOptionsDict = new Dictionary<int, string[]>
  103. {
  104. { 0, new string[] { "scale_cuda", "Output format (default \"same\")" } },
  105. { 1, new string[] { "tonemap_cuda", "GPU accelerated HDR to SDR tonemapping" } },
  106. { 2, new string[] { "tonemap_opencl", "bt2390" } },
  107. { 3, new string[] { "overlay_opencl", "Action to take when encountering EOF from secondary input" } },
  108. { 4, new string[] { "overlay_vaapi", "Action to take when encountering EOF from secondary input" } }
  109. };
  110. // These are the library versions that corresponds to our minimum ffmpeg version 4.x according to the version table below
  111. private static readonly IReadOnlyDictionary<string, Version> _ffmpegMinimumLibraryVersions = new Dictionary<string, Version>
  112. {
  113. { "libavutil", new Version(56, 14) },
  114. { "libavcodec", new Version(58, 18) },
  115. { "libavformat", new Version(58, 12) },
  116. { "libavdevice", new Version(58, 3) },
  117. { "libavfilter", new Version(7, 16) },
  118. { "libswscale", new Version(5, 1) },
  119. { "libswresample", new Version(3, 1) },
  120. { "libpostproc", new Version(55, 1) }
  121. };
  122. private readonly ILogger _logger;
  123. private readonly string _encoderPath;
  124. public EncoderValidator(ILogger logger, string encoderPath)
  125. {
  126. _logger = logger;
  127. _encoderPath = encoderPath;
  128. }
  129. private enum Codec
  130. {
  131. Encoder,
  132. Decoder
  133. }
  134. // When changing this, also change the minimum library versions in _ffmpegMinimumLibraryVersions
  135. public static Version MinVersion { get; } = new Version(4, 0);
  136. public static Version? MaxVersion { get; } = null;
  137. public bool ValidateVersion()
  138. {
  139. string output;
  140. try
  141. {
  142. output = GetProcessOutput(_encoderPath, "-version", false);
  143. }
  144. catch (Exception ex)
  145. {
  146. _logger.LogError(ex, "Error validating encoder");
  147. return false;
  148. }
  149. if (string.IsNullOrWhiteSpace(output))
  150. {
  151. _logger.LogError("FFmpeg validation: The process returned no result");
  152. return false;
  153. }
  154. _logger.LogDebug("ffmpeg output: {Output}", output);
  155. return ValidateVersionInternal(output);
  156. }
  157. internal bool ValidateVersionInternal(string versionOutput)
  158. {
  159. if (versionOutput.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
  160. {
  161. _logger.LogError("FFmpeg validation: avconv instead of ffmpeg is not supported");
  162. return false;
  163. }
  164. // Work out what the version under test is
  165. var version = GetFFmpegVersionInternal(versionOutput);
  166. _logger.LogInformation("Found ffmpeg version {Version}", version != null ? version.ToString() : "unknown");
  167. if (version == null)
  168. {
  169. if (MaxVersion != null) // Version is unknown
  170. {
  171. if (MinVersion == MaxVersion)
  172. {
  173. _logger.LogWarning("FFmpeg validation: We recommend version {MinVersion}", MinVersion);
  174. }
  175. else
  176. {
  177. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {MinVersion} and maximum of {MaxVersion}", MinVersion, MaxVersion);
  178. }
  179. }
  180. else
  181. {
  182. _logger.LogWarning("FFmpeg validation: We recommend minimum version {MinVersion}", MinVersion);
  183. }
  184. return false;
  185. }
  186. else if (version < MinVersion) // Version is below what we recommend
  187. {
  188. _logger.LogWarning("FFmpeg validation: The minimum recommended version is {MinVersion}", MinVersion);
  189. return false;
  190. }
  191. else if (MaxVersion != null && version > MaxVersion) // Version is above what we recommend
  192. {
  193. _logger.LogWarning("FFmpeg validation: The maximum recommended version is {MaxVersion}", MaxVersion);
  194. return false;
  195. }
  196. return true;
  197. }
  198. public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
  199. public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
  200. public IEnumerable<string> GetHwaccels() => GetHwaccelTypes();
  201. public IEnumerable<string> GetFilters() => GetFFmpegFilters();
  202. public IDictionary<int, bool> GetFiltersWithOption() => GetFFmpegFiltersWithOption();
  203. public Version? GetFFmpegVersion()
  204. {
  205. string output;
  206. try
  207. {
  208. output = GetProcessOutput(_encoderPath, "-version", false);
  209. }
  210. catch (Exception ex)
  211. {
  212. _logger.LogError(ex, "Error validating encoder");
  213. return null;
  214. }
  215. if (string.IsNullOrWhiteSpace(output))
  216. {
  217. _logger.LogError("FFmpeg validation: The process returned no result");
  218. return null;
  219. }
  220. _logger.LogDebug("ffmpeg output: {Output}", output);
  221. return GetFFmpegVersionInternal(output);
  222. }
  223. /// <summary>
  224. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  225. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  226. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  227. /// If that fails then we test the libraries to determine if they're newer than our minimum versions.
  228. /// </summary>
  229. /// <param name="output">The output from "ffmpeg -version".</param>
  230. /// <returns>The FFmpeg version.</returns>
  231. internal Version? GetFFmpegVersionInternal(string output)
  232. {
  233. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  234. var match = Regex.Match(output, @"^ffmpeg version n?((?:[0-9]+\.?)+)");
  235. if (match.Success)
  236. {
  237. if (Version.TryParse(match.Groups[1].Value, out var result))
  238. {
  239. return result;
  240. }
  241. }
  242. var versionMap = GetFFmpegLibraryVersions(output);
  243. var allVersionsValidated = true;
  244. foreach (var minimumVersion in _ffmpegMinimumLibraryVersions)
  245. {
  246. if (versionMap.TryGetValue(minimumVersion.Key, out var foundVersion))
  247. {
  248. if (foundVersion >= minimumVersion.Value)
  249. {
  250. _logger.LogInformation("Found {Library} version {FoundVersion} ({MinimumVersion})", minimumVersion.Key, foundVersion, minimumVersion.Value);
  251. }
  252. else
  253. {
  254. _logger.LogWarning("Found {Library} version {FoundVersion} lower than recommended version {MinimumVersion}", minimumVersion.Key, foundVersion, minimumVersion.Value);
  255. allVersionsValidated = false;
  256. }
  257. }
  258. else
  259. {
  260. _logger.LogError("{Library} version not found", minimumVersion.Key);
  261. allVersionsValidated = false;
  262. }
  263. }
  264. return allVersionsValidated ? MinVersion : null;
  265. }
  266. /// <summary>
  267. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  268. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc.".
  269. /// </summary>
  270. /// <param name="output">The 'ffmpeg -version' output.</param>
  271. /// <returns>The library names and major.minor version numbers.</returns>
  272. private static IReadOnlyDictionary<string, Version> GetFFmpegLibraryVersions(string output)
  273. {
  274. var map = new Dictionary<string, Version>();
  275. foreach (Match match in Regex.Matches(
  276. output,
  277. @"((?<name>lib\w+)\s+(?<major>[0-9]+)\.\s*(?<minor>[0-9]+))",
  278. RegexOptions.Multiline))
  279. {
  280. var version = new Version(
  281. int.Parse(match.Groups["major"].Value, CultureInfo.InvariantCulture),
  282. int.Parse(match.Groups["minor"].Value, CultureInfo.InvariantCulture));
  283. map.Add(match.Groups["name"].Value, version);
  284. }
  285. return map;
  286. }
  287. public bool CheckVaapiDeviceByDriverName(string driverName, string renderNodePath)
  288. {
  289. if (!OperatingSystem.IsLinux())
  290. {
  291. return false;
  292. }
  293. if (string.IsNullOrEmpty(driverName) || string.IsNullOrEmpty(renderNodePath))
  294. {
  295. return false;
  296. }
  297. try
  298. {
  299. var output = GetProcessOutput(_encoderPath, "-v verbose -hide_banner -init_hw_device vaapi=va:" + renderNodePath, true);
  300. return output.Contains(driverName, StringComparison.Ordinal);
  301. }
  302. catch (Exception ex)
  303. {
  304. _logger.LogError(ex, "Error detecting the given vaapi render node path");
  305. return false;
  306. }
  307. }
  308. private IEnumerable<string> GetHwaccelTypes()
  309. {
  310. string? output = null;
  311. try
  312. {
  313. output = GetProcessOutput(_encoderPath, "-hwaccels", false);
  314. }
  315. catch (Exception ex)
  316. {
  317. _logger.LogError(ex, "Error detecting available hwaccel types");
  318. }
  319. if (string.IsNullOrWhiteSpace(output))
  320. {
  321. return Enumerable.Empty<string>();
  322. }
  323. var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
  324. _logger.LogInformation("Available hwaccel types: {Types}", found);
  325. return found;
  326. }
  327. public bool CheckFilterWithOption(string filter, string option)
  328. {
  329. if (string.IsNullOrEmpty(filter) || string.IsNullOrEmpty(option))
  330. {
  331. return false;
  332. }
  333. string output;
  334. try
  335. {
  336. output = GetProcessOutput(_encoderPath, "-h filter=" + filter, false);
  337. }
  338. catch (Exception ex)
  339. {
  340. _logger.LogError(ex, "Error detecting the given filter");
  341. return false;
  342. }
  343. if (output.Contains("Filter " + filter, StringComparison.Ordinal))
  344. {
  345. return output.Contains(option, StringComparison.Ordinal);
  346. }
  347. _logger.LogWarning("Filter: {Name} with option {Option} is not available", filter, option);
  348. return false;
  349. }
  350. private IEnumerable<string> GetCodecs(Codec codec)
  351. {
  352. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  353. string output;
  354. try
  355. {
  356. output = GetProcessOutput(_encoderPath, "-" + codecstr, false);
  357. }
  358. catch (Exception ex)
  359. {
  360. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  361. return Enumerable.Empty<string>();
  362. }
  363. if (string.IsNullOrWhiteSpace(output))
  364. {
  365. return Enumerable.Empty<string>();
  366. }
  367. var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
  368. var found = Regex
  369. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  370. .Cast<Match>()
  371. .Select(x => x.Groups["codec"].Value)
  372. .Where(x => required.Contains(x));
  373. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  374. return found;
  375. }
  376. private IEnumerable<string> GetFFmpegFilters()
  377. {
  378. string output;
  379. try
  380. {
  381. output = GetProcessOutput(_encoderPath, "-filters", false);
  382. }
  383. catch (Exception ex)
  384. {
  385. _logger.LogError(ex, "Error detecting available filters");
  386. return Enumerable.Empty<string>();
  387. }
  388. if (string.IsNullOrWhiteSpace(output))
  389. {
  390. return Enumerable.Empty<string>();
  391. }
  392. var found = Regex
  393. .Matches(output, @"^\s\S{3}\s(?<filter>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  394. .Cast<Match>()
  395. .Select(x => x.Groups["filter"].Value)
  396. .Where(x => _requiredFilters.Contains(x));
  397. _logger.LogInformation("Available filters: {Filters}", found);
  398. return found;
  399. }
  400. private IDictionary<int, bool> GetFFmpegFiltersWithOption()
  401. {
  402. IDictionary<int, bool> dict = new Dictionary<int, bool>();
  403. for (int i = 0; i < _filterOptionsDict.Count; i++)
  404. {
  405. if (_filterOptionsDict.TryGetValue(i, out var val) && val.Length == 2)
  406. {
  407. dict.Add(i, CheckFilterWithOption(val[0], val[1]));
  408. }
  409. }
  410. return dict;
  411. }
  412. private string GetProcessOutput(string path, string arguments, bool readStdErr)
  413. {
  414. using (var process = new Process()
  415. {
  416. StartInfo = new ProcessStartInfo(path, arguments)
  417. {
  418. CreateNoWindow = true,
  419. UseShellExecute = false,
  420. WindowStyle = ProcessWindowStyle.Hidden,
  421. ErrorDialog = false,
  422. RedirectStandardOutput = true,
  423. RedirectStandardError = true
  424. }
  425. })
  426. {
  427. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  428. process.Start();
  429. return readStdErr ? process.StandardError.ReadToEnd() : process.StandardOutput.ReadToEnd();
  430. }
  431. }
  432. }
  433. }