BaseFFProbeProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 = streamInfo.display_aspect_ratio;
  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. /// <summary>
  220. /// Gets a frame rate from a string value in ffprobe output
  221. /// This could be a number or in the format of 2997/125.
  222. /// </summary>
  223. /// <param name="value">The value.</param>
  224. /// <returns>System.Nullable{System.Single}.</returns>
  225. private float? GetFrameRate(string value)
  226. {
  227. if (!string.IsNullOrEmpty(value))
  228. {
  229. var parts = value.Split('/');
  230. float result;
  231. if (parts.Length == 2)
  232. {
  233. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  234. }
  235. else
  236. {
  237. result = float.Parse(parts[0], UsCulture);
  238. }
  239. return float.IsNaN(result) ? (float?)null : result;
  240. }
  241. return null;
  242. }
  243. /// <summary>
  244. /// Gets a string from an FFProbeResult tags dictionary
  245. /// </summary>
  246. /// <param name="tags">The tags.</param>
  247. /// <param name="key">The key.</param>
  248. /// <returns>System.String.</returns>
  249. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  250. {
  251. if (tags == null)
  252. {
  253. return null;
  254. }
  255. string val;
  256. tags.TryGetValue(key, out val);
  257. return val;
  258. }
  259. /// <summary>
  260. /// Gets an int from an FFProbeResult tags dictionary
  261. /// </summary>
  262. /// <param name="tags">The tags.</param>
  263. /// <param name="key">The key.</param>
  264. /// <returns>System.Nullable{System.Int32}.</returns>
  265. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  266. {
  267. var val = GetDictionaryValue(tags, key);
  268. if (!string.IsNullOrEmpty(val))
  269. {
  270. int i;
  271. if (int.TryParse(val, out i))
  272. {
  273. return i;
  274. }
  275. }
  276. return null;
  277. }
  278. /// <summary>
  279. /// Gets a DateTime from an FFProbeResult tags dictionary
  280. /// </summary>
  281. /// <param name="tags">The tags.</param>
  282. /// <param name="key">The key.</param>
  283. /// <returns>System.Nullable{DateTime}.</returns>
  284. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  285. {
  286. var val = GetDictionaryValue(tags, key);
  287. if (!string.IsNullOrEmpty(val))
  288. {
  289. DateTime i;
  290. if (DateTime.TryParse(val, out i))
  291. {
  292. return i.ToUniversalTime();
  293. }
  294. }
  295. return null;
  296. }
  297. /// <summary>
  298. /// Converts a dictionary to case insensitive
  299. /// </summary>
  300. /// <param name="dict">The dict.</param>
  301. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  302. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  303. {
  304. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  305. }
  306. }
  307. }