MediaEncoderHelpers.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. using MediaBrowser.Model.Entities;
  2. using MediaBrowser.Model.IO;
  3. using MediaBrowser.Model.MediaInfo;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. namespace MediaBrowser.Controller.MediaEncoding
  10. {
  11. /// <summary>
  12. /// Class MediaEncoderHelpers
  13. /// </summary>
  14. public static class MediaEncoderHelpers
  15. {
  16. /// <summary>
  17. /// Gets the input argument.
  18. /// </summary>
  19. /// <param name="videoPath">The video path.</param>
  20. /// <param name="protocol">The protocol.</param>
  21. /// <param name="isoMount">The iso mount.</param>
  22. /// <param name="playableStreamFileNames">The playable stream file names.</param>
  23. /// <returns>System.String[][].</returns>
  24. public static string[] GetInputArgument(string videoPath, MediaProtocol protocol, IIsoMount isoMount, List<string> playableStreamFileNames)
  25. {
  26. if (playableStreamFileNames.Count > 0)
  27. {
  28. if (isoMount == null)
  29. {
  30. return GetPlayableStreamFiles(videoPath, playableStreamFileNames).ToArray();
  31. }
  32. return GetPlayableStreamFiles(isoMount.MountedPath, playableStreamFileNames).ToArray();
  33. }
  34. return new[] {videoPath};
  35. }
  36. public static List<string> GetPlayableStreamFiles(string rootPath, IEnumerable<string> filenames)
  37. {
  38. var allFiles = Directory
  39. .EnumerateFiles(rootPath, "*", SearchOption.AllDirectories)
  40. .ToList();
  41. return filenames.Select(name => allFiles.FirstOrDefault(f => string.Equals(Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase)))
  42. .Where(f => !string.IsNullOrEmpty(f))
  43. .ToList();
  44. }
  45. public static MediaInfo GetMediaInfo(InternalMediaInfoResult data)
  46. {
  47. var internalStreams = data.streams ?? new MediaStreamInfo[] { };
  48. var info = new MediaInfo
  49. {
  50. MediaStreams = internalStreams.Select(s => GetMediaStream(s, data.format))
  51. .Where(i => i != null)
  52. .ToList()
  53. };
  54. if (data.format != null)
  55. {
  56. info.Format = data.format.format_name;
  57. if (!string.IsNullOrEmpty(data.format.bit_rate))
  58. {
  59. info.TotalBitrate = int.Parse(data.format.bit_rate, UsCulture);
  60. }
  61. }
  62. return info;
  63. }
  64. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  65. /// <summary>
  66. /// Converts ffprobe stream info to our MediaStream class
  67. /// </summary>
  68. /// <param name="streamInfo">The stream info.</param>
  69. /// <param name="formatInfo">The format info.</param>
  70. /// <returns>MediaStream.</returns>
  71. private static MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  72. {
  73. var stream = new MediaStream
  74. {
  75. Codec = streamInfo.codec_name,
  76. Profile = streamInfo.profile,
  77. Level = streamInfo.level,
  78. Index = streamInfo.index,
  79. PixelFormat = streamInfo.pix_fmt
  80. };
  81. if (streamInfo.tags != null)
  82. {
  83. stream.Language = GetDictionaryValue(streamInfo.tags, "language");
  84. }
  85. if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase))
  86. {
  87. stream.Type = MediaStreamType.Audio;
  88. stream.Channels = streamInfo.channels;
  89. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  90. {
  91. stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture);
  92. }
  93. stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
  94. }
  95. else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
  96. {
  97. stream.Type = MediaStreamType.Subtitle;
  98. }
  99. else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
  100. {
  101. stream.Type = (streamInfo.codec_name ?? string.Empty).IndexOf("mjpeg", StringComparison.OrdinalIgnoreCase) != -1
  102. ? MediaStreamType.EmbeddedImage
  103. : MediaStreamType.Video;
  104. stream.Width = streamInfo.width;
  105. stream.Height = streamInfo.height;
  106. stream.AspectRatio = GetAspectRatio(streamInfo);
  107. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  108. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  109. stream.BitDepth = GetBitDepth(stream.PixelFormat);
  110. stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  111. string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  112. string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  113. }
  114. else
  115. {
  116. return null;
  117. }
  118. // Get stream bitrate
  119. var bitrate = 0;
  120. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  121. {
  122. bitrate = int.Parse(streamInfo.bit_rate, UsCulture);
  123. }
  124. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
  125. {
  126. // If the stream info doesn't have a bitrate get the value from the media format info
  127. bitrate = int.Parse(formatInfo.bit_rate, UsCulture);
  128. }
  129. if (bitrate > 0)
  130. {
  131. stream.BitRate = bitrate;
  132. }
  133. if (streamInfo.disposition != null)
  134. {
  135. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  136. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  137. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  138. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  139. }
  140. return stream;
  141. }
  142. private static int? GetBitDepth(string pixelFormat)
  143. {
  144. var eightBit = new List<string>
  145. {
  146. "yuv420p",
  147. "yuv411p",
  148. "yuvj420p",
  149. "uyyvyy411",
  150. "nv12",
  151. "nv21",
  152. "rgb444le",
  153. "rgb444be",
  154. "bgr444le",
  155. "bgr444be",
  156. "yuvj411p"
  157. };
  158. if (!string.IsNullOrEmpty(pixelFormat))
  159. {
  160. if (eightBit.Contains(pixelFormat, StringComparer.OrdinalIgnoreCase))
  161. {
  162. return 8;
  163. }
  164. }
  165. return null;
  166. }
  167. /// <summary>
  168. /// Gets a string from an FFProbeResult tags dictionary
  169. /// </summary>
  170. /// <param name="tags">The tags.</param>
  171. /// <param name="key">The key.</param>
  172. /// <returns>System.String.</returns>
  173. private static string GetDictionaryValue(Dictionary<string, string> tags, string key)
  174. {
  175. if (tags == null)
  176. {
  177. return null;
  178. }
  179. string val;
  180. tags.TryGetValue(key, out val);
  181. return val;
  182. }
  183. private static string ParseChannelLayout(string input)
  184. {
  185. if (string.IsNullOrEmpty(input))
  186. {
  187. return input;
  188. }
  189. return input.Split('(').FirstOrDefault();
  190. }
  191. private static string GetAspectRatio(MediaStreamInfo info)
  192. {
  193. var original = info.display_aspect_ratio;
  194. int height;
  195. int width;
  196. var parts = (original ?? string.Empty).Split(':');
  197. if (!(parts.Length == 2 &&
  198. int.TryParse(parts[0], NumberStyles.Any, UsCulture, out width) &&
  199. int.TryParse(parts[1], NumberStyles.Any, UsCulture, out height) &&
  200. width > 0 &&
  201. height > 0))
  202. {
  203. width = info.width;
  204. height = info.height;
  205. }
  206. if (width > 0 && height > 0)
  207. {
  208. double ratio = width;
  209. ratio /= height;
  210. if (IsClose(ratio, 1.777777778, .03))
  211. {
  212. return "16:9";
  213. }
  214. if (IsClose(ratio, 1.3333333333, .05))
  215. {
  216. return "4:3";
  217. }
  218. if (IsClose(ratio, 1.41))
  219. {
  220. return "1.41:1";
  221. }
  222. if (IsClose(ratio, 1.5))
  223. {
  224. return "1.5:1";
  225. }
  226. if (IsClose(ratio, 1.6))
  227. {
  228. return "1.6:1";
  229. }
  230. if (IsClose(ratio, 1.66666666667))
  231. {
  232. return "5:3";
  233. }
  234. if (IsClose(ratio, 1.85, .02))
  235. {
  236. return "1.85:1";
  237. }
  238. if (IsClose(ratio, 2.35, .025))
  239. {
  240. return "2.35:1";
  241. }
  242. if (IsClose(ratio, 2.4, .025))
  243. {
  244. return "2.40:1";
  245. }
  246. }
  247. return original;
  248. }
  249. private static bool IsClose(double d1, double d2, double variance = .005)
  250. {
  251. return Math.Abs(d1 - d2) <= variance;
  252. }
  253. /// <summary>
  254. /// Gets a frame rate from a string value in ffprobe output
  255. /// This could be a number or in the format of 2997/125.
  256. /// </summary>
  257. /// <param name="value">The value.</param>
  258. /// <returns>System.Nullable{System.Single}.</returns>
  259. private static float? GetFrameRate(string value)
  260. {
  261. if (!string.IsNullOrEmpty(value))
  262. {
  263. var parts = value.Split('/');
  264. float result;
  265. if (parts.Length == 2)
  266. {
  267. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  268. }
  269. else
  270. {
  271. result = float.Parse(parts[0], UsCulture);
  272. }
  273. return float.IsNaN(result) ? (float?)null : result;
  274. }
  275. return null;
  276. }
  277. }
  278. }