2
0

BaseFFProbeProvider.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. using MediaBrowser.Common.MediaInfo;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.MediaInfo;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.IO;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Providers.MediaInfo
  17. {
  18. /// <summary>
  19. /// Provides a base class for extracting media information through ffprobe
  20. /// </summary>
  21. /// <typeparam name="T"></typeparam>
  22. public abstract class BaseFFProbeProvider<T> : BaseMetadataProvider
  23. where T : BaseItem, IHasMediaStreams
  24. {
  25. protected BaseFFProbeProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder, IJsonSerializer jsonSerializer)
  26. : base(logManager, configurationManager)
  27. {
  28. JsonSerializer = jsonSerializer;
  29. MediaEncoder = mediaEncoder;
  30. }
  31. protected readonly IMediaEncoder MediaEncoder;
  32. protected readonly IJsonSerializer JsonSerializer;
  33. /// <summary>
  34. /// Gets the priority.
  35. /// </summary>
  36. /// <value>The priority.</value>
  37. public override MetadataProviderPriority Priority
  38. {
  39. get { return MetadataProviderPriority.First; }
  40. }
  41. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  42. /// <summary>
  43. /// Supportses the specified item.
  44. /// </summary>
  45. /// <param name="item">The item.</param>
  46. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  47. public override bool Supports(BaseItem item)
  48. {
  49. return item.LocationType == LocationType.FileSystem && item is T;
  50. }
  51. /// <summary>
  52. /// Override this to return the date that should be compared to the last refresh date
  53. /// to determine if this provider should be re-fetched.
  54. /// </summary>
  55. /// <param name="item">The item.</param>
  56. /// <returns>DateTime.</returns>
  57. protected override DateTime CompareDate(BaseItem item)
  58. {
  59. return item.DateModified;
  60. }
  61. /// <summary>
  62. /// The null mount task result
  63. /// </summary>
  64. protected readonly Task<IIsoMount> NullMountTaskResult = Task.FromResult<IIsoMount>(null);
  65. /// <summary>
  66. /// Gets the provider version.
  67. /// </summary>
  68. /// <value>The provider version.</value>
  69. protected override string ProviderVersion
  70. {
  71. get
  72. {
  73. return MediaEncoder.Version;
  74. }
  75. }
  76. /// <summary>
  77. /// Gets a value indicating whether [refresh on version change].
  78. /// </summary>
  79. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  80. protected override bool RefreshOnVersionChange
  81. {
  82. get
  83. {
  84. return true;
  85. }
  86. }
  87. /// <summary>
  88. /// Gets the media info.
  89. /// </summary>
  90. /// <param name="item">The item.</param>
  91. /// <param name="isoMount">The iso mount.</param>
  92. /// <param name="cancellationToken">The cancellation token.</param>
  93. /// <returns>Task{MediaInfoResult}.</returns>
  94. /// <exception cref="System.ArgumentNullException">inputPath
  95. /// or
  96. /// cache</exception>
  97. protected async Task<MediaInfoResult> GetMediaInfo(BaseItem item, IIsoMount isoMount, CancellationToken cancellationToken)
  98. {
  99. cancellationToken.ThrowIfCancellationRequested();
  100. var type = InputType.AudioFile;
  101. var inputPath = isoMount == null ? new[] { item.Path } : new[] { isoMount.MountedPath };
  102. var video = item as Video;
  103. if (video != null)
  104. {
  105. inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  106. }
  107. return await MediaEncoder.GetMediaInfo(inputPath, type, cancellationToken).ConfigureAwait(false);
  108. }
  109. /// <summary>
  110. /// Mounts the iso if needed.
  111. /// </summary>
  112. /// <param name="item">The item.</param>
  113. /// <param name="cancellationToken">The cancellation token.</param>
  114. /// <returns>IsoMount.</returns>
  115. protected virtual Task<IIsoMount> MountIsoIfNeeded(T item, CancellationToken cancellationToken)
  116. {
  117. return NullMountTaskResult;
  118. }
  119. /// <summary>
  120. /// Called when [pre fetch].
  121. /// </summary>
  122. /// <param name="item">The item.</param>
  123. /// <param name="mount">The mount.</param>
  124. protected virtual void OnPreFetch(T item, IIsoMount mount)
  125. {
  126. }
  127. /// <summary>
  128. /// Normalizes the FF probe result.
  129. /// </summary>
  130. /// <param name="result">The result.</param>
  131. protected void NormalizeFFProbeResult(MediaInfoResult result)
  132. {
  133. if (result.format != null && result.format.tags != null)
  134. {
  135. result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
  136. }
  137. if (result.streams != null)
  138. {
  139. // Convert all dictionaries to case insensitive
  140. foreach (var stream in result.streams)
  141. {
  142. if (stream.tags != null)
  143. {
  144. stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
  145. }
  146. if (stream.disposition != null)
  147. {
  148. stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
  149. }
  150. }
  151. }
  152. }
  153. /// <summary>
  154. /// Converts ffprobe stream info to our MediaStream class
  155. /// </summary>
  156. /// <param name="streamInfo">The stream info.</param>
  157. /// <param name="formatInfo">The format info.</param>
  158. /// <returns>MediaStream.</returns>
  159. protected MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  160. {
  161. var stream = new MediaStream
  162. {
  163. Codec = streamInfo.codec_name,
  164. Profile = streamInfo.profile,
  165. Level = streamInfo.level,
  166. Index = streamInfo.index
  167. };
  168. if (streamInfo.tags != null)
  169. {
  170. stream.Language = GetDictionaryValue(streamInfo.tags, "language");
  171. }
  172. if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase))
  173. {
  174. stream.Type = MediaStreamType.Audio;
  175. stream.Channels = streamInfo.channels;
  176. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  177. {
  178. stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture);
  179. }
  180. stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
  181. }
  182. else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
  183. {
  184. stream.Type = MediaStreamType.Subtitle;
  185. }
  186. else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
  187. {
  188. stream.Type = MediaStreamType.Video;
  189. stream.Width = streamInfo.width;
  190. stream.Height = streamInfo.height;
  191. stream.AspectRatio = GetAspectRatio(streamInfo);
  192. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  193. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  194. }
  195. else
  196. {
  197. return null;
  198. }
  199. // Get stream bitrate
  200. if (stream.Type != MediaStreamType.Subtitle)
  201. {
  202. var bitrate = 0;
  203. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  204. {
  205. bitrate = int.Parse(streamInfo.bit_rate, UsCulture);
  206. }
  207. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate))
  208. {
  209. // If the stream info doesn't have a bitrate get the value from the media format info
  210. bitrate = int.Parse(formatInfo.bit_rate, UsCulture);
  211. }
  212. if (bitrate > 0)
  213. {
  214. stream.BitRate = bitrate;
  215. }
  216. }
  217. if (streamInfo.disposition != null)
  218. {
  219. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  220. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  221. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  222. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  223. }
  224. return stream;
  225. }
  226. private string ParseChannelLayout(string input)
  227. {
  228. if (string.IsNullOrEmpty(input))
  229. {
  230. return input;
  231. }
  232. return input.Split('(').FirstOrDefault();
  233. }
  234. private string GetAspectRatio(MediaStreamInfo info)
  235. {
  236. var original = info.display_aspect_ratio;
  237. int height;
  238. int width;
  239. var parts = (original ?? string.Empty).Split(':');
  240. if (!(parts.Length == 2 &&
  241. int.TryParse(parts[0], NumberStyles.Any, UsCulture, out width) &&
  242. int.TryParse(parts[1], NumberStyles.Any, UsCulture, out height) &&
  243. width > 0 &&
  244. height > 0))
  245. {
  246. width = info.width;
  247. height = info.height;
  248. }
  249. if (width > 0 && height > 0)
  250. {
  251. double ratio = width;
  252. ratio /= height;
  253. if (IsClose(ratio, 1.777777778, .03))
  254. {
  255. return "16:9";
  256. }
  257. if (IsClose(ratio, 1.3333333333, .05))
  258. {
  259. return "4:3";
  260. }
  261. if (IsClose(ratio, 1.41))
  262. {
  263. return "1.41:1";
  264. }
  265. if (IsClose(ratio, 1.5))
  266. {
  267. return "1.5:1";
  268. }
  269. if (IsClose(ratio, 1.6))
  270. {
  271. return "1.6:1";
  272. }
  273. if (IsClose(ratio, 1.66666666667))
  274. {
  275. return "5:3";
  276. }
  277. if (IsClose(ratio, 1.85, .02))
  278. {
  279. return "1.85:1";
  280. }
  281. if (IsClose(ratio, 2.35, .025))
  282. {
  283. return "2.35:1";
  284. }
  285. if (IsClose(ratio, 2.4, .025))
  286. {
  287. return "2.40:1";
  288. }
  289. }
  290. return original;
  291. }
  292. private bool IsClose(double d1, double d2, double variance = .005)
  293. {
  294. return Math.Abs(d1 - d2) <= variance;
  295. }
  296. /// <summary>
  297. /// Gets a frame rate from a string value in ffprobe output
  298. /// This could be a number or in the format of 2997/125.
  299. /// </summary>
  300. /// <param name="value">The value.</param>
  301. /// <returns>System.Nullable{System.Single}.</returns>
  302. private float? GetFrameRate(string value)
  303. {
  304. if (!string.IsNullOrEmpty(value))
  305. {
  306. var parts = value.Split('/');
  307. float result;
  308. if (parts.Length == 2)
  309. {
  310. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  311. }
  312. else
  313. {
  314. result = float.Parse(parts[0], UsCulture);
  315. }
  316. return float.IsNaN(result) ? (float?)null : result;
  317. }
  318. return null;
  319. }
  320. /// <summary>
  321. /// Gets a string from an FFProbeResult tags dictionary
  322. /// </summary>
  323. /// <param name="tags">The tags.</param>
  324. /// <param name="key">The key.</param>
  325. /// <returns>System.String.</returns>
  326. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  327. {
  328. if (tags == null)
  329. {
  330. return null;
  331. }
  332. string val;
  333. tags.TryGetValue(key, out val);
  334. return val;
  335. }
  336. /// <summary>
  337. /// Gets an int from an FFProbeResult tags dictionary
  338. /// </summary>
  339. /// <param name="tags">The tags.</param>
  340. /// <param name="key">The key.</param>
  341. /// <returns>System.Nullable{System.Int32}.</returns>
  342. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  343. {
  344. var val = GetDictionaryValue(tags, key);
  345. if (!string.IsNullOrEmpty(val))
  346. {
  347. int i;
  348. if (int.TryParse(val, out i))
  349. {
  350. return i;
  351. }
  352. }
  353. return null;
  354. }
  355. /// <summary>
  356. /// Gets a DateTime from an FFProbeResult tags dictionary
  357. /// </summary>
  358. /// <param name="tags">The tags.</param>
  359. /// <param name="key">The key.</param>
  360. /// <returns>System.Nullable{DateTime}.</returns>
  361. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  362. {
  363. var val = GetDictionaryValue(tags, key);
  364. if (!string.IsNullOrEmpty(val))
  365. {
  366. DateTime i;
  367. if (DateTime.TryParse(val, out i))
  368. {
  369. return i.ToUniversalTime();
  370. }
  371. }
  372. return null;
  373. }
  374. /// <summary>
  375. /// Converts a dictionary to case insensitive
  376. /// </summary>
  377. /// <param name="dict">The dict.</param>
  378. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  379. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  380. {
  381. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  382. }
  383. }
  384. }