AudioImagesTask.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Entities.Audio;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Model.Entities;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using MediaBrowser.Model.Logging;
  15. using MoreLinq;
  16. namespace MediaBrowser.Server.Implementations.ScheduledTasks
  17. {
  18. /// <summary>
  19. /// Class AudioImagesTask
  20. /// </summary>
  21. public class AudioImagesTask : 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. private readonly ILogger _logger;
  37. /// <summary>
  38. /// The _locks
  39. /// </summary>
  40. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  41. private readonly List<Audio> _newlyAddedItems = new List<Audio>();
  42. private const int NewItemDelay = 60000;
  43. /// <summary>
  44. /// The current new item timer
  45. /// </summary>
  46. /// <value>The new item timer.</value>
  47. private Timer NewItemTimer { get; set; }
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="AudioImagesTask" /> class.
  50. /// </summary>
  51. /// <param name="libraryManager">The library manager.</param>
  52. /// <param name="mediaEncoder">The media encoder.</param>
  53. public AudioImagesTask(ILibraryManager libraryManager, IMediaEncoder mediaEncoder, ILogManager logManager)
  54. {
  55. _libraryManager = libraryManager;
  56. _mediaEncoder = mediaEncoder;
  57. _logger = logManager.GetLogger(GetType().Name);
  58. ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.AudioImagesDataPath);
  59. libraryManager.ItemAdded += libraryManager_ItemAdded;
  60. libraryManager.ItemUpdated += libraryManager_ItemAdded;
  61. }
  62. /// <summary>
  63. /// Handles the ItemAdded event of the libraryManager control.
  64. /// </summary>
  65. /// <param name="sender">The source of the event.</param>
  66. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  67. void libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  68. {
  69. var audio = e.Item as Audio;
  70. if (audio != null)
  71. {
  72. lock (_newlyAddedItems)
  73. {
  74. _newlyAddedItems.Add(audio);
  75. if (NewItemTimer == null)
  76. {
  77. NewItemTimer = new Timer(NewItemTimerCallback, null, NewItemDelay, Timeout.Infinite);
  78. }
  79. else
  80. {
  81. NewItemTimer.Change(NewItemDelay, Timeout.Infinite);
  82. }
  83. }
  84. }
  85. }
  86. /// <summary>
  87. /// News the item timer callback.
  88. /// </summary>
  89. /// <param name="state">The state.</param>
  90. private async void NewItemTimerCallback(object state)
  91. {
  92. List<Audio> newSongs;
  93. // Lock the list and release all resources
  94. lock (_newlyAddedItems)
  95. {
  96. newSongs = _newlyAddedItems.DistinctBy(i => i.Id).ToList();
  97. _newlyAddedItems.Clear();
  98. NewItemTimer.Dispose();
  99. NewItemTimer = null;
  100. }
  101. foreach (var item in newSongs
  102. .Where(i => i.LocationType == LocationType.FileSystem && string.IsNullOrEmpty(i.PrimaryImagePath) && i.MediaStreams.Any(m => m.Type == MediaStreamType.Video))
  103. .Take(10))
  104. {
  105. try
  106. {
  107. await CreateImagesForSong(item, CancellationToken.None).ConfigureAwait(false);
  108. }
  109. catch (Exception ex)
  110. {
  111. _logger.ErrorException("Error creating image for {0}", ex, item.Name);
  112. }
  113. }
  114. }
  115. /// <summary>
  116. /// Gets the name of the task
  117. /// </summary>
  118. /// <value>The name.</value>
  119. public string Name
  120. {
  121. get { return "Audio image extraction"; }
  122. }
  123. /// <summary>
  124. /// Gets the description.
  125. /// </summary>
  126. /// <value>The description.</value>
  127. public string Description
  128. {
  129. get { return "Extracts images from audio files that do not have external images."; }
  130. }
  131. /// <summary>
  132. /// Gets the category.
  133. /// </summary>
  134. /// <value>The category.</value>
  135. public string Category
  136. {
  137. get { return "Library"; }
  138. }
  139. /// <summary>
  140. /// Executes the task
  141. /// </summary>
  142. /// <param name="cancellationToken">The cancellation token.</param>
  143. /// <param name="progress">The progress.</param>
  144. /// <returns>Task.</returns>
  145. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  146. {
  147. var items = _libraryManager.RootFolder.RecursiveChildren
  148. .OfType<Audio>()
  149. .Where(i => i.LocationType == LocationType.FileSystem && string.IsNullOrEmpty(i.PrimaryImagePath) && i.MediaStreams.Any(m => m.Type == MediaStreamType.Video))
  150. .ToList();
  151. progress.Report(0);
  152. var numComplete = 0;
  153. foreach (var item in items)
  154. {
  155. try
  156. {
  157. await CreateImagesForSong(item, cancellationToken).ConfigureAwait(false);
  158. }
  159. catch
  160. {
  161. // Already logged at lower levels.
  162. // Just don't let the task fail
  163. }
  164. numComplete++;
  165. double percent = numComplete;
  166. percent /= items.Count;
  167. progress.Report(100 * percent);
  168. }
  169. progress.Report(100);
  170. }
  171. /// <summary>
  172. /// Creates the images for song.
  173. /// </summary>
  174. /// <param name="item">The item.</param>
  175. /// <param name="cancellationToken">The cancellation token.</param>
  176. /// <returns>Task.</returns>
  177. private async Task CreateImagesForSong(Audio item, CancellationToken cancellationToken)
  178. {
  179. cancellationToken.ThrowIfCancellationRequested();
  180. if (item.MediaStreams.All(i => i.Type != MediaStreamType.Video))
  181. {
  182. throw new InvalidOperationException("Can't extract an image unless the audio file has an embedded image.");
  183. }
  184. var album = item.Parent as MusicAlbum;
  185. var filename = item.Album ?? string.Empty;
  186. filename += album == null ? item.Id.ToString("N") + item.DateModified.Ticks : album.Id.ToString("N") + album.DateModified.Ticks;
  187. var path = ImageCache.GetResourcePath(filename + "_primary", ".jpg");
  188. if (!ImageCache.ContainsFilePath(path))
  189. {
  190. var semaphore = GetLock(path);
  191. // Acquire a lock
  192. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  193. // Check again
  194. if (!ImageCache.ContainsFilePath(path))
  195. {
  196. try
  197. {
  198. await _mediaEncoder.ExtractImage(new[] { item.Path }, InputType.AudioFile, null, path, cancellationToken).ConfigureAwait(false);
  199. }
  200. finally
  201. {
  202. semaphore.Release();
  203. }
  204. // Image is already in the cache
  205. item.PrimaryImagePath = path;
  206. await _libraryManager.UpdateItem(item, cancellationToken).ConfigureAwait(false);
  207. }
  208. else
  209. {
  210. semaphore.Release();
  211. }
  212. }
  213. }
  214. /// <summary>
  215. /// Gets the default triggers.
  216. /// </summary>
  217. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  218. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  219. {
  220. return new ITaskTrigger[]
  221. {
  222. new DailyTrigger { TimeOfDay = TimeSpan.FromHours(1) }
  223. };
  224. }
  225. /// <summary>
  226. /// Gets the lock.
  227. /// </summary>
  228. /// <param name="filename">The filename.</param>
  229. /// <returns>System.Object.</returns>
  230. private SemaphoreSlim GetLock(string filename)
  231. {
  232. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  233. }
  234. }
  235. }