BaseFFProbeProvider.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  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>
  20. where T : BaseItem
  21. {
  22. protected BaseFFProbeProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder, IJsonSerializer jsonSerializer)
  23. : base(logManager, configurationManager, mediaEncoder)
  24. {
  25. JsonSerializer = jsonSerializer;
  26. }
  27. protected readonly IJsonSerializer JsonSerializer;
  28. /// <summary>
  29. /// Gets the priority.
  30. /// </summary>
  31. /// <value>The priority.</value>
  32. public override MetadataProviderPriority Priority
  33. {
  34. // Give this second priority
  35. // Give metadata xml providers a chance to fill in data first, so that we can skip this whenever possible
  36. get { return MetadataProviderPriority.Second; }
  37. }
  38. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  39. /// <summary>
  40. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  41. /// </summary>
  42. /// <param name="item">The item.</param>
  43. /// <param name="force">if set to <c>true</c> [force].</param>
  44. /// <param name="cancellationToken">The cancellation token.</param>
  45. /// <returns>Task{System.Boolean}.</returns>
  46. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  47. {
  48. var myItem = (T)item;
  49. var isoMount = await MountIsoIfNeeded(myItem, cancellationToken).ConfigureAwait(false);
  50. try
  51. {
  52. OnPreFetch(myItem, isoMount);
  53. var result = await GetMediaInfo(item, isoMount, cancellationToken).ConfigureAwait(false);
  54. cancellationToken.ThrowIfCancellationRequested();
  55. NormalizeFFProbeResult(result);
  56. cancellationToken.ThrowIfCancellationRequested();
  57. Fetch(myItem, cancellationToken, result, isoMount);
  58. var video = myItem as Video;
  59. if (video != null)
  60. {
  61. await
  62. Kernel.Instance.FFMpegManager.PopulateChapterImages(video, cancellationToken, false, false)
  63. .ConfigureAwait(false);
  64. }
  65. SetLastRefreshed(item, DateTime.UtcNow);
  66. }
  67. finally
  68. {
  69. if (isoMount != null)
  70. {
  71. isoMount.Dispose();
  72. }
  73. }
  74. return true;
  75. }
  76. /// <summary>
  77. /// Gets the media info.
  78. /// </summary>
  79. /// <param name="item">The item.</param>
  80. /// <param name="isoMount">The iso mount.</param>
  81. /// <param name="cancellationToken">The cancellation token.</param>
  82. /// <returns>Task{MediaInfoResult}.</returns>
  83. /// <exception cref="System.ArgumentNullException">inputPath
  84. /// or
  85. /// cache</exception>
  86. private async Task<MediaInfoResult> GetMediaInfo(BaseItem item, IIsoMount isoMount, CancellationToken cancellationToken)
  87. {
  88. cancellationToken.ThrowIfCancellationRequested();
  89. var type = InputType.AudioFile;
  90. var inputPath = isoMount == null ? new[] { item.Path } : new[] { isoMount.MountedPath };
  91. var video = item as Video;
  92. if (video != null)
  93. {
  94. inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  95. }
  96. return await MediaEncoder.GetMediaInfo(inputPath, type, cancellationToken).ConfigureAwait(false);
  97. }
  98. /// <summary>
  99. /// Mounts the iso if needed.
  100. /// </summary>
  101. /// <param name="item">The item.</param>
  102. /// <param name="cancellationToken">The cancellation token.</param>
  103. /// <returns>IsoMount.</returns>
  104. protected virtual Task<IIsoMount> MountIsoIfNeeded(T item, CancellationToken cancellationToken)
  105. {
  106. return NullMountTaskResult;
  107. }
  108. /// <summary>
  109. /// Called when [pre fetch].
  110. /// </summary>
  111. /// <param name="item">The item.</param>
  112. /// <param name="mount">The mount.</param>
  113. protected virtual void OnPreFetch(T item, IIsoMount mount)
  114. {
  115. }
  116. /// <summary>
  117. /// Normalizes the FF probe result.
  118. /// </summary>
  119. /// <param name="result">The result.</param>
  120. private void NormalizeFFProbeResult(MediaInfoResult result)
  121. {
  122. if (result.format != null && result.format.tags != null)
  123. {
  124. result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
  125. }
  126. if (result.streams != null)
  127. {
  128. // Convert all dictionaries to case insensitive
  129. foreach (var stream in result.streams)
  130. {
  131. if (stream.tags != null)
  132. {
  133. stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
  134. }
  135. if (stream.disposition != null)
  136. {
  137. stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
  138. }
  139. }
  140. }
  141. }
  142. /// <summary>
  143. /// Subclasses must set item values using this
  144. /// </summary>
  145. /// <param name="item">The item.</param>
  146. /// <param name="cancellationToken">The cancellation token.</param>
  147. /// <param name="result">The result.</param>
  148. /// <param name="isoMount">The iso mount.</param>
  149. /// <returns>Task.</returns>
  150. protected abstract void Fetch(T item, CancellationToken cancellationToken, MediaInfoResult result, IIsoMount isoMount);
  151. /// <summary>
  152. /// Converts ffprobe stream info to our MediaStream class
  153. /// </summary>
  154. /// <param name="streamInfo">The stream info.</param>
  155. /// <param name="formatInfo">The format info.</param>
  156. /// <returns>MediaStream.</returns>
  157. protected MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  158. {
  159. var stream = new MediaStream
  160. {
  161. Codec = streamInfo.codec_name,
  162. Language = GetDictionaryValue(streamInfo.tags, "language"),
  163. Profile = streamInfo.profile,
  164. Level = streamInfo.level,
  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, UsCulture);
  174. }
  175. }
  176. else if (streamInfo.codec_type.Equals("subtitle", StringComparison.OrdinalIgnoreCase))
  177. {
  178. stream.Type = MediaStreamType.Subtitle;
  179. }
  180. else if (streamInfo.codec_type.Equals("video", StringComparison.OrdinalIgnoreCase))
  181. {
  182. stream.Type = MediaStreamType.Video;
  183. stream.Width = streamInfo.width;
  184. stream.Height = streamInfo.height;
  185. stream.PixelFormat = streamInfo.pix_fmt;
  186. stream.AspectRatio = streamInfo.display_aspect_ratio;
  187. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  188. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  189. }
  190. else
  191. {
  192. return null;
  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, UsCulture);
  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, UsCulture);
  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], UsCulture) / float.Parse(parts[1], UsCulture);
  231. }
  232. else
  233. {
  234. result = float.Parse(parts[0], UsCulture);
  235. }
  236. return float.IsNaN(result) ? (float?)null : result;
  237. }
  238. return null;
  239. }
  240. /// <summary>
  241. /// Gets a string from an FFProbeResult tags dictionary
  242. /// </summary>
  243. /// <param name="tags">The tags.</param>
  244. /// <param name="key">The key.</param>
  245. /// <returns>System.String.</returns>
  246. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  247. {
  248. if (tags == null)
  249. {
  250. return null;
  251. }
  252. string val;
  253. tags.TryGetValue(key, out val);
  254. return val;
  255. }
  256. /// <summary>
  257. /// Gets an int from an FFProbeResult tags dictionary
  258. /// </summary>
  259. /// <param name="tags">The tags.</param>
  260. /// <param name="key">The key.</param>
  261. /// <returns>System.Nullable{System.Int32}.</returns>
  262. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  263. {
  264. var val = GetDictionaryValue(tags, key);
  265. if (!string.IsNullOrEmpty(val))
  266. {
  267. int i;
  268. if (int.TryParse(val, out i))
  269. {
  270. return i;
  271. }
  272. }
  273. return null;
  274. }
  275. /// <summary>
  276. /// Gets a DateTime from an FFProbeResult tags dictionary
  277. /// </summary>
  278. /// <param name="tags">The tags.</param>
  279. /// <param name="key">The key.</param>
  280. /// <returns>System.Nullable{DateTime}.</returns>
  281. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  282. {
  283. var val = GetDictionaryValue(tags, key);
  284. if (!string.IsNullOrEmpty(val))
  285. {
  286. DateTime i;
  287. if (DateTime.TryParse(val, out i))
  288. {
  289. return i.ToUniversalTime();
  290. }
  291. }
  292. return null;
  293. }
  294. /// <summary>
  295. /// Converts a dictionary to case insensitive
  296. /// </summary>
  297. /// <param name="dict">The dict.</param>
  298. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  299. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  300. {
  301. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  302. }
  303. }
  304. }