AudioImageProvider.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. using System;
  2. using MediaBrowser.Common.Extensions;
  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 System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using CommonIO;
  16. namespace MediaBrowser.Providers.MediaInfo
  17. {
  18. /// <summary>
  19. /// Uses ffmpeg to create video images
  20. /// </summary>
  21. public class AudioImageProvider : IDynamicImageProvider, IHasItemChangeMonitor
  22. {
  23. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  24. private readonly IMediaEncoder _mediaEncoder;
  25. private readonly IServerConfigurationManager _config;
  26. private readonly IFileSystem _fileSystem;
  27. public AudioImageProvider(IMediaEncoder mediaEncoder, IServerConfigurationManager config, IFileSystem fileSystem)
  28. {
  29. _mediaEncoder = mediaEncoder;
  30. _config = config;
  31. _fileSystem = fileSystem;
  32. }
  33. public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  34. {
  35. return new List<ImageType> { ImageType.Primary };
  36. }
  37. public Task<DynamicImageResponse> GetImage(IHasImages item, ImageType type, CancellationToken cancellationToken)
  38. {
  39. var audio = (Audio)item;
  40. var imageStreams =
  41. audio.GetMediaSources(false)
  42. .Take(1)
  43. .SelectMany(i => i.MediaStreams)
  44. .Where(i => i.Type == MediaStreamType.EmbeddedImage)
  45. .ToList();
  46. // Can't extract if we didn't find a video stream in the file
  47. if (imageStreams.Count == 0)
  48. {
  49. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  50. }
  51. return GetImage((Audio)item, imageStreams, cancellationToken);
  52. }
  53. public async Task<DynamicImageResponse> GetImage(Audio item, List<MediaStream> imageStreams, CancellationToken cancellationToken)
  54. {
  55. var path = GetAudioImagePath(item);
  56. if (!_fileSystem.FileExists(path))
  57. {
  58. var semaphore = GetLock(path);
  59. // Acquire a lock
  60. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  61. try
  62. {
  63. // Check again in case it was saved while waiting for the lock
  64. if (!_fileSystem.FileExists(path))
  65. {
  66. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  67. var imageStream = imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("front", StringComparison.OrdinalIgnoreCase) != -1) ??
  68. imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("cover", StringComparison.OrdinalIgnoreCase) != -1) ??
  69. imageStreams.FirstOrDefault();
  70. var imageStreamIndex = imageStream == null ? (int?)null : imageStream.Index;
  71. using (var stream = await _mediaEncoder.ExtractAudioImage(item.Path, imageStreamIndex, cancellationToken).ConfigureAwait(false))
  72. {
  73. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  74. {
  75. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  76. }
  77. }
  78. }
  79. }
  80. finally
  81. {
  82. semaphore.Release();
  83. }
  84. }
  85. return new DynamicImageResponse
  86. {
  87. HasImage = true,
  88. Path = path
  89. };
  90. }
  91. private string GetAudioImagePath(Audio item)
  92. {
  93. var filename = item.Album ?? string.Empty;
  94. filename += string.Join(",", item.Artists.ToArray());
  95. if (!string.IsNullOrWhiteSpace(item.Album))
  96. {
  97. filename += "_" + item.Album;
  98. }
  99. else if (!string.IsNullOrWhiteSpace(item.Name))
  100. {
  101. filename += "_" + item.Name;
  102. }
  103. else
  104. {
  105. filename += "_" + item.Id.ToString("N");
  106. }
  107. filename = filename.GetMD5() + ".jpg";
  108. var prefix = filename.Substring(0, 1);
  109. return Path.Combine(AudioImagesPath, prefix, filename);
  110. }
  111. public string AudioImagesPath
  112. {
  113. get
  114. {
  115. return Path.Combine(_config.ApplicationPaths.CachePath, "extracted-audio-images");
  116. }
  117. }
  118. /// <summary>
  119. /// Gets the lock.
  120. /// </summary>
  121. /// <param name="filename">The filename.</param>
  122. /// <returns>SemaphoreSlim.</returns>
  123. private SemaphoreSlim GetLock(string filename)
  124. {
  125. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  126. }
  127. public string Name
  128. {
  129. get { return "Image Extractor"; }
  130. }
  131. public bool Supports(IHasImages item)
  132. {
  133. var audio = item as Audio;
  134. return item.LocationType == LocationType.FileSystem && audio != null && !audio.IsArchive;
  135. }
  136. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService)
  137. {
  138. if (item.DateModifiedDuringLastRefresh.HasValue)
  139. {
  140. return item.DateModifiedDuringLastRefresh.Value != item.DateModified;
  141. }
  142. return false;
  143. }
  144. }
  145. }