BaseFFProbeProvider.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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>, IDisposable
  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. public override async Task<bool> FetchAsync(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. float result;
  228. if (parts.Length == 2)
  229. {
  230. result = float.Parse(parts[0]) / float.Parse(parts[1]);
  231. }
  232. result = float.Parse(parts[0]);
  233. return float.IsNaN(result) ? (float?)null : result;
  234. }
  235. return null;
  236. }
  237. /// <summary>
  238. /// Gets a string from an FFProbeResult tags dictionary
  239. /// </summary>
  240. /// <param name="tags">The tags.</param>
  241. /// <param name="key">The key.</param>
  242. /// <returns>System.String.</returns>
  243. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  244. {
  245. if (tags == null)
  246. {
  247. return null;
  248. }
  249. string val;
  250. tags.TryGetValue(key, out val);
  251. return val;
  252. }
  253. /// <summary>
  254. /// Gets an int from an FFProbeResult tags dictionary
  255. /// </summary>
  256. /// <param name="tags">The tags.</param>
  257. /// <param name="key">The key.</param>
  258. /// <returns>System.Nullable{System.Int32}.</returns>
  259. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  260. {
  261. var val = GetDictionaryValue(tags, key);
  262. if (!string.IsNullOrEmpty(val))
  263. {
  264. int i;
  265. if (int.TryParse(val, out i))
  266. {
  267. return i;
  268. }
  269. }
  270. return null;
  271. }
  272. /// <summary>
  273. /// Gets a DateTime from an FFProbeResult tags dictionary
  274. /// </summary>
  275. /// <param name="tags">The tags.</param>
  276. /// <param name="key">The key.</param>
  277. /// <returns>System.Nullable{DateTime}.</returns>
  278. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  279. {
  280. var val = GetDictionaryValue(tags, key);
  281. if (!string.IsNullOrEmpty(val))
  282. {
  283. DateTime i;
  284. if (DateTime.TryParse(val, out i))
  285. {
  286. return i.ToUniversalTime();
  287. }
  288. }
  289. return null;
  290. }
  291. /// <summary>
  292. /// Converts a dictionary to case insensitive
  293. /// </summary>
  294. /// <param name="dict">The dict.</param>
  295. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  296. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  297. {
  298. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  299. }
  300. /// <summary>
  301. /// Releases unmanaged and - optionally - managed resources.
  302. /// </summary>
  303. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  304. protected virtual void Dispose(bool dispose)
  305. {
  306. if (dispose)
  307. {
  308. FFProbeCache.Dispose();
  309. }
  310. }
  311. public void Dispose()
  312. {
  313. Dispose(true);
  314. }
  315. }
  316. }