2
0

VideoImagesTask.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Entities.Movies;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Providers.MediaInfo;
  9. using MediaBrowser.Model.Entities;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Server.Implementations.ScheduledTasks
  17. {
  18. /// <summary>
  19. /// Class VideoImagesTask
  20. /// </summary>
  21. public class VideoImagesTask : IScheduledTask
  22. {
  23. /// <summary>
  24. /// Gets or sets the image cache.
  25. /// </summary>
  26. /// <value>The image cache.</value>
  27. public FileSystemRepository ImageCache { get; set; }
  28. /// <summary>
  29. /// The _library manager
  30. /// </summary>
  31. private readonly ILibraryManager _libraryManager;
  32. /// <summary>
  33. /// The _media encoder
  34. /// </summary>
  35. private readonly IMediaEncoder _mediaEncoder;
  36. /// <summary>
  37. /// The _iso manager
  38. /// </summary>
  39. private readonly IIsoManager _isoManager;
  40. /// <summary>
  41. /// The _locks
  42. /// </summary>
  43. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="AudioImagesTask" /> class.
  46. /// </summary>
  47. /// <param name="libraryManager">The library manager.</param>
  48. /// <param name="mediaEncoder">The media encoder.</param>
  49. /// <param name="isoManager">The iso manager.</param>
  50. public VideoImagesTask(ILibraryManager libraryManager, IMediaEncoder mediaEncoder, IIsoManager isoManager)
  51. {
  52. _libraryManager = libraryManager;
  53. _mediaEncoder = mediaEncoder;
  54. _isoManager = isoManager;
  55. ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.VideoImagesDataPath);
  56. }
  57. /// <summary>
  58. /// Gets the name of the task
  59. /// </summary>
  60. /// <value>The name.</value>
  61. public string Name
  62. {
  63. get { return "Video image extraction"; }
  64. }
  65. /// <summary>
  66. /// Gets the description.
  67. /// </summary>
  68. /// <value>The description.</value>
  69. public string Description
  70. {
  71. get { return "Extracts images from video files that do not have external images."; }
  72. }
  73. /// <summary>
  74. /// Gets the category.
  75. /// </summary>
  76. /// <value>The category.</value>
  77. public string Category
  78. {
  79. get { return "Library"; }
  80. }
  81. /// <summary>
  82. /// Executes the task
  83. /// </summary>
  84. /// <param name="cancellationToken">The cancellation token.</param>
  85. /// <param name="progress">The progress.</param>
  86. /// <returns>Task.</returns>
  87. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  88. {
  89. var allItems = _libraryManager.RootFolder.RecursiveChildren.ToList();
  90. var localTrailers = allItems.SelectMany(i => i.LocalTrailers);
  91. var videos = allItems.OfType<Video>().ToList();
  92. var items = videos;
  93. items.AddRange(localTrailers);
  94. items.AddRange(videos.OfType<Movie>().SelectMany(i => i.SpecialFeatures).ToList());
  95. items = items.Where(i =>
  96. {
  97. if (!string.IsNullOrEmpty(i.PrimaryImagePath))
  98. {
  99. return false;
  100. }
  101. if (i.LocationType != LocationType.FileSystem)
  102. {
  103. return false;
  104. }
  105. if (i.VideoType == VideoType.HdDvd)
  106. {
  107. return false;
  108. }
  109. if (i.VideoType == VideoType.Iso && !i.IsoType.HasValue)
  110. {
  111. return false;
  112. }
  113. return i.MediaStreams != null && i.MediaStreams.Any(m => m.Type == MediaStreamType.Video);
  114. }).ToList();
  115. progress.Report(0);
  116. var numComplete = 0;
  117. foreach (var item in items)
  118. {
  119. cancellationToken.ThrowIfCancellationRequested();
  120. var filename = item.Id + "_" + item.DateModified.Ticks + "_primary";
  121. var path = ImageCache.GetResourcePath(filename, ".jpg");
  122. var success = true;
  123. if (!ImageCache.ContainsFilePath(path))
  124. {
  125. var semaphore = GetLock(path);
  126. // Acquire a lock
  127. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  128. // Check again
  129. if (!ImageCache.ContainsFilePath(path))
  130. {
  131. try
  132. {
  133. await ExtractImage(item, path, cancellationToken).ConfigureAwait(false);
  134. }
  135. catch
  136. {
  137. success = false;
  138. }
  139. finally
  140. {
  141. semaphore.Release();
  142. }
  143. }
  144. else
  145. {
  146. semaphore.Release();
  147. }
  148. }
  149. numComplete++;
  150. double percent = numComplete;
  151. percent /= items.Count;
  152. progress.Report(100 * percent);
  153. if (success)
  154. {
  155. // Image is already in the cache
  156. item.PrimaryImagePath = path;
  157. await _libraryManager.SaveItem(item, cancellationToken).ConfigureAwait(false);
  158. }
  159. }
  160. progress.Report(100);
  161. }
  162. /// <summary>
  163. /// Extracts the image.
  164. /// </summary>
  165. /// <param name="video">The video.</param>
  166. /// <param name="path">The path.</param>
  167. /// <param name="cancellationToken">The cancellation token.</param>
  168. /// <returns>Task.</returns>
  169. private async Task ExtractImage(Video video, string path, CancellationToken cancellationToken)
  170. {
  171. var isoMount = await MountIsoIfNeeded(video, cancellationToken).ConfigureAwait(false);
  172. try
  173. {
  174. // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in.
  175. // Always use 10 seconds for dvd because our duration could be out of whack
  176. var imageOffset = video.VideoType != VideoType.Dvd && video.RunTimeTicks.HasValue &&
  177. video.RunTimeTicks.Value > 0
  178. ? TimeSpan.FromTicks(Convert.ToInt64(video.RunTimeTicks.Value * .1))
  179. : TimeSpan.FromSeconds(10);
  180. InputType type;
  181. var inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  182. await _mediaEncoder.ExtractImage(inputPath, type, imageOffset, path, cancellationToken).ConfigureAwait(false);
  183. video.PrimaryImagePath = path;
  184. }
  185. finally
  186. {
  187. if (isoMount != null)
  188. {
  189. isoMount.Dispose();
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// The null mount task result
  195. /// </summary>
  196. protected readonly Task<IIsoMount> NullMountTaskResult = Task.FromResult<IIsoMount>(null);
  197. /// <summary>
  198. /// Mounts the iso if needed.
  199. /// </summary>
  200. /// <param name="item">The item.</param>
  201. /// <param name="cancellationToken">The cancellation token.</param>
  202. /// <returns>Task{IIsoMount}.</returns>
  203. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  204. {
  205. if (item.VideoType == VideoType.Iso)
  206. {
  207. return _isoManager.Mount(item.Path, cancellationToken);
  208. }
  209. return NullMountTaskResult;
  210. }
  211. /// <summary>
  212. /// Gets the default triggers.
  213. /// </summary>
  214. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  215. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  216. {
  217. return new ITaskTrigger[]
  218. {
  219. new DailyTrigger { TimeOfDay = TimeSpan.FromHours(2) }
  220. };
  221. }
  222. /// <summary>
  223. /// Gets the lock.
  224. /// </summary>
  225. /// <param name="filename">The filename.</param>
  226. /// <returns>System.Object.</returns>
  227. private SemaphoreSlim GetLock(string filename)
  228. {
  229. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  230. }
  231. }
  232. }