BaseFFProbeProvider.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. // Give this second priority
  38. // Give metadata xml providers a chance to fill in data first, so that we can skip this whenever possible
  39. get { return MetadataProviderPriority.Second; }
  40. }
  41. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  42. /// <summary>
  43. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  44. /// </summary>
  45. /// <param name="item">The item.</param>
  46. /// <param name="force">if set to <c>true</c> [force].</param>
  47. /// <param name="cancellationToken">The cancellation token.</param>
  48. /// <returns>Task{System.Boolean}.</returns>
  49. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  50. {
  51. var myItem = (T)item;
  52. var isoMount = await MountIsoIfNeeded(myItem, cancellationToken).ConfigureAwait(false);
  53. try
  54. {
  55. OnPreFetch(myItem, isoMount);
  56. var result = await GetMediaInfo(item, isoMount, cancellationToken).ConfigureAwait(false);
  57. cancellationToken.ThrowIfCancellationRequested();
  58. NormalizeFFProbeResult(result);
  59. cancellationToken.ThrowIfCancellationRequested();
  60. Fetch(myItem, cancellationToken, result, isoMount);
  61. var video = myItem as Video;
  62. if (video != null)
  63. {
  64. await Kernel.Instance.FFMpegManager.PopulateChapterImages(video, cancellationToken, false, false).ConfigureAwait(false);
  65. }
  66. SetLastRefreshed(item, DateTime.UtcNow);
  67. }
  68. finally
  69. {
  70. if (isoMount != null)
  71. {
  72. isoMount.Dispose();
  73. }
  74. }
  75. return true;
  76. }
  77. /// <summary>
  78. /// Gets the media info.
  79. /// </summary>
  80. /// <param name="item">The item.</param>
  81. /// <param name="isoMount">The iso mount.</param>
  82. /// <param name="cancellationToken">The cancellation token.</param>
  83. /// <returns>Task{MediaInfoResult}.</returns>
  84. /// <exception cref="System.ArgumentNullException">inputPath
  85. /// or
  86. /// cache</exception>
  87. private async Task<MediaInfoResult> GetMediaInfo(BaseItem item, IIsoMount isoMount, CancellationToken cancellationToken)
  88. {
  89. cancellationToken.ThrowIfCancellationRequested();
  90. var type = InputType.AudioFile;
  91. var inputPath = isoMount == null ? new[] { item.Path } : new[] { isoMount.MountedPath };
  92. var video = item as Video;
  93. if (video != null)
  94. {
  95. inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  96. }
  97. return await MediaEncoder.GetMediaInfo(inputPath, type, cancellationToken).ConfigureAwait(false);
  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(MediaInfoResult 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 void Fetch(T item, CancellationToken cancellationToken, MediaInfoResult 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(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  159. {
  160. var stream = new MediaStream
  161. {
  162. Codec = streamInfo.codec_name,
  163. Language = GetDictionaryValue(streamInfo.tags, "language"),
  164. Profile = streamInfo.profile,
  165. Level = streamInfo.level,
  166. Index = streamInfo.index
  167. };
  168. if (streamInfo.codec_type.Equals("audio", StringComparison.OrdinalIgnoreCase))
  169. {
  170. stream.Type = MediaStreamType.Audio;
  171. stream.Channels = streamInfo.channels;
  172. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  173. {
  174. stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture);
  175. }
  176. }
  177. else if (streamInfo.codec_type.Equals("subtitle", StringComparison.OrdinalIgnoreCase))
  178. {
  179. stream.Type = MediaStreamType.Subtitle;
  180. }
  181. else if (streamInfo.codec_type.Equals("video", StringComparison.OrdinalIgnoreCase))
  182. {
  183. stream.Type = MediaStreamType.Video;
  184. stream.Width = streamInfo.width;
  185. stream.Height = streamInfo.height;
  186. stream.PixelFormat = streamInfo.pix_fmt;
  187. stream.AspectRatio = streamInfo.display_aspect_ratio;
  188. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  189. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  190. }
  191. else
  192. {
  193. return null;
  194. }
  195. // Get stream bitrate
  196. if (stream.Type != MediaStreamType.Subtitle)
  197. {
  198. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  199. {
  200. stream.BitRate = int.Parse(streamInfo.bit_rate, UsCulture);
  201. }
  202. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate))
  203. {
  204. // If the stream info doesn't have a bitrate get the value from the media format info
  205. stream.BitRate = int.Parse(formatInfo.bit_rate, UsCulture);
  206. }
  207. }
  208. if (streamInfo.disposition != null)
  209. {
  210. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  211. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  212. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  213. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  214. }
  215. return stream;
  216. }
  217. /// <summary>
  218. /// Gets a frame rate from a string value in ffprobe output
  219. /// This could be a number or in the format of 2997/125.
  220. /// </summary>
  221. /// <param name="value">The value.</param>
  222. /// <returns>System.Nullable{System.Single}.</returns>
  223. private float? GetFrameRate(string value)
  224. {
  225. if (!string.IsNullOrEmpty(value))
  226. {
  227. var parts = value.Split('/');
  228. float result;
  229. if (parts.Length == 2)
  230. {
  231. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  232. }
  233. else
  234. {
  235. result = float.Parse(parts[0], UsCulture);
  236. }
  237. return float.IsNaN(result) ? (float?)null : result;
  238. }
  239. return null;
  240. }
  241. /// <summary>
  242. /// Gets a string from an FFProbeResult tags dictionary
  243. /// </summary>
  244. /// <param name="tags">The tags.</param>
  245. /// <param name="key">The key.</param>
  246. /// <returns>System.String.</returns>
  247. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  248. {
  249. if (tags == null)
  250. {
  251. return null;
  252. }
  253. string val;
  254. tags.TryGetValue(key, out val);
  255. return val;
  256. }
  257. /// <summary>
  258. /// Gets an int from an FFProbeResult tags dictionary
  259. /// </summary>
  260. /// <param name="tags">The tags.</param>
  261. /// <param name="key">The key.</param>
  262. /// <returns>System.Nullable{System.Int32}.</returns>
  263. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  264. {
  265. var val = GetDictionaryValue(tags, key);
  266. if (!string.IsNullOrEmpty(val))
  267. {
  268. int i;
  269. if (int.TryParse(val, out i))
  270. {
  271. return i;
  272. }
  273. }
  274. return null;
  275. }
  276. /// <summary>
  277. /// Gets a DateTime from an FFProbeResult tags dictionary
  278. /// </summary>
  279. /// <param name="tags">The tags.</param>
  280. /// <param name="key">The key.</param>
  281. /// <returns>System.Nullable{DateTime}.</returns>
  282. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  283. {
  284. var val = GetDictionaryValue(tags, key);
  285. if (!string.IsNullOrEmpty(val))
  286. {
  287. DateTime i;
  288. if (DateTime.TryParse(val, out i))
  289. {
  290. return i.ToUniversalTime();
  291. }
  292. }
  293. return null;
  294. }
  295. /// <summary>
  296. /// Converts a dictionary to case insensitive
  297. /// </summary>
  298. /// <param name="dict">The dict.</param>
  299. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  300. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  301. {
  302. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  303. }
  304. }
  305. }