2
0

EncoderValidator.cs 12 KB

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