EncoderValidator.cs 10.0 KB

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