VideoImageProvider.cs 11 KB

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