EncoderValidator.cs 12 KB

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