BaseFFProbeProvider.cs 14 KB

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