EncoderValidator.cs 16 KB

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