EncoderValidator.cs 17 KB

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