VideoImagesTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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.Persistence;
  9. using MediaBrowser.Controller.Providers.MediaInfo;
  10. using MediaBrowser.Model.Entities;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using MediaBrowser.Model.Logging;
  18. using MoreLinq;
  19. namespace MediaBrowser.Server.Implementations.ScheduledTasks
  20. {
  21. /// <summary>
  22. /// Class VideoImagesTask
  23. /// </summary>
  24. public class VideoImagesTask : IScheduledTask
  25. {
  26. /// <summary>
  27. /// Gets or sets the image cache.
  28. /// </summary>
  29. /// <value>The image cache.</value>
  30. public FileSystemRepository ImageCache { get; set; }
  31. /// <summary>
  32. /// The _library manager
  33. /// </summary>
  34. private readonly ILibraryManager _libraryManager;
  35. /// <summary>
  36. /// The _media encoder
  37. /// </summary>
  38. private readonly IMediaEncoder _mediaEncoder;
  39. /// <summary>
  40. /// The _iso manager
  41. /// </summary>
  42. private readonly IIsoManager _isoManager;
  43. private readonly IItemRepository _itemRepo;
  44. private readonly ILogger _logger;
  45. /// <summary>
  46. /// The _locks
  47. /// </summary>
  48. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  49. private readonly List<BaseItem> _newlyAddedItems = new List<BaseItem>();
  50. private const int NewItemDelay = 60000;
  51. /// <summary>
  52. /// The current new item timer
  53. /// </summary>
  54. /// <value>The new item timer.</value>
  55. private Timer NewItemTimer { get; set; }
  56. /// <summary>
  57. /// Initializes a new instance of the <see cref="AudioImagesTask" /> class.
  58. /// </summary>
  59. /// <param name="libraryManager">The library manager.</param>
  60. /// <param name="logManager">The log manager.</param>
  61. /// <param name="mediaEncoder">The media encoder.</param>
  62. /// <param name="isoManager">The iso manager.</param>
  63. public VideoImagesTask(ILibraryManager libraryManager, ILogManager logManager, IMediaEncoder mediaEncoder, IIsoManager isoManager, IItemRepository itemRepo)
  64. {
  65. _libraryManager = libraryManager;
  66. _mediaEncoder = mediaEncoder;
  67. _isoManager = isoManager;
  68. _itemRepo = itemRepo;
  69. _logger = logManager.GetLogger(GetType().Name);
  70. ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.VideoImagesDataPath);
  71. libraryManager.ItemAdded += libraryManager_ItemAdded;
  72. libraryManager.ItemUpdated += libraryManager_ItemAdded;
  73. }
  74. /// <summary>
  75. /// Handles the ItemAdded event of the libraryManager control.
  76. /// </summary>
  77. /// <param name="sender">The source of the event.</param>
  78. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  79. void libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  80. {
  81. lock (_newlyAddedItems)
  82. {
  83. _newlyAddedItems.Add(e.Item);
  84. if (NewItemTimer == null)
  85. {
  86. NewItemTimer = new Timer(NewItemTimerCallback, null, NewItemDelay, Timeout.Infinite);
  87. }
  88. else
  89. {
  90. NewItemTimer.Change(NewItemDelay, Timeout.Infinite);
  91. }
  92. }
  93. }
  94. /// <summary>
  95. /// News the item timer callback.
  96. /// </summary>
  97. /// <param name="state">The state.</param>
  98. private async void NewItemTimerCallback(object state)
  99. {
  100. List<BaseItem> newItems;
  101. // Lock the list and release all resources
  102. lock (_newlyAddedItems)
  103. {
  104. newItems = _newlyAddedItems.DistinctBy(i => i.Id).ToList();
  105. _newlyAddedItems.Clear();
  106. NewItemTimer.Dispose();
  107. NewItemTimer = null;
  108. }
  109. foreach (var item in GetItemsForExtraction(newItems.Take(3)))
  110. {
  111. try
  112. {
  113. await ExtractImage(item, CancellationToken.None).ConfigureAwait(false);
  114. }
  115. catch (Exception ex)
  116. {
  117. _logger.ErrorException("Error creating image for {0}", ex, item.Name);
  118. }
  119. }
  120. }
  121. /// <summary>
  122. /// Gets the name of the task
  123. /// </summary>
  124. /// <value>The name.</value>
  125. public string Name
  126. {
  127. get { return "Video image extraction"; }
  128. }
  129. /// <summary>
  130. /// Gets the description.
  131. /// </summary>
  132. /// <value>The description.</value>
  133. public string Description
  134. {
  135. get { return "Extracts images from video files that do not have external images."; }
  136. }
  137. /// <summary>
  138. /// Gets the category.
  139. /// </summary>
  140. /// <value>The category.</value>
  141. public string Category
  142. {
  143. get { return "Library"; }
  144. }
  145. /// <summary>
  146. /// Executes the task
  147. /// </summary>
  148. /// <param name="cancellationToken">The cancellation token.</param>
  149. /// <param name="progress">The progress.</param>
  150. /// <returns>Task.</returns>
  151. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  152. {
  153. var items = GetItemsForExtraction(_libraryManager.RootFolder.RecursiveChildren).ToList();
  154. progress.Report(0);
  155. var numComplete = 0;
  156. foreach (var item in items)
  157. {
  158. try
  159. {
  160. await ExtractImage(item, cancellationToken).ConfigureAwait(false);
  161. }
  162. catch
  163. {
  164. // Already logged at lower levels.
  165. // Just don't let the task fail
  166. }
  167. numComplete++;
  168. double percent = numComplete;
  169. percent /= items.Count;
  170. progress.Report(100 * percent);
  171. }
  172. progress.Report(100);
  173. }
  174. /// <summary>
  175. /// Gets the items for extraction.
  176. /// </summary>
  177. /// <param name="sourceItems">The source items.</param>
  178. /// <returns>IEnumerable{BaseItem}.</returns>
  179. private IEnumerable<Video> GetItemsForExtraction(IEnumerable<BaseItem> sourceItems)
  180. {
  181. var allItems = sourceItems.ToList();
  182. var localTrailers = allItems.SelectMany(i => _itemRepo.GetItems(i.LocalTrailerIds).Cast<Video>());
  183. var themeVideos = allItems.SelectMany(i => _itemRepo.GetItems(i.ThemeVideoIds).Cast<Video>());
  184. var videos = allItems.OfType<Video>().ToList();
  185. var items = videos.ToList();
  186. items.AddRange(localTrailers);
  187. items.AddRange(themeVideos);
  188. items.AddRange(videos.OfType<Movie>().SelectMany(i => _itemRepo.GetItems(i.SpecialFeatureIds).Cast<Video>()).ToList());
  189. return items.Where(i =>
  190. {
  191. if (!string.IsNullOrEmpty(i.PrimaryImagePath))
  192. {
  193. return false;
  194. }
  195. if (i.LocationType != LocationType.FileSystem)
  196. {
  197. return false;
  198. }
  199. if (i.VideoType == VideoType.HdDvd)
  200. {
  201. return false;
  202. }
  203. if (i.VideoType == VideoType.Iso && !i.IsoType.HasValue)
  204. {
  205. return false;
  206. }
  207. return i.MediaStreams != null && i.MediaStreams.Any(m => m.Type == MediaStreamType.Video);
  208. });
  209. }
  210. /// <summary>
  211. /// Extracts the image.
  212. /// </summary>
  213. /// <param name="item">The item.</param>
  214. /// <param name="cancellationToken">The cancellation token.</param>
  215. /// <returns>Task.</returns>
  216. private async Task ExtractImage(Video item, CancellationToken cancellationToken)
  217. {
  218. cancellationToken.ThrowIfCancellationRequested();
  219. var filename = item.Id + "_" + item.DateModified.Ticks + "_primary";
  220. var path = ImageCache.GetResourcePath(filename, ".jpg");
  221. if (!ImageCache.ContainsFilePath(path))
  222. {
  223. var semaphore = GetLock(path);
  224. // Acquire a lock
  225. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  226. // Check again
  227. if (!ImageCache.ContainsFilePath(path))
  228. {
  229. try
  230. {
  231. await ExtractImageInternal(item, path, cancellationToken).ConfigureAwait(false);
  232. }
  233. finally
  234. {
  235. semaphore.Release();
  236. }
  237. // Image is already in the cache
  238. item.PrimaryImagePath = path;
  239. await _libraryManager.UpdateItem(item, cancellationToken).ConfigureAwait(false);
  240. }
  241. else
  242. {
  243. semaphore.Release();
  244. }
  245. }
  246. }
  247. /// <summary>
  248. /// Extracts the image.
  249. /// </summary>
  250. /// <param name="video">The video.</param>
  251. /// <param name="path">The path.</param>
  252. /// <param name="cancellationToken">The cancellation token.</param>
  253. /// <returns>Task.</returns>
  254. private async Task ExtractImageInternal(Video video, string path, CancellationToken cancellationToken)
  255. {
  256. var isoMount = await MountIsoIfNeeded(video, cancellationToken).ConfigureAwait(false);
  257. try
  258. {
  259. // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in.
  260. // Always use 10 seconds for dvd because our duration could be out of whack
  261. var imageOffset = video.VideoType != VideoType.Dvd && video.RunTimeTicks.HasValue &&
  262. video.RunTimeTicks.Value > 0
  263. ? TimeSpan.FromTicks(Convert.ToInt64(video.RunTimeTicks.Value * .1))
  264. : TimeSpan.FromSeconds(10);
  265. InputType type;
  266. var inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type);
  267. await _mediaEncoder.ExtractImage(inputPath, type, imageOffset, path, cancellationToken).ConfigureAwait(false);
  268. video.PrimaryImagePath = path;
  269. }
  270. finally
  271. {
  272. if (isoMount != null)
  273. {
  274. isoMount.Dispose();
  275. }
  276. }
  277. }
  278. /// <summary>
  279. /// The null mount task result
  280. /// </summary>
  281. protected readonly Task<IIsoMount> NullMountTaskResult = Task.FromResult<IIsoMount>(null);
  282. /// <summary>
  283. /// Mounts the iso if needed.
  284. /// </summary>
  285. /// <param name="item">The item.</param>
  286. /// <param name="cancellationToken">The cancellation token.</param>
  287. /// <returns>Task{IIsoMount}.</returns>
  288. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  289. {
  290. if (item.VideoType == VideoType.Iso)
  291. {
  292. return _isoManager.Mount(item.Path, cancellationToken);
  293. }
  294. return NullMountTaskResult;
  295. }
  296. /// <summary>
  297. /// Gets the default triggers.
  298. /// </summary>
  299. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  300. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  301. {
  302. return new ITaskTrigger[]
  303. {
  304. new DailyTrigger { TimeOfDay = TimeSpan.FromHours(2) }
  305. };
  306. }
  307. /// <summary>
  308. /// Gets the lock.
  309. /// </summary>
  310. /// <param name="filename">The filename.</param>
  311. /// <returns>System.Object.</returns>
  312. private SemaphoreSlim GetLock(string filename)
  313. {
  314. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  315. }
  316. }
  317. }