BaseFFProbeProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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.PixelFormat = streamInfo.pix_fmt;
  190. stream.AspectRatio = streamInfo.display_aspect_ratio;
  191. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  192. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  193. }
  194. else
  195. {
  196. return null;
  197. }
  198. // Get stream bitrate
  199. if (stream.Type != MediaStreamType.Subtitle)
  200. {
  201. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  202. {
  203. stream.BitRate = int.Parse(streamInfo.bit_rate, UsCulture);
  204. }
  205. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate))
  206. {
  207. // If the stream info doesn't have a bitrate get the value from the media format info
  208. stream.BitRate = int.Parse(formatInfo.bit_rate, UsCulture);
  209. }
  210. }
  211. if (streamInfo.disposition != null)
  212. {
  213. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  214. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  215. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  216. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  217. }
  218. return stream;
  219. }
  220. /// <summary>
  221. /// Gets a frame rate from a string value in ffprobe output
  222. /// This could be a number or in the format of 2997/125.
  223. /// </summary>
  224. /// <param name="value">The value.</param>
  225. /// <returns>System.Nullable{System.Single}.</returns>
  226. private float? GetFrameRate(string value)
  227. {
  228. if (!string.IsNullOrEmpty(value))
  229. {
  230. var parts = value.Split('/');
  231. float result;
  232. if (parts.Length == 2)
  233. {
  234. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  235. }
  236. else
  237. {
  238. result = float.Parse(parts[0], UsCulture);
  239. }
  240. return float.IsNaN(result) ? (float?)null : result;
  241. }
  242. return null;
  243. }
  244. /// <summary>
  245. /// Gets a string from an FFProbeResult tags dictionary
  246. /// </summary>
  247. /// <param name="tags">The tags.</param>
  248. /// <param name="key">The key.</param>
  249. /// <returns>System.String.</returns>
  250. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  251. {
  252. if (tags == null)
  253. {
  254. return null;
  255. }
  256. string val;
  257. tags.TryGetValue(key, out val);
  258. return val;
  259. }
  260. /// <summary>
  261. /// Gets an int from an FFProbeResult tags dictionary
  262. /// </summary>
  263. /// <param name="tags">The tags.</param>
  264. /// <param name="key">The key.</param>
  265. /// <returns>System.Nullable{System.Int32}.</returns>
  266. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  267. {
  268. var val = GetDictionaryValue(tags, key);
  269. if (!string.IsNullOrEmpty(val))
  270. {
  271. int i;
  272. if (int.TryParse(val, out i))
  273. {
  274. return i;
  275. }
  276. }
  277. return null;
  278. }
  279. /// <summary>
  280. /// Gets a DateTime from an FFProbeResult tags dictionary
  281. /// </summary>
  282. /// <param name="tags">The tags.</param>
  283. /// <param name="key">The key.</param>
  284. /// <returns>System.Nullable{DateTime}.</returns>
  285. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  286. {
  287. var val = GetDictionaryValue(tags, key);
  288. if (!string.IsNullOrEmpty(val))
  289. {
  290. DateTime i;
  291. if (DateTime.TryParse(val, out i))
  292. {
  293. return i.ToUniversalTime();
  294. }
  295. }
  296. return null;
  297. }
  298. /// <summary>
  299. /// Converts a dictionary to case insensitive
  300. /// </summary>
  301. /// <param name="dict">The dict.</param>
  302. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  303. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  304. {
  305. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  306. }
  307. }
  308. }