EncoderValidator.cs 10 KB

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