EncoderValidator.cs 11 KB

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