EncoderValidator.cs 10 KB

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