AudioImageProvider.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.MediaInfo;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Providers.MediaInfo
  17. {
  18. /// <summary>
  19. /// Uses ffmpeg to create video images
  20. /// </summary>
  21. public class AudioImageProvider : BaseMetadataProvider
  22. {
  23. /// <summary>
  24. /// The _locks
  25. /// </summary>
  26. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  27. /// <summary>
  28. /// The _media encoder
  29. /// </summary>
  30. private readonly IMediaEncoder _mediaEncoder;
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="BaseMetadataProvider" /> class.
  33. /// </summary>
  34. /// <param name="logManager">The log manager.</param>
  35. /// <param name="configurationManager">The configuration manager.</param>
  36. /// <param name="mediaEncoder">The media encoder.</param>
  37. public AudioImageProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder)
  38. : base(logManager, configurationManager)
  39. {
  40. _mediaEncoder = mediaEncoder;
  41. }
  42. /// <summary>
  43. /// Gets a value indicating whether [refresh on version change].
  44. /// </summary>
  45. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  46. protected override bool RefreshOnVersionChange
  47. {
  48. get
  49. {
  50. return true;
  51. }
  52. }
  53. /// <summary>
  54. /// Gets the provider version.
  55. /// </summary>
  56. /// <value>The provider version.</value>
  57. protected override string ProviderVersion
  58. {
  59. get
  60. {
  61. return "1";
  62. }
  63. }
  64. /// <summary>
  65. /// Supportses the specified item.
  66. /// </summary>
  67. /// <param name="item">The item.</param>
  68. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  69. public override bool Supports(BaseItem item)
  70. {
  71. return item.LocationType == LocationType.FileSystem && item is Audio;
  72. }
  73. /// <summary>
  74. /// Override this to return the date that should be compared to the last refresh date
  75. /// to determine if this provider should be re-fetched.
  76. /// </summary>
  77. /// <param name="item">The item.</param>
  78. /// <returns>DateTime.</returns>
  79. protected override DateTime CompareDate(BaseItem item)
  80. {
  81. return item.DateModified;
  82. }
  83. /// <summary>
  84. /// Gets the priority.
  85. /// </summary>
  86. /// <value>The priority.</value>
  87. public override MetadataProviderPriority Priority
  88. {
  89. get { return MetadataProviderPriority.Last; }
  90. }
  91. public override ItemUpdateType ItemUpdateType
  92. {
  93. get
  94. {
  95. return ItemUpdateType.ImageUpdate;
  96. }
  97. }
  98. /// <summary>
  99. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  100. /// </summary>
  101. /// <param name="item">The item.</param>
  102. /// <param name="force">if set to <c>true</c> [force].</param>
  103. /// <param name="cancellationToken">The cancellation token.</param>
  104. /// <returns>Task{System.Boolean}.</returns>
  105. public override async Task<bool> FetchAsync(BaseItem item, bool force, BaseProviderInfo providerInfo, CancellationToken cancellationToken)
  106. {
  107. item.ValidateImages();
  108. var audio = (Audio)item;
  109. if (string.IsNullOrEmpty(audio.PrimaryImagePath) && audio.HasEmbeddedImage)
  110. {
  111. try
  112. {
  113. await CreateImagesForSong(audio, cancellationToken).ConfigureAwait(false);
  114. }
  115. catch (Exception ex)
  116. {
  117. Logger.ErrorException("Error extracting image for {0}", ex, item.Name);
  118. }
  119. }
  120. SetLastRefreshed(item, DateTime.UtcNow, providerInfo);
  121. return true;
  122. }
  123. /// <summary>
  124. /// Creates the images for song.
  125. /// </summary>
  126. /// <param name="item">The item.</param>
  127. /// <param name="cancellationToken">The cancellation token.</param>
  128. /// <returns>Task.</returns>
  129. /// <exception cref="System.InvalidOperationException">Can't extract an image unless the audio file has an embedded image.</exception>
  130. private async Task CreateImagesForSong(Audio item, CancellationToken cancellationToken)
  131. {
  132. cancellationToken.ThrowIfCancellationRequested();
  133. var path = GetAudioImagePath(item);
  134. if (!File.Exists(path))
  135. {
  136. var semaphore = GetLock(path);
  137. // Acquire a lock
  138. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  139. // Check again
  140. if (!File.Exists(path))
  141. {
  142. try
  143. {
  144. var parentPath = Path.GetDirectoryName(path);
  145. Directory.CreateDirectory(parentPath);
  146. await _mediaEncoder.ExtractImage(new[] { item.Path }, InputType.File, true, null, null, path, cancellationToken).ConfigureAwait(false);
  147. }
  148. finally
  149. {
  150. semaphore.Release();
  151. }
  152. }
  153. else
  154. {
  155. semaphore.Release();
  156. }
  157. }
  158. // Image is already in the cache
  159. item.PrimaryImagePath = path;
  160. }
  161. /// <summary>
  162. /// Gets the audio image path.
  163. /// </summary>
  164. /// <param name="item">The item.</param>
  165. /// <returns>System.String.</returns>
  166. private string GetAudioImagePath(Audio item)
  167. {
  168. var album = item.Parent as MusicAlbum;
  169. var filename = item.Album ?? string.Empty;
  170. filename += item.Artists.FirstOrDefault() ?? string.Empty;
  171. filename += album == null ? item.Id.ToString("N") + "_primary" + item.DateModified.Ticks : album.Id.ToString("N") + album.DateModified.Ticks + "_primary";
  172. filename = filename.GetMD5() + ".jpg";
  173. var prefix = filename.Substring(0, 1);
  174. return Path.Combine(AudioImagesPath, prefix, filename);
  175. }
  176. /// <summary>
  177. /// Gets the audio images data path.
  178. /// </summary>
  179. /// <value>The audio images data path.</value>
  180. public string AudioImagesPath
  181. {
  182. get
  183. {
  184. return Path.Combine(ConfigurationManager.ApplicationPaths.DataPath, "extracted-audio-images");
  185. }
  186. }
  187. /// <summary>
  188. /// Gets the lock.
  189. /// </summary>
  190. /// <param name="filename">The filename.</param>
  191. /// <returns>SemaphoreSlim.</returns>
  192. private SemaphoreSlim GetLock(string filename)
  193. {
  194. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  195. }
  196. }
  197. }