VideoImageProvider.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.MediaEncoding;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Model.Drawing;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.MediaInfo;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Providers.MediaInfo
  17. {
  18. public class VideoImageProvider : IDynamicImageProvider, IHasItemChangeMonitor, IHasOrder
  19. {
  20. private readonly IIsoManager _isoManager;
  21. private readonly IMediaEncoder _mediaEncoder;
  22. private readonly IServerConfigurationManager _config;
  23. private readonly ILibraryManager _libraryManager;
  24. private readonly ILogger _logger;
  25. private readonly IFileSystem _fileSystem;
  26. public VideoImageProvider(IIsoManager isoManager, IMediaEncoder mediaEncoder, IServerConfigurationManager config, ILibraryManager libraryManager, ILogger logger, IFileSystem fileSystem)
  27. {
  28. _isoManager = isoManager;
  29. _mediaEncoder = mediaEncoder;
  30. _config = config;
  31. _libraryManager = libraryManager;
  32. _logger = logger;
  33. _fileSystem = fileSystem;
  34. }
  35. /// <summary>
  36. /// The null mount task result
  37. /// </summary>
  38. protected readonly Task<IIsoMount> NullMountTaskResult = Task.FromResult<IIsoMount>(null);
  39. /// <summary>
  40. /// Mounts the iso if needed.
  41. /// </summary>
  42. /// <param name="item">The item.</param>
  43. /// <param name="cancellationToken">The cancellation token.</param>
  44. /// <returns>Task{IIsoMount}.</returns>
  45. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  46. {
  47. if (item.VideoType == VideoType.Iso)
  48. {
  49. return _isoManager.Mount(item.Path, cancellationToken);
  50. }
  51. return NullMountTaskResult;
  52. }
  53. public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  54. {
  55. return new List<ImageType> { ImageType.Primary };
  56. }
  57. public Task<DynamicImageResponse> GetImage(IHasImages item, ImageType type, CancellationToken cancellationToken)
  58. {
  59. var video = (Video)item;
  60. // No support for this
  61. if (video.VideoType == VideoType.HdDvd || video.IsPlaceHolder)
  62. {
  63. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  64. }
  65. // Can't extract from iso's if we weren't unable to determine iso type
  66. if (video.VideoType == VideoType.Iso && !video.IsoType.HasValue)
  67. {
  68. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  69. }
  70. // Can't extract if we didn't find a video stream in the file
  71. if (!video.DefaultVideoStreamIndex.HasValue)
  72. {
  73. _logger.Info("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty);
  74. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  75. }
  76. return GetVideoImage(video, cancellationToken);
  77. }
  78. public async Task<DynamicImageResponse> GetVideoImage(Video item, CancellationToken cancellationToken)
  79. {
  80. var isoMount = await MountIsoIfNeeded(item, cancellationToken).ConfigureAwait(false);
  81. try
  82. {
  83. var protocol = item.LocationType == LocationType.Remote
  84. ? MediaProtocol.Http
  85. : MediaProtocol.File;
  86. var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, item.Path, protocol, isoMount, item.PlayableStreamFileNames);
  87. var mediaStreams =
  88. item.GetMediaSources(false)
  89. .Take(1)
  90. .SelectMany(i => i.MediaStreams)
  91. .ToList();
  92. var imageStreams =
  93. mediaStreams
  94. .Where(i => i.Type == MediaStreamType.EmbeddedImage)
  95. .ToList();
  96. var imageStream = imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("front", StringComparison.OrdinalIgnoreCase) != -1) ??
  97. imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("cover", StringComparison.OrdinalIgnoreCase) != -1) ??
  98. imageStreams.FirstOrDefault();
  99. string extractedImagePath;
  100. if (imageStream != null)
  101. {
  102. // Instead of using the raw stream index, we need to use nth video/embedded image stream
  103. var videoIndex = -1;
  104. foreach (var mediaStream in mediaStreams)
  105. {
  106. if (mediaStream.Type == MediaStreamType.Video ||
  107. mediaStream.Type == MediaStreamType.EmbeddedImage)
  108. {
  109. videoIndex++;
  110. }
  111. if (mediaStream == imageStream)
  112. {
  113. break;
  114. }
  115. }
  116. extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, protocol, videoIndex, cancellationToken).ConfigureAwait(false);
  117. }
  118. else
  119. {
  120. // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in.
  121. // Always use 10 seconds for dvd because our duration could be out of whack
  122. var imageOffset = item.VideoType != VideoType.Dvd && item.RunTimeTicks.HasValue &&
  123. item.RunTimeTicks.Value > 0
  124. ? TimeSpan.FromTicks(Convert.ToInt64(item.RunTimeTicks.Value * .1))
  125. : TimeSpan.FromSeconds(10);
  126. extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, protocol, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false);
  127. }
  128. return new DynamicImageResponse
  129. {
  130. Format = ImageFormat.Jpg,
  131. HasImage = true,
  132. Path = extractedImagePath,
  133. Protocol = MediaProtocol.File
  134. };
  135. }
  136. finally
  137. {
  138. if (isoMount != null)
  139. {
  140. isoMount.Dispose();
  141. }
  142. }
  143. }
  144. public string Name
  145. {
  146. get { return "Screen Grabber"; }
  147. }
  148. public bool Supports(IHasImages item)
  149. {
  150. var video = item as Video;
  151. if (item.LocationType == LocationType.FileSystem && video != null && !video.IsPlaceHolder && !video.IsShortcut)
  152. {
  153. return true;
  154. }
  155. return false;
  156. }
  157. public int Order
  158. {
  159. get
  160. {
  161. // Make sure this comes after internet image providers
  162. return 100;
  163. }
  164. }
  165. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService)
  166. {
  167. if (item.EnableRefreshOnDateModifiedChange && !string.IsNullOrWhiteSpace(item.Path) && item.LocationType == LocationType.FileSystem)
  168. {
  169. var file = directoryService.GetFile(item.Path);
  170. if (file != null && file.LastWriteTimeUtc != item.DateModified)
  171. {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. }
  178. }