EncoderValidator.cs 12 KB

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