EncoderValidator.cs 22 KB

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