EncoderValidator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Text;
  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. "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. "srt",
  71. "h264_amf",
  72. "hevc_amf",
  73. "h264_qsv",
  74. "hevc_qsv",
  75. "h264_nvenc",
  76. "hevc_nvenc",
  77. "h264_vaapi",
  78. "hevc_vaapi",
  79. "h264_omx",
  80. "hevc_omx",
  81. "h264_v4l2m2m",
  82. "h264_videotoolbox",
  83. "hevc_videotoolbox"
  84. };
  85. // These are the library versions that corresponds to our minimum ffmpeg version 4.x according to the version table below
  86. private static readonly IReadOnlyDictionary<string, Version> _ffmpegMinimumLibraryVersions = new Dictionary<string, Version>
  87. {
  88. { "libavutil", new Version(56, 14) },
  89. { "libavcodec", new Version(58, 18) },
  90. { "libavformat", new Version(58, 12) },
  91. { "libavdevice", new Version(58, 3) },
  92. { "libavfilter", new Version(7, 16) },
  93. { "libswscale", new Version(5, 1) },
  94. { "libswresample", new Version(3, 1) },
  95. { "libpostproc", new Version(55, 1) }
  96. };
  97. // This lookup table is to be maintained with the following command line:
  98. // $ ffmpeg -version | perl -ne ' print "$1=$2.$3," if /^(lib\w+)\s+(\d+)\.\s*(\d+)/'
  99. private static readonly IReadOnlyDictionary<string, Version> _ffmpegVersionMap = new Dictionary<string, Version>
  100. {
  101. { "libavutil=56.51,libavcodec=58.91,libavformat=58.45,libavdevice=58.10,libavfilter=7.85,libswscale=5.7,libswresample=3.7,libpostproc=55.7,", new Version(4, 3) },
  102. { "libavutil=56.31,libavcodec=58.54,libavformat=58.29,libavdevice=58.8,libavfilter=7.57,libswscale=5.5,libswresample=3.5,libpostproc=55.5,", new Version(4, 2) },
  103. { "libavutil=56.22,libavcodec=58.35,libavformat=58.20,libavdevice=58.5,libavfilter=7.40,libswscale=5.3,libswresample=3.3,libpostproc=55.3,", new Version(4, 1) },
  104. { "libavutil=56.14,libavcodec=58.18,libavformat=58.12,libavdevice=58.3,libavfilter=7.16,libswscale=5.1,libswresample=3.1,libpostproc=55.1,", new Version(4, 0) },
  105. { "libavutil=55.78,libavcodec=57.107,libavformat=57.83,libavdevice=57.10,libavfilter=6.107,libswscale=4.8,libswresample=2.9,libpostproc=54.7,", new Version(3, 4) },
  106. { "libavutil=55.58,libavcodec=57.89,libavformat=57.71,libavdevice=57.6,libavfilter=6.82,libswscale=4.6,libswresample=2.7,libpostproc=54.5,", new Version(3, 3) },
  107. { "libavutil=55.34,libavcodec=57.64,libavformat=57.56,libavdevice=57.1,libavfilter=6.65,libswscale=4.2,libswresample=2.3,libpostproc=54.1,", new Version(3, 2) },
  108. { "libavutil=54.31,libavcodec=56.60,libavformat=56.40,libavdevice=56.4,libavfilter=5.40,libswscale=3.1,libswresample=1.2,libpostproc=53.3,", new Version(2, 8) }
  109. };
  110. private readonly ILogger _logger;
  111. private readonly string _encoderPath;
  112. public EncoderValidator(ILogger logger, string encoderPath = DefaultEncoderPath)
  113. {
  114. _logger = logger;
  115. _encoderPath = encoderPath;
  116. }
  117. private enum Codec
  118. {
  119. Encoder,
  120. Decoder
  121. }
  122. public static Version MinVersion { get; } = new Version(4, 0);
  123. public static Version MaxVersion { get; } = null;
  124. public bool ValidateVersion()
  125. {
  126. string output = null;
  127. try
  128. {
  129. output = GetProcessOutput(_encoderPath, "-version");
  130. }
  131. catch (Exception ex)
  132. {
  133. _logger.LogError(ex, "Error validating encoder");
  134. }
  135. if (string.IsNullOrWhiteSpace(output))
  136. {
  137. _logger.LogError("FFmpeg validation: The process returned no result");
  138. return false;
  139. }
  140. _logger.LogDebug("ffmpeg output: {Output}", output);
  141. return ValidateVersionInternal(output);
  142. }
  143. internal bool ValidateVersionInternal(string versionOutput)
  144. {
  145. if (versionOutput.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
  146. {
  147. _logger.LogError("FFmpeg validation: avconv instead of ffmpeg is not supported");
  148. return false;
  149. }
  150. // Work out what the version under test is
  151. var version = GetFFmpegVersion(versionOutput);
  152. _logger.LogInformation("Found ffmpeg version {Version}", version != null ? version.ToString() : "unknown");
  153. if (version == null)
  154. {
  155. if (MaxVersion != null) // Version is unknown
  156. {
  157. if (MinVersion == MaxVersion)
  158. {
  159. _logger.LogWarning("FFmpeg validation: We recommend version {MinVersion}", MinVersion);
  160. }
  161. else
  162. {
  163. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {MinVersion} and maximum of {MaxVersion}", MinVersion, MaxVersion);
  164. }
  165. }
  166. else
  167. {
  168. _logger.LogWarning("FFmpeg validation: We recommend minimum version {MinVersion}", MinVersion);
  169. }
  170. return false;
  171. }
  172. else if (version < MinVersion) // Version is below what we recommend
  173. {
  174. _logger.LogWarning("FFmpeg validation: The minimum recommended version is {MinVersion}", MinVersion);
  175. return false;
  176. }
  177. else if (MaxVersion != null && version > MaxVersion) // Version is above what we recommend
  178. {
  179. _logger.LogWarning("FFmpeg validation: The maximum recommended version is {MaxVersion}", MaxVersion);
  180. return false;
  181. }
  182. return true;
  183. }
  184. public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
  185. public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
  186. public IEnumerable<string> GetHwaccels() => GetHwaccelTypes();
  187. /// <summary>
  188. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  189. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  190. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  191. /// If that fails then we test the libraries to determine if they're newer than our minimum versions.
  192. /// </summary>
  193. /// <param name="output">The output from "ffmpeg -version".</param>
  194. /// <returns>The FFmpeg version.</returns>
  195. internal Version GetFFmpegVersion(string output)
  196. {
  197. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  198. var match = Regex.Match(output, @"^ffmpeg version n?((?:[0-9]+\.?)+)");
  199. if (match.Success)
  200. {
  201. return new Version(match.Groups[1].Value);
  202. }
  203. else
  204. {
  205. if (!TryGetFFmpegLibraryVersions(output, out string versionString, out IReadOnlyDictionary<string, Version> versionMap))
  206. {
  207. _logger.LogError("No ffmpeg library versions found");
  208. return null;
  209. }
  210. // First try to lookup the full version string
  211. if (_ffmpegVersionMap.TryGetValue(versionString, out Version version))
  212. {
  213. return version;
  214. }
  215. // Then try to test for minimum library versions
  216. return TestMinimumFFmpegLibraryVersions(versionMap);
  217. }
  218. }
  219. private Version TestMinimumFFmpegLibraryVersions(IReadOnlyDictionary<string, Version> versionMap)
  220. {
  221. var allVersionsValidated = true;
  222. foreach (var minimumVersion in _ffmpegMinimumLibraryVersions)
  223. {
  224. if (versionMap.TryGetValue(minimumVersion.Key, out var foundVersion))
  225. {
  226. if (foundVersion >= minimumVersion.Value)
  227. {
  228. _logger.LogInformation("Found {Library} version {FoundVersion} ({MinimumVersion})", minimumVersion.Key, foundVersion, minimumVersion.Value);
  229. }
  230. else
  231. {
  232. _logger.LogWarning("Found {Library} version {FoundVersion} lower than recommended version {MinimumVersion}", minimumVersion.Key, foundVersion, minimumVersion.Value);
  233. allVersionsValidated = false;
  234. }
  235. }
  236. else
  237. {
  238. _logger.LogError("{Library} version not found", minimumVersion.Key);
  239. allVersionsValidated = false;
  240. }
  241. }
  242. return allVersionsValidated ? MinVersion : null;
  243. }
  244. /// <summary>
  245. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  246. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc.".
  247. /// </summary>
  248. /// <param name="output">The 'ffmpeg -version' output.</param>
  249. /// <returns>The library names and major.minor version numbers.</returns>
  250. private static bool TryGetFFmpegLibraryVersions(string output, out string versionString, out IReadOnlyDictionary<string, Version> versionMap)
  251. {
  252. var sb = new StringBuilder(144);
  253. var map = new Dictionary<string, Version>();
  254. foreach (Match match in Regex.Matches(
  255. output,
  256. @"((?<name>lib\w+)\s+(?<major>[0-9]+)\.\s*(?<minor>[0-9]+))",
  257. RegexOptions.Multiline))
  258. {
  259. sb.Append(match.Groups["name"])
  260. .Append('=')
  261. .Append(match.Groups["major"])
  262. .Append('.')
  263. .Append(match.Groups["minor"])
  264. .Append(',');
  265. var str = $"{match.Groups["major"]}.{match.Groups["minor"]}";
  266. var version = Version.Parse(str);
  267. map.Add(match.Groups["name"].Value, version);
  268. }
  269. versionString = sb.ToString();
  270. versionMap = map;
  271. return sb.Length > 0;
  272. }
  273. private IEnumerable<string> GetHwaccelTypes()
  274. {
  275. string output = null;
  276. try
  277. {
  278. output = GetProcessOutput(_encoderPath, "-hwaccels");
  279. }
  280. catch (Exception ex)
  281. {
  282. _logger.LogError(ex, "Error detecting available hwaccel types");
  283. }
  284. if (string.IsNullOrWhiteSpace(output))
  285. {
  286. return Enumerable.Empty<string>();
  287. }
  288. var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
  289. _logger.LogInformation("Available hwaccel types: {Types}", found);
  290. return found;
  291. }
  292. private IEnumerable<string> GetCodecs(Codec codec)
  293. {
  294. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  295. string output = null;
  296. try
  297. {
  298. output = GetProcessOutput(_encoderPath, "-" + codecstr);
  299. }
  300. catch (Exception ex)
  301. {
  302. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  303. }
  304. if (string.IsNullOrWhiteSpace(output))
  305. {
  306. return Enumerable.Empty<string>();
  307. }
  308. var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
  309. var found = Regex
  310. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  311. .Cast<Match>()
  312. .Select(x => x.Groups["codec"].Value)
  313. .Where(x => required.Contains(x));
  314. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  315. return found;
  316. }
  317. private string GetProcessOutput(string path, string arguments)
  318. {
  319. using (var process = new Process()
  320. {
  321. StartInfo = new ProcessStartInfo(path, arguments)
  322. {
  323. CreateNoWindow = true,
  324. UseShellExecute = false,
  325. WindowStyle = ProcessWindowStyle.Hidden,
  326. ErrorDialog = false,
  327. RedirectStandardOutput = true,
  328. // ffmpeg uses stderr to log info, don't show this
  329. RedirectStandardError = true
  330. }
  331. })
  332. {
  333. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  334. process.Start();
  335. return process.StandardOutput.ReadToEnd();
  336. }
  337. }
  338. }
  339. }