VideoImageProvider.cs 11 KB

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