BaseFFProbeProvider.cs 12 KB

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