2
0

EncoderValidator.cs 20 KB

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