EncoderValidator.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 && MinVersion != null && MaxVersion != null) // Version is unknown
  105. {
  106. if (MinVersion == MaxVersion)
  107. {
  108. _logger.LogWarning("FFmpeg validation: We recommend ffmpeg version {0}", MinVersion);
  109. }
  110. else
  111. {
  112. _logger.LogWarning("FFmpeg validation: We recommend a minimum of {0} and maximum of {1}", MinVersion, MaxVersion);
  113. }
  114. return false;
  115. }
  116. else if (MinVersion != null && version < MinVersion) // Version is below what we recommend
  117. {
  118. _logger.LogWarning("FFmpeg validation: The minimum recommended ffmpeg version is {0}", MinVersion);
  119. return false;
  120. }
  121. else if (MaxVersion != null && version > MaxVersion) // Version is above what we recommend
  122. {
  123. _logger.LogWarning("FFmpeg validation: The maximum recommended ffmpeg version is {0}", MaxVersion);
  124. return false;
  125. }
  126. return true;
  127. }
  128. public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
  129. public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
  130. /// <summary>
  131. /// Using the output from "ffmpeg -version" work out the FFmpeg version.
  132. /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
  133. /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
  134. /// If that fails then we use one of the main libraries to determine if it's new/older than the latest
  135. /// we have stored.
  136. /// </summary>
  137. /// <param name="output"></param>
  138. /// <returns></returns>
  139. internal static Version GetFFmpegVersion(string output)
  140. {
  141. // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
  142. var match = Regex.Match(output, @"ffmpeg version ((?:\d+\.?)+)");
  143. if (match.Success)
  144. {
  145. return new Version(match.Groups[1].Value);
  146. }
  147. else
  148. {
  149. // Create a reduced version string and lookup key from dictionary
  150. var reducedVersion = GetLibrariesVersionString(output);
  151. // Try to lookup the string and return Key, otherwise if not found returns null
  152. return _ffmpegVersionMap.TryGetValue(reducedVersion, out Version version) ? version : null;
  153. }
  154. }
  155. /// <summary>
  156. /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
  157. /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc."
  158. /// </summary>
  159. /// <param name="output"></param>
  160. /// <returns></returns>
  161. private static string GetLibrariesVersionString(string output)
  162. {
  163. var rc = new StringBuilder(144);
  164. foreach (Match m in Regex.Matches(
  165. output,
  166. @"((?<name>lib\w+)\s+(?<major>\d+)\.\s*(?<minor>\d+))",
  167. RegexOptions.Multiline))
  168. {
  169. rc.Append(m.Groups["name"])
  170. .Append('=')
  171. .Append(m.Groups["major"])
  172. .Append('.')
  173. .Append(m.Groups["minor"])
  174. .Append(',');
  175. }
  176. return rc.Length == 0 ? null : rc.ToString();
  177. }
  178. private enum Codec
  179. {
  180. Encoder,
  181. Decoder
  182. }
  183. private IEnumerable<string> GetCodecs(Codec codec)
  184. {
  185. string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
  186. string output = null;
  187. try
  188. {
  189. output = GetProcessOutput(_encoderPath, "-" + codecstr);
  190. }
  191. catch (Exception ex)
  192. {
  193. _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
  194. }
  195. if (string.IsNullOrWhiteSpace(output))
  196. {
  197. return Enumerable.Empty<string>();
  198. }
  199. var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders;
  200. var found = Regex
  201. .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
  202. .Cast<Match>()
  203. .Select(x => x.Groups["codec"].Value)
  204. .Where(x => required.Contains(x));
  205. _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
  206. return found;
  207. }
  208. private string GetProcessOutput(string path, string arguments)
  209. {
  210. using (var process = new Process()
  211. {
  212. StartInfo = new ProcessStartInfo(path, arguments)
  213. {
  214. CreateNoWindow = true,
  215. UseShellExecute = false,
  216. WindowStyle = ProcessWindowStyle.Hidden,
  217. ErrorDialog = false,
  218. RedirectStandardOutput = true,
  219. // ffmpeg uses stderr to log info, don't show this
  220. RedirectStandardError = true
  221. }
  222. })
  223. {
  224. _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
  225. process.Start();
  226. return process.StandardOutput.ReadToEnd();
  227. }
  228. }
  229. }
  230. }