BaseFFProbeProvider.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. using System.Globalization;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.MediaInfo;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  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. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  60. /// <summary>
  61. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  62. /// </summary>
  63. /// <param name="item">The item.</param>
  64. /// <param name="force">if set to <c>true</c> [force].</param>
  65. /// <param name="cancellationToken">The cancellation token.</param>
  66. /// <returns>Task{System.Boolean}.</returns>
  67. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  68. {
  69. var myItem = (T)item;
  70. var isoMount = await MountIsoIfNeeded(myItem, cancellationToken).ConfigureAwait(false);
  71. try
  72. {
  73. OnPreFetch(myItem, isoMount);
  74. var inputPath = isoMount == null ?
  75. Kernel.Instance.FFMpegManager.GetInputArgument(myItem) :
  76. Kernel.Instance.FFMpegManager.GetInputArgument((Video)item, isoMount);
  77. var result = await Kernel.Instance.FFMpegManager.RunFFProbe(item, inputPath, item.DateModified, FFProbeCache, cancellationToken).ConfigureAwait(false);
  78. cancellationToken.ThrowIfCancellationRequested();
  79. NormalizeFFProbeResult(result);
  80. cancellationToken.ThrowIfCancellationRequested();
  81. await Fetch(myItem, cancellationToken, result, isoMount).ConfigureAwait(false);
  82. cancellationToken.ThrowIfCancellationRequested();
  83. SetLastRefreshed(item, DateTime.UtcNow);
  84. }
  85. finally
  86. {
  87. if (isoMount != null)
  88. {
  89. isoMount.Dispose();
  90. }
  91. }
  92. return true;
  93. }
  94. /// <summary>
  95. /// Gets a value indicating whether [refresh on version change].
  96. /// </summary>
  97. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  98. protected override bool RefreshOnVersionChange
  99. {
  100. get
  101. {
  102. return true;
  103. }
  104. }
  105. /// <summary>
  106. /// Mounts the iso if needed.
  107. /// </summary>
  108. /// <param name="item">The item.</param>
  109. /// <param name="cancellationToken">The cancellation token.</param>
  110. /// <returns>IsoMount.</returns>
  111. protected virtual Task<IIsoMount> MountIsoIfNeeded(T item, CancellationToken cancellationToken)
  112. {
  113. return NullMountTaskResult;
  114. }
  115. /// <summary>
  116. /// Called when [pre fetch].
  117. /// </summary>
  118. /// <param name="item">The item.</param>
  119. /// <param name="mount">The mount.</param>
  120. protected virtual void OnPreFetch(T item, IIsoMount mount)
  121. {
  122. }
  123. /// <summary>
  124. /// Normalizes the FF probe result.
  125. /// </summary>
  126. /// <param name="result">The result.</param>
  127. private void NormalizeFFProbeResult(FFProbeResult result)
  128. {
  129. if (result.format != null && result.format.tags != null)
  130. {
  131. result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
  132. }
  133. if (result.streams != null)
  134. {
  135. // Convert all dictionaries to case insensitive
  136. foreach (var stream in result.streams)
  137. {
  138. if (stream.tags != null)
  139. {
  140. stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
  141. }
  142. if (stream.disposition != null)
  143. {
  144. stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
  145. }
  146. }
  147. }
  148. }
  149. /// <summary>
  150. /// Subclasses must set item values using this
  151. /// </summary>
  152. /// <param name="item">The item.</param>
  153. /// <param name="cancellationToken">The cancellation token.</param>
  154. /// <param name="result">The result.</param>
  155. /// <param name="isoMount">The iso mount.</param>
  156. /// <returns>Task.</returns>
  157. protected abstract Task Fetch(T item, CancellationToken cancellationToken, FFProbeResult result, IIsoMount isoMount);
  158. /// <summary>
  159. /// Converts ffprobe stream info to our MediaStream class
  160. /// </summary>
  161. /// <param name="streamInfo">The stream info.</param>
  162. /// <param name="formatInfo">The format info.</param>
  163. /// <returns>MediaStream.</returns>
  164. protected MediaStream GetMediaStream(FFProbeMediaStreamInfo streamInfo, FFProbeMediaFormatInfo formatInfo)
  165. {
  166. var stream = new MediaStream
  167. {
  168. Codec = streamInfo.codec_name,
  169. Language = GetDictionaryValue(streamInfo.tags, "language"),
  170. Profile = streamInfo.profile,
  171. Level = streamInfo.level,
  172. Index = streamInfo.index
  173. };
  174. if (streamInfo.codec_type.Equals("audio", StringComparison.OrdinalIgnoreCase))
  175. {
  176. stream.Type = MediaStreamType.Audio;
  177. stream.Channels = streamInfo.channels;
  178. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  179. {
  180. stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture);
  181. }
  182. }
  183. else if (streamInfo.codec_type.Equals("subtitle", StringComparison.OrdinalIgnoreCase))
  184. {
  185. stream.Type = MediaStreamType.Subtitle;
  186. }
  187. else if (streamInfo.codec_type.Equals("data", StringComparison.OrdinalIgnoreCase))
  188. {
  189. stream.Type = MediaStreamType.Data;
  190. }
  191. else
  192. {
  193. stream.Type = MediaStreamType.Video;
  194. stream.Width = streamInfo.width;
  195. stream.Height = streamInfo.height;
  196. stream.AspectRatio = streamInfo.display_aspect_ratio;
  197. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  198. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  199. }
  200. // Get stream bitrate
  201. if (stream.Type != MediaStreamType.Subtitle)
  202. {
  203. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  204. {
  205. stream.BitRate = int.Parse(streamInfo.bit_rate, UsCulture);
  206. }
  207. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate))
  208. {
  209. // If the stream info doesn't have a bitrate get the value from the media format info
  210. stream.BitRate = int.Parse(formatInfo.bit_rate, UsCulture);
  211. }
  212. }
  213. if (streamInfo.disposition != null)
  214. {
  215. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  216. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  217. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  218. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  219. }
  220. return stream;
  221. }
  222. /// <summary>
  223. /// Gets a frame rate from a string value in ffprobe output
  224. /// This could be a number or in the format of 2997/125.
  225. /// </summary>
  226. /// <param name="value">The value.</param>
  227. /// <returns>System.Nullable{System.Single}.</returns>
  228. private float? GetFrameRate(string value)
  229. {
  230. if (!string.IsNullOrEmpty(value))
  231. {
  232. var parts = value.Split('/');
  233. float result;
  234. if (parts.Length == 2)
  235. {
  236. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  237. }
  238. else
  239. {
  240. result = float.Parse(parts[0], UsCulture);
  241. }
  242. return float.IsNaN(result) ? (float?)null : result;
  243. }
  244. return null;
  245. }
  246. /// <summary>
  247. /// Gets a string from an FFProbeResult tags dictionary
  248. /// </summary>
  249. /// <param name="tags">The tags.</param>
  250. /// <param name="key">The key.</param>
  251. /// <returns>System.String.</returns>
  252. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  253. {
  254. if (tags == null)
  255. {
  256. return null;
  257. }
  258. string val;
  259. tags.TryGetValue(key, out val);
  260. return val;
  261. }
  262. /// <summary>
  263. /// Gets an int from an FFProbeResult tags dictionary
  264. /// </summary>
  265. /// <param name="tags">The tags.</param>
  266. /// <param name="key">The key.</param>
  267. /// <returns>System.Nullable{System.Int32}.</returns>
  268. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  269. {
  270. var val = GetDictionaryValue(tags, key);
  271. if (!string.IsNullOrEmpty(val))
  272. {
  273. int i;
  274. if (int.TryParse(val, out i))
  275. {
  276. return i;
  277. }
  278. }
  279. return null;
  280. }
  281. /// <summary>
  282. /// Gets a DateTime from an FFProbeResult tags dictionary
  283. /// </summary>
  284. /// <param name="tags">The tags.</param>
  285. /// <param name="key">The key.</param>
  286. /// <returns>System.Nullable{DateTime}.</returns>
  287. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  288. {
  289. var val = GetDictionaryValue(tags, key);
  290. if (!string.IsNullOrEmpty(val))
  291. {
  292. DateTime i;
  293. if (DateTime.TryParse(val, out i))
  294. {
  295. return i.ToUniversalTime();
  296. }
  297. }
  298. return null;
  299. }
  300. /// <summary>
  301. /// Converts a dictionary to case insensitive
  302. /// </summary>
  303. /// <param name="dict">The dict.</param>
  304. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  305. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  306. {
  307. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  308. }
  309. /// <summary>
  310. /// Releases unmanaged and - optionally - managed resources.
  311. /// </summary>
  312. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  313. protected virtual void Dispose(bool dispose)
  314. {
  315. if (dispose)
  316. {
  317. FFProbeCache.Dispose();
  318. }
  319. }
  320. public void Dispose()
  321. {
  322. Dispose(true);
  323. }
  324. }
  325. }