EmbeddedImageProvider.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. #nullable disable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Entities.TV;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Persistence;
  13. using MediaBrowser.Controller.Providers;
  14. using MediaBrowser.Model.Drawing;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.MediaInfo;
  18. using MediaBrowser.Model.Net;
  19. using Microsoft.Extensions.Logging;
  20. namespace MediaBrowser.Providers.MediaInfo
  21. {
  22. /// <summary>
  23. /// Uses <see cref="IMediaEncoder"/> to extract embedded images.
  24. /// </summary>
  25. public class EmbeddedImageProvider : IDynamicImageProvider, IHasOrder
  26. {
  27. private static readonly string[] _primaryImageFileNames =
  28. {
  29. "poster",
  30. "folder",
  31. "cover",
  32. "default",
  33. "movie",
  34. "show"
  35. };
  36. private static readonly string[] _backdropImageFileNames =
  37. {
  38. "backdrop",
  39. "background",
  40. "art"
  41. };
  42. private static readonly string[] _logoImageFileNames =
  43. {
  44. "logo",
  45. };
  46. private readonly IMediaSourceManager _mediaSourceManager;
  47. private readonly IMediaEncoder _mediaEncoder;
  48. private readonly ILogger<EmbeddedImageProvider> _logger;
  49. /// <summary>
  50. /// Initializes a new instance of the <see cref="EmbeddedImageProvider"/> class.
  51. /// </summary>
  52. /// <param name="mediaSourceManager">The media source manager for fetching item streams and attachments.</param>
  53. /// <param name="mediaEncoder">The media encoder for extracting attached/embedded images.</param>
  54. /// <param name="logger">The logger.</param>
  55. public EmbeddedImageProvider(IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, ILogger<EmbeddedImageProvider> logger)
  56. {
  57. _mediaSourceManager = mediaSourceManager;
  58. _mediaEncoder = mediaEncoder;
  59. _logger = logger;
  60. }
  61. /// <inheritdoc />
  62. public string Name => "Embedded Image Extractor";
  63. /// <inheritdoc />
  64. // Default to after internet image providers but before Screen Grabber
  65. public int Order => 99;
  66. /// <inheritdoc />
  67. public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
  68. {
  69. if (item is Video)
  70. {
  71. if (item is Episode)
  72. {
  73. return new[]
  74. {
  75. ImageType.Primary,
  76. };
  77. }
  78. return new[]
  79. {
  80. ImageType.Primary,
  81. ImageType.Backdrop,
  82. ImageType.Logo,
  83. };
  84. }
  85. return Array.Empty<ImageType>();
  86. }
  87. /// <inheritdoc />
  88. public Task<DynamicImageResponse> GetImage(BaseItem item, ImageType type, CancellationToken cancellationToken)
  89. {
  90. var video = (Video)item;
  91. // No support for these
  92. if (video.IsPlaceHolder || video.VideoType == VideoType.Dvd)
  93. {
  94. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  95. }
  96. return GetEmbeddedImage(video, type, cancellationToken);
  97. }
  98. private async Task<DynamicImageResponse> GetEmbeddedImage(Video item, ImageType type, CancellationToken cancellationToken)
  99. {
  100. MediaSourceInfo mediaSource = new MediaSourceInfo
  101. {
  102. VideoType = item.VideoType,
  103. IsoType = item.IsoType,
  104. Protocol = item.PathProtocol ?? MediaProtocol.File,
  105. };
  106. string[] imageFileNames = type switch
  107. {
  108. ImageType.Primary => _primaryImageFileNames,
  109. ImageType.Backdrop => _backdropImageFileNames,
  110. ImageType.Logo => _logoImageFileNames,
  111. _ => Array.Empty<string>()
  112. };
  113. if (imageFileNames.Length == 0)
  114. {
  115. _logger.LogWarning("Attempted to load unexpected image type: {Type}", type);
  116. return new DynamicImageResponse { HasImage = false };
  117. }
  118. // Try attachments first
  119. var attachmentStream = _mediaSourceManager.GetMediaAttachments(item.Id)
  120. .FirstOrDefault(attachment => !string.IsNullOrEmpty(attachment.FileName)
  121. && imageFileNames.Any(name => attachment.FileName.Contains(name, StringComparison.OrdinalIgnoreCase)));
  122. if (attachmentStream is not null)
  123. {
  124. return await ExtractAttachment(item, attachmentStream, mediaSource, cancellationToken).ConfigureAwait(false);
  125. }
  126. // Fall back to EmbeddedImage streams
  127. var imageStreams = _mediaSourceManager.GetMediaStreams(new MediaStreamQuery
  128. {
  129. ItemId = item.Id,
  130. Type = MediaStreamType.EmbeddedImage
  131. });
  132. if (imageStreams.Count == 0)
  133. {
  134. // Can't extract if we don't have any EmbeddedImage streams
  135. return new DynamicImageResponse { HasImage = false };
  136. }
  137. // Extract first stream containing an element of imageFileNames
  138. var imageStream = imageStreams
  139. .FirstOrDefault(stream => !string.IsNullOrEmpty(stream.Comment)
  140. && imageFileNames.Any(name => stream.Comment.Contains(name, StringComparison.OrdinalIgnoreCase)));
  141. // Primary type only: default to first image if none found by label
  142. if (imageStream is null)
  143. {
  144. if (type == ImageType.Primary)
  145. {
  146. imageStream = imageStreams[0];
  147. }
  148. else
  149. {
  150. // No streams matched, abort
  151. return new DynamicImageResponse { HasImage = false };
  152. }
  153. }
  154. var format = imageStream.Codec switch
  155. {
  156. "bmp" => ImageFormat.Bmp,
  157. "gif" => ImageFormat.Gif,
  158. "mjpeg" => ImageFormat.Jpg,
  159. "png" => ImageFormat.Png,
  160. "webp" => ImageFormat.Webp,
  161. _ => ImageFormat.Jpg
  162. };
  163. string extractedImagePath =
  164. await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, imageStream, imageStream.Index, format, cancellationToken)
  165. .ConfigureAwait(false);
  166. return new DynamicImageResponse
  167. {
  168. Format = format,
  169. HasImage = true,
  170. Path = extractedImagePath,
  171. Protocol = MediaProtocol.File
  172. };
  173. }
  174. private async Task<DynamicImageResponse> ExtractAttachment(Video item, MediaAttachment attachmentStream, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  175. {
  176. var extension = string.IsNullOrEmpty(attachmentStream.MimeType)
  177. ? Path.GetExtension(attachmentStream.FileName)
  178. : MimeTypes.ToExtension(attachmentStream.MimeType);
  179. ImageFormat format = extension switch
  180. {
  181. ".bmp" => ImageFormat.Bmp,
  182. ".gif" => ImageFormat.Gif,
  183. ".png" => ImageFormat.Png,
  184. ".webp" => ImageFormat.Webp,
  185. _ => ImageFormat.Jpg
  186. };
  187. string extractedAttachmentPath =
  188. await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, null, attachmentStream.Index, format, cancellationToken)
  189. .ConfigureAwait(false);
  190. return new DynamicImageResponse
  191. {
  192. Format = format,
  193. HasImage = true,
  194. Path = extractedAttachmentPath,
  195. Protocol = MediaProtocol.File
  196. };
  197. }
  198. /// <inheritdoc />
  199. public bool Supports(BaseItem item)
  200. {
  201. if (item.IsShortcut)
  202. {
  203. return false;
  204. }
  205. if (!item.IsFileProtocol)
  206. {
  207. return false;
  208. }
  209. return item is Video video && !video.IsPlaceHolder && video.IsCompleteMedia;
  210. }
  211. }
  212. }