EncoderValidator.cs 22 KB

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