EncoderValidator.cs 16 KB

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