EncoderValidator.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 readonly int _major;
  13. private readonly int _minor;
  14. private const int _unknown = 0;
  15. public FFmpegVersion(string p1)
  16. {
  17. var match = Regex.Match(p1, @"(?<major>\d+)\.(?<minor>\d+)");
  18. if (match.Groups["major"].Success && match.Groups["minor"].Success)
  19. {
  20. _major = int.Parse(match.Groups["major"].Value);
  21. _minor = int.Parse(match.Groups["minor"].Value);
  22. }
  23. else
  24. {
  25. _major = _unknown;
  26. _minor = _unknown;
  27. }
  28. }
  29. public override string ToString()
  30. {
  31. switch (_major)
  32. {
  33. case _unknown:
  34. return "Unknown";
  35. default:
  36. return string.Format("{0}.{1}",_major,_minor);
  37. }
  38. }
  39. public bool Unknown()
  40. {
  41. return _major == _unknown;
  42. }
  43. public bool Below(FFmpegVersion checkAgainst)
  44. {
  45. return ToScalar() < checkAgainst.ToScalar();
  46. }
  47. public bool Above(FFmpegVersion checkAgainst)
  48. {
  49. return ToScalar() > checkAgainst.ToScalar();
  50. }
  51. public bool Same(FFmpegVersion checkAgainst)
  52. {
  53. return ToScalar() == checkAgainst.ToScalar();
  54. }
  55. private int ToScalar()
  56. {
  57. return (_major * 1000) + _minor;
  58. }
  59. }
  60. public class EncoderValidator
  61. {
  62. private readonly ILogger _logger;
  63. private readonly IProcessFactory _processFactory;
  64. public EncoderValidator(ILogger logger, IProcessFactory processFactory)
  65. {
  66. _logger = logger;
  67. _processFactory = processFactory;
  68. }
  69. public (IEnumerable<string> decoders, IEnumerable<string> encoders) Validate(string encoderPath)
  70. {
  71. _logger.LogInformation("Validating media encoder at {EncoderPath}", encoderPath);
  72. var decoders = GetCodecs(encoderPath, Codec.Decoder);
  73. var encoders = GetCodecs(encoderPath, Codec.Encoder);
  74. _logger.LogInformation("Encoder validation complete");
  75. return (decoders, encoders);
  76. }
  77. public bool ValidateVersion(string encoderAppPath, bool logOutput)
  78. {
  79. string output = null;
  80. try
  81. {
  82. output = GetProcessOutput(encoderAppPath, "-version");
  83. }
  84. catch (Exception ex)
  85. {
  86. if (logOutput)
  87. {
  88. _logger.LogError(ex, "Error validating encoder");
  89. }
  90. }
  91. if (string.IsNullOrWhiteSpace(output))
  92. {
  93. return false;
  94. }
  95. _logger.LogDebug("ffmpeg output: {Output}", output);
  96. if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
  97. {
  98. return false;
  99. }
  100. // The min and max FFmpeg versions required to run jellyfin successfully
  101. FFmpegVersion minRequired = new FFmpegVersion("4.0");
  102. FFmpegVersion maxRequired = new FFmpegVersion("4.0");
  103. // Work out what the version under test is
  104. FFmpegVersion underTest = GetFFmpegVersion(output);
  105. if (logOutput)
  106. {
  107. _logger.LogInformation("FFmpeg validation: Found ffmpeg version {0}", underTest.ToString());
  108. if (underTest.Unknown())
  109. {
  110. if (minRequired.Same(maxRequired))
  111. {
  112. _logger.LogWarning("FFmpeg validation: We recommend ffmpeg version {0}", minRequired.ToString());
  113. }
  114. else
  115. {
  116. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {0} and maximum of {1}", minRequired.ToString(), maxRequired.ToString());
  117. }
  118. }
  119. else if (underTest.Below(minRequired))
  120. {
  121. _logger.LogWarning("FFmpeg validation: The minimum recommended ffmpeg version is {0}", minRequired.ToString());
  122. }
  123. else if (underTest.Above(maxRequired))
  124. {
  125. _logger.LogWarning("FFmpeg validation: The maximum recommended ffmpeg version is {0}", maxRequired.ToString());
  126. }
  127. else
  128. {
  129. // Version is ok so no warning required
  130. }
  131. }
  132. return !underTest.Below(minRequired) && !underTest.Above(maxRequired);
  133. }
  134. /// <summary>
  135. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  136. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  137. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  138. /// If that fails then we use one of the main libraries to determine if it's new/older than the latest
  139. /// we have stored.
  140. /// </summary>
  141. /// <param name="output"></param>
  142. /// <returns></returns>
  143. static private FFmpegVersion GetFFmpegVersion(string output)
  144. {
  145. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  146. var match = Regex.Match(output, @"ffmpeg version (\d+\.\d+)");
  147. if (match.Success)
  148. {
  149. return new FFmpegVersion(match.Groups[1].Value);
  150. }
  151. else
  152. {
  153. // Try and use the individual library versions to determine a FFmpeg version
  154. // This lookup table is to be maintained with the following command line:
  155. // $ ./ffmpeg.exe -version | perl -ne ' print "$1=$2.$3," if /^(lib\w+)\s+(\d+)\.\s*(\d+)/'
  156. var lut = new ReadOnlyDictionary<FFmpegVersion, string>
  157. (new Dictionary<FFmpegVersion, string>
  158. {
  159. { 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," },
  160. { 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," },
  161. { 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," },
  162. { 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," },
  163. { 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," },
  164. { 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," }
  165. });
  166. // Create a reduced version string and lookup key from dictionary
  167. var reducedVersion = GetVersionString(output);
  168. var found = lut.FirstOrDefault(x => x.Value == reducedVersion).Key;
  169. return found ?? new FFmpegVersion("Unknown");
  170. }
  171. }
  172. /// <summary>
  173. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  174. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc."
  175. /// </summary>
  176. /// <param name="output"></param>
  177. /// <returns></returns>
  178. static private string GetVersionString(string output)
  179. {
  180. string pattern = @"((?<name>lib\w+)\s+(?<major>\d+)\.\s*(?<minor>\d+))";
  181. RegexOptions options = RegexOptions.Multiline;
  182. string rc = null;
  183. foreach (Match m in Regex.Matches(output, pattern, options))
  184. {
  185. rc += string.Concat(m.Groups["name"], '=', m.Groups["major"], '.', m.Groups["minor"], ',');
  186. }
  187. return rc;
  188. }
  189. private static readonly string[] requiredDecoders = new[]
  190. {
  191. "mpeg2video",
  192. "h264_qsv",
  193. "hevc_qsv",
  194. "mpeg2_qsv",
  195. "vc1_qsv",
  196. "h264_cuvid",
  197. "hevc_cuvid",
  198. "dts",
  199. "ac3",
  200. "aac",
  201. "mp3",
  202. "h264",
  203. "hevc"
  204. };
  205. private static readonly string[] requiredEncoders = new[]
  206. {
  207. "libx264",
  208. "libx265",
  209. "mpeg4",
  210. "msmpeg4",
  211. "libvpx",
  212. "libvpx-vp9",
  213. "aac",
  214. "libmp3lame",
  215. "libopus",
  216. "libvorbis",
  217. "srt",
  218. "h264_nvenc",
  219. "hevc_nvenc",
  220. "h264_qsv",
  221. "hevc_qsv",
  222. "h264_omx",
  223. "hevc_omx",
  224. "h264_vaapi",
  225. "hevc_vaapi",
  226. "ac3"
  227. };
  228. private enum Codec
  229. {
  230. Encoder,
  231. Decoder
  232. }
  233. private IEnumerable<string> GetCodecs(string encoderAppPath, Codec codec)
  234. {
  235. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  236. string output = null;
  237. try
  238. {
  239. output = GetProcessOutput(encoderAppPath, "-" + codecstr);
  240. }
  241. catch (Exception ex)
  242. {
  243. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  244. }
  245. if (string.IsNullOrWhiteSpace(output))
  246. {
  247. return Enumerable.Empty<string>();
  248. }
  249. var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders;
  250. var found = Regex
  251. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  252. .Cast<Match>()
  253. .Select(x => x.Groups["codec"].Value)
  254. .Where(x => required.Contains(x));
  255. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  256. return found;
  257. }
  258. private string GetProcessOutput(string path, string arguments)
  259. {
  260. IProcess process = _processFactory.Create(new ProcessOptions
  261. {
  262. CreateNoWindow = true,
  263. UseShellExecute = false,
  264. FileName = path,
  265. Arguments = arguments,
  266. IsHidden = true,
  267. ErrorDialog = false,
  268. RedirectStandardOutput = true,
  269. // ffmpeg uses stderr to log info, don't show this
  270. RedirectStandardError = true
  271. });
  272. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  273. using (process)
  274. {
  275. process.Start();
  276. try
  277. {
  278. return process.StandardOutput.ReadToEnd();
  279. }
  280. catch
  281. {
  282. _logger.LogWarning("Killing process {Path} {Arguments}", path, arguments);
  283. // Hate having to do this
  284. try
  285. {
  286. process.Kill();
  287. }
  288. catch (Exception ex)
  289. {
  290. _logger.LogError(ex, "Error killing process");
  291. }
  292. throw;
  293. }
  294. }
  295. }
  296. }
  297. }