BaseFFProbeProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.MediaInfo;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Serialization;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Globalization;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Providers.MediaInfo
  17. {
  18. /// <summary>
  19. /// Provides a base class for extracting media information through ffprobe
  20. /// </summary>
  21. /// <typeparam name="T"></typeparam>
  22. public abstract class BaseFFProbeProvider<T> : BaseFFMpegProvider<T>
  23. where T : BaseItem
  24. {
  25. protected BaseFFProbeProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder, IJsonSerializer jsonSerializer)
  26. : base(logManager, configurationManager, mediaEncoder)
  27. {
  28. JsonSerializer = jsonSerializer;
  29. }
  30. protected readonly IJsonSerializer JsonSerializer;
  31. /// <summary>
  32. /// Gets the priority.
  33. /// </summary>
  34. /// <value>The priority.</value>
  35. public override MetadataProviderPriority Priority
  36. {
  37. get { return MetadataProviderPriority.First; }
  38. }
  39. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  40. /// <summary>
  41. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  42. /// </summary>
  43. /// <param name="item">The item.</param>
  44. /// <param name="force">if set to <c>true</c> [force].</param>
  45. /// <param name="cancellationToken">The cancellation token.</param>
  46. /// <returns>Task{System.Boolean}.</returns>
  47. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  48. {
  49. var myItem = (T)item;
  50. var isoMount = await MountIsoIfNeeded(myItem, cancellationToken).ConfigureAwait(false);
  51. try
  52. {
  53. OnPreFetch(myItem, isoMount);
  54. var result = await GetMediaInfo(item, isoMount, cancellationToken).ConfigureAwait(false);
  55. cancellationToken.ThrowIfCancellationRequested();
  56. NormalizeFFProbeResult(result);
  57. cancellationToken.ThrowIfCancellationRequested();
  58. Fetch(myItem, cancellationToken, result, isoMount);
  59. var video = myItem as Video;
  60. if (video != null)
  61. {
  62. await Kernel.Instance.FFMpegManager.PopulateChapterImages(video, cancellationToken, false, false).ConfigureAwait(false);
  63. }
  64. SetLastRefreshed(item, DateTime.UtcNow);
  65. }
  66. finally
  67. {
  68. if (isoMount != null)
  69. {
  70. isoMount.Dispose();
  71. }
  72. }
  73. return true;
  74. }
  75. /// <summary>
  76. /// Gets the media info.
  77. /// </summary>
  78. /// <param name="item">The item.</param>
  79. /// <param name="isoMount">The iso mount.</param>
  80. /// <param name="cancellationToken">The cancellation token.</param>
  81. /// <returns>Task{MediaInfoResult}.</returns>
  82. /// <exception cref="System.ArgumentNullException">inputPath
  83. /// or
  84. /// cache</exception>
  85. private async Task<MediaInfoResult> GetMediaInfo(BaseItem item, IIsoMount isoMount, CancellationToken cancellationToken)
  86. {
  87. cancellationToken.ThrowIfCancellationRequested();
  88. var type = InputType.AudioFile;
  89. var inputPath = isoMount == null ? new[] { item.Path } : new[] { isoMount.MountedPath };
  90. var video = item as Video;
  91. if (video != null)
  92. {
  93. inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  94. }
  95. return await MediaEncoder.GetMediaInfo(inputPath, type, cancellationToken).ConfigureAwait(false);
  96. }
  97. /// <summary>
  98. /// Mounts the iso if needed.
  99. /// </summary>
  100. /// <param name="item">The item.</param>
  101. /// <param name="cancellationToken">The cancellation token.</param>
  102. /// <returns>IsoMount.</returns>
  103. protected virtual Task<IIsoMount> MountIsoIfNeeded(T item, CancellationToken cancellationToken)
  104. {
  105. return NullMountTaskResult;
  106. }
  107. /// <summary>
  108. /// Called when [pre fetch].
  109. /// </summary>
  110. /// <param name="item">The item.</param>
  111. /// <param name="mount">The mount.</param>
  112. protected virtual void OnPreFetch(T item, IIsoMount mount)
  113. {
  114. }
  115. /// <summary>
  116. /// Normalizes the FF probe result.
  117. /// </summary>
  118. /// <param name="result">The result.</param>
  119. private void NormalizeFFProbeResult(MediaInfoResult result)
  120. {
  121. if (result.format != null && result.format.tags != null)
  122. {
  123. result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
  124. }
  125. if (result.streams != null)
  126. {
  127. // Convert all dictionaries to case insensitive
  128. foreach (var stream in result.streams)
  129. {
  130. if (stream.tags != null)
  131. {
  132. stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
  133. }
  134. if (stream.disposition != null)
  135. {
  136. stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
  137. }
  138. }
  139. }
  140. }
  141. /// <summary>
  142. /// Subclasses must set item values using this
  143. /// </summary>
  144. /// <param name="item">The item.</param>
  145. /// <param name="cancellationToken">The cancellation token.</param>
  146. /// <param name="result">The result.</param>
  147. /// <param name="isoMount">The iso mount.</param>
  148. /// <returns>Task.</returns>
  149. protected abstract void Fetch(T item, CancellationToken cancellationToken, MediaInfoResult result, IIsoMount isoMount);
  150. /// <summary>
  151. /// Converts ffprobe stream info to our MediaStream class
  152. /// </summary>
  153. /// <param name="streamInfo">The stream info.</param>
  154. /// <param name="formatInfo">The format info.</param>
  155. /// <returns>MediaStream.</returns>
  156. protected MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  157. {
  158. var stream = new MediaStream
  159. {
  160. Codec = streamInfo.codec_name,
  161. Language = GetDictionaryValue(streamInfo.tags, "language"),
  162. Profile = streamInfo.profile,
  163. Level = streamInfo.level,
  164. Index = streamInfo.index
  165. };
  166. if (streamInfo.codec_type.Equals("audio", StringComparison.OrdinalIgnoreCase))
  167. {
  168. stream.Type = MediaStreamType.Audio;
  169. stream.Channels = streamInfo.channels;
  170. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  171. {
  172. stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture);
  173. }
  174. }
  175. else if (streamInfo.codec_type.Equals("subtitle", StringComparison.OrdinalIgnoreCase))
  176. {
  177. stream.Type = MediaStreamType.Subtitle;
  178. }
  179. else if (streamInfo.codec_type.Equals("video", StringComparison.OrdinalIgnoreCase))
  180. {
  181. stream.Type = MediaStreamType.Video;
  182. stream.Width = streamInfo.width;
  183. stream.Height = streamInfo.height;
  184. stream.PixelFormat = streamInfo.pix_fmt;
  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. else
  190. {
  191. return null;
  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, UsCulture);
  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, UsCulture);
  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], UsCulture) / float.Parse(parts[1], UsCulture);
  230. }
  231. else
  232. {
  233. result = float.Parse(parts[0], UsCulture);
  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. }
  303. }