EncoderValidator.cs 19 KB

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