EncoderValidator.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. // These are the library versions that corresponds to our minimum ffmpeg version 4.x according to the version table below
  88. private static readonly IReadOnlyDictionary<string, Version> _ffmpegMinimumLibraryVersions = new Dictionary<string, Version>
  89. {
  90. { "libavutil", new Version(56, 14) },
  91. { "libavcodec", new Version(58, 18) },
  92. { "libavformat", new Version(58, 12) },
  93. { "libavdevice", new Version(58, 3) },
  94. { "libavfilter", new Version(7, 16) },
  95. { "libswscale", new Version(5, 1) },
  96. { "libswresample", new Version(3, 1) },
  97. { "libpostproc", new Version(55, 1) }
  98. };
  99. private readonly ILogger _logger;
  100. private readonly string _encoderPath;
  101. public EncoderValidator(ILogger logger, string encoderPath = DefaultEncoderPath)
  102. {
  103. _logger = logger;
  104. _encoderPath = encoderPath;
  105. }
  106. private enum Codec
  107. {
  108. Encoder,
  109. Decoder
  110. }
  111. // When changing this, also change the minimum library versions in _ffmpegMinimumLibraryVersions
  112. public static Version MinVersion { get; } = new Version(4, 0);
  113. public static Version MaxVersion { get; } = null;
  114. public bool ValidateVersion()
  115. {
  116. string output = null;
  117. try
  118. {
  119. output = GetProcessOutput(_encoderPath, "-version");
  120. }
  121. catch (Exception ex)
  122. {
  123. _logger.LogError(ex, "Error validating encoder");
  124. }
  125. if (string.IsNullOrWhiteSpace(output))
  126. {
  127. _logger.LogError("FFmpeg validation: The process returned no result");
  128. return false;
  129. }
  130. _logger.LogDebug("ffmpeg output: {Output}", output);
  131. return ValidateVersionInternal(output);
  132. }
  133. internal bool ValidateVersionInternal(string versionOutput)
  134. {
  135. if (versionOutput.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
  136. {
  137. _logger.LogError("FFmpeg validation: avconv instead of ffmpeg is not supported");
  138. return false;
  139. }
  140. // Work out what the version under test is
  141. var version = GetFFmpegVersion(versionOutput);
  142. _logger.LogInformation("Found ffmpeg version {Version}", version != null ? version.ToString() : "unknown");
  143. if (version == null)
  144. {
  145. if (MaxVersion != null) // Version is unknown
  146. {
  147. if (MinVersion == MaxVersion)
  148. {
  149. _logger.LogWarning("FFmpeg validation: We recommend version {MinVersion}", MinVersion);
  150. }
  151. else
  152. {
  153. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {MinVersion} and maximum of {MaxVersion}", MinVersion, MaxVersion);
  154. }
  155. }
  156. else
  157. {
  158. _logger.LogWarning("FFmpeg validation: We recommend minimum version {MinVersion}", MinVersion);
  159. }
  160. return false;
  161. }
  162. else if (version < MinVersion) // Version is below what we recommend
  163. {
  164. _logger.LogWarning("FFmpeg validation: The minimum recommended version is {MinVersion}", MinVersion);
  165. return false;
  166. }
  167. else if (MaxVersion != null && version > MaxVersion) // Version is above what we recommend
  168. {
  169. _logger.LogWarning("FFmpeg validation: The maximum recommended version is {MaxVersion}", MaxVersion);
  170. return false;
  171. }
  172. return true;
  173. }
  174. public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
  175. public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
  176. public IEnumerable<string> GetHwaccels() => GetHwaccelTypes();
  177. /// <summary>
  178. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  179. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  180. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  181. /// If that fails then we test the libraries to determine if they're newer than our minimum versions.
  182. /// </summary>
  183. /// <param name="output">The output from "ffmpeg -version".</param>
  184. /// <returns>The FFmpeg version.</returns>
  185. internal Version GetFFmpegVersion(string output)
  186. {
  187. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  188. var match = Regex.Match(output, @"^ffmpeg version n?((?:[0-9]+\.?)+)");
  189. if (match.Success)
  190. {
  191. if (Version.TryParse(match.Groups[1].Value, out var result))
  192. {
  193. return result;
  194. }
  195. }
  196. var versionMap = GetFFmpegLibraryVersions(output);
  197. var allVersionsValidated = true;
  198. foreach (var minimumVersion in _ffmpegMinimumLibraryVersions)
  199. {
  200. if (versionMap.TryGetValue(minimumVersion.Key, out var foundVersion))
  201. {
  202. if (foundVersion >= minimumVersion.Value)
  203. {
  204. _logger.LogInformation("Found {Library} version {FoundVersion} ({MinimumVersion})", minimumVersion.Key, foundVersion, minimumVersion.Value);
  205. }
  206. else
  207. {
  208. _logger.LogWarning("Found {Library} version {FoundVersion} lower than recommended version {MinimumVersion}", minimumVersion.Key, foundVersion, minimumVersion.Value);
  209. allVersionsValidated = false;
  210. }
  211. }
  212. else
  213. {
  214. _logger.LogError("{Library} version not found", minimumVersion.Key);
  215. allVersionsValidated = false;
  216. }
  217. }
  218. return allVersionsValidated ? MinVersion : null;
  219. }
  220. /// <summary>
  221. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  222. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc.".
  223. /// </summary>
  224. /// <param name="output">The 'ffmpeg -version' output.</param>
  225. /// <returns>The library names and major.minor version numbers.</returns>
  226. private static IReadOnlyDictionary<string, Version> GetFFmpegLibraryVersions(string output)
  227. {
  228. var map = new Dictionary<string, Version>();
  229. foreach (Match match in Regex.Matches(
  230. output,
  231. @"((?<name>lib\w+)\s+(?<major>[0-9]+)\.\s*(?<minor>[0-9]+))",
  232. RegexOptions.Multiline))
  233. {
  234. var version = new Version(
  235. int.Parse(match.Groups["major"].Value, CultureInfo.InvariantCulture),
  236. int.Parse(match.Groups["minor"].Value, CultureInfo.InvariantCulture));
  237. map.Add(match.Groups["name"].Value, version);
  238. }
  239. return map;
  240. }
  241. private IEnumerable<string> GetHwaccelTypes()
  242. {
  243. string output = null;
  244. try
  245. {
  246. output = GetProcessOutput(_encoderPath, "-hwaccels");
  247. }
  248. catch (Exception ex)
  249. {
  250. _logger.LogError(ex, "Error detecting available hwaccel types");
  251. }
  252. if (string.IsNullOrWhiteSpace(output))
  253. {
  254. return Enumerable.Empty<string>();
  255. }
  256. var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
  257. _logger.LogInformation("Available hwaccel types: {Types}", found);
  258. return found;
  259. }
  260. private IEnumerable<string> GetCodecs(Codec codec)
  261. {
  262. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  263. string output = null;
  264. try
  265. {
  266. output = GetProcessOutput(_encoderPath, "-" + codecstr);
  267. }
  268. catch (Exception ex)
  269. {
  270. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  271. }
  272. if (string.IsNullOrWhiteSpace(output))
  273. {
  274. return Enumerable.Empty<string>();
  275. }
  276. var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
  277. var found = Regex
  278. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  279. .Cast<Match>()
  280. .Select(x => x.Groups["codec"].Value)
  281. .Where(x => required.Contains(x));
  282. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  283. return found;
  284. }
  285. private string GetProcessOutput(string path, string arguments)
  286. {
  287. using (var process = new Process()
  288. {
  289. StartInfo = new ProcessStartInfo(path, arguments)
  290. {
  291. CreateNoWindow = true,
  292. UseShellExecute = false,
  293. WindowStyle = ProcessWindowStyle.Hidden,
  294. ErrorDialog = false,
  295. RedirectStandardOutput = true,
  296. // ffmpeg uses stderr to log info, don't show this
  297. RedirectStandardError = true
  298. }
  299. })
  300. {
  301. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  302. process.Start();
  303. return process.StandardOutput.ReadToEnd();
  304. }
  305. }
  306. }
  307. }