AudioImageProvider.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Audio;
  6. using MediaBrowser.Controller.MediaEncoding;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.IO;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Providers.MediaInfo
  18. {
  19. /// <summary>
  20. /// Uses ffmpeg to create video images
  21. /// </summary>
  22. public class AudioImageProvider : IDynamicImageProvider, IHasChangeMonitor
  23. {
  24. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  25. private readonly IIsoManager _isoManager;
  26. private readonly IMediaEncoder _mediaEncoder;
  27. private readonly IServerConfigurationManager _config;
  28. private readonly IFileSystem _fileSystem;
  29. public AudioImageProvider(IIsoManager isoManager, IMediaEncoder mediaEncoder, IServerConfigurationManager config, IFileSystem fileSystem)
  30. {
  31. _isoManager = isoManager;
  32. _mediaEncoder = mediaEncoder;
  33. _config = config;
  34. _fileSystem = fileSystem;
  35. }
  36. /// <summary>
  37. /// The null mount task result
  38. /// </summary>
  39. protected readonly Task<IIsoMount> NullMountTaskResult = Task.FromResult<IIsoMount>(null);
  40. /// <summary>
  41. /// Mounts the iso if needed.
  42. /// </summary>
  43. /// <param name="item">The item.</param>
  44. /// <param name="cancellationToken">The cancellation token.</param>
  45. /// <returns>Task{IIsoMount}.</returns>
  46. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  47. {
  48. if (item.VideoType == VideoType.Iso)
  49. {
  50. return _isoManager.Mount(item.Path, cancellationToken);
  51. }
  52. return NullMountTaskResult;
  53. }
  54. public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  55. {
  56. return new List<ImageType> { ImageType.Primary };
  57. }
  58. public Task<DynamicImageResponse> GetImage(IHasImages item, ImageType type, CancellationToken cancellationToken)
  59. {
  60. var audio = (Audio)item;
  61. // Can't extract if we didn't find a video stream in the file
  62. if (!audio.HasEmbeddedImage)
  63. {
  64. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  65. }
  66. return GetImage((Audio)item, cancellationToken);
  67. }
  68. public async Task<DynamicImageResponse> GetImage(Audio item, CancellationToken cancellationToken)
  69. {
  70. var path = GetAudioImagePath(item);
  71. if (!File.Exists(path))
  72. {
  73. var semaphore = GetLock(path);
  74. // Acquire a lock
  75. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  76. try
  77. {
  78. // Check again in case it was saved while waiting for the lock
  79. if (!File.Exists(path))
  80. {
  81. Directory.CreateDirectory(Path.GetDirectoryName(path));
  82. using (var stream = await _mediaEncoder.ExtractAudioImage(item.Path, cancellationToken).ConfigureAwait(false))
  83. {
  84. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  85. {
  86. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  87. }
  88. }
  89. }
  90. }
  91. finally
  92. {
  93. semaphore.Release();
  94. }
  95. }
  96. return new DynamicImageResponse
  97. {
  98. HasImage = true,
  99. Path = path
  100. };
  101. }
  102. private string GetAudioImagePath(Audio item)
  103. {
  104. var album = item.Parent as MusicAlbum;
  105. var filename = item.Album ?? string.Empty;
  106. filename += item.Artists.FirstOrDefault() ?? string.Empty;
  107. filename += album == null ? item.Id.ToString("N") + "_primary" + item.DateModified.Ticks : album.Id.ToString("N") + album.DateModified.Ticks + "_primary";
  108. filename = filename.GetMD5() + ".jpg";
  109. var prefix = filename.Substring(0, 1);
  110. return Path.Combine(AudioImagesPath, prefix, filename);
  111. }
  112. public string AudioImagesPath
  113. {
  114. get
  115. {
  116. return Path.Combine(_config.ApplicationPaths.CachePath, "extracted-audio-images");
  117. }
  118. }
  119. /// <summary>
  120. /// Gets the lock.
  121. /// </summary>
  122. /// <param name="filename">The filename.</param>
  123. /// <returns>SemaphoreSlim.</returns>
  124. private SemaphoreSlim GetLock(string filename)
  125. {
  126. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  127. }
  128. public string Name
  129. {
  130. get { return "Image Extractor"; }
  131. }
  132. public bool Supports(IHasImages item)
  133. {
  134. return item.LocationType == LocationType.FileSystem && item is Audio;
  135. }
  136. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
  137. {
  138. return item.DateModified > date;
  139. }
  140. }
  141. }