BaseFFProbeProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.MediaInfo;
  5. using MediaBrowser.Controller.Persistence;
  6. using MediaBrowser.Model.Entities;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Model.Logging;
  13. namespace MediaBrowser.Controller.Providers.MediaInfo
  14. {
  15. /// <summary>
  16. /// Provides a base class for extracting media information through ffprobe
  17. /// </summary>
  18. /// <typeparam name="T"></typeparam>
  19. public abstract class BaseFFProbeProvider<T> : BaseFFMpegProvider<T>
  20. where T : BaseItem
  21. {
  22. protected BaseFFProbeProvider(ILogManager logManager, IServerConfigurationManager configurationManager) : base(logManager, configurationManager)
  23. {
  24. }
  25. /// <summary>
  26. /// Gets or sets the FF probe cache.
  27. /// </summary>
  28. /// <value>The FF probe cache.</value>
  29. protected FileSystemRepository FFProbeCache { get; set; }
  30. /// <summary>
  31. /// Initializes this instance.
  32. /// </summary>
  33. protected override void Initialize()
  34. {
  35. base.Initialize();
  36. FFProbeCache = new FileSystemRepository(Path.Combine(ConfigurationManager.ApplicationPaths.CachePath, CacheDirectoryName));
  37. }
  38. /// <summary>
  39. /// Gets the name of the cache directory.
  40. /// </summary>
  41. /// <value>The name of the cache directory.</value>
  42. protected virtual string CacheDirectoryName
  43. {
  44. get
  45. {
  46. return "ffmpeg-video-info";
  47. }
  48. }
  49. /// <summary>
  50. /// Gets the priority.
  51. /// </summary>
  52. /// <value>The priority.</value>
  53. public override MetadataProviderPriority Priority
  54. {
  55. // Give this second priority
  56. // Give metadata xml providers a chance to fill in data first, so that we can skip this whenever possible
  57. get { return MetadataProviderPriority.Second; }
  58. }
  59. /// <summary>
  60. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  61. /// </summary>
  62. /// <param name="item">The item.</param>
  63. /// <param name="force">if set to <c>true</c> [force].</param>
  64. /// <param name="cancellationToken">The cancellation token.</param>
  65. /// <returns>Task{System.Boolean}.</returns>
  66. protected override async Task<bool> FetchAsyncInternal(BaseItem item, bool force, CancellationToken cancellationToken)
  67. {
  68. var myItem = (T)item;
  69. var isoMount = await MountIsoIfNeeded(myItem, cancellationToken).ConfigureAwait(false);
  70. try
  71. {
  72. OnPreFetch(myItem, isoMount);
  73. var inputPath = isoMount == null ?
  74. Kernel.Instance.FFMpegManager.GetInputArgument(myItem) :
  75. Kernel.Instance.FFMpegManager.GetInputArgument((Video)item, isoMount);
  76. var result = await Kernel.Instance.FFMpegManager.RunFFProbe(item, inputPath, item.DateModified, FFProbeCache, cancellationToken).ConfigureAwait(false);
  77. cancellationToken.ThrowIfCancellationRequested();
  78. NormalizeFFProbeResult(result);
  79. cancellationToken.ThrowIfCancellationRequested();
  80. await Fetch(myItem, cancellationToken, result, isoMount).ConfigureAwait(false);
  81. cancellationToken.ThrowIfCancellationRequested();
  82. SetLastRefreshed(item, DateTime.UtcNow);
  83. }
  84. finally
  85. {
  86. if (isoMount != null)
  87. {
  88. isoMount.Dispose();
  89. }
  90. }
  91. return true;
  92. }
  93. /// <summary>
  94. /// Gets a value indicating whether [refresh on version change].
  95. /// </summary>
  96. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  97. protected override bool RefreshOnVersionChange
  98. {
  99. get
  100. {
  101. return true;
  102. }
  103. }
  104. /// <summary>
  105. /// Mounts the iso if needed.
  106. /// </summary>
  107. /// <param name="item">The item.</param>
  108. /// <param name="cancellationToken">The cancellation token.</param>
  109. /// <returns>IsoMount.</returns>
  110. protected virtual Task<IIsoMount> MountIsoIfNeeded(T item, CancellationToken cancellationToken)
  111. {
  112. return NullMountTaskResult;
  113. }
  114. /// <summary>
  115. /// Called when [pre fetch].
  116. /// </summary>
  117. /// <param name="item">The item.</param>
  118. /// <param name="mount">The mount.</param>
  119. protected virtual void OnPreFetch(T item, IIsoMount mount)
  120. {
  121. }
  122. /// <summary>
  123. /// Normalizes the FF probe result.
  124. /// </summary>
  125. /// <param name="result">The result.</param>
  126. private void NormalizeFFProbeResult(FFProbeResult result)
  127. {
  128. if (result.format != null && result.format.tags != null)
  129. {
  130. result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
  131. }
  132. if (result.streams != null)
  133. {
  134. // Convert all dictionaries to case insensitive
  135. foreach (var stream in result.streams)
  136. {
  137. if (stream.tags != null)
  138. {
  139. stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
  140. }
  141. if (stream.disposition != null)
  142. {
  143. stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
  144. }
  145. }
  146. }
  147. }
  148. /// <summary>
  149. /// Subclasses must set item values using this
  150. /// </summary>
  151. /// <param name="item">The item.</param>
  152. /// <param name="cancellationToken">The cancellation token.</param>
  153. /// <param name="result">The result.</param>
  154. /// <param name="isoMount">The iso mount.</param>
  155. /// <returns>Task.</returns>
  156. protected abstract Task Fetch(T item, CancellationToken cancellationToken, FFProbeResult result, IIsoMount isoMount);
  157. /// <summary>
  158. /// Converts ffprobe stream info to our MediaStream class
  159. /// </summary>
  160. /// <param name="streamInfo">The stream info.</param>
  161. /// <param name="formatInfo">The format info.</param>
  162. /// <returns>MediaStream.</returns>
  163. protected MediaStream GetMediaStream(FFProbeMediaStreamInfo streamInfo, FFProbeMediaFormatInfo formatInfo)
  164. {
  165. var stream = new MediaStream
  166. {
  167. Codec = streamInfo.codec_name,
  168. Language = GetDictionaryValue(streamInfo.tags, "language"),
  169. Profile = streamInfo.profile,
  170. Index = streamInfo.index
  171. };
  172. if (streamInfo.codec_type.Equals("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);
  179. }
  180. }
  181. else if (streamInfo.codec_type.Equals("subtitle", StringComparison.OrdinalIgnoreCase))
  182. {
  183. stream.Type = MediaStreamType.Subtitle;
  184. }
  185. else
  186. {
  187. stream.Type = MediaStreamType.Video;
  188. stream.Width = streamInfo.width;
  189. stream.Height = streamInfo.height;
  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. // Get stream bitrate
  195. if (stream.Type != MediaStreamType.Subtitle)
  196. {
  197. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  198. {
  199. stream.BitRate = int.Parse(streamInfo.bit_rate);
  200. }
  201. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate))
  202. {
  203. // If the stream info doesn't have a bitrate get the value from the media format info
  204. stream.BitRate = int.Parse(formatInfo.bit_rate);
  205. }
  206. }
  207. if (streamInfo.disposition != null)
  208. {
  209. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  210. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  211. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  212. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  213. }
  214. return stream;
  215. }
  216. /// <summary>
  217. /// Gets a frame rate from a string value in ffprobe output
  218. /// This could be a number or in the format of 2997/125.
  219. /// </summary>
  220. /// <param name="value">The value.</param>
  221. /// <returns>System.Nullable{System.Single}.</returns>
  222. private float? GetFrameRate(string value)
  223. {
  224. if (!string.IsNullOrEmpty(value))
  225. {
  226. var parts = value.Split('/');
  227. if (parts.Length == 2)
  228. {
  229. return float.Parse(parts[0]) / float.Parse(parts[1]);
  230. }
  231. return float.Parse(parts[0]);
  232. }
  233. return null;
  234. }
  235. /// <summary>
  236. /// Gets a string from an FFProbeResult tags dictionary
  237. /// </summary>
  238. /// <param name="tags">The tags.</param>
  239. /// <param name="key">The key.</param>
  240. /// <returns>System.String.</returns>
  241. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  242. {
  243. if (tags == null)
  244. {
  245. return null;
  246. }
  247. string val;
  248. tags.TryGetValue(key, out val);
  249. return val;
  250. }
  251. /// <summary>
  252. /// Gets an int from an FFProbeResult tags dictionary
  253. /// </summary>
  254. /// <param name="tags">The tags.</param>
  255. /// <param name="key">The key.</param>
  256. /// <returns>System.Nullable{System.Int32}.</returns>
  257. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  258. {
  259. var val = GetDictionaryValue(tags, key);
  260. if (!string.IsNullOrEmpty(val))
  261. {
  262. int i;
  263. if (int.TryParse(val, out i))
  264. {
  265. return i;
  266. }
  267. }
  268. return null;
  269. }
  270. /// <summary>
  271. /// Gets a DateTime from an FFProbeResult tags dictionary
  272. /// </summary>
  273. /// <param name="tags">The tags.</param>
  274. /// <param name="key">The key.</param>
  275. /// <returns>System.Nullable{DateTime}.</returns>
  276. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  277. {
  278. var val = GetDictionaryValue(tags, key);
  279. if (!string.IsNullOrEmpty(val))
  280. {
  281. DateTime i;
  282. if (DateTime.TryParse(val, out i))
  283. {
  284. return i.ToUniversalTime();
  285. }
  286. }
  287. return null;
  288. }
  289. /// <summary>
  290. /// Converts a dictionary to case insensitive
  291. /// </summary>
  292. /// <param name="dict">The dict.</param>
  293. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  294. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  295. {
  296. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  297. }
  298. /// <summary>
  299. /// Releases unmanaged and - optionally - managed resources.
  300. /// </summary>
  301. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  302. protected override void Dispose(bool dispose)
  303. {
  304. if (dispose)
  305. {
  306. FFProbeCache.Dispose();
  307. }
  308. base.Dispose(dispose);
  309. }
  310. }
  311. }