VideoImageProvider.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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.Library;
  7. using MediaBrowser.Controller.MediaInfo;
  8. using MediaBrowser.Controller.Providers;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.IO;
  11. using MediaBrowser.Model.Logging;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Providers.MediaInfo
  19. {
  20. class VideoImageProvider : BaseMetadataProvider
  21. {
  22. /// <summary>
  23. /// Gets or sets the image cache.
  24. /// </summary>
  25. /// <value>The image cache.</value>
  26. public FileSystemRepository ImageCache { get; set; }
  27. /// <summary>
  28. /// The _locks
  29. /// </summary>
  30. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  31. /// <summary>
  32. /// The _media encoder
  33. /// </summary>
  34. private readonly IMediaEncoder _mediaEncoder;
  35. private readonly IIsoManager _isoManager;
  36. public VideoImageProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder, IIsoManager isoManager)
  37. : base(logManager, configurationManager)
  38. {
  39. _mediaEncoder = mediaEncoder;
  40. _isoManager = isoManager;
  41. ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.VideoImagesDataPath);
  42. }
  43. /// <summary>
  44. /// Gets a value indicating whether [refresh on version change].
  45. /// </summary>
  46. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  47. protected override bool RefreshOnVersionChange
  48. {
  49. get
  50. {
  51. return true;
  52. }
  53. }
  54. /// <summary>
  55. /// Gets the provider version.
  56. /// </summary>
  57. /// <value>The provider version.</value>
  58. protected override string ProviderVersion
  59. {
  60. get
  61. {
  62. return "1";
  63. }
  64. }
  65. /// <summary>
  66. /// Supportses the specified item.
  67. /// </summary>
  68. /// <param name="item">The item.</param>
  69. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  70. public override bool Supports(BaseItem item)
  71. {
  72. return item.LocationType == LocationType.FileSystem && item is Video;
  73. }
  74. /// <summary>
  75. /// Needses the refresh internal.
  76. /// </summary>
  77. /// <param name="item">The item.</param>
  78. /// <param name="providerInfo">The provider info.</param>
  79. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  80. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  81. {
  82. var video = (Video)item;
  83. if (!QualifiesForExtraction(video))
  84. {
  85. return false;
  86. }
  87. return base.NeedsRefreshInternal(item, providerInfo);
  88. }
  89. /// <summary>
  90. /// Qualifieses for extraction.
  91. /// </summary>
  92. /// <param name="item">The item.</param>
  93. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  94. private bool QualifiesForExtraction(Video item)
  95. {
  96. if (!ConfigurationManager.Configuration.EnableVideoImageExtraction)
  97. {
  98. return false;
  99. }
  100. if (!string.IsNullOrEmpty(item.PrimaryImagePath))
  101. {
  102. return false;
  103. }
  104. // No support for this
  105. if (item.VideoType == VideoType.HdDvd)
  106. {
  107. return false;
  108. }
  109. // Can't extract from iso's if we weren't unable to determine iso type
  110. if (item.VideoType == VideoType.Iso && !item.IsoType.HasValue)
  111. {
  112. return false;
  113. }
  114. // Can't extract if we didn't find a video stream in the file
  115. if (item.MediaStreams.All(m => m.Type != MediaStreamType.Video))
  116. {
  117. return false;
  118. }
  119. return true;
  120. }
  121. /// <summary>
  122. /// Override this to return the date that should be compared to the last refresh date
  123. /// to determine if this provider should be re-fetched.
  124. /// </summary>
  125. /// <param name="item">The item.</param>
  126. /// <returns>DateTime.</returns>
  127. protected override DateTime CompareDate(BaseItem item)
  128. {
  129. return item.DateModified;
  130. }
  131. /// <summary>
  132. /// Gets the priority.
  133. /// </summary>
  134. /// <value>The priority.</value>
  135. public override MetadataProviderPriority Priority
  136. {
  137. get { return MetadataProviderPriority.Last; }
  138. }
  139. public override ItemUpdateType ItemUpdateType
  140. {
  141. get
  142. {
  143. return ItemUpdateType.ImageUpdate;
  144. }
  145. }
  146. /// <summary>
  147. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  148. /// </summary>
  149. /// <param name="item">The item.</param>
  150. /// <param name="force">if set to <c>true</c> [force].</param>
  151. /// <param name="cancellationToken">The cancellation token.</param>
  152. /// <returns>Task{System.Boolean}.</returns>
  153. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  154. {
  155. item.ValidateImages();
  156. var video = (Video)item;
  157. // Double check this here in case force was used
  158. if (QualifiesForExtraction(video))
  159. {
  160. try
  161. {
  162. await ExtractImage(video, cancellationToken).ConfigureAwait(false);
  163. }
  164. catch (Exception ex)
  165. {
  166. // Swallow this so that we don't keep on trying over and over again
  167. Logger.ErrorException("Error extracting image for {0}", ex, item.Name);
  168. }
  169. }
  170. SetLastRefreshed(item, DateTime.UtcNow);
  171. return true;
  172. }
  173. /// <summary>
  174. /// Extracts the image.
  175. /// </summary>
  176. /// <param name="item">The item.</param>
  177. /// <param name="cancellationToken">The cancellation token.</param>
  178. /// <returns>Task.</returns>
  179. private async Task ExtractImage(Video item, CancellationToken cancellationToken)
  180. {
  181. cancellationToken.ThrowIfCancellationRequested();
  182. var filename = item.Path + "_" + item.DateModified.Ticks + "_primary";
  183. var path = ImageCache.GetResourcePath(filename, ".jpg");
  184. if (!File.Exists(path))
  185. {
  186. var semaphore = GetLock(path);
  187. // Acquire a lock
  188. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  189. // Check again
  190. if (!File.Exists(path))
  191. {
  192. try
  193. {
  194. var parentPath = Path.GetDirectoryName(path);
  195. Directory.CreateDirectory(parentPath);
  196. await ExtractImageInternal(item, path, cancellationToken).ConfigureAwait(false);
  197. }
  198. finally
  199. {
  200. semaphore.Release();
  201. }
  202. }
  203. else
  204. {
  205. semaphore.Release();
  206. }
  207. }
  208. // Image is already in the cache
  209. item.PrimaryImagePath = path;
  210. }
  211. /// <summary>
  212. /// Extracts the image.
  213. /// </summary>
  214. /// <param name="video">The video.</param>
  215. /// <param name="path">The path.</param>
  216. /// <param name="cancellationToken">The cancellation token.</param>
  217. /// <returns>Task.</returns>
  218. private async Task ExtractImageInternal(Video video, string path, CancellationToken cancellationToken)
  219. {
  220. var isoMount = await MountIsoIfNeeded(video, cancellationToken).ConfigureAwait(false);
  221. try
  222. {
  223. // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in.
  224. // Always use 10 seconds for dvd because our duration could be out of whack
  225. var imageOffset = video.VideoType != VideoType.Dvd && video.RunTimeTicks.HasValue &&
  226. video.RunTimeTicks.Value > 0
  227. ? TimeSpan.FromTicks(Convert.ToInt64(video.RunTimeTicks.Value * .1))
  228. : TimeSpan.FromSeconds(10);
  229. InputType type;
  230. var inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  231. await _mediaEncoder.ExtractImage(inputPath, type, video.Video3DFormat, imageOffset, path, cancellationToken).ConfigureAwait(false);
  232. video.PrimaryImagePath = path;
  233. }
  234. finally
  235. {
  236. if (isoMount != null)
  237. {
  238. isoMount.Dispose();
  239. }
  240. }
  241. }
  242. /// <summary>
  243. /// The null mount task result
  244. /// </summary>
  245. protected readonly Task<IIsoMount> NullMountTaskResult = Task.FromResult<IIsoMount>(null);
  246. /// <summary>
  247. /// Mounts the iso if needed.
  248. /// </summary>
  249. /// <param name="item">The item.</param>
  250. /// <param name="cancellationToken">The cancellation token.</param>
  251. /// <returns>Task{IIsoMount}.</returns>
  252. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  253. {
  254. if (item.VideoType == VideoType.Iso)
  255. {
  256. return _isoManager.Mount(item.Path, cancellationToken);
  257. }
  258. return NullMountTaskResult;
  259. }
  260. /// <summary>
  261. /// Gets the lock.
  262. /// </summary>
  263. /// <param name="filename">The filename.</param>
  264. /// <returns>SemaphoreSlim.</returns>
  265. private SemaphoreSlim GetLock(string filename)
  266. {
  267. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  268. }
  269. }
  270. }