BaseFFProbeProvider.cs 13 KB

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