EncoderValidator.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. "procamp_vaapi",
  100. "overlay_vaapi",
  101. "hwupload_vaapi",
  102. // vulkan
  103. "libplacebo",
  104. "scale_vulkan",
  105. "overlay_vulkan"
  106. };
  107. private static readonly IReadOnlyDictionary<int, string[]> _filterOptionsDict = new Dictionary<int, string[]>
  108. {
  109. { 0, new string[] { "scale_cuda", "Output format (default \"same\")" } },
  110. { 1, new string[] { "tonemap_cuda", "GPU accelerated HDR to SDR tonemapping" } },
  111. { 2, new string[] { "tonemap_opencl", "bt2390" } },
  112. { 3, new string[] { "overlay_opencl", "Action to take when encountering EOF from secondary input" } },
  113. { 4, new string[] { "overlay_vaapi", "Action to take when encountering EOF from secondary input" } },
  114. { 5, new string[] { "overlay_vulkan", "Action to take when encountering EOF from secondary input" } }
  115. };
  116. // These are the library versions that corresponds to our minimum ffmpeg version 4.x according to the version table below
  117. private static readonly IReadOnlyDictionary<string, Version> _ffmpegMinimumLibraryVersions = new Dictionary<string, Version>
  118. {
  119. { "libavutil", new Version(56, 14) },
  120. { "libavcodec", new Version(58, 18) },
  121. { "libavformat", new Version(58, 12) },
  122. { "libavdevice", new Version(58, 3) },
  123. { "libavfilter", new Version(7, 16) },
  124. { "libswscale", new Version(5, 1) },
  125. { "libswresample", new Version(3, 1) },
  126. { "libpostproc", new Version(55, 1) }
  127. };
  128. private readonly ILogger _logger;
  129. private readonly string _encoderPath;
  130. public EncoderValidator(ILogger logger, string encoderPath)
  131. {
  132. _logger = logger;
  133. _encoderPath = encoderPath;
  134. }
  135. private enum Codec
  136. {
  137. Encoder,
  138. Decoder
  139. }
  140. // When changing this, also change the minimum library versions in _ffmpegMinimumLibraryVersions
  141. public static Version MinVersion { get; } = new Version(4, 0);
  142. public static Version? MaxVersion { get; } = null;
  143. public bool ValidateVersion()
  144. {
  145. string output;
  146. try
  147. {
  148. output = GetProcessOutput(_encoderPath, "-version", false, null);
  149. }
  150. catch (Exception ex)
  151. {
  152. _logger.LogError(ex, "Error validating encoder");
  153. return false;
  154. }
  155. if (string.IsNullOrWhiteSpace(output))
  156. {
  157. _logger.LogError("FFmpeg validation: The process returned no result");
  158. return false;
  159. }
  160. _logger.LogDebug("ffmpeg output: {Output}", output);
  161. return ValidateVersionInternal(output);
  162. }
  163. internal bool ValidateVersionInternal(string versionOutput)
  164. {
  165. if (versionOutput.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
  166. {
  167. _logger.LogError("FFmpeg validation: avconv instead of ffmpeg is not supported");
  168. return false;
  169. }
  170. // Work out what the version under test is
  171. var version = GetFFmpegVersionInternal(versionOutput);
  172. _logger.LogInformation("Found ffmpeg version {Version}", version != null ? version.ToString() : "unknown");
  173. if (version == null)
  174. {
  175. if (MaxVersion != null) // Version is unknown
  176. {
  177. if (MinVersion == MaxVersion)
  178. {
  179. _logger.LogWarning("FFmpeg validation: We recommend version {MinVersion}", MinVersion);
  180. }
  181. else
  182. {
  183. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {MinVersion} and maximum of {MaxVersion}", MinVersion, MaxVersion);
  184. }
  185. }
  186. else
  187. {
  188. _logger.LogWarning("FFmpeg validation: We recommend minimum version {MinVersion}", MinVersion);
  189. }
  190. return false;
  191. }
  192. else if (version < MinVersion) // Version is below what we recommend
  193. {
  194. _logger.LogWarning("FFmpeg validation: The minimum recommended version is {MinVersion}", MinVersion);
  195. return false;
  196. }
  197. else if (MaxVersion != null && version > MaxVersion) // Version is above what we recommend
  198. {
  199. _logger.LogWarning("FFmpeg validation: The maximum recommended version is {MaxVersion}", MaxVersion);
  200. return false;
  201. }
  202. return true;
  203. }
  204. public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
  205. public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
  206. public IEnumerable<string> GetHwaccels() => GetHwaccelTypes();
  207. public IEnumerable<string> GetFilters() => GetFFmpegFilters();
  208. public IDictionary<int, bool> GetFiltersWithOption() => GetFFmpegFiltersWithOption();
  209. public Version? GetFFmpegVersion()
  210. {
  211. string output;
  212. try
  213. {
  214. output = GetProcessOutput(_encoderPath, "-version", false, null);
  215. }
  216. catch (Exception ex)
  217. {
  218. _logger.LogError(ex, "Error validating encoder");
  219. return null;
  220. }
  221. if (string.IsNullOrWhiteSpace(output))
  222. {
  223. _logger.LogError("FFmpeg validation: The process returned no result");
  224. return null;
  225. }
  226. _logger.LogDebug("ffmpeg output: {Output}", output);
  227. return GetFFmpegVersionInternal(output);
  228. }
  229. /// <summary>
  230. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  231. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  232. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  233. /// If that fails then we test the libraries to determine if they're newer than our minimum versions.
  234. /// </summary>
  235. /// <param name="output">The output from "ffmpeg -version".</param>
  236. /// <returns>The FFmpeg version.</returns>
  237. internal Version? GetFFmpegVersionInternal(string output)
  238. {
  239. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  240. var match = Regex.Match(output, @"^ffmpeg version n?((?:[0-9]+\.?)+)");
  241. if (match.Success)
  242. {
  243. if (Version.TryParse(match.Groups[1].Value, out var result))
  244. {
  245. return result;
  246. }
  247. }
  248. var versionMap = GetFFmpegLibraryVersions(output);
  249. var allVersionsValidated = true;
  250. foreach (var minimumVersion in _ffmpegMinimumLibraryVersions)
  251. {
  252. if (versionMap.TryGetValue(minimumVersion.Key, out var foundVersion))
  253. {
  254. if (foundVersion >= minimumVersion.Value)
  255. {
  256. _logger.LogInformation("Found {Library} version {FoundVersion} ({MinimumVersion})", minimumVersion.Key, foundVersion, minimumVersion.Value);
  257. }
  258. else
  259. {
  260. _logger.LogWarning("Found {Library} version {FoundVersion} lower than recommended version {MinimumVersion}", minimumVersion.Key, foundVersion, minimumVersion.Value);
  261. allVersionsValidated = false;
  262. }
  263. }
  264. else
  265. {
  266. _logger.LogError("{Library} version not found", minimumVersion.Key);
  267. allVersionsValidated = false;
  268. }
  269. }
  270. return allVersionsValidated ? MinVersion : null;
  271. }
  272. /// <summary>
  273. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  274. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc.".
  275. /// </summary>
  276. /// <param name="output">The 'ffmpeg -version' output.</param>
  277. /// <returns>The library names and major.minor version numbers.</returns>
  278. private static IReadOnlyDictionary<string, Version> GetFFmpegLibraryVersions(string output)
  279. {
  280. var map = new Dictionary<string, Version>();
  281. foreach (Match match in Regex.Matches(
  282. output,
  283. @"((?<name>lib\w+)\s+(?<major>[0-9]+)\.\s*(?<minor>[0-9]+))",
  284. RegexOptions.Multiline))
  285. {
  286. var version = new Version(
  287. int.Parse(match.Groups["major"].Value, CultureInfo.InvariantCulture),
  288. int.Parse(match.Groups["minor"].Value, CultureInfo.InvariantCulture));
  289. map.Add(match.Groups["name"].Value, version);
  290. }
  291. return map;
  292. }
  293. public bool CheckVaapiDeviceByDriverName(string driverName, string renderNodePath)
  294. {
  295. if (!OperatingSystem.IsLinux())
  296. {
  297. return false;
  298. }
  299. if (string.IsNullOrEmpty(driverName) || string.IsNullOrEmpty(renderNodePath))
  300. {
  301. return false;
  302. }
  303. try
  304. {
  305. var output = GetProcessOutput(_encoderPath, "-v verbose -hide_banner -init_hw_device vaapi=va:" + renderNodePath, true, null);
  306. return output.Contains(driverName, StringComparison.Ordinal);
  307. }
  308. catch (Exception ex)
  309. {
  310. _logger.LogError(ex, "Error detecting the given vaapi render node path");
  311. return false;
  312. }
  313. }
  314. public bool CheckVulkanDrmDeviceByExtensionName(string renderNodePath, string[] vulkanExtensions)
  315. {
  316. if (!OperatingSystem.IsLinux())
  317. {
  318. return false;
  319. }
  320. if (string.IsNullOrEmpty(renderNodePath))
  321. {
  322. return false;
  323. }
  324. try
  325. {
  326. var command = "-v verbose -hide_banner -init_hw_device drm=dr:" + renderNodePath + " -init_hw_device vulkan=vk@dr";
  327. var output = GetProcessOutput(_encoderPath, command, true, null);
  328. foreach (string ext in vulkanExtensions)
  329. {
  330. if (!output.Contains(ext, StringComparison.Ordinal))
  331. {
  332. return false;
  333. }
  334. }
  335. return true;
  336. }
  337. catch (Exception ex)
  338. {
  339. _logger.LogError(ex, "Error detecting the given drm render node path");
  340. return false;
  341. }
  342. }
  343. private IEnumerable<string> GetHwaccelTypes()
  344. {
  345. string? output = null;
  346. try
  347. {
  348. output = GetProcessOutput(_encoderPath, "-hwaccels", false, null);
  349. }
  350. catch (Exception ex)
  351. {
  352. _logger.LogError(ex, "Error detecting available hwaccel types");
  353. }
  354. if (string.IsNullOrWhiteSpace(output))
  355. {
  356. return Enumerable.Empty<string>();
  357. }
  358. var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
  359. _logger.LogInformation("Available hwaccel types: {Types}", found);
  360. return found;
  361. }
  362. public bool CheckFilterWithOption(string filter, string option)
  363. {
  364. if (string.IsNullOrEmpty(filter) || string.IsNullOrEmpty(option))
  365. {
  366. return false;
  367. }
  368. string output;
  369. try
  370. {
  371. output = GetProcessOutput(_encoderPath, "-h filter=" + filter, false, null);
  372. }
  373. catch (Exception ex)
  374. {
  375. _logger.LogError(ex, "Error detecting the given filter");
  376. return false;
  377. }
  378. if (output.Contains("Filter " + filter, StringComparison.Ordinal))
  379. {
  380. return output.Contains(option, StringComparison.Ordinal);
  381. }
  382. _logger.LogWarning("Filter: {Name} with option {Option} is not available", filter, option);
  383. return false;
  384. }
  385. public bool CheckSupportedRuntimeKey(string keyDesc)
  386. {
  387. if (string.IsNullOrEmpty(keyDesc))
  388. {
  389. return false;
  390. }
  391. string output;
  392. try
  393. {
  394. output = GetProcessOutput(_encoderPath, "-hide_banner -f lavfi -i nullsrc=s=1x1:d=500 -f null -", true, "?");
  395. }
  396. catch (Exception ex)
  397. {
  398. _logger.LogError(ex, "Error checking supported runtime key");
  399. return false;
  400. }
  401. return output.Contains(keyDesc, StringComparison.Ordinal);
  402. }
  403. private IEnumerable<string> GetCodecs(Codec codec)
  404. {
  405. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  406. string output;
  407. try
  408. {
  409. output = GetProcessOutput(_encoderPath, "-" + codecstr, false, null);
  410. }
  411. catch (Exception ex)
  412. {
  413. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  414. return Enumerable.Empty<string>();
  415. }
  416. if (string.IsNullOrWhiteSpace(output))
  417. {
  418. return Enumerable.Empty<string>();
  419. }
  420. var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
  421. var found = Regex
  422. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  423. .Cast<Match>()
  424. .Select(x => x.Groups["codec"].Value)
  425. .Where(x => required.Contains(x));
  426. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  427. return found;
  428. }
  429. private IEnumerable<string> GetFFmpegFilters()
  430. {
  431. string output;
  432. try
  433. {
  434. output = GetProcessOutput(_encoderPath, "-filters", false, null);
  435. }
  436. catch (Exception ex)
  437. {
  438. _logger.LogError(ex, "Error detecting available filters");
  439. return Enumerable.Empty<string>();
  440. }
  441. if (string.IsNullOrWhiteSpace(output))
  442. {
  443. return Enumerable.Empty<string>();
  444. }
  445. var found = Regex
  446. .Matches(output, @"^\s\S{3}\s(?<filter>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  447. .Cast<Match>()
  448. .Select(x => x.Groups["filter"].Value)
  449. .Where(x => _requiredFilters.Contains(x));
  450. _logger.LogInformation("Available filters: {Filters}", found);
  451. return found;
  452. }
  453. private IDictionary<int, bool> GetFFmpegFiltersWithOption()
  454. {
  455. IDictionary<int, bool> dict = new Dictionary<int, bool>();
  456. for (int i = 0; i < _filterOptionsDict.Count; i++)
  457. {
  458. if (_filterOptionsDict.TryGetValue(i, out var val) && val.Length == 2)
  459. {
  460. dict.Add(i, CheckFilterWithOption(val[0], val[1]));
  461. }
  462. }
  463. return dict;
  464. }
  465. private string GetProcessOutput(string path, string arguments, bool readStdErr, string? testKey)
  466. {
  467. using (var process = new Process()
  468. {
  469. StartInfo = new ProcessStartInfo(path, arguments)
  470. {
  471. CreateNoWindow = true,
  472. UseShellExecute = false,
  473. WindowStyle = ProcessWindowStyle.Hidden,
  474. ErrorDialog = false,
  475. RedirectStandardInput = !string.IsNullOrEmpty(testKey),
  476. RedirectStandardOutput = true,
  477. RedirectStandardError = true
  478. }
  479. })
  480. {
  481. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  482. process.Start();
  483. if (!string.IsNullOrEmpty(testKey))
  484. {
  485. process.StandardInput.Write(testKey);
  486. }
  487. return readStdErr ? process.StandardError.ReadToEnd() : process.StandardOutput.ReadToEnd();
  488. }
  489. }
  490. }
  491. }