EncoderValidator.cs 20 KB

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