AudioImageProvider.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Audio;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Controller.Providers.MediaInfo
  15. {
  16. /// <summary>
  17. /// Uses ffmpeg to create video images
  18. /// </summary>
  19. public class AudioImageProvider : BaseMetadataProvider
  20. {
  21. /// <summary>
  22. /// Gets or sets the image cache.
  23. /// </summary>
  24. /// <value>The image cache.</value>
  25. public FileSystemRepository ImageCache { get; set; }
  26. /// <summary>
  27. /// The _locks
  28. /// </summary>
  29. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  30. /// <summary>
  31. /// The _media encoder
  32. /// </summary>
  33. private readonly IMediaEncoder _mediaEncoder;
  34. /// <summary>
  35. /// The _library manager
  36. /// </summary>
  37. private readonly ILibraryManager _libraryManager;
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="BaseMetadataProvider" /> class.
  40. /// </summary>
  41. /// <param name="logManager">The log manager.</param>
  42. /// <param name="configurationManager">The configuration manager.</param>
  43. /// <param name="libraryManager">The library manager.</param>
  44. /// <param name="mediaEncoder">The media encoder.</param>
  45. public AudioImageProvider(ILogManager logManager, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IMediaEncoder mediaEncoder)
  46. : base(logManager, configurationManager)
  47. {
  48. _libraryManager = libraryManager;
  49. _mediaEncoder = mediaEncoder;
  50. ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.AudioImagesDataPath);
  51. }
  52. /// <summary>
  53. /// Supportses the specified item.
  54. /// </summary>
  55. /// <param name="item">The item.</param>
  56. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  57. public override bool Supports(BaseItem item)
  58. {
  59. return item.LocationType == LocationType.FileSystem && item is Audio;
  60. }
  61. /// <summary>
  62. /// Override this to return the date that should be compared to the last refresh date
  63. /// to determine if this provider should be re-fetched.
  64. /// </summary>
  65. /// <param name="item">The item.</param>
  66. /// <returns>DateTime.</returns>
  67. protected override DateTime CompareDate(BaseItem item)
  68. {
  69. return item.DateModified;
  70. }
  71. /// <summary>
  72. /// Gets the priority.
  73. /// </summary>
  74. /// <value>The priority.</value>
  75. public override MetadataProviderPriority Priority
  76. {
  77. get { return MetadataProviderPriority.Last; }
  78. }
  79. /// <summary>
  80. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  81. /// </summary>
  82. /// <param name="item">The item.</param>
  83. /// <param name="force">if set to <c>true</c> [force].</param>
  84. /// <param name="cancellationToken">The cancellation token.</param>
  85. /// <returns>Task{System.Boolean}.</returns>
  86. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  87. {
  88. var audio = (Audio)item;
  89. if (string.IsNullOrEmpty(audio.PrimaryImagePath) && audio.MediaStreams.Any(s => s.Type == MediaStreamType.Video))
  90. {
  91. try
  92. {
  93. await CreateImagesForSong(audio, cancellationToken).ConfigureAwait(false);
  94. }
  95. catch (Exception ex)
  96. {
  97. Logger.ErrorException("Error extracting image for {0}", ex, item.Name);
  98. }
  99. }
  100. SetLastRefreshed(item, DateTime.UtcNow);
  101. return true;
  102. }
  103. /// <summary>
  104. /// Creates the images for song.
  105. /// </summary>
  106. /// <param name="item">The item.</param>
  107. /// <param name="cancellationToken">The cancellation token.</param>
  108. /// <returns>Task.</returns>
  109. /// <exception cref="System.InvalidOperationException">Can't extract an image unless the audio file has an embedded image.</exception>
  110. private async Task CreateImagesForSong(Audio item, CancellationToken cancellationToken)
  111. {
  112. cancellationToken.ThrowIfCancellationRequested();
  113. var album = item.Parent as MusicAlbum;
  114. var filename = item.Album ?? string.Empty;
  115. filename += item.Artist ?? string.Empty;
  116. filename += album == null ? item.Id.ToString("N") + item.DateModified.Ticks : album.Id.ToString("N") + album.DateModified.Ticks;
  117. var path = ImageCache.GetResourcePath(filename + "_primary", ".jpg");
  118. if (!ImageCache.ContainsFilePath(path))
  119. {
  120. var semaphore = GetLock(path);
  121. // Acquire a lock
  122. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  123. // Check again
  124. if (!ImageCache.ContainsFilePath(path))
  125. {
  126. try
  127. {
  128. await _mediaEncoder.ExtractImage(new[] { item.Path }, InputType.AudioFile, null, path, cancellationToken).ConfigureAwait(false);
  129. }
  130. finally
  131. {
  132. semaphore.Release();
  133. }
  134. // Image is already in the cache
  135. item.PrimaryImagePath = path;
  136. await _libraryManager.UpdateItem(item, cancellationToken).ConfigureAwait(false);
  137. }
  138. else
  139. {
  140. semaphore.Release();
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// Gets the lock.
  146. /// </summary>
  147. /// <param name="filename">The filename.</param>
  148. /// <returns>SemaphoreSlim.</returns>
  149. private SemaphoreSlim GetLock(string filename)
  150. {
  151. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  152. }
  153. }
  154. }