EncoderValidator.cs 10 KB

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