2
0

EncoderValidator.cs 18 KB

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