BaseFFProbeProvider.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 Kernel.Instance.FFMpegManager.PopulateChapterImages(video, cancellationToken, false, false).ConfigureAwait(false);
  62. }
  63. SetLastRefreshed(item, DateTime.UtcNow);
  64. }
  65. finally
  66. {
  67. if (isoMount != null)
  68. {
  69. isoMount.Dispose();
  70. }
  71. }
  72. return true;
  73. }
  74. /// <summary>
  75. /// Gets the media info.
  76. /// </summary>
  77. /// <param name="item">The item.</param>
  78. /// <param name="isoMount">The iso mount.</param>
  79. /// <param name="cancellationToken">The cancellation token.</param>
  80. /// <returns>Task{MediaInfoResult}.</returns>
  81. /// <exception cref="System.ArgumentNullException">inputPath
  82. /// or
  83. /// cache</exception>
  84. private async Task<MediaInfoResult> GetMediaInfo(BaseItem item, IIsoMount isoMount, CancellationToken cancellationToken)
  85. {
  86. cancellationToken.ThrowIfCancellationRequested();
  87. var type = InputType.AudioFile;
  88. var inputPath = isoMount == null ? new[] { item.Path } : new[] { isoMount.MountedPath };
  89. var video = item as Video;
  90. if (video != null)
  91. {
  92. inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  93. }
  94. return await MediaEncoder.GetMediaInfo(inputPath, type, cancellationToken).ConfigureAwait(false);
  95. }
  96. /// <summary>
  97. /// Mounts the iso if needed.
  98. /// </summary>
  99. /// <param name="item">The item.</param>
  100. /// <param name="cancellationToken">The cancellation token.</param>
  101. /// <returns>IsoMount.</returns>
  102. protected virtual Task<IIsoMount> MountIsoIfNeeded(T item, CancellationToken cancellationToken)
  103. {
  104. return NullMountTaskResult;
  105. }
  106. /// <summary>
  107. /// Called when [pre fetch].
  108. /// </summary>
  109. /// <param name="item">The item.</param>
  110. /// <param name="mount">The mount.</param>
  111. protected virtual void OnPreFetch(T item, IIsoMount mount)
  112. {
  113. }
  114. /// <summary>
  115. /// Normalizes the FF probe result.
  116. /// </summary>
  117. /// <param name="result">The result.</param>
  118. private void NormalizeFFProbeResult(MediaInfoResult result)
  119. {
  120. if (result.format != null && result.format.tags != null)
  121. {
  122. result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
  123. }
  124. if (result.streams != null)
  125. {
  126. // Convert all dictionaries to case insensitive
  127. foreach (var stream in result.streams)
  128. {
  129. if (stream.tags != null)
  130. {
  131. stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
  132. }
  133. if (stream.disposition != null)
  134. {
  135. stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
  136. }
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Subclasses must set item values using this
  142. /// </summary>
  143. /// <param name="item">The item.</param>
  144. /// <param name="cancellationToken">The cancellation token.</param>
  145. /// <param name="result">The result.</param>
  146. /// <param name="isoMount">The iso mount.</param>
  147. /// <returns>Task.</returns>
  148. protected abstract void Fetch(T item, CancellationToken cancellationToken, MediaInfoResult result, IIsoMount isoMount);
  149. /// <summary>
  150. /// Converts ffprobe stream info to our MediaStream class
  151. /// </summary>
  152. /// <param name="streamInfo">The stream info.</param>
  153. /// <param name="formatInfo">The format info.</param>
  154. /// <returns>MediaStream.</returns>
  155. protected MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  156. {
  157. var stream = new MediaStream
  158. {
  159. Codec = streamInfo.codec_name,
  160. Language = GetDictionaryValue(streamInfo.tags, "language"),
  161. Profile = streamInfo.profile,
  162. Level = streamInfo.level,
  163. Index = streamInfo.index
  164. };
  165. if (streamInfo.codec_type.Equals("audio", StringComparison.OrdinalIgnoreCase))
  166. {
  167. stream.Type = MediaStreamType.Audio;
  168. stream.Channels = streamInfo.channels;
  169. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  170. {
  171. stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture);
  172. }
  173. }
  174. else if (streamInfo.codec_type.Equals("subtitle", StringComparison.OrdinalIgnoreCase))
  175. {
  176. stream.Type = MediaStreamType.Subtitle;
  177. }
  178. else if (streamInfo.codec_type.Equals("video", StringComparison.OrdinalIgnoreCase))
  179. {
  180. stream.Type = MediaStreamType.Video;
  181. stream.Width = streamInfo.width;
  182. stream.Height = streamInfo.height;
  183. stream.PixelFormat = streamInfo.pix_fmt;
  184. stream.AspectRatio = streamInfo.display_aspect_ratio;
  185. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  186. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  187. }
  188. else
  189. {
  190. return null;
  191. }
  192. // Get stream bitrate
  193. if (stream.Type != MediaStreamType.Subtitle)
  194. {
  195. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  196. {
  197. stream.BitRate = int.Parse(streamInfo.bit_rate, UsCulture);
  198. }
  199. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate))
  200. {
  201. // If the stream info doesn't have a bitrate get the value from the media format info
  202. stream.BitRate = int.Parse(formatInfo.bit_rate, UsCulture);
  203. }
  204. }
  205. if (streamInfo.disposition != null)
  206. {
  207. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  208. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  209. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  210. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  211. }
  212. return stream;
  213. }
  214. /// <summary>
  215. /// Gets a frame rate from a string value in ffprobe output
  216. /// This could be a number or in the format of 2997/125.
  217. /// </summary>
  218. /// <param name="value">The value.</param>
  219. /// <returns>System.Nullable{System.Single}.</returns>
  220. private float? GetFrameRate(string value)
  221. {
  222. if (!string.IsNullOrEmpty(value))
  223. {
  224. var parts = value.Split('/');
  225. float result;
  226. if (parts.Length == 2)
  227. {
  228. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  229. }
  230. else
  231. {
  232. result = float.Parse(parts[0], UsCulture);
  233. }
  234. return float.IsNaN(result) ? (float?)null : result;
  235. }
  236. return null;
  237. }
  238. /// <summary>
  239. /// Gets a string from an FFProbeResult tags dictionary
  240. /// </summary>
  241. /// <param name="tags">The tags.</param>
  242. /// <param name="key">The key.</param>
  243. /// <returns>System.String.</returns>
  244. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  245. {
  246. if (tags == null)
  247. {
  248. return null;
  249. }
  250. string val;
  251. tags.TryGetValue(key, out val);
  252. return val;
  253. }
  254. /// <summary>
  255. /// Gets an int from an FFProbeResult tags dictionary
  256. /// </summary>
  257. /// <param name="tags">The tags.</param>
  258. /// <param name="key">The key.</param>
  259. /// <returns>System.Nullable{System.Int32}.</returns>
  260. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  261. {
  262. var val = GetDictionaryValue(tags, key);
  263. if (!string.IsNullOrEmpty(val))
  264. {
  265. int i;
  266. if (int.TryParse(val, out i))
  267. {
  268. return i;
  269. }
  270. }
  271. return null;
  272. }
  273. /// <summary>
  274. /// Gets a DateTime from an FFProbeResult tags dictionary
  275. /// </summary>
  276. /// <param name="tags">The tags.</param>
  277. /// <param name="key">The key.</param>
  278. /// <returns>System.Nullable{DateTime}.</returns>
  279. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  280. {
  281. var val = GetDictionaryValue(tags, key);
  282. if (!string.IsNullOrEmpty(val))
  283. {
  284. DateTime i;
  285. if (DateTime.TryParse(val, out i))
  286. {
  287. return i.ToUniversalTime();
  288. }
  289. }
  290. return null;
  291. }
  292. /// <summary>
  293. /// Converts a dictionary to case insensitive
  294. /// </summary>
  295. /// <param name="dict">The dict.</param>
  296. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  297. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  298. {
  299. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  300. }
  301. }
  302. }