BaseFFProbeProvider.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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.IO;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Controller.Providers.MediaInfo
  15. {
  16. /// <summary>
  17. /// Provides a base class for extracting media information through ffprobe
  18. /// </summary>
  19. /// <typeparam name="T"></typeparam>
  20. public abstract class BaseFFProbeProvider<T> : BaseFFMpegProvider<T>
  21. where T : BaseItem
  22. {
  23. protected BaseFFProbeProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder, IJsonSerializer jsonSerializer)
  24. : base(logManager, configurationManager, mediaEncoder)
  25. {
  26. JsonSerializer = jsonSerializer;
  27. }
  28. protected readonly IJsonSerializer JsonSerializer;
  29. /// <summary>
  30. /// Gets or sets the FF probe cache.
  31. /// </summary>
  32. /// <value>The FF probe cache.</value>
  33. protected FileSystemRepository FFProbeCache { get; set; }
  34. /// <summary>
  35. /// Initializes this instance.
  36. /// </summary>
  37. protected override void Initialize()
  38. {
  39. base.Initialize();
  40. FFProbeCache = new FileSystemRepository(Path.Combine(ConfigurationManager.ApplicationPaths.CachePath, CacheDirectoryName));
  41. }
  42. /// <summary>
  43. /// Gets the name of the cache directory.
  44. /// </summary>
  45. /// <value>The name of the cache directory.</value>
  46. protected virtual string CacheDirectoryName
  47. {
  48. get
  49. {
  50. return "ffmpeg-video-info";
  51. }
  52. }
  53. /// <summary>
  54. /// Gets the priority.
  55. /// </summary>
  56. /// <value>The priority.</value>
  57. public override MetadataProviderPriority Priority
  58. {
  59. // Give this second priority
  60. // Give metadata xml providers a chance to fill in data first, so that we can skip this whenever possible
  61. get { return MetadataProviderPriority.Second; }
  62. }
  63. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  64. /// <summary>
  65. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  66. /// </summary>
  67. /// <param name="item">The item.</param>
  68. /// <param name="force">if set to <c>true</c> [force].</param>
  69. /// <param name="cancellationToken">The cancellation token.</param>
  70. /// <returns>Task{System.Boolean}.</returns>
  71. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  72. {
  73. var myItem = (T)item;
  74. var isoMount = await MountIsoIfNeeded(myItem, cancellationToken).ConfigureAwait(false);
  75. try
  76. {
  77. OnPreFetch(myItem, isoMount);
  78. var result = await GetMediaInfo(item, isoMount, item.DateModified, FFProbeCache, cancellationToken).ConfigureAwait(false);
  79. cancellationToken.ThrowIfCancellationRequested();
  80. NormalizeFFProbeResult(result);
  81. cancellationToken.ThrowIfCancellationRequested();
  82. Fetch(myItem, cancellationToken, result, isoMount);
  83. var video = myItem as Video;
  84. if (video != null)
  85. {
  86. await
  87. Kernel.Instance.FFMpegManager.PopulateChapterImages(video, cancellationToken, false, false)
  88. .ConfigureAwait(false);
  89. }
  90. SetLastRefreshed(item, DateTime.UtcNow);
  91. }
  92. finally
  93. {
  94. if (isoMount != null)
  95. {
  96. isoMount.Dispose();
  97. }
  98. }
  99. return true;
  100. }
  101. /// <summary>
  102. /// Gets the media info.
  103. /// </summary>
  104. /// <param name="item">The item.</param>
  105. /// <param name="isoMount">The iso mount.</param>
  106. /// <param name="lastDateModified">The last date modified.</param>
  107. /// <param name="cache">The cache.</param>
  108. /// <param name="cancellationToken">The cancellation token.</param>
  109. /// <returns>Task{MediaInfoResult}.</returns>
  110. /// <exception cref="System.ArgumentNullException">inputPath
  111. /// or
  112. /// cache</exception>
  113. private async Task<MediaInfoResult> GetMediaInfo(BaseItem item, IIsoMount isoMount, DateTime lastDateModified, FileSystemRepository cache, CancellationToken cancellationToken)
  114. {
  115. if (cache == null)
  116. {
  117. throw new ArgumentNullException("cache");
  118. }
  119. // Put the ffmpeg version into the cache name so that it's unique per-version
  120. // We don't want to try and deserialize data based on an old version, which could potentially fail
  121. var resourceName = item.Id + "_" + lastDateModified.Ticks + "_" + MediaEncoder.Version;
  122. // Forumulate the cache file path
  123. var cacheFilePath = cache.GetResourcePath(resourceName, ".js");
  124. cancellationToken.ThrowIfCancellationRequested();
  125. // Avoid File.Exists by just trying to deserialize
  126. try
  127. {
  128. return JsonSerializer.DeserializeFromFile<MediaInfoResult>(cacheFilePath);
  129. }
  130. catch (FileNotFoundException)
  131. {
  132. // Cache file doesn't exist
  133. }
  134. var type = InputType.AudioFile;
  135. var inputPath = isoMount == null ? new[] { item.Path } : new[] { isoMount.MountedPath };
  136. var video = item as Video;
  137. if (video != null)
  138. {
  139. inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  140. }
  141. var info = await MediaEncoder.GetMediaInfo(inputPath, type, cancellationToken).ConfigureAwait(false);
  142. JsonSerializer.SerializeToFile(info, cacheFilePath);
  143. return info;
  144. }
  145. /// <summary>
  146. /// Gets a value indicating whether [refresh on version change].
  147. /// </summary>
  148. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  149. protected override bool RefreshOnVersionChange
  150. {
  151. get
  152. {
  153. return true;
  154. }
  155. }
  156. /// <summary>
  157. /// Mounts the iso if needed.
  158. /// </summary>
  159. /// <param name="item">The item.</param>
  160. /// <param name="cancellationToken">The cancellation token.</param>
  161. /// <returns>IsoMount.</returns>
  162. protected virtual Task<IIsoMount> MountIsoIfNeeded(T item, CancellationToken cancellationToken)
  163. {
  164. return NullMountTaskResult;
  165. }
  166. /// <summary>
  167. /// Called when [pre fetch].
  168. /// </summary>
  169. /// <param name="item">The item.</param>
  170. /// <param name="mount">The mount.</param>
  171. protected virtual void OnPreFetch(T item, IIsoMount mount)
  172. {
  173. }
  174. /// <summary>
  175. /// Normalizes the FF probe result.
  176. /// </summary>
  177. /// <param name="result">The result.</param>
  178. private void NormalizeFFProbeResult(MediaInfoResult result)
  179. {
  180. if (result.format != null && result.format.tags != null)
  181. {
  182. result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
  183. }
  184. if (result.streams != null)
  185. {
  186. // Convert all dictionaries to case insensitive
  187. foreach (var stream in result.streams)
  188. {
  189. if (stream.tags != null)
  190. {
  191. stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
  192. }
  193. if (stream.disposition != null)
  194. {
  195. stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
  196. }
  197. }
  198. }
  199. }
  200. /// <summary>
  201. /// Subclasses must set item values using this
  202. /// </summary>
  203. /// <param name="item">The item.</param>
  204. /// <param name="cancellationToken">The cancellation token.</param>
  205. /// <param name="result">The result.</param>
  206. /// <param name="isoMount">The iso mount.</param>
  207. /// <returns>Task.</returns>
  208. protected abstract void Fetch(T item, CancellationToken cancellationToken, MediaInfoResult result, IIsoMount isoMount);
  209. /// <summary>
  210. /// Converts ffprobe stream info to our MediaStream class
  211. /// </summary>
  212. /// <param name="streamInfo">The stream info.</param>
  213. /// <param name="formatInfo">The format info.</param>
  214. /// <returns>MediaStream.</returns>
  215. protected MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  216. {
  217. var stream = new MediaStream
  218. {
  219. Codec = streamInfo.codec_name,
  220. Language = GetDictionaryValue(streamInfo.tags, "language"),
  221. Profile = streamInfo.profile,
  222. Level = streamInfo.level,
  223. Index = streamInfo.index
  224. };
  225. if (streamInfo.codec_type.Equals("audio", StringComparison.OrdinalIgnoreCase))
  226. {
  227. stream.Type = MediaStreamType.Audio;
  228. stream.Channels = streamInfo.channels;
  229. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  230. {
  231. stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture);
  232. }
  233. }
  234. else if (streamInfo.codec_type.Equals("subtitle", StringComparison.OrdinalIgnoreCase))
  235. {
  236. stream.Type = MediaStreamType.Subtitle;
  237. }
  238. else if (streamInfo.codec_type.Equals("data", StringComparison.OrdinalIgnoreCase))
  239. {
  240. stream.Type = MediaStreamType.Data;
  241. }
  242. else
  243. {
  244. stream.Type = MediaStreamType.Video;
  245. stream.Width = streamInfo.width;
  246. stream.Height = streamInfo.height;
  247. stream.PixelFormat = streamInfo.pix_fmt;
  248. stream.AspectRatio = streamInfo.display_aspect_ratio;
  249. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  250. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  251. }
  252. // Get stream bitrate
  253. if (stream.Type != MediaStreamType.Subtitle)
  254. {
  255. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  256. {
  257. stream.BitRate = int.Parse(streamInfo.bit_rate, UsCulture);
  258. }
  259. else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate))
  260. {
  261. // If the stream info doesn't have a bitrate get the value from the media format info
  262. stream.BitRate = int.Parse(formatInfo.bit_rate, UsCulture);
  263. }
  264. }
  265. if (streamInfo.disposition != null)
  266. {
  267. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  268. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  269. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  270. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  271. }
  272. return stream;
  273. }
  274. /// <summary>
  275. /// Gets a frame rate from a string value in ffprobe output
  276. /// This could be a number or in the format of 2997/125.
  277. /// </summary>
  278. /// <param name="value">The value.</param>
  279. /// <returns>System.Nullable{System.Single}.</returns>
  280. private float? GetFrameRate(string value)
  281. {
  282. if (!string.IsNullOrEmpty(value))
  283. {
  284. var parts = value.Split('/');
  285. float result;
  286. if (parts.Length == 2)
  287. {
  288. result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture);
  289. }
  290. else
  291. {
  292. result = float.Parse(parts[0], UsCulture);
  293. }
  294. return float.IsNaN(result) ? (float?)null : result;
  295. }
  296. return null;
  297. }
  298. /// <summary>
  299. /// Gets a string from an FFProbeResult tags dictionary
  300. /// </summary>
  301. /// <param name="tags">The tags.</param>
  302. /// <param name="key">The key.</param>
  303. /// <returns>System.String.</returns>
  304. protected string GetDictionaryValue(Dictionary<string, string> tags, string key)
  305. {
  306. if (tags == null)
  307. {
  308. return null;
  309. }
  310. string val;
  311. tags.TryGetValue(key, out val);
  312. return val;
  313. }
  314. /// <summary>
  315. /// Gets an int from an FFProbeResult tags dictionary
  316. /// </summary>
  317. /// <param name="tags">The tags.</param>
  318. /// <param name="key">The key.</param>
  319. /// <returns>System.Nullable{System.Int32}.</returns>
  320. protected int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
  321. {
  322. var val = GetDictionaryValue(tags, key);
  323. if (!string.IsNullOrEmpty(val))
  324. {
  325. int i;
  326. if (int.TryParse(val, out i))
  327. {
  328. return i;
  329. }
  330. }
  331. return null;
  332. }
  333. /// <summary>
  334. /// Gets a DateTime from an FFProbeResult tags dictionary
  335. /// </summary>
  336. /// <param name="tags">The tags.</param>
  337. /// <param name="key">The key.</param>
  338. /// <returns>System.Nullable{DateTime}.</returns>
  339. protected DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
  340. {
  341. var val = GetDictionaryValue(tags, key);
  342. if (!string.IsNullOrEmpty(val))
  343. {
  344. DateTime i;
  345. if (DateTime.TryParse(val, out i))
  346. {
  347. return i.ToUniversalTime();
  348. }
  349. }
  350. return null;
  351. }
  352. /// <summary>
  353. /// Converts a dictionary to case insensitive
  354. /// </summary>
  355. /// <param name="dict">The dict.</param>
  356. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  357. private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
  358. {
  359. return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
  360. }
  361. }
  362. }