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. "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. private readonly Version _minFFmpegMultiThreadedCli = new Version(7, 0);
  163. public EncoderValidator(ILogger logger, string encoderPath)
  164. {
  165. _logger = logger;
  166. _encoderPath = encoderPath;
  167. }
  168. private enum Codec
  169. {
  170. Encoder,
  171. Decoder
  172. }
  173. // When changing this, also change the minimum library versions in _ffmpegMinimumLibraryVersions
  174. public static Version MinVersion { get; } = new Version(4, 4);
  175. public static Version? MaxVersion { get; } = null;
  176. [GeneratedRegex(@"^ffmpeg version n?((?:[0-9]+\.?)+)")]
  177. private static partial Regex FfmpegVersionRegex();
  178. [GeneratedRegex(@"((?<name>lib\w+)\s+(?<major>[0-9]+)\.\s*(?<minor>[0-9]+))", RegexOptions.Multiline)]
  179. private static partial Regex LibraryRegex();
  180. public bool ValidateVersion()
  181. {
  182. string output;
  183. try
  184. {
  185. output = GetProcessOutput(_encoderPath, "-version", false, null);
  186. }
  187. catch (Exception ex)
  188. {
  189. _logger.LogError(ex, "Error validating encoder");
  190. return false;
  191. }
  192. if (string.IsNullOrWhiteSpace(output))
  193. {
  194. _logger.LogError("FFmpeg validation: The process returned no result");
  195. return false;
  196. }
  197. _logger.LogDebug("ffmpeg output: {Output}", output);
  198. return ValidateVersionInternal(output);
  199. }
  200. internal bool ValidateVersionInternal(string versionOutput)
  201. {
  202. if (versionOutput.Contains("Libav developers", StringComparison.OrdinalIgnoreCase))
  203. {
  204. _logger.LogError("FFmpeg validation: avconv instead of ffmpeg is not supported");
  205. return false;
  206. }
  207. // Work out what the version under test is
  208. var version = GetFFmpegVersionInternal(versionOutput);
  209. _logger.LogInformation("Found ffmpeg version {Version}", version is not null ? version.ToString() : "unknown");
  210. if (version is null)
  211. {
  212. if (MaxVersion is not null) // Version is unknown
  213. {
  214. if (MinVersion == MaxVersion)
  215. {
  216. _logger.LogWarning("FFmpeg validation: We recommend version {MinVersion}", MinVersion);
  217. }
  218. else
  219. {
  220. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {MinVersion} and maximum of {MaxVersion}", MinVersion, MaxVersion);
  221. }
  222. }
  223. else
  224. {
  225. _logger.LogWarning("FFmpeg validation: We recommend minimum version {MinVersion}", MinVersion);
  226. }
  227. return false;
  228. }
  229. if (version < MinVersion) // Version is below what we recommend
  230. {
  231. _logger.LogWarning("FFmpeg validation: The minimum recommended version is {MinVersion}", MinVersion);
  232. return false;
  233. }
  234. if (MaxVersion is not null && version > MaxVersion) // Version is above what we recommend
  235. {
  236. _logger.LogWarning("FFmpeg validation: The maximum recommended version is {MaxVersion}", MaxVersion);
  237. return false;
  238. }
  239. return true;
  240. }
  241. public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
  242. public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
  243. public IEnumerable<string> GetHwaccels() => GetHwaccelTypes();
  244. public IEnumerable<string> GetFilters() => GetFFmpegFilters();
  245. public IDictionary<int, bool> GetFiltersWithOption() => GetFFmpegFiltersWithOption();
  246. public Version? GetFFmpegVersion()
  247. {
  248. string output;
  249. try
  250. {
  251. output = GetProcessOutput(_encoderPath, "-version", false, null);
  252. }
  253. catch (Exception ex)
  254. {
  255. _logger.LogError(ex, "Error validating encoder");
  256. return null;
  257. }
  258. if (string.IsNullOrWhiteSpace(output))
  259. {
  260. _logger.LogError("FFmpeg validation: The process returned no result");
  261. return null;
  262. }
  263. _logger.LogDebug("ffmpeg output: {Output}", output);
  264. return GetFFmpegVersionInternal(output);
  265. }
  266. /// <summary>
  267. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  268. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  269. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  270. /// If that fails then we test the libraries to determine if they're newer than our minimum versions.
  271. /// </summary>
  272. /// <param name="output">The output from "ffmpeg -version".</param>
  273. /// <returns>The FFmpeg version.</returns>
  274. internal Version? GetFFmpegVersionInternal(string output)
  275. {
  276. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  277. var match = FfmpegVersionRegex().Match(output);
  278. if (match.Success)
  279. {
  280. if (Version.TryParse(match.Groups[1].ValueSpan, out var result))
  281. {
  282. return result;
  283. }
  284. }
  285. var versionMap = GetFFmpegLibraryVersions(output);
  286. var allVersionsValidated = true;
  287. foreach (var minimumVersion in _ffmpegMinimumLibraryVersions)
  288. {
  289. if (versionMap.TryGetValue(minimumVersion.Key, out var foundVersion))
  290. {
  291. if (foundVersion >= minimumVersion.Value)
  292. {
  293. _logger.LogInformation("Found {Library} version {FoundVersion} ({MinimumVersion})", minimumVersion.Key, foundVersion, minimumVersion.Value);
  294. }
  295. else
  296. {
  297. _logger.LogWarning("Found {Library} version {FoundVersion} lower than recommended version {MinimumVersion}", minimumVersion.Key, foundVersion, minimumVersion.Value);
  298. allVersionsValidated = false;
  299. }
  300. }
  301. else
  302. {
  303. _logger.LogError("{Library} version not found", minimumVersion.Key);
  304. allVersionsValidated = false;
  305. }
  306. }
  307. return allVersionsValidated ? MinVersion : null;
  308. }
  309. /// <summary>
  310. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  311. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc.".
  312. /// </summary>
  313. /// <param name="output">The 'ffmpeg -version' output.</param>
  314. /// <returns>The library names and major.minor version numbers.</returns>
  315. private static Dictionary<string, Version> GetFFmpegLibraryVersions(string output)
  316. {
  317. var map = new Dictionary<string, Version>();
  318. foreach (Match match in LibraryRegex().Matches(output))
  319. {
  320. var version = new Version(
  321. int.Parse(match.Groups["major"].ValueSpan, CultureInfo.InvariantCulture),
  322. int.Parse(match.Groups["minor"].ValueSpan, CultureInfo.InvariantCulture));
  323. map.Add(match.Groups["name"].Value, version);
  324. }
  325. return map;
  326. }
  327. public bool CheckVaapiDeviceByDriverName(string driverName, string renderNodePath)
  328. {
  329. if (!OperatingSystem.IsLinux())
  330. {
  331. return false;
  332. }
  333. if (string.IsNullOrEmpty(driverName) || string.IsNullOrEmpty(renderNodePath))
  334. {
  335. return false;
  336. }
  337. try
  338. {
  339. var output = GetProcessOutput(_encoderPath, "-v verbose -hide_banner -init_hw_device vaapi=va:" + renderNodePath, true, null);
  340. return output.Contains(driverName, StringComparison.Ordinal);
  341. }
  342. catch (Exception ex)
  343. {
  344. _logger.LogError(ex, "Error detecting the given vaapi render node path");
  345. return false;
  346. }
  347. }
  348. public bool CheckVulkanDrmDeviceByExtensionName(string renderNodePath, string[] vulkanExtensions)
  349. {
  350. if (!OperatingSystem.IsLinux())
  351. {
  352. return false;
  353. }
  354. if (string.IsNullOrEmpty(renderNodePath))
  355. {
  356. return false;
  357. }
  358. try
  359. {
  360. var command = "-v verbose -hide_banner -init_hw_device drm=dr:" + renderNodePath + " -init_hw_device vulkan=vk@dr";
  361. var output = GetProcessOutput(_encoderPath, command, true, null);
  362. foreach (string ext in vulkanExtensions)
  363. {
  364. if (!output.Contains(ext, StringComparison.Ordinal))
  365. {
  366. return false;
  367. }
  368. }
  369. return true;
  370. }
  371. catch (Exception ex)
  372. {
  373. _logger.LogError(ex, "Error detecting the given drm render node path");
  374. return false;
  375. }
  376. }
  377. private IEnumerable<string> GetHwaccelTypes()
  378. {
  379. string? output = null;
  380. try
  381. {
  382. output = GetProcessOutput(_encoderPath, "-hwaccels", false, null);
  383. }
  384. catch (Exception ex)
  385. {
  386. _logger.LogError(ex, "Error detecting available hwaccel types");
  387. }
  388. if (string.IsNullOrWhiteSpace(output))
  389. {
  390. return Enumerable.Empty<string>();
  391. }
  392. var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
  393. _logger.LogInformation("Available hwaccel types: {Types}", found);
  394. return found;
  395. }
  396. public bool CheckFilterWithOption(string filter, string option)
  397. {
  398. if (string.IsNullOrEmpty(filter) || string.IsNullOrEmpty(option))
  399. {
  400. return false;
  401. }
  402. string output;
  403. try
  404. {
  405. output = GetProcessOutput(_encoderPath, "-h filter=" + filter, false, null);
  406. }
  407. catch (Exception ex)
  408. {
  409. _logger.LogError(ex, "Error detecting the given filter");
  410. return false;
  411. }
  412. if (output.Contains("Filter " + filter, StringComparison.Ordinal))
  413. {
  414. return output.Contains(option, StringComparison.Ordinal);
  415. }
  416. _logger.LogWarning("Filter: {Name} with option {Option} is not available", filter, option);
  417. return false;
  418. }
  419. public bool CheckSupportedRuntimeKey(string keyDesc, Version? ffmpegVersion)
  420. {
  421. if (string.IsNullOrEmpty(keyDesc))
  422. {
  423. return false;
  424. }
  425. string output;
  426. try
  427. {
  428. // With multi-threaded cli support, FFmpeg 7 is less sensitive to keyboard input
  429. var duration = ffmpegVersion >= _minFFmpegMultiThreadedCli ? 10000 : 1000;
  430. output = GetProcessOutput(_encoderPath, $"-hide_banner -f lavfi -i nullsrc=s=1x1:d={duration} -f null -", true, "?");
  431. }
  432. catch (Exception ex)
  433. {
  434. _logger.LogError(ex, "Error checking supported runtime key");
  435. return false;
  436. }
  437. return output.Contains(keyDesc, StringComparison.Ordinal);
  438. }
  439. private IEnumerable<string> GetCodecs(Codec codec)
  440. {
  441. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  442. string output;
  443. try
  444. {
  445. output = GetProcessOutput(_encoderPath, "-" + codecstr, false, null);
  446. }
  447. catch (Exception ex)
  448. {
  449. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  450. return Enumerable.Empty<string>();
  451. }
  452. if (string.IsNullOrWhiteSpace(output))
  453. {
  454. return Enumerable.Empty<string>();
  455. }
  456. var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
  457. var found = CodecRegex()
  458. .Matches(output)
  459. .Select(x => x.Groups["codec"].Value)
  460. .Where(x => required.Contains(x));
  461. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  462. return found;
  463. }
  464. private IEnumerable<string> GetFFmpegFilters()
  465. {
  466. string output;
  467. try
  468. {
  469. output = GetProcessOutput(_encoderPath, "-filters", false, null);
  470. }
  471. catch (Exception ex)
  472. {
  473. _logger.LogError(ex, "Error detecting available filters");
  474. return Enumerable.Empty<string>();
  475. }
  476. if (string.IsNullOrWhiteSpace(output))
  477. {
  478. return Enumerable.Empty<string>();
  479. }
  480. var found = FilterRegex()
  481. .Matches(output)
  482. .Select(x => x.Groups["filter"].Value)
  483. .Where(x => _requiredFilters.Contains(x));
  484. _logger.LogInformation("Available filters: {Filters}", found);
  485. return found;
  486. }
  487. private Dictionary<int, bool> GetFFmpegFiltersWithOption()
  488. {
  489. Dictionary<int, bool> dict = new Dictionary<int, bool>();
  490. for (int i = 0; i < _filterOptionsDict.Count; i++)
  491. {
  492. if (_filterOptionsDict.TryGetValue(i, out var val) && val.Length == 2)
  493. {
  494. dict.Add(i, CheckFilterWithOption(val[0], val[1]));
  495. }
  496. }
  497. return dict;
  498. }
  499. private string GetProcessOutput(string path, string arguments, bool readStdErr, string? testKey)
  500. {
  501. var redirectStandardIn = !string.IsNullOrEmpty(testKey);
  502. using (var process = new Process
  503. {
  504. StartInfo = new ProcessStartInfo(path, arguments)
  505. {
  506. CreateNoWindow = true,
  507. UseShellExecute = false,
  508. WindowStyle = ProcessWindowStyle.Hidden,
  509. ErrorDialog = false,
  510. RedirectStandardInput = redirectStandardIn,
  511. RedirectStandardOutput = true,
  512. RedirectStandardError = true
  513. }
  514. })
  515. {
  516. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  517. process.Start();
  518. if (redirectStandardIn)
  519. {
  520. using var writer = process.StandardInput;
  521. writer.Write(testKey);
  522. }
  523. using var reader = readStdErr ? process.StandardError : process.StandardOutput;
  524. return reader.ReadToEnd();
  525. }
  526. }
  527. [GeneratedRegex("^\\s\\S{6}\\s(?<codec>[\\w|-]+)\\s+.+$", RegexOptions.Multiline)]
  528. private static partial Regex CodecRegex();
  529. [GeneratedRegex("^\\s\\S{3}\\s(?<filter>[\\w|-]+)\\s+.+$", RegexOptions.Multiline)]
  530. private static partial Regex FilterRegex();
  531. }
  532. }