2
0

EncoderValidator.cs 22 KB

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