EncoderValidator.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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.RegularExpressions;
  7. using Microsoft.Extensions.Logging;
  8. namespace MediaBrowser.MediaEncoding.Encoder
  9. {
  10. public class EncoderValidator
  11. {
  12. private const string DefaultEncoderPath = "ffmpeg";
  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. "h264_qsv",
  25. "hevc_qsv",
  26. "mpeg2_qsv",
  27. "vc1_qsv",
  28. "vp8_qsv",
  29. "vp9_qsv",
  30. "h264_cuvid",
  31. "hevc_cuvid",
  32. "mpeg2_cuvid",
  33. "vc1_cuvid",
  34. "mpeg4_cuvid",
  35. "vp8_cuvid",
  36. "vp9_cuvid",
  37. "h264_mmal",
  38. "mpeg2_mmal",
  39. "mpeg4_mmal",
  40. "vc1_mmal",
  41. "h264_mediacodec",
  42. "hevc_mediacodec",
  43. "mpeg2_mediacodec",
  44. "mpeg4_mediacodec",
  45. "vp8_mediacodec",
  46. "vp9_mediacodec",
  47. "h264_opencl",
  48. "hevc_opencl",
  49. "mpeg2_opencl",
  50. "mpeg4_opencl",
  51. "vp8_opencl",
  52. "vp9_opencl",
  53. "vc1_opencl"
  54. };
  55. private static readonly string[] _requiredEncoders = new[]
  56. {
  57. "libx264",
  58. "libx265",
  59. "mpeg4",
  60. "msmpeg4",
  61. "libvpx",
  62. "libvpx-vp9",
  63. "aac",
  64. "libfdk_aac",
  65. "ac3",
  66. "libmp3lame",
  67. "libopus",
  68. "libvorbis",
  69. "srt",
  70. "h264_amf",
  71. "hevc_amf",
  72. "h264_qsv",
  73. "hevc_qsv",
  74. "h264_nvenc",
  75. "hevc_nvenc",
  76. "h264_vaapi",
  77. "hevc_vaapi",
  78. "h264_omx",
  79. "hevc_omx",
  80. "h264_v4l2m2m",
  81. "h264_videotoolbox",
  82. "hevc_videotoolbox"
  83. };
  84. // These are the library versions that corresponds to our minimum ffmpeg version 4.x according to the version table below
  85. private static readonly IReadOnlyDictionary<string, Version> _ffmpegMinimumLibraryVersions = new Dictionary<string, Version>
  86. {
  87. { "libavutil", new Version(56, 14) },
  88. { "libavcodec", new Version(58, 18) },
  89. { "libavformat", new Version(58, 12) },
  90. { "libavdevice", new Version(58, 3) },
  91. { "libavfilter", new Version(7, 16) },
  92. { "libswscale", new Version(5, 1) },
  93. { "libswresample", new Version(3, 1) },
  94. { "libpostproc", new Version(55, 1) }
  95. };
  96. private readonly ILogger _logger;
  97. private readonly string _encoderPath;
  98. public EncoderValidator(ILogger logger, string encoderPath = DefaultEncoderPath)
  99. {
  100. _logger = logger;
  101. _encoderPath = encoderPath;
  102. }
  103. private enum Codec
  104. {
  105. Encoder,
  106. Decoder
  107. }
  108. // When changing this, also change the minimum library versions in _ffmpegMinimumLibraryVersions
  109. public static Version MinVersion { get; } = new Version(4, 0);
  110. public static Version MaxVersion { get; } = null;
  111. public bool ValidateVersion()
  112. {
  113. string output = null;
  114. try
  115. {
  116. output = GetProcessOutput(_encoderPath, "-version");
  117. }
  118. catch (Exception ex)
  119. {
  120. _logger.LogError(ex, "Error validating encoder");
  121. }
  122. if (string.IsNullOrWhiteSpace(output))
  123. {
  124. _logger.LogError("FFmpeg validation: The process returned no result");
  125. return false;
  126. }
  127. _logger.LogDebug("ffmpeg output: {Output}", output);
  128. return ValidateVersionInternal(output);
  129. }
  130. internal bool ValidateVersionInternal(string versionOutput)
  131. {
  132. if (versionOutput.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
  133. {
  134. _logger.LogError("FFmpeg validation: avconv instead of ffmpeg is not supported");
  135. return false;
  136. }
  137. // Work out what the version under test is
  138. var version = GetFFmpegVersion(versionOutput);
  139. _logger.LogInformation("Found ffmpeg version {Version}", version != null ? version.ToString() : "unknown");
  140. if (version == null)
  141. {
  142. if (MaxVersion != null) // Version is unknown
  143. {
  144. if (MinVersion == MaxVersion)
  145. {
  146. _logger.LogWarning("FFmpeg validation: We recommend version {MinVersion}", MinVersion);
  147. }
  148. else
  149. {
  150. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {MinVersion} and maximum of {MaxVersion}", MinVersion, MaxVersion);
  151. }
  152. }
  153. else
  154. {
  155. _logger.LogWarning("FFmpeg validation: We recommend minimum version {MinVersion}", MinVersion);
  156. }
  157. return false;
  158. }
  159. else if (version < MinVersion) // Version is below what we recommend
  160. {
  161. _logger.LogWarning("FFmpeg validation: The minimum recommended version is {MinVersion}", MinVersion);
  162. return false;
  163. }
  164. else if (MaxVersion != null && version > MaxVersion) // Version is above what we recommend
  165. {
  166. _logger.LogWarning("FFmpeg validation: The maximum recommended version is {MaxVersion}", MaxVersion);
  167. return false;
  168. }
  169. return true;
  170. }
  171. public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
  172. public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
  173. public IEnumerable<string> GetHwaccels() => GetHwaccelTypes();
  174. /// <summary>
  175. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  176. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  177. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  178. /// If that fails then we test the libraries to determine if they're newer than our minimum versions.
  179. /// </summary>
  180. /// <param name="output">The output from "ffmpeg -version".</param>
  181. /// <returns>The FFmpeg version.</returns>
  182. internal Version GetFFmpegVersion(string output)
  183. {
  184. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  185. var match = Regex.Match(output, @"^ffmpeg version n?((?:[0-9]+\.?)+)");
  186. if (match.Success)
  187. {
  188. return new Version(match.Groups[1].Value);
  189. }
  190. var versionMap = GetFFmpegLibraryVersions(output);
  191. var allVersionsValidated = true;
  192. foreach (var minimumVersion in _ffmpegMinimumLibraryVersions)
  193. {
  194. if (versionMap.TryGetValue(minimumVersion.Key, out var foundVersion))
  195. {
  196. if (foundVersion >= minimumVersion.Value)
  197. {
  198. _logger.LogInformation("Found {Library} version {FoundVersion} ({MinimumVersion})", minimumVersion.Key, foundVersion, minimumVersion.Value);
  199. }
  200. else
  201. {
  202. _logger.LogWarning("Found {Library} version {FoundVersion} lower than recommended version {MinimumVersion}", minimumVersion.Key, foundVersion, minimumVersion.Value);
  203. allVersionsValidated = false;
  204. }
  205. }
  206. else
  207. {
  208. _logger.LogError("{Library} version not found", minimumVersion.Key);
  209. allVersionsValidated = false;
  210. }
  211. }
  212. return allVersionsValidated ? MinVersion : null;
  213. }
  214. /// <summary>
  215. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  216. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc.".
  217. /// </summary>
  218. /// <param name="output">The 'ffmpeg -version' output.</param>
  219. /// <returns>The library names and major.minor version numbers.</returns>
  220. private static IReadOnlyDictionary<string, Version> GetFFmpegLibraryVersions(string output)
  221. {
  222. var map = new Dictionary<string, Version>();
  223. foreach (Match match in Regex.Matches(
  224. output,
  225. @"((?<name>lib\w+)\s+(?<major>[0-9]+)\.\s*(?<minor>[0-9]+))",
  226. RegexOptions.Multiline))
  227. {
  228. var version = new Version(
  229. int.Parse(match.Groups["major"].Value),
  230. int.Parse(match.Groups["minor"].Value));
  231. map.Add(match.Groups["name"].Value, version);
  232. }
  233. return map;
  234. }
  235. private IEnumerable<string> GetHwaccelTypes()
  236. {
  237. string output = null;
  238. try
  239. {
  240. output = GetProcessOutput(_encoderPath, "-hwaccels");
  241. }
  242. catch (Exception ex)
  243. {
  244. _logger.LogError(ex, "Error detecting available hwaccel types");
  245. }
  246. if (string.IsNullOrWhiteSpace(output))
  247. {
  248. return Enumerable.Empty<string>();
  249. }
  250. var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
  251. _logger.LogInformation("Available hwaccel types: {Types}", found);
  252. return found;
  253. }
  254. private IEnumerable<string> GetCodecs(Codec codec)
  255. {
  256. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  257. string output = null;
  258. try
  259. {
  260. output = GetProcessOutput(_encoderPath, "-" + codecstr);
  261. }
  262. catch (Exception ex)
  263. {
  264. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  265. }
  266. if (string.IsNullOrWhiteSpace(output))
  267. {
  268. return Enumerable.Empty<string>();
  269. }
  270. var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
  271. var found = Regex
  272. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  273. .Cast<Match>()
  274. .Select(x => x.Groups["codec"].Value)
  275. .Where(x => required.Contains(x));
  276. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  277. return found;
  278. }
  279. private string GetProcessOutput(string path, string arguments)
  280. {
  281. using (var process = new Process()
  282. {
  283. StartInfo = new ProcessStartInfo(path, arguments)
  284. {
  285. CreateNoWindow = true,
  286. UseShellExecute = false,
  287. WindowStyle = ProcessWindowStyle.Hidden,
  288. ErrorDialog = false,
  289. RedirectStandardOutput = true,
  290. // ffmpeg uses stderr to log info, don't show this
  291. RedirectStandardError = true
  292. }
  293. })
  294. {
  295. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  296. process.Start();
  297. return process.StandardOutput.ReadToEnd();
  298. }
  299. }
  300. }
  301. }