EncoderValidator.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using MediaBrowser.Model.Diagnostics;
  7. using Microsoft.Extensions.Logging;
  8. namespace MediaBrowser.MediaEncoding.Encoder
  9. {
  10. public class FFmpegVersion
  11. {
  12. private int _version;
  13. private int _multi => 100;
  14. private const int _unknown = 0;
  15. private const int _experimental = -1;
  16. public FFmpegVersion(int p1)
  17. {
  18. _version = p1;
  19. }
  20. public FFmpegVersion(string p1)
  21. {
  22. var match = Regex.Match(p1, @"(?<major>\d+)\.(?<minor>\d+)");
  23. if (match.Groups["major"].Success && match.Groups["minor"].Success)
  24. {
  25. int major = int.Parse(match.Groups["major"].Value);
  26. int minor = int.Parse(match.Groups["minor"].Value);
  27. _version = (major * _multi) + minor;
  28. }
  29. }
  30. public override string ToString()
  31. {
  32. switch (_version)
  33. {
  34. case _unknown:
  35. return "Unknown";
  36. case _experimental:
  37. return "Experimental";
  38. default:
  39. string major = Convert.ToString(_version / _multi);
  40. string minor = Convert.ToString(_version % _multi);
  41. return string.Concat(major, ".", minor);
  42. }
  43. }
  44. public bool Unknown()
  45. {
  46. return _version == _unknown;
  47. }
  48. public int Version()
  49. {
  50. return _version;
  51. }
  52. public bool Experimental()
  53. {
  54. return _version == _experimental;
  55. }
  56. public bool Below(FFmpegVersion checkAgainst)
  57. {
  58. return (_version > 0) && (_version < checkAgainst._version);
  59. }
  60. public bool Suitable(FFmpegVersion checkAgainst)
  61. {
  62. return (_version > 0) && (_version >= checkAgainst._version);
  63. }
  64. }
  65. public class EncoderValidator
  66. {
  67. private readonly ILogger _logger;
  68. private readonly IProcessFactory _processFactory;
  69. public EncoderValidator(ILogger logger, IProcessFactory processFactory)
  70. {
  71. _logger = logger;
  72. _processFactory = processFactory;
  73. }
  74. public (IEnumerable<string> decoders, IEnumerable<string> encoders) Validate(string encoderPath)
  75. {
  76. _logger.LogInformation("Validating media encoder at {EncoderPath}", encoderPath);
  77. var decoders = GetCodecs(encoderPath, Codec.Decoder);
  78. var encoders = GetCodecs(encoderPath, Codec.Encoder);
  79. _logger.LogInformation("Encoder validation complete");
  80. return (decoders, encoders);
  81. }
  82. public bool ValidateVersion(string encoderAppPath, bool logOutput)
  83. {
  84. string output = null;
  85. try
  86. {
  87. output = GetProcessOutput(encoderAppPath, "-version");
  88. }
  89. catch (Exception ex)
  90. {
  91. if (logOutput)
  92. {
  93. _logger.LogError(ex, "Error validating encoder");
  94. }
  95. }
  96. if (string.IsNullOrWhiteSpace(output))
  97. {
  98. return false;
  99. }
  100. _logger.LogDebug("ffmpeg output: {Output}", output);
  101. if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
  102. {
  103. return false;
  104. }
  105. // The minimum FFmpeg version required to run jellyfin successfully
  106. FFmpegVersion required = new FFmpegVersion("4.0");
  107. // Work out what the version under test is
  108. FFmpegVersion underTest = GetFFmpegVersion(output);
  109. if (logOutput)
  110. {
  111. if (underTest.Unknown())
  112. {
  113. _logger.LogWarning("FFmpeg validation: Unknown version");
  114. }
  115. else if (underTest.Below(required))
  116. {
  117. _logger.LogWarning("FFmpeg validation: Found version {0} which is below the minimum recommended of {1}",
  118. underTest.ToString(), required.ToString());
  119. }
  120. else if (underTest.Experimental())
  121. {
  122. _logger.LogWarning("FFmpeg validation: Unknown version: {0}?", underTest.ToString());
  123. }
  124. else
  125. {
  126. _logger.LogInformation("FFmpeg validation: Detected version {0}", underTest.ToString());
  127. }
  128. }
  129. return underTest.Suitable(required);
  130. }
  131. /// <summary>
  132. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  133. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  134. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  135. /// If that fails then we use one of the main libraries to determine if it's new/older than the latest
  136. /// we have stored.
  137. /// </summary>
  138. /// <param name="output"></param>
  139. /// <returns></returns>
  140. static private FFmpegVersion GetFFmpegVersion(string output)
  141. {
  142. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  143. var match = Regex.Match(output, @"ffmpeg version (\d+\.\d+)");
  144. if (match.Success)
  145. {
  146. return new FFmpegVersion(match.Groups[1].Value);
  147. }
  148. else
  149. {
  150. // Try and use the individual library versions to determine a FFmpeg version
  151. // This lookup table is to be maintained with the following command line:
  152. // $ ./ffmpeg.exe -version | perl -ne ' print "$1=$2.$3," if /^(lib\w+)\s+(\d+)\.\s*(\d+)/'
  153. ReadOnlyDictionary<FFmpegVersion, string> lut = new ReadOnlyDictionary<FFmpegVersion, string>
  154. (new Dictionary<FFmpegVersion, string>
  155. {
  156. { new FFmpegVersion("4.1"), "libavutil=56.22,libavcodec=58.35,libavformat=58.20,libavdevice=58.5,libavfilter=7.40,libswscale=5.3,libswresample=3.3,libpostproc=55.3," },
  157. { new FFmpegVersion("4.0"), "libavutil=56.14,libavcodec=58.18,libavformat=58.12,libavdevice=58.3,libavfilter=7.16,libswscale=5.1,libswresample=3.1,libpostproc=55.1," },
  158. { new FFmpegVersion("3.4"), "libavutil=55.78,libavcodec=57.107,libavformat=57.83,libavdevice=57.10,libavfilter=6.107,libswscale=4.8,libswresample=2.9,libpostproc=54.7," },
  159. { new FFmpegVersion("3.3"), "libavutil=55.58,libavcodec=57.89,libavformat=57.71,libavdevice=57.6,libavfilter=6.82,libswscale=4.6,libswresample=2.7,libpostproc=54.5," },
  160. { new FFmpegVersion("3.2"), "libavutil=55.34,libavcodec=57.64,libavformat=57.56,libavdevice=57.1,libavfilter=6.65,libswscale=4.2,libswresample=2.3,libpostproc=54.1," },
  161. { new FFmpegVersion("2.8"), "libavutil=54.31,libavcodec=56.60,libavformat=56.40,libavdevice=56.4,libavfilter=5.40,libswscale=3.1,libswresample=1.2,libpostproc=53.3," }
  162. });
  163. // Create a reduced version string and lookup key from dictionary
  164. var reducedVersion = GetVersionString(output);
  165. var found = lut.FirstOrDefault(x => x.Value == reducedVersion).Key;
  166. if (found != null)
  167. {
  168. return found;
  169. }
  170. else
  171. {
  172. // Unknown version. Test the main libavcoder version in the candidate with the
  173. // latest from the dictionary. If candidate is greater than dictionary chances are
  174. // the user if running HEAD/master ffmpeg build (which is probably ok)
  175. var firstElement = lut.FirstOrDefault();
  176. var reqVer = Regex.Match(firstElement.Value, @"libavcodec=(\d+\.\d+)");
  177. var gotVer = Regex.Match(reducedVersion, @"libavcodec=(\d+\.\d+)");
  178. if (reqVer.Success && gotVer.Success)
  179. {
  180. var req = new FFmpegVersion(reqVer.Groups[1].Value);
  181. var got = new FFmpegVersion(gotVer.Groups[1].Value);
  182. // The library versions are not comparable with the FFmpeg version so must check
  183. // candidate (got) against value from dictionary (req). Return Experimental if suitable
  184. if( got.Suitable(req) )
  185. {
  186. return new FFmpegVersion(-1);
  187. }
  188. }
  189. }
  190. }
  191. // Default to return Unknown
  192. return new FFmpegVersion(0);
  193. }
  194. /// <summary>
  195. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  196. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc."
  197. /// </summary>
  198. /// <param name="output"></param>
  199. /// <returns></returns>
  200. static private string GetVersionString(string output)
  201. {
  202. string pattern = @"((?<name>lib\w+)\s+(?<major>\d+)\.\s*(?<minor>\d+))";
  203. RegexOptions options = RegexOptions.Multiline;
  204. string rc = null;
  205. foreach (Match m in Regex.Matches(output, pattern, options))
  206. {
  207. rc += string.Concat(m.Groups["name"], '=', m.Groups["major"], '.', m.Groups["minor"], ',');
  208. }
  209. return rc;
  210. }
  211. private static readonly string[] requiredDecoders = new[]
  212. {
  213. "mpeg2video",
  214. "h264_qsv",
  215. "hevc_qsv",
  216. "mpeg2_qsv",
  217. "vc1_qsv",
  218. "h264_cuvid",
  219. "hevc_cuvid",
  220. "dts",
  221. "ac3",
  222. "aac",
  223. "mp3",
  224. "h264",
  225. "hevc"
  226. };
  227. private static readonly string[] requiredEncoders = new[]
  228. {
  229. "libx264",
  230. "libx265",
  231. "mpeg4",
  232. "msmpeg4",
  233. "libvpx",
  234. "libvpx-vp9",
  235. "aac",
  236. "libmp3lame",
  237. "libopus",
  238. "libvorbis",
  239. "srt",
  240. "h264_nvenc",
  241. "hevc_nvenc",
  242. "h264_qsv",
  243. "hevc_qsv",
  244. "h264_omx",
  245. "hevc_omx",
  246. "h264_vaapi",
  247. "hevc_vaapi",
  248. "ac3"
  249. };
  250. private enum Codec
  251. {
  252. Encoder,
  253. Decoder
  254. }
  255. private IEnumerable<string> GetCodecs(string encoderAppPath, Codec codec)
  256. {
  257. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  258. string output = null;
  259. try
  260. {
  261. output = GetProcessOutput(encoderAppPath, "-" + codecstr);
  262. }
  263. catch (Exception ex)
  264. {
  265. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  266. }
  267. if (string.IsNullOrWhiteSpace(output))
  268. {
  269. return Enumerable.Empty<string>();
  270. }
  271. var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders;
  272. var found = Regex
  273. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  274. .Cast<Match>()
  275. .Select(x => x.Groups["codec"].Value)
  276. .Where(x => required.Contains(x));
  277. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  278. return found;
  279. }
  280. private string GetProcessOutput(string path, string arguments)
  281. {
  282. IProcess process = _processFactory.Create(new ProcessOptions
  283. {
  284. CreateNoWindow = true,
  285. UseShellExecute = false,
  286. FileName = path,
  287. Arguments = arguments,
  288. IsHidden = true,
  289. ErrorDialog = false,
  290. RedirectStandardOutput = true,
  291. // ffmpeg uses stderr to log info, don't show this
  292. RedirectStandardError = true
  293. });
  294. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  295. using (process)
  296. {
  297. process.Start();
  298. try
  299. {
  300. return process.StandardOutput.ReadToEnd();
  301. }
  302. catch
  303. {
  304. _logger.LogWarning("Killing process {Path} {Arguments}", path, arguments);
  305. // Hate having to do this
  306. try
  307. {
  308. process.Kill();
  309. }
  310. catch (Exception ex)
  311. {
  312. _logger.LogError(ex, "Error killing process");
  313. }
  314. throw;
  315. }
  316. }
  317. }
  318. }
  319. }