EmbeddedImageProvider.cs 8.4 KB

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