2
0

EncoderValidator.cs 19 KB

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