VideoImagesTask.cs 13 KB

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