MediaEncoderHelpers.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase);
  114. }
  115. else
  116. {
  117. return null;
  118. }
  119. // Get stream bitrate
  120. var bitrate = 0;
  121. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  122. {
  123. bitrate = int.Parse(streamInfo.bit_rate, UsCulture);
  124. }
  125. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
  126. {
  127. // If the stream info doesn't have a bitrate get the value from the media format info
  128. bitrate = int.Parse(formatInfo.bit_rate, UsCulture);
  129. }
  130. if (bitrate > 0)
  131. {
  132. stream.BitRate = bitrate;
  133. }
  134. if (streamInfo.disposition != null)
  135. {
  136. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  137. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  138. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  139. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  140. }
  141. return stream;
  142. }
  143. private static int? GetBitDepth(string pixelFormat)
  144. {
  145. var eightBit = new List<string>
  146. {
  147. "yuv420p",
  148. "yuv411p",
  149. "yuvj420p",
  150. "uyyvyy411",
  151. "nv12",
  152. "nv21",
  153. "rgb444le",
  154. "rgb444be",
  155. "bgr444le",
  156. "bgr444be",
  157. "yuvj411p"
  158. };
  159. if (!string.IsNullOrEmpty(pixelFormat))
  160. {
  161. if (eightBit.Contains(pixelFormat, StringComparer.OrdinalIgnoreCase))
  162. {
  163. return 8;
  164. }
  165. }
  166. return null;
  167. }
  168. /// <summary>
  169. /// Gets a string from an FFProbeResult tags dictionary
  170. /// </summary>
  171. /// <param name="tags">The tags.</param>
  172. /// <param name="key">The key.</param>
  173. /// <returns>System.String.</returns>
  174. private static string GetDictionaryValue(Dictionary<string, string> tags, string key)
  175. {
  176. if (tags == null)
  177. {
  178. return null;
  179. }
  180. string val;
  181. tags.TryGetValue(key, out val);
  182. return val;
  183. }
  184. private static string ParseChannelLayout(string input)
  185. {
  186. if (string.IsNullOrEmpty(input))
  187. {
  188. return input;
  189. }
  190. return input.Split('(').FirstOrDefault();
  191. }
  192. private static string GetAspectRatio(MediaStreamInfo info)
  193. {
  194. var original = info.display_aspect_ratio;
  195. int height;
  196. int width;
  197. var parts = (original ?? string.Empty).Split(':');
  198. if (!(parts.Length == 2 &&
  199. int.TryParse(parts[0], NumberStyles.Any, UsCulture, out width) &&
  200. int.TryParse(parts[1], NumberStyles.Any, UsCulture, out height) &&
  201. width > 0 &&
  202. height > 0))
  203. {
  204. width = info.width;
  205. height = info.height;
  206. }
  207. if (width > 0 && height > 0)
  208. {
  209. double ratio = width;
  210. ratio /= height;
  211. if (IsClose(ratio, 1.777777778, .03))
  212. {
  213. return "16:9";
  214. }
  215. if (IsClose(ratio, 1.3333333333, .05))
  216. {
  217. return "4:3";
  218. }
  219. if (IsClose(ratio, 1.41))
  220. {
  221. return "1.41:1";
  222. }
  223. if (IsClose(ratio, 1.5))
  224. {
  225. return "1.5:1";
  226. }
  227. if (IsClose(ratio, 1.6))
  228. {
  229. return "1.6:1";
  230. }
  231. if (IsClose(ratio, 1.66666666667))
  232. {
  233. return "5:3";
  234. }
  235. if (IsClose(ratio, 1.85, .02))
  236. {
  237. return "1.85:1";
  238. }
  239. if (IsClose(ratio, 2.35, .025))
  240. {
  241. return "2.35:1";
  242. }
  243. if (IsClose(ratio, 2.4, .025))
  244. {
  245. return "2.40:1";
  246. }
  247. }
  248. return original;
  249. }
  250. private static bool IsClose(double d1, double d2, double variance = .005)
  251. {
  252. return Math.Abs(d1 - d2) <= variance;
  253. }
  254. /// <summary>
  255. /// Gets a frame rate from a string value in ffprobe output
  256. /// This could be a number or in the format of 2997/125.
  257. /// </summary>
  258. /// <param name="value">The value.</param>
  259. /// <returns>System.Nullable{System.Single}.</returns>
  260. private static float? GetFrameRate(string value)
  261. {
  262. if (!string.IsNullOrEmpty(value))
  263. {
  264. var parts = value.Split('/');
  265. float result;
  266. if (parts.Length == 2)
  267. {
  268. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  269. }
  270. else
  271. {
  272. result = float.Parse(parts[0], UsCulture);
  273. }
  274. return float.IsNaN(result) ? (float?)null : result;
  275. }
  276. return null;
  277. }
  278. }
  279. }