EncoderValidator.cs 11 KB

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