EncoderValidator.cs 20 KB

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