EncoderValidator.cs 13 KB

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