2
0

EncoderValidator.cs 17 KB

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